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.

31.5 KB
Raw Blame
package opensuite.session;

import opensuite.core.*;
import opensuite.ui.*;
import opensuite.ui.settings.SettingsPage;

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

/**
 * Settings > Sessions: the session handling rules, which tools feed the
 * cookie jar, and the macros the rules can run. Requests join a macro through
 * the right-click "send to session macro" of any other tool.
 */
public class SessionPanel extends SettingsPage {

    static final String[] TOOLS = {"proxy", "repeater", "intruder", "sequencer", "scanner"};

    private final SuiteContext ctx;
    private final SessionManager sm;

    private final RuleModel ruleModel = new RuleModel();
    private final MacroModel macroModel = new MacroModel();
    private final ItemModel itemModel = new ItemModel();
    private final ExtractionModel extractionModel = new ExtractionModel();
    private final CookieModel cookieModel = new CookieModel();

    /** The macro open in the macro editor, if one is. */
    private Macro editing;
    private JTable itemTable;
    private MessageEditor itemPreview;
    private JLabel runStatus;
    private JFrame tracer;

    public SessionPanel(SuiteContext ctx) {
        this.ctx = ctx;
        this.sm = ctx.sessions();
        Settings s = ctx.settings();

        JButton openTracer = Ui.button("Open sessions tracer");
        openTracer.addActionListener(e -> openTracer());
        block("Session handling rules", Kind.PROJECT,
                "You can define session handling rules to make Open Suite perform specific actions when making HTTP requests. "
              + "Each rule has a defined scope (for particular tools, URLs or parameters), and can perform actions such as adding session cookies, "
              + "logging in to the application, or checking session validity. Before each request is issued, the rules that are in scope for it "
              + "are applied in sequence. Use these settings to manage your active session handling rules.",
                () -> { sm.rules().clear(); sm.rules().add(SessionManager.defaultRule()); ruleModel.fireTableDataChanged(); },
                underDescription(), buildRules(), Sections.gap(15),
                Sections.text("Use the sessions tracer to monitor or troubleshoot the behavior of your session handling rules."),
                Sections.gap(5), openTracer);

        JCheckBox[] feeds = new JCheckBox[SessionManager.JAR_TOOLS.length];
        JPanel grid = new JPanel(new GridBagLayout());
        grid.setOpaque(false);
        // Proxy, Repeater, Sequencer down the first column; Scanner, Intruder, Extensions down the second.
        int[] order = { 0, 2, 4, 1, 3, 5 };
        for (int n = 0; n < order.length; n++) {
            String tool = SessionManager.JAR_TOOLS[order[n]];
            feeds[n] = check(s, SessionManager.jarKey(tool), "proxy".equals(tool), label(tool));
            GridBagConstraints gc = new GridBagConstraints();
            gc.gridx = n / 3; gc.gridy = n % 3; gc.anchor = GridBagConstraints.WEST;
            gc.insets = new Insets(0, n / 3 == 0 ? 2 : 0, n % 3 < 2 ? 3 : 0, n / 3 == 0 ? 10 : 0);
            grid.add(feeds[n], gc);
        }
        JButton openJar = Ui.button("Open cookie jar");
        openJar.addActionListener(e -> openCookieJar());
        block("Cookie jar", Kind.PROJECT,
                "Open Suite maintains a cookie jar that stores all of the cookies issued by visited web sites. Session handling rules can use and "
              + "update these cookies to maintain valid sessions with applications that are being tested. You can use the settings below to "
              + "control how the cookie jar is updated automatically, based on traffic from particular tools.",
                () -> { for (int n = 0; n < feeds.length; n++) {
                            s.remove(SessionManager.jarKey(SessionManager.JAR_TOOLS[order[n]]));
                            feeds[n].setSelected(order[n] == 0);
                        } },
                Sections.text("Use these settings to control which tools can update the cookie jar."),
                Sections.gap(4), grid, Sections.gap(4), openJar);

        block("Macros", Kind.PROJECT,
                "A macro is a sequence of one or more requests. You can use macros within session handling rules to perform tasks such as "
              + "logging in to the application, obtaining anti-CSRF tokens, etc. Use these settings to manage your macros.",
                () -> { sm.macros().clear(); macroModel.fireTableDataChanged(); },
                underDescription(), buildMacros());

        // Refresh when traffic is recorded into a macro via "send to session macro".
        sm.addChangeListener(() -> SwingUtilities.invokeLater(this::refreshAll));
    }

