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.

58.0 KB
Raw Blame
package opensuite.dashboard;

import opensuite.core.HttpService;
import opensuite.core.LogEntry;
import opensuite.core.SuiteContext;
import opensuite.engine.LoginFlow;
import opensuite.engine.LoginStore;
import opensuite.engine.ScanAuth;
import opensuite.ui.Glyphs;
import opensuite.ui.LibraryDialog;
import opensuite.ui.Theme;
import opensuite.ui.Ui;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Supplier;

/**
 * The scan wizard's Application login step: how the scan stays logged in.
 *
 * <p>Three choices. The scan can ride on the session the user's browser has:
 * the cookies and tokens seen in the proxy history are listed, ticked, and
 * sent on the scanner's requests only. It can log in by itself with a
 * username and a password. Or it can send nothing. Under every choice sit
 * the session checks (requests that only work when logged in), the option
 * to leave log out links alone, and headers typed in by hand.
 */
public final class ApplicationLoginPanel extends JPanel {

    private final SuiteContext ctx;
    private final Supplier<List<String>> targets;

    private final JRadioButton useBrowser = Ui.radio("Use the browser's session (log in to the application in the browser first)", false);
    private final JRadioButton useCredentials = Ui.radio("Log in with a username and password", false);
    private final JRadioButton useNone = Ui.radio("Do not log in", true);
    private boolean chosenByHand;

    /** One header of the browser's session, with whether the scan is to send it. */
    private static final class Row {
        boolean use = true;
        ScanAuth.Header header;
        /** The cookie's name when the row is one cookie of the site's Cookie header; null for a header of its own. */
        String cookie;
        /** What Find needed made of it, or empty. */
        String needed = "";
        Row(ScanAuth.Header h) { header = h; }
        Row(ScanAuth.Header h, String cookie) { header = h; this.cookie = cookie; }
        String key() { return header.key() + (cookie == null ? "" : "\n" + cookie); }
    }
    private final List<Row> rows = new ArrayList<>();
    private final AbstractTableModel headerModel = new AbstractTableModel() {
        private final String[] cols = {"Send", "Site", "Header", "Value", "Required"};
        @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 Class<?> getColumnClass(int c) { return c == 0 ? Boolean.class : String.class; }
        @Override public boolean isCellEditable(int r, int c) { return c == 0; }
        @Override public void setValueAt(Object v, int r, int c) { if (c == 0) { rows.get(r).use = Boolean.TRUE.equals(v); checkChanged(); } }
        @Override public Object getValueAt(int r, int c) {
            Row row = rows.get(r);
            return switch (c) {
                case 0 -> row.use;
                case 1 -> row.header.site();
                case 2 -> row.cookie == null ? row.header.name() : "Cookie: " + row.cookie;
                case 3 -> row.header.value();
                default -> row.needed;
            };
        }
    };
    private final JTable headerTable = new JTable(headerModel);
    private final JLabel headerNote = Ui.label("");
    private final JCheckBox follow = Ui.check("Use updated session tokens from the browser during the scan", true);

    private final List<LoginStore.Credentials> credentials = new ArrayList<>();
    private final AbstractTableModel credModel = new AbstractTableModel() {
        @Override public int getRowCount() { return credentials.size(); }
        @Override public int getColumnCount() { return 2; }
        @Override public String getColumnName(int c) { return c == 0 ? "Label" : "Username"; }
        @Override public Object getValueAt(int r, int c) { return c == 0 ? credentials.get(r).label : credentials.get(r).username; }
    };
    private final JTable credTable = new JTable(credModel);
    private final JLabel loginResult = Ui.label("Press Test login, then add a session check: a login is confirmed by the text you mark.");
    private final JTextField loginPage = Ui.field("", 34);

    private final List<ScanAuth.Header> extra = new ArrayList<>();
    private final AbstractTableModel extraModel = new AbstractTableModel() {
        @Override public int getRowCount() { return extra.size(); }
        @Override public int getColumnCount() { return 2; }
        @Override public String getColumnName(int c) { return c == 0 ? "Header" : "Value"; }
        @Override public Object getValueAt(int r, int c) { return c == 0 ? extra.get(r).name() : extra.get(r).value(); }
    };
    private final JTable extraTable = new JTable(extraModel);

    /** The session checks: each a real request, the text marked in its response, and what proving it on this application showed. */
    private final List<ScanAuth.Check> checks = new ArrayList<>();
    private final AbstractTableModel checkModel = new AbstractTableModel() {
        private final String[] cols = {"Request", "Logged-in text", "Result", "Monitors"};
        @Override public int getRowCount() { return checks.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) {
            ScanAuth.Check k = checks.get(r);
            return switch (c) {
                case 0 -> k.request.method() + " " + k.service.url() + k.request.requestTarget();
                case 1 -> k.text.replace("\n", " ");
                case 2 -> k.measured.isEmpty() ? "Not verified yet: press Verify" : k.measured;
                default -> watches(k);
            };
        }
    };
    private final JTable checkTable = new JTable(checkModel);
    private final JLabel checkNote = Ui.label(" ");
    private final JCheckBox skipLogout = Ui.check("Skip logout links", true);
    private final JCheckBox skipLoops = Ui.check("Skip crawl loops and stack trace references", true);

    // What the Options window sets. Each part of keeping a scan logged in can be switched off by itself.
    private boolean monitor = true, pauseOnLoss = true, relogin = true;
    /** The session a Test login received, and the requests its browser made: what a check is marked on when the scan logs in by itself. */
    private List<ScanAuth.Header> loginSession = new ArrayList<>();
    private List<ScanAuth.Check> loginRequests = new ArrayList<>();
    private final List<String> avoid = new ArrayList<>();
    private final JLabel optionsLabel = Ui.label("");
    private final DefaultListModel<String> avoidModel = new DefaultListModel<>();
    private final JList<String> avoidList = new JList<>(avoidModel);

    private final CardLayout cards = new CardLayout();
    private final JPanel body = new JPanel(cards);
    private final JPanel common;
    private final JPanel modes;
    private final JPanel noneCard;
    private final JTabbedPane lower = new JTabbedPane();

    /**
     * The step from top to bottom: the three choices, the session, and the
     * tabs under it. The choices take the height they need; what is left is
     * shared between the session and the tabs, so each list has room for
     * several rows and none is cut off at the bottom. A scan that does not log
     * in has no session to show, so the tabs take all of it.
     */
    private final class Shared implements LayoutManager {
        private static final int GAP = 10;
        @Override public void addLayoutComponent(String name, Component c) { }
        @Override public void removeLayoutComponent(Component c) { }
        @Override public Dimension preferredLayoutSize(Container parent) {
            Dimension m = modes.getPreferredSize(), b = body.getPreferredSize(), c = common.getPreferredSize();
            return new Dimension(Math.max(m.width, Math.max(b.width, c.width)), m.height + b.height + c.height + 2 * GAP);
        }
        @Override public Dimension minimumLayoutSize(Container parent) { return new Dimension(200, 200); }
        @Override public void layoutContainer(Container parent) {
            int w = parent.getWidth(), h = parent.getHeight();
            int top = modes.getPreferredSize().height;
            modes.setBounds(0, 0, w, top);
            int left = Math.max(0, h - top - 2 * GAP);
            int session = useNone.isSelected() ? Math.min(left, noneCard.getPreferredSize().height) : sessionShare(left);
            body.setBounds(0, top + GAP, w, session);
            common.setBounds(0, top + GAP + session + GAP, w, Math.max(0, left - session));
        }
    }

