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.

52.9 KB
Raw Blame
package opensuite.sequencer;

import opensuite.core.Bytes;
import opensuite.core.Debug;
import opensuite.core.HttpClient;
import opensuite.core.HttpMessage;
import opensuite.core.HttpService;
import opensuite.core.SuiteContext;
import opensuite.core.ToolModule;
import opensuite.ui.Ui;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Sequencer: collects a sample of session tokens (by manual load or by live
 * capture of a repeated request) and performs real statistical randomness
 * analysis on them -- per-character Shannon entropy and the FIPS 140-2
 * bit-level test battery -- presenting results in a separate window.
 */
public class SequencerTool implements ToolModule {

    private SuiteContext ctx;

    private int analysisCounter = 0;
    private int captureCounter = 0;

    // ---- manual load state ----
    private final List<String> manualTokens = new ArrayList<>();
    private TokenTableModel manualModel;
    private JLabel manualLoaded, manualShortest, manualLongest;

    // ---- live capture state ----
    private volatile HttpService baseService;
    private volatile HttpMessage baseRequest;
    private volatile HttpMessage baseResponse;
    private JComboBox<String> cookieCombo;
    private JComboBox<String> formCombo;
    private JRadioButton rCookie, rForm, rManual;
    private JTextField startDelim, endDelim;
    private JTextField threadsField, throttleField;
    private JButton startCaptureButton;
    private JLabel captureStatus;
    private volatile boolean capturing;
    private final List<Thread> captureThreads = new ArrayList<>();
    private final List<String> liveTokens = Collections.synchronizedList(new ArrayList<>());
    private final AtomicInteger liveRequests = new AtomicInteger();
    private final AtomicInteger liveErrors = new AtomicInteger();
    private AnalysisWindow liveWindow;

    // ---- options ----
    private JCheckBox optCount, optTransitions, optMonobit, optPoker, optRuns, optLongRun;
    private JCheckBox optChiSquare, optSerial, optCompression;

    // cached tab components
    private JComponent liveTab, manualTab, optionsTab;

    public SequencerTool() {
        optionsTab = buildOptions();
        manualTab = buildManualLoad();
        liveTab = buildLiveCapture();
    }

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

    @Override public Tab[] tabs() {
        return new Tab[] {
            new Tab("Live capture", liveTab),
            new Tab("Manual load", manualTab),
            new Tab("Sequencer settings", opensuite.ui.SettingsDialog.launcher(ctx, "Sequencer", "Sequencer settings",
                    "The randomness tests applied to captured tokens are configured under "
                    + "Settings > Sequencer.")),
        };
    }

    @Override public void init(SuiteContext ctx) {
        this.ctx = ctx;
        opensuite.ui.SettingsDialog.register("Sequencer", () -> optionsTab);
        ctx.registerSink("sequencer", (svc, req, resp, cap) ->
            SwingUtilities.invokeLater(() -> receive(svc, req, resp)));
    }

    @Override public void shutdown() {
        capturing = false;
    }

    // ---- the requests sent here, listed for live capture ----

    private record Received(HttpService svc, HttpMessage req, HttpMessage resp) {}

    private JTable requestTable;
    private RequestListModel requestModel;