    /** Re-read the manager's state into every table and list. */
    public void refreshAll() {
        macroModel.fireTableDataChanged();
        itemModel.fireTableDataChanged();
        extractionModel.fireTableDataChanged();
        cookieModel.refresh();
        ruleModel.fireTableDataChanged();
    }

    private Window window() { return SwingUtilities.getWindowAncestor(this); }

    static String label(String tool) { return Character.toUpperCase(tool.charAt(0)) + tool.substring(1); }

    /** The six buttons that stand beside a rule or macro table, 95px wide. */
    private static JPanel sixButtons(JButton... buttons) {
        for (JButton b : buttons) Ui.sized(b, 95);
        return Ui.buttonColumn(buttons);
    }

    private static <T> void move(List<T> list, JTable table, AbstractTableModel model, int dir) {
        int i = table.getSelectedRow(), j = i + dir;
        if (i < 0 || j < 0 || j >= list.size()) return;
        T moved = list.get(i);
        list.set(i, list.get(j));
        list.set(j, moved);
        model.fireTableDataChanged();
        table.setRowSelectionInterval(j, j);
    }

    // ---------------- rules ----------------

    /** The tables stand 16px under the description at the smallest font and, as measured, 10px at the usual 13px. */
    private static Component underDescription() {
        int g = Ui.fontGrowth();
        return g == 0 ? Sections.gap(1) : Sections.lift(3 * g - 1);
    }