    /** How much of the height left over the session takes: a little under half, the tabs having their own headings to fit. */
    static int sessionShare(int left) { return Math.max(0, left * 45 / 100); }

    public ApplicationLoginPanel(SuiteContext ctx, Supplier<List<String>> targets) {
        super(null);
        this.ctx = ctx;
        this.targets = targets;
        setOpaque(false);
        ButtonGroup g = new ButtonGroup();
        g.add(useBrowser); g.add(useCredentials); g.add(useNone);
        modes = Ui.vbox(useBrowser, useCredentials, useNone);
        add(modes);

        body.setOpaque(false);
        body.add(browserCard(), "browser");
        body.add(credentialsCard(), "credentials");
        JPanel none = new JPanel(new BorderLayout());
        none.setOpaque(false);
        none.add(Ui.note("The scan runs without a session. Pages that require a login are not reached."), BorderLayout.NORTH);
        body.add(none, "none");
        noneCard = none;
        add(body);
        common = commonPanel();
        add(common);
        setLayout(new Shared());

        java.awt.event.ActionListener pick = e -> { chosenByHand = true; showMode(); };
        useBrowser.addActionListener(pick); useCredentials.addActionListener(pick); useNone.addActionListener(pick);
        showMode();
    }

    private void showMode() {
        cards.show(body, useBrowser.isSelected() ? "browser" : useCredentials.isSelected() ? "credentials" : "none");
        revalidate();
        boolean session = !useNone.isSelected();
        for (Component c : checkParts) c.setEnabled(session);
        showOptionsLabel();
        showCheck();
    }

    // ------------------------------------------------------- browser session

    private JComponent browserCard() {
        Ui.styleTable(headerTable);
        headerTable.getColumnModel().getColumn(0).setMaxWidth(Ui.em(52));
        headerTable.getColumnModel().getColumn(1).setPreferredWidth(190);
        headerTable.getColumnModel().getColumn(2).setPreferredWidth(110);
        headerTable.getColumnModel().getColumn(3).setPreferredWidth(340);
        headerTable.getColumnModel().getColumn(4).setPreferredWidth(90);
        JButton refresh = Ui.button("Refresh", "Reload session headers from the proxy history");
        refresh.addActionListener(e -> refresh());
        JPanel top = new JPanel(new BorderLayout(8, 0));
        top.setOpaque(false);
        top.add(headerNote, BorderLayout.CENTER);
        JButton needed = Ui.button("Find required", "Repeat a verified session check with each cookie and header removed in turn, to identify which ones the login requires");
        needed.addActionListener(e -> findNeeded(needed));
        JButton mark = Ui.button("Mark header...", "Select another request header that carries this application's session, when it is not listed");
        mark.addActionListener(e -> markHeader());
        top.add(Ui.row(mark, needed, refresh), BorderLayout.EAST);
        JScrollPane sp = Ui.scroll(headerTable);
        sp.setPreferredSize(new Dimension(200, 110));
        JPanel p = new JPanel(new BorderLayout(0, 6));
        p.setOpaque(false);
        p.add(top, BorderLayout.NORTH);
        p.add(sp, BorderLayout.CENTER);
        follow.setOpaque(false);
        p.add(follow, BorderLayout.SOUTH);
        return p;
    }

    /** The services the scan is aimed at, and any other in-scope service the browser has used. */
    private Set<String> sites() {
        Set<String> out = new LinkedHashSet<>();
        for (String url : targets.get()) {
            HttpService s = HttpService.parse(url.trim());
            if (s != null) out.add(s.url());
        }
        if (ctx != null && !ctx.scope().isEmpty()) {
            List<LogEntry> all = ctx.store().all();
            for (int i = all.size() - 1, looked = 0; i >= 0 && looked < 3000; i--, looked++) {
                LogEntry e = all.get(i);
                if (!"proxy".equals(e.tool()) || e.service() == null || out.contains(e.service().url())) continue;
                try { if (ctx.scope().isInScope(e.service(), "/")) out.add(e.service().url()); } catch (RuntimeException ignored) { }
            }
        }
        return out;
    }

    /**
     * Read the browser's session from the proxy history again. Called when
     * the step is shown, so it reflects the targets typed in and whatever
     * the browser has done since.
     */
    public void refresh() {
        if (ctx == null) return;
        Set<String> sites = sites();
        List<ScanAuth.Header> found = ScanAuth.capture(ctx.store().all(), sites, 0);
        java.util.Map<String, Boolean> was = new java.util.HashMap<>();
        java.util.Map<String, String> needed = new java.util.HashMap<>();
        for (Row r : rows) { was.put(r.key(), r.use); needed.put(r.key(), r.needed); }
        rows.clear();
        for (ScanAuth.Header h : found) {
            List<Row> made = new ArrayList<>();
            // Each cookie has a row of its own, so one can be left out.
            if (h.name().equalsIgnoreCase("cookie"))
                for (java.util.Map.Entry<String, String> ck : ScanAuth.parseCookies(h.value()).entrySet())
                    made.add(new Row(new ScanAuth.Header(h.site(), "Cookie", ck.getValue()), ck.getKey()));
            else made.add(new Row(h));
            for (Row r : made) {
                r.use = was.getOrDefault(r.key(), Boolean.TRUE);
                r.needed = needed.getOrDefault(r.key(), "");
                rows.add(r);
            }
        }
        headerModel.fireTableDataChanged();
        headerNote.setText(sites.isEmpty() ? "Enter the URLs to scan first."
                : rows.isEmpty() ? "No session observed for " + String.join(", ", sites) + ". Log in to the application in the browser, then press Refresh."
                : "Session headers from the browser, sent on scanner requests only.");
        if (!chosenByHand) {
            if (!rows.isEmpty()) useBrowser.setSelected(true); else if (useBrowser.isSelected()) useNone.setSelected(true);
        }
        showMode();
    }

    /** Request headers every browser sends, which carry no session: not offered for marking. */
    private static final Set<String> ORDINARY = Set.of("host", "user-agent", "accept", "accept-language", "accept-encoding", "connection",
            "referer", "origin", "content-type", "content-length", "cache-control", "pragma", "upgrade-insecure-requests", "if-none-match",
            "if-modified-since", "dnt", "te", "priority", "range", "x-requested-with");

