Skip to content
Merged
42 changes: 36 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,16 @@ npm install --save-dev buttonmash
npx playwright install --with-deps chromium # one-time browser install
```

Requires Node 20+.
Requires Node 20+. Playwright 1.65 no longer tests on Node 20, so prefer 22 or
newer.

buttonmash runs on Playwright 1.64.1 or newer, and uses your project's copy
when that version fits. If your project pins an older Playwright, npm gives
buttonmash a copy of its own, and a bare `npx playwright install` then
downloads browsers for your copy instead. `buttonmash doctor` reports which
Playwright buttonmash loads, and when its browser is missing, `doctor` and
`run` print the command that installs it, such as
`npx playwright@1.64.1 install --with-deps chromium`.

## Quickstart

Expand Down Expand Up @@ -140,14 +149,14 @@ jobs:
steps:
- uses: actions/checkout@v5
# start your app under test here (e.g. npm ci && npm run start &) and wait for it…
- uses: cj-vana/buttonmash@v0.3.1
- uses: cj-vana/buttonmash@v0.4.0
with:
target: http://localhost:3000
args: --seed ci --max-actions 800
```

The action runs the buttonmash release that matches its own tag (`@v0.3.1`
installs 0.3.1) and reads a committed `buttonmash.config.*` from the
The action runs the buttonmash release that matches its own tag (`@v0.4.0`
installs 0.4.0) and reads a committed `buttonmash.config.*` from the
workspace. Its inputs:

| Input | Default | What it does |
Expand Down Expand Up @@ -259,7 +268,8 @@ Salesforce LWC, Ionic, Shoelace/Lit/Material Web) and **same-origin iframes**
(embedded editors, wizards), so component-based apps aren't invisible to it.
It also skips what a user couldn't reach: the contents of a closed `<details>`,
inert subtrees, and, while a modal dialog is open, everything outside the top
modal.
modal. The same holds for an iframe: nothing inside it is offered when the
iframe is hidden, inert, or outside an open modal.

