@ashishjain15491/tapcheck 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/LICENSE +21 -0
  3. package/README.md +190 -2
  4. package/dist/auth.d.ts +5 -0
  5. package/dist/auth.js +100 -0
  6. package/dist/browser.d.ts +143 -0
  7. package/dist/browser.js +237 -0
  8. package/dist/cli.d.ts +2 -0
  9. package/dist/cli.js +321 -0
  10. package/dist/config.d.ts +169 -0
  11. package/dist/config.js +369 -0
  12. package/dist/coverage.d.ts +17 -0
  13. package/dist/coverage.js +56 -0
  14. package/dist/flow.d.ts +193 -0
  15. package/dist/flow.js +512 -0
  16. package/dist/jev.d.ts +48 -0
  17. package/dist/jev.js +89 -0
  18. package/dist/parts.d.ts +65 -0
  19. package/dist/parts.js +157 -0
  20. package/dist/questions.d.ts +66 -0
  21. package/dist/questions.js +203 -0
  22. package/dist/report.d.ts +29 -0
  23. package/dist/report.js +59 -0
  24. package/dist/routes.d.ts +18 -0
  25. package/dist/routes.js +54 -0
  26. package/dist/stub.d.ts +51 -0
  27. package/dist/stub.js +244 -0
  28. package/dist/suites/a11y.d.ts +3 -0
  29. package/dist/suites/a11y.js +73 -0
  30. package/dist/suites/audit.d.ts +2 -0
  31. package/dist/suites/audit.js +440 -0
  32. package/dist/suites/code.d.ts +10 -0
  33. package/dist/suites/code.js +48 -0
  34. package/dist/suites/contract.d.ts +5 -0
  35. package/dist/suites/contract.js +79 -0
  36. package/dist/suites/crawl.d.ts +2 -0
  37. package/dist/suites/crawl.js +135 -0
  38. package/dist/suites/interact.d.ts +2 -0
  39. package/dist/suites/interact.js +319 -0
  40. package/dist/suites/security.d.ts +12 -0
  41. package/dist/suites/security.js +134 -0
  42. package/dist/suites/usability.d.ts +3 -0
  43. package/dist/suites/usability.js +205 -0
  44. package/dist/suites/ux.d.ts +6 -0
  45. package/dist/suites/ux.js +183 -0
  46. package/package.json +61 -5
  47. package/schema/tapcheck.schema.json +368 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,87 @@