    private JComponent buildRules() {
        JTable table = new JTable(ruleModel);
        Ui.styleTable(table);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        Ui.exactWidths(table, 60, 239, 239);

        JButton add = Ui.button("Add", "Create a session handling rule");
        JButton edit = Ui.button("Edit", "Edit the selected rule");
        JButton remove = Ui.button("Remove", "Remove the selected rule");
        JButton duplicate = Ui.button("Duplicate", "Add a copy of the selected rule");
        JButton up = Ui.button("Up", "Apply the selected rule earlier");
        JButton down = Ui.button("Down", "Apply the selected rule later");
        add.addActionListener(e -> { SessionRule r = new SessionRule(); if (editRule(r)) { sm.rules().add(r); ruleModel.fireTableDataChanged(); } });
        Runnable editSelected = () -> {
            int i = table.getSelectedRow();
            if (i >= 0 && editRule(sm.rules().get(i))) ruleModel.fireTableDataChanged();
        };
        edit.addActionListener(e -> editSelected.run());
        table.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override public void mouseClicked(java.awt.event.MouseEvent e) {
                if (e.getClickCount() == 2 && table.columnAtPoint(e.getPoint()) > 0) editSelected.run();
            }
        });
        remove.addActionListener(e -> {
            int i = table.getSelectedRow();
            if (i >= 0) { sm.rules().remove(i); ruleModel.fireTableDataChanged(); }
        });
        duplicate.addActionListener(e -> {
            int i = table.getSelectedRow();
            if (i < 0) return;
            SessionRule from = sm.rules().get(i), copy = new SessionRule();
            copy.name = from.name; copy.enabled = from.enabled; copy.hostPattern = from.hostPattern;
            copy.tools.addAll(from.tools); copy.useCookieJar = from.useCookieJar; copy.macroName = from.macroName;
            copy.trigger = from.trigger; copy.triggerValue = from.triggerValue;
            sm.rules().add(i + 1, copy);
            ruleModel.fireTableDataChanged();
        });
        up.addActionListener(e -> move(sm.rules(), table, ruleModel, -1));
        down.addActionListener(e -> move(sm.rules(), table, ruleModel, 1));
        return Sections.besideTable(sixButtons(add, edit, remove, duplicate, up, down),
                Sections.withArrow(Ui.scroll(table), 540, Ui.buttonBlock(6).height));   // as tall as its six buttons
    }

    private boolean editRule(SessionRule r) {
        JTextField name = Ui.field(r.name);
        JTextField host = Ui.field(r.hostPattern);
        JCheckBox jar = Ui.check("Add cookies from the cookie jar to matching requests", r.useCookieJar);
        JComboBox<String> macro = Ui.combo(macroNames());
        macro.setSelectedItem(r.macroName);
        JComboBox<SessionRule.Trigger> trig = Ui.combo(SessionRule.Trigger.values());
        trig.setSelectedItem(r.trigger);
        JTextField trigVal = Ui.field(r.triggerValue);

        JPanel tools = new JPanel(new FlowLayout(FlowLayout.LEFT, 6, 0));
        tools.setOpaque(false);
        JCheckBox[] toolBoxes = new JCheckBox[TOOLS.length];
        for (int i = 0; i < TOOLS.length; i++) {
            toolBoxes[i] = Ui.check(label(TOOLS[i]), r.tools.isEmpty() || r.tools.contains(TOOLS[i]));
            tools.add(toolBoxes[i]);
        }

        JPanel form = Ui.form(
                "Rule description", name,
                "Host (blank = all, *.example.com allowed)", host,
                "Tools", tools,
                "Cookies", jar,
                "Macro to run", macro,
                "Run macro when", trig,
                "Status codes, or response text", trigVal);

        int ok = JOptionPane.showConfirmDialog(window(), form, "Session handling rule editor",
                JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
        if (ok != JOptionPane.OK_OPTION) return false;

        r.name = name.getText().trim().isEmpty() ? "rule" : name.getText().trim();
        r.hostPattern = host.getText().trim();
        r.useCookieJar = jar.isSelected();
        r.macroName = macro.getSelectedItem() == null ? "" : macro.getSelectedItem().toString();
        r.trigger = (SessionRule.Trigger) trig.getSelectedItem();
        r.triggerValue = trigVal.getText().trim();
        r.tools.clear();
        boolean all = true;
        for (JCheckBox b : toolBoxes) if (!b.isSelected()) all = false;
        if (!all) for (int i = 0; i < TOOLS.length; i++) if (toolBoxes[i].isSelected()) r.tools.add(TOOLS[i]);
        return true;
    }

    // ---------------- sessions tracer ----------------

    /** A window listing what the session handling does to each request, while it is open. */
    private void openTracer() {
        if (tracer != null) { tracer.setVisible(true); tracer.toFront(); return; }
        final List<SessionManager.Trace>[] rows = new List[] { sm.trace() };
        java.text.SimpleDateFormat clock = new java.text.SimpleDateFormat("HH:mm:ss");
        AbstractTableModel model = new AbstractTableModel() {
            private final String[] cols = { "Time", "Tool", "URL", "Rule", "Action" };
            @Override public int getRowCount() { return rows[0].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) {
                SessionManager.Trace t = rows[0].get(r);
                return switch (c) {
                    case 0 -> clock.format(new java.util.Date(t.time()));
                    case 1 -> t.tool().isEmpty() ? "" : label(t.tool());
                    case 2 -> t.url();
                    case 3 -> t.rule();
                    default -> t.action();
                };
            }
        };
        JTable table = new JTable(model);
        Ui.styleTable(table);
        Ui.distributeWidths(table, 70, 80, 280, 180, 360);
        JTextArea detail = Ui.note("");
        detail.setBorder(Ui.pad(8, 10, 8, 10));
        table.getSelectionModel().addListSelectionListener(e -> {
            int i = table.getSelectedRow();
            detail.setText(i < 0 || i >= rows[0].size() ? "" : rows[0].get(i).action());
        });
        // Many requests can arrive at once; the table is reloaded once for all of them.
        boolean[] pending = new boolean[1];
        Runnable changed = () -> {
            synchronized (pending) { if (pending[0]) return; pending[0] = true; }
            SwingUtilities.invokeLater(() -> {
                synchronized (pending) { pending[0] = false; }
                rows[0] = sm.trace();
                model.fireTableDataChanged();
            });
        };
        JButton clear = Ui.button("Clear");
        clear.addActionListener(e -> sm.clearTrace());
        JPanel bar = new JPanel(new BorderLayout());
        bar.setBorder(Ui.pad(8, 10, 8, 10));
        bar.add(Ui.note("Lists each request processed by a session handling rule while this window is open."), BorderLayout.CENTER);
        bar.add(clear, BorderLayout.EAST);

        JFrame f = new JFrame("Sessions tracer");
        f.setIconImages(ctx.frame().getIconImages());
        JPanel root = new JPanel(new BorderLayout());
        root.add(bar, BorderLayout.NORTH);
        root.add(Ui.scroll(table), BorderLayout.CENTER);
        root.add(detail, BorderLayout.SOUTH);
        f.setContentPane(root);
        f.setSize(900, 480);
        f.setLocationRelativeTo(window());
        f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        f.addWindowListener(new java.awt.event.WindowAdapter() {
            @Override public void windowClosed(java.awt.event.WindowEvent e) {
                sm.setTracing(false);
                sm.removeTraceListener(changed);
                tracer = null;
            }
        });
        sm.addTraceListener(changed);
        sm.setTracing(true);
        tracer = f;
        f.setVisible(true);
    }

    // ---------------- macros ----------------

    private JComponent buildMacros() {
        JTable table = new JTable(macroModel);
        Ui.styleTable(table);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        // The reference lists macros by description alone, in a box without a header.
        table.removeColumn(table.getColumnModel().getColumn(2));
        table.removeColumn(table.getColumnModel().getColumn(1));
        table.setTableHeader(null);

        JButton add = Ui.button("Add", "create a macro");
        JButton edit = Ui.button("Edit", "Edit the selected macro");
        JButton remove = Ui.button("Remove", "Remove the selected macro");
        JButton duplicate = Ui.button("Duplicate", "Add a copy of the selected macro");
        JButton up = Ui.button("Up");
        JButton down = Ui.button("Down");
        add.addActionListener(e -> {
            Macro m = new Macro(freeName("Macro " + (sm.macros().size() + 1)));
            sm.macros().add(m);
            macroModel.fireTableDataChanged();
            editMacro(m);
        });
        Runnable editSelected = () -> {
            int i = table.getSelectedRow();
            if (i >= 0) editMacro(sm.macros().get(i));
        };
        edit.addActionListener(e -> editSelected.run());
        table.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override public void mouseClicked(java.awt.event.MouseEvent e) { if (e.getClickCount() == 2) editSelected.run(); }
        });
        remove.addActionListener(e -> {
            int i = table.getSelectedRow();
            if (i >= 0) { sm.macros().remove(i); macroModel.fireTableDataChanged(); }
        });
        duplicate.addActionListener(e -> {
            int i = table.getSelectedRow();
            if (i < 0) return;
            Macro from = sm.macros().get(i), copy = new Macro(freeName(from.name + " copy"));
            for (Macro.Item it : from.items) copy.items.add(new Macro.Item(it.service(), it.request()));
            for (Extraction ex : from.extractions) copy.extractions.add(new Extraction(ex.name, ex.from, ex.pattern));
            sm.macros().add(i + 1, copy);
            macroModel.fireTableDataChanged();
        });
        up.addActionListener(e -> move(sm.macros(), table, macroModel, -1));
        down.addActionListener(e -> move(sm.macros(), table, macroModel, 1));
        return Sections.besideTable(sixButtons(add, edit, remove, duplicate, up, down),
                Sections.withArrow(Ui.scroll(table), 360, Ui.buttonBlock(6).height));   // as tall as its six buttons
    }

    /** Rules name their macro, so two macros may not share a name. */
    private String freeName(String wanted) {
        String name = wanted;
        for (int n = 2; sm.macro(name) != null; n++) name = wanted + " " + n;
        return name;
    }

    /** The macro editor: the macro's name, its requests in order, and the values taken from its responses. */
    private void editMacro(Macro m) {
        editing = m;
        JDialog d = new JDialog(window(), "Macro editor", Dialog.ModalityType.APPLICATION_MODAL);
        JTextField name = Ui.field(m.name);
        JPanel top = new JPanel(new BorderLayout(8, 0));
        top.setBorder(Ui.pad(10, 10, 6, 10));
        top.add(Ui.label("Macro description:"), BorderLayout.WEST);
        top.add(name, BorderLayout.CENTER);

        itemTable = new JTable(itemModel);
        Ui.styleTable(itemTable);
        itemTable.getSelectionModel().addListSelectionListener(e -> showSelectedItem());
        itemPreview = new MessageEditor(ctx, MessageEditor.REQUEST, false);

        JButton up = Ui.button("Up"); JButton down = Ui.button("Down"); JButton rm = Ui.button("Remove");
        up.addActionListener(e -> moveItem(-1));
        down.addActionListener(e -> moveItem(1));
        rm.addActionListener(e -> {
            int i = itemTable.getSelectedRow();
            if (i >= 0 && i < m.items.size()) { m.items.remove(i); itemModel.fireTableDataChanged(); }
        });
        JButton run = Ui.primaryButton("Test macro", "Replay this macro and capture cookies");
        runStatus = Ui.label("");
        run.addActionListener(e -> runSelectedMacro());

        JPanel itemBar = new JPanel(new FlowLayout(FlowLayout.LEFT, 4, 4));
        itemBar.add(up); itemBar.add(down); itemBar.add(rm);
        itemBar.add(run); itemBar.add(runStatus);

        JPanel itemsPanel = new JPanel(new BorderLayout());
        itemsPanel.add(Ui.bold(" Macro items (add requests with \u201csend to session macro\u201d; they are appended to the last macro in the list)"), BorderLayout.NORTH);
        JSplitPane itemSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, Ui.scroll(itemTable), itemPreview);
        itemSplit.setDividerSize(1);
        Ui.balance(itemSplit, 0.4);
        itemsPanel.add(itemSplit, BorderLayout.CENTER);
        itemsPanel.add(itemBar, BorderLayout.SOUTH);

        JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, itemsPanel, buildExtractions());
        split.setDividerSize(1);
        Ui.balance(split, 0.65);

        JButton ok = Ui.primaryButton("OK", "");
        ok.addActionListener(e -> d.dispose());
        JPanel foot = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 8));
        foot.add(ok);

        JPanel root = new JPanel(new BorderLayout());
        root.add(top, BorderLayout.NORTH);
        root.add(split, BorderLayout.CENTER);
        root.add(foot, BorderLayout.SOUTH);
        d.setContentPane(root);
        d.setSize(860, 680);
        d.setLocationRelativeTo(window());
        refreshMacroDetail();
        d.setVisible(true);

        // Rules that named the macro follow it to its new name.
        String renamed = name.getText().trim();
        if (!renamed.isEmpty() && !renamed.equals(m.name) && sm.macro(renamed) == null) {
            for (SessionRule r : sm.rules()) if (m.name.equals(r.macroName)) r.macroName = renamed;
            m.name = renamed;
        }
        editing = null;
        refreshAll();
    }

    private JComponent buildExtractions() {
        JTable table = new JTable(extractionModel);
        Ui.styleTable(table);
        JButton add = Ui.button("Add"); JButton del = Ui.button("Remove");
        add.addActionListener(e -> {
            Macro m = editing;
            if (m == null) return;
            Extraction ex = new Extraction("token", Extraction.From.REGEX, "");
            if (editExtraction(ex)) { m.extractions.add(ex); extractionModel.fireTableDataChanged(); }
        });
        del.addActionListener(e -> {
            Macro m = editing;
            int i = table.getSelectedRow();
            if (m != null && i >= 0 && i < m.extractions.size()) { m.extractions.remove(i); extractionModel.fireTableDataChanged(); }
        });
        table.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override public void mouseClicked(java.awt.event.MouseEvent e) {
                Macro m = editing;
                int i = table.getSelectedRow();
                if (e.getClickCount() == 2 && m != null && i >= 0 && i < m.extractions.size()
                        && editExtraction(m.extractions.get(i))) extractionModel.fireTableDataChanged();
            }
        });
        JPanel buttons = new JPanel(new FlowLayout(FlowLayout.LEFT, 4, 4));
        buttons.add(add); buttons.add(del);
        JPanel bar = withNote(buttons,
                "Values extracted from the macro's responses for reuse (double-click to edit).");
        JPanel panel = new JPanel(new BorderLayout());
        panel.add(Ui.bold(" Extractions"), BorderLayout.NORTH);
        panel.add(Ui.scroll(table), BorderLayout.CENTER);
        panel.add(bar, BorderLayout.SOUTH);
        return panel;
    }

    private boolean editExtraction(Extraction ex) {
        JTextField name = Ui.field(ex.name);
        JComboBox<Extraction.From> from = Ui.combo(Extraction.From.values());
        from.setSelectedItem(ex.from);
        JTextField pattern = Ui.field(ex.pattern);
        JPanel form = Ui.form("Name", name, "Source", from, "Pattern, name or regex", pattern);
        int ok = JOptionPane.showConfirmDialog(window(), form, "Extraction",
                JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
        if (ok != JOptionPane.OK_OPTION) return false;
        ex.name = name.getText().trim();
        ex.from = (Extraction.From) from.getSelectedItem();
        ex.pattern = pattern.getText();
        return true;
    }

    private void moveItem(int dir) {
        Macro m = editing;
        int i = itemTable.getSelectedRow();
        if (m == null || i < 0) return;
        int j = i + dir;
        if (j < 0 || j >= m.items.size()) return;
        Macro.Item tmp = m.items.get(i);
        m.items.set(i, m.items.get(j));
        m.items.set(j, tmp);
        itemModel.fireTableDataChanged();
        itemTable.getSelectionModel().setSelectionInterval(j, j);
    }

    private void showSelectedItem() {
        Macro m = editing;
        int i = itemTable.getSelectedRow();
        if (itemPreview == null) return;
        if (m == null || i < 0 || i >= m.items.size()) {
            itemPreview.setMessage(new HttpService("", 0, false), new HttpMessage(new byte[0]));
            return;
        }
        Macro.Item it = m.items.get(i);
        itemPreview.setMessage(it.service(), it.request());
    }

    private void refreshMacroDetail() {
        itemModel.fireTableDataChanged();
        extractionModel.fireTableDataChanged();
        showSelectedItem();
    }

    private void runSelectedMacro() {
        Macro m = editing;
        if (m == null) return;
        runStatus.setText("Running...");
        final Macro macro = m;
        Thread t = new Thread(() -> {
            try {
                Map<String, String> vals = sm.runMacro(macro);
                SwingUtilities.invokeLater(() -> {
                    runStatus.setText(vals.isEmpty() ? "Done (no extractions)" : "Done, extracted " + vals);
                    cookieModel.refresh();
                });
            } catch (Exception e) {
                Debug.error("macro '" + macro.name + "' failed", e);
                SwingUtilities.invokeLater(() -> runStatus.setText("Failed: " + e.getMessage()));
            }
        }, "session-macro-run");
        t.setDaemon(true);
        t.start();
    }

    private String[] macroNames() {
        List<Macro> ms = sm.macros();
        String[] out = new String[ms.size() + 1];
        out[0] = "";
        for (int i = 0; i < ms.size(); i++) out[i + 1] = ms.get(i).name;
        return out;
    }

    // ---------------- cookie jar ----------------

    private void openCookieJar() {
        JDialog d = new JDialog(window(), "Cookie jar", Dialog.ModalityType.MODELESS);
        d.setContentPane(buildCookieJar());
        d.setSize(820, 480);
        d.setLocationRelativeTo(window());
        d.setVisible(true);
    }

    private JComponent buildCookieJar() {
        JTable table = new JTable(cookieModel);
        Ui.styleTable(table);
        Ui.distributeWidths(table, 160, 120, 220, 90, 60);

        JButton add = Ui.button("Add", "Add a cookie to the jar");
        JButton del = Ui.button("Remove");
        JButton clear = Ui.button("Empty cookie jar");
        JButton refresh = Ui.button("Refresh");
        add.addActionListener(e -> {
            Cookie c = new Cookie("", "", "", "/", false, 0);
            if (editCookie(c) && !c.name.isEmpty()) { sm.jar().set(c); cookieModel.refresh(); }
        });
        del.addActionListener(e -> {
            int i = table.getSelectedRow();
            List<Cookie> all = sm.jar().all();
            if (i >= 0 && i < all.size()) { sm.jar().remove(all.get(i)); cookieModel.refresh(); }
        });
        clear.addActionListener(e -> { sm.jar().clear(); cookieModel.refresh(); });
        refresh.addActionListener(e -> cookieModel.refresh());

        JPanel buttons = new JPanel(new FlowLayout(FlowLayout.LEFT, 6, 4));
        buttons.add(add); buttons.add(del); buttons.add(clear); buttons.add(refresh);
        JPanel bar = withNote(buttons,
                "Stores cookies observed by any tool and supplies them to matching requests.");

        JPanel root = new JPanel(new BorderLayout());
        root.add(bar, BorderLayout.NORTH);
        root.add(Ui.scroll(table), BorderLayout.CENTER);
        cookieModel.refresh();
        return root;
    }

    private boolean editCookie(Cookie c) {
        JTextField name = Ui.field(c.name);
        JTextField value = Ui.field(c.value);
        JTextField domain = Ui.field(c.domain);
        JTextField path = Ui.field(c.path);
        JCheckBox secure = Ui.check("HTTPS only", c.secure);
        JPanel form = Ui.form("Name", name, "Value", value, "Domain", domain, "Path", path, "Secure", secure);
        int ok = JOptionPane.showConfirmDialog(window(), form, "Cookie",
                JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
        if (ok != JOptionPane.OK_OPTION) return false;
        c.name = name.getText().trim();
        c.value = value.getText();
        c.domain = domain.getText().trim();
        c.path = path.getText().trim().isEmpty() ? "/" : path.getText().trim();
        c.secure = secure.isSelected();
        return true;
    }

    // ---------------- table models ----------------

    /**
     * A button row with its explanatory note on the line beneath, so the note
     * wraps to the width available instead of being cut off at the row's end.
     */
    private static JPanel withNote(JPanel buttons, String note) {
        JTextArea n = Ui.note(note);
        n.setBorder(Ui.pad(0, 8, 6, 8));
        JPanel bar = new JPanel(new BorderLayout());
        bar.add(buttons, BorderLayout.NORTH);
        bar.add(n, BorderLayout.SOUTH);
        return bar;
    }

    private final class RuleModel extends AbstractTableModel {
        private final String[] cols = {"Enabled", "Description", "Tools"};
        @Override public int getRowCount() { return sm == null ? 0 : sm.rules().size(); }
        @Override public int getColumnCount() { return cols.length; }
        @Override public String getColumnName(int c) { return cols[c]; }
        @Override public Class<?> getColumnClass(int c) { return c == 0 ? Boolean.class : String.class; }
        @Override public boolean isCellEditable(int r, int c) { return c == 0; }
        @Override public void setValueAt(Object v, int r, int c) {
            if (c == 0) { sm.rules().get(r).enabled = Boolean.TRUE.equals(v); fireTableRowsUpdated(r, r); }
        }
        @Override public Object getValueAt(int r, int c) {
            SessionRule rule = sm.rules().get(r);
            if (c == 0) return rule.enabled;
            if (c == 1) return rule.name;
            if (rule.tools.isEmpty()) return "All tools";
            StringBuilder sb = new StringBuilder();
            for (String t : rule.tools) sb.append(sb.length() > 0 ? ", " : "").append(label(t));
            return sb.toString();
        }
    }

    private final class MacroModel extends AbstractTableModel {
        private final String[] cols = {"Description", "Requests", "Extractions"};
        @Override public int getRowCount() { return sm == null ? 0 : sm.macros().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) {
            Macro m = sm.macros().get(r);
            return c == 0 ? m.name : c == 1 ? String.valueOf(m.items.size()) : String.valueOf(m.extractions.size());
        }
    }

    private final class ItemModel extends AbstractTableModel {
        private final String[] cols = {"#", "Method", "URL"};
        private Macro current() { return editing; }
        @Override public int getRowCount() { Macro m = current(); return m == null ? 0 : m.items.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) {
            Macro.Item it = current().items.get(r);
            HttpMessage req = it.request();
            return switch (c) {
                case 0 -> r + 1;
                case 1 -> req.method();
                default -> (it.secure ? "https://" : "http://") + it.host + req.path();
            };
        }
    }

    private final class ExtractionModel extends AbstractTableModel {
        private final String[] cols = {"Name", "Source", "Pattern"};
        private Macro current() { return editing; }
        @Override public int getRowCount() { Macro m = current(); return m == null ? 0 : m.extractions.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) {
            Extraction ex = current().extractions.get(r);
            return switch (c) { case 0 -> ex.name; case 1 -> ex.from; default -> ex.pattern; };
        }
    }

    private final class CookieModel extends AbstractTableModel {
        private final String[] cols = {"Domain", "Name", "Value", "Path", "Secure"};
        private List<Cookie> rows = java.util.List.of();
        void refresh() { rows = sm.jar().all(); 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 Class<?> getColumnClass(int c) { return c == 4 ? Boolean.class : String.class; }
        @Override public Object getValueAt(int r, int c) {
            Cookie k = rows.get(r);
            return switch (c) { case 0 -> k.domain; case 1 -> k.name; case 2 -> k.value; case 3 -> k.path; default -> k.secure; };
        }
    }
}