It's built to survive messy real apps on long CI sweeps: it **recovers from
renderer crashes** (recreates the page and continues, skipping the page that
Expand Down Expand Up @@ -338,6 +348,10 @@ export default defineConfig({
billing: { mode: 'refuse' }, // refuse | warn | off
// dryRun: true, // read-only: explore without submitting
// vetRedirects: true, // check a page's first redirect before following it
// blockedRequests: [ // refuse by HTTP method, path (regex), or both
// { method: 'DELETE' },
// { method: 'POST', path: '^/api/admin/' },
// ],
destructive: {
enabled: true,
extraVerbs: ['archivar'],
Expand Down Expand Up @@ -405,7 +419,10 @@ loops, React dev warnings, HMR…) and **downgrades third-party `console.error`*
errors stay high (`detectors.thirdPartyConsole: true` to opt in). State dedup is
**structural** by default, so live counters/clocks don't explode the state space
on dynamic apps. Requests buttonmash's own fence blocks (a web font under
`blockMedia`, a logout ping) are never reported as app errors, in any engine. A
`blockMedia`, a logout ping) are never reported as app errors, in any engine;
the logout ping shows up as an `info` fence finding instead (see Safety).
Neither is a request cancelled before it finished, such as a navigation a
double-click restarted or a fetch the page aborted. A
control another layer covers (a canvas, a stuck overlay) costs one timeout per
page, not one per pick. And if CI cancels or times out mid-run (SIGINT or
SIGTERM), a **partial report is still written** with exit code `2`, so you never
Expand All @@ -425,6 +442,19 @@ buttonmash is built to break things without breaking *you*:
then the fence checks each page's first redirect before it is followed
(Chromium and Firefox), at the cost of fetching every page itself, which
buffers it and drops its `Sec-Fetch-*` headers.
- **Fence writes by method.** `guardrails.blockedRequests` refuses requests by
HTTP method, path, or both, so `{ method: 'DELETE' }` stops every delete
while reads of the same path still load. `path` is a regex matched like a
`blockedPathPatterns` entry, and both parts must match when a rule has both.
A rule that refuses a GET also keeps the crawl and link clicks off its path.
Like path guards, rules never block scripts, styles, images, fonts or media.
- **Show what the fence blocked.** Each request the fence refuses, whether by a
path guard, a `blockedRequests` rule or another origin, becomes an `info`
finding in the `fence` category: one per route (one per origin for page
loads), with a count. At the default `failOn` it doesn't fail the run, but it
shows when the fence stopped something it shouldn't have. Fonts and media
dropped by `blockMedia` aren't reported, and a payment provider's pages are
left to the billing guard.
- **Skip destructive controls.** Buttons/links matching a multilingual verb
list (delete, pay, logout, cancel subscription, …), or pointing at dangerous
paths (`/logout`, `/account/delete`, `/billing/cancel`), are detected and
Expand Down
20 changes: 10 additions & 10 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "buttonmash",
"version": "0.3.1",
"version": "0.4.0",
"description": "A CI chaos monkey for web apps. It presses every button, mashes random keystrokes, tries to break your UI, and reports what it found. Safe by default.",
"keywords": [
"chaos-monkey",
Expand Down Expand Up @@ -64,7 +64,7 @@
"commander": "^12.1.0",
"jiti": "^2.4.2",
"picocolors": "^1.1.1",
"playwright": "^1.49.1",
"playwright": "^1.64.1",
"zod": "^3.24.1"
},
"devDependencies": {
Expand Down
20 changes: 16 additions & 4 deletions src/cli-program.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,12 @@ import { runDoctor } from './doctor';
import { runButtonmash } from './explorer/runner';
import { writeReports } from './report';
import { captureAuth } from './session/auth';
import type { Engine } from './session/browser';
import {
browserInstallCommand,
isMissingBrowser,
playwrightVersion,
type Engine,
} from './session/browser';
import { version } from './version';

interface RunOpts {
Expand Down Expand Up @@ -183,6 +188,8 @@ async function doRun(
opts: RunOpts,
replayed: Partial<Config> = {},
): Promise<never> {
// The config file can choose the engine too, so the hint below reads it once loaded.
let engine: Engine = opts.browser ?? 'chromium';
try {
if (opts.failOn && !(opts.failOn in SEVERITY_ORDER)) {
throw new ConfigError(`--fail-on must be one of: ${Object.keys(SEVERITY_ORDER).join(', ')}`);
Expand All @@ -194,6 +201,7 @@ async function doRun(
// config file's lists rather than replacing them.
append: { routes: opts.route, allowedOrigins: opts.allowOrigin },
});
engine = cfg.browser;
const { result, outDir } = await runButtonmash(cfg);
await writeReports(result, outDir, cfg);
printSummary(result, outDir, cfg.report.formats.includes('html'));
Expand All @@ -202,9 +210,11 @@ async function doRun(
const message = (err as Error).message ?? String(err);
if (err instanceof ConfigError || err instanceof BaselineError) {
logger.error(message);
} else if (/Executable doesn't exist|playwright install|browserType\.launch/i.test(message)) {
logger.error('The browser is not installed.');
logger.info(`Run: npx playwright install --with-deps ${opts.browser ?? 'chromium'}`);
} else if (isMissingBrowser(message)) {
logger.error(`${engine} is not installed for Playwright ${playwrightVersion}.`);
logger.info(`Run: ${browserInstallCommand(engine)}`);
} else if (/browserType\.launch/.test(message)) {
logger.error(`${engine} could not start: ${message.split('\n')[0]}`);
} else {
logger.error(`buttonmash crashed: ${(err as Error).stack ?? message}`);
}
Expand Down Expand Up @@ -423,6 +433,8 @@ export default defineConfig({
// Refuse to run if LIVE Stripe/Braintree keys are detected. Use test mode!
billing: { mode: 'refuse' },
// dryRun: true, // read-only: explore without submitting/mutating
// Refuse requests by HTTP method, path (regex), or both. Reads still load.
// blockedRequests: [{ method: 'DELETE' }, { method: 'POST', path: '^/api/admin/' }],
// Controls whose names only look destructive (regex), e.g. a canvas "Reset zoom".
// destructive: { safeNames: ['^reset zoom$'] },
},
Expand Down
22 changes: 22 additions & 0 deletions src/config/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,12 +191,34 @@ const SecretsSchema = z
})
.default({});

/** One request the fence refuses. Both parts are optional, and when both are
* given both must match: `{ method: 'DELETE' }` refuses every delete, while
* `{ method: 'POST', path: '^/api/admin/' }` refuses only admin writes. */
const BlockedRequestSchema = z
.object({
/** HTTP method, in any case. */
method: z
.string()
.regex(/^[A-Za-z]+$/, 'must be an HTTP method such as POST or DELETE')
.transform((method) => method.toUpperCase())
.optional(),
/** Regex for the path with its query, matched as blockedPathPatterns are. */
path: RegexSchema.optional(),
})
.refine((rule) => rule.method !== undefined || rule.path !== undefined, {
message: 'needs a method, a path, or both',
});

const GuardrailsSchema = z
.object({
/** Origins the monkey may navigate to. Empty → just the target's origin. */
allowedOrigins: z.array(z.string()).default([]),
/** Extra regex strings for paths to hard-block, even on allowed origins. */
blockedPathPatterns: z.array(RegexSchema).default([]),
/** Requests to refuse by HTTP method, path, or both. Unlike a blocked path,
* a rule with a method leaves the path's other methods alone, so a read
* of the same path still loads. */
blockedRequests: z.array(BlockedRequestSchema).default([]),
/** If non-empty, only crawl paths matching one of these regexes (scope a
* sweep to e.g. ^/app/). */
includePaths: z.array(RegexSchema).default([]),
Expand Down
1 change: 1 addition & 0 deletions src/core/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@ export type SignalKind =
| 'form-validation'
| 'session-lost'
| 'guardrail'
| 'fence'
| 'custom'
| 'driver';

Expand Down
5 changes: 4 additions & 1 deletion src/detectors/aggregate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,18 +67,21 @@ const KIND_META: Record<SignalKind, KindMeta> = {
label: 'Session lost (logged out mid-run)',
},
guardrail: { category: 'guardrail', defaultSeverity: 'info', label: 'Guardrail' },
fence: { category: 'fence', defaultSeverity: 'info', label: 'Blocked by the fence' },
custom: { category: 'custom', defaultSeverity: 'medium', label: 'Custom rule' },
driver: { category: 'driver-error', defaultSeverity: 'medium', label: 'Driver error' },
};

/** Network failures are resource-scoped, not page-scoped: the same broken
* asset/endpoint (its URL is in the detail) referenced from ten pages is one
* bug, not ten findings — so these kinds drop the page URL from their key. */
* bug, not ten findings, so these kinds drop the page URL from their key.
* A fence block is the same: one finding per blocked route. */
const RESOURCE_KINDS = new Set<SignalKind>([
'http.4xx',
'http.5xx',
'requestfailed',
'broken-image',
'fence',
]);

/** The part of a signal's detail that identifies the bug. An axe violation's
Expand Down
11 changes: 10 additions & 1 deletion src/detectors/signals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,16 @@ export function attachSignalListeners(deps: SignalDeps): void {
const errorText = req.failure()?.errorText ?? 'unknown';
// Ignore the navigations/resources WE aborted via the fence.
if (fenced.has(req.url())) return;
if (/ERR_ABORTED|BLOCKED_BY_CLIENT|blockedbyclient/i.test(errorText)) return;
// A request cancelled before it finished (a restarted navigation, an
// aborted fetch) did not fail: Chromium net::ERR_ABORTED, Firefox
// NS_BINDING_ABORTED, WebKit "cancelled".
if (
/ERR_ABORTED|NS_BINDING_ABORTED|^cancelled$|BLOCKED_BY_CLIENT|blockedbyclient/i.test(
errorText,
)
) {
return;
}
if (!cfg.detectors.httpErrors) return;
const line = `${req.method()} ${req.url()} — ${errorText}`;
if (ignored(line)) return;
Expand Down
28 changes: 24 additions & 4 deletions src/doctor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,21 @@ import { combineRegexes, compileRegexes } from './core/regex';
import { SignalRecorder } from './detectors/recorder';
import { inspectRequestForLiveMode, scanTextForLiveMode } from './guardrails/billing';
import { DANGEROUS_PATH_RE } from './guardrails/destructive';
import { attachPageFence, installContextFence, isAllowedOrigin } from './guardrails/fence';
import {
attachPageFence,
compileRequestRules,
installContextFence,
isAllowedOrigin,
} from './guardrails/fence';
import { redactString } from './guardrails/secrets';
import { performScriptedLogin, validateStorageState } from './session/auth';
import { createDeterministicContext, launchBrowser } from './session/browser';
import {
browserInstallCommand,
createDeterministicContext,
isMissingBrowser,
launchBrowser,
playwrightVersion,
} from './session/browser';
import { version } from './version';

export type DoctorStatus = 'pass' | 'warn' | 'fail';
Expand Down Expand Up @@ -111,9 +122,17 @@ export async function runDoctor(cfg: ResolvedConfig): Promise<DoctorResult> {
browser = await launchBrowser(cfg.browser, true, {
vetRedirects: cfg.guardrails.vetRedirects,
});
check(checks, 'browser', 'pass', `${cfg.browser} launched successfully`);
check(checks, 'browser', 'pass', `${cfg.browser} launched (Playwright ${playwrightVersion})`);
} catch (err) {
check(checks, 'browser', 'fail', `${cfg.browser} could not launch: ${(err as Error).message}`);
const message = (err as Error).message;
check(
checks,
'browser',
'fail',
isMissingBrowser(message)
? `${cfg.browser} is not installed for Playwright ${playwrightVersion}. Run: ${browserInstallCommand(cfg.browser)}`
: `${cfg.browser} could not launch: ${message}`,
);
return { ok: false, checks };
}

Expand Down Expand Up @@ -144,6 +163,7 @@ export async function runDoctor(cfg: ResolvedConfig): Promise<DoctorResult> {
const fenceOptions = {
allowedOrigins: cfg.guardrails.allowedOrigins,
blockedPathRe: combineRegexes(pathRegexes),
blockedRequests: compileRequestRules(cfg.guardrails.blockedRequests),
blockMedia: cfg.guardrails.blockMedia,
billingMode: cfg.guardrails.billing.mode,
isBillingLatched: () => billingLatched,
Expand Down
3 changes: 2 additions & 1 deletion src/explorer/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { combineRegexes, compileRegexes } from '../core/regex';
import type { Rng } from '../core/rng';
import type { ActionKind, ElementDescriptor, FormDescriptor } from '../core/types';
import { classifyControl } from '../guardrails/destructive';
import { navigationBlockedPatterns } from '../guardrails/fence';
import type { SignalRecorder } from '../detectors/recorder';
import { addCanary, type DetectorState } from '../detectors/page-checks';
import { locate } from './discover';
Expand Down Expand Up @@ -163,7 +164,7 @@ export function gatePlan(plan: Plan, cfg: ResolvedConfig, recorder: SignalRecord

// A link into a path the user blocked. The fence stops a real navigation
// there, but not a hash-router or pushState route.
const blockedPaths = combineRegexes(compileRegexes(cfg.guardrails.blockedPathPatterns));
const blockedPaths = combineRegexes(compileRegexes(navigationBlockedPatterns(cfg.guardrails)));
if (el?.href && blockedPaths && MUTATING.has(kind)) {
let dest: URL | undefined;
try {
Expand Down
Loading
Loading