    /** The request headers seen at the sites that are not listed as session headers and are not ones every browser sends. */
    static List<String> otherHeaders(List<LogEntry> history, Set<String> sites, int lookBack) {
        Set<String> out = new java.util.TreeSet<>(String.CASE_INSENSITIVE_ORDER);
        for (int i = history.size() - 1, looked = 0; i >= 0 && looked < lookBack; i--) {
            LogEntry e = history.get(i);
            if (!"proxy".equals(e.tool()) || e.service() == null || !sites.contains(e.service().url())) continue;
            looked++;
            try {
                for (String line : e.request().headerLines()) {
                    int c = line.indexOf(':');
                    if (c <= 0) continue;
                    String name = line.substring(0, c).trim(), low = name.toLowerCase(java.util.Locale.ROOT);
                    if (ORDINARY.contains(low) || low.startsWith("sec-") || low.startsWith("proxy-") || ScanAuth.isAuthHeader(name)) continue;
                    out.add(name);
                }
            } catch (RuntimeException ignored) { }
        }
        return new ArrayList<>(out);
    }

    /**
     * Let the user say that a header of the application's own carries its
     * session. Session headers are recognised by their usual names; an
     * application may use any name, and only its user knows which.
     */
    private void markHeader() {
        List<String> names = otherHeaders(ctx.store().all(), sites(), 3000);
        if (names.isEmpty()) {
            JOptionPane.showMessageDialog(this, "No other request header has been observed for the target.\n"
                    + "Browse the application while logged in, then press Mark header again.", "Session headers", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        JList<String> list = new JList<>(names.toArray(new String[0]));
        list.setFont(Ui.PLAIN);
        JScrollPane sp = Ui.scroll(list);
        sp.setPreferredSize(new Dimension(Ui.em(420), Ui.em(200)));
        JPanel p = new JPanel(new BorderLayout(0, 8));
        javax.swing.JTextArea note = Ui.note("Request headers observed for the target that are not listed as session headers. Select any that carry this "
                + "application's session; hold Ctrl to select several. They are then listed with the others and follow the browser's session.");
        Ui.sizeNote(note, Ui.em(420));
        p.add(note, BorderLayout.NORTH);
        p.add(sp, BorderLayout.CENTER);
        if (JOptionPane.showConfirmDialog(this, p, "Session headers", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE) != JOptionPane.OK_OPTION) return;
        for (String name : list.getSelectedValuesList()) ScanAuth.MARKED.add(name.toLowerCase(java.util.Locale.ROOT));
        refresh();
    }

    private List<ScanAuth.Header> ticked() { return tickedWithout(null); }

    /** The ticked headers, the ticked cookies of a site put back into one Cookie header, leaving one row out. */
    private List<ScanAuth.Header> tickedWithout(Row left) {
        List<ScanAuth.Header> out = new ArrayList<>();
        java.util.Map<String, java.util.Map<String, String>> jars = new java.util.LinkedHashMap<>();
        for (Row r : rows) {
            if (!r.use || r == left) continue;
            if (r.cookie == null) out.add(r.header);
            else jars.computeIfAbsent(r.header.site(), k -> new java.util.LinkedHashMap<>()).put(r.cookie, r.header.value());
        }
        List<ScanAuth.Header> cookies = new ArrayList<>();
        for (java.util.Map.Entry<String, java.util.Map<String, String>> j : jars.entrySet())
            cookies.add(new ScanAuth.Header(j.getKey(), "Cookie", ScanAuth.cookieHeader(j.getValue())));
        cookies.addAll(out);
        return cookies;
    }

    /**
     * Find out which of the ticked cookies and headers the login depends on:
     * a verified session check is sent with each one left out in turn, and
     * the ones without which its logged-in text is gone are marked.
     */
    private void findNeeded(JButton button) {
        if (ticked().isEmpty()) { headerNote.setText("No session available to test."); return; }
        ScanAuth.Check proven = null;
        for (ScanAuth.Check c : checks) if (c.usable) { proven = c; break; }
        if (proven == null) {
            headerNote.setText("Add and verify a session check first: the required headers are those without which its logged-in text is gone.");
            lower.setSelectedIndex(1);
            return;
        }
        final ScanAuth.Check use = proven;
        button.setEnabled(false);
        List<Row> tried = new ArrayList<>();
        for (Row r : rows) if (r.use) tried.add(r);
        new Thread(() -> {
            java.util.Map<Row, String> result = new java.util.LinkedHashMap<>();
            String said;
            try {
                for (Row r : tried) {
                    List<ScanAuth.Header> rest = new ArrayList<>(extra);
                    rest.addAll(tickedWithout(r));
                    ScanAuth.State st = ScanAuth.run(use, rest).state();
                    result.put(r, st == ScanAuth.State.IN ? "no" : st == ScanAuth.State.OUT ? "yes" : "unknown");
                }
                said = "Tested on " + use.request.method() + " " + use.request.requestTarget()
                        + ": \"yes\" marks what that request requires. Other pages may require more, so deselect with care.";
            } catch (RuntimeException ex) {
                said = "Could not be determined: " + ex;
            }
            final String shown = said;
            SwingUtilities.invokeLater(() -> {
                for (java.util.Map.Entry<Row, String> e : result.entrySet()) e.getKey().needed = e.getValue();
                headerModel.fireTableDataChanged();
                headerNote.setText(shown);
                button.setEnabled(true);
            });
        }, "session-needed").start();
    }

    // ----------------------------------------------------------- credentials

    private JComponent credentialsCard() {
        Ui.styleTable(credTable);
        JButton neu = Ui.button("New"), edit = Ui.button("Edit"), delete = Ui.button("Delete");
        JButton test = Ui.button("Test login", "Log in now with the selected credentials and show the result");
        neu.addActionListener(e -> { LoginStore.Credentials c = CredentialsDialog.show(this, null); if (c != null) { credentials.add(c); credModel.fireTableDataChanged(); credTable.setRowSelectionInterval(credentials.size() - 1, credentials.size() - 1); } });
        edit.addActionListener(e -> { int i = credTable.getSelectedRow(); if (i >= 0 && CredentialsDialog.show(this, credentials.get(i)) != null) credModel.fireTableDataChanged(); });
        delete.addActionListener(e -> { int i = credTable.getSelectedRow(); if (i >= 0) { credentials.remove(i); credModel.fireTableDataChanged(); } });
        test.addActionListener(e -> testLogin(test));
        JScrollPane sp = Ui.scroll(credTable);
        sp.setPreferredSize(new Dimension(200, 90));
        JPanel mid = new JPanel(new BorderLayout(6, 0));
        mid.setOpaque(false);
        mid.add(Ui.buttonColumn(neu, edit, delete, test), BorderLayout.WEST);
        mid.add(sp, BorderLayout.CENTER);
        JPanel links = new JPanel(new FlowLayout(FlowLayout.LEFT, 14, 0));
        links.setOpaque(false);
        links.add(link("Select from library", this::selectFromLibrary));
        links.add(link("Save to library", this::saveToLibrary));
        JPanel p = new JPanel(new BorderLayout(0, 6));
        p.setOpaque(false);
        p.add(Ui.note("The scan opens the login page in a headless browser, enters the selected credentials, "
                + "and repeats the login automatically whenever the session ends."), BorderLayout.NORTH);
        p.add(mid, BorderLayout.CENTER);
        loginPage.setToolTipText("URL of the page containing the login form. Leave empty to detect it automatically: "
                + "from a login recorded in the proxy history, or from the forms at the target.");
        p.add(Ui.vbox(Ui.form("Login page (empty to detect):", loginPage), loginResult, links), BorderLayout.SOUTH);
        return p;
    }

    private LoginStore.Credentials selectedCredentials() {
        if (credentials.isEmpty()) return null;
        int i = credTable.getSelectedRow();
        return credentials.get(i >= 0 && i < credentials.size() ? i : 0);
    }

    private void testLogin(JButton button) {
        LoginStore.Credentials c = selectedCredentials();
        if (c == null) { loginResult.setText("Add the credentials first."); return; }
        Set<String> sites = sites();
        if (sites.isEmpty()) { loginResult.setText("Enter the URLs to scan first."); return; }
        button.setEnabled(false);
        loginResult.setText("Logging in...");
        List<LogEntry> history = ctx.store().all();
        HttpService first = HttpService.parse(sites.iterator().next());
        final String typed = loginPage.getText().strip();
        new Thread(() -> {
            String text;
            List<ScanAuth.Header> got = new ArrayList<>();
            List<ScanAuth.Check> requests = new ArrayList<>();
            try {
                String url = typed;
                if (url.isEmpty()) {
                    LoginFlow.Template t = LoginFlow.fromHistory(history, sites, c.username, c.password);
                    if (t == null && first != null) t = LoginFlow.detect(first, "/");
                    if (t != null) url = t.pageUrl();
                }
                if (url.isEmpty()) text = "No login page was found. Enter its URL above.";
                else {
                    opensuite.engine.ZapEngine ze = opensuite.engine.ZapEngine.shared();
                    ze.start();
                    opensuite.engine.EngineLogin.Result r = opensuite.engine.EngineLogin.login(
                            ze.api(), ctx.settings(), sites, url, c.username, c.password);
                    if (r.ok()) { got.addAll(r.headers()); requests.addAll(r.checks()); }
                    text = !r.ok() ? "Not logged in: " + r.detail()
                            : "Login completed at " + url + ": a session was received. Add a session check to confirm it and to monitor it during the scan.";
                }
            } catch (Exception ex) {
                text = "Not logged in: " + (ex.getMessage() == null ? ex.toString() : ex.getMessage());
            }
            final String shown = text;
            SwingUtilities.invokeLater(() -> {
                loginSession = got;
                loginRequests = requests;
                loginResult.setText(shown);
                loginResult.setToolTipText(shown);
                button.setEnabled(true);
                showCheck();
            });
        }, "login-test").start();
    }

    // ------------------------------------------------- common to both modes

    private final List<Component> checkParts = new ArrayList<>();

    private JPanel commonPanel() {
        JButton add = Ui.button("Add...", "Select a request, highlight the text in its response that appears only while logged in, and verify it");
        JButton drop = Ui.button("Remove", "Remove the selected check from the list");
        JButton test = Ui.button("Verify", "Verify each check again: its text must be in every response with the session and absent without it");
        add.addActionListener(e -> addCheck());
        drop.addActionListener(e -> { int r = checkTable.getSelectedRow(); if (r >= 0) { checks.remove(r); checkModel.fireTableDataChanged(); showCheck(); } });
        test.addActionListener(e -> testChecks(test));
        checkParts.add(add); checkParts.add(drop); checkParts.add(test); checkParts.add(checkTable);
        Ui.styleTable(checkTable);
        checkTable.getColumnModel().getColumn(0).setPreferredWidth(260);
        checkTable.getColumnModel().getColumn(1).setPreferredWidth(150);
        checkTable.getColumnModel().getColumn(2).setPreferredWidth(330);
        checkTable.getColumnModel().getColumn(3).setPreferredWidth(110);
        JScrollPane checkScroll = Ui.scroll(checkTable);
        checkScroll.setPreferredSize(new Dimension(200, 110));
        JPanel checkHead = new JPanel(new BorderLayout(8, 0));
        checkHead.setOpaque(false);
        checkHead.add(Ui.bold("Session checks"), BorderLayout.WEST);
        checkHead.add(Ui.row(add, drop, test), BorderLayout.EAST);
        JPanel checkRow = new JPanel(new BorderLayout(0, 4));
        checkRow.setOpaque(false);
        checkRow.add(checkHead, BorderLayout.NORTH);
        checkRow.add(checkScroll, BorderLayout.CENTER);

        Ui.styleTable(extraTable);
        JButton addHeader = Ui.button("Add"), remove = Ui.button("Remove");
        addHeader.addActionListener(e -> addExtra());
        remove.addActionListener(e -> { int i = extraTable.getSelectedRow(); if (i >= 0) { extra.remove(i); extraModel.fireTableDataChanged(); } });
        JScrollPane sp = Ui.scroll(extraTable);
        sp.setPreferredSize(new Dimension(200, 110));
        JPanel extraRow = new JPanel(new BorderLayout(6, 0));
        extraRow.setOpaque(false);
        extraRow.add(Ui.buttonColumn(addHeader, remove), BorderLayout.WEST);
        extraRow.add(sp, BorderLayout.CENTER);

        skipLogout.setOpaque(false);
        JButton options = Ui.button("Options...", "Session handling options for the scan, and the URLs it excludes");
        options.addActionListener(e -> showOptions());
        checkParts.add(options);
        JPanel optionsRow = new JPanel(new BorderLayout(8, 0));
        optionsRow.setOpaque(false);
        optionsRow.add(optionsLabel, BorderLayout.CENTER);
        optionsRow.add(options, BorderLayout.EAST);
        showOptionsLabel();
        JButton select = Ui.button("Select...", "Select pages to exclude from this scan");
        JButton unselect = Ui.button("Remove", "Allow the scan to request the selected page again");
        JButton addTyped = Ui.button("Enter URL...", "Type the URLs to exclude from this scan");
        addTyped.addActionListener(e -> addAvoid());
        select.addActionListener(e -> selectAvoid());
        unselect.addActionListener(e -> {
            for (String v : avoidList.getSelectedValuesList()) { avoid.remove(v); avoidModel.removeElement(v); }
        });
        avoidList.setFont(Ui.PLAIN);
        avoidList.setVisibleRowCount(5);
        JScrollPane avoidScroll = Ui.scroll(avoidList);
        avoidScroll.setPreferredSize(new Dimension(200, 110));
        JPanel avoidHead = new JPanel(new BorderLayout(8, 0));
        avoidHead.setOpaque(false);
        avoidHead.add(Ui.bold("Pages excluded from this scan"), BorderLayout.WEST);
        avoidHead.add(Ui.row(select, addTyped, unselect), BorderLayout.EAST);
        JPanel avoidRow = new JPanel(new BorderLayout(0, 4));
        avoidRow.setOpaque(false);
        avoidRow.add(avoidHead, BorderLayout.NORTH);
        avoidRow.add(avoidScroll, BorderLayout.CENTER);
        JLabel avoidNote = Ui.label("Select or enter logout pages and any other page that ends the session, so that the scan stays logged in.");
        avoidNote.setForeground(Theme.MUTED);
        skipLoops.setOpaque(false);
        skipLoops.setToolTipText("<html>Some applications return a page for any URL, so a crawl can generate new URLs indefinitely.<br>"
                + "A URL that repeats a folder name three times (/a/b/a/b/a/b) is requested once and compared with the same URL<br>"
                + "without the repeats. If the responses match, further URLs of that form are skipped; if they differ, they are kept.<br>"
                + "Stack trace references (/app/file.js:68:18) are skipped. Every skipped URL is listed in the scan's event log.</html>");
        // Each list has a tab to itself, so it has the height of the whole lower half and not a third of it.
        lower.addTab("Out of scope", tab(avoidRow, Ui.vbox(avoidNote, skipLoops)));
        lower.addTab("Session checks", tab(checkRow, checkNote));
        JLabel extraNote = Ui.label("Added to every scanner request, in addition to the session headers.");
        extraNote.setForeground(Theme.MUTED);
        lower.addTab("Extra headers", tab(extraRow, extraNote));
        avoidModel.addListDataListener(new javax.swing.event.ListDataListener() {
            @Override public void intervalAdded(javax.swing.event.ListDataEvent e) { nameTabs(); }
            @Override public void intervalRemoved(javax.swing.event.ListDataEvent e) { nameTabs(); }
            @Override public void contentsChanged(javax.swing.event.ListDataEvent e) { nameTabs(); }
        });
        checkModel.addTableModelListener(e -> nameTabs());
        extraModel.addTableModelListener(e -> nameTabs());
        nameTabs();
        JPanel p = new JPanel(new BorderLayout(0, 6));
        p.setOpaque(false);
        p.add(lower, BorderLayout.CENTER);
        p.add(optionsRow, BorderLayout.SOUTH);
        return p;
    }

    /** One tab: a list that takes the room there is, with what is said about it underneath. */
    private static JPanel tab(JComponent list, JComponent under) {
        JPanel p = new JPanel(new BorderLayout(0, 4));
        p.setOpaque(false);
        p.setBorder(Ui.pad(8, 8, 6, 8));
        p.add(list, BorderLayout.CENTER);
        p.add(under, BorderLayout.SOUTH);
        return p;
    }

    /** Each tab says how many entries it holds, so a list that is not in front is not forgotten. */
    private void nameTabs() {
        if (lower.getTabCount() < 3) return;
        lower.setTitleAt(0, tabTitle("Out of scope", avoidModel.size()));
        lower.setTitleAt(1, tabTitle("Session checks", checks.size()));
        lower.setTitleAt(2, tabTitle("Extra headers", extra.size()));
    }

    static String tabTitle(String name, int entries) { return entries == 0 ? name : name + " (" + entries + ")"; }

    private void checkChanged() { showCheck(); }

    /**
     * Type the addresses this scan is not to request, one on a line. For pages
     * that have not been browsed to, and for whole areas given with a *.
     */
    private void addAvoid() {
        JTextArea typed = new JTextArea(5, 44);
        typed.setFont(Ui.PLAIN);
        focusOnOpen(typed);
        JPanel p = new JPanel(new BorderLayout(0, 8));
        p.add(Ui.note("Enter the URLs the scan must not request, one per line. Use a full URL (https://app.example/logout), "
                + "a path that applies to every target (/logout), or * as a wildcard (/admin/*). A page is excluded over HTTP and HTTPS, on any port of its host."), BorderLayout.NORTH);
        p.add(Ui.scroll(typed), BorderLayout.CENTER);
        if (JOptionPane.showConfirmDialog(this, p, "Out of scope for this scan", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE) != JOptionPane.OK_OPTION) return;
        for (String v : typedAddresses(typed.getText())) if (!avoid.contains(v)) { avoid.add(v); avoidModel.addElement(v); }
    }

    /** What was typed, a line at a time: blank lines and repeats dropped, spaces around an address removed. */
    static List<String> typedAddresses(String typed) {
        List<String> out = new ArrayList<>();
        if (typed == null) return out;
        for (String line : typed.split("\\R")) {
            String t = line.strip();
            if (!t.isEmpty() && !out.contains(t)) out.add(t);
        }
        return out;
    }

    /**
     * Pick the pages this scan is not to request, from the pages seen at its
     * targets. Pages whose names say they end a session are offered first and
     * already picked. The choice holds for this scan only; the suite's own
     * scope is not touched.
     */
    private void selectAvoid() {
        Set<String> sites = sites();
        java.util.TreeSet<String> pages = new java.util.TreeSet<>();
        List<LogEntry> all = ctx.store().all();
        for (int i = all.size() - 1, looked = 0; i >= 0 && looked < 20000; i--, looked++) {
            LogEntry e = all.get(i);
            try {
                if (e.service() == null || !sites.contains(e.service().url())) continue;
                String path = e.request().path();
                if (path != null && !path.isEmpty() && !path.equals("/")) pages.add(e.service().url() + path);
            } catch (RuntimeException ignored) { }
        }
        pages.removeAll(avoid);
        if (pages.isEmpty()) {
            JOptionPane.showMessageDialog(this, sites.isEmpty() ? "Enter the URLs to scan first."
                    : "No pages of the target have been observed. Browse the application first, including the logout page, then select again.",
                    "Out of scope for this scan", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        List<String> ordered = new ArrayList<>();
        java.util.regex.Pattern ends = java.util.regex.Pattern.compile("(?i)log[-_]?out|sign[-_]?out|log[-_]?off|sign[-_]?off");
        for (String pg : pages) if (ends.matcher(pg).find()) ordered.add(pg);
        int likely = ordered.size();
        for (String pg : pages) if (!ordered.contains(pg)) ordered.add(pg);
        // What is picked is kept apart from what is shown, so a page picked under one search stays picked under the next.
        Set<String> picked = new LinkedHashSet<>(ordered.subList(0, likely));
        DefaultListModel<String> shown = new DefaultListModel<>();
        JList<String> list = new JList<>(shown);
        list.setFont(Ui.PLAIN);
        JTextField search = new JTextField();
        search.setFont(Ui.PLAIN);
        search.setToolTipText("Show only pages whose URL contains this text, such as logout. Multiple words must all match");
        JLabel count = Ui.label(" ");
        count.setForeground(Theme.MUTED);
        boolean[] filling = {false};
        Runnable say = () -> count.setText(shown.size() + " of " + ordered.size() + " shown, " + picked.size() + " selected");
        Runnable fill = () -> {
            filling[0] = true;
            shown.clear();
            List<String> match = matching(ordered, search.getText());
            shown.addAll(match);
            List<Integer> rows = new ArrayList<>();
            for (int i = 0; i < match.size(); i++) if (picked.contains(match.get(i))) rows.add(i);
            list.setSelectedIndices(rows.stream().mapToInt(Integer::intValue).toArray());
            filling[0] = false;
            say.run();
        };
        list.addListSelectionListener(e -> {
            if (filling[0] || e.getValueIsAdjusting()) return;
            for (int i = 0; i < shown.size(); i++) {
                if (list.isSelectedIndex(i)) picked.add(shown.get(i)); else picked.remove(shown.get(i));
            }
            say.run();
        });
        search.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {
            @Override public void insertUpdate(javax.swing.event.DocumentEvent e) { fill.run(); }
            @Override public void removeUpdate(javax.swing.event.DocumentEvent e) { fill.run(); }
            @Override public void changedUpdate(javax.swing.event.DocumentEvent e) { fill.run(); }
        });
        // Enter in the search box goes to the list. It does not press OK, which would add pages nobody looked at.
        search.addActionListener(e -> { list.requestFocusInWindow(); if (list.isSelectionEmpty() && !shown.isEmpty()) list.ensureIndexIsVisible(0); });
        focusOnOpen(search);
        fill.run();
        JScrollPane sp = Ui.scroll(list);
        sp.setPreferredSize(new Dimension(Ui.em(560), Ui.em(280)));
        JPanel find = new JPanel(new BorderLayout(8, 0));
        find.setOpaque(false);
        find.add(Ui.label("Search:"), BorderLayout.WEST);
        find.add(search, BorderLayout.CENTER);
        find.add(count, BorderLayout.EAST);
        JPanel top = new JPanel(new BorderLayout(0, 8));
        top.setOpaque(false);
        top.add(Ui.note("A scan requests every page it finds. Select the pages it must not request: logout, and any other page that ends "
                + "the session or changes the account. Hold Ctrl to select several. A page is excluded over HTTP and HTTPS, on any port of its host."), BorderLayout.NORTH);
        top.add(find, BorderLayout.SOUTH);
        JPanel p = new JPanel(new BorderLayout(0, 8));
        p.add(top, BorderLayout.NORTH);
        p.add(sp, BorderLayout.CENTER);
        if (JOptionPane.showConfirmDialog(this, p, "Out of scope for this scan", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE) != JOptionPane.OK_OPTION) return;
        for (String v : picked) if (!avoid.contains(v)) { avoid.add(v); avoidModel.addElement(v); }
    }

    /**
     * The pages whose address has what was typed in it, in the order given.
     * Capitals make no difference. Several words narrow the search: an address
     * must have every one of them. Nothing typed shows every page.
     */
    static List<String> matching(List<String> pages, String typed) {
        List<String> words = new ArrayList<>();
        if (typed != null) for (String w : typed.toLowerCase(java.util.Locale.ROOT).trim().split("\\s+")) if (!w.isEmpty()) words.add(w);
        if (words.isEmpty()) return new ArrayList<>(pages);
        List<String> out = new ArrayList<>();
        for (String pg : pages) {
            String low = pg.toLowerCase(java.util.Locale.ROOT);
            boolean all = true;
            for (String w : words) if (!low.contains(w)) { all = false; break; }
            if (all) out.add(pg);
        }
        return out;
    }

    /**
     * Typing goes straight into this box when its window opens. The window
     * puts OK in focus as it opens, so the box is asked for once the window
     * itself has the focus.
     */
    private static void focusOnOpen(JComponent box) {
        box.addHierarchyListener(e -> {
            if ((e.getChangeFlags() & java.awt.event.HierarchyEvent.SHOWING_CHANGED) == 0 || !box.isShowing()) return;
            java.awt.Window w = SwingUtilities.getWindowAncestor(box);
            if (w == null) return;
            w.addWindowFocusListener(new java.awt.event.WindowAdapter() {
                @Override public void windowGainedFocus(java.awt.event.WindowEvent ev) {
                    w.removeWindowFocusListener(this);
                    SwingUtilities.invokeLater(box::requestFocusInWindow);
                }
            });
        });
    }

    /** What a check was found to depend on, in words. */
    private String watches(ScanAuth.Check k) {
        if (!k.usable) return "";
        List<String> out = new ArrayList<>();
        for (String need : k.needs) {
            for (ScanAuth.Header h : sessionNow()) if (h.key().equals(need)) out.add(h.name());
        }
        return out.isEmpty() ? "" : String.join(", ", out);
    }

    private void showOptionsLabel() {
        String watch = !monitor ? "The session is not monitored during the scan."
                : useCredentials.isSelected() && relogin ? "If the session ends, the scan logs in again."
                : pauseOnLoss ? "If the session ends, the scan pauses until a new session is available."
                : "If the session ends, the scan continues and reports it.";
        optionsLabel.setText(useNone.isSelected() ? " " : watch
                + (skipLogout.isSelected() ? " Logout and sign-out links are skipped." : ""));
    }

    private final List<String> formTokens = new ArrayList<>();

    /** Names typed with commas, spaces or new lines between them. */
    private static List<String> tokenList(String typed) {
        List<String> out = new ArrayList<>();
        for (String t : typed.split("[,\\s]+")) if (!t.isBlank() && !out.contains(t.strip())) out.add(t.strip());
        return out;
    }

    /** The window where each part of keeping the scan logged in is switched on or off. */
    private void showOptions() {
        JCheckBox watch = Ui.check("Monitor the session during the scan", monitor);
        JRadioButton pause = Ui.radio("Pause the scan until a valid session is available", pauseOnLoss);
        JRadioButton carryOn = Ui.radio("Continue the scan and only report it", !pauseOnLoss);
        ButtonGroup g = new ButtonGroup();
        g.add(pause); g.add(carryOn);
        JCheckBox again = Ui.check("Log in again when the session ends (username and password only)", relogin);
        JCheckBox logout = Ui.check("Skip logout links and buttons (URLs containing log out, sign out, log off or sign off)", skipLogout.isSelected());
        JTextField tokens = Ui.field(String.join(", ", formTokens), 30);
        JButton tokenSelect = Ui.button("Select...", "Select from the hidden fields of forms observed at the target");
        tokenSelect.addActionListener(e -> {
            List<String> found = ScanAuth.hiddenFields(ctx.store().all(), sites(), 12);
            if (found.isEmpty()) {
                JOptionPane.showMessageDialog(tokenSelect, "No form with a hidden field of a non-standard name has been observed at the target.\n"
                        + "Browse to the form first, then press Select again.", "Form tokens", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            JList<String> pick = new JList<>(found.toArray(new String[0]));
            pick.setFont(Ui.PLAIN);
            JPanel box = new JPanel(new BorderLayout(0, 6));
            box.add(Ui.note("Hidden fields of forms observed at the target. Select those that change each time the form is loaded."), BorderLayout.NORTH);
            box.add(Ui.scroll(pick), BorderLayout.CENTER);
            if (JOptionPane.showConfirmDialog(tokenSelect, box, "Form tokens", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE) != JOptionPane.OK_OPTION) return;
            List<String> now = tokenList(tokens.getText());
            for (String v : pick.getSelectedValuesList()) if (!now.contains(v)) now.add(v);
            tokens.setText(String.join(", ", now));
        });
        Runnable enable = () -> {
            for (Component c : new Component[] {pause, carryOn, again}) c.setEnabled(watch.isSelected());
        };
        watch.addActionListener(e -> enable.run());
        enable.run();
        for (JComponent c : new JComponent[] {watch, pause, carryOn, again, logout}) c.setOpaque(false);
        JPanel indent = Ui.vbox(Ui.label("When the session ends:"), pause, carryOn, Box.createVerticalStrut(4), again,
                Box.createVerticalStrut(4),
                Ui.note("The session is monitored by the session checks: it is valid while each check's response contains its logged-in text. "
                        + "Without a session check, the session is not monitored."));
        indent.setBorder(Ui.pad(0, 18, 0, 0));
        JPanel tokenRow = new JPanel(new BorderLayout(6, 0));
        tokenRow.setOpaque(false);
        tokenRow.add(tokens, BorderLayout.CENTER);
        tokenRow.add(tokenSelect, BorderLayout.EAST);
        JPanel p = Ui.vbox(watch, indent, Box.createVerticalStrut(10), logout, Box.createVerticalStrut(10),
                Ui.bold("Form tokens"),
                Ui.note("A form that carries a new token each time it is loaded is tested only if the scanner knows the token field name. "
                        + "Common names are recognised by default. Add any others here, separated by commas."),
                tokenRow);
        if (JOptionPane.showConfirmDialog(this, p, "Session options", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE) != JOptionPane.OK_OPTION) return;
        monitor = watch.isSelected();
        pauseOnLoss = pause.isSelected();
        relogin = again.isSelected();
        skipLogout.setSelected(logout.isSelected());
        formTokens.clear();
        formTokens.addAll(tokenList(tokens.getText()));
        showOptionsLabel();
        checkChanged();
    }

    private void showCheck() {
        String text;
        if (useNone.isSelected()) text = "Not used without a login.";
        else if (checks.isEmpty()) text = "No session check is set: the session will not be monitored during the scan. Press Add to set one.";
        else {
            boolean tried = false;
            for (ScanAuth.Check c : checks) if (!c.measured.isEmpty()) tried = true;
            List<String> bare = new ArrayList<>();
            if (tried) for (ScanAuth.Header h : ScanAuth.unwatched(checks, sessionNow())) bare.add(h.name() + " on " + h.site());
            text = !tried ? "Press Verify to check them against the application."
                    : bare.isEmpty() ? "Every session header is monitored by a check."
                    : "Not monitored: " + String.join("; ", bare) + ". Add a check on a request that requires it, or its expiry will not be detected.";
        }
        checkNote.setText(text);
        checkNote.setToolTipText(text);
    }

    /** The headers a check is sent with now: the browser's ticked ones, or the ones a Test login received. */
    private List<ScanAuth.Header> sessionNow() {
        return useBrowser.isSelected() ? ticked() : useCredentials.isSelected() ? new ArrayList<>(loginSession) : new ArrayList<>();
    }

    /** Open the window where a request is chosen, its response shown and the logged-in text marked and proven. */
    private void addCheck() {
        List<ScanAuth.Header> session = sessionNow();
        if (session.isEmpty()) {
            JOptionPane.showMessageDialog(this, useCredentials.isSelected()
                    ? "Press Test login first. The session check is marked on a response the application returns after the login."
                    : "No session is selected. Log in to the application in the browser, press Refresh, then add the check.",
                    "Session checks", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        List<ScanAuth.Check> found = new ArrayList<>();
        if (useCredentials.isSelected()) found.addAll(loginRequests);
        Set<String> have = new java.util.HashSet<>();
        for (ScanAuth.Check c : found) have.add(c.service.url() + c.request.requestTarget());
        for (ScanAuth.Check c : ScanAuth.candidates(ctx.store().all(), sites(), 500))
            if (have.add(c.service.url() + c.request.requestTarget())) found.add(c);
        if (found.isEmpty()) {
            JOptionPane.showMessageDialog(this, "The proxy history contains no page or API request for the target.\n"
                    + "Open a page that shows you are logged in, in the browser, then press Add again.", "Session checks", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        ScanAuth.Check made = SessionCheckDialog.show(this, found, session, new ArrayList<>(extra));
        if (made == null) return;
        checks.add(made);
        checkModel.fireTableDataChanged();
        showCheck();
    }

    /** Prove every listed check again and show what the application answered. */
    private void testChecks(JButton button) {
        List<ScanAuth.Header> session = sessionNow();
        if (checks.isEmpty()) { checkNote.setText("No session check is set. Press Add to set one."); return; }
        if (session.isEmpty()) {
            checkNote.setText(useCredentials.isSelected() ? "Press Test login first: the checks are verified with the session the login receives."
                    : "No session available to test.");
            return;
        }
        button.setEnabled(false);
        checkNote.setText("Verifying...");
        List<ScanAuth.Check> all = new ArrayList<>(checks);
        List<ScanAuth.Header> typed = new ArrayList<>(extra);
        new Thread(() -> {
            for (ScanAuth.Check c : all) {
                try { ScanAuth.measure(c, session, typed); }
                catch (RuntimeException ex) { c.usable = false; c.measured = "Could not be verified: " + ex; }
            }
            SwingUtilities.invokeLater(() -> { checkModel.fireTableDataChanged(); showCheck(); button.setEnabled(true); });
        }, "session-check-test").start();
    }

    private void addExtra() {
        JTextField name = Ui.field("", 18), value = Ui.field("", 34);
        JPanel form = Ui.form("Header:", name, "Value:", value);
        focusWhenShown(name);
        if (JOptionPane.showConfirmDialog(this, form, "Extra header", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE) != JOptionPane.OK_OPTION) return;
        String n = name.getText().strip().replaceAll(":$", ""), v = value.getText().strip();
        if (n.isEmpty() || !n.matches("[!#$%&'*+.^_`|~0-9A-Za-z-]+")) {
            JOptionPane.showMessageDialog(this, "Invalid header name.", "Extra header", JOptionPane.WARNING_MESSAGE);
            return;
        }
        extra.add(new ScanAuth.Header("", n, v));
        extraModel.fireTableDataChanged();
    }

    // ---------------------------------------------------------------- result

    /** How the scan is to stay logged in, as set on this step. */
    public ScanAuth auth() {
        ScanAuth a = new ScanAuth();
        a.extra.addAll(extra);
        a.skipLogout = skipLogout.isSelected();
        a.skipLoops = skipLoops.isSelected();
        a.checks.addAll(checks);
        a.monitor = monitor; a.pauseOnLoss = pauseOnLoss; a.relogin = relogin;
        a.avoid.addAll(avoid);
        a.formTokens.addAll(formTokens);
        if (useBrowser.isSelected() && !ticked().isEmpty()) {
            a.mode = ScanAuth.Mode.BROWSER;
            a.headers.addAll(ticked());
            a.follow = follow.isSelected();
            // The session is the browser's: the scan names itself as that browser, unless the user
            // has set a User-Agent of their own under Extra headers.
            boolean own = false;
            for (ScanAuth.Header h : a.extra) own |= h.name().equalsIgnoreCase("User-Agent");
            if (!own) {
                java.util.Set<String> at = new java.util.LinkedHashSet<>();
                for (ScanAuth.Header h : a.headers) at.add(h.site());
                String ua = ScanAuth.userAgent(ctx.store().all(), at);
                if (ua != null) a.extra.add(new ScanAuth.Header("", "User-Agent", ua));
            }
            // A single-page application keeps its login in the browser's storage: taken from the
            // built-in browser, where the user is signed in, for each site of the scan.
            for (String site : sites()) {
                java.util.Map<String, String> held = opensuite.proxy.NewTabPage.storageOf(site);
                if (!held.isEmpty()) a.storage.put(site, held);
            }
            for (Row r : rows) if (!r.use && r.cookie != null) a.dropCookies.add(r.header.site() + "\n" + r.cookie);
        } else if (useCredentials.isSelected() && selectedCredentials() != null) {
            LoginStore.Credentials c = selectedCredentials();
            a.mode = ScanAuth.Mode.CREDENTIALS;
            a.username = c.username;
            a.password = c.password;
            a.loginUrl = loginPage.getText().strip();
        }
        a.sessionMissing = useBrowser.isSelected() && a.mode == ScanAuth.Mode.NONE;
        if (a.mode == ScanAuth.Mode.NONE) a.checks.clear();
        return a;
    }

    public boolean usesCredentials() { return useCredentials.isSelected(); }
    public List<LoginStore.Credentials> credentials() { return new ArrayList<>(credentials); }

    /** A one-line description for the task card. */
    public String describe() { return auth().describe(); }

    /** Put the caret in a dialog's first field as it opens, so typing goes there. */
    private static void focusWhenShown(JComponent c) {
        c.addHierarchyListener(e -> {
            if ((e.getChangeFlags() & java.awt.event.HierarchyEvent.SHOWING_CHANGED) != 0 && c.isShowing())
                SwingUtilities.invokeLater(c::requestFocusInWindow);
        });
    }

    private static JComponent link(String text, Runnable action) {
        JLabel l = new JLabel("<html><u>" + text + "</u></html>");
        l.setFont(Ui.PLAIN);
        l.setForeground(new Color(0x1A, 0x5F, 0xB4));
        l.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        l.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override public void mouseClicked(java.awt.event.MouseEvent e) { action.run(); }
        });
        return l;
    }

    private void selectFromLibrary() {
        String name = LibraryDialog.pick(this, "login", "Load from configuration library");
        if (name == null) return;
        Object o = LoginStore.load(name);
        if (o instanceof LoginStore.Credentials c) {
            credentials.add(c);
            credModel.fireTableDataChanged();
            credTable.setRowSelectionInterval(credentials.size() - 1, credentials.size() - 1);
        } else {
            JOptionPane.showMessageDialog(this, "The selected library entry does not contain a username and password.", "Load from configuration library", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    private void saveToLibrary() {
        try {
            LoginStore.Credentials c = credTable.getSelectedRow() < 0 ? null : selectedCredentials();
            if (c == null) { JOptionPane.showMessageDialog(this, "Select a credential to save.", "Save to library", JOptionPane.INFORMATION_MESSAGE); return; }
            LoginStore.save(c);
        } catch (java.io.IOException e) {
            JOptionPane.showMessageDialog(this, "Could not save: " + e.getMessage(), "Save to library", JOptionPane.ERROR_MESSAGE);
        }
    }

    // ---- dialogs ----

    /** "New Login Credentials": label, username, password (with show/hide). */
    static final class CredentialsDialog {
        static LoginStore.Credentials show(Component parent, LoginStore.Credentials editing) {
            Window owner = parent == null ? null : SwingUtilities.getWindowAncestor(parent);
            JDialog d = new JDialog(owner, editing == null ? "New Login Credentials" : "Edit Login Credentials", Dialog.ModalityType.APPLICATION_MODAL);
            LoginStore.Credentials[] out = {null};
            JTextField label = Ui.field(editing == null ? "" : editing.label);
            JTextField user = Ui.field(editing == null ? "" : editing.username);
            JPasswordField pass = Ui.passwordField(editing == null ? "" : editing.password);
            pass.setFont(Ui.PLAIN);
            JToggleButton eye = new JToggleButton(Glyphs.search(14, Theme.MUTED));
            eye.setToolTipText("Show or hide the password");
            eye.setFocusable(false);
            char echo = pass.getEchoChar();
            eye.addActionListener(e -> pass.setEchoChar(eye.isSelected() ? (char) 0 : echo));
            JPanel form = Ui.form("Label:", label, "Username:", user, "Password:", Ui.row(pass, eye));
            form.setBorder(Ui.pad(16, 18, 8, 18));
            JButton ok = Ui.primaryButton("OK", "Save these credentials");
            JButton cancel = Ui.button("Cancel");
            ok.addActionListener(e -> {
                if (label.getText().isBlank()) { JOptionPane.showMessageDialog(d, "Enter a label for the credentials.", "Login credentials", JOptionPane.WARNING_MESSAGE); return; }
                LoginStore.Credentials c = editing == null ? new LoginStore.Credentials() : editing;
                c.label = label.getText().strip(); c.username = user.getText(); c.password = new String(pass.getPassword());
                out[0] = c; d.dispose();
            });
            cancel.addActionListener(e -> d.dispose());
            JPanel bar = new JPanel(new FlowLayout(FlowLayout.RIGHT, 6, 8));
            bar.add(ok); bar.add(cancel);
            JPanel root = new JPanel(new BorderLayout());
            root.add(form, BorderLayout.CENTER); root.add(bar, BorderLayout.SOUTH);
            d.setContentPane(root); d.pack(); d.setLocationRelativeTo(parent); d.setVisible(true);
            return out[0];
        }
    }
}