@aarwitz/tapp 0.17.26 → 0.18.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/.claude-plugin/plugin.json +2 -2
- package/AGENTS.md +43 -44
- package/README.md +32 -42
- package/bin/tapp.js +168 -99
- package/browser/app.css +220 -208
- package/browser/app.js +173 -20
- package/browser/index.html +118 -57
- package/browser/tokens.css +33 -25
- package/docs/BROWSER-PRODUCT.md +16 -8
- package/docs/BUSINESS-WORKFLOWS.md +134 -0
- package/docs/PRODUCT-ENGINE.md +5 -0
- package/mcp-server/src/browser-product.js +15 -3
- package/mcp-server/src/business-observation.d.ts +2 -0
- package/mcp-server/src/business-observation.js +25 -0
- package/mcp-server/src/business-workflow-files.js +36 -0
- package/mcp-server/src/business-workflow-runtime.js +47 -0
- package/mcp-server/src/business-workflows.d.ts +50 -0
- package/mcp-server/src/business-workflows.js +169 -0
- package/mcp-server/src/environment-capabilities.d.ts +16 -0
- package/mcp-server/src/environment-capabilities.js +78 -0
- package/mcp-server/src/index.js +546 -794
- package/mcp-server/src/product-operations.js +3 -1
- package/mcp-server/src/public-network.js +65 -0
- package/mcp-server/src/web-audit.js +131 -20
- package/mcp-server/src/web-explorer.js +119 -23
- package/mcp-server/src/web-flow.js +17 -4
- package/package.json +7 -1
- package/scripts/run-web-flow.js +4 -0
- package/skills/tapp/SKILL.md +14 -13
- package/skills/tapp/references/commands.md +73 -57
|
@@ -20,6 +20,7 @@ import {
|
|
|
20
20
|
import { baselinePathForTarget, existingBaselinePathForTarget, renderGithubWorkflow, selectApplicationTarget, writeCiInstallation, writeTargetBaseline } from "./ci-setup.js";
|
|
21
21
|
import { executeReleaseContract, runProductProcess } from "./product-execution.js";
|
|
22
22
|
import { projectArtifactDirectory } from "./project-paths.js";
|
|
23
|
+
import { BUSINESS_WORKFLOW_PATH } from "./business-workflows.js";
|
|
23
24
|
|
|
24
25
|
const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
|
|
25
26
|
const packageVersion = JSON.parse(fs.readFileSync(path.join(packageRoot, "package.json"), "utf8")).version;
|
|
@@ -209,7 +210,7 @@ function listRepositoryFlows(root) {
|
|
|
209
210
|
steps = (block.match(/^\s{2}-\s/gm) || []).length;
|
|
210
211
|
}
|
|
211
212
|
} catch { /* Artifact remains inspectable; deterministic replay reports invalid syntax. */ }
|
|
212
|
-
return { id:`flow_${crypto.createHash("sha256").update(relativePath).digest("hex").slice(0, 16)}`, name, path:relativePath, platform, steps, status:"committed" };
|
|
213
|
+
return { id:`flow_${crypto.createHash("sha256").update(relativePath).digest("hex").slice(0, 16)}`, name, path:relativePath, platform, steps, sha256:crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex"), status:"committed" };
|
|
213
214
|
})
|
|
214
215
|
.sort((left, right) => left.path.localeCompare(right.path));
|
|
215
216
|
}
|
|
@@ -242,6 +243,7 @@ export function readProductProject({ projectDir, outDir = ".tapp" } = {}) {
|
|
|
242
243
|
ci,
|
|
243
244
|
baselines,
|
|
244
245
|
flows: listRepositoryFlows(root),
|
|
246
|
+
businessWorkflowDefinition: readJson(path.join(root,BUSINESS_WORKFLOW_PATH)),
|
|
245
247
|
evidence: listProductRuns(root),
|
|
246
248
|
state: {
|
|
247
249
|
inspected: !!model,
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import http from "node:http";
|
|
2
|
+
import https from "node:https";
|
|
3
|
+
import net from "node:net";
|
|
4
|
+
import dns from "node:dns/promises";
|
|
5
|
+
|
|
6
|
+
function publicIPv4(value) {
|
|
7
|
+
if (net.isIP(value) !== 4) return false;
|
|
8
|
+
const [a,b,c] = value.split('.').map(Number);
|
|
9
|
+
return !(a === 0 || a === 10 || a === 127 || a >= 224 ||
|
|
10
|
+
(a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) ||
|
|
11
|
+
(a === 172 && b >= 16 && b <= 31) || (a === 192 && (b === 168 || b === 0 || (b === 88 && c === 99))) ||
|
|
12
|
+
(a === 198 && (b === 18 || b === 19 || (b === 51 && c === 100))) || (a === 203 && b === 0 && c === 113));
|
|
13
|
+
}
|
|
14
|
+
export async function resolvePublicHost(host) {
|
|
15
|
+
const normalized = host.toLowerCase().replace(/\.$/, "");
|
|
16
|
+
if (!normalized || normalized === "localhost" || /\.(localhost|local|internal|test|invalid)$/.test(normalized)) throw new Error("A publicly reachable app hostname is required");
|
|
17
|
+
const addresses = net.isIP(normalized) ? [{address:normalized}] : await dns.lookup(normalized,{all:true,family:4});
|
|
18
|
+
if (!addresses.length || addresses.some(item=>!publicIPv4(item.address))) throw new Error("Private and reserved network addresses are unavailable to hosted website runs");
|
|
19
|
+
return addresses[0].address;
|
|
20
|
+
}
|
|
21
|
+
export async function publicRequest(url, {method="POST",headers={},body,timeout=15000}={}) {
|
|
22
|
+
const target = new URL(url);
|
|
23
|
+
if(target.protocol !== "https:" || target.username || target.password || (target.port && target.port !== "443")) throw new Error("Backend actions require public HTTPS on port 443");
|
|
24
|
+
const address=await resolvePublicHost(target.hostname);
|
|
25
|
+
return new Promise((resolve,reject)=>{
|
|
26
|
+
const req=https.request(target,{method,headers,family:4,lookup:(_host,options,callback)=>options.all ? callback(null,[{address,family:4}]) : callback(null,address,4)},response=>{
|
|
27
|
+
let size=0; const chunks=[];
|
|
28
|
+
response.on("data",chunk=>{size+=chunk.length;if(size>262144) {response.destroy();req.destroy(new Error("Backend response exceeded 256 KiB"));}else chunks.push(chunk);});
|
|
29
|
+
response.on("error",reject);
|
|
30
|
+
response.on("end",()=>resolve({status:response.statusCode,body:Buffer.concat(chunks).toString("utf8")}));
|
|
31
|
+
});
|
|
32
|
+
req.on("error",reject);req.setTimeout(timeout,()=>req.destroy(new Error("Backend action timed out")));
|
|
33
|
+
if(body)req.write(body);req.end();
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Resolve and pin every TCP connection, including redirects and subresources.
|
|
38
|
+
// This proxy is for URL-only work; it deliberately cannot reach local dev servers.
|
|
39
|
+
export async function startPublicBrowserProxy() {
|
|
40
|
+
const sockets=new Set();
|
|
41
|
+
const track=socket=>{sockets.add(socket);socket.on("close",()=>sockets.delete(socket));socket.on("error",()=>{});return socket;};
|
|
42
|
+
const server=http.createServer(async (request,response)=>{
|
|
43
|
+
try{
|
|
44
|
+
const url=new URL(request.url);
|
|
45
|
+
if(url.protocol!=="http:" || (url.port && url.port!=="80") || url.username || url.password) throw new Error();
|
|
46
|
+
const address=await resolvePublicHost(url.hostname);
|
|
47
|
+
const headers={...request.headers,host:url.host};delete headers["proxy-authorization"];delete headers["proxy-connection"];
|
|
48
|
+
const outgoing=http.request({host:address,port:80,path:url.pathname+url.search,method:request.method,headers},remote=>{response.writeHead(remote.statusCode,remote.headers);remote.pipe(response);});
|
|
49
|
+
outgoing.on("socket",track);outgoing.setTimeout(30000,()=>outgoing.destroy());outgoing.on("error",()=>{if(!response.headersSent)response.writeHead(502);response.end();});
|
|
50
|
+
request.on("aborted",()=>outgoing.destroy());request.pipe(outgoing);
|
|
51
|
+
}catch{response.writeHead(403);response.end("Public network access required");}
|
|
52
|
+
});
|
|
53
|
+
server.on("connection",track);
|
|
54
|
+
server.on("connect",async (request,socket,head)=>{
|
|
55
|
+
try{
|
|
56
|
+
const target=new URL(`https://${request.url}`);
|
|
57
|
+
if(target.port && target.port!=="443")throw new Error();
|
|
58
|
+
const address=await resolvePublicHost(target.hostname);
|
|
59
|
+
const upstream=track(net.connect(443,address,()=>{socket.write("HTTP/1.1 200 Connection Established\r\n\r\n");if(head.length)upstream.write(head);socket.pipe(upstream);upstream.pipe(socket);}));
|
|
60
|
+
upstream.setTimeout(120000,()=>upstream.destroy());socket.on("close",()=>upstream.destroy());upstream.on("close",()=>socket.destroy());
|
|
61
|
+
}catch{socket.end("HTTP/1.1 403 Forbidden\r\n\r\n");}
|
|
62
|
+
});
|
|
63
|
+
await new Promise((resolve,reject)=>{server.once("error",reject);server.listen(0,"127.0.0.1",resolve);});
|
|
64
|
+
return {url:`http://127.0.0.1:${server.address().port}`,close:async()=>{for(const socket of sockets)socket.destroy();await new Promise(resolve=>server.close(resolve));}};
|
|
65
|
+
}
|
|
@@ -21,6 +21,7 @@ import { buildQaReport } from "./report.js";
|
|
|
21
21
|
import { writeHtmlReport } from "./html-report.js";
|
|
22
22
|
import { buildUiMapFromMarkers, writeUiMap } from "./ui-map.js";
|
|
23
23
|
import { writeCaptureProvenance } from "./capture-provenance.js";
|
|
24
|
+
import { passiveUrlRisk } from "./business-observation.js";
|
|
24
25
|
|
|
25
26
|
const require = createRequire(import.meta.url);
|
|
26
27
|
const VERSION = (() => { try { return require("../../package.json").version; } catch { return "0.0.0"; } })();
|
|
@@ -32,7 +33,7 @@ const LINK_CHECK_TIMEOUT_MS = 10_000;
|
|
|
32
33
|
|
|
33
34
|
// What an audit does and does not look at. Spelled out so a report never borrows the exploration
|
|
34
35
|
// run's "checked for" list and claims clicks that never happened.
|
|
35
|
-
export function auditScope({ linksChecked = { total: 0, checked: 0 }, pages = 1 } = {}) {
|
|
36
|
+
export function auditScope({ linksChecked = { total: 0, checked: 0 }, pages = 1, wiringUnverifiable = [] } = {}) {
|
|
36
37
|
const checkedFor = [
|
|
37
38
|
"controls that were never alive: dead in-page anchors, placeholder links, aria-controls naming nothing, buttons with no handler/form/link",
|
|
38
39
|
"images that failed to load",
|
|
@@ -52,6 +53,10 @@ export function auditScope({ linksChecked = { total: 0, checked: 0 }, pages = 1
|
|
|
52
53
|
"app-specific business logic, content accuracy, privacy, brand, visual quality",
|
|
53
54
|
pages > 1 ? `pages beyond the ${pages} audited` : "pages other than the one audited (pass --pages N to crawl same-origin links)",
|
|
54
55
|
];
|
|
56
|
+
if (wiringUnverifiable.length) {
|
|
57
|
+
const reasons = [...new Set(wiringUnverifiable)];
|
|
58
|
+
notChecked.unshift(`dead controls and placeholder links on ${wiringUnverifiable.length} page(s) where the check would accuse working controls: ${reasons.join("; ")}`);
|
|
59
|
+
}
|
|
55
60
|
return { checkedFor, notChecked };
|
|
56
61
|
}
|
|
57
62
|
|
|
@@ -105,6 +110,15 @@ async function auditPageHealth(page) {
|
|
|
105
110
|
const src = img.getAttribute("src") || "";
|
|
106
111
|
if (!src || src.startsWith("data:")) continue;
|
|
107
112
|
if (img.complete && img.naturalWidth === 0) {
|
|
113
|
+
// A 1×1 (or hidden) image that failed is a tracking pixel the visitor never sees, not a
|
|
114
|
+
// broken picture on the page.
|
|
115
|
+
const box = img.getBoundingClientRect();
|
|
116
|
+
if (box.width <= 2 || box.height <= 2) continue;
|
|
117
|
+
// A failed image lays out as a 16px placeholder box even when it was meant to be
|
|
118
|
+
// invisible; a cross-origin, query-string, alt-less image is a beacon, not a picture.
|
|
119
|
+
let crossOrigin = false;
|
|
120
|
+
try { crossOrigin = new URL(src, location.href).origin !== location.origin; } catch { /* keep */ }
|
|
121
|
+
if (crossOrigin && /\?/.test(src) && !img.hasAttribute("alt")) continue;
|
|
108
122
|
findings.push({ kind: "broken_image", src: src.slice(0, 160), alt: (img.getAttribute("alt") || "").slice(0, 80), selector: visible(img) ? tag(img) : null });
|
|
109
123
|
}
|
|
110
124
|
}
|
|
@@ -167,14 +181,25 @@ async function checkLinks(context, links, { limit, pageUrl }) {
|
|
|
167
181
|
const pathOf = (() => { try { return new URL(href).pathname; } catch { return href; } })();
|
|
168
182
|
try {
|
|
169
183
|
let res = await context.request.fetch(href, { method: "HEAD", maxRedirects: 5, timeout: LINK_CHECK_TIMEOUT_MS, failOnStatusCode: false });
|
|
170
|
-
|
|
184
|
+
// Some servers refuse HEAD outright, and some answer 404/5xx to HEAD for pages that GET
|
|
185
|
+
// fine. Only a GET is allowed to call a link broken.
|
|
186
|
+
if ([405, 501, 403, 404, 410].includes(res.status()) || res.status() >= 500) {
|
|
171
187
|
res = await context.request.fetch(href, { method: "GET", maxRedirects: 5, timeout: LINK_CHECK_TIMEOUT_MS, failOnStatusCode: false });
|
|
172
188
|
}
|
|
173
189
|
const status = res.status();
|
|
174
190
|
if (status === 404 || status === 410) findings.push({ type: "broken_link", severity: "medium", title: `Link ${where} → ${pathOf} answers ${status}`, target: href, url: href });
|
|
175
191
|
else if (status >= 500) findings.push({ type: "broken_link", severity: "high", title: `Link ${where} → ${pathOf} answers ${status}`, target: href, url: href });
|
|
176
192
|
} catch (error) {
|
|
177
|
-
|
|
193
|
+
// One dropped connection is not a broken link; a second is worth a low-severity note.
|
|
194
|
+
await new Promise((r) => setTimeout(r, 1000));
|
|
195
|
+
try {
|
|
196
|
+
const retry = await context.request.fetch(href, { method: "GET", maxRedirects: 5, timeout: LINK_CHECK_TIMEOUT_MS, failOnStatusCode: false });
|
|
197
|
+
const status = retry.status();
|
|
198
|
+
if (status === 404 || status === 410) findings.push({ type: "broken_link", severity: "medium", title: `Link ${where} → ${pathOf} answers ${status}`, target: href, url: href });
|
|
199
|
+
else if (status >= 500) findings.push({ type: "broken_link", severity: "high", title: `Link ${where} → ${pathOf} answers ${status}`, target: href, url: href });
|
|
200
|
+
} catch (again) {
|
|
201
|
+
findings.push({ type: "broken_link", severity: "low", title: `Link ${where} → ${pathOf} could not be fetched twice (${String(again?.message || again).split("\n")[0].slice(0, 80)})`, target: href, url: href });
|
|
202
|
+
}
|
|
178
203
|
}
|
|
179
204
|
}
|
|
180
205
|
};
|
|
@@ -185,7 +210,7 @@ async function checkLinks(context, links, { limit, pageUrl }) {
|
|
|
185
210
|
|
|
186
211
|
// One page, inside an already-open context. Collects everything, then (if a capture is open) shoots
|
|
187
212
|
// the page and each named element and appends the markers.
|
|
188
|
-
async function auditOnePage(context, target, { timeoutMs, linkCheckLimit, capture }) {
|
|
213
|
+
async function auditOnePage(context, target, { timeoutMs, linkCheckLimit, capture, blockedRequests = new WeakSet(), observationOnly = false, allowLink = () => true }) {
|
|
189
214
|
const page = await context.newPage();
|
|
190
215
|
const bounded = Math.max(1000, Math.min(60_000, Number(timeoutMs) || NAV_TIMEOUT_MS));
|
|
191
216
|
page.setDefaultTimeout(bounded);
|
|
@@ -208,6 +233,7 @@ async function auditOnePage(context, target, { timeoutMs, linkCheckLimit, captur
|
|
|
208
233
|
});
|
|
209
234
|
page.on("requestfailed", (req) => {
|
|
210
235
|
try {
|
|
236
|
+
if (blockedRequests.has(req)) return; // Our observation policy is not an application defect.
|
|
211
237
|
const u = new URL(req.url());
|
|
212
238
|
if (u.origin !== origin) return;
|
|
213
239
|
const errorText = req.failure()?.errorText || "?";
|
|
@@ -223,7 +249,8 @@ async function auditOnePage(context, target, { timeoutMs, linkCheckLimit, captur
|
|
|
223
249
|
|
|
224
250
|
const controls = await auditStructuralControls(page);
|
|
225
251
|
const health = await auditPageHealth(page);
|
|
226
|
-
const
|
|
252
|
+
const allowedLinks = health.links.filter(allowLink);
|
|
253
|
+
const links = await checkLinks(context, allowedLinks, { limit: linkCheckLimit, pageUrl: page.url() });
|
|
227
254
|
|
|
228
255
|
const structural = auditFindingsFromControls(controls.dead).map((f, i) => ({ ...f, selector: controls.dead[i].selector }));
|
|
229
256
|
const findings = [...structural, ...healthFindings(health.findings), ...loadFindings, ...links.findings];
|
|
@@ -250,10 +277,15 @@ async function auditOnePage(context, target, { timeoutMs, linkCheckLimit, captur
|
|
|
250
277
|
return {
|
|
251
278
|
url: page.url(),
|
|
252
279
|
title: controls.title,
|
|
280
|
+
...(observationOnly ? { visibleText: await page.locator("body").innerText({ timeout: bounded }).then(text => text.slice(0, 12000)).catch(() => ""),
|
|
281
|
+
visibleTextLimit: 12000 } : {}),
|
|
282
|
+
...(page.video() ? { recording: path.basename(await page.video().path()) } : {}),
|
|
253
283
|
controlsExamined: controls.controlCount,
|
|
254
284
|
linksChecked: { total: links.total, checked: links.checked },
|
|
285
|
+
// Why the wiring-dependent checks were skipped on this page, if they were.
|
|
286
|
+
...(controls.wiringUnverifiable ? { wiringUnverifiable: controls.wiringUnverifiable } : {}),
|
|
255
287
|
findings,
|
|
256
|
-
links:
|
|
288
|
+
links: allowedLinks,
|
|
257
289
|
};
|
|
258
290
|
} finally {
|
|
259
291
|
await page.close().catch(() => {});
|
|
@@ -276,27 +308,30 @@ export function auditCaptureId(now = new Date()) {
|
|
|
276
308
|
return `web-audit-${now.getFullYear()}${p(now.getMonth() + 1)}${p(now.getDate())}-${p(now.getHours())}${p(now.getMinutes())}${p(now.getSeconds())}`;
|
|
277
309
|
}
|
|
278
310
|
|
|
279
|
-
function finalizeCapture(capture, { startUrl, pages, findings, robotsBlocked, linksChecked }) {
|
|
311
|
+
function finalizeCapture(capture, { startUrl, pages, findings, robotsBlocked, linksChecked, observationLimits = [], skippedLinks = [], wiringUnverifiable = [] }) {
|
|
280
312
|
capture.emit("COMPLETE", { actions: 0, screens: pages.length, credentialsProvided: false, credentialsUsed: false, timedOut: false, stop: "audit-complete", readOnly: true, robotsBlocked });
|
|
281
313
|
capture.close();
|
|
282
314
|
const markers = path.join(capture.dir, "ocqa-markers.txt");
|
|
283
315
|
const report = buildQaReport(markers, { platform: "web", target: startUrl });
|
|
284
316
|
if (!report) return null;
|
|
285
317
|
// The exploration report's coverage floor and wording assume clicks; an audit has none by design.
|
|
286
|
-
const scope = auditScope({ linksChecked, pages: pages.length });
|
|
318
|
+
const scope = auditScope({ linksChecked, pages: pages.length, wiringUnverifiable });
|
|
287
319
|
const counts = report.deterministicFindingCounts || report.findingCounts || { critical: 0, high: 0, medium: 0, low: 0 };
|
|
288
320
|
Object.assign(report, {
|
|
289
321
|
kind: "tapp-structural-audit",
|
|
290
322
|
readOnly: true,
|
|
291
|
-
inconclusive:
|
|
323
|
+
inconclusive: observationLimits.length > 0,
|
|
292
324
|
runStatus: "completed",
|
|
293
325
|
stopReason: "audit-complete",
|
|
294
|
-
headline:
|
|
326
|
+
headline: observationLimits.length > 0
|
|
327
|
+
? `Passive audit of ${pages.length} page(s): ${findings.length} finding(s). Observation restrictions limited rendering; inspect those limits before attributing findings to the app.`
|
|
328
|
+
: findings.length === 0
|
|
295
329
|
? `Read-only audit of ${pages.length} page(s) — nothing broken was observed. Nothing was clicked; this says the page is served without structural defects, not that the product works.`
|
|
296
330
|
: `${findings.length} defect(s) observed on ${pages.length} page(s) without clicking anything (${counts.critical} critical, ${counts.high} high, ${counts.medium} medium, ${counts.low} low).`,
|
|
297
331
|
checkedFor: scope.checkedFor,
|
|
298
|
-
notChecked: scope.notChecked,
|
|
299
|
-
|
|
332
|
+
notChecked: [...scope.notChecked, ...observationLimits, ...(skippedLinks.length ? ["Potential action/signed links and robots exclusions were not fetched; see skippedLinks."] : [])],
|
|
333
|
+
skippedLinks,
|
|
334
|
+
conditionsNotReached: observationLimits,
|
|
300
335
|
});
|
|
301
336
|
fs.writeFileSync(path.join(capture.dir, "report.json"), JSON.stringify(report, null, 2));
|
|
302
337
|
// The capture-local UI map is what ties a page screenshot to the findings on that page for
|
|
@@ -307,17 +342,37 @@ function finalizeCapture(capture, { startUrl, pages, findings, robotsBlocked, li
|
|
|
307
342
|
return report;
|
|
308
343
|
}
|
|
309
344
|
|
|
345
|
+
// The same defect seen on several pages (site-wide navigation, a footer, a missing viewport
|
|
346
|
+
// meta) is one issue. Keyed by type and target; the title is the first one seen.
|
|
347
|
+
export function dedupeSiteIssues(findings = []) {
|
|
348
|
+
const byKey = new Map();
|
|
349
|
+
for (const f of findings) {
|
|
350
|
+
const key = `${f.type}|${f.target ?? f.title}`;
|
|
351
|
+
const page = f.screen || f.url || "";
|
|
352
|
+
const existing = byKey.get(key);
|
|
353
|
+
if (existing) {
|
|
354
|
+
if (page && !existing.pages.includes(page)) existing.pages.push(page);
|
|
355
|
+
existing.occurrences += 1;
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
byKey.set(key, { type: f.type, severity: f.severity, title: f.title, target: f.target ?? null, evidence: f.evidence || null, pages: page ? [page] : [], occurrences: 1 });
|
|
359
|
+
}
|
|
360
|
+
const rank = { critical: 0, high: 1, medium: 2, low: 3 };
|
|
361
|
+
return [...byKey.values()].sort((a, b) => (rank[a.severity] ?? 4) - (rank[b.severity] ?? 4) || b.pages.length - a.pages.length);
|
|
362
|
+
}
|
|
363
|
+
|
|
310
364
|
// Audit a site: the start page and, with pages > 1, same-origin links discovered on audited pages
|
|
311
365
|
// (breadth-first, robots.txt honoured, one request at a time with a pause between pages).
|
|
312
366
|
export async function auditWebSite({
|
|
313
367
|
url, pages = 1, timeoutMs = NAV_TIMEOUT_MS, device = "", viewport = "",
|
|
314
368
|
linkCheckLimit = AUDIT_LINK_CHECK_LIMIT, delayMs = AUDIT_CRAWL_DELAY_MS,
|
|
315
|
-
capturesDir = "", captureId = "", onPage = null,
|
|
369
|
+
capturesDir = "", captureId = "", onPage = null, observationOnly = false, recordVideo = false,
|
|
316
370
|
}) {
|
|
317
371
|
let start;
|
|
318
372
|
try { start = new URL(url); }
|
|
319
373
|
catch { throw new Error("Audit needs a valid http(s) URL"); }
|
|
320
374
|
if (!/^https?:$/.test(start.protocol)) throw new Error("Audit needs a valid http(s) URL");
|
|
375
|
+
if (observationOnly && passiveUrlRisk(start.href)) throw new Error("Passive checks cannot open signed or potentially state-changing links");
|
|
321
376
|
const maxPages = Math.max(1, Math.min(200, Number(pages) || 1));
|
|
322
377
|
|
|
323
378
|
const { chromium, devices } = await loadPlaywright();
|
|
@@ -330,12 +385,39 @@ export async function auditWebSite({
|
|
|
330
385
|
const probe = await browser.newContext(contextOptions);
|
|
331
386
|
const defaultUa = contextOptions.userAgent || await (await probe.newPage()).evaluate(() => navigator.userAgent).catch(() => "");
|
|
332
387
|
await probe.close();
|
|
333
|
-
const context = await browser.newContext({ ...contextOptions,
|
|
388
|
+
const context = await browser.newContext({ ...contextOptions,
|
|
389
|
+
...(observationOnly ? { serviceWorkers: "block", acceptDownloads: false } : {}),
|
|
390
|
+
...(recordVideo && capture ? { recordVideo: { dir: capture.dir } } : {}),
|
|
391
|
+
userAgent: `${defaultUa} tapp-audit/${VERSION} (+https://runtapp.com)`.trim() });
|
|
392
|
+
const blockedRequests = new WeakSet();
|
|
393
|
+
const observationLimits = new Set();
|
|
394
|
+
if (observationOnly) {
|
|
395
|
+
// Enforce the passive path even if page JavaScript tries to submit data.
|
|
396
|
+
// No login/storage state or application credentials enter this fresh context.
|
|
397
|
+
await context.route("**/*", async route => {
|
|
398
|
+
const request = route.request();
|
|
399
|
+
const method = request.method();
|
|
400
|
+
const risk = passiveUrlRisk(request.url());
|
|
401
|
+
if (!["GET", "HEAD"].includes(method) || risk) {
|
|
402
|
+
blockedRequests.add(request);
|
|
403
|
+
observationLimits.add(risk ? "A possible action or signed resource URL was blocked; dependent content was not verified."
|
|
404
|
+
: `${method} requests were blocked; content depending on those requests was not verified.`);
|
|
405
|
+
await route.abort("blockedbyclient");
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
await route.continue();
|
|
409
|
+
});
|
|
410
|
+
if (typeof context.routeWebSocket !== "function") throw new Error("Passive hosted checks require a Playwright version with WebSocket routing");
|
|
411
|
+
await context.routeWebSocket("**/*", socket => {
|
|
412
|
+
observationLimits.add("WebSockets were blocked; live content depending on them was not verified.");
|
|
413
|
+
socket.close();
|
|
414
|
+
});
|
|
415
|
+
}
|
|
334
416
|
await installWebListenerTracking(context);
|
|
335
417
|
if (capture) capture.emit("CONTEXT", { ...(String(device || "").trim() ? { device: String(device).trim() } : {}), viewport: contextOptions.viewport, deviceScaleFactor: contextOptions.deviceScaleFactor ?? 1, mode: "audit", readOnly: true });
|
|
336
418
|
|
|
337
419
|
let robots = [];
|
|
338
|
-
if (maxPages > 1) {
|
|
420
|
+
if (maxPages > 1 || observationOnly) {
|
|
339
421
|
try {
|
|
340
422
|
const res = await context.request.get(new URL("/robots.txt", start).href, { timeout: 5_000, failOnStatusCode: false });
|
|
341
423
|
if (res.ok()) robots = parseRobots(await res.text());
|
|
@@ -344,19 +426,33 @@ export async function auditWebSite({
|
|
|
344
426
|
|
|
345
427
|
const results = [];
|
|
346
428
|
const robotsBlocked = [];
|
|
429
|
+
const skippedLinks = new Map();
|
|
430
|
+
const allowLink = link => {
|
|
431
|
+
if (!observationOnly) return true;
|
|
432
|
+
const url = new URL(link.href);
|
|
433
|
+
const reason = passiveUrlRisk(link.href) || (url.origin === start.origin && !robotsAllows(robots, url.pathname) ? "robots-excluded" : null);
|
|
434
|
+
if (!reason) return true;
|
|
435
|
+
if (skippedLinks.size < 100) skippedLinks.set(link.href, { path: url.pathname, reason });
|
|
436
|
+
return false;
|
|
437
|
+
};
|
|
347
438
|
const queued = new Set([start.href]);
|
|
348
439
|
const queue = [start];
|
|
349
440
|
let linksTotal = 0;
|
|
350
441
|
let linksChecked = 0;
|
|
351
442
|
while (queue.length && results.length < maxPages) {
|
|
352
443
|
const target = queue.shift();
|
|
444
|
+
if (observationOnly && !robotsAllows(robots, target.pathname)) {
|
|
445
|
+
robotsBlocked.push(target.href);
|
|
446
|
+
observationLimits.add("robots.txt excluded a requested page; it was not inspected.");
|
|
447
|
+
continue;
|
|
448
|
+
}
|
|
353
449
|
if (results.length > 0) {
|
|
354
450
|
if (!robotsAllows(robots, target.pathname)) { robotsBlocked.push(target.href); continue; }
|
|
355
451
|
if (delayMs > 0) await new Promise((r) => setTimeout(r, delayMs));
|
|
356
452
|
}
|
|
357
453
|
let result;
|
|
358
454
|
try {
|
|
359
|
-
result = await auditOnePage(context, target, { timeoutMs, linkCheckLimit, capture });
|
|
455
|
+
result = await auditOnePage(context, target, { timeoutMs, linkCheckLimit, capture, blockedRequests, observationOnly, allowLink });
|
|
360
456
|
} catch (error) {
|
|
361
457
|
if (results.length === 0) throw error;
|
|
362
458
|
result = { url: target.href, title: "", controlsExamined: 0, linksChecked: { total: 0, checked: 0 }, links: [],
|
|
@@ -365,7 +461,8 @@ export async function auditWebSite({
|
|
|
365
461
|
linksTotal += result.linksChecked.total;
|
|
366
462
|
linksChecked += result.linksChecked.checked;
|
|
367
463
|
const { links, ...pageResult } = result;
|
|
368
|
-
results.push(pageResult)
|
|
464
|
+
results.push({ ...pageResult, ...(observationOnly ? { observedLinks: links.slice(0, 100),
|
|
465
|
+
observedLinksTruncated: links.length > 100 } : {}) });
|
|
369
466
|
if (typeof onPage === "function") onPage(pageResult, results.length);
|
|
370
467
|
// A link the HEAD check already found broken is reported; opening it would only repeat the finding.
|
|
371
468
|
const broken = new Set(pageResult.findings.filter((f) => f.type === "broken_link").map((f) => f.target));
|
|
@@ -373,31 +470,45 @@ export async function auditWebSite({
|
|
|
373
470
|
if (!link.sameOrigin || queued.has(link.href) || broken.has(link.href) || queued.size >= maxPages * 4) continue;
|
|
374
471
|
let next;
|
|
375
472
|
try { next = new URL(link.href); } catch { continue; }
|
|
473
|
+
if (observationOnly && next.origin !== start.origin) continue;
|
|
376
474
|
if (/\.(pdf|zip|png|jpe?g|gif|svg|webp|mp4|mp3|css|js|xml|ico)$/i.test(next.pathname)) continue;
|
|
377
475
|
queued.add(next.href);
|
|
378
476
|
queue.push(next);
|
|
379
477
|
}
|
|
380
478
|
}
|
|
381
479
|
|
|
480
|
+
// Closing the context finalizes page recordings before evidence is uploaded.
|
|
481
|
+
await context.close();
|
|
382
482
|
const findings = results.flatMap((r) => r.findings);
|
|
483
|
+
const issues = dedupeSiteIssues(findings);
|
|
383
484
|
const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
|
|
384
485
|
for (const f of findings) if (f.severity in bySeverity) bySeverity[f.severity] += 1;
|
|
385
|
-
const
|
|
486
|
+
const wiringUnverifiable = results.map((r) => r.wiringUnverifiable).filter(Boolean);
|
|
487
|
+
const scope = auditScope({ linksChecked: { total: linksTotal, checked: linksChecked }, pages: results.length, wiringUnverifiable });
|
|
386
488
|
const summary = {
|
|
387
489
|
kind: "tapp-structural-audit",
|
|
388
490
|
readOnly: true,
|
|
491
|
+
...(observationOnly ? { observationOnly: true, observationLimits: [...observationLimits],
|
|
492
|
+
inconclusive: observationLimits.size > 0,
|
|
493
|
+
observationPolicy: "Fresh unauthenticated browser; no interactions; GET/HEAD only; no WebSockets or service workers. Page loads may still generate server logs and analytics. Restricted rendering may affect findings." } : {}),
|
|
389
494
|
url: start.href,
|
|
390
495
|
pagesAudited: results.length,
|
|
496
|
+
pagesWithUnverifiableWiring: wiringUnverifiable.length,
|
|
391
497
|
pagesQueued: queue.length,
|
|
392
498
|
robotsBlocked,
|
|
499
|
+
...(observationOnly ? { skippedLinks: [...skippedLinks.values()], skippedLinksLimit: 100 } : {}),
|
|
393
500
|
findingCounts: { ...bySeverity, total: findings.length },
|
|
501
|
+
// One entry per distinct defect across the site, with the pages it appears on: a footer
|
|
502
|
+
// link that answers 404 on six pages is one thing to fix, and one line in an email.
|
|
503
|
+
issues,
|
|
504
|
+
issueCount: issues.length,
|
|
394
505
|
checkedFor: scope.checkedFor,
|
|
395
|
-
notChecked: scope.notChecked,
|
|
506
|
+
notChecked: [...scope.notChecked, ...observationLimits, ...(skippedLinks.size ? ["Potential action/signed links and robots exclusions were not fetched; see skippedLinks."] : [])],
|
|
396
507
|
pages: results,
|
|
397
508
|
capture: null,
|
|
398
509
|
};
|
|
399
510
|
if (capture) {
|
|
400
|
-
finalizeCapture(capture, { startUrl: start.href, pages: results, findings, robotsBlocked, linksChecked: { total: linksTotal, checked: linksChecked } });
|
|
511
|
+
finalizeCapture(capture, { startUrl: start.href, pages: results, findings, robotsBlocked, linksChecked: { total: linksTotal, checked: linksChecked }, observationLimits: [...observationLimits], skippedLinks: [...skippedLinks.values()], wiringUnverifiable });
|
|
401
512
|
summary.capture = { id: capture.id, path: capture.dir, report: path.join(capture.dir, "report.html"), provenance };
|
|
402
513
|
fs.writeFileSync(path.join(capture.dir, "audit.json"), JSON.stringify(summary, null, 2));
|
|
403
514
|
}
|