    private static final class RequestListModel extends javax.swing.table.AbstractTableModel {
        private final List<Received> rows = new ArrayList<>();
        private final String[] cols = {"#", "Host", "Request"};
        void add(Received r) { rows.add(r); fireTableRowsInserted(rows.size() - 1, rows.size() - 1); }
        void remove(int i) { if (i >= 0 && i < rows.size()) { rows.remove(i); fireTableDataChanged(); } }
        void clear() { rows.clear(); fireTableDataChanged(); }
        Received at(int i) { return (i >= 0 && i < rows.size()) ? rows.get(i) : null; }
        @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 ? Integer.class : String.class; }
        @Override public Object getValueAt(int r, int c) {
            Received x = rows.get(r);
            return switch (c) {
                case 0 -> r + 1;
                case 1 -> x.svc() == null ? "" : x.svc().url();
                default -> x.req() == null ? "" : x.req().startLine();
            };
        }
    }

    /** Make the chosen request the one a live capture will replay. */
    private void selectReceived(int viewRow) {
        Received r = viewRow < 0 ? null : requestModel.at(requestTable.convertRowIndexToModel(viewRow));
        baseService = r == null ? null : r.svc();
        baseRequest = r == null ? null : r.req();
        baseResponse = r == null ? null : r.resp();
        populateCombos(baseResponse);
        startCaptureButton.setEnabled(baseRequest != null && baseService != null);
    }

    // ================================================================
    //  options tab
    // ================================================================

    private JComponent buildOptions() {
        optCount       = Ui.check("Count", true);
        optTransitions = Ui.check("Transitions", true);
        optMonobit     = Ui.check("FIPS monobit", true);
        optPoker       = Ui.check("FIPS poker", true);
        optRuns        = Ui.check("FIPS runs", true);
        optLongRun     = Ui.check("FIPS long run", true);
        optSpectral    = Ui.check("Spectral", true);
        optSerial      = Ui.check("Correlation", true);
        optCompression = Ui.check("Compression", true);
        optChiSquare   = Ui.check("Chi-square", true);
        if (threadsField == null) threadsField = Ui.shortField("5");
        if (throttleField == null) throttleField = Ui.shortField("0");

        // "Ignore tokens whose length deviates by [5] characters", on one line.
        optIgnoreLength.setBorder(null);
        JPanel ignore = line(22, optIgnoreLength, 5, deviationField, 5, opensuite.ui.Sections.caption("characters"));
        // The two fields above stand in the same column as this one.
        int column = optIgnoreLength.getPreferredSize().width;
        JLabel threadsLabel = opensuite.ui.Sections.caption("Number of threads:");
        JLabel throttleLabel = opensuite.ui.Sections.caption("Throttle between requests (milliseconds):");
        threadsLabel.setPreferredSize(new Dimension(column, Ui.tall(22)));
        throttleLabel.setPreferredSize(new Dimension(column, Ui.tall(22)));

        ButtonGroup pad = new ButtonGroup();
        pad.add(padStart);
        pad.add(padEnd);
        padStart.setBorder(null);
        padEnd.setBorder(null);
        JPanel padRow = line(16, Ui.label("Pad short tokens at:"), 5, padStart, 5, padEnd);
        JPanel padWith = line(22, Ui.label("Pad with (single character or 2-digit ASCII hex code):"), 5, padCharField);

        // The bit-level tests stand in two columns.
        JPanel bitTests = new JPanel(new GridBagLayout());
        bitTests.setOpaque(false);
        JCheckBox[][] columns = { { optMonobit, optPoker, optRuns, optLongRun }, { optSpectral, optSerial, optCompression, optChiSquare } };
        GridBagConstraints gc = new GridBagConstraints();
        gc.anchor = GridBagConstraints.LINE_START;
        for (int col = 0; col < columns.length; col++) {
            for (int row = 0; row < columns[col].length; row++) {
                JCheckBox box = columns[col][row];
                box.setBorder(Ui.pad(0, 2, 0, 0));
                box.setPreferredSize(new Dimension(box.getPreferredSize().width, Ui.tall(20)));
                gc.gridx = col;
                gc.gridy = row;
                gc.insets = new Insets(0, 0, row < columns[col].length - 1 ? 5 : 0, col == 0 ? 42 : 0);
                bitTests.add(box, gc);
            }
        }

        opensuite.ui.OptionsPage page = new opensuite.ui.OptionsPage();
        page.section("Live capture",
                Ui.note("Use these settings to control the engine used for making HTTP requests and harvesting tokens when performing the live capture."),
                line(22, threadsLabel, 5, threadsField),
                line(22, throttleLabel, 5, throttleField),
                ignore);
        page.section("Token handling",
                Ui.note("Use these settings to control how tokens are handled during analysis."),
                padRow, padWith, optBase64);
        page.section("Token analysis",
                Ui.note("Use these settings to control the types of analysis performed by Sequencer."),
                optCount, optTransitions,
                opensuite.ui.Sections.gap(5),
                opensuite.ui.Sections.text("The options below control the types of analysis that are performed at the bit level."),
                opensuite.ui.Sections.gap(5),
                bitTests);
        return page;
    }

    /** Components on one line of the given height, with gaps between them: height, component, gap, component, ... */
    private static JPanel line(int height, Object... parts) {
        JPanel p = new JPanel();
        p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
        p.setOpaque(false);
        int width = 0;
        for (Object o : parts) {
            Component c = o instanceof Integer gap ? Box.createHorizontalStrut(gap) : (Component) o;
            if (c instanceof JComponent jc) jc.setAlignmentY(Component.CENTER_ALIGNMENT);
            width += c.getPreferredSize().width;
            p.add(c);
        }
        p.setPreferredSize(new Dimension(width, Ui.tall(height)));   // rows grow with the font
        return p;
    }

    // Token handling and the extra tests, set on the Settings page.
    private JCheckBox optSpectral;
    private final JCheckBox optIgnoreLength = Ui.check("Ignore tokens whose length deviates by", true);
    private final JTextField deviationField = Ui.shortField("5");
    private final JRadioButton padStart = Ui.radio("Start", true);
    private final JRadioButton padEnd = Ui.radio("End", false);
    private final JTextField padCharField = Ui.shortField("0");
    private final JCheckBox optBase64 = Ui.check("Base64-decode before analyzing", false);

    /**
     * The sample as the analysis sees it: decoded from Base64 if asked, without
     * the tokens whose length strays too far from the commonest length, and
     * with the short ones padded out to the longest.
     */
    private List<String> prepare(List<String> raw) {
        return prepare(raw, optBase64.isSelected(), optIgnoreLength.isSelected() ? parseInt(deviationField.getText(), 5) : -1,
                padStart.isSelected(), padChar(padCharField.getText()));
    }

    /** The padding character: one character as typed, or two hex digits naming its code. */
    static char padChar(String text) {
        String t = text == null ? "" : text;
        if (t.length() == 2) {
            try { return (char) Integer.parseInt(t, 16); } catch (NumberFormatException ignored) { }
        }
        return t.isEmpty() ? '0' : t.charAt(0);
    }

    static List<String> prepare(List<String> raw, boolean base64, int deviation, boolean padAtStart, char pad) {
        List<String> out = new ArrayList<>(raw.size());
        for (String t : raw) {
            if (base64) {
                try {
                    String clean = t.strip().replace('-', '+').replace('_', '/');
                    out.add(new String(java.util.Base64.getMimeDecoder().decode(clean), java.nio.charset.StandardCharsets.ISO_8859_1));
                    continue;
                } catch (IllegalArgumentException ignored) { }
            }
            out.add(t);
        }
        if (deviation >= 0 && !out.isEmpty()) {
            Map<Integer, Integer> lengths = new java.util.HashMap<>();
            for (String t : out) lengths.merge(t.length(), 1, Integer::sum);
            int usual = 0, most = -1;
            for (Map.Entry<Integer, Integer> e : lengths.entrySet()) {
                if (e.getValue() > most || (e.getValue() == most && e.getKey() > usual)) { most = e.getValue(); usual = e.getKey(); }
            }
            final int centre = usual;
            out.removeIf(t -> Math.abs(t.length() - centre) > deviation);
        }
        int longest = 0;
        for (String t : out) longest = Math.max(longest, t.length());
        for (int k = 0; k < out.size(); k++) {
            String t = out.get(k);
            if (t.length() >= longest) continue;
            String fill = String.valueOf(pad).repeat(longest - t.length());
            out.set(k, padAtStart ? fill + t : t + fill);
        }
        return out;
    }

    /**
     * The spectral test: the discrete Fourier transform of the bit stream, as
     * plus and minus ones, should have about 95% of its peaks under the
     * threshold. Periodic patterns raise peaks above it.
     */
    static String spectral(boolean[] bits) {
        int n = Integer.highestOneBit(Math.min(bits.length, 16384));
        if (n < 64) return "Spectral test\n  (insufficient data)\n";
        double[] re = new double[n], im = new double[n];
        for (int k = 0; k < n; k++) re[k] = bits[k] ? 1 : -1;
        // In-place radix-2 transform.
        for (int a = 1, b = 0; a < n; a++) {
            int bit = n >> 1;
            for (; (b & bit) != 0; bit >>= 1) b ^= bit;
            b ^= bit;
            if (a < b) { double t = re[a]; re[a] = re[b]; re[b] = t; }
        }
        for (int len = 2; len <= n; len <<= 1) {
            double ang = -2 * Math.PI / len;
            double wr = Math.cos(ang), wi = Math.sin(ang);
            for (int a = 0; a < n; a += len) {
                double cr = 1, ci = 0;
                for (int k = 0; k < len / 2; k++) {
                    int u = a + k, v = a + k + len / 2;
                    double xr = re[v] * cr - im[v] * ci, xi = re[v] * ci + im[v] * cr;
                    re[v] = re[u] - xr; im[v] = im[u] - xi;
                    re[u] += xr; im[u] += xi;
                    double nr = cr * wr - ci * wi;
                    ci = cr * wi + ci * wr;
                    cr = nr;
                }
            }
        }
        double threshold = Math.sqrt(Math.log(1 / 0.05) * n);
        double expected = 0.95 * n / 2.0;
        int under = 0;
        for (int k = 0; k < n / 2; k++) if (Math.hypot(re[k], im[k]) < threshold) under++;
        double d = (under - expected) / Math.sqrt(n * 0.95 * 0.05 / 4.0);
        double pv = erfc(Math.abs(d) / Math.sqrt(2.0));
        return "Spectral test\n"
                + "  bits tested          : " + n + "\n"
                + "  peaks under threshold: " + under + " of " + (n / 2) + " (expected " + fmt(expected) + ")\n"
                + "  p-value              : " + fmt(pv) + "\n"
                + "  result               : " + (pv >= 0.01 ? "PASS" : "FAIL") + "\n";
    }

    // ================================================================
    //  manual load tab
    // ================================================================

    private JComponent buildManualLoad() {
        JButton analyse = Ui.primaryButton("Analyze now", "Run the statistical analysis on the loaded tokens");
        JButton paste = Ui.button("Paste", "Add tokens from the clipboard, one per line");
        JButton load  = Ui.button("Load ...", "Add tokens from a file, one per line");
        JButton clear = Ui.button("Clear", "Remove every loaded token");

        // The three counts: names in one column, values in the next.
        manualLoaded   = Ui.label("0");
        manualShortest = Ui.label("");
        manualLongest  = Ui.label("");
        JPanel counters = new JPanel(new GridBagLayout());
        counters.setOpaque(false);
        GridBagConstraints gc = new GridBagConstraints();
        gc.anchor = GridBagConstraints.LINE_START;
        String[] names = { "Tokens loaded:", "Shortest:", "Longest:" };
        JLabel[] values = { manualLoaded, manualShortest, manualLongest };
        for (int r = 0; r < 3; r++) {
            gc.gridy = r;
            gc.gridx = 0; gc.insets = new Insets(0, 0, r < 2 ? 5 : 0, 12);
            counters.add(Ui.label(names[r]), gc);
            gc.gridx = 1; gc.insets = new Insets(0, 0, r < 2 ? 5 : 0, 0);
            counters.add(values[r], gc);
        }

        manualModel = new TokenTableModel(manualTokens);
        JTable table = new JTable(manualModel);
        Ui.styleTable(table);
        table.setTableHeader(null);
        table.setFont(Ui.MONO);
        JScrollPane list = Ui.scroll(table);
        list.setPreferredSize(new Dimension(240, 100));

        JPanel head = opensuite.ui.Sections.section("Manual load",
                "This function allows you to load Sequencer with a sample of tokens that you have already obtained, "
                + "and then perform the statistical analysis on the sample.",
                analyse, opensuite.ui.Sections.gap(10), counters);
        head.setBorder(Ui.pad(8, opensuite.ui.Sections.MARGIN, 15, opensuite.ui.Sections.MARGIN));

        // The list runs to the foot of the page, with its buttons beside it.
        JLabel arrow = new JLabel(opensuite.ui.Glyphs.play(9, opensuite.ui.Theme.TAB_TEXT_ON));
        JPanel listRow = new JPanel(new BorderLayout(2, 0));
        listRow.setOpaque(false);
        listRow.add(list, BorderLayout.CENTER);
        listRow.add(arrow, BorderLayout.EAST);
        JPanel row = new JPanel(new BorderLayout(opensuite.ui.Sections.ROW_GAP, 0));
        row.setOpaque(false);
        row.add(Ui.buttonColumn(paste, load, clear), BorderLayout.WEST);
        row.add(listRow, BorderLayout.CENTER);
        JPanel rowWrap = new JPanel(new BorderLayout());
        rowWrap.setOpaque(false);
        rowWrap.setBorder(Ui.pad(0, opensuite.ui.Sections.MARGIN + opensuite.ui.Sections.GUTTER, 10, 0));
        rowWrap.add(row, BorderLayout.WEST);

        JPanel panel = new JPanel(new BorderLayout());
        panel.setBackground(opensuite.ui.Theme.BG);
        panel.add(head, BorderLayout.NORTH);
        panel.add(rowWrap, BorderLayout.CENTER);

        load.addActionListener(e -> loadFromFile());
        paste.addActionListener(e -> pasteTokens());
        clear.addActionListener(e -> { manualTokens.clear(); refreshManual(); });
        analyse.addActionListener(e -> analyseManual());

        refreshManual();
        return panel;
    }

    private void loadFromFile() {
        JFileChooser fc = new opensuite.ui.FileChooser();
        fc.setDialogTitle("load tokens");
        if (fc.showOpenDialog(ctx == null ? null : ctx.frame()) != JFileChooser.APPROVE_OPTION) return;
        List<String> loaded = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader(fc.getSelectedFile()))) {
            String line;
            while ((line = br.readLine()) != null) {
                if (!line.isEmpty()) loaded.add(line);
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(panelAnchor(), "Could not read file: " + ex.getMessage(),
                "error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        manualTokens.addAll(loaded);
        refreshManual();
    }

    private void pasteTokens() {
        try {
            Object data = Toolkit.getDefaultToolkit().getSystemClipboard()
                .getData(DataFlavor.stringFlavor);
            String text = String.valueOf(data);
            for (String line : Bytes.lines(text)) {
                if (!line.isEmpty()) manualTokens.add(line);
            }
            refreshManual();
        } catch (Exception ignored) {
        }
    }

    private void refreshManual() {
        manualModel.fireTableDataChanged();
        // The lengths are blank until there is a token to measure, as the reference.
        manualLoaded.setText(String.valueOf(manualTokens.size()));
        manualShortest.setText(manualTokens.isEmpty() ? "" : String.valueOf(shortest(manualTokens)));
        manualLongest.setText(manualTokens.isEmpty() ? "" : String.valueOf(longest(manualTokens)));
    }

    private void analyseManual() {
        if (manualTokens.size() < 100) {
            JOptionPane.showMessageDialog(panelAnchor(),
                "At least 100 tokens must be loaded", "error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        analysisCounter++;
        String id = "[manual load analysis #" + analysisCounter + "]";
        AnalysisWindow w = new AnalysisWindow("sequencer " + id, false);
        w.setTokens(new ArrayList<>(manualTokens));
        w.setVisible(true);
    }

    private Component panelAnchor() {
        return ctx == null ? null : ctx.frame();
    }

    // ================================================================
    //  live capture tab
    // ================================================================

    private JComponent buildLiveCapture() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(Ui.pad(10, 10, 10, 10));

        // --- Select live capture request ---
        requestModel = new RequestListModel();
        requestTable = new JTable(requestModel);
        Ui.styleTable(requestTable);
        Ui.distributeWidths(requestTable, 74, 75, Ui.wide(420) - 151);
        requestTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        requestTable.getSelectionModel().addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) selectReceived(requestTable.getSelectedRow());
        });
        requestTable.setToolTipText("Find a request within the application which returns a token "
            + "whose randomness you want to analyse, and send it here");
        JScrollPane reqScroll = Ui.scroll(requestTable);
        // The reference holds this list to a fixed, narrow width with the start
        // arrow beside it, rather than stretching it across the whole tab.
        JButton remove = Ui.button("Remove", "Remove the selected request");
        JButton clearReq = Ui.button("Clear", "Remove every request");
        remove.addActionListener(e -> {
            int r = requestTable.getSelectedRow();
            if (r >= 0) requestModel.remove(requestTable.convertRowIndexToModel(r));
            selectReceived(requestTable.getSelectedRow());
        });
        clearReq.addActionListener(e -> { requestModel.clear(); selectReceived(-1); });
        JComponent reqRow = opensuite.ui.Sections.besideTable(Ui.buttonColumn(remove, clearReq),
                opensuite.ui.Sections.withArrow(reqScroll, 420, 150));

        startCaptureButton = Ui.primaryButton("Start live capture", "Start sampling tokens from the selected request");
        startCaptureButton.setFont(Ui.BOLD);
        startCaptureButton.setEnabled(false);
        startCaptureButton.addActionListener(e -> toggleCapture());
        captureStatus = Ui.label(" ");
        JPanel startRow = Ui.row(startCaptureButton, captureStatus);

        // The thread and throttle fields live on the Settings page.
        if (threadsField == null) threadsField = Ui.shortField("5");
        if (throttleField == null) throttleField = Ui.shortField("0");
        panel.setBorder(null);
        panel.add(opensuite.ui.Sections.page(
            opensuite.ui.Sections.section("Select live capture request",
                "Send requests here from other tools to configure a live capture. Select the request to use, "
                + "configure the other options below, then click \"Start live capture\".",
                reqRow, opensuite.ui.Sections.gap(20), startRow),
            opensuite.ui.Sections.section("Token location within response",
                "Select the location in the response where the token appears.",
                buildTokenLocation())), BorderLayout.CENTER);
        return panel;
    }

    private JComponent buildTokenLocation() {
        rCookie = Ui.radio("Cookie:", false);
        rForm   = Ui.radio("Form field:", false);
        rManual = Ui.radio("Custom location:", true);
        ButtonGroup g = new ButtonGroup();
        g.add(rCookie); g.add(rForm); g.add(rManual);
        rCookie.setEnabled(false);
        rManual.setEnabled(false);
        rForm.setEnabled(false);

        cookieCombo = Ui.combo(new String[0]);
        formCombo   = Ui.combo(new String[0]);
        cookieCombo.setEnabled(false);
        formCombo.setEnabled(false);
        startDelim = Ui.field("");
        endDelim   = Ui.field("");
        startDelim.setToolTipText("The token starts after this expression");
        endDelim.setToolTipText("The token ends at this delimiter");
        JTextField customSummary = Ui.field("");
        customSummary.setEditable(false);
        JButton configure = Ui.button("Configure", "Define the expressions that delimit the token");
        configure.addActionListener(e -> {
            JPanel f = Ui.form("Starts after:", startDelim, "Ends at:", endDelim);
            f.setBorder(Ui.pad(10, 10, 10, 10));
            if (JOptionPane.showConfirmDialog(this.liveTab, f, "Custom token location", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE) == JOptionPane.OK_OPTION)
                customSummary.setText(startDelim.getText().isEmpty() && endDelim.getText().isEmpty() ? "" : "after \"" + startDelim.getText() + "\" until \"" + endDelim.getText() + "\"");
        });
        JPanel custom = Ui.row(customSummary, configure);

        // The two choosers are as wide as the custom-location row, so the three
        // controls share one right edge as well as one left edge.
        customSummary.setColumns(0);   // a column count would override the width set below
        for (JComponent c : new JComponent[] { cookieCombo, formCombo, customSummary })
            c.setPreferredSize(new Dimension(Ui.em(314) + 3, Ui.tall(22)));
        JPanel form = Ui.form(rCookie, Ui.natural(cookieCombo), rForm, Ui.natural(formCombo), rManual, custom);
        JPanel panel = new JPanel(new BorderLayout());
        panel.setOpaque(false);
        panel.add(form, BorderLayout.WEST);
        return panel;
    }

    /** "send to sequencer" lands here: list the request and select it. */
    private void receive(HttpService svc, HttpMessage req, HttpMessage resp) {
        requestModel.add(new Received(svc, req, resp));
        int last = requestTable.convertRowIndexToView(requestModel.getRowCount() - 1);
        requestTable.setRowSelectionInterval(last, last);
    }

    private void populateCombos(HttpMessage resp) {
        List<String> cookies = new ArrayList<>();
        List<String> forms = new ArrayList<>();
        if (resp != null) {
            for (String line : resp.headerLines()) {
                int c = line.indexOf(':');
                if (c > 0 && line.substring(0, c).trim().equalsIgnoreCase("Set-Cookie")) {
                    String nv = line.substring(c + 1).trim();
                    int semi = nv.indexOf(';');
                    if (semi >= 0) nv = nv.substring(0, semi);
                    if (!nv.isEmpty()) cookies.add(nv.trim());
                }
            }
            Matcher m = INPUT_PATTERN.matcher(resp.bodyText());
            while (m.find()) {
                String nm = m.group(1);
                String val = m.group(2) == null ? "" : m.group(2);
                forms.add(nm + "=" + val);
            }
        }
        cookieCombo.setModel(new DefaultComboBoxModel<>(cookies.toArray(new String[0])));
        formCombo.setModel(new DefaultComboBoxModel<>(forms.toArray(new String[0])));

        boolean hasCookies = !cookies.isEmpty();
        boolean hasForms = !forms.isEmpty();
        rCookie.setEnabled(hasCookies);
        cookieCombo.setEnabled(hasCookies);
        rForm.setEnabled(hasForms);
        formCombo.setEnabled(hasForms);
        // The custom location is offered once there is a request to take it from.
        if (rManual != null) rManual.setEnabled(baseRequest != null);
    }

    private static final Pattern INPUT_PATTERN = Pattern.compile(
        "<input[^>]*\\bname\\s*=\\s*[\"']?([^\"'>\\s]+)[\"']?[^>]*?(?:\\bvalue\\s*=\\s*[\"']?([^\"'>]*)[\"']?)?",
        Pattern.CASE_INSENSITIVE);

    private void toggleCapture() {
        if (capturing) {
            stopCapture();
        } else {
            startCapture();
        }
    }

    private void startCapture() {
        if (baseRequest == null || baseService == null) return;
        liveTokens.clear();
        liveRequests.set(0);
        liveErrors.set(0);
        capturing = true;
        startCaptureButton.setText("Stop live capture");

        captureCounter++;
        String id = "[live capture #" + captureCounter + ": "
            + (baseService == null ? "?" : baseService.host()) + "]";
        liveWindow = new AnalysisWindow("sequencer " + id, true);
        liveWindow.setVisible(true);

        int threads = parseInt(threadsField.getText(), 5);
        final long throttle = parseInt(throttleField.getText(), 0);

        final HttpService svc = baseService;
        final HttpMessage req = baseRequest.copy();
        final boolean useCookie = rCookie.isSelected();
        final String cookieName = useCookie ? nameOf(stringOf(cookieCombo.getSelectedItem())) : null;
        final String start = startDelim.getText();
        final String end = endDelim.getText();

        captureThreads.clear();
        for (int i = 0; i < Math.max(1, threads); i++) {
            Thread t = new Thread(() -> captureLoop(svc, req, useCookie, cookieName, start, end, throttle),
                "sequencer-capture-" + i);
            t.setDaemon(true);
            captureThreads.add(t);
            t.start();
        }
        updateCaptureStatus();
    }

    private void captureLoop(HttpService svc, HttpMessage req, boolean useCookie,
                             String cookieName, String start, String end, long throttle) {
        HttpClient client = new HttpClient();
        HttpClient.Options opt = new HttpClient.Options();
        opt.updateContentLength = false;
        opt.session = ctx.sessions();
        opt.sessionTool = "sequencer";
        while (capturing) {
            HttpClient.Result r = client.send(svc, req, opt);
            ctx.trafficLog().record("sequencer", svc, req, r.response);
            liveRequests.incrementAndGet();
            if (r.ok()) {
                String token = extractToken(r.response, useCookie, cookieName, start, end);
                if (token != null && !token.isEmpty()) {
                    liveTokens.add(token);
                    onTokenCaptured();
                }
            } else {
                liveErrors.incrementAndGet();
            }
            if (throttle > 0) {
                try { Thread.sleep(throttle); }
                catch (InterruptedException e) { Thread.currentThread().interrupt(); break; }
            }
        }
    }

    private String extractToken(HttpMessage resp, boolean useCookie,
                                String cookieName, String start, String end) {
        if (resp == null) return null;
        if (useCookie && cookieName != null && !cookieName.isEmpty()) {
            for (String line : resp.headerLines()) {
                int c = line.indexOf(':');
                if (c > 0 && line.substring(0, c).trim().equalsIgnoreCase("Set-Cookie")) {
                    String nv = line.substring(c + 1).trim();
                    int semi = nv.indexOf(';');
                    if (semi >= 0) nv = nv.substring(0, semi);
                    int eq = nv.indexOf('=');
                    if (eq > 0 && nv.substring(0, eq).trim().equals(cookieName)) {
                        return nv.substring(eq + 1).trim();
                    }
                }
            }
            return null;
        }
        // delimiter-based extraction
        String text = Bytes.str(resp.raw());
        int from = 0;
        if (start != null && !start.isEmpty()) {
            int s = text.indexOf(start);
            if (s < 0) return null;
            from = s + start.length();
        }
        int to;
        if (end != null && !end.isEmpty()) {
            to = text.indexOf(end, from);
            if (to < 0) return null;
        } else {
            to = text.length();
        }
        if (to <= from) return null;
        return text.substring(from, to);
    }

    private void onTokenCaptured() {
        final int count = liveTokens.size();
        SwingUtilities.invokeLater(() -> {
            updateCaptureStatus();
            if (liveWindow != null && (count % 20 == 0 || count < 20)) {
                liveWindow.setTokens(new ArrayList<>(liveTokens));
            }
        });
    }

    private void stopCapture() {
        capturing = false;
        startCaptureButton.setText("Start live capture");
        for (Thread t : captureThreads) t.interrupt();
        captureThreads.clear();
        if (liveWindow != null) liveWindow.setTokens(new ArrayList<>(liveTokens));
        updateCaptureStatus();
    }

    private void updateCaptureStatus() {
        captureStatus.setText("live capture (" + liveTokens.size() + " tokens)   requests: "
            + liveRequests.get() + "   errors: " + liveErrors.get());
    }

    // ================================================================
    //  analysis window
    // ================================================================

    private class AnalysisWindow extends JFrame {
        private final boolean live;
        private final JTextArea summaryArea = resultArea();
        private final JTextArea charArea = resultArea();
        private final JTextArea bitArea = resultArea();
        private List<String> tokens = new ArrayList<>();

        AnalysisWindow(String title, boolean live) {
            super(title);
            this.live = live;
            setDefaultCloseOperation(DISPOSE_ON_CLOSE);
            setSize(1000, 600);
            setLocationByPlatform(true);

            JTabbedPane tabs = new JTabbedPane();
            tabs.addTab("summary", Ui.scroll(summaryArea));
            tabs.addTab("character-level analysis", Ui.scroll(charArea));
            tabs.addTab("bit-level analysis", Ui.scroll(bitArea));
            setContentPane(tabs);
        }

        void setTokens(List<String> t) {
            this.tokens = t;
            recompute();
        }

        private void recompute() {
            final List<String> snapshot = new ArrayList<>(tokens);
            new Thread(() -> {
                try {
                    List<String> sample = prepare(snapshot);
                    String summary = buildSummary(sample);
                    String chars = buildCharReport(sample);
                    String bits = buildBitReport(sample);
                    SwingUtilities.invokeLater(() -> {
                        summaryArea.setText(summary);
                        summaryArea.setCaretPosition(0);
                        charArea.setText(chars);
                        charArea.setCaretPosition(0);
                        bitArea.setText(bits);
                        bitArea.setCaretPosition(0);
                    });
                } catch (Exception e) {
                    Debug.error("token analysis failed", e);
                    SwingUtilities.invokeLater(() ->
                            summaryArea.setText("analysis failed: " + e.getMessage()));
                }
            }, "sequencer-analysis").start();
        }

        private String buildSummary(List<String> t) {
            StringBuilder sb = new StringBuilder();
            sb.append(live ? "live capture analysis\n" : "manual load analysis\n");
            sb.append("====================\n\n");
            sb.append("Sample\n");
            sb.append("  tokens analysed : ").append(t.size()).append('\n');
            sb.append("  shortest token  : ").append(shortest(t)).append('\n');
            sb.append("  longest token   : ").append(longest(t)).append("\n\n");

            double effective = effectiveEntropy(t);
            sb.append("Effective entropy\n");
            sb.append("  estimated bits of entropy : ").append(fmt(effective)).append("\n\n");

            sb.append("Overall result\n");
            sb.append("  quality grade : ").append(grade(effective)).append('\n');
            sb.append("  reliability   : ").append(reliability(t.size())).append("\n\n");

            sb.append("This grade is derived from the summed per-character-position Shannon\n");
            sb.append("entropy of the sample. See the character-level and bit-level tabs for\n");
            sb.append("the detailed statistics.\n");
            return sb.toString();
        }

        private String buildCharReport(List<String> t) {
            StringBuilder sb = new StringBuilder();
            sb.append("CHARACTER-LEVEL ANALYSIS\n========================\n\n");

            int maxLen = 0;
            for (String s : t) maxLen = Math.max(maxLen, s.length());
            double[] perPos = positionEntropies(t, maxLen);
            double total = 0;
            for (double d : perPos) total += d;

            sb.append("Effective entropy\n");
            sb.append("  summed effective entropy : ").append(fmt(total)).append(" bits\n");
            sb.append("  character positions       : ").append(maxLen).append("\n\n");

            if (optCount.isSelected()) {
                sb.append("Character count analysis - significance levels\n");
                sb.append("  per-position Shannon entropy (bits):\n");
                for (int p = 0; p < maxLen; p++) {
                    sb.append(String.format("    position %4d : %s%n", p, fmt(perPos[p])));
                }
                sb.append('\n');
            }

            if (optTransitions.isSelected()) {
                sb.append("Character transition analysis - significance levels\n");
                double[] trans = transitionEntropies(t, maxLen);
                for (int p = 0; p < trans.length; p++) {
                    sb.append(String.format("    pos %4d -> %-4d : %s bits%n", p, p + 1, fmt(trans[p])));
                }
                sb.append('\n');
            }

            sb.append("Character set\n");
            java.util.TreeSet<Character> set = new java.util.TreeSet<>();
            for (String s : t) for (int i = 0; i < s.length(); i++) set.add(s.charAt(i));
            sb.append("  distinct characters observed : ").append(set.size()).append('\n');
            double maxBits = set.size() <= 1 ? 0 : (Math.log(set.size()) / Math.log(2));
            sb.append("  maximum entropy per character : ").append(fmt(maxBits)).append(" bits\n");
            return sb.toString();
        }

        private String buildBitReport(List<String> t) {
            StringBuilder sb = new StringBuilder();
            sb.append("BIT-LEVEL ANALYSIS\n==================\n\n");

            boolean[] bits = toBits(t);
            sb.append("Bit conversion\n");
            sb.append("  usable bits of entropy : ").append(bits.length).append("\n\n");

            if (optMonobit.isSelected()) {
                sb.append(monobit(bits)).append('\n');
            }
            if (optPoker.isSelected()) {
                sb.append(poker(bits)).append('\n');
            }
            if (optRuns.isSelected()) {
                sb.append(runs(bits)).append('\n');
            }
            if (optLongRun.isSelected()) {
                sb.append(longRun(bits)).append('\n');
            }
            if (optSpectral.isSelected()) {
                sb.append(spectral(bits)).append('\n');
            }
            if (optChiSquare.isSelected()) {
                sb.append(chiSquare(bits)).append('\n');
            }
            if (optSerial.isSelected()) {
                sb.append(serialCorrelation(bits)).append('\n');
            }
            if (optCompression.isSelected()) {
                sb.append(compressionTest(t)).append('\n');
            }
            return sb.toString();
        }
    }

    // ---- additional randomness tests (chi-square, serial correlation, compression) ----

    /** Chi-square test of the 0/1 bit distribution (1 degree of freedom) with a p-value. */
    static String chiSquare(boolean[] bits) {
        int n = bits.length;
        if (n == 0) return "Chi-square (bit uniformity)\n  (no bits to test)\n";
        int ones = 0;
        for (boolean b : bits) if (b) ones++;
        double e = n / 2.0;
        double chi = Math.pow(ones - e, 2) / e + Math.pow((n - ones) - e, 2) / e;
        double p = erfc(Math.sqrt(chi / 2.0));
        return "Chi-square (bit uniformity)\n"
                + "  chi-square : " + fmt(chi) + "\n"
                + "  p-value    : " + fmt(p) + "\n"
                + "  result     : " + (p >= 0.01 ? "PASS" : "FAIL") + "\n";
    }

    /** Lag-1 serial correlation of the bit stream; near zero indicates no linear dependence. */
    static String serialCorrelation(boolean[] bits) {
        int n = bits.length;
        if (n < 2) return "Serial correlation (lag-1)\n  (insufficient data)\n";
        double sum = 0, sumSq = 0, prod = 0;
        for (int i = 0; i < n; i++) {
            double x = bits[i] ? 1 : 0;
            sum += x;
            sumSq += x * x;
            prod += x * (bits[(i + 1) % n] ? 1 : 0);
        }
        double den = n * sumSq - sum * sum;
        double scc = den == 0 ? 0 : (n * prod - sum * sum) / den;
        return "Serial correlation (lag-1)\n"
                + "  coefficient : " + fmt(scc) + "\n"
                + "  result      : " + (Math.abs(scc) < 0.10 ? "PASS" : "review") + " (near 0 is ideal)\n";
    }

    /** Compression ratio of the concatenated tokens; a ratio near or above 1.0 means high entropy. */
    static String compressionTest(List<String> tokens) {
        java.io.ByteArrayOutputStream raw = new java.io.ByteArrayOutputStream();
        for (String s : tokens) raw.writeBytes(s.getBytes(java.nio.charset.StandardCharsets.ISO_8859_1));
        byte[] data = raw.toByteArray();
        if (data.length == 0) return "Compression\n  (no data)\n";
        int clen;
        try {
            java.io.ByteArrayOutputStream gz = new java.io.ByteArrayOutputStream();
            try (java.util.zip.GZIPOutputStream g = new java.util.zip.GZIPOutputStream(gz)) { g.write(data); }
            clen = gz.size();
        } catch (Exception e) { return "Compression\n  (failed)\n"; }
        double ratio = (double) clen / data.length;
        return "Compression\n"
                + "  original : " + data.length + " bytes\n"
                + "  gzipped  : " + clen + " bytes\n"
                + "  ratio    : " + fmt(ratio) + "\n"
                + "  result   : " + (ratio >= 0.95 ? "PASS" : "review") + " (ratio near/above 1.0 = high entropy)\n";
    }

    /** Complementary error function (Abramowitz &amp; Stegun 7.1.26), for the chi-square p-value. */
    static double erfc(double x) {
        double z = Math.abs(x);
        double t = 1.0 / (1.0 + 0.5 * z);
        double r = t * Math.exp(-z * z - 1.26551223 + t * (1.00002368 + t * (0.37409196 + t * (0.09678418
                + t * (-0.18628806 + t * (0.27886807 + t * (-1.13520398 + t * (1.48851587
                + t * (-0.82215223 + t * 0.17087277)))))))));
        return x >= 0 ? r : 2.0 - r;
    }

    private static JTextArea resultArea() {
        JTextArea a = new JTextArea();
        a.setFont(Ui.MONO);
        a.setEditable(false);
        a.setText("collecting tokens...");
        return a;
    }

    // ================================================================
    //  statistics
    // ================================================================

    /** Summed per-position Shannon entropy of the character distribution. */
    private static double effectiveEntropy(List<String> tokens) {
        int maxLen = 0;
        for (String s : tokens) maxLen = Math.max(maxLen, s.length());
        double total = 0;
        for (double d : positionEntropies(tokens, maxLen)) total += d;
        return total;
    }

    private static double[] positionEntropies(List<String> tokens, int maxLen) {
        double[] out = new double[maxLen];
        for (int p = 0; p < maxLen; p++) {
            Map<Character, Integer> counts = new LinkedHashMap<>();
            int total = 0;
            for (String s : tokens) {
                if (p < s.length()) {
                    char c = s.charAt(p);
                    counts.merge(c, 1, Integer::sum);
                    total++;
                }
            }
            out[p] = shannon(counts.values(), total);
        }
        return out;
    }

    /** Entropy of the (char at p, char at p+1) joint distribution, minus H(p). */
    private static double[] transitionEntropies(List<String> tokens, int maxLen) {
        int n = Math.max(0, maxLen - 1);
        double[] out = new double[n];
        for (int p = 0; p < n; p++) {
            Map<String, Integer> counts = new LinkedHashMap<>();
            int total = 0;
            for (String s : tokens) {
                if (p + 1 < s.length()) {
                    counts.merge("" + s.charAt(p) + s.charAt(p + 1), 1, Integer::sum);
                    total++;
                }
            }
            out[p] = shannon(counts.values(), total);
        }
        return out;
    }

    private static double shannon(Iterable<Integer> counts, int total) {
        if (total <= 0) return 0;
        double h = 0;
        for (int c : counts) {
            if (c <= 0) continue;
            double pr = (double) c / total;
            h -= pr * (Math.log(pr) / Math.log(2));
        }
        return h;
    }

    private static boolean[] toBits(List<String> tokens) {
        // cap the stream at 20000 bits for FIPS-style tests, but build from all tokens
        int cap = 20000;
        List<Boolean> acc = new ArrayList<>();
        outer:
        for (String s : tokens) {
            byte[] b = Bytes.bytes(s);
            for (byte x : b) {
                for (int bit = 7; bit >= 0; bit--) {
                    acc.add(((x >> bit) & 1) == 1);
                    if (acc.size() >= cap) break outer;
                }
            }
        }
        boolean[] out = new boolean[acc.size()];
        for (int i = 0; i < out.length; i++) out[i] = acc.get(i);
        return out;
    }

    private static String monobit(boolean[] bits) {
        int n = bits.length;
        int ones = 0;
        for (boolean b : bits) if (b) ones++;
        double mean = n / 2.0;
        double sd = Math.sqrt(n) / 2.0;
        double z = sd == 0 ? 0 : (ones - mean) / sd;
        boolean pass = n > 0 && Math.abs(z) < 3.9;
        StringBuilder sb = new StringBuilder();
        sb.append("FIPS monobit test - significance levels\n");
        sb.append("  Test description\n");
        sb.append("    counts the number of 1 bits in the stream (expected ~ n/2)\n");
        sb.append("  Anomalies\n");
        sb.append("    ones = ").append(ones).append(" of ").append(n)
          .append("   z = ").append(fmt(z)).append('\n');
        sb.append("  FIPS result : ").append(pass ? "PASS" : "FAIL").append('\n');
        return sb.toString();
    }

    private static String poker(boolean[] bits) {
        int m = bits.length / 4;
        int[] freq = new int[16];
        for (int i = 0; i < m; i++) {
            int v = 0;
            for (int j = 0; j < 4; j++) v = (v << 1) | (bits[i * 4 + j] ? 1 : 0);
            freq[v]++;
        }
        double sum = 0;
        for (int f : freq) sum += (double) f * f;
        double x = m == 0 ? 0 : (16.0 / m) * sum - m;
        boolean pass = m > 0 && x > 2.16 && x < 46.17;
        StringBuilder sb = new StringBuilder();
        sb.append("FIPS poker test - significance levels\n");
        sb.append("  Test description\n");
        sb.append("    chi-square over the sixteen 4-bit patterns across ").append(m).append(" groups\n");
        sb.append("  Anomalies\n");
        sb.append("    X = ").append(fmt(x)).append("   (FIPS interval 2.16 .. 46.17)\n");
        sb.append("  FIPS result : ").append(pass ? "PASS" : "FAIL").append('\n');
        return sb.toString();
    }

    private static final int[][] RUN_INTERVALS = {
        {2315, 2685}, {1114, 1386}, {527, 723}, {240, 384}, {103, 209}, {103, 209}
    };

    private static String runs(boolean[] bits) {
        int[] runs0 = new int[7];
        int[] runs1 = new int[7];
        int i = 0;
        int n = bits.length;
        while (i < n) {
            boolean v = bits[i];
            int len = 1;
            while (i + len < n && bits[i + len] == v) len++;
            int bucket = Math.min(len, 6);
            if (v) runs1[bucket]++; else runs0[bucket]++;
            i += len;
        }
        // compare against FIPS intervals only when the stream is close to 20000 bits
        boolean checkIntervals = n >= 18000 && n <= 22000;
        boolean pass = true;
        StringBuilder sb = new StringBuilder();
        sb.append("FIPS runs test - significance levels\n");
        sb.append("  Test description\n");
        sb.append("    counts runs of consecutive identical bits, by length\n");
        sb.append("  Anomalies\n");
        sb.append(String.format("    %-8s %8s %8s%n", "length", "runs-0", "runs-1"));
        for (int len = 1; len <= 6; len++) {
            int c0 = runs0[len];
            int c1 = runs1[len];
            String flag = "";
            if (checkIntervals) {
                int[] iv = RUN_INTERVALS[len - 1];
                boolean ok = c0 >= iv[0] && c0 <= iv[1] && c1 >= iv[0] && c1 <= iv[1];
                if (!ok) { pass = false; flag = "  <-- outside " + iv[0] + ".." + iv[1]; }
            }
            String label = len == 6 ? "6+" : String.valueOf(len);
            sb.append(String.format("    %-8s %8d %8d%s%n", label, c0, c1, flag));
        }
        if (!checkIntervals) {
            sb.append("    (FIPS pass/fail intervals apply to a 20000-bit stream; "
                + "sample size ").append(n).append(")\n");
        }
        sb.append("  FIPS result : ").append(checkIntervals ? (pass ? "PASS" : "FAIL") : "n/a").append('\n');
        return sb.toString();
    }

    private static String longRun(boolean[] bits) {
        int maxRun = 0;
        int i = 0;
        int n = bits.length;
        while (i < n) {
            boolean v = bits[i];
            int len = 1;
            while (i + len < n && bits[i + len] == v) len++;
            maxRun = Math.max(maxRun, len);
            i += len;
        }
        boolean pass = maxRun < 26;
        StringBuilder sb = new StringBuilder();
        sb.append("FIPS long run test - significance levels\n");
        sb.append("  Test description\n");
        sb.append("    a long run is any run of length 26 or greater; none are permitted\n");
        sb.append("  Anomalies\n");
        sb.append("    longest run observed : ").append(maxRun).append('\n');
        sb.append("  FIPS result : ").append(pass ? "PASS" : "FAIL").append('\n');
        return sb.toString();
    }

    // ================================================================
    //  grading
    // ================================================================

    private static String grade(double bits) {
        if (bits < 1)   return "extremely poor";
        if (bits < 8)   return "very poor";
        if (bits < 20)  return "poor";
        if (bits < 40)  return "reasonable";
        if (bits < 64)  return "good";
        if (bits < 96)  return "very good";
        return "excellent";
    }

    private static String reliability(int sampleSize) {
        if (sampleSize < 100)   return "very poor";
        if (sampleSize < 300)   return "poor";
        if (sampleSize < 1000)  return "reasonable";
        if (sampleSize < 5000)  return "good";
        if (sampleSize < 20000) return "very good";
        return "FIPS-compliant";
    }

    // ================================================================
    //  helpers
    // ================================================================

    private static int shortest(List<String> t) {
        if (t.isEmpty()) return 0;
        int m = Integer.MAX_VALUE;
        for (String s : t) m = Math.min(m, s.length());
        return m;
    }

    private static int longest(List<String> t) {
        int m = 0;
        for (String s : t) m = Math.max(m, s.length());
        return m;
    }

    private static int parseInt(String s, int def) {
        try { return Integer.parseInt(s.trim()); } catch (Exception e) { return def; }
    }

    private static String fmt(double d) {
        return String.format("%.4f", d);
    }

    private static String stringOf(Object o) {
        return o == null ? "" : o.toString();
    }

    private static String nameOf(String nameValue) {
        int eq = nameValue.indexOf('=');
        return eq >= 0 ? nameValue.substring(0, eq).trim() : nameValue.trim();
    }

    // ================================================================
    //  token table model
    // ================================================================

    private static class TokenTableModel extends AbstractTableModel {
        private final List<String> data;
        TokenTableModel(List<String> data) { this.data = data; }
        @Override public int getRowCount() { return data.size(); }
        @Override public int getColumnCount() { return 1; }
        @Override public String getColumnName(int c) { return ""; }
        @Override public Object getValueAt(int r, int c) { return data.get(r); }
        @Override public boolean isCellEditable(int r, int c) { return false; }
    }
}