@ashishjain15491/tapcheck 0.0.0-stage → 0.1.0
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.
- package/CHANGELOG.md +75 -0
- package/LICENSE +21 -0
- package/README.md +243 -2
- package/dist/auth.d.ts +5 -0
- package/dist/auth.js +100 -0
- package/dist/browser.d.ts +143 -0
- package/dist/browser.js +237 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +321 -0
- package/dist/config.d.ts +169 -0
- package/dist/config.js +369 -0
- package/dist/coverage.d.ts +17 -0
- package/dist/coverage.js +56 -0
- package/dist/flow.d.ts +193 -0
- package/dist/flow.js +512 -0
- package/dist/jev.d.ts +48 -0
- package/dist/jev.js +89 -0
- package/dist/parts.d.ts +65 -0
- package/dist/parts.js +157 -0
- package/dist/questions.d.ts +66 -0
- package/dist/questions.js +203 -0
- package/dist/report.d.ts +29 -0
- package/dist/report.js +59 -0
- package/dist/routes.d.ts +18 -0
- package/dist/routes.js +54 -0
- package/dist/stub.d.ts +51 -0
- package/dist/stub.js +244 -0
- package/dist/suites/a11y.d.ts +3 -0
- package/dist/suites/a11y.js +73 -0
- package/dist/suites/audit.d.ts +2 -0
- package/dist/suites/audit.js +440 -0
- package/dist/suites/code.d.ts +10 -0
- package/dist/suites/code.js +48 -0
- package/dist/suites/contract.d.ts +5 -0
- package/dist/suites/contract.js +79 -0
- package/dist/suites/crawl.d.ts +2 -0
- package/dist/suites/crawl.js +135 -0
- package/dist/suites/interact.d.ts +2 -0
- package/dist/suites/interact.js +319 -0
- package/dist/suites/security.d.ts +12 -0
- package/dist/suites/security.js +134 -0
- package/dist/suites/usability.d.ts +3 -0
- package/dist/suites/usability.js +205 -0
- package/dist/suites/ux.d.ts +6 -0
- package/dist/suites/ux.js +183 -0
- package/package.json +61 -5
- package/schema/tapcheck.schema.json +368 -0
package/dist/routes.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The app's own route list, from the `routes` command in tapcheck.yml: any program that prints JSON
|
|
3
|
+
* [{method, path, auth?}] on stdout (the framework's route lister piped through a few lines of script). Paths may write
|
|
4
|
+
* their parameters in any common style ({id}, {id?}, <int:pk>, <pk>, :id, (.:format), *splat); each becomes a matcher,
|
|
5
|
+
* so the crawl can say which GET routes it reached and the code suite which writing routes need no sign-in. Routes
|
|
6
|
+
* written as regular expressions aren't understood.
|
|
7
|
+
*/
|
|
8
|
+
import { execSync } from 'node:child_process';
|
|
9
|
+
const TOKEN = /\/\{[^}]+\?\}|\/:\w+\?|\{[^}]+\}|<path:[^>]+>|<[^>]+>|:\w+|\*\w*|[()]|[^]/g;
|
|
10
|
+
/** A route path as a regular expression on a URL path: parameters match one segment, splats the rest, (groups) are optional. */
|
|
11
|
+
export function matcher(path) {
|
|
12
|
+
const src = `/${path.replace(/^\/+|\/+$/g, '')}`.replace(TOKEN, (t) => {
|
|
13
|
+
if (t.length > 1 && t.startsWith('/'))
|
|
14
|
+
return '(?:/[^/]+)?'; // /{id?} and /:id?
|
|
15
|
+
if (t.startsWith('<path:') || t.startsWith('*'))
|
|
16
|
+
return '.+';
|
|
17
|
+
if (t.length > 1)
|
|
18
|
+
return '[^/]+'; // {id}, <int:pk>, <pk>, :id
|
|
19
|
+
return t === '(' ? '(?:' : t === ')' ? ')?' : t.replace(/[.+?^$|[\]\\]/, '\\$&');
|
|
20
|
+
});
|
|
21
|
+
return new RegExp(`^${src}/?$`);
|
|
22
|
+
}
|
|
23
|
+
export const hasParams = (path) => /[{<:*(]/.test(path);
|
|
24
|
+
/** What the routes command printed, one route per method (GET|HEAD becomes GET), paths with a leading slash. */
|
|
25
|
+
export function parse(out) {
|
|
26
|
+
let list;
|
|
27
|
+
try {
|
|
28
|
+
list = JSON.parse(out);
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
throw new Error('routes: the command did not print JSON (want [{method, path, auth?}]).');
|
|
32
|
+
}
|
|
33
|
+
if (!Array.isArray(list))
|
|
34
|
+
throw new Error('routes: the command must print a JSON list of {method, path, auth?}.');
|
|
35
|
+
return list.flatMap((r, i) => {
|
|
36
|
+
if (typeof r?.path !== 'string' || !(typeof r.method === 'string' || Array.isArray(r.method)))
|
|
37
|
+
throw new Error(`routes: entry ${i} needs a method and a path.`);
|
|
38
|
+
const methods = (Array.isArray(r.method) ? r.method : r.method.split(/[|,\s]+/)).map((m) => m.toUpperCase()).filter((m) => m && m !== 'HEAD' && m !== 'OPTIONS');
|
|
39
|
+
return methods.map((method) => ({ method, path: `/${r.path.replace(/^\/+/, '')}`, ...(typeof r.auth === 'boolean' ? { auth: r.auth } : {}) }));
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
let cached;
|
|
43
|
+
/** The app's routes: the command runs once per run, from the config file's folder. Empty when no command is configured. */
|
|
44
|
+
export function routes(cfg) {
|
|
45
|
+
if (!cfg.routes)
|
|
46
|
+
return [];
|
|
47
|
+
return (cached ??= parse(execSync(cfg.routes, { cwd: cfg.root, encoding: 'utf8', shell: '/bin/sh', maxBuffer: 64 * 1024 * 1024 })));
|
|
48
|
+
}
|
|
49
|
+
/** Of the GET routes, the ones no reached URL path matches. */
|
|
50
|
+
export function coverage(list, reached) {
|
|
51
|
+
const gets = [...new Set(list.filter((r) => r.method === 'GET').map((r) => r.path))];
|
|
52
|
+
const missed = gets.filter((p) => { const re = matcher(p); return !reached.some((u) => re.test(u)); });
|
|
53
|
+
return { total: gets.length, missed };
|
|
54
|
+
}
|
package/dist/stub.d.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { type IncomingHttpHeaders } from 'node:http';
|
|
2
|
+
import { type Config, type StubRule } from './config.ts';
|
|
3
|
+
export type Seen = {
|
|
4
|
+
t: number;
|
|
5
|
+
method: string;
|
|
6
|
+
host: string;
|
|
7
|
+
path: string;
|
|
8
|
+
query: Record<string, string>;
|
|
9
|
+
headers: Record<string, string>;
|
|
10
|
+
body: unknown;
|
|
11
|
+
status: number;
|
|
12
|
+
ms: number;
|
|
13
|
+
};
|
|
14
|
+
export type FailRule = {
|
|
15
|
+
host?: string;
|
|
16
|
+
path?: string;
|
|
17
|
+
status?: number;
|
|
18
|
+
body?: unknown;
|
|
19
|
+
times?: number;
|
|
20
|
+
};
|
|
21
|
+
export type Reply = {
|
|
22
|
+
host?: string;
|
|
23
|
+
path?: string;
|
|
24
|
+
status?: number;
|
|
25
|
+
json?: unknown;
|
|
26
|
+
body?: string;
|
|
27
|
+
};
|
|
28
|
+
/** The outside host a request was meant for ('' when it is for the stub itself) and its path there. */
|
|
29
|
+
export declare function target(headers: IncomingHttpHeaders, path: string, port: number): {
|
|
30
|
+
host: string;
|
|
31
|
+
path: string;
|
|
32
|
+
};
|
|
33
|
+
/** The first rule matching the request. */
|
|
34
|
+
export declare const match: (rules: StubRule[], host: string, method: string, path: string) => StubRule | undefined;
|
|
35
|
+
/** The question in a DNS message (lower-cased name, type by name or ''), or null when it isn't a plain query. */
|
|
36
|
+
export declare function dnsQuestion(msg: Buffer): {
|
|
37
|
+
name: string;
|
|
38
|
+
type: string;
|
|
39
|
+
end: number;
|
|
40
|
+
} | null;
|
|
41
|
+
/** The reply to `msg`: its question, then one record per value (the name is a pointer back to the question). */
|
|
42
|
+
export declare function dnsReply(msg: Buffer, q: {
|
|
43
|
+
type: string;
|
|
44
|
+
end: number;
|
|
45
|
+
}, values: string[], rcode?: number): Buffer;
|
|
46
|
+
/** Starts the stub on 127.0.0.1; `out` is where stub-requests.jsonl goes, `root` what rule files are relative to. */
|
|
47
|
+
export declare function start(cfg: NonNullable<Config['stub']>, out: string, root?: string): Promise<{
|
|
48
|
+
url: string;
|
|
49
|
+
dns: string | undefined;
|
|
50
|
+
stop: () => Promise<void>;
|
|
51
|
+
}>;
|
package/dist/stub.js
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The stub: one small HTTP server standing in for every outside service the app calls (payment, mail, AI and other
|
|
3
|
+
* providers, webhook targets), so a run never reaches a real one. tapcheck starts it before the app when tapcheck.yml has
|
|
4
|
+
* `stub:`, and hands its address to the app's start command and the gates as TAPCHECK_STUB_URL.
|
|
5
|
+
*
|
|
6
|
+
* Which outside host a request was meant for, first that applies:
|
|
7
|
+
* 1. the X-Forwarded-Host header;
|
|
8
|
+
* 2. the Host header, when it isn't the stub's own (a proxy or a hosts-file entry sent it here);
|
|
9
|
+
* 3. a first path segment with a dot in it: /api.example.com/v1/x is host api.example.com, path /v1/x.
|
|
10
|
+
* So the simplest wiring is to point each provider's base URL at ${TAPCHECK_STUB_URL}/<its host>.
|
|
11
|
+
*
|
|
12
|
+
* The answer, first that applies:
|
|
13
|
+
* 1. a failure switched on through the control API (below);
|
|
14
|
+
* 2. 500 for any request with "tapcheck-fail" in its URL or body (a failure a flow can trigger with plain test data);
|
|
15
|
+
* 3. a one-off reply queued through the control API;
|
|
16
|
+
* 4. the first of stub.rules that matches host (or a parent domain), method and path;
|
|
17
|
+
* 5. 200 {} (so anything can be a webhook target).
|
|
18
|
+
*
|
|
19
|
+
* Control API, on the stub's own host (flows use it through t.stub):
|
|
20
|
+
* GET /_tapcheck/requests?host=&path=&since= requests seen, oldest first (path: a part of it; since: ms timestamp)
|
|
21
|
+
* DELETE /_tapcheck/requests forget them
|
|
22
|
+
* POST /_tapcheck/fail {host, path?, status?, body?, times?} fail the next `times` matching requests (default 1; 0 = until cleared)
|
|
23
|
+
* DELETE /_tapcheck/fail clear the failures
|
|
24
|
+
* POST /_tapcheck/reply {host, path?, status?, json? | body?} answer the next matching request with this, once
|
|
25
|
+
* DELETE /_tapcheck/reply clear the queued replies
|
|
26
|
+
* POST /_tapcheck/dns {name, type, values} answer that DNS question with these values (null: back to the config)
|
|
27
|
+
* DELETE /_tapcheck/dns forget those
|
|
28
|
+
* Every request is also appended to <out>/stub-requests.jsonl (sign-in headers left out).
|
|
29
|
+
*
|
|
30
|
+
* DNS: with `stub.dns`, the same process answers DNS questions over UDP (its address is TAPCHECK_DNS, host:port), so an
|
|
31
|
+
* app that verifies domains can be pointed at it instead of a real resolver. The answer, first that applies: an override
|
|
32
|
+
* set through the control API; no such name (NXDOMAIN) for a name containing "tapcheck-fail"; the `records` for that name
|
|
33
|
+
* and type; `defaultA` for an A question; else no records. Only A, AAAA, MX, TXT, CNAME and NS, one question per message,
|
|
34
|
+
* UDP only. Each question is logged like a request: method DNS, host the name, path the type, status the DNS rcode.
|
|
35
|
+
*/
|
|
36
|
+
import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
37
|
+
import { createSocket } from 'node:dgram';
|
|
38
|
+
import { createServer } from 'node:http';
|
|
39
|
+
import { matchesGlob, resolve } from 'node:path';
|
|
40
|
+
import { DNS_TYPES, dnsValue } from './config.js';
|
|
41
|
+
const OWN = ['127.0.0.1', 'localhost', '[::1]'];
|
|
42
|
+
const SECRET = /^(authorization|proxy-authorization|cookie|set-cookie|x-api-key)$/;
|
|
43
|
+
const TYPES = { json: 'application/json', html: 'text/html; charset=utf-8', xml: 'application/xml', txt: 'text/plain; charset=utf-8' };
|
|
44
|
+
/** The outside host a request was meant for ('' when it is for the stub itself) and its path there. */
|
|
45
|
+
export function target(headers, path, port) {
|
|
46
|
+
const name = (h) => h.trim().toLowerCase().replace(/:\d+$/, '');
|
|
47
|
+
const fwd = String(headers['x-forwarded-host'] ?? '').split(',')[0];
|
|
48
|
+
if (fwd.trim())
|
|
49
|
+
return { host: name(fwd), path };
|
|
50
|
+
const h = headers.host ?? '';
|
|
51
|
+
if (h && !(OWN.includes(name(h)) && (h.match(/:(\d+)$/)?.[1] ?? '80') === String(port)))
|
|
52
|
+
return { host: name(h), path };
|
|
53
|
+
const m = path.match(/^\/([a-z0-9-]+(?:\.[a-z0-9-]+)*\.[a-z][a-z0-9-]*)(\/.*)?$/i); // shaped like a host name, so /v1.2/x isn't one
|
|
54
|
+
return m ? { host: m[1].toLowerCase(), path: m[2] ?? '/' } : { host: '', path };
|
|
55
|
+
}
|
|
56
|
+
const onHost = (want, host) => !want || host === want || host.endsWith(`.${want}`);
|
|
57
|
+
/** The first rule matching the request. */
|
|
58
|
+
export const match = (rules, host, method, path) => rules.find((r) => onHost(r.host, host)
|
|
59
|
+
&& (!r.method || r.method === method) && (!r.path || (r.path.startsWith('^') ? new RegExp(r.path).test(path) : matchesGlob(path, r.path))));
|
|
60
|
+
// ── DNS: just enough of RFC 1035 to answer one question with records of the six types ──
|
|
61
|
+
const QTYPE = { 1: 'A', 2: 'NS', 5: 'CNAME', 15: 'MX', 16: 'TXT', 28: 'AAAA' };
|
|
62
|
+
const encName = (n) => Buffer.concat([...n.replace(/\.$/, '').split('.').filter(Boolean).map((l) => Buffer.concat([Buffer.from([Buffer.byteLength(l)]), Buffer.from(l)])), Buffer.from([0])]);
|
|
63
|
+
function rdata(type, v) {
|
|
64
|
+
if (type === 'A')
|
|
65
|
+
return Buffer.from(v.split('.').map(Number));
|
|
66
|
+
if (type === 'AAAA') { // hex groups, with at most one :: standing for the zero groups left out
|
|
67
|
+
const [head, tail] = v.split('::').map((x) => (x ? x.split(':') : []));
|
|
68
|
+
const groups = tail ? [...head, ...Array(8 - head.length - tail.length).fill('0'), ...tail] : head;
|
|
69
|
+
return Buffer.from(groups.flatMap((g) => { const n = parseInt(g, 16); return [n >> 8, n & 255]; }));
|
|
70
|
+
}
|
|
71
|
+
if (type === 'MX') {
|
|
72
|
+
const [, pri, name] = v.match(/^(?:(\d+)\s+)?(\S+)$/);
|
|
73
|
+
const b = Buffer.alloc(2);
|
|
74
|
+
b.writeUInt16BE(Number(pri ?? 10));
|
|
75
|
+
return Buffer.concat([b, encName(name)]);
|
|
76
|
+
}
|
|
77
|
+
if (type === 'TXT') { // character strings of at most 255 bytes each
|
|
78
|
+
const s = Buffer.from(v), parts = [];
|
|
79
|
+
for (let i = 0; i < s.length || i === 0; i += 255) {
|
|
80
|
+
const c = s.subarray(i, i + 255);
|
|
81
|
+
parts.push(Buffer.from([c.length]), c);
|
|
82
|
+
}
|
|
83
|
+
return Buffer.concat(parts);
|
|
84
|
+
}
|
|
85
|
+
return encName(v); // CNAME, NS
|
|
86
|
+
}
|
|
87
|
+
/** The question in a DNS message (lower-cased name, type by name or ''), or null when it isn't a plain query. */
|
|
88
|
+
export function dnsQuestion(msg) {
|
|
89
|
+
if (msg.length < 17 || msg[2] & 0xf8 || msg.readUInt16BE(4) !== 1)
|
|
90
|
+
return null; // a response, another opcode, or not one question
|
|
91
|
+
const labels = [];
|
|
92
|
+
let off = 12;
|
|
93
|
+
while (msg[off]) {
|
|
94
|
+
if (msg[off] > 63 || off + msg[off] + 5 >= msg.length)
|
|
95
|
+
return null;
|
|
96
|
+
labels.push(msg.subarray(off + 1, off + 1 + msg[off]).toString());
|
|
97
|
+
off += msg[off] + 1;
|
|
98
|
+
}
|
|
99
|
+
return { name: labels.join('.').toLowerCase(), type: QTYPE[msg.readUInt16BE(off + 1)] ?? '', end: off + 5 };
|
|
100
|
+
}
|
|
101
|
+
/** The reply to `msg`: its question, then one record per value (the name is a pointer back to the question). */
|
|
102
|
+
export function dnsReply(msg, q, values, rcode = 0) {
|
|
103
|
+
const head = Buffer.alloc(12);
|
|
104
|
+
head.writeUInt16BE(msg.readUInt16BE(0), 0);
|
|
105
|
+
head.writeUInt16BE(0x8180 | rcode, 2);
|
|
106
|
+
head.writeUInt16BE(1, 4);
|
|
107
|
+
head.writeUInt16BE(values.length, 6);
|
|
108
|
+
return Buffer.concat([head, msg.subarray(12, q.end), ...values.map((v) => {
|
|
109
|
+
const d = rdata(q.type, v), h = Buffer.alloc(12);
|
|
110
|
+
h.writeUInt16BE(0xc00c, 0);
|
|
111
|
+
h.writeUInt16BE(msg.readUInt16BE(q.end - 4), 2);
|
|
112
|
+
h.writeUInt16BE(1, 4);
|
|
113
|
+
h.writeUInt16BE(d.length, 10); // TTL 0 (the zeroes at 6): never cached, so an override shows at once
|
|
114
|
+
return Buffer.concat([h, d]);
|
|
115
|
+
})]);
|
|
116
|
+
}
|
|
117
|
+
function send(res, status, body, headers = {}) {
|
|
118
|
+
const raw = typeof body === 'string' || Buffer.isBuffer(body);
|
|
119
|
+
res.writeHead(status, { 'content-type': raw ? TYPES.txt : TYPES.json, ...headers }).end(raw ? body : JSON.stringify(body));
|
|
120
|
+
return status;
|
|
121
|
+
}
|
|
122
|
+
/** Starts the stub on 127.0.0.1; `out` is where stub-requests.jsonl goes, `root` what rule files are relative to. */
|
|
123
|
+
export async function start(cfg, out, root = process.cwd()) {
|
|
124
|
+
const log = [], fails = [], replies = [];
|
|
125
|
+
const dnsOver = new Map(); // "name|TYPE" → values, set through the control API
|
|
126
|
+
const file = `${out}/stub-requests.jsonl`;
|
|
127
|
+
mkdirSync(out, { recursive: true });
|
|
128
|
+
writeFileSync(file, '');
|
|
129
|
+
let port = cfg.port;
|
|
130
|
+
function control(method, path, q, body, res) {
|
|
131
|
+
if (path === '/_tapcheck/dns') {
|
|
132
|
+
if (method === 'DELETE') {
|
|
133
|
+
dnsOver.clear();
|
|
134
|
+
return send(res, 200, { ok: true });
|
|
135
|
+
}
|
|
136
|
+
if (!cfg.dns)
|
|
137
|
+
return send(res, 400, { error: 'tapcheck stub: tapcheck.yml has no stub.dns' });
|
|
138
|
+
const type = String(body?.type ?? '').toUpperCase(), key = `${String(body?.name ?? '').toLowerCase().replace(/\.$/, '')}|${type}`;
|
|
139
|
+
const ok = method === 'POST' && body?.name && DNS_TYPES.includes(type) && (body.values === null || (Array.isArray(body.values) && body.values.every((x) => dnsValue(type, x))));
|
|
140
|
+
if (!ok)
|
|
141
|
+
return send(res, 400, { error: `tapcheck stub: POST {name, type (${DNS_TYPES.join(', ')}), values: [..] or null}` });
|
|
142
|
+
if (body.values === null)
|
|
143
|
+
dnsOver.delete(key);
|
|
144
|
+
else
|
|
145
|
+
dnsOver.set(key, body.values);
|
|
146
|
+
return send(res, 200, { ok: true });
|
|
147
|
+
}
|
|
148
|
+
const list = path === '/_tapcheck/fail' ? fails : path === '/_tapcheck/reply' ? replies : path === '/_tapcheck/requests' ? log : null;
|
|
149
|
+
if (!list)
|
|
150
|
+
return send(res, 404, { error: 'tapcheck stub: no such control path' });
|
|
151
|
+
if (method === 'DELETE') {
|
|
152
|
+
list.length = 0;
|
|
153
|
+
return send(res, 200, { ok: true });
|
|
154
|
+
}
|
|
155
|
+
if (list === log) {
|
|
156
|
+
const since = Number(q.get('since') ?? 0), part = q.get('path');
|
|
157
|
+
return send(res, 200, log.filter((s) => s.t >= since && onHost(q.get('host')?.toLowerCase(), s.host) && (!part || s.path.includes(part))));
|
|
158
|
+
}
|
|
159
|
+
if (method !== 'POST' || !body || typeof body !== 'object')
|
|
160
|
+
return send(res, 400, { error: 'tapcheck stub: POST a JSON object' });
|
|
161
|
+
list.push(list === fails ? { ...body, times: body.times ?? 1 } : body);
|
|
162
|
+
return send(res, 200, { ok: true });
|
|
163
|
+
}
|
|
164
|
+
/** Takes the first entry matching host and path (a part of it) out of a queue; a fail rule stays until its `times` are used. */
|
|
165
|
+
function take(list, host, path) {
|
|
166
|
+
const i = list.findIndex((r) => onHost(r.host?.toLowerCase(), host) && (!r.path || path.includes(r.path)));
|
|
167
|
+
if (i < 0)
|
|
168
|
+
return undefined;
|
|
169
|
+
const r = list[i];
|
|
170
|
+
if (r.times === undefined || (r.times > 0 && --r.times === 0))
|
|
171
|
+
list.splice(i, 1);
|
|
172
|
+
return r;
|
|
173
|
+
}
|
|
174
|
+
const server = createServer(async (req, res) => {
|
|
175
|
+
const t = Date.now();
|
|
176
|
+
const chunks = [];
|
|
177
|
+
for await (const c of req)
|
|
178
|
+
chunks.push(c);
|
|
179
|
+
const text = Buffer.concat(chunks).toString('utf8');
|
|
180
|
+
let body = text;
|
|
181
|
+
if (/json/.test(req.headers['content-type'] ?? '')) {
|
|
182
|
+
try {
|
|
183
|
+
body = JSON.parse(text);
|
|
184
|
+
}
|
|
185
|
+
catch { /* kept as text */ }
|
|
186
|
+
}
|
|
187
|
+
const u = new URL(req.url ?? '/', 'http://stub');
|
|
188
|
+
const { host, path } = target(req.headers, u.pathname, port);
|
|
189
|
+
const method = req.method ?? 'GET';
|
|
190
|
+
if (!host && path.startsWith('/_tapcheck/')) {
|
|
191
|
+
control(method, path, u.searchParams, body, res);
|
|
192
|
+
return;
|
|
193
|
+
} // not logged
|
|
194
|
+
let status;
|
|
195
|
+
const fail = take(fails, host, path);
|
|
196
|
+
const forced = !!fail || /tapcheck-fail/i.test(req.url + text);
|
|
197
|
+
const reply = forced ? undefined : take(replies, host, path);
|
|
198
|
+
if (forced)
|
|
199
|
+
status = send(res, fail?.status ?? 500, fail?.body ?? { error: 'tapcheck stub: forced failure' });
|
|
200
|
+
else if (reply)
|
|
201
|
+
status = send(res, reply.status ?? 200, reply.body ?? reply.json ?? {});
|
|
202
|
+
else {
|
|
203
|
+
const r = match(cfg.rules, host, method, path);
|
|
204
|
+
if (r?.delayMs)
|
|
205
|
+
await new Promise((done) => setTimeout(done, r.delayMs));
|
|
206
|
+
const type = r?.file ? { 'content-type': TYPES[r.file.split('.').pop()] ?? 'application/octet-stream' } : {};
|
|
207
|
+
status = send(res, r?.status ?? 200, r?.file ? readFileSync(resolve(root, r.file)) : r?.body ?? r?.json ?? {}, { ...type, ...r?.headers });
|
|
208
|
+
}
|
|
209
|
+
const seen = { t, method, host, path, query: Object.fromEntries(u.searchParams), body: typeof body === 'string' ? body.slice(0, 65_536) : body, status, ms: Date.now() - t,
|
|
210
|
+
headers: Object.fromEntries(Object.entries(req.headers).filter(([k]) => !SECRET.test(k)).map(([k, v]) => [k, String(v)])) };
|
|
211
|
+
keep(seen);
|
|
212
|
+
});
|
|
213
|
+
function keep(seen) {
|
|
214
|
+
log.push(seen);
|
|
215
|
+
if (log.length > 5000)
|
|
216
|
+
log.shift();
|
|
217
|
+
appendFileSync(file, JSON.stringify(seen) + '\n');
|
|
218
|
+
}
|
|
219
|
+
await new Promise((done, failed) => {
|
|
220
|
+
server.once('error', (e) => failed(new Error(`The stub can't listen on 127.0.0.1:${cfg.port} (stub.port): ${e.message}`)));
|
|
221
|
+
server.listen(cfg.port, '127.0.0.1', done);
|
|
222
|
+
});
|
|
223
|
+
port = server.address().port;
|
|
224
|
+
const d = cfg.dns, udp = d ? createSocket('udp4') : null;
|
|
225
|
+
if (d && udp) {
|
|
226
|
+
udp.on('message', (msg, from) => {
|
|
227
|
+
const q = dnsQuestion(msg);
|
|
228
|
+
if (!q)
|
|
229
|
+
return;
|
|
230
|
+
const over = dnsOver.get(`${q.name}|${q.type}`), gone = !over && q.name.includes('tapcheck-fail');
|
|
231
|
+
const values = over ?? (gone || !q.type ? [] : d.records.filter((r) => r.name === q.name && r.type === q.type).flatMap((r) => r.values));
|
|
232
|
+
if (!over && !gone && !values.length && q.type === 'A' && d.defaultA)
|
|
233
|
+
values.push(d.defaultA);
|
|
234
|
+
udp.send(dnsReply(msg, q, values, gone ? 3 : 0), from.port, from.address);
|
|
235
|
+
keep({ t: Date.now(), method: 'DNS', host: q.name, path: q.type, query: {}, headers: {}, body: values, status: gone ? 3 : 0, ms: 0 });
|
|
236
|
+
});
|
|
237
|
+
await new Promise((done, failed) => {
|
|
238
|
+
udp.once('error', (e) => { server.close(); failed(new Error(`The stub's DNS can't listen on 127.0.0.1:${d.port} (stub.dns.port): ${e.message}`)); });
|
|
239
|
+
udp.bind(d.port, '127.0.0.1', done);
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
return { url: `http://127.0.0.1:${port}`, dns: udp ? `127.0.0.1:${udp.address().port}` : undefined,
|
|
243
|
+
stop: () => new Promise((done) => { udp?.close(); server.closeAllConnections(); server.close(() => done()); }) };
|
|
244
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Accessibility (measured, no Jev): axe-core (WCAG 2.2 A/AA rules) on every screen at every viewport, critical and
|
|
3
|
+
* serious violations fail, moderate ones warn; and a keyboard pass on desktop-sized viewports: Tab moves focus through
|
|
4
|
+
* the page, the focused control shows a visible focus style, and the page declares its language.
|
|
5
|
+
*/
|
|
6
|
+
import { readFileSync, writeFileSync } from 'node:fs';
|
|
7
|
+
import { createRequire } from 'node:module';
|
|
8
|
+
import { context, open, resolve, SessionExpired, slug } from '../browser.js';
|
|
9
|
+
export const AXE = readFileSync(createRequire(import.meta.url).resolve('axe-core/axe.min.js'), 'utf8');
|
|
10
|
+
const TABS = 12;
|
|
11
|
+
export async function run(r) {
|
|
12
|
+
const S = 'a11y';
|
|
13
|
+
const screens = r.side.screens.length ? r.side.screens : [{ name: 'Home', path: '/' }];
|
|
14
|
+
const all = {};
|
|
15
|
+
for (const vp of r.cfg.viewports) {
|
|
16
|
+
const ctx = await context(r, vp, true, true); // axe is injected, so the page's own CSP is set aside
|
|
17
|
+
const page = await ctx.newPage();
|
|
18
|
+
try {
|
|
19
|
+
for (const s of screens) {
|
|
20
|
+
const where = `${s.name} · ${vp.name}`;
|
|
21
|
+
try {
|
|
22
|
+
const path = await resolve(r, page, s);
|
|
23
|
+
if (!path) {
|
|
24
|
+
r.record({ suite: S, where, check: 'screen reachable', status: 'warn', detail: 'no link to it found' });
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
await open(r, page, path);
|
|
28
|
+
await page.addScriptTag({ content: AXE });
|
|
29
|
+
const res = await page.evaluate(() => window.axe.run(document, { runOnly: { type: 'tag', values: ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22aa'] } }));
|
|
30
|
+
all[`${slug(s.name)}-${vp.name}`] = res.violations.map((x) => ({ id: x.id, impact: x.impact, help: x.help, nodes: x.nodes.slice(0, 5).map((n) => n.target) }));
|
|
31
|
+
for (const impact of ['critical', 'serious', 'moderate']) {
|
|
32
|
+
const v = res.violations.filter((x) => x.impact === impact);
|
|
33
|
+
r.record({ suite: S, where, check: `axe: no ${impact} violations`, status: v.length ? (impact === 'moderate' ? 'warn' : 'fail') : 'pass',
|
|
34
|
+
detail: v.map((x) => `${x.id} ×${x.nodes.length}`).join(', ') || undefined });
|
|
35
|
+
}
|
|
36
|
+
if (vp.mobile)
|
|
37
|
+
continue;
|
|
38
|
+
// Keyboard: does Tab move focus, and can a person see where it is?
|
|
39
|
+
await page.evaluate(() => document.activeElement?.blur());
|
|
40
|
+
const stops = [];
|
|
41
|
+
for (let i = 0; i < TABS; i++) {
|
|
42
|
+
await page.keyboard.press('Tab');
|
|
43
|
+
stops.push(await page.evaluate(() => {
|
|
44
|
+
const el = document.activeElement;
|
|
45
|
+
if (!el || el === document.body)
|
|
46
|
+
return { label: '(body)', visible: false };
|
|
47
|
+
const st = getComputedStyle(el);
|
|
48
|
+
const ring = (st.outlineStyle !== 'none' && parseFloat(st.outlineWidth) > 0) || (!!st.boxShadow && st.boxShadow !== 'none');
|
|
49
|
+
return { label: `${el.tagName.toLowerCase()} "${(el.innerText || el.getAttribute('aria-label') || '').trim().slice(0, 30)}"`, visible: ring };
|
|
50
|
+
}));
|
|
51
|
+
}
|
|
52
|
+
const moved = new Set(stops.map((x) => x.label)).size;
|
|
53
|
+
const focusable = await page.$$eval('a[href], button, input:not([type=hidden]), select, textarea, [tabindex]:not([tabindex="-1"])', (els) => els.length);
|
|
54
|
+
// A page with one or two controls can't show more distinct stops than it has.
|
|
55
|
+
r.record({ suite: S, where, check: 'keyboard: Tab moves focus', status: moved > Math.min(2, focusable - 1) ? 'pass' : 'fail', detail: `${moved} distinct stops in ${TABS} presses, ${focusable} focusable` });
|
|
56
|
+
const unseen = stops.filter((x) => x.label !== '(body)' && !x.visible);
|
|
57
|
+
r.record({ suite: S, where, check: 'keyboard: focus is visible', status: unseen.length ? 'fail' : 'pass', detail: unseen.slice(0, 4).map((x) => x.label).join(', ') || undefined });
|
|
58
|
+
const lang = await page.evaluate(() => document.documentElement.lang);
|
|
59
|
+
r.record({ suite: S, where, check: 'page language set', status: lang ? 'pass' : 'fail', detail: lang || 'no lang attribute' });
|
|
60
|
+
}
|
|
61
|
+
catch (e) {
|
|
62
|
+
if (e instanceof SessionExpired)
|
|
63
|
+
throw e;
|
|
64
|
+
r.record({ suite: S, where, check: 'audit ran', status: 'fail', detail: e.message.slice(0, 200) });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
finally {
|
|
69
|
+
await ctx.close();
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
writeFileSync(`${r.dir}/axe.json`, JSON.stringify(all, null, 2));
|
|
73
|
+
}
|