@miracle352/statute 0.0.0-stage → 0.3.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/LICENSE +21 -0
- package/README.md +319 -2
- package/action.yml +356 -0
- package/bin/hook.js +81 -0
- package/bin/init.js +142 -0
- package/bin/mcp.js +166 -0
- package/bin/scope.js +78 -0
- package/bin/shots.js +52 -0
- package/bin/statute.js +362 -0
- package/examples/expect/newsletter_test.md +22 -0
- package/examples/expect/output-newsletter/.internal/execution.json +2053 -0
- package/examples/expect/output-newsletter/.internal/meta.json +39 -0
- package/examples/expect/output-newsletter/.internal/steps/1-d2368411/flows/0/actions.ndjson +2 -0
- package/examples/expect/output-newsletter/.internal/steps/2-a9e761f8/flows/0/actions.ndjson +6 -0
- package/examples/expect/output-newsletter/.internal/steps/3-63305a01/flows/0/actions.ndjson +2 -0
- package/examples/expect/output-newsletter/Result.md +21 -0
- package/examples/expect/search_test.md +20 -0
- package/laws/README.md +24 -0
- package/laws/accept_still_works_test.md +12 -0
- package/laws/cancel_as_easy_as_signup_test.md +15 -0
- package/laws/output-reject_means_reject/.internal/execution.json +1279 -0
- package/laws/output-reject_means_reject/.internal/meta.json +18 -0
- package/laws/output-reject_means_reject/.internal/steps/1-567cc234/flows/0/actions.ndjson +6 -0
- package/laws/output-reject_means_reject/.internal/steps/2-e3c06462/flows/0/actions.ndjson +1 -0
- package/laws/output-reject_means_reject/.internal/steps/3-3040a29b/flows/0/actions.ndjson +2 -0
- package/laws/output-reject_means_reject/Result.md +21 -0
- package/laws/price_shown_is_price_paid_test.md +12 -0
- package/laws/reject_means_reject_test.md +15 -0
- package/package.json +65 -4
- package/replays/cancel-demo-shop/evidence/cancel-1794754943192.evidence +0 -0
- package/replays/cancel-demo-shop/evidence/cancel-1794755110410.evidence +0 -0
- package/replays/cancel-demo-shop/loop.json +32 -0
- package/replays/demo-shop/evidence/consent-1794751413210.evidence +0 -0
- package/replays/demo-shop/evidence/consent-1794751523524.evidence +0 -0
- package/replays/demo-shop/evidence/consent-accept-1794751588395.evidence +0 -0
- package/replays/demo-shop/loop.json +40 -0
- package/replays/haxcms/evidence/consent-1794831086682.evidence +0 -0
- package/replays/haxcms/evidence/consent-1794831262757.evidence +0 -0
- package/replays/haxcms/evidence/consent-accept-1794831347132.evidence +0 -0
- package/replays/haxcms/loop.json +56 -0
- package/replays/in-the-wake-check/consent.json +67 -0
- package/replays/in-the-wake-check/consent.md +32 -0
- package/replays/kane-testmd-demo-shop/evidence/consent-1794935266000.evidence +0 -0
- package/replays/kane-testmd-demo-shop/loop.json +18 -0
- package/replays/lumen-pr-2/evidence/consent-1794929771799.evidence +0 -0
- package/replays/lumen-pr-2/evidence/consent-1794929845913.evidence +0 -0
- package/replays/lumen-pr-2/evidence/consent-accept-1794929886905.evidence +0 -0
- package/replays/lumen-pr-2/loop.json +57 -0
- package/replays/newsletter-expect/evidence/newsletter_test-round1-1795518837738.evidence +0 -0
- package/replays/newsletter-expect/evidence/newsletter_test-round2-1795519079029.evidence +0 -0
- package/replays/newsletter-expect/loop.json +99 -0
- package/replays/price-demo-shop/evidence/price-1794837093949.evidence +0 -0
- package/replays/price-demo-shop/evidence/price-1794837311639.evidence +0 -0
- package/replays/price-demo-shop/loop.json +43 -0
- package/rules/trackers.json +61 -0
- package/site/assets/fonts/OFL-archivo.txt +93 -0
- package/site/assets/fonts/OFL-geist.txt +93 -0
- package/site/assets/fonts/OFL-instrument-serif.txt +93 -0
- package/site/assets/fonts/archivo.woff2 +0 -0
- package/site/assets/fonts/geist.woff2 +0 -0
- package/site/assets/fonts/instrument-serif-italic.woff2 +0 -0
- package/site/assets/fonts/instrument-serif.woff2 +0 -0
- package/site/assets/fonts/inter.woff2 +0 -0
- package/site/assets/fonts/jetbrains-mono.woff2 +0 -0
- package/skill/statute/SKILL.md +57 -0
- package/src/agent.js +70 -0
- package/src/app.js +41 -0
- package/src/evidence.js +80 -0
- package/src/expect-cli.js +296 -0
- package/src/expect-view.js +79 -0
- package/src/expect.js +392 -0
- package/src/infer.js +32 -0
- package/src/kane.js +124 -0
- package/src/pack.js +128 -0
- package/src/packs/cancel.js +83 -0
- package/src/packs/consent-accept.js +57 -0
- package/src/packs/consent.js +237 -0
- package/src/packs/price.js +104 -0
- package/src/page.js +360 -0
- package/src/report.js +59 -0
- package/src/zip.js +38 -0
package/src/expect.js
ADDED
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
// Expectations: what a page must and must not do while Kane uses it, checked
|
|
2
|
+
// against Kane's sealed evidence by plain code. Kane's own verdict says the
|
|
3
|
+
// steps ran; these rules say what the page did underneath (requests, cookies,
|
|
4
|
+
// data leaving the site, errors, numbers, effort).
|
|
5
|
+
//
|
|
6
|
+
// Write them in the test file's frontmatter, one per line:
|
|
7
|
+
//
|
|
8
|
+
// expect:
|
|
9
|
+
// - no request to a tracker after "Refuse cookies"
|
|
10
|
+
// - no visitor ID sent to a tracker after "Refuse cookies"
|
|
11
|
+
// - no tracker cookie after "Refuse cookies"
|
|
12
|
+
// - what was typed in "Sign up" never leaves this site
|
|
13
|
+
// - text "jane@example.com" never leaves this site
|
|
14
|
+
// - value of $email never leaves this site
|
|
15
|
+
// - no request to google-analytics.com
|
|
16
|
+
// - no request to a third party before "Accept"
|
|
17
|
+
// - no server errors
|
|
18
|
+
// - no failed requests to this site
|
|
19
|
+
// - no console errors
|
|
20
|
+
// - value $checkout_total is at most $product_price plus $shipping
|
|
21
|
+
// - clicks in "Cancel" at most clicks in "Subscribe" plus 1
|
|
22
|
+
//
|
|
23
|
+
// Steps are named by their "## heading" in the test file. "after" and
|
|
24
|
+
// "before" mean after or before the last thing Kane did in that step.
|
|
25
|
+
const crypto = require("crypto");
|
|
26
|
+
const consent = require("./packs/consent");
|
|
27
|
+
const trackers = require("../rules/trackers.json");
|
|
28
|
+
|
|
29
|
+
const cookieRes = trackers.cookies.map((c) => new RegExp(c));
|
|
30
|
+
const isTrackerCookie = (n) => cookieRes.some((r) => r.test(n));
|
|
31
|
+
const STEP = `"([^"]+)"`;
|
|
32
|
+
const WHEN = `(?:\\s+(after|before|during)\\s+${STEP})?`;
|
|
33
|
+
|
|
34
|
+
// ---------- the grammar ----------
|
|
35
|
+
// Each rule: a pattern and a function that judges it against the pack.
|
|
36
|
+
const RULES = [
|
|
37
|
+
{ re: new RegExp(`^no request to (.+?)${WHEN}$`, "i"), kind: "request" },
|
|
38
|
+
{ re: new RegExp(`^no visitor id sent to (?:a )?trackers?${WHEN}$`, "i"), kind: "visitorId" },
|
|
39
|
+
{ re: new RegExp(`^no tracker cookies?${WHEN}$`, "i"), kind: "cookie" },
|
|
40
|
+
{ re: new RegExp(`^what was typed in ${STEP} never leaves this site$`, "i"), kind: "typed" },
|
|
41
|
+
{ re: new RegExp(`^text ${STEP} never leaves this site$`, "i"), kind: "text" },
|
|
42
|
+
{ re: /^value of \$([a-z_][\w]*) never leaves this site$/i, kind: "variable" },
|
|
43
|
+
{ re: /^no server errors$/i, kind: "server" },
|
|
44
|
+
{ re: /^no failed requests to this site$/i, kind: "failed" },
|
|
45
|
+
{ re: /^no console errors$/i, kind: "console" },
|
|
46
|
+
{ re: /^value \$([a-z_]\w*) (equals|is at most|is at least) (\$[a-z_]\w*|-?\d+(?:\.\d+)?)(?: plus (\$[a-z_]\w*|\d+(?:\.\d+)?))?$/i, kind: "compare" },
|
|
47
|
+
{ re: new RegExp(`^clicks in ${STEP} at most clicks in ${STEP}(?: plus (\\d+))?$`, "i"), kind: "clicks" },
|
|
48
|
+
];
|
|
49
|
+
|
|
50
|
+
function parse(line) {
|
|
51
|
+
const s = String(line).trim().replace(/\s+/g, " ").replace(/[“”]/g, '"');
|
|
52
|
+
for (const r of RULES) {
|
|
53
|
+
const m = s.match(r.re);
|
|
54
|
+
if (m) return { text: s, kind: r.kind, m };
|
|
55
|
+
}
|
|
56
|
+
return { text: s, kind: "unknown", m: null };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// ---------- helpers over the pack ----------
|
|
60
|
+
// Registrable-ish domain: "a.b.example.co.uk" -> "example.co.uk"; localhost stays.
|
|
61
|
+
function site(host) {
|
|
62
|
+
const h = String(host || "").toLowerCase();
|
|
63
|
+
if (!h.includes(".") || /^\d+\.\d+\.\d+\.\d+$/.test(h)) return h;
|
|
64
|
+
const p = h.split(".");
|
|
65
|
+
const two = p.slice(-2).join(".");
|
|
66
|
+
// Shared hosting suffixes: each app on them is its own site.
|
|
67
|
+
if (p.length > 2 && (/^(co|com|org|net|gov|ac|edu)\.[a-z]{2}$/.test(two) || /^(up\.railway\.app|railway\.app|vercel\.app|netlify\.app|github\.io|herokuapp\.com|onrender\.com|pages\.dev|workers\.dev|fly\.dev|web\.app|firebaseapp\.com|azurewebsites\.net|glitch\.me)$/.test(p.slice(-3).join(".")) || /^(railway\.app|vercel\.app|netlify\.app|github\.io|herokuapp\.com|onrender\.com|pages\.dev|workers\.dev|fly\.dev|web\.app|firebaseapp\.com|azurewebsites\.net|glitch\.me)$/.test(two))) {
|
|
68
|
+
const sfx = /^up\.railway\.app$/.test(p.slice(-3).join(".")) ? 3 : 2;
|
|
69
|
+
return p.slice(-(sfx + 1)).join(".");
|
|
70
|
+
}
|
|
71
|
+
return two;
|
|
72
|
+
}
|
|
73
|
+
const hostOf = (u) => { try { return new URL(u).hostname; } catch { return ""; } };
|
|
74
|
+
|
|
75
|
+
// The site under test: the first page Kane opened.
|
|
76
|
+
function homeSite(pack) {
|
|
77
|
+
for (const a of pack.actions) {
|
|
78
|
+
const u = a.params && a.params.url;
|
|
79
|
+
if (a.type === "navigate" && u && /^https?:/.test(u)) return site(hostOf(u));
|
|
80
|
+
}
|
|
81
|
+
for (const r of pack.requests) {
|
|
82
|
+
let u;
|
|
83
|
+
try { u = new URL(r.url); } catch { continue; }
|
|
84
|
+
if (/^https?:$/.test(u.protocol) && !consent.matchDomain(u)) return site(u.hostname);
|
|
85
|
+
}
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// A step by its heading; falls back to Kane's own action descriptions for
|
|
90
|
+
// single runs that have no test file.
|
|
91
|
+
function findStep(pack, name) {
|
|
92
|
+
const want = name.toLowerCase();
|
|
93
|
+
const sec = pack.sections.find((s) => s.title.toLowerCase() === want) || pack.sections.find((s) => s.title.toLowerCase().includes(want));
|
|
94
|
+
if (sec && sec.actions.length) {
|
|
95
|
+
const times = sec.actions.map((a) => a.time).filter(Boolean);
|
|
96
|
+
return { label: sec.title, section: sec, start: Math.min(...times), end: Math.max(...times) };
|
|
97
|
+
}
|
|
98
|
+
if (sec) return { label: sec.title, section: sec, start: null, end: null };
|
|
99
|
+
const a = pack.actions.find((x) => `${x.instruction} ${x.intent}`.toLowerCase().includes(want));
|
|
100
|
+
if (a) return { label: a.instruction, section: null, start: a.time, end: a.time };
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Requests inside a time window given by "after/before/during <step>".
|
|
105
|
+
function windowed(pack, items, when, stepName) {
|
|
106
|
+
if (!when) return { items, scope: "during the whole run" };
|
|
107
|
+
const step = findStep(pack, stepName);
|
|
108
|
+
if (!step) return { error: `there is no step called "${stepName}" in this run` };
|
|
109
|
+
if (when.toLowerCase() === "during") {
|
|
110
|
+
const inSec = step.section ? items.filter((x) => x.section === step.section.index) : items.filter((x) => x.time >= step.start && x.time <= step.end);
|
|
111
|
+
return { items: inSec, scope: `during "${step.label}"` };
|
|
112
|
+
}
|
|
113
|
+
if (step.end == null) return { error: `Kane recorded no actions in "${step.label}", so there is no moment to measure from` };
|
|
114
|
+
const after = when.toLowerCase() === "after";
|
|
115
|
+
return { items: items.filter((x) => x.time != null && (after ? x.time > step.end : x.time < step.end)), scope: `${after ? "after" : "before"} "${step.label}"` };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// Same counting as the consent law: Consent Mode "denied" pings and the bare
|
|
119
|
+
// Tag Manager library carry no measurement, so they are listed, not counted.
|
|
120
|
+
function trackerHit(r) {
|
|
121
|
+
let u;
|
|
122
|
+
try { u = new URL(r.url); } catch { return null; }
|
|
123
|
+
const tracker = consent.matchDomain(u);
|
|
124
|
+
if (!tracker) return null;
|
|
125
|
+
const denied = consent.consentModeDenied(u);
|
|
126
|
+
const loader = /(^|\.)googletagmanager\.com$/.test(u.hostname) && /^\/(gtm\.js|gtag\/js|gtag\/destination)$/.test(u.pathname);
|
|
127
|
+
return { tracker, url: u, counted: !denied && !loader };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const short = (u) => { try { const x = new URL(u); return x.host + x.pathname; } catch { return String(u).slice(0, 80); } };
|
|
131
|
+
const sample = (list, f, n = 3) => list.slice(0, n).map(f);
|
|
132
|
+
const plural = (n, w) => `${n} ${w}${n === 1 ? "" : "s"}`;
|
|
133
|
+
|
|
134
|
+
// How a value can appear in a request: as is, URL-encoded, Base64, or hashed
|
|
135
|
+
// (ad pixels send SHA-256 of a lower-cased email as "advanced matching").
|
|
136
|
+
function forms(value) {
|
|
137
|
+
const v = String(value).trim();
|
|
138
|
+
if (v.length < 4) return [];
|
|
139
|
+
const norm = v.toLowerCase();
|
|
140
|
+
const sha = (s) => crypto.createHash("sha256").update(s).digest("hex");
|
|
141
|
+
const out = [
|
|
142
|
+
{ how: "as typed", needle: norm },
|
|
143
|
+
{ how: "URL-encoded", needle: encodeURIComponent(v).toLowerCase() },
|
|
144
|
+
{ how: "Base64", needle: Buffer.from(v).toString("base64").toLowerCase() },
|
|
145
|
+
{ how: "SHA-256 hashed", needle: sha(norm) },
|
|
146
|
+
];
|
|
147
|
+
if (norm !== v) out.push({ how: "SHA-256 hashed", needle: sha(v) });
|
|
148
|
+
return out.filter((f, i, a) => a.findIndex((g) => g.needle === f.needle) === i);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// A request as sent, then decoded up to three times ("+" read as a space, the
|
|
152
|
+
// way forms encode it): tags often wrap a page URL inside their own, so a
|
|
153
|
+
// search for "pregnancy test" arrives as pregnancy%252Btest.
|
|
154
|
+
function decodedLayers(raw) {
|
|
155
|
+
const dec = (u) => u.replace(/(%[0-9a-f]{2})+/gi, (m) => { try { return decodeURIComponent(m); } catch { return m; } });
|
|
156
|
+
const out = [raw.toLowerCase()];
|
|
157
|
+
let cur = raw;
|
|
158
|
+
for (let i = 0; i < 3; i++) {
|
|
159
|
+
const next = dec(cur.replace(/\+/g, " "));
|
|
160
|
+
if (next === cur) break;
|
|
161
|
+
out.push(next.toLowerCase());
|
|
162
|
+
cur = next;
|
|
163
|
+
}
|
|
164
|
+
return out;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function leaks(pack, values) {
|
|
168
|
+
const home = homeSite(pack);
|
|
169
|
+
const found = [];
|
|
170
|
+
for (const r of pack.requests) {
|
|
171
|
+
const host = hostOf(r.url);
|
|
172
|
+
if (!host || site(host) === home) continue;
|
|
173
|
+
const layers = decodedLayers(`${r.url} ${r.body || ""}`);
|
|
174
|
+
let hit = null;
|
|
175
|
+
for (const v of values) {
|
|
176
|
+
for (let i = 0; i < layers.length && !hit; i++) {
|
|
177
|
+
const f = forms(v).find((x) => layers[i].includes(x.needle));
|
|
178
|
+
if (f) hit = { how: i && f.how === "as typed" ? "URL-encoded" : f.how, value: v };
|
|
179
|
+
}
|
|
180
|
+
if (hit) break;
|
|
181
|
+
}
|
|
182
|
+
if (hit) found.push({ host, url: short(r.url), time: r.iso, how: hit.how, value: hit.value });
|
|
183
|
+
}
|
|
184
|
+
return { home, found };
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// What Kane typed: the value in the action's parameters, or the quoted text
|
|
188
|
+
// in its own description ("Typing "jane@x.com" into Email").
|
|
189
|
+
function typedValues(actions) {
|
|
190
|
+
const out = [];
|
|
191
|
+
for (const a of actions) {
|
|
192
|
+
if (!/type|fill|input|enter|press_sequentially/i.test(a.type || "")) continue;
|
|
193
|
+
const p = a.params || {};
|
|
194
|
+
const v = p.value ?? p.text ?? p.input ?? p.content ?? p.keys;
|
|
195
|
+
if (typeof v === "string" && v.trim() && !/^\{\{.*\}\}$/.test(v.trim())) { out.push(v); continue; }
|
|
196
|
+
const q = String(a.instruction).match(/"([^"]{4,})"|'([^']{4,})'/);
|
|
197
|
+
if (q) out.push(q[1] || q[2]);
|
|
198
|
+
}
|
|
199
|
+
return [...new Set(out)];
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function variables(pack) {
|
|
203
|
+
const v = {};
|
|
204
|
+
for (const a of pack.actions) {
|
|
205
|
+
if (!a.variable || a.value == null || a.status === "failed") continue;
|
|
206
|
+
v[String(a.variable).toLowerCase()] = a.value;
|
|
207
|
+
}
|
|
208
|
+
return v;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// "€1.234,50" / "$1,234.50" / "49" -> number
|
|
212
|
+
function money(s) {
|
|
213
|
+
const m = String(s ?? "").replace(/ /g, " ").match(/-?\d[\d.,\s]*/);
|
|
214
|
+
if (!m) return null;
|
|
215
|
+
let x = m[0].replace(/\s/g, "");
|
|
216
|
+
const c = x.lastIndexOf(","), d = x.lastIndexOf(".");
|
|
217
|
+
if (c > d) x = x.replace(/\./g, "").replace(",", ".");
|
|
218
|
+
else x = x.replace(/,/g, "");
|
|
219
|
+
const n = Number(x);
|
|
220
|
+
return Number.isFinite(n) ? n : null;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const INTERACTIVE = new Set(["click", "type", "fill", "select", "check", "uncheck", "press", "tap"]);
|
|
224
|
+
const noise = (s) => /favicon\.ico/i.test(s);
|
|
225
|
+
|
|
226
|
+
// Tags often send a few seconds after a page loads. Kane records network
|
|
227
|
+
// traffic per step, and nothing between steps, so a page load near the end of
|
|
228
|
+
// a step can be followed by requests nobody recorded. A clean network result
|
|
229
|
+
// only counts if the seconds after the last page load were recorded.
|
|
230
|
+
const SETTLE_MS = 6000;
|
|
231
|
+
const NETWORK_KINDS = new Set(["request", "visitorId", "cookie", "typed", "text", "variable"]);
|
|
232
|
+
function coverage(pack) {
|
|
233
|
+
return pack.sections.map((s) => {
|
|
234
|
+
const t = [...s.actions.map((a) => a.time), ...s.requests.map((r) => r.time)].filter(Boolean);
|
|
235
|
+
return t.length ? [Math.min(...t), Math.max(...t)] : null;
|
|
236
|
+
}).filter(Boolean).sort((a, b) => a[0] - b[0]);
|
|
237
|
+
}
|
|
238
|
+
function recordedMs(intervals, from, to) {
|
|
239
|
+
let got = 0;
|
|
240
|
+
for (const [a, b] of intervals) got += Math.max(0, Math.min(b, to) - Math.max(a, from));
|
|
241
|
+
return got;
|
|
242
|
+
}
|
|
243
|
+
function settle(pack) {
|
|
244
|
+
const home = homeSite(pack);
|
|
245
|
+
// Page loads: HTML documents from the site, GET or POST (a form submit is a page load too).
|
|
246
|
+
const docs = pack.requests.filter((r) => site(hostOf(r.url)) === home && (r.mime ? /html/i.test(r.mime) : r.method === "GET" && !/\.(js|css|png|jpe?g|gif|svg|webp|ico|woff2?|json)(\?|$)/i.test(r.url)));
|
|
247
|
+
if (!docs.length) return null;
|
|
248
|
+
const last = docs.reduce((a, b) => ((b.time || 0) > (a.time || 0) ? b : a));
|
|
249
|
+
const covered = recordedMs(coverage(pack), last.time, last.time + SETTLE_MS);
|
|
250
|
+
return covered < SETTLE_MS - 250 ? { gap: covered, url: last.url } : null;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// ---------- judging ----------
|
|
254
|
+
function judgeRule(pack, r) {
|
|
255
|
+
const pass = (detail) => ({ rule: r.text, status: "pass", detail });
|
|
256
|
+
const fail = (detail, evidence = []) => ({ rule: r.text, status: "fail", detail, evidence });
|
|
257
|
+
const unknown = (detail) => ({ rule: r.text, status: "unknown", detail });
|
|
258
|
+
const m = r.m;
|
|
259
|
+
|
|
260
|
+
switch (r.kind) {
|
|
261
|
+
case "request": {
|
|
262
|
+
const target = m[1].trim().toLowerCase();
|
|
263
|
+
const w = windowed(pack, pack.requests, m[2], m[3]);
|
|
264
|
+
if (w.error) return unknown(w.error);
|
|
265
|
+
let hits;
|
|
266
|
+
if (/^(a |any )?trackers?$/.test(target)) {
|
|
267
|
+
hits = w.items.map((x) => ({ r: x, h: trackerHit(x) })).filter((x) => x.h && x.h.counted).map((x) => x.r);
|
|
268
|
+
} else if (/^(a |any )?third[- ]part(y|ies)$|^(any )?other sites?$/.test(target)) {
|
|
269
|
+
const home = homeSite(pack);
|
|
270
|
+
if (!home) return unknown("could not tell which site Kane was testing");
|
|
271
|
+
hits = w.items.filter((x) => { const h = hostOf(x.url); return h && site(h) !== home; });
|
|
272
|
+
} else {
|
|
273
|
+
const host = target.replace(/^https?:\/\//, "").replace(/\/.*$/, "");
|
|
274
|
+
hits = w.items.filter((x) => { const h = hostOf(x.url).toLowerCase(); return h === host || h.endsWith("." + host); });
|
|
275
|
+
}
|
|
276
|
+
if (!pack.requests.length) return unknown("the evidence pack has no network recording");
|
|
277
|
+
return hits.length
|
|
278
|
+
? fail(`${plural(hits.length, "request")} ${w.scope}: ${sample(hits, (x) => `${x.method} ${short(x.url)}`).join("; ")}${hits.length > 3 ? "; ..." : ""}`, hits.map((x) => ({ time: x.iso, method: x.method, url: x.url, step: x.section })))
|
|
279
|
+
: pass(`none of the ${plural(w.items.length, "request")} ${w.scope} matched`);
|
|
280
|
+
}
|
|
281
|
+
case "visitorId": {
|
|
282
|
+
const w = windowed(pack, pack.requests, m[1], m[2]);
|
|
283
|
+
if (w.error) return unknown(w.error);
|
|
284
|
+
const ids = [];
|
|
285
|
+
for (const x of w.items) {
|
|
286
|
+
const h = trackerHit(x);
|
|
287
|
+
if (!h || !h.counted) continue;
|
|
288
|
+
const id = consent.visitorId(h.url);
|
|
289
|
+
if (id) ids.push({ x, id });
|
|
290
|
+
}
|
|
291
|
+
const distinct = [...new Set(ids.map((i) => `${i.id.kind}: ${i.id.value}`))];
|
|
292
|
+
return ids.length
|
|
293
|
+
? fail(`${plural(ids.length, "request")} ${w.scope} carried a visitor ID (${distinct.join("; ")})`, ids.map((i) => ({ time: i.x.iso, url: i.x.url, id: i.id })))
|
|
294
|
+
: pass(`no visitor ID went to a tracker ${w.scope}`);
|
|
295
|
+
}
|
|
296
|
+
case "cookie": {
|
|
297
|
+
const w = windowed(pack, pack.requests, m[1], m[2]);
|
|
298
|
+
if (w.error) return unknown(w.error);
|
|
299
|
+
const names = new Set();
|
|
300
|
+
for (const x of w.items) for (const c of [...x.setCookies, ...x.sentCookies]) if (isTrackerCookie(c)) names.add(c);
|
|
301
|
+
return names.size ? fail(`tracker cookies present ${w.scope}: ${[...names].join(", ")}`) : pass(`no tracker cookie ${w.scope}`);
|
|
302
|
+
}
|
|
303
|
+
case "typed": {
|
|
304
|
+
const step = findStep(pack, m[1]);
|
|
305
|
+
if (!step) return unknown(`there is no step called "${m[1]}" in this run`);
|
|
306
|
+
const values = typedValues(step.section ? step.section.actions : pack.actions.filter((a) => a.time >= step.start && a.time <= step.end));
|
|
307
|
+
if (!values.length) return unknown(`Kane typed nothing it recorded in "${step.label}"`);
|
|
308
|
+
const { home, found } = leaks(pack, values);
|
|
309
|
+
if (!home) return unknown("could not tell which site Kane was testing");
|
|
310
|
+
return found.length
|
|
311
|
+
? fail(`what was typed in "${step.label}" reached ${plural(new Set(found.map((f) => f.host)).size, "other host")}: ${sample(found, (f) => `${f.host} (${f.how})`).join("; ")}`, found)
|
|
312
|
+
: pass(`${plural(values.length, "typed value")} stayed on ${home}`);
|
|
313
|
+
}
|
|
314
|
+
case "text":
|
|
315
|
+
case "variable": {
|
|
316
|
+
let value = m[1];
|
|
317
|
+
if (r.kind === "variable") {
|
|
318
|
+
value = variables(pack)[m[1].toLowerCase()];
|
|
319
|
+
if (value == null) return unknown(`Kane stored no variable named ${m[1]} in this run`);
|
|
320
|
+
}
|
|
321
|
+
const { home, found } = leaks(pack, [value]);
|
|
322
|
+
if (!home) return unknown("could not tell which site Kane was testing");
|
|
323
|
+
return found.length
|
|
324
|
+
? fail(`the value reached ${sample(found, (f) => `${f.host} (${f.how})`).join("; ")}`, found)
|
|
325
|
+
: pass(`the value stayed on ${home}`);
|
|
326
|
+
}
|
|
327
|
+
case "server": {
|
|
328
|
+
if (!pack.requests.length) return unknown("the evidence pack has no network recording");
|
|
329
|
+
const bad = pack.requests.filter((x) => x.status >= 500);
|
|
330
|
+
return bad.length ? fail(`${plural(bad.length, "server error")}: ${sample(bad, (x) => `${x.status} ${short(x.url)}`).join("; ")}`, bad.map((x) => ({ time: x.iso, status: x.status, url: x.url }))) : pass(`no 5xx in ${plural(pack.requests.length, "request")}`);
|
|
331
|
+
}
|
|
332
|
+
case "failed": {
|
|
333
|
+
const home = homeSite(pack);
|
|
334
|
+
if (!home) return unknown("could not tell which site Kane was testing");
|
|
335
|
+
const bad = pack.requests.filter((x) => x.status >= 400 && site(hostOf(x.url)) === home && !noise(x.url));
|
|
336
|
+
return bad.length ? fail(`${plural(bad.length, "failed request")} to ${home}: ${sample(bad, (x) => `${x.status} ${short(x.url)}`).join("; ")}`, bad.map((x) => ({ time: x.iso, status: x.status, url: x.url }))) : pass(`every request to ${home} succeeded`);
|
|
337
|
+
}
|
|
338
|
+
case "console": {
|
|
339
|
+
const bad = pack.console.filter((c) => c.level === "error" && !noise(`${c.text} ${c.url}`));
|
|
340
|
+
return bad.length ? fail(`${plural(bad.length, "console error")}: ${sample(bad, (c) => c.text.slice(0, 120)).join("; ")}`, bad) : pass("no console errors");
|
|
341
|
+
}
|
|
342
|
+
case "compare": {
|
|
343
|
+
const vars = variables(pack);
|
|
344
|
+
const val = (tok) => (tok.startsWith("$") ? (vars[tok.slice(1).toLowerCase()] != null ? money(vars[tok.slice(1).toLowerCase()]) : undefined) : Number(tok));
|
|
345
|
+
const a = val("$" + m[1]), b = val(m[3]), c = m[4] ? val(m[4]) : 0;
|
|
346
|
+
const missing = [["$" + m[1], a], [m[3], b], [m[4] || "", c]].filter(([k, v]) => k && (v === undefined || v === null)).map(([k]) => k);
|
|
347
|
+
if (missing.length) return unknown(`Kane recorded no number for ${missing.join(", ")}`);
|
|
348
|
+
const limit = Math.round((b + c) * 100) / 100;
|
|
349
|
+
const op = m[2].toLowerCase();
|
|
350
|
+
const ok = op === "equals" ? Math.abs(a - limit) < 0.005 : op === "is at most" ? a <= limit + 0.005 : a >= limit - 0.005;
|
|
351
|
+
const said = `$${m[1]} = ${a}, ${m[3]}${m[4] ? ` plus ${m[4]}` : ""} = ${limit}`;
|
|
352
|
+
return ok ? pass(said) : fail(`${said}: the first ${op === "equals" ? "does not equal" : op === "is at most" ? "is more than" : "is less than"} the second`);
|
|
353
|
+
}
|
|
354
|
+
case "clicks": {
|
|
355
|
+
const A = findStep(pack, m[1]), B = findStep(pack, m[2]);
|
|
356
|
+
if (!A || !B) return unknown(`there is no step called "${!A ? m[1] : m[2]}" in this run`);
|
|
357
|
+
if (!A.section || !B.section) return unknown("click counts need steps from a Kane test file");
|
|
358
|
+
const n = (s) => s.actions.filter((a) => INTERACTIVE.has(a.type) && a.status !== "failed").length;
|
|
359
|
+
const extra = Number(m[3] || 0);
|
|
360
|
+
const a = n(A.section), b = n(B.section);
|
|
361
|
+
return a <= b + extra
|
|
362
|
+
? pass(`"${A.label}" took ${plural(a, "click")}, "${B.label}" took ${b}${extra ? ` (allowed ${b + extra})` : ""}`)
|
|
363
|
+
: fail(`"${A.label}" took ${plural(a, "click")}, more than the ${b + extra} allowed by "${B.label}"`);
|
|
364
|
+
}
|
|
365
|
+
default:
|
|
366
|
+
return unknown(`Statute doesn't understand this rule. See "statute expect --help" for the ones it knows`);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// The verdict over all rules: any fail -> violation; else any unknown -> inconclusive.
|
|
371
|
+
function judge(pack, lines) {
|
|
372
|
+
const early = settle(pack);
|
|
373
|
+
const results = lines.map((l) => {
|
|
374
|
+
const r = parse(l);
|
|
375
|
+
const out = judgeRule(pack, r);
|
|
376
|
+
if (early && out.status === "pass" && NETWORK_KINDS.has(r.kind)) {
|
|
377
|
+
return { ...out, status: "unknown", detail: `${out.detail}, but Kane recorded only ${(early.gap / 1000).toFixed(1)} s of network traffic after the last page loaded (${short(early.url)}); Kane records traffic inside steps, not between them. Tags often send later than that, so this clean result proves nothing. End the step that loads the page with a wait, for example "Then wait 10 seconds."` };
|
|
378
|
+
}
|
|
379
|
+
return out;
|
|
380
|
+
});
|
|
381
|
+
const failed = results.filter((r) => r.status === "fail");
|
|
382
|
+
const unknown = results.filter((r) => r.status === "unknown");
|
|
383
|
+
const verdict = failed.length ? "violation" : unknown.length ? "inconclusive" : "pass";
|
|
384
|
+
const why = failed.length
|
|
385
|
+
? `${plural(failed.length, "expectation")} broken: ${failed.map((r) => r.rule).join("; ")}.`
|
|
386
|
+
: unknown.length
|
|
387
|
+
? `${plural(unknown.length, "expectation")} could not be checked from this evidence.`
|
|
388
|
+
: `All ${plural(results.length, "expectation")} held.`;
|
|
389
|
+
return { verdict, why, kaneStatus: pack.kaneStatus, results, site: homeSite(pack) };
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
module.exports = { parse, judge, judgeRule, RULES, site, forms, typedValues, money, settle, coverage, homeSite, trackerHit, hostOf, SETTLE_MS };
|
package/src/infer.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// Expectations for a Kane run nobody wrote any for, worked out with code from
|
|
2
|
+
// what Kane did: where it typed, and where it refused cookies.
|
|
3
|
+
const expect = require("./expect");
|
|
4
|
+
|
|
5
|
+
// The words on a "refuse" button, in the languages the census met.
|
|
6
|
+
const REFUSE = /\b(reject\w*|declin\w*|refus\w*|deny\w*|denied|disagree\w*|only (strictly )?necessary|necessary only|essential only|weiger\w*|ablehn\w*|rechaz\w*|rifiut\w*|recus\w*|rejeit\w*|odrzu\w*|avvisa|afvis|hylkää|nur notwendige)\b/i;
|
|
7
|
+
|
|
8
|
+
const quoteable = (t) => t && !t.includes('"');
|
|
9
|
+
|
|
10
|
+
// "Decline advertising cookies" refuses one kind, not all of them.
|
|
11
|
+
const PARTIAL = /\b(advertis\w*|marketing|ads?|analytics|performance|statistic\w*|werbung|publicit\w*)\b/i;
|
|
12
|
+
|
|
13
|
+
function infer(pack) {
|
|
14
|
+
const out = [];
|
|
15
|
+
const add = (rule, why) => { if (!out.some((r) => r.rule === rule)) out.push({ rule, why }); };
|
|
16
|
+
|
|
17
|
+
for (const s of pack.sections) {
|
|
18
|
+
const refused = s.actions.find((a) => /click|tap|press/i.test(a.type || "") && REFUSE.test(a.instruction || "") && !PARTIAL.test(a.instruction || ""));
|
|
19
|
+
// Anchor on the click itself (its own words), so "after" starts at the refusal.
|
|
20
|
+
const click = refused && (refused.instruction || "").trim();
|
|
21
|
+
if (quoteable(click) && click.length >= 6) {
|
|
22
|
+
add(`no request to a tracker after "${click}"`, "Kane refused cookies here");
|
|
23
|
+
add(`no visitor ID sent to a tracker after "${click}"`, "a refusal means no tracking ID either");
|
|
24
|
+
add(`no tracker cookie after "${click}"`, "nor tracker cookies");
|
|
25
|
+
}
|
|
26
|
+
if (quoteable(s.title) && expect.typedValues(s.actions).length) add(`what was typed in "${s.title}" never leaves this site`, "Kane typed something here");
|
|
27
|
+
}
|
|
28
|
+
add("no server errors", "always");
|
|
29
|
+
return out;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
module.exports = { infer, REFUSE, PARTIAL };
|
package/src/kane.js
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// Runs kane-cli in agent mode and returns its parsed NDJSON stream.
|
|
2
|
+
const { spawn, execSync } = require("child_process");
|
|
3
|
+
const fs = require("fs");
|
|
4
|
+
const path = require("path");
|
|
5
|
+
|
|
6
|
+
// Find kane-cli's own entry script so it can run without a shell when an argument
|
|
7
|
+
// (like a cloud endpoint URL) contains characters a shell would interpret.
|
|
8
|
+
let kaneBin;
|
|
9
|
+
function findKane() {
|
|
10
|
+
if (kaneBin !== undefined) return kaneBin;
|
|
11
|
+
kaneBin = null;
|
|
12
|
+
try {
|
|
13
|
+
const root = execSync("npm root -g", { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
|
|
14
|
+
const p = path.join(root, "@testmuai", "kane-cli", "bin", "kane-cli.cjs");
|
|
15
|
+
if (fs.existsSync(p)) kaneBin = p;
|
|
16
|
+
} catch {}
|
|
17
|
+
return kaneBin;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// A TestMu AI cloud browser in a chosen country, for Kane's --ws-endpoint.
|
|
21
|
+
function cloudEndpoint({ country, username, accessKey, name }) {
|
|
22
|
+
const caps = {
|
|
23
|
+
browserName: "Chrome",
|
|
24
|
+
browserVersion: "latest",
|
|
25
|
+
"LT:Options": { platform: "Windows 11", build: "Statute", name: name || "Statute audit", user: username, accessKey, geoLocation: country, video: false, console: false },
|
|
26
|
+
};
|
|
27
|
+
return `wss://cdp.lambdatest.com/playwright?capabilities=${encodeURIComponent(JSON.stringify(caps))}`;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function run(objective, { headless = true, maxSteps = 25, timeout = 300, onEvent, cdpEndpoint, wsEndpoint, username, accessKey } = {}) {
|
|
31
|
+
// Preferred path: start kane-cli directly, with no shell, so the objective can
|
|
32
|
+
// contain any character. The shell path below is only a fallback.
|
|
33
|
+
if (findKane()) {
|
|
34
|
+
const args = ["run", objective, "--agent", "--max-steps", String(Number(maxSteps)), "--timeout", String(Number(timeout))];
|
|
35
|
+
if (wsEndpoint) args.push("--ws-endpoint", wsEndpoint);
|
|
36
|
+
else if (cdpEndpoint) {
|
|
37
|
+
if (!/^http:\/\/127\.0\.0\.1:\d+$/.test(cdpEndpoint)) throw new Error("bad CDP endpoint");
|
|
38
|
+
args.push("--cdp-endpoint", cdpEndpoint);
|
|
39
|
+
} else if (headless) args.push("--headless");
|
|
40
|
+
if (username || accessKey) args.push("--username", String(username || ""), "--access-key", String(accessKey || ""));
|
|
41
|
+
return runArgs(args, onEvent, timeout);
|
|
42
|
+
}
|
|
43
|
+
if (wsEndpoint) throw new Error("Could not find kane-cli's install folder (npm root -g), which cloud runs need.");
|
|
44
|
+
// The objective goes through the shell inside double quotes, so refuse anything
|
|
45
|
+
// that could break out of them (cmd.exe and sh metacharacters).
|
|
46
|
+
if (/["%^&|<>`$\\]/.test(objective)) {
|
|
47
|
+
throw new Error("objective contains a character that is unsafe to pass to the shell");
|
|
48
|
+
}
|
|
49
|
+
let cmd = `kane-cli run "${objective}" --agent --max-steps ${Number(maxSteps)} --timeout ${Number(timeout)}`;
|
|
50
|
+
if (cdpEndpoint) {
|
|
51
|
+
// Drive a Chrome we launched ourselves (so we can watch it live).
|
|
52
|
+
if (!/^http:\/\/127\.0\.0\.1:\d+$/.test(cdpEndpoint)) throw new Error("bad CDP endpoint");
|
|
53
|
+
cmd += ` --cdp-endpoint ${cdpEndpoint}`;
|
|
54
|
+
} else if (headless) cmd += " --headless";
|
|
55
|
+
if (username || accessKey) {
|
|
56
|
+
// Non-interactive auth for servers and CI. Values come from the environment.
|
|
57
|
+
if (!/^[\w.@+-]+$/.test(username || "") || !/^[\w.@+-]+$/.test(accessKey || "")) throw new Error("LT_USERNAME / LT_ACCESS_KEY have unexpected characters");
|
|
58
|
+
cmd += ` --username ${username} --access-key ${accessKey}`;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
return collect(spawn(cmd, {
|
|
62
|
+
// One command string with shell:true so Windows finds the kane-cli.cmd shim.
|
|
63
|
+
shell: true,
|
|
64
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
65
|
+
env: { ...process.env, KANE_CLI_USER_AGENT: "statute" },
|
|
66
|
+
}), onEvent, timeout);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Run kane-cli with an argument list and no shell at all.
|
|
70
|
+
function runArgs(args, onEvent, timeout) {
|
|
71
|
+
const bin = findKane();
|
|
72
|
+
if (!bin) return Promise.reject(new Error("Could not find kane-cli's install folder (npm root -g). Install it with: npm i -g @testmuai/kane-cli"));
|
|
73
|
+
return collect(spawn(process.execPath, [bin, ...args], { stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, KANE_CLI_USER_AGENT: "statute" } }), onEvent, timeout);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Kill kane-cli and everything it started (its runner and browser children).
|
|
77
|
+
function killTree(child) {
|
|
78
|
+
try {
|
|
79
|
+
if (process.platform === "win32") spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
|
|
80
|
+
else child.kill("SIGKILL");
|
|
81
|
+
} catch {}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function collect(child, onEvent, timeout = 300) {
|
|
85
|
+
return new Promise((resolve, reject) => {
|
|
86
|
+
// Kane's own --timeout is not always honoured (a cloud run hung for hours),
|
|
87
|
+
// so a wall-clock limit sits on top of it.
|
|
88
|
+
let killed = false;
|
|
89
|
+
const limit = setTimeout(() => { killed = true; killTree(child); }, (Number(timeout) + 90) * 1000);
|
|
90
|
+
const events = [];
|
|
91
|
+
let buf = "";
|
|
92
|
+
let stderr = "";
|
|
93
|
+
child.stdout.on("data", (d) => {
|
|
94
|
+
buf += d;
|
|
95
|
+
let i;
|
|
96
|
+
while ((i = buf.indexOf("\n")) >= 0) {
|
|
97
|
+
const line = buf.slice(0, i).trim();
|
|
98
|
+
buf = buf.slice(i + 1);
|
|
99
|
+
if (!line.startsWith("{")) continue;
|
|
100
|
+
try {
|
|
101
|
+
const ev = JSON.parse(line);
|
|
102
|
+
events.push(ev);
|
|
103
|
+
if (onEvent) onEvent(ev);
|
|
104
|
+
} catch { /* ignore partial or non-JSON lines */ }
|
|
105
|
+
}
|
|
106
|
+
});
|
|
107
|
+
child.stderr.on("data", (d) => (stderr += d));
|
|
108
|
+
child.on("error", reject);
|
|
109
|
+
child.on("close", (code) => {
|
|
110
|
+
clearTimeout(limit);
|
|
111
|
+
let end = events.find((e) => e.type === "run_end");
|
|
112
|
+
if (!end && killed) end = { status: "timeout", summary: `Kane did not finish within ${Number(timeout) + 90} seconds and was stopped.`, credits_consumed: 0 };
|
|
113
|
+
resolve({ code, events, end, stderr, killed });
|
|
114
|
+
});
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// True when kane-cli is installed globally or on PATH.
|
|
119
|
+
function available() {
|
|
120
|
+
if (findKane()) return true;
|
|
121
|
+
try { execSync(process.platform === "win32" ? "where kane-cli" : "command -v kane-cli", { stdio: "ignore" }); return true; } catch { return false; }
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
module.exports = { available, run, cloudEndpoint, collect, binary: findKane };
|