@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
@@ -0,0 +1,135 @@
1
+ /*
2
+ * End-to-end crawl (measured, no Jev). Breadth-first from the side's screens (or / when none are configured) through every
3
+ * in-app link they show, two levels deep and at most crawl.max pages: each page's status, load time, console and page
4
+ * errors, broken images, links that answer 4xx/5xx, form fields without a label, and every request the page made (kept for
5
+ * the contract and security suites). GET only: links matching crawl.skip (sign out, delete, export…) are never followed.
6
+ * With a `routes` command, the app's parameterless GET routes fill what the links leave of crawl.max (one this side is
7
+ * refused, or that isn't a page, is left out quietly), and "route coverage" says how many GET routes the crawl reached; the rest are listed in
8
+ * missed-routes.json.
9
+ */
10
+ import { writeFileSync } from 'node:fs';
11
+ import { abs, context, facts, guard, host, watch } from '../browser.js';
12
+ import { coverage, hasParams, routes } from '../routes.js';
13
+ const SLOW_MS = 3000;
14
+ function listen(r, page, current) {
15
+ const started = new Map();
16
+ page.on('request', (q) => started.set(q, Date.now()));
17
+ page.on('response', async (res) => {
18
+ const q = res.request();
19
+ const ct = res.headers()['content-type'] ?? '';
20
+ const hit = { url: q.url(), method: q.method(), type: q.resourceType(), status: res.status(), contentType: ct,
21
+ ms: Date.now() - (started.get(q) ?? Date.now()), bytes: 0, page: current() };
22
+ r.crawl.hits.push(hit);
23
+ if (['xhr', 'fetch'].includes(hit.type)) {
24
+ const body = await res.text().catch(() => null);
25
+ if (body === null || (body === '' && res.status() !== 204 && res.status() < 300 && !res.headers()['content-length']))
26
+ return; // unread: the page moved on first
27
+ hit.bytes = body.length;
28
+ if (/json/.test(ct) && body !== '') {
29
+ try {
30
+ JSON.parse(body);
31
+ hit.json = 'ok';
32
+ }
33
+ catch {
34
+ hit.json = 'invalid';
35
+ }
36
+ }
37
+ hit.body = body.slice(0, 400);
38
+ }
39
+ });
40
+ }
41
+ export async function run(r) {
42
+ const S = 'crawl';
43
+ const own = host(r.side.baseUrl);
44
+ const skip = r.cfg.crawl.skip;
45
+ const gets = routes(r.cfg).filter((x) => x.method === 'GET' && !skip.test(x.path)); // the same list for every side
46
+ const signedOut = 'none' in r.side.login;
47
+ const ctx = await context(r, r.cfg.viewports[0]);
48
+ const page = await ctx.newPage();
49
+ let current = '';
50
+ listen(r, page, () => current);
51
+ const errors = watch(page);
52
+ const seeds = r.side.screens.filter((s) => s.path && host(abs(r, s.path)) === own).map((s) => s.path);
53
+ const queue = (seeds.length ? seeds : ['/']).map((path) => ({ path, depth: 0, route: false }));
54
+ const seen = new Set(queue.map((q) => q.path));
55
+ // The routes fill what the links leave of crawl.max: links first, so a long route list can't crowd them out.
56
+ // A signed-out side skips the routes the list marks as needing sign-in: each would only redirect to it.
57
+ const fill = gets.filter((x) => !hasParams(x.path) && !seen.has(x.path) && !(signedOut && x.auth)).map((x) => ({ path: x.path, depth: 0, route: true }));
58
+ let visits = 0;
59
+ const linkStatus = new Map();
60
+ try {
61
+ while (visits < r.cfg.crawl.max) {
62
+ const next = queue.shift() ?? fill.shift();
63
+ if (!next)
64
+ break;
65
+ const { path, depth, route } = next;
66
+ if (route && seen.has(path))
67
+ continue; // a link reached it already
68
+ if (route)
69
+ seen.add(path);
70
+ current = path;
71
+ errors.length = 0;
72
+ const t0 = Date.now();
73
+ let download = false; // a link to a file (a PDF invoice): Playwright downloads it and goto throws
74
+ const res = await page.goto(abs(r, path), { waitUntil: 'domcontentloaded' }).catch((e) => { download = /Download is starting/.test(e.message); return null; });
75
+ if (download)
76
+ continue; // not a page; "in-app links answer" still checks that it answers
77
+ await page.waitForLoadState('networkidle', { timeout: 15_000 }).catch(() => { });
78
+ const ms = Date.now() - t0;
79
+ const finalPath = new URL(page.url()).pathname;
80
+ const st = res?.status() ?? 0;
81
+ // A route from the list that isn't this side's (refused, sent to sign in) or isn't a page (a download): not a finding.
82
+ if (route && (st === 0 || [401, 403, 404, 405].includes(st) || (r.cfg.loginPaths.test(finalPath) && !r.cfg.loginPaths.test(path))))
83
+ continue;
84
+ guard(r, path, page.url());
85
+ const f = await facts(page).catch(() => null);
86
+ const links = [...new Set((f?.controls ?? []).map((c) => c.href).filter((h) => !!h && host(h) === own)
87
+ .map((h) => { const u = new URL(h); return u.pathname + u.search; }))];
88
+ r.crawl.pages.push({ path, status: st, finalPath, ms, errors: [...errors], links });
89
+ visits++;
90
+ const where = path;
91
+ r.record({ suite: S, where, check: 'page answers', status: st >= 200 && st < 400 ? 'pass' : 'fail', detail: `${st}${finalPath !== path.split('?')[0] ? ` → ${finalPath}` : ''}` });
92
+ r.record({ suite: S, where, check: `loads under ${SLOW_MS} ms`, status: ms < SLOW_MS ? 'pass' : 'warn', detail: `${ms} ms` });
93
+ r.record({ suite: S, where, check: 'no console or page errors', status: errors.length ? 'fail' : 'pass', detail: errors.slice(0, 3).join(' | ') || undefined });
94
+ if (f?.brokenImages.length)
95
+ r.record({ suite: S, where, check: 'images load', status: 'fail', detail: f.brokenImages.slice(0, 5).join(', ') });
96
+ const unlabelled = await page.$$eval('input:not([type=hidden]):not([type=submit]):not([type=button]), select, textarea', (els) => els.filter((el) => {
97
+ const e = el;
98
+ if (e.offsetParent === null || el.closest('[aria-hidden=true]'))
99
+ return false;
100
+ return !(e.labels?.length || e.getAttribute('aria-label') || e.getAttribute('aria-labelledby') || e.title);
101
+ }).map((el) => el.name || el.id || el.tagName.toLowerCase())).catch(() => []);
102
+ r.record({ suite: S, where, check: 'form fields labelled', status: unlabelled.length ? 'fail' : 'pass', detail: unlabelled.slice(0, 6).join(', ') || undefined });
103
+ for (const l of links) {
104
+ if (skip.test(l.split('?')[0]))
105
+ continue;
106
+ if (!linkStatus.has(l)) {
107
+ const lr = await page.request.get(abs(r, l), { maxRedirects: 3, failOnStatusCode: false }).catch(() => null);
108
+ linkStatus.set(l, lr?.status() ?? 0);
109
+ }
110
+ if (depth < 2 && !seen.has(l) && !/[?&](page|sort|q|search)=/.test(l)) {
111
+ seen.add(l);
112
+ queue.push({ path: l, depth: depth + 1, route: false });
113
+ }
114
+ }
115
+ }
116
+ }
117
+ finally {
118
+ await ctx.close();
119
+ }
120
+ const broken = [...linkStatus].filter(([, s]) => s === 0 || s >= 400);
121
+ r.record({ suite: S, where: 'all crawled pages', check: 'in-app links answer', status: broken.length ? 'fail' : 'pass',
122
+ detail: broken.length ? broken.slice(0, 10).map(([l, s]) => `${s} ${l}`).join('; ') : `${linkStatus.size} links checked` });
123
+ r.record({ suite: S, where: 'all crawled pages', check: 'crawl coverage', status: 'info', detail: `${r.crawl.pages.length} pages, ${r.crawl.hits.length} requests, cap ${r.cfg.crawl.max}` });
124
+ if (gets.length) {
125
+ // Reached: every GET on this host that answered 2xx, pages and the requests they made alike.
126
+ const reached = r.crawl.hits.filter((h) => h.method === 'GET' && host(h.url) === own && h.status >= 200 && h.status < 300).map((h) => new URL(h.url).pathname);
127
+ const { total, missed } = coverage(gets, reached);
128
+ writeFileSync(`${r.dir}/missed-routes.json`, JSON.stringify(missed, null, 2));
129
+ r.record({ suite: S, where: 'routes', check: 'route coverage', status: 'info',
130
+ detail: `${total - missed.length}/${total} GET routes reached${missed.length ? `; unreached in ${r.dir}/missed-routes.json` : ''}` });
131
+ }
132
+ r.crawl.done = true;
133
+ writeFileSync(`${r.dir}/crawl.json`, JSON.stringify({ pages: r.crawl.pages, links: Object.fromEntries(linkStatus) }, null, 2));
134
+ writeFileSync(`${r.dir}/network.json`, JSON.stringify(r.crawl.hits, null, 2));
135
+ }
@@ -0,0 +1,2 @@
1
+ import { type Run } from '../browser.ts';
2
+ export declare function run(r: Run): Promise<void>;
@@ -0,0 +1,319 @@
1
+ /*
2
+ * Interaction sweep (measured, no Jev). On each screen the crawl reached (at most interact.max), on the first
3
+ * desktop-sized viewport:
4
+ * - clicks every safe visible control (buttons, tabs, disclosures, in-app links) and checks that nothing breaks: no page
5
+ * or console error, no 5xx from the app, no native alert/confirm/prompt, and that the click did something (the DOM or
6
+ * the address changed, a request went out, something opened); a control that does nothing is a warning;
7
+ * - every dialog a click opens (dialog[open], role=dialog, role=alertdialog): it has an accessible name, focus moves into
8
+ * it, Escape closes it, and one that deletes is an alertdialog. A form inside is given invalid input (required fields
9
+ * emptied, a malformed address in email fields, text past maxlength) and must show an error state: aria-invalid, a
10
+ * visible message, or the browser's own validation message;
11
+ * - every table (table, role=grid): a sortable header, a search or filter box near it, the pager's next control and the
12
+ * first row's menu must each change the rows (or open) without an error; one that changes nothing is a warning.
13
+ * interact.json records the controls, dialogs (by accessible name) and table controls that were exercised; the dialogs
14
+ * and table controls also go into the side's hits.json, for the coverage map.
15
+ *
16
+ * Safety: never clicked are controls whose label matches the usability suite's UNSAFE words (delete, send, pay, sign
17
+ * out…), links matching crawl.skip or leaving the app's host, unlabelled controls, and the submit button of a form that
18
+ * POSTs. Native confirms are dismissed. A dialog form is submitted with invalid input only when that can't save: the
19
+ * browser's validation refuses it, or the form doesn't POST. With interact.submit: true (and a local app, as for
20
+ * app.reset) such forms are submitted anyway, and valid input after it: that changes data, so a throwaway database only.
21
+ * ponytail: a button that saves on click through script alone can't be told from one that opens a menu; it is clicked.
22
+ */
23
+ import { writeFileSync } from 'node:fs';
24
+ import { isLocal } from '../config.js';
25
+ import { context, host, open, reach, SessionExpired, watch } from '../browser.js';
26
+ import { UNSAFE } from './usability.js';
27
+ const S = 'interact';
28
+ const MAX_CLICKS = 30; // per screen
29
+ const WAIT = 350; // ms for a click to show what it does
30
+ const DIALOG = 'dialog[open], [role=dialog], [role=alertdialog]';
31
+ const DESTRUCTIVE = /\b(delete|remove|destroy|discard|erase|revoke)/i;
32
+ const FIELDS = 'input:not([type=hidden]):not([type=checkbox]):not([type=radio]):not([type=file]):not([type=submit]):not([type=button]):not([readonly]):not([disabled]), textarea:not([readonly]):not([disabled])';
33
+ /** Marks each safe, visible control with data-tapcheck and returns them. Of a table's rows only the first one's controls count. */
34
+ const tag = (page, own, skip) => page.evaluate(({ own, unsafe, skip, DIALOG }) => {
35
+ const no = new RegExp(unsafe, 'i'), skipped = new RegExp(skip, 'i');
36
+ const out = [];
37
+ [...document.querySelectorAll('a[href], button, input[type=button], input[type=submit], [role=button], [role=tab], summary')].forEach((el, i) => {
38
+ el.removeAttribute('data-tapcheck');
39
+ const r = el.getBoundingClientRect(), b = el;
40
+ const label = (b.innerText || b.value || el.getAttribute('aria-label') || el.getAttribute('title') || '').replace(/\s+/g, ' ').trim().slice(0, 60);
41
+ // A form's submit button (an untyped button of a form submits too) is left alone when the form POSTs.
42
+ const submit = el.matches('button[type=submit], input[type=submit]') || (el.matches('button:not([type])') && !!b.form);
43
+ const row = el.closest('tbody tr');
44
+ if (r.width === 0 || r.height === 0 || getComputedStyle(el).visibility === 'hidden' || !label || no.test(label) || b.disabled || el.getAttribute('aria-disabled') === 'true'
45
+ || el.closest(`[aria-hidden=true], ${DIALOG}`) || (submit && (b.form?.method === 'post' || b.formMethod === 'post')) || row?.previousElementSibling)
46
+ return;
47
+ const a = el instanceof HTMLAnchorElement ? el : null;
48
+ if (a && (a.host !== own || skipped.test(a.pathname) || a.hasAttribute('download')))
49
+ return;
50
+ el.setAttribute('data-tapcheck', String(i));
51
+ out.push({ i, label, href: a ? a.pathname + a.search + a.hash : '' });
52
+ });
53
+ return out;
54
+ }, { own, unsafe: UNSAFE.source, skip: skip.source, DIALOG });
55
+ /** The dialog showing now, marked so it can be found again; null when there is none. */
56
+ async function shown(page) {
57
+ const any = await page.evaluate((DIALOG) => {
58
+ document.querySelectorAll('[data-tapcheck-dialog]').forEach((el) => el.removeAttribute('data-tapcheck-dialog'));
59
+ const d = [...document.querySelectorAll(DIALOG)].filter((el) => { const r = el.getBoundingClientRect(); return r.width > 1 && r.height > 1 && getComputedStyle(el).visibility !== 'hidden'; }).at(-1);
60
+ d?.setAttribute('data-tapcheck-dialog', '');
61
+ return !!d;
62
+ }, DIALOG).catch(() => false);
63
+ return any ? page.locator('[data-tapcheck-dialog]') : null;
64
+ }
65
+ /** The dialog's error state: the browser's validation refusing a field, an invalid field, or a message the app shows. '' when none. */
66
+ const errorState = (d) => d.evaluate((el) => {
67
+ const bad = [...el.querySelectorAll('input, textarea, select')].find((f) => f.willValidate && !f.form?.noValidate && !f.validity.valid);
68
+ if (bad)
69
+ return `browser validation: ${bad.validationMessage}`;
70
+ const msg = [...el.querySelectorAll('[aria-invalid=true], [role=alert], [class*=error i], [class*=invalid i]')]
71
+ .find((e) => e.getClientRects().length > 0 && (e.getAttribute('aria-invalid') === 'true' || e.innerText.trim()));
72
+ return !msg ? '' : msg.getAttribute('aria-invalid') === 'true' ? 'aria-invalid on a field' : `message: ${msg.innerText.replace(/\s+/g, ' ').trim().slice(0, 80)}`;
73
+ }).catch(() => '');
74
+ /**
75
+ * Invalid input, then (with `submit`) valid input, in the form of the dialog that is open now. Returns the findings to
76
+ * record as [check, status, detail]. The dialog may be closed, or the page moved, when it returns.
77
+ */
78
+ async function probe(d, submit, wait) {
79
+ const CHECK = 'invalid input shows an error';
80
+ const form = d.locator('form').first();
81
+ const fields = await form.locator(FIELDS).filter({ visible: true }).all();
82
+ const kind = (f) => f.evaluate((el) => { const e = el; return { type: e.type, required: e.required || e.getAttribute('aria-required') === 'true', max: e.maxLength }; });
83
+ let made = 0;
84
+ for (const f of fields) {
85
+ const k = await kind(f);
86
+ if (k.required)
87
+ await f.fill('');
88
+ else if (k.type === 'email')
89
+ await f.fill('not-an-email');
90
+ else if (k.max > 0)
91
+ await f.fill('x'.repeat(k.max + 10));
92
+ else
93
+ continue;
94
+ made++;
95
+ }
96
+ if (!made)
97
+ return [[CHECK, 'info', 'not tried: the form has no required, email or maxlength field to make invalid']];
98
+ const button = form.locator('button[type=submit], input[type=submit], button:not([type])').filter({ visible: true }).last();
99
+ const label = (await button.count()) ? (await button.evaluate((b) => b.innerText || b.value)).replace(/\s+/g, ' ').trim() : '';
100
+ const send = async () => { await (label ? button.click({ timeout: 3000 }) : form.evaluate((f) => f.requestSubmit())).catch(() => { }); await wait(); };
101
+ // Refused by the browser itself, nothing can be sent, so any form may be tried. Otherwise only one that can't save.
102
+ const state = await form.evaluate((f) => ({ posts: f.method === 'post', blocked: !f.noValidate && !f.checkValidity() }));
103
+ if (!state.blocked && UNSAFE.test(label))
104
+ return [[CHECK, 'info', `not submitted: its button is "${label}"`]];
105
+ if (!state.blocked && state.posts && !submit)
106
+ return [[CHECK, 'info', 'not submitted: the form posts and only the app can refuse it (interact.submit: true tries it, on a throwaway database)']];
107
+ await send();
108
+ const open = await d.isVisible().catch(() => false);
109
+ const err = open ? await errorState(d) : '';
110
+ if (!err)
111
+ return [[CHECK, 'fail', open ? 'none shown: no aria-invalid, no visible message, no browser validation message' : 'the invalid input was accepted: the dialog closed']];
112
+ const out = [[CHECK, 'pass', err]];
113
+ if (!submit || UNSAFE.test(label))
114
+ return out;
115
+ // ponytail: text-like fields only; selects, checkboxes and pickers keep their values, so a form needing them is refused.
116
+ for (const [n, f] of fields.entries()) {
117
+ const k = await kind(f);
118
+ const v = { email: `tapcheck-${n}@example.com`, url: 'https://example.com/tapcheck', number: '1', range: '1', date: '2030-01-01', time: '09:00', tel: '5550100' }[k.type] ?? `tapcheck ${n}`;
119
+ if (!['password', 'search'].includes(k.type))
120
+ await f.fill(k.max > 0 ? v.slice(0, k.max) : v).catch(() => { });
121
+ }
122
+ await send();
123
+ const left = (await d.isVisible().catch(() => false)) ? await errorState(d) : '';
124
+ out.push(['valid input is accepted', left ? 'warn' : 'pass', left || 'submitted']);
125
+ return out;
126
+ }
127
+ /** Marks the page's tables (the first three) and, near each, its sort header, search box, next-page control and first row menu. */
128
+ const tagTables = (page) => page.evaluate((unsafe) => {
129
+ const no = new RegExp(unsafe, 'i');
130
+ const seen = (el) => { const r = el.getBoundingClientRect(); return r.width > 1 && r.height > 1 && getComputedStyle(el).visibility !== 'hidden'; };
131
+ const text = (el) => (el.innerText || el.getAttribute('aria-label') || '').replace(/\s+/g, ' ').trim();
132
+ const ok = (el) => seen(el) && !no.test(text(el)) && !el.disabled && el.getAttribute('aria-disabled') !== 'true';
133
+ for (const a of ['table', 'sort', 'search', 'next', 'menu'])
134
+ document.querySelectorAll(`[data-tapcheck-${a}]`).forEach((el) => el.removeAttribute(`data-tapcheck-${a}`));
135
+ return [...document.querySelectorAll('table, [role=grid]')].filter(seen).slice(0, 3).map((t, k) => {
136
+ t.setAttribute('data-tapcheck-table', String(k));
137
+ const mark = (what, el) => { el?.setAttribute(`data-tapcheck-${what}`, String(k)); return !!el; };
138
+ // "Near": the closest of the table's four nearest ancestors that holds one.
139
+ const near = (find) => { for (let p = t.parentElement, n = 0; p && n < 4; p = p.parentElement, n++) {
140
+ const hit = find(p);
141
+ if (hit)
142
+ return hit;
143
+ } };
144
+ const pick = (sel) => [...t.querySelectorAll(sel)].find(ok);
145
+ const sort = pick('th button, th a, [role=columnheader] button, [role=columnheader] a') ?? pick('th[aria-sort], [role=columnheader][aria-sort]'); // the control in a header, else the header itself
146
+ const search = near((p) => [...p.querySelectorAll('input[type=search], [role=searchbox], input[placeholder*=search i], input[placeholder*=filter i], input[aria-label*=search i], input[aria-label*=filter i]')].find(seen));
147
+ const next = near((p) => [...p.querySelectorAll('a, button')].find((el) => ok(el) && !t.contains(el) && (el.rel === 'next' || /^(next\b|[›»>]$)/i.test(text(el)))));
148
+ const menu = [...(t.querySelector('tbody tr, [role=rowgroup] [role=row]')?.querySelectorAll('[aria-haspopup]:not([aria-haspopup=false]), summary') ?? [])].find(ok);
149
+ return { headers: [...t.querySelectorAll('th, [role=columnheader]')].map(text).filter(Boolean).join(', ').slice(0, 80) || 'no headers',
150
+ sort: mark('sort', sort), search: mark('search', search), next: mark('next', next), menu: mark('menu', menu) };
151
+ });
152
+ }, UNSAFE.source);
153
+ export async function run(r) {
154
+ const own = host(r.side.baseUrl);
155
+ const reached = [...new Set(r.crawl.pages.filter((p) => p.status >= 200 && p.status < 400).map((p) => p.path))];
156
+ const paths = reached.slice(0, r.cfg.interact.max);
157
+ // Valid input changes data: like app.reset, it runs against a local app only unless app.allowRemoteReset says the remote one is a throwaway.
158
+ const submit = r.cfg.interact.submit && (isLocal(r.side.baseUrl) || r.cfg.app.allowRemoteReset);
159
+ if (r.cfg.interact.submit && !submit) {
160
+ r.record({ suite: S, where: r.side.baseUrl, check: 'interact.submit', status: 'info', detail: "left off: the app isn't local (app.allowRemoteReset: true lifts that, for a remote throwaway copy only)" });
161
+ }
162
+ const log = { screens: [], dialogs: [], tables: [] };
163
+ const dialogs = new Set(), tables = new Set(), followed = new Set(); // each dialog, table and link once per run
164
+ const ctx = await context(r, r.cfg.viewports.find((v) => !v.mobile) ?? r.cfg.viewports[0]);
165
+ const page = await ctx.newPage();
166
+ // What a click set off, collected until drain() files it under the control's label.
167
+ const seen = { errors: watch(page), bad: [], natives: [], requests: 0, popups: 0 };
168
+ page.on('request', () => { seen.requests++; });
169
+ page.on('response', (res) => { if (res.status() >= 500 && host(res.url()) === own)
170
+ seen.bad.push(`${res.status()} ${res.request().method()} ${new URL(res.url()).pathname}`); });
171
+ page.on('popup', (p) => { seen.popups++; p.close().catch(() => { }); });
172
+ page.on('dialog', (d) => {
173
+ if (d.type() === 'beforeunload') {
174
+ d.accept().catch(() => { });
175
+ return;
176
+ }
177
+ seen.natives.push(`${d.type()}("${d.message().slice(0, 60)}")`);
178
+ d.dismiss().catch(() => { });
179
+ });
180
+ const wait = async () => { await page.waitForTimeout(WAIT); if (seen.requests)
181
+ await page.waitForLoadState('networkidle', { timeout: 5000 }).catch(() => { }); };
182
+ const still = (u) => u.split('#')[0];
183
+ try {
184
+ for (const path of paths) {
185
+ const broke = [], failed = [], native = [], dead = [], clicked = [];
186
+ const clear = () => { seen.errors.length = seen.bad.length = seen.natives.length = seen.requests = seen.popups = 0; };
187
+ const drain = (label) => {
188
+ if (seen.errors.length)
189
+ broke.push(`"${label}": ${seen.errors[0].slice(0, 120)}`);
190
+ if (seen.bad.length)
191
+ failed.push(`"${label}" → ${seen.bad[0]}`);
192
+ if (seen.natives.length)
193
+ native.push(`"${label}": ${seen.natives[0]}`);
194
+ clear();
195
+ };
196
+ try {
197
+ await open(r, page, path);
198
+ const home = page.url();
199
+ let fresh = await tag(page, own, r.cfg.crawl.skip);
200
+ const reopen = async () => { if (still(page.url()) !== still(home) || await shown(page))
201
+ await open(r, page, path); fresh = await tag(page, own, r.cfg.crawl.skip); };
202
+ for (const c of fresh.filter((x) => !x.href || !followed.has(x.href)).slice(0, MAX_CLICKS)) {
203
+ const el = page.locator(`[data-tapcheck="${c.i}"]`);
204
+ if (fresh.find((x) => x.i === c.i)?.label !== c.label || !(await el.isVisible().catch(() => false)))
205
+ continue; // the page changed under it
206
+ if (c.href)
207
+ followed.add(c.href);
208
+ clear();
209
+ await page.evaluate(() => {
210
+ const w = window;
211
+ w.__tapcheckObserver ??= new MutationObserver((m) => { w.__tapcheck += m.length; });
212
+ w.__tapcheckObserver.observe(document.documentElement, { subtree: true, childList: true, attributes: true, characterData: true });
213
+ w.__tapcheck = 0;
214
+ });
215
+ if (await el.click({ timeout: 3000 }).then(() => false, () => true))
216
+ continue; // covered or gone: not clicked
217
+ await wait();
218
+ clicked.push(c.label);
219
+ // Did anything happen? A new document has no counter, which is a change too.
220
+ const mutations = await page.evaluate(() => window.__tapcheck).catch(() => undefined);
221
+ const moved = page.url().replace(/#$/, '') !== home.replace(/#$/, '');
222
+ if (mutations === 0 && !moved && !seen.requests && !seen.natives.length && !seen.popups)
223
+ dead.push(c.label);
224
+ const d = still(page.url()) === still(home) ? await shown(page) : null;
225
+ if (d) {
226
+ const info = await d.evaluate((el) => {
227
+ const flat = (s) => (s ?? '').replace(/\s+/g, ' ').trim().slice(0, 60);
228
+ const by = (el.getAttribute('aria-labelledby') ?? '').split(/\s+/).map((id) => document.getElementById(id)?.innerText ?? '').join(' ');
229
+ return { name: flat(el.getAttribute('aria-label') || by || el.getAttribute('title')), heading: flat(el.querySelector('h1, h2, h3, [role=heading]')?.innerText),
230
+ role: el.getAttribute('role') ?? el.tagName.toLowerCase(), focus: el.contains(document.activeElement), form: !!el.querySelector('form') };
231
+ });
232
+ const key = info.name || info.heading || `opened by "${c.label}"`;
233
+ if (!dialogs.has(key)) {
234
+ dialogs.add(key);
235
+ const where = `${path} › ${key}`;
236
+ const rec = (check, status, detail) => r.record({ suite: S, where, check, status, detail });
237
+ rec('dialog has an accessible name', info.name ? 'pass' : 'fail', info.name ? undefined : `opened by "${c.label}": it needs aria-label or aria-labelledby`);
238
+ rec('focus moves into the dialog', info.focus ? 'pass' : 'warn', info.focus ? undefined : 'focus stayed on the page behind it');
239
+ if (DESTRUCTIVE.test(key))
240
+ rec('destructive dialog is an alertdialog', info.role === 'alertdialog' ? 'pass' : 'warn', `role: ${info.role}`);
241
+ await page.keyboard.press('Escape');
242
+ await page.waitForTimeout(200);
243
+ const closes = !(await d.isVisible().catch(() => false));
244
+ rec('dialog closes with Escape', closes ? 'pass' : 'fail');
245
+ const entry = { name: key, named: !!info.name, role: info.role, page: path, opener: c.label, form: info.form };
246
+ if (info.form) {
247
+ if (closes) {
248
+ await el.click({ timeout: 3000 }).catch(() => { });
249
+ await wait();
250
+ }
251
+ const again = await shown(page);
252
+ for (const [check, status, detail] of again ? await probe(again, submit, wait) : []) {
253
+ rec(check, status, detail);
254
+ entry[check] = `${status}: ${detail}`;
255
+ }
256
+ }
257
+ log.dialogs.push(entry);
258
+ reach(r, `dialog ${key}`, path);
259
+ }
260
+ }
261
+ drain(c.label);
262
+ await page.keyboard.press('Escape').catch(() => { }); // close what the click opened
263
+ if (mutations === undefined || still(page.url()) !== still(home) || await shown(page))
264
+ await reopen();
265
+ }
266
+ // Tables: each one once per run (a list looks the same on every page it is on).
267
+ for (const [k, t] of (await tagTables(page)).entries()) {
268
+ if (tables.has(t.headers))
269
+ continue;
270
+ tables.add(t.headers);
271
+ const where = `${path} › table (${t.headers.slice(0, 40)})`;
272
+ const table = page.locator(`[data-tapcheck-table="${k}"]`);
273
+ const rows = () => table.evaluate((el) => [...el.querySelectorAll('tbody tr, [role=row]')].map((x) => x.innerText).join('\n')
274
+ + [...el.querySelectorAll('[aria-sort]')].map((h) => h.getAttribute('aria-sort')).join()).catch(() => '');
275
+ const entry = { page: path, headers: t.headers };
276
+ const attempt = async (what, check, has, act, changed) => {
277
+ if (!has)
278
+ return;
279
+ const before = await rows(), url = page.url();
280
+ clear();
281
+ await act(page.locator(`[data-tapcheck-${what}="${k}"]`)).catch(() => { });
282
+ await wait();
283
+ const did = page.url() !== url || (changed ? await changed() : (await rows()) !== before);
284
+ r.record({ suite: S, where, check, status: did ? 'pass' : 'warn', detail: did ? undefined : 'nothing changed' });
285
+ entry[what] = did ? 'changed' : 'unchanged';
286
+ reach(r, `table ${t.headers.slice(0, 40)}: ${what}`, path);
287
+ drain(`table ${what}`);
288
+ await page.keyboard.press('Escape').catch(() => { });
289
+ await open(r, page, path); // back to the table as it was
290
+ await tagTables(page);
291
+ };
292
+ await attempt('sort', 'sorting changes the rows', t.sort, (l) => l.click({ timeout: 3000 }));
293
+ // A term no row has. Enter is pressed unless that would submit a form that POSTs.
294
+ await attempt('search', 'search changes the rows', t.search, async (l) => { await l.fill('zzqx-tapcheck'); if (await l.evaluate((el) => el.form?.method !== 'post'))
295
+ await l.press('Enter'); });
296
+ await attempt('next', 'paging changes the rows', t.next, (l) => l.click({ timeout: 3000 }));
297
+ await attempt('menu', 'row menu opens', t.menu, (l) => l.click({ timeout: 3000 }), () => page.evaluate((DIALOG) => [...document.querySelectorAll(`[role=menu], [role=listbox], details[open], ${DIALOG}`)].some((el) => el.getClientRects().length > 0), DIALOG));
298
+ log.tables.push(entry);
299
+ }
300
+ r.record({ suite: S, where: path, check: 'clicks raise no page or console errors', status: broke.length ? 'fail' : 'pass', detail: broke.slice(0, 4).join(' | ') || `${clicked.length} control(s) clicked` });
301
+ r.record({ suite: S, where: path, check: 'clicks set off no 5xx', status: failed.length ? 'fail' : 'pass', detail: failed.slice(0, 4).join('; ') || undefined });
302
+ r.record({ suite: S, where: path, check: 'no native alert, confirm or prompt', status: native.length ? 'fail' : 'pass', detail: native.slice(0, 4).join('; ') || undefined });
303
+ r.record({ suite: S, where: path, check: 'every control does something', status: dead.length ? 'warn' : 'pass', detail: dead.length ? `nothing changed after: ${dead.slice(0, 6).map((l) => `"${l}"`).join(', ')}` : undefined });
304
+ }
305
+ catch (e) {
306
+ if (e instanceof SessionExpired)
307
+ throw e;
308
+ r.record({ suite: S, where: path, check: 'sweep ran', status: 'fail', detail: e.message.slice(0, 200) });
309
+ }
310
+ log.screens.push({ path, clicked, dead });
311
+ }
312
+ }
313
+ finally {
314
+ writeFileSync(`${r.dir}/interact.json`, JSON.stringify(log, null, 2));
315
+ await ctx.close();
316
+ }
317
+ r.record({ suite: S, where: 'all crawled pages', check: 'interaction coverage', status: 'info', evidence: [`${r.dir}/interact.json`],
318
+ detail: `${paths.length} of ${reached.length} screen(s), ${log.screens.reduce((n, s) => n + s.clicked.length, 0)} control(s) clicked, ${log.dialogs.length} dialog(s), ${log.tables.length} table(s)` });
319
+ }
@@ -0,0 +1,12 @@
1
+ import { type Run } from '../browser.ts';
2
+ export declare const SECRETS: [string, RegExp][];
3
+ export declare const leaksIn: (text: string) => string[];
4
+ export declare function run(r: Run): Promise<void>;
5
+ /** What is wrong with a session-like cookie's flags. A CSRF token cookie (XSRF-TOKEN, csrftoken) is meant to be read
6
+ * by the page's script, so it may lack HttpOnly; SameSite and Secure still apply. */
7
+ export declare const cookieProblems: (c: {
8
+ name: string;
9
+ httpOnly: boolean;
10
+ sameSite: string;
11
+ secure: boolean;
12
+ }, https: boolean) => string[];
@@ -0,0 +1,134 @@
1
+ /*
2
+ * Security evidence (measured, no Jev), over the pages the crawl reached:
3
+ * - response headers on HTML pages: nosniff, framing blocked (X-Frame-Options or CSP frame-ancestors), Referrer-Policy,
4
+ * a CSP, HSTS when served over https;
5
+ * - session cookies (a side that signs in): HttpOnly (not for a CSRF token cookie), SameSite, Secure over https;
6
+ * - signed out, every crawled page of a side that signs in refuses or sends the visitor to sign in;
7
+ * - CSRF (when security.csrf is set; on the sides that sign in, or every side when none does): the request, without a
8
+ * token, is refused with the expected status;
9
+ * - secrets: no API keys, private keys or tokens in the served HTML or in the app's own scripts as served;
10
+ * - links that open a new tab carry rel=noopener (or noreferrer);
11
+ * - no requests to third-party hosts outside security.allowedHosts, listed with the page that made them.
12
+ */
13
+ import { request as pwRequest } from 'playwright';
14
+ import { abs, context, host } from '../browser.js';
15
+ import { run as runCrawl } from './crawl.js';
16
+ export const SECRETS = [
17
+ ['Anthropic key', /sk-ant-[a-z0-9_-]{20,}/i], ['OpenAI-style key', /\bsk-[a-zA-Z0-9]{32,}/], ['Stripe live key', /\b[rs]k_live_[0-9a-zA-Z]{16,}/],
18
+ ['AWS access key', /\bAKIA[0-9A-Z]{16}\b/], ['private key', /-----BEGIN [A-Z ]*PRIVATE KEY-----/], ['Slack token', /\bxox[abpr]-[0-9a-zA-Z-]{10,}/],
19
+ ['GitHub token', /\bgh[pousr]_[0-9a-zA-Z]{30,}/], ['Google API key', /\bAIza[0-9A-Za-z_-]{35}\b/],
20
+ ];
21
+ export const leaksIn = (text) => SECRETS.filter(([, re]) => re.test(text)).map(([name]) => name);
22
+ export async function run(r) {
23
+ const S = 'security';
24
+ if (!r.crawl.done)
25
+ await runCrawl(r);
26
+ const base = r.side.baseUrl;
27
+ const https = base.startsWith('https://');
28
+ const signsIn = !('none' in r.side.login);
29
+ const headers = ['X-Content-Type-Options: nosniff', 'framing blocked', 'Referrer-Policy', 'Content-Security-Policy', ...(https ? ['Strict-Transport-Security'] : [])];
30
+ const pages = r.crawl.pages.filter((p) => p.status < 400 && !r.cfg.crawl.skip.test(p.path)).slice(0, 40);
31
+ const ctx = await context(r, r.cfg.viewports[0]);
32
+ const api = ctx.request;
33
+ try {
34
+ // Headers and bodies, as the side sees them.
35
+ const missing = {};
36
+ const leaks = [];
37
+ const blank = [];
38
+ let html = 0;
39
+ for (const p of pages) {
40
+ const res = await api.get(abs(r, p.path), { failOnStatusCode: false, maxRedirects: 0 }).catch(() => null);
41
+ if (!res || !/text\/html/.test(res.headers()['content-type'] ?? ''))
42
+ continue;
43
+ html++;
44
+ const h = res.headers();
45
+ const csp = h['content-security-policy'] ?? '';
46
+ const has = {
47
+ 'X-Content-Type-Options: nosniff': /nosniff/i.test(h['x-content-type-options'] ?? ''),
48
+ 'framing blocked': /deny|sameorigin/i.test(h['x-frame-options'] ?? '') || /frame-ancestors/i.test(csp),
49
+ 'Referrer-Policy': !!h['referrer-policy'],
50
+ 'Content-Security-Policy': !!csp,
51
+ 'Strict-Transport-Security': !!h['strict-transport-security'],
52
+ };
53
+ for (const name of headers)
54
+ if (!has[name])
55
+ (missing[name] ??= []).push(p.path);
56
+ const body = await res.text();
57
+ for (const name of leaksIn(body))
58
+ leaks.push(`${name} in ${p.path}`);
59
+ const opens = [...body.matchAll(/<a\b[^>]*target=["']?_blank[^>]*>/gi)].map((m) => m[0]).filter((a) => !/rel=["'][^"']*(noopener|noreferrer)/i.test(a));
60
+ if (opens.length)
61
+ blank.push(`${p.path} (${opens.length})`);
62
+ }
63
+ for (const name of headers) {
64
+ const on = missing[name] ?? [];
65
+ r.record({ suite: S, where: 'HTML pages', check: `header: ${name}`, status: on.length ? (name === 'Content-Security-Policy' ? 'warn' : 'fail') : 'pass',
66
+ detail: on.length ? `missing on ${on.length}/${html}: ${on.slice(0, 5).join(', ')}` : `${html} pages` });
67
+ }
68
+ r.record({ suite: S, where: 'HTML pages', check: 'new-tab links use rel=noopener', status: blank.length ? 'warn' : 'pass', detail: blank.slice(0, 6).join('; ') || undefined });
69
+ // The app's own scripts, as served (whatever built them).
70
+ const scripts = [...new Set(r.crawl.hits.filter((h) => h.type === 'script' && host(h.url) === host(base) && h.status < 400).map((h) => h.url))].slice(0, 60);
71
+ for (const u of scripts) {
72
+ const js = await api.get(u, { failOnStatusCode: false }).then((x) => x.text()).catch(() => '');
73
+ for (const name of leaksIn(js))
74
+ leaks.push(`${name} in ${new URL(u).pathname}`);
75
+ }
76
+ r.record({ suite: S, where: 'served HTML and scripts', check: 'no secrets', status: leaks.length ? 'fail' : 'pass',
77
+ detail: leaks.slice(0, 6).join('; ') || `${html} pages, ${scripts.length} scripts` });
78
+ if (signsIn) {
79
+ // Cookies.
80
+ const session = (await ctx.cookies(base)).filter((c) => /sess|auth|token|sid/i.test(c.name));
81
+ for (const c of session) {
82
+ const bad = cookieProblems(c, https);
83
+ r.record({ suite: S, where: `cookie ${c.name}`, check: 'session cookie flags', status: bad.length ? 'fail' : 'pass',
84
+ detail: bad.join(', ') || `${c.httpOnly ? 'HttpOnly' : 'readable by script (a CSRF token)'}, SameSite=${c.sameSite}${https ? ', Secure' : ''}` });
85
+ }
86
+ if (!session.length)
87
+ r.record({ suite: S, where: 'cookies', check: 'session cookie flags', status: 'warn', detail: 'no session-like cookie in the saved session' });
88
+ // Signed out: every page must refuse or send to sign in.
89
+ const anon = await pwRequest.newContext();
90
+ const open = [];
91
+ for (const p of pages) {
92
+ // Redirects are followed: `/` → `/admin` → `/login` refuses as surely as one hop does.
93
+ const res = await anon.get(abs(r, p.path), { failOnStatusCode: false, maxRedirects: 5 }).catch(() => null);
94
+ if (!res)
95
+ continue;
96
+ const to = new URL(res.url()).pathname, moved = to !== new URL(abs(r, p.path)).pathname;
97
+ const refused = [401, 403, 404, 419].includes(res.status()) || (moved && r.cfg.loginPaths.test(to));
98
+ if (!refused)
99
+ open.push(`${res.status()} ${p.path}${moved ? ` → ${to}` : ''}`);
100
+ }
101
+ await anon.dispose();
102
+ r.record({ suite: S, where: 'signed out', check: 'pages need sign-in', status: open.length ? 'fail' : 'pass', detail: open.slice(0, 8).join('; ') || `${pages.length} pages refused` });
103
+ }
104
+ // CSRF: the configured request, signed in, without a token.
105
+ // Sent on the sides that sign in, or on every side when none does (a public app's own forms).
106
+ const c = r.side.csrf ?? r.cfg.security.csrf;
107
+ if (c && (signsIn || r.cfg.sides.every((s) => 'none' in s.login))) {
108
+ const res = await api.fetch(abs(r, c.path), { method: c.method, headers: { Accept: 'application/json' }, data: {}, failOnStatusCode: false });
109
+ r.record({ suite: S, where: `${c.method} ${c.path} without a CSRF token`, check: `refused with ${c.expect}`, status: res.status() === c.expect ? 'pass' : 'fail', detail: `answered ${res.status()}` });
110
+ }
111
+ // Third-party requests.
112
+ const own = host(base);
113
+ const third = new Map();
114
+ for (const h of r.crawl.hits) {
115
+ const hh = host(h.url);
116
+ if (!hh || hh === own || r.cfg.security.allowedHosts.includes(hh))
117
+ continue;
118
+ if (!third.has(hh))
119
+ third.set(hh, new Set());
120
+ third.get(hh).add(h.page);
121
+ }
122
+ r.record({ suite: S, where: 'all crawled pages', check: 'no third-party requests', status: third.size ? 'fail' : 'pass',
123
+ detail: [...third].map(([hh, ps]) => `${hh} (from ${[...ps].slice(0, 3).join(', ')})`).join('; ') || undefined });
124
+ if (!https)
125
+ r.record({ suite: S, where: base, check: 'https-only checks', status: 'info', detail: 'HSTS and Secure cookies are checked only over https' });
126
+ }
127
+ finally {
128
+ await ctx.close();
129
+ }
130
+ }
131
+ /** What is wrong with a session-like cookie's flags. A CSRF token cookie (XSRF-TOKEN, csrftoken) is meant to be read
132
+ * by the page's script, so it may lack HttpOnly; SameSite and Secure still apply. */
133
+ export const cookieProblems = (c, https) => [!c.httpOnly && !/xsrf|csrf/i.test(c.name) && 'not HttpOnly', !['Lax', 'Strict'].includes(c.sameSite) && `SameSite=${c.sameSite}`,
134
+ https && !c.secure && 'not Secure'].filter((x) => !!x);
@@ -0,0 +1,3 @@
1
+ import { type Run } from '../browser.ts';
2
+ export declare const UNSAFE: RegExp;
3
+ export declare function run(r: Run): Promise<void>;