1
+ # Changelog
2
+
3
+ ## 0.1.1 (2026-11-25)
4
+
5
+ No change to what tapcheck checks or how it runs.
6
+
7
+ - **README and logo.** A shorter README in the usual layout, with the tapcheck logo (light and dark), a report
8
+ screenshot and badges; the logo kit is in `assets/`. The Codex plugin and the Action use the brand colour.
9
+ - **GitHub Marketplace.** The Action's description fits the Marketplace's 125 characters.
10
+ - **Action.** It runs on the current `actions/setup-node` and `actions/upload-artifact` (v7).
11
+ - **Releases from GitHub.** `.github/workflows/publish.yml` publishes to npm when a release is published, through npm
12
+ trusted publishing with provenance; the release steps are in `CONTRIBUTING.md`.
13
+ - **Repository.** Dependabot updates, a security policy, issue forms, a pull request template and a code of conduct.
14
+
15
+ ## 0.1.0 (2026-11-25)
16
+
17
+ The first release: on npm as `@ashishjain15491/tapcheck` (the CLI is still `tapcheck`), and as the GitHub Action `ashishjain15491/tapcheck@v0.1.0`.
18
+
19
+ - **Core harness.** One `tapcheck.yml` describes the app: how to start, stop and reset it, its sides and how each
20
+ signs in (`none`, `manual`, `form` with optional TOTP, `command`), screens, tasks and viewports. `$NAME` values come
21
+ from the environment. One run writes `report.html`, `REPORT.md`, `findings.json` and the evidence. Parts that were
22
+ skipped or couldn't run (no Jev key, budget reached, sign-in failed, session expired) get a "part ran" finding each,
23
+ so the report says which and why.
24
+ - **Measured suites.** `crawl` (page status, load time, console errors, broken images and links, unlabelled fields),
25
+ `contract` (API status, JSON that parses, latency, response shape against a saved baseline), `security` (headers,
26
+ cookie flags, pages that need sign-in, CSRF, served secrets, third-party requests) and `a11y` (axe-core WCAG 2.2
27
+ A/AA, keyboard focus, page language).
28
+ - **Interaction and UI audit suites.** `interact` clicks every safe control on the crawled
29
+ screens and reports page errors, 5xx answers, native dialogs and controls that do nothing; checks each dialog it
30
+ opens (accessible name, focus, Escape, an error state for invalid input) and each table's sorting, search, paging
31
+ and row menu; and writes `interact.json`. `audit` is the full UI audit per screen: desktop light and dark, tablet
32
+ and phone, opened menus and dialogs, component and label-case consistency across screens, optional design-token
33
+ adherence, and Jev's look when Jev is on; it writes `audit.json`. New keys: `interact: {max, submit}`,
34
+ `audit: {max, skip}`, `design: {colors, fonts, radii, spacing}`. `interact.submit: true` changes data and is for a
35
+ throwaway database only.
36
+ - **Run-level additions.** `HEADED=1`, `SLOWMO=<ms>` and `START_DELAY=<s>` for watching a run;
37
+ `RECORD=1` for a video and a Playwright trace of every browser context, linked from the report. Flows get
38
+ `t.jev(label, questions?)` (Jev's look at the current page) and `t.mail.judge(mail, questions?)` (at an email), both
39
+ skipped cleanly with `JEV=off`. Every run writes `hits.json` per side, and `COVERAGE=1` merges all runs into
40
+ `COVERAGE.md`: each route with the part that reached it or GAP (`coverage: {file, reasons}`). `app.resetWhen` runs
41
+ `app.reset` by itself when matching files changed since the last reset. `stub.dns` answers DNS over UDP
42
+ (`TAPCHECK_DNS`), with overrides through the control API and `t.stub.dns()`.
43
+ - **Jev suites.** `ux` (visual QA, design, heuristics, a five-second test, predicted attention) and `usability` (a
44
+ simulated first-time user attempting each task, with a clickstream), with a per-run budget, a memo, and a log of
45
+ every request. Unsure answers are warnings.
46
+ - **Parts.** Every suite on every side is a part; `ONLY` and `SKIP` pick them by name or tag, `LIST=1` prints them,
47
+ `CHANGED=1` runs only the parts whose files changed since each last passed. `CHANGED=<git ref>` (the Action's
48
+ `changed: base`) is QA for a pull request: the parts whose files changed since the branch point with that ref, with
49
+ no state needed. `changes:` also keys on a part name, so each flow can depend on its own files. `parallel: <n>`
50
+ (or `PARALLEL=<n>`) runs that many of a side's flows at once; a flow with `serial: true` runs alone.
51
+ - **Your own checks.** `gates` (the project's linters and audits, as the part `code`), `routes` (route coverage and
52
+ writing routes without sign-in), `stub` (a stand-in for outside services, with a control API) and `flows` (custom
53
+ journeys with `t.step`, `t.stub`, `t.mail`).
54
+ - **Plugin.** A Claude Code and Codex plugin with three skills: `tapcheck-setup`, `tapcheck-run`, `tapcheck-fix`,
55
+ and recipes for Laravel, Django, Rails, Express and Next.js, Go and static sites.
56
+ - **Shipping.** A compiled npm package (`dist/`, Node.js 22.18 or newer) with types for flows; a JSON Schema for
57
+ `tapcheck.yml`; a Docker image on the official Playwright image; a GitHub Action that runs tapcheck, writes the
58
+ job summary and uploads the run folder; CI with a type check. A missing Chromium is now one line naming the
59
+ command that installs it, and `CHANGED=1` works where git has no author configured (containers, CI runners).
60
+ - **Fixes from the first real project.** The crawl follows the links it finds before the route list, and
61
+ only pages it actually crawled count toward `crawl.max` (a long route list used to crowd the links out). The
62
+ signed-out check follows redirects, so `/` → `/admin` → `/login` counts as refused. A CSRF token cookie
63
+ (`XSRF-TOKEN`, `csrftoken`) may be readable by script. The CSRF probe goes to the sides that sign in (every side
64
+ when none does), and a side can have its own `csrf`. Flows get `t.note(name, detail, 'warn' | 'info')` and a `timeout` (default 3600 s), so a flow that hangs fails instead
65
+ of stalling the run. A step that returns `{ warn: '…' }` is recorded as a warning, and `t.mail` has `count()` and
66
+ `all()`, with each message's `id` and `headers` (for checks such as List-Unsubscribe on every email of a send).
67
+ `t.jev()` waits for the page to settle and looks again when the page reloads under it. The crawl takes a link to a
68
+ file (a PDF download) for what it is, not a page that answered 0, and a signed-out side skips the routes the list
69
+ marks `auth`. Stopping the app stops what `app.start` left running in the background too, and `app.stop` runs only
70
+ when tapcheck started the app. The setup skill has a step for what the app needs around it: outside services,
71
+ background work, build and seed. A page load that fails (a timeout on a busy app, an aborted
72
+ navigation) is tried once more before it counts. Flows: a flow past its timeout records nothing more, `t.signal` is
73
+ aborted and `t.cleanup(fn)` callbacks run; each step prints a line as it ends; `t.ask` (Jev about text, on the
74
+ budget), `t.reach`, `t.page({ fresh: true })`, `t.dir` and a failing `t.note`; `t.goto` notices an ended session;
75
+ `VISUAL` and `EMAIL` are exported; a Jev request is capped at 120 s and retried once, and an outage is a warning;
76
+ with a dialog open `t.jev` looks at the screen only; failure screenshots are numbered so long names can't overwrite
77
+ each other. The visual "error shown" question no longer counts a notice about the data as an error.
78
+ Past its timeout a flow's pages are closed before its cleanups run, and only the cleanups' own `t.*` calls still
79
+ work (the abandoned run() stops at its next one); `t.use(page)` makes a page current again; `t.reach` takes the
80
+ answer's status and skips refused ones; Mailpit and stub calls give up after 30 s or at the timeout;
81
+ `t.mail.all({ limit })`; a form POST with `_method` is reached as that method.
82
+ `browser.args` passes extra switches to the run's Chromium (an app on localhost whose sandboxed preview frames load
83
+ its own files needs `--disable-features=LocalNetworkAccessChecks`). A side whose sign-in fails says so in the terminal, not only in the report.
84
+ Waiting for a page to settle is capped outside the page, so a page whose own timers never fire (one
85
+ sandboxed by its CSP without `allow-scripts`, such as an email preview) can't hang the run.
86
+ `t.page({ viewport: 'mobile' })` hands a flow a page at any of the config's viewports (the first one by default), so
87
+ a flow can check a journey at a phone's width and have Jev look at it.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ashishjain15491
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,191 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ashishjain15491/tapcheck/main/assets/tapcheck-primary-dark.svg">
4
+ <img alt="tapcheck" src="https://raw.githubusercontent.com/ashishjain15491/tapcheck/main/assets/tapcheck-primary.svg" width="360">
5
+ </picture>
6
+ </p>
2
7
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
8
+ <p align="center">
9
+ <a href="https://www.npmjs.com/package/@ashishjain15491/tapcheck"><img alt="npm" src="https://img.shields.io/npm/v/@ashishjain15491/tapcheck"></a>
10
+ <a href="https://github.com/ashishjain15491/tapcheck/actions/workflows/ci.yml"><img alt="ci" src="https://github.com/ashishjain15491/tapcheck/actions/workflows/ci.yml/badge.svg"></a>
11
+ <a href="https://github.com/ashishjain15491/tapcheck/blob/main/LICENSE"><img alt="license" src="https://img.shields.io/github/license/ashishjain15491/tapcheck"></a>
12
+ </p>
13
+
14
+ End-to-end and UI audit for any web app, whatever its language or stack. tapcheck drives the running app in a real
15
+ browser, measures what code can measure, and asks Jev to judge what needs a human eye. One file, `tapcheck.yml`,
16
+ describes the app; one run writes one report.
17
+
18
+ ## What it checks
19
+
20
+ | Suite | Judged by | What it reports |
21
+ |---|---|---|
22
+ | `crawl` | code | 4xx/5xx and slow pages, console errors, broken images and links, unlabelled fields |
23
+ | `contract` | code | failing or slow API calls, unparsable JSON, responses that changed shape |
24
+ | `security` | code | missing headers, weak cookie flags, pages open when signed out, CSRF, leaked secrets |
25
+ | `a11y` | code | axe-core WCAG 2.2 A/AA violations, keyboard focus, page language |
26
+ | `interact` | code | clicks every safe control: errors, controls that do nothing, broken dialogs and tables |
27
+ | `audit` | code and Jev | the UI on desktop, dark mode, tablet and phone; inconsistent components and design tokens |
28
+ | `code` | code | your own linters and checks (`gates:`) |
29
+ | `flow-<name>` | code | your own journeys (`flows:`), one finding per step |
30
+ | `ux` | Jev | visual QA, design, usability heuristics, a five-second test |
31
+ | `usability` | Jev | a simulated first-time user tries each task |
32
+
33
+ Each suite runs once per side (`public`, `customer`, `admin`: each kind of person who sees a different app). Jev answers
34
+ with probabilities and code decides: a clear answer passes or fails, an unsure one is a warning. Without a Jev key the
35
+ Jev parts are skipped and everything else runs.
36
+
37
+ ## Install
38
+
39
+ Pick one. Each runs the same CLI.
40
+
41
+ **Claude Code or Codex plugin.** Three skills set tapcheck up for your app, run it and fix what it finds. In Claude
42
+ Code:
43
+
44
+ ```
45
+ /plugin marketplace add ashishjain15491/tapcheck
46
+ /plugin install tapcheck@tapcheck
47
+ ```
48
+
49
+ In Codex:
50
+
51
+ ```bash
52
+ codex plugin marketplace add ashishjain15491/tapcheck
53
+ codex plugin add tapcheck@tapcheck
54
+ ```
55
+
56
+ Any other agent can follow the same steps from [AGENTS.md](AGENTS.md). The plugin needs Node.js 23.6 or newer; its
57
+ first run installs its own dependencies and Chromium.
58
+
59
+ **npm.** Node.js 22.18 or newer:
60
+
61
+ ```bash
62
+ npm install --save-dev tapcheck@npm:@ashishjain15491/tapcheck
63
+ npx playwright install chromium # once
64
+ ```
65
+
66
+ Or run it without installing: `npx @ashishjain15491/tapcheck@0.1.1`.
67
+
68
+ **GitHub Action** and **Docker**: see [Run it](#3-run-it) below.
69
+
70
+ ## Set up
71
+
72
+ ### 1. Write tapcheck.yml
73
+
74
+ **With the plugin**, ask your agent to *"Set up tapcheck for this app"*. The `tapcheck-setup` skill detects the
75
+ stack, writes `tapcheck.yml` (how to start the app, who signs in, the screens and tasks that matter, your linters as
76
+ gates), adds `.tapcheck/` and `.env` to `.gitignore`, and gets a first run through. It tells you which variables to
77
+ set; it never asks for a password or key in chat.
78
+
79
+ **By hand**, put `tapcheck.yml` in the project root. Only `baseUrl` is required:
80
+
81
+ ```yaml
82
+ baseUrl: http://127.0.0.1:8000
83
+ app:
84
+ start: npm start # skipped when the app already answers; stopped after the run
85
+ audience: a shop owner who is not technical
86
+ screens: # what Jev looks at; the crawl finds the rest
87
+ - { name: Home, path: /, purpose: see what the shop sells }
88
+ tasks: # what the simulated first-time user tries
89
+ - name: Find the opening hours
90
+ from: /
91
+ goal: Find when the shop is open on Saturday.
92
+ done: A page showing the opening hours is open.
93
+ notDone: It shows the home page, another page, or an error.
94
+ optimal: 1 # the fewest clicks that reach it
95
+ ```
96
+
97
+ Then add `.tapcheck/` (reports, screenshots, signed-in sessions) and `.env` to `.gitignore`. Every key is in
98
+ [CONFIG.md](skills/tapcheck-setup/references/CONFIG.md), with
99
+ [recipes per stack](skills/tapcheck-setup/references/stacks) (Laravel, Django, Rails, Express and Next.js, Go, static
100
+ sites) and a [working example](examples/static-site).
101
+
102
+ **Signed-in pages.** Give each kind of user a side with a `login`, and keep credentials out of the file: write
103
+ `$NAME` and set the variable when you run. A missing one stops the run.
104
+
105
+ ```yaml
106
+ sides:
107
+ public: {}
108
+ customer:
109
+ login:
110
+ form: { url: /login, fields: { email: $TAPCHECK_EMAIL, password: $TAPCHECK_PASSWORD } }
111
+ ```
112
+
113
+ ### 2. Add the Jev key (optional)
114
+
115
+ `ux`, `usability` and `audit`'s look at each screen ask Jev, a paid model from [TypeSafe](https://docs.typesafe.ai).
116
+ Without a key those are skipped and everything else runs. With one:
117
+
118
+ | Where you run | Put the key |
119
+ |---|---|
120
+ | your machine, the plugin or npm | `TYPESAFE_API_KEY=…` in `.env` next to `tapcheck.yml` (git-ignored), or `export TYPESAFE_API_KEY=…` |
121
+ | GitHub Actions | a repository secret `TYPESAFE_API_KEY`, passed as `env:` on the step (below) |
122
+ | Docker | `-e TYPESAFE_API_KEY` on `docker run`, with the variable set in your shell |
123
+
124
+ A run stops asking once it has spent `jev.budget` US dollars (default 1; `JEV_BUDGET=0.25` for one run), and
125
+ `JEV=off` turns Jev off. Only the key is read from `.env`; sign-in variables come from the environment.
126
+
127
+ ### 3. Run it
128
+
129
+ **Plugin:** ask *"Run tapcheck on what I changed"*, or *"Fix the tapcheck failures"* to have it fix your code and
130
+ rerun until each check passes.
131
+
132
+ **npm:** from the folder with `tapcheck.yml`:
133
+
134
+ ```bash
135
+ npx tapcheck # everything
136
+ ONLY=a11y,security npx tapcheck # some parts
137
+ CHANGED=origin/main npx tapcheck # only what this branch changed
138
+ ```
139
+
140
+ **GitHub Action:** the job has to install what `app.start` needs first. It adds the report to the job summary,
141
+ uploads the run folder and fails the step when a check fails; inputs are in [action.yml](action.yml).
142
+
143
+ ```yaml
144
+ - uses: actions/checkout@v4
145
+ with: { fetch-depth: 0 } # for changed: base
146
+ # …install your app's language, dependencies and a test database…
147
+ - uses: ashishjain15491/tapcheck@v0.1.1
148
+ with:
149
+ changed: base # optional: only what the pull request changed
150
+ env:
151
+ TYPESAFE_API_KEY: ${{ secrets.TYPESAFE_API_KEY }} # optional
152
+ TAPCHECK_EMAIL: ${{ secrets.TAPCHECK_EMAIL }} # whatever your tapcheck.yml asks for
153
+ TAPCHECK_PASSWORD: ${{ secrets.TAPCHECK_PASSWORD }}
154
+ ```
155
+
156
+ **Docker:** the image has Node.js, Chromium and tapcheck but not your app's runtime, so start the app outside it and
157
+ point `baseUrl` at `host.docker.internal` (macOS, Windows) or add `--network host` (Linux):
158
+
159
+ ```bash
160
+ git clone https://github.com/ashishjain15491/tapcheck && docker build -t tapcheck tapcheck
161
+ docker run --rm --ipc=host -e TYPESAFE_API_KEY -v "$PWD:/work" -w /work tapcheck
162
+ ```
163
+
164
+ Options are environment variables (`ONLY`, `SKIP`, `CHANGED`, `PARALLEL=4` for flows at once, `LIST=1` to list the
165
+ parts); the full list is in [CONFIG.md](skills/tapcheck-setup/references/CONFIG.md#environment-variables-for-a-run).
166
+
167
+ ## Output
168
+
169
+ <img alt="A tapcheck report: one card per suite, then each finding with its evidence" src="https://raw.githubusercontent.com/ashishjain15491/tapcheck/main/assets/report.png">
170
+
171
+ Each run writes `.tapcheck/run-<time>/` (git-ignore it): `report.html`, `REPORT.md` for a pull request,
172
+ `findings.json` for tools and agents, and the screenshots and evidence. The exit code is 0 when no check fails, 1 when
173
+ one does, and 2 when the run couldn't start.
174
+
175
+ ## Jev and your data
176
+
177
+ Jev is sent screenshots of the configured screens, tasks, menus and dialogs, with the screen names, purposes, tasks and
178
+ visible control labels. No page source, cookies, sessions or environment variables. `payloads.json` in the run folder
179
+ holds every request as sent. Run against test data, since screenshots show whatever the test user sees.
180
+
181
+ ## Safety
182
+
183
+ - The built-in suites only read, except `interact`, which clicks controls but never one labelled delete, send, pay,
184
+ sign out and the like, nor a form's submit. Run it against test data.
185
+ - Flows are your own code and may change data; leave them out with `SKIP=flow`.
186
+ - `RESET=1` (`app.reset`) and `interact.submit: true` only run when the app is local.
187
+ - Signed-in sessions are saved under `.tapcheck`; keep it out of git and shared artifacts.
188
+
189
+ ## Contributing
190
+
191
+ See [CONTRIBUTING.md](CONTRIBUTING.md) and the [changelog](CHANGELOG.md). MIT licensed.
package/dist/auth.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ import type { Config, Side } from './config.ts';
2
+ /** RFC 6238 time-based one-time code (SHA-1, 30 s, 6 digits) from a base32 secret. */
3
+ export declare function totp(secret: string, at?: number): string;
4
+ /** The side's saved session file, signing in first when needed; undefined for a side that doesn't sign in. */
5
+ export declare function signIn(cfg: Config, side: Side): Promise<string | undefined>;
package/dist/auth.js ADDED
@@ -0,0 +1,100 @@
1
+ /*
2
+ * Signing in, per side, saved as a Playwright storageState under the out folder (git-ignored) that every suite reuses:
3
+ * none no session (a public site)
4
+ * manual a visible browser on the sign-in page; a person signs in (and passes 2FA); kept until LOGIN=1 or it expires
5
+ * form fills the named fields, submits, and fills a TOTP code if the app asks for one; every run
6
+ * command any program that prints a storageState JSON (for apps whose sign-in is easier to script in their own stack)
7
+ */
8
+ import { createHmac } from 'node:crypto';
9
+ import { execSync } from 'node:child_process';
10
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
11
+ import { chromium } from 'playwright';
12
+ /** RFC 6238 time-based one-time code (SHA-1, 30 s, 6 digits) from a base32 secret. */
13
+ export function totp(secret, at = Date.now()) {
14
+ const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
15
+ let bits = '';
16
+ for (const c of secret.replace(/=+$/, '').toUpperCase().replace(/\s/g, '')) {
17
+ const i = alphabet.indexOf(c);
18
+ if (i < 0)
19
+ throw new Error('The TOTP secret is not base32.');
20
+ bits += i.toString(2).padStart(5, '0');
21
+ }
22
+ const key = Buffer.from(bits.match(/.{8}/g).map((b) => parseInt(b, 2)));
23
+ const counter = Buffer.alloc(8);
24
+ counter.writeBigUInt64BE(BigInt(Math.floor(at / 1000 / 30)));
25
+ const h = createHmac('sha1', key).update(counter).digest();
26
+ const o = h[h.length - 1] & 0xf;
27
+ return String((h.readUInt32BE(o) & 0x7fffffff) % 1_000_000).padStart(6, '0');
28
+ }
29
+ /** A field by CSS selector, else by name attribute, else by its label text. */
30
+ async function field(page, key) {
31
+ if (/^[#.[]|[\s=>]/.test(key))
32
+ return page.locator(key).first();
33
+ const byName = page.locator(`[name="${key.replace(/"/g, '\\"')}"]`);
34
+ return (await byName.count()) ? byName.first() : page.getByLabel(key, { exact: false }).first();
35
+ }
36
+ const off = (cfg, u) => !cfg.loginPaths.test(new URL(u).pathname);
37
+ /** The side's saved session file, signing in first when needed; undefined for a side that doesn't sign in. */
38
+ export async function signIn(cfg, side) {
39
+ const l = side.login;
40
+ if ('none' in l)
41
+ return undefined;
42
+ mkdirSync(cfg.out, { recursive: true });
43
+ const file = `${cfg.out}/auth-${side.name}.json`;
44
+ const at = (p) => (/^https?:\/\//.test(p) ? p : side.baseUrl + p);
45
+ if ('command' in l) {
46
+ const out = execSync(l.command, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'inherit'], shell: '/bin/sh' });
47
+ let state;
48
+ try {
49
+ state = JSON.parse(out);
50
+ }
51
+ catch {
52
+ throw new Error(`sides.${side.name}.login.command did not print JSON (a Playwright storageState).`);
53
+ }
54
+ if (!Array.isArray(state?.cookies))
55
+ throw new Error(`sides.${side.name}.login.command printed JSON without a cookies list.`);
56
+ writeFileSync(file, JSON.stringify(state));
57
+ return file;
58
+ }
59
+ if ('manual' in l) {
60
+ if (existsSync(file) && process.env.LOGIN !== '1')
61
+ return file;
62
+ const browser = await chromium.launch({ headless: false });
63
+ const ctx = await browser.newContext({ viewport: { width: 1280, height: 860 } });
64
+ const page = await ctx.newPage();
65
+ await page.goto(at(l.manual));
66
+ console.log(`Sign in as ${side.name} in the browser window. Waiting up to 10 minutes…`);
67
+ await page.waitForURL((u) => off(cfg, u.href), { timeout: 600_000 });
68
+ await page.waitForLoadState('networkidle').catch(() => { });
69
+ await ctx.storageState({ path: file });
70
+ await browser.close();
71
+ return file;
72
+ }
73
+ const f = l.form;
74
+ const browser = await chromium.launch();
75
+ try {
76
+ const ctx = await browser.newContext();
77
+ const page = await ctx.newPage();
78
+ await page.goto(at(f.url), { waitUntil: 'domcontentloaded' });
79
+ for (const [k, v] of Object.entries(f.fields))
80
+ await (await field(page, k)).fill(v);
81
+ const submit = () => page.locator(f.submit ?? 'button[type=submit], input[type=submit]').first().click();
82
+ await submit();
83
+ await page.waitForLoadState('networkidle', { timeout: 15_000 }).catch(() => { });
84
+ if (f.totp && !off(cfg, page.url())) {
85
+ await (await field(page, f.totp.field)).fill(totp(f.totp.secret));
86
+ await submit();
87
+ }
88
+ await page.waitForURL((u) => off(cfg, u.href), { timeout: 30_000 }).catch(() => { });
89
+ if (!off(cfg, page.url())) {
90
+ const shot = `${cfg.out}/login-${side.name}-failed.png`;
91
+ await page.screenshot({ path: shot }).catch(() => { });
92
+ throw new Error(`Signing in as ${side.name} left the browser on ${page.url()} (see ${shot}). Check sides.${side.name}.login.form.`);
93
+ }
94
+ await ctx.storageState({ path: file });
95
+ return file;
96
+ }
97
+ finally {
98
+ await browser.close();
99
+ }
100
+ }
@@ -0,0 +1,143 @@
1
+ import { type Browser, type BrowserContext, type BrowserContextOptions, type Page } from 'playwright';
2
+ import type { Config, Screen, Side } from './config.ts';
3
+ import type { Finding } from './report.ts';
4
+ export type Viewport = Config['viewports'][number];
5
+ export type Hit = {
6
+ url: string;
7
+ method: string;
8
+ type: string;
9
+ status: number;
10
+ contentType: string;
11
+ ms: number;
12
+ bytes: number;
13
+ page: string;
14
+ json?: 'ok' | 'invalid';
15
+ body?: string;
16
+ };
17
+ export type Visited = {
18
+ path: string;
19
+ status: number;
20
+ finalPath: string;
21
+ ms: number;
22
+ errors: string[];
23
+ links: string[];
24
+ };
25
+ /** One side's run: its config, where its evidence goes, its saved session, and what its crawl found (contract and security read it). */
26
+ export type Run = {
27
+ cfg: Config;
28
+ side: Side;
29
+ dir: string;
30
+ auth?: string;
31
+ record: (f: Omit<Finding, 'side'>) => void;
32
+ crawl: {
33
+ pages: Visited[];
34
+ hits: Hit[];
35
+ done: boolean;
36
+ };
37
+ part?: string;
38
+ step?: string;
39
+ reached?: Reach[];
40
+ prefix?: string;
41
+ };
42
+ /** One thing a part touched: "GET /orders", "dialog <name>", "table <headers>: sort". */
43
+ export type Reach = {
44
+ part: string;
45
+ step?: string;
46
+ what: string;
47
+ };
48
+ export type Recording = {
49
+ side: string;
50
+ part: string;
51
+ label: string;
52
+ videos: string[];
53
+ trace?: string;
54
+ };
55
+ /** Every recording of the run (RECORD=1), for the report. */
56
+ export declare const recordings: Recording[];
57
+ /** How the run's browser starts: HEADED=1 shows it, SLOWMO=<ms> waits that long between its actions; `args` are the config's browser.args. */
58
+ export declare const launchOptions: (env?: NodeJS.ProcessEnv, args?: string[]) => {
59
+ headless: boolean;
60
+ slowMo: number;
61
+ args?: string[] | undefined;
62
+ };
63
+ /** START_DELAY=<s>: seconds to count down before the first action (time to start a screen recording). */
64
+ export declare const startDelay: (env?: NodeJS.ProcessEnv) => number;
65
+ /** The run's one Chromium; `args` (browser.args) count on the call that starts it. */
66
+ export declare function launch(args?: string[]): Promise<Browser>;
67
+ /** Closes the browser. A recorded context a suite left open is closed first, so its video and trace are still written. */
68
+ export declare const closeBrowser: () => Promise<void>;
69
+ /** Counts down START_DELAY seconds, in the terminal and (headed) in the browser window. */
70
+ export declare function countdown(s?: number): Promise<void>;
71
+ /** Files `what` under the part (and flow step) running now, once. */
72
+ export declare function reach(r: Run, what: string, step?: string | undefined): void;
73
+ /** Answers that mean the app refused the request or has no such route: not reached. */
74
+ export declare const REFUSED: number[];
75
+ /** The method the app routes a request by: a form POST that says `_method` (Laravel, Rails, Symfony) or an override header is that method. */
76
+ export declare function routedMethod(q: {
77
+ method(): string;
78
+ url(): string;
79
+ headers(): Record<string, string>;
80
+ postData(): string | null;
81
+ }): string;
82
+ /** A screen's address: a path on the side's base URL, or a full URL as given. */
83
+ export declare const abs: (r: Run, path: string) => string;
84
+ export declare const host: (u: string) => string;
85
+ export declare const slug: (s: string) => string;
86
+ /**
87
+ * A context at this viewport: signed in with the side's session unless auth is false. Every suite and flow gets its
88
+ * contexts here, so two things hold for all of them: each answered request to the side's own host is filed for the
89
+ * coverage map, and with RECORD=1 the context records a video per page (<side dir>/videos/) and a Playwright trace
90
+ * (<side dir>/traces/), written when the context closes.
91
+ */
92
+ export declare function context(r: Run, vp: Viewport, auth?: boolean, bypassCSP?: boolean, more?: BrowserContextOptions): Promise<BrowserContext>;
93
+ /** Console errors and uncaught page errors, collected from now on. */
94
+ export declare function watch(page: Page): string[];
95
+ /**
96
+ * Network idle, then the DOM quiet for 500 ms (at most 5 s more), so late-rendering widgets are judged as people see them.
97
+ * page.evaluate has no timeout, and a page's own timers never fire when its CSP sandboxes it without allow-scripts (an
98
+ * email preview, say) or its main thread never yields, so the 6 s cap is kept here, outside the page.
99
+ */
100
+ export declare function settle(page: Page): Promise<void>;
101
+ export declare class SessionExpired extends Error {
102
+ }
103
+ /** Being sent to a sign-in page on a side that signs in means the session is gone: stop rather than audit the login page. */
104
+ export declare function guard(r: Run, requested: string, landed: string): void;
105
+ /** Opens a page of the app and waits for it to settle. A load that fails (a timeout on a busy app, a navigation
106
+ * aborted or cut short by another) is tried once more before the error counts; a download is not a page and isn't. */
107
+ export declare function open(r: Run, page: Page, path: string): Promise<import("playwright").Response | null>;
108
+ /** A screen's path: given directly, or the first link on `from` whose path matches `link`. Null when no link matches. */
109
+ export declare function resolve(r: Run, page: Page, s: Screen): Promise<string | null>;
110
+ /** The screen as up to `max` viewport-sized slices, top to bottom, saved as <run dir>/shots/<key>-<n>.png (Jev takes images 280–1568 px a side). */
111
+ export declare function slices(r: Run, page: Page, key: string, height: number, vh: number, max?: number): Promise<string[]>;
112
+ export type Control = {
113
+ tag: string;
114
+ role: string;
115
+ label: string;
116
+ x: number;
117
+ y: number;
118
+ w: number;
119
+ h: number;
120
+ href?: string;
121
+ };
122
+ /** What code measures exactly: sideways scroll, broken images, off-screen and small controls, text coverage, headings. */
123
+ export declare function facts(page: Page): Promise<{
124
+ title: string;
125
+ lang: string;
126
+ overflowX: boolean;
127
+ brokenImages: string[];
128
+ offscreen: number;
129
+ controls: {
130
+ tag: string;
131
+ role: string;
132
+ label: string;
133
+ x: number;
134
+ y: number;
135
+ w: number;
136
+ h: number;
137
+ href: string | undefined;
138
+ }[];
139
+ height: number;
140
+ textCoverage: number;
141
+ smallTargets: string[];
142
+ h1: number;
143
+ }>;