@aarwitz/tapp 0.18.4 → 0.19.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +2 -2
- package/AGENTS.md +5 -0
- package/bin/tapp.js +113 -6
- package/browser/app.js +92 -1
- package/browser/index.html +11 -11
- package/mcp-server/src/browser-product.js +207 -25
- package/mcp-server/src/capture-frames.js +189 -0
- package/mcp-server/src/index.js +73 -2
- package/mcp-server/src/job-lanes.js +49 -0
- package/mcp-server/src/web-audit.js +6 -1
- package/mcp-server/src/web-explorer.js +16 -5
- package/mcp-server/src/web-flow.js +16 -0
- package/package.json +2 -2
- package/skills/tapp/SKILL.md +1 -0
- package/skills/tapp/references/commands.md +7 -0
|
@@ -16,6 +16,7 @@ import { initializeProductProject, prepareProductTarget, readProductProject, run
|
|
|
16
16
|
import { readCaptureProvenance } from "./capture-provenance.js";
|
|
17
17
|
import { collectShots } from "./html-report.js";
|
|
18
18
|
import { classifyPrompt } from "../../browser/view-model.js";
|
|
19
|
+
import { JobLanes } from "./job-lanes.js";
|
|
19
20
|
|
|
20
21
|
const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
|
|
21
22
|
const assetRoot = path.join(packageRoot, "browser");
|
|
@@ -110,15 +111,72 @@ function capturePath(captureId, relative = "report.html") {
|
|
|
110
111
|
return candidate === root || candidate.startsWith(root + path.sep) ? candidate : null;
|
|
111
112
|
}
|
|
112
113
|
|
|
114
|
+
// Captures live in one flat directory shared by every run on this machine. A public Studio has
|
|
115
|
+
// many visitors in it, so an anonymous visitor's capture is stamped with their visitor id and
|
|
116
|
+
// only ever listed or served back to them. An unstamped capture belongs to the operator.
|
|
117
|
+
const VISITOR_MARKER = ".visitor";
|
|
118
|
+
const VISITOR_COOKIE = "tapp_visitor";
|
|
119
|
+
|
|
120
|
+
// What a signed-out visitor on a public Studio may reach. Everything absent from this list is
|
|
121
|
+
// refused, so a new route is private until someone deliberately opens it.
|
|
122
|
+
function anonymousAllows(method, pathname) {
|
|
123
|
+
if (method === "GET") {
|
|
124
|
+
if (pathname === "/" || pathname === "/api/version" || pathname === "/api/session" || pathname === "/api/audits") return true;
|
|
125
|
+
if (pathname.startsWith("/assets/")) return true;
|
|
126
|
+
if (/^\/api\/captures\/[A-Za-z0-9._-]{1,128}\/files$/.test(pathname)) return true;
|
|
127
|
+
if (/^\/evidence\/captures\//.test(pathname)) return true;
|
|
128
|
+
if (/^\/api\/jobs\/[a-f0-9]{20}(\/frame)?$/.test(pathname)) return true;
|
|
129
|
+
return false;
|
|
130
|
+
}
|
|
131
|
+
// A visitor may start a read-only audit, and may *ask* about the other kinds of target so the
|
|
132
|
+
// Studio can say where they actually run. A bare 401 reads as "broken" to someone who typed a
|
|
133
|
+
// repo into the landing page, which is how five of its six examples used to dead-end.
|
|
134
|
+
return method === "POST" && ["/api/operations/audit", "/api/operations/open", "/api/operations/explore-build"].includes(pathname);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// One visitor may start a bounded number of audits per hour. Each audit drives a real browser
|
|
138
|
+
// over as many as 20 pages, so this is about the machine, not about abuse alone.
|
|
139
|
+
const AUDIT_LIMIT_PER_HOUR = 10;
|
|
140
|
+
const auditHistory = new Map();
|
|
141
|
+
function auditRateLimit(visitorId, method, pathname) {
|
|
142
|
+
if (method !== "POST" || pathname !== "/api/operations/audit") return 0;
|
|
143
|
+
const now = Date.now();
|
|
144
|
+
const hour = 60 * 60 * 1000;
|
|
145
|
+
const recent = (auditHistory.get(visitorId) || []).filter((at) => now - at < hour);
|
|
146
|
+
if (auditHistory.size > 5000) auditHistory.clear();
|
|
147
|
+
if (recent.length >= AUDIT_LIMIT_PER_HOUR) return Math.ceil((hour - (now - recent[0])) / 1000);
|
|
148
|
+
recent.push(now);
|
|
149
|
+
auditHistory.set(visitorId, recent);
|
|
150
|
+
return 0;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function captureOwner(captureId) {
|
|
154
|
+
const marker = capturePath(captureId, VISITOR_MARKER);
|
|
155
|
+
if (!marker) return null;
|
|
156
|
+
try { return fs.readFileSync(marker, "utf8").trim() || null; } catch { return null; }
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function setCaptureOwner(captureId, visitorId) {
|
|
160
|
+
const marker = capturePath(captureId, VISITOR_MARKER);
|
|
161
|
+
if (!marker || !visitorId) return;
|
|
162
|
+
try { fs.writeFileSync(marker, `${visitorId}\n`, { mode: 0o600 }); } catch { /* evidence is still written */ }
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// `owner` null means the operator, who sees every capture; a visitor id sees only their own.
|
|
166
|
+
function visibleToOwner(captureId, owner) {
|
|
167
|
+
return owner === null || captureOwner(captureId) === owner;
|
|
168
|
+
}
|
|
169
|
+
|
|
113
170
|
// Read-only website audits live in the captures directory like every other run; the Studio
|
|
114
171
|
// lists the ones with a summary file. Newest first, bounded.
|
|
115
|
-
function listAudits(limit = 50) {
|
|
172
|
+
function listAudits(limit = 50, owner = null) {
|
|
116
173
|
const root = captureRoot();
|
|
117
174
|
let names;
|
|
118
175
|
try { names = fs.readdirSync(root); } catch { return []; }
|
|
119
176
|
const audits = [];
|
|
120
177
|
for (const name of names) {
|
|
121
178
|
if (!name.startsWith("web-audit-")) continue;
|
|
179
|
+
if (!visibleToOwner(name, owner)) continue;
|
|
122
180
|
const summaryPath = path.join(root, name, "audit.json");
|
|
123
181
|
let summary;
|
|
124
182
|
try { summary = JSON.parse(fs.readFileSync(summaryPath, "utf8")); } catch { continue; }
|
|
@@ -311,7 +369,23 @@ function readFormBody(request) {
|
|
|
311
369
|
});
|
|
312
370
|
}
|
|
313
371
|
|
|
314
|
-
|
|
372
|
+
const escapeHtml = (value) => String(value)
|
|
373
|
+
.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">")
|
|
374
|
+
.replace(/"/g, """).replace(/'/g, "'");
|
|
375
|
+
|
|
376
|
+
// A path the sign-in flow may return to. Only a local path is ever accepted: anything with a
|
|
377
|
+
// scheme or authority (including the "//evil.com" protocol-relative form) would make /login an
|
|
378
|
+
// open redirect, so it is rejected rather than sanitized.
|
|
379
|
+
function safeReturnPath(raw) {
|
|
380
|
+
const value = String(raw || "");
|
|
381
|
+
if (!value.startsWith("/") || value.startsWith("//") || value.includes("\\")) return "";
|
|
382
|
+
if (value.startsWith("/login")) return "";
|
|
383
|
+
// "/" is where sign-in lands anyway; carrying it adds a querystring that says nothing.
|
|
384
|
+
if (value === "/") return "";
|
|
385
|
+
return value.slice(0, 2048);
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function serveLoginPage(response, { failed = false, next = "" } = {}) {
|
|
315
389
|
const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|
316
390
|
<title>tapp — sign in</title><style>
|
|
317
391
|
body{margin:0;min-height:100vh;display:grid;place-items:center;background:#0c1210;color:#e8efe9;font:16px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}
|
|
@@ -329,6 +403,7 @@ function serveLoginPage(response, { failed = false } = {}) {
|
|
|
329
403
|
<h1>tapp<span>.</span></h1><p class="tag">ship with proof.</p>
|
|
330
404
|
${failed ? '<p class="err" role="alert">That username or password did not match.</p>' : ""}
|
|
331
405
|
<form method="post" action="/api/auth">
|
|
406
|
+
${next ? `<input type="hidden" name="next" value="${escapeHtml(next)}">` : ""}
|
|
332
407
|
<label>Username<input name="username" autocomplete="username" placeholder="username" required></label>
|
|
333
408
|
<label>Password<input name="password" type="password" autocomplete="current-password" placeholder="password" required></label>
|
|
334
409
|
<button type="submit">Launch Tapp →</button>
|
|
@@ -339,29 +414,54 @@ function serveLoginPage(response, { failed = false } = {}) {
|
|
|
339
414
|
response.end(html);
|
|
340
415
|
}
|
|
341
416
|
|
|
342
|
-
export async function startBrowserProduct({ projectDir, port = 0, launch = false, workspaceRoot, githubProvider, publicOrigin = "", trustedProxyToken = "", directLogin = null } = {}) {
|
|
343
|
-
const hosted = !!trustedProxyToken || !!directLogin;
|
|
417
|
+
export async function startBrowserProduct({ projectDir, port = 0, launch = false, workspaceRoot, githubProvider, publicOrigin = "", trustedProxyToken = "", directLogin = null, publicEgressOnly = null, publicAccess = false } = {}) {
|
|
418
|
+
const hosted = !!trustedProxyToken || !!directLogin || !!publicAccess;
|
|
344
419
|
// publicOrigin accepts a comma-separated allowlist; the first entry is canonical.
|
|
345
420
|
const publicOrigins = String(publicOrigin || "").split(",").map((value) => value.trim().replace(/\/$/, "")).filter(Boolean);
|
|
346
421
|
if (hosted && !publicOrigins.length) throw new Error("Hosted browser mode requires an explicit publicOrigin");
|
|
347
422
|
const loginFailures = { count: 0, windowStartedAt: 0 };
|
|
423
|
+
// A hosted Studio audits whatever URL a visitor types, from a machine that can also see its
|
|
424
|
+
// own loopback services and private network. Route the browser through the egress proxy, which
|
|
425
|
+
// resolves and pins every connection — redirects and subresources included — and refuses
|
|
426
|
+
// anything that is not a public address. TAPP_ENFORCE_PUBLIC_EGRESS makes a missing proxy fail
|
|
427
|
+
// the run rather than silently reaching the private network. On by default whenever hosted:
|
|
428
|
+
// forgetting to opt in is exactly the mistake that matters here.
|
|
429
|
+
const enforcePublicEgress = publicEgressOnly === null ? hosted : !!publicEgressOnly;
|
|
430
|
+
// The engine reads the proxy off process.env, so enabling it mutates process-wide state. Keep
|
|
431
|
+
// what was there and put it back on close: a local Studio started later in the same process
|
|
432
|
+
// would otherwise inherit a proxy that no longer exists and fail every run.
|
|
433
|
+
let egressProxy = null;
|
|
434
|
+
const previousEgressEnv = {
|
|
435
|
+
server: process.env.TAPP_BROWSER_PROXY_SERVER,
|
|
436
|
+
enforce: process.env.TAPP_ENFORCE_PUBLIC_EGRESS,
|
|
437
|
+
};
|
|
438
|
+
const restoreEgressEnv = () => {
|
|
439
|
+
for (const [key, value] of [["TAPP_BROWSER_PROXY_SERVER", previousEgressEnv.server], ["TAPP_ENFORCE_PUBLIC_EGRESS", previousEgressEnv.enforce]]) {
|
|
440
|
+
if (value === undefined) delete process.env[key]; else process.env[key] = value;
|
|
441
|
+
}
|
|
442
|
+
};
|
|
443
|
+
if (enforcePublicEgress) {
|
|
444
|
+
const { startPublicBrowserProxy } = await import("./public-network.js");
|
|
445
|
+
egressProxy = await startPublicBrowserProxy();
|
|
446
|
+
process.env.TAPP_BROWSER_PROXY_SERVER = egressProxy.url;
|
|
447
|
+
process.env.TAPP_ENFORCE_PUBLIC_EGRESS = "1";
|
|
448
|
+
}
|
|
348
449
|
const registry = new BrowserWorkspaceRegistry({ initialProjectDir: projectDir, workspaceRoot, githubProvider });
|
|
349
450
|
const serverStartedAt = new Date().toISOString();
|
|
350
451
|
const sessionToken = crypto.randomBytes(32).toString("base64url");
|
|
351
452
|
const csrfToken = crypto.randomBytes(24).toString("base64url");
|
|
352
453
|
const jobs = new Map();
|
|
353
|
-
|
|
454
|
+
// Work is serialized per lane rather than globally; see job-lanes.js for why.
|
|
455
|
+
const OPERATOR_LANE = "operator";
|
|
456
|
+
const lanes = new JobLanes({ operatorLane: OPERATOR_LANE });
|
|
354
457
|
let liveSession = null;
|
|
355
458
|
let liveManagedRuntime = null;
|
|
356
459
|
let origin = "";
|
|
357
460
|
|
|
358
|
-
const startJob = (operation, work, repositoryId = registry.current()?.id || null) => {
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
throw error;
|
|
363
|
-
}
|
|
364
|
-
const job = { id: crypto.randomBytes(10).toString("hex"), operation, repositoryId, status: "running", createdAt: new Date().toISOString(), progress: [] };
|
|
461
|
+
const startJob = (operation, work, repositoryId = registry.current()?.id || null, { lane = OPERATOR_LANE } = {}) => {
|
|
462
|
+
const job = { id: crypto.randomBytes(10).toString("hex"), operation, repositoryId, lane, status: "running", createdAt: new Date().toISOString(), progress: [] };
|
|
463
|
+
const claimed = lanes.claim(lane, job);
|
|
464
|
+
if (!claimed.ok) throw Object.assign(new Error(claimed.message), { statusCode: claimed.statusCode });
|
|
365
465
|
const progress = (entry) => {
|
|
366
466
|
const normalized = typeof entry === "string" ? { text: entry } : entry || {};
|
|
367
467
|
job.progress.push({ at: new Date().toISOString(), phase: normalized.phase || operation, text: String(normalized.text || "").slice(-1200), ...(normalized.current ? { current: normalized.current, total: normalized.total } : {}), ...(normalized.screen ? { screen: String(normalized.screen).slice(0, 200) } : {}) });
|
|
@@ -371,7 +471,6 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
371
471
|
if (normalized.screenshot && path.isAbsolute(normalized.screenshot)) job.latestFrame = normalized.screenshot;
|
|
372
472
|
};
|
|
373
473
|
jobs.set(job.id, job);
|
|
374
|
-
activeMutation = job;
|
|
375
474
|
Promise.resolve().then(() => work(progress)).then((result) => {
|
|
376
475
|
job.status = "completed";
|
|
377
476
|
job.result = result;
|
|
@@ -380,7 +479,7 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
380
479
|
job.error = { message: error.message || String(error), ...(error.details ? { details: error.details } : {}) };
|
|
381
480
|
}).finally(() => {
|
|
382
481
|
job.completedAt = new Date().toISOString();
|
|
383
|
-
|
|
482
|
+
lanes.release(lane, job);
|
|
384
483
|
});
|
|
385
484
|
return job;
|
|
386
485
|
};
|
|
@@ -409,8 +508,31 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
409
508
|
}
|
|
410
509
|
const proxyAuthenticated = !!trustedProxyToken && sameSecret(request.headers["x-tapp-proxy-token"], trustedProxyToken);
|
|
411
510
|
const authenticated = proxyAuthenticated || sameSecret(cookies(request)[SESSION_COOKIE], sessionToken);
|
|
511
|
+
|
|
512
|
+
// A public Studio lets anyone in without an account, but an anonymous visitor gets a far
|
|
513
|
+
// smaller surface than the operator: audit a public website, and read back only the
|
|
514
|
+
// evidence from their own audits. Repositories, live sessions, the gate and this
|
|
515
|
+
// machine's project all stay behind authentication.
|
|
516
|
+
let visitorId = null;
|
|
517
|
+
let anonymous = false;
|
|
518
|
+
if (publicAccess && !authenticated) {
|
|
519
|
+
anonymous = true;
|
|
520
|
+
visitorId = String(cookies(request)[VISITOR_COOKIE] || "");
|
|
521
|
+
if (!/^[a-f0-9]{32}$/.test(visitorId)) {
|
|
522
|
+
visitorId = crypto.randomBytes(16).toString("hex");
|
|
523
|
+
response.setHeader("set-cookie", `${VISITOR_COOKIE}=${visitorId}; HttpOnly; SameSite=Lax; Secure; Path=/; Max-Age=2592000`);
|
|
524
|
+
}
|
|
525
|
+
if (!anonymousAllows(request.method, url.pathname)) {
|
|
526
|
+
json(response, 401, { error: "Sign in to use this. A public visitor can audit a website read-only; repositories, live sessions and the release gate need an account." });
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
529
|
+
const limited = auditRateLimit(visitorId, request.method, url.pathname);
|
|
530
|
+
if (limited) { response.writeHead(429, { "content-type": "application/json; charset=utf-8", "retry-after": String(limited) }); response.end(JSON.stringify({ error: `Too many audits from here. Try again in ${Math.ceil(limited / 60)} minute(s).` })); return; }
|
|
531
|
+
}
|
|
532
|
+
// The operator sees every capture; a visitor sees only captures stamped with their id.
|
|
533
|
+
const evidenceOwner = anonymous ? visitorId : null;
|
|
412
534
|
if (!authenticated && directLogin) {
|
|
413
|
-
if (request.method === "GET" && url.pathname === "/login") { serveLoginPage(response, { failed: url.searchParams.has("failed") }); return; }
|
|
535
|
+
if (request.method === "GET" && url.pathname === "/login") { serveLoginPage(response, { failed: url.searchParams.has("failed"), next: safeReturnPath(url.searchParams.get("next")) }); return; }
|
|
414
536
|
if (request.method === "POST" && url.pathname === "/api/auth") {
|
|
415
537
|
const now = Date.now();
|
|
416
538
|
if (now - loginFailures.windowStartedAt > 10 * 60_000) { loginFailures.windowStartedAt = now; loginFailures.count = 0; }
|
|
@@ -431,20 +553,32 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
431
553
|
if (!valid) {
|
|
432
554
|
loginFailures.count += 1;
|
|
433
555
|
await new Promise((resolve) => setTimeout(resolve, 400));
|
|
434
|
-
|
|
556
|
+
const retry = safeReturnPath(form.get("next"));
|
|
557
|
+
response.writeHead(303, { location: retry ? `/login?failed=1&next=${encodeURIComponent(retry)}` : "/login?failed=1" });
|
|
435
558
|
response.end();
|
|
436
559
|
return;
|
|
437
560
|
}
|
|
438
|
-
response.writeHead(303, { location: "/", "set-cookie": `${SESSION_COOKIE}=${encodeURIComponent(sessionToken)}; HttpOnly; SameSite=Strict; Secure; Path=/` });
|
|
561
|
+
response.writeHead(303, { location: safeReturnPath(form.get("next")) || "/", "set-cookie": `${SESSION_COOKIE}=${encodeURIComponent(sessionToken)}; HttpOnly; SameSite=Strict; Secure; Path=/` });
|
|
562
|
+
response.end();
|
|
563
|
+
return;
|
|
564
|
+
}
|
|
565
|
+
if (request.method === "GET" && !url.pathname.startsWith("/api/")) {
|
|
566
|
+
// Carry the destination through sign-in; landing on an empty Studio loses whatever
|
|
567
|
+
// the visitor asked for (the landing page sends ?target=... here).
|
|
568
|
+
const want = safeReturnPath(`${url.pathname}${url.search}`);
|
|
569
|
+
response.writeHead(302, { location: want ? `/login?next=${encodeURIComponent(want)}` : "/login" });
|
|
439
570
|
response.end();
|
|
440
571
|
return;
|
|
441
572
|
}
|
|
442
|
-
if (request.method === "GET" && !url.pathname.startsWith("/api/")) { response.writeHead(302, { location: "/login" }); response.end(); return; }
|
|
443
573
|
}
|
|
444
|
-
if (!authenticated) { response.writeHead(401, { "content-type": "text/plain; charset=utf-8" }); response.end(directLogin ? "Sign in at /login to continue." : "Open Tapp from the authenticated launch URL printed by the CLI."); return; }
|
|
574
|
+
if (!authenticated && !anonymous) { response.writeHead(401, { "content-type": "text/plain; charset=utf-8" }); response.end(directLogin ? "Sign in at /login to continue." : "Open Tapp from the authenticated launch URL printed by the CLI."); return; }
|
|
445
575
|
|
|
446
576
|
if (request.method === "GET" && url.pathname === "/") {
|
|
447
|
-
|
|
577
|
+
// Without a sign-in page there is nowhere to bounce an anonymous visitor to, and a
|
|
578
|
+
// loginUrl would send them in a loop on their first privileged 401.
|
|
579
|
+
serveBrowserIndex(response, hosted
|
|
580
|
+
? (proxyAuthenticated ? { apiBase:"/api/tapp", loginUrl:"/solutions/tapp" } : { apiBase:"", loginUrl: directLogin ? "/login" : "" })
|
|
581
|
+
: {});
|
|
448
582
|
return;
|
|
449
583
|
}
|
|
450
584
|
if (request.method === "GET" && url.pathname.startsWith("/assets/")) {
|
|
@@ -454,13 +588,27 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
454
588
|
return;
|
|
455
589
|
}
|
|
456
590
|
if (request.method === "GET" && url.pathname === "/api/session") {
|
|
591
|
+
if (anonymous) {
|
|
592
|
+
json(response, 200, {
|
|
593
|
+
csrfToken, mode: "public", product: "Tapp", root: null, repository: null, repositories: [],
|
|
594
|
+
contract: customerProductContract, supportedPlatforms: ["web"], runners: [],
|
|
595
|
+
access: "anonymous",
|
|
596
|
+
// The prompt screen offers folders, bundle ids and builds. None of them can work in
|
|
597
|
+
// a hosted Studio — there is no Mac, no simulator and no access to the visitor's
|
|
598
|
+
// disk — so say so here rather than letting the UI offer them.
|
|
599
|
+
accepts: ["url"],
|
|
600
|
+
selfHostOnly: ["path", "github", "bundle", "app", "apk"],
|
|
601
|
+
});
|
|
602
|
+
return;
|
|
603
|
+
}
|
|
457
604
|
json(response, 200, { csrfToken, mode: hosted ? "managed" : "local", product: "Tapp", root: hosted ? null : registry.currentRoot(), repository: hosted ? hostedRepository(registry.current()) : registry.current(), repositories: hosted ? registry.list().map(hostedRepository) : registry.list(), contract: customerProductContract, supportedPlatforms: customerProductContract.targetPlatforms, runners: runnerSummary({ hosted }) });
|
|
458
605
|
return;
|
|
459
606
|
}
|
|
460
607
|
if (request.method === "GET" && url.pathname === "/api/repositories") { json(response, 200, hosted ? { current:hostedRepository(registry.current()), repositories:registry.list().map(hostedRepository) } : { current: registry.current(), repositories: registry.list() }); return; }
|
|
461
|
-
if (request.method === "GET" && url.pathname === "/api/audits") { json(response, 200, { audits: hosted ? hostedPayload(
|
|
608
|
+
if (request.method === "GET" && url.pathname === "/api/audits") { const audits = listAudits(50, evidenceOwner); const explores = anonymous ? [] : listBuildExplores(); json(response, 200, { audits: hosted ? hostedPayload(audits) : audits, explores: hosted ? hostedPayload(explores) : explores }); return; }
|
|
462
609
|
const filesMatch = url.pathname.match(/^\/api\/captures\/([A-Za-z0-9._-]{1,128})\/files$/);
|
|
463
610
|
if (request.method === "GET" && filesMatch) {
|
|
611
|
+
if (!visibleToOwner(filesMatch[1], evidenceOwner)) { response.writeHead(404); response.end("Not found"); return; }
|
|
464
612
|
const files = captureFiles(filesMatch[1]);
|
|
465
613
|
if (!files) { json(response, 404, { error: "No such capture" }); return; }
|
|
466
614
|
json(response, 200, files);
|
|
@@ -482,11 +630,13 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
482
630
|
const jobMatch = url.pathname.match(/^\/api\/jobs\/([a-f0-9]{20})$/);
|
|
483
631
|
if (request.method === "GET" && jobMatch) {
|
|
484
632
|
const job = jobs.get(jobMatch[1]);
|
|
633
|
+
if (job && anonymous && job.visitorId !== visitorId) { response.writeHead(404); response.end("Not found"); return; }
|
|
485
634
|
if (!job) { json(response, 404, { error: "No such operation" }); return; }
|
|
486
635
|
json(response, 200, publicJob(job, { hosted }));
|
|
487
636
|
return;
|
|
488
637
|
}
|
|
489
638
|
const jobFrameMatch = url.pathname.match(/^\/api\/jobs\/([a-f0-9]{20})\/frame$/);
|
|
639
|
+
if (request.method === "GET" && jobFrameMatch && anonymous && jobs.get(jobFrameMatch[1])?.visitorId !== visitorId) { response.writeHead(404); response.end("Not found"); return; }
|
|
490
640
|
if (request.method === "GET" && jobFrameMatch) {
|
|
491
641
|
const job = jobs.get(jobFrameMatch[1]);
|
|
492
642
|
if (job && !job.latestFrame && job.liveSimulator && job.status === "running") {
|
|
@@ -508,6 +658,7 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
508
658
|
}
|
|
509
659
|
const captureMatch = url.pathname.match(/^\/evidence\/captures\/([A-Za-z0-9._-]{1,128})(?:\/(.*))?$/);
|
|
510
660
|
if (request.method === "GET" && captureMatch) {
|
|
661
|
+
if (!visibleToOwner(captureMatch[1], evidenceOwner)) { response.writeHead(404); response.end("Not found"); return; }
|
|
511
662
|
const file = capturePath(captureMatch[1], captureMatch[2] || "report.html");
|
|
512
663
|
if (!file) { response.writeHead(404); response.end("Not found"); return; }
|
|
513
664
|
serveFile(response, file);
|
|
@@ -516,7 +667,8 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
516
667
|
|
|
517
668
|
if (request.method === "POST" && url.pathname === "/api/repositories/select") {
|
|
518
669
|
requireMutationAuth(request, hosted ? publicOrigins : origin, csrfToken);
|
|
519
|
-
|
|
670
|
+
const busy = lanes.running(OPERATOR_LANE);
|
|
671
|
+
if (busy) throw Object.assign(new Error(`Operation '${busy.operation}' is still running`), { statusCode: 409 });
|
|
520
672
|
if (liveSession?.active) throw Object.assign(new Error("End the active live session before changing repositories"), { statusCode:409 });
|
|
521
673
|
const body = await readJsonBody(request);
|
|
522
674
|
const repository = registry.select(body.id);
|
|
@@ -535,6 +687,11 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
535
687
|
const prompt = classifyPrompt(body.input);
|
|
536
688
|
if (liveSession?.active) throw Object.assign(new Error("End the active live session before opening another project"), { statusCode: 409 });
|
|
537
689
|
if (prompt.kind === "path") {
|
|
690
|
+
if (anonymous) {
|
|
691
|
+
json(response, 200, { kind: "self-host", target: prompt.value, command: `npx -y @aarwitz/tapp@latest app ${prompt.value}`,
|
|
692
|
+
message: `A folder on your machine is not visible from the cloud. Open it with the Studio there: npx -y @aarwitz/tapp@latest app ${prompt.value}` });
|
|
693
|
+
return;
|
|
694
|
+
}
|
|
538
695
|
if (hosted) throw Object.assign(new Error("A hosted Studio cannot open a path on your machine; run `tapp app /path/to/repo` locally"), { statusCode: 400 });
|
|
539
696
|
const resolved = prompt.value.startsWith("~") ? path.join(os.homedir(), prompt.value.slice(1)) : path.resolve(prompt.value);
|
|
540
697
|
if (!fs.existsSync(resolved) || !fs.statSync(resolved).isDirectory()) throw Object.assign(new Error(`No folder at ${resolved}`), { statusCode: 400 });
|
|
@@ -543,6 +700,11 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
543
700
|
return;
|
|
544
701
|
}
|
|
545
702
|
if (prompt.kind === "github") {
|
|
703
|
+
if (anonymous) {
|
|
704
|
+
json(response, 200, { kind: "self-host", target: prompt.value, command: "npx -y @aarwitz/tapp@latest app",
|
|
705
|
+
message: `Cloning and building ${prompt.value} needs a machine with your toolchain on it. Run the Studio there and paste the same thing: npx -y @aarwitz/tapp@latest app` });
|
|
706
|
+
return;
|
|
707
|
+
}
|
|
546
708
|
const job = startJob(operation, async (progress) => ({ kind: "repository", repository: await registry.cloneGithub(prompt.value, progress) }), null);
|
|
547
709
|
json(response, 202, { job: publicJob(job, { hosted }) });
|
|
548
710
|
return;
|
|
@@ -555,6 +717,13 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
555
717
|
return;
|
|
556
718
|
}
|
|
557
719
|
if (operation === "explore-build") {
|
|
720
|
+
if (anonymous) {
|
|
721
|
+
const asked = classifyPrompt(body.input);
|
|
722
|
+
const where = asked.kind === "apk" ? "an Android device or emulator" : "a Mac with an iOS simulator";
|
|
723
|
+
json(response, 200, { kind: "self-host", target: asked.value, command: "npx -y @aarwitz/tapp@latest app",
|
|
724
|
+
message: `Running ${asked.value || "a build"} needs ${where}, which the cloud does not have. Start the Studio on that machine: npx -y @aarwitz/tapp@latest app` });
|
|
725
|
+
return;
|
|
726
|
+
}
|
|
558
727
|
if (hosted) throw Object.assign(new Error("Builds are explored on the machine that has the simulator; run the Studio locally"), { statusCode: 400 });
|
|
559
728
|
const prompt = classifyPrompt(body.input);
|
|
560
729
|
if (!["bundle", "app", "apk"].includes(prompt.kind)) throw Object.assign(new Error("Give a bundle id (com.company.app), a simulator .app, or an .apk"), { statusCode: 400 });
|
|
@@ -601,15 +770,27 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
601
770
|
try { target = new URL(String(body.url || "")); } catch { throw Object.assign(new Error("Audit needs a valid http(s) URL"), { statusCode: 400 }); }
|
|
602
771
|
if (!/^https?:$/.test(target.protocol)) throw Object.assign(new Error("Audit needs a valid http(s) URL"), { statusCode: 400 });
|
|
603
772
|
const pages = Math.max(1, Math.min(20, Number(body.pages) || 6));
|
|
773
|
+
// Mint the capture id here so the evidence can be stamped as this visitor's before the
|
|
774
|
+
// run writes anything; a capture that appeared first and was claimed afterwards would be
|
|
775
|
+
// briefly readable by everyone.
|
|
776
|
+
const auditCapture = `web-audit-${Date.now().toString(36)}-${crypto.randomBytes(6).toString("hex")}`;
|
|
777
|
+
if (visitorId) {
|
|
778
|
+
try { fs.mkdirSync(path.join(captureRoot(), auditCapture), { recursive: true }); } catch { /* the run reports its own failure */ }
|
|
779
|
+
setCaptureOwner(auditCapture, visitorId);
|
|
780
|
+
}
|
|
604
781
|
const job = startJob(operation, async (progress) => {
|
|
605
782
|
const { auditWebSite } = await import("./web-audit.js");
|
|
606
783
|
progress({ phase: "runtime", text: `Opening ${target.href} read-only (up to ${pages} pages, nothing will be clicked)` });
|
|
607
784
|
const summary = await auditWebSite({
|
|
608
|
-
url: target.href, pages, delayMs: 750, capturesDir: captureRoot(),
|
|
609
|
-
|
|
785
|
+
url: target.href, pages, delayMs: 750, capturesDir: captureRoot(), captureId: auditCapture,
|
|
786
|
+
// Hand the page's screenshot to the progress channel: the Studio's device stage polls
|
|
787
|
+
// the job's latest frame, and without this an audit watches an empty panel for its
|
|
788
|
+
// whole run while the real screenshots sit in the capture.
|
|
789
|
+
onPage: (page, n) => progress({ phase: "explore", text: `Audited ${page.url} — ${page.findings.length} finding(s)`, current: n, total: pages, ...(page.screenshot ? { screenshot: page.screenshot } : {}) }),
|
|
610
790
|
});
|
|
611
791
|
return hosted ? hostedPayload(summary) : summary;
|
|
612
|
-
}, null);
|
|
792
|
+
}, null, { lane: visitorId || OPERATOR_LANE });
|
|
793
|
+
job.visitorId = visitorId;
|
|
613
794
|
json(response, 202, { job: publicJob(job, { hosted }) });
|
|
614
795
|
return;
|
|
615
796
|
}
|
|
@@ -750,6 +931,7 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
750
931
|
if (liveManagedRuntime) await engine.stopManagedWebTarget(liveManagedRuntime).catch(() => {});
|
|
751
932
|
}
|
|
752
933
|
await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
|
|
934
|
+
if (egressProxy) { await egressProxy.close().catch(() => {}); restoreEgressEnv(); }
|
|
753
935
|
registry.close();
|
|
754
936
|
},
|
|
755
937
|
};
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
// Reading a finished run back: the states it observed, and the frame of the recording that
|
|
2
|
+
// shows each one.
|
|
3
|
+
//
|
|
4
|
+
// The engine already knows every state transition — it emits them as OCQA_STATE while the run
|
|
5
|
+
// happens. So this does not analyse the video to work out what changed; it reads the index the
|
|
6
|
+
// run wrote and seeks. A state's frame costs one seek, not a scan of several hundred frames.
|
|
7
|
+
//
|
|
8
|
+
// Everything here is read-only and works on a capture directory alone.
|
|
9
|
+
import fs from "node:fs";
|
|
10
|
+
import os from "node:os";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
import { execFile } from "node:child_process";
|
|
13
|
+
import { promisify } from "node:util";
|
|
14
|
+
|
|
15
|
+
const run = promisify(execFile);
|
|
16
|
+
|
|
17
|
+
const VIDEO_NAMES = ["exploration.webm", "replay.webm", "exploration.mp4", "replay.mp4", "exploration.mov"];
|
|
18
|
+
|
|
19
|
+
export function captureRoot() {
|
|
20
|
+
return path.join(process.env.TAPP_HOME || path.join(os.homedir(), ".tapp"), "captures");
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// A capture is addressable by id, by path, or by "latest".
|
|
24
|
+
export function resolveCapture(target = "") {
|
|
25
|
+
const value = String(target || "").trim();
|
|
26
|
+
const root = captureRoot();
|
|
27
|
+
if (!value || value === "latest") {
|
|
28
|
+
let entries = [];
|
|
29
|
+
try { entries = fs.readdirSync(root, { withFileTypes: true }).filter((e) => e.isDirectory()); } catch { return null; }
|
|
30
|
+
const newest = entries
|
|
31
|
+
.map((e) => ({ dir: path.join(root, e.name), at: fs.statSync(path.join(root, e.name)).mtimeMs }))
|
|
32
|
+
.sort((a, b) => b.at - a.at)[0];
|
|
33
|
+
return newest ? newest.dir : null;
|
|
34
|
+
}
|
|
35
|
+
const direct = path.resolve(value);
|
|
36
|
+
if (fs.existsSync(path.join(direct, "ocqa-markers.txt"))) return direct;
|
|
37
|
+
const byId = path.join(root, value);
|
|
38
|
+
if (fs.existsSync(path.join(byId, "ocqa-markers.txt"))) return byId;
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function readMarkers(dir) {
|
|
43
|
+
let text = "";
|
|
44
|
+
try { text = fs.readFileSync(path.join(dir, "ocqa-markers.txt"), "utf8"); } catch { return []; }
|
|
45
|
+
const markers = [];
|
|
46
|
+
for (const line of text.split("\n")) {
|
|
47
|
+
const match = /^OCQA_([A-Z_]+):(.*)$/.exec(line.trim());
|
|
48
|
+
if (!match) continue;
|
|
49
|
+
try { markers.push({ kind: match[1], payload: JSON.parse(match[2]) }); } catch { /* a truncated final line */ }
|
|
50
|
+
}
|
|
51
|
+
return markers;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function findRecording(dir) {
|
|
55
|
+
for (const name of VIDEO_NAMES) {
|
|
56
|
+
const candidate = path.join(dir, name);
|
|
57
|
+
if (fs.existsSync(candidate)) return candidate;
|
|
58
|
+
}
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// The screenshot a run already wrote for a state, when it named one. Older captures name it in
|
|
63
|
+
// the STATE marker; the rest are matched positionally by the state_N_ prefix the engine uses.
|
|
64
|
+
function screenshotFor(dir, state, index) {
|
|
65
|
+
if (state.screenshot && fs.existsSync(path.join(dir, state.screenshot))) return state.screenshot;
|
|
66
|
+
let names = [];
|
|
67
|
+
try { names = fs.readdirSync(dir); } catch { return null; }
|
|
68
|
+
const prefix = `state_${index + 1}_`;
|
|
69
|
+
return names.find((name) => name.startsWith(prefix)) || null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* What a finished run can show: one entry per observed state, with the time it was reached and
|
|
74
|
+
* the evidence that exists for it. `t` is milliseconds on the run's own clock; `videoAtMs` is
|
|
75
|
+
* the same instant expressed against the recording, when the run recorded one.
|
|
76
|
+
*/
|
|
77
|
+
export function captureIndex(dir) {
|
|
78
|
+
const markers = readMarkers(dir);
|
|
79
|
+
const context = markers.find((m) => m.kind === "CONTEXT")?.payload || {};
|
|
80
|
+
const recording = markers.find((m) => m.kind === "RECORDING")?.payload || null;
|
|
81
|
+
const video = findRecording(dir);
|
|
82
|
+
const issues = markers.filter((m) => m.kind === "ISSUE").map((m) => m.payload);
|
|
83
|
+
const actions = markers.filter((m) => m.kind === "ACTION").map((m) => m.payload);
|
|
84
|
+
|
|
85
|
+
const states = markers.filter((m) => m.kind === "STATE").map((m, index) => {
|
|
86
|
+
const state = m.payload;
|
|
87
|
+
const t = Number.isFinite(state.t) ? state.t : null;
|
|
88
|
+
return {
|
|
89
|
+
index: index + 1,
|
|
90
|
+
screen: state.screen || `state ${index + 1}`,
|
|
91
|
+
url: state.url || "",
|
|
92
|
+
t,
|
|
93
|
+
// A recording starts a moment after the run's clock does; subtract that offset so the
|
|
94
|
+
// seek lands on the frame that actually shows this state.
|
|
95
|
+
videoAtMs: t != null && recording ? Math.max(0, t - (recording.startsAtMs || 0)) : null,
|
|
96
|
+
screenshot: screenshotFor(dir, state, index),
|
|
97
|
+
elements: state.elements ?? null,
|
|
98
|
+
role: state.role || "",
|
|
99
|
+
controls: Array.isArray(state.controls) ? state.controls : [],
|
|
100
|
+
inputs: Array.isArray(state.inputs) ? state.inputs : [],
|
|
101
|
+
findings: issues.filter((issue) => issue.screen === state.screen).map((issue) => ({
|
|
102
|
+
type: issue.type, severity: issue.severity, title: issue.title,
|
|
103
|
+
t: Number.isFinite(issue.t) ? issue.t : null,
|
|
104
|
+
})),
|
|
105
|
+
};
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
return {
|
|
109
|
+
capture: path.basename(dir),
|
|
110
|
+
dir,
|
|
111
|
+
context,
|
|
112
|
+
recording: video ? { file: path.basename(video), path: video, startsAtMs: recording?.startsAtMs ?? null, indexed: !!recording } : null,
|
|
113
|
+
states,
|
|
114
|
+
actions: actions.length,
|
|
115
|
+
findings: issues.length,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function selectState(index, at) {
|
|
120
|
+
const value = String(at ?? "").trim();
|
|
121
|
+
if (!value) return null;
|
|
122
|
+
if (/^\d+$/.test(value)) return index.states.find((s) => s.index === Number(value)) || null;
|
|
123
|
+
const needle = value.toLowerCase();
|
|
124
|
+
return index.states.find((s) => s.screen.toLowerCase() === needle)
|
|
125
|
+
|| index.states.find((s) => s.screen.toLowerCase().includes(needle))
|
|
126
|
+
|| null;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
async function ffmpeg(args) {
|
|
130
|
+
try {
|
|
131
|
+
await run("ffmpeg", args, { timeout: 120000, maxBuffer: 8 * 1024 * 1024 });
|
|
132
|
+
return true;
|
|
133
|
+
} catch (error) {
|
|
134
|
+
if (error?.code === "ENOENT") throw Object.assign(new Error("ffmpeg is required to read frames out of a recording"), { code: "NO_FFMPEG" });
|
|
135
|
+
throw error;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// One frame, by seeking to a known instant. Falls back to the state's screenshot when the run
|
|
140
|
+
// has no recording, because the answer to "what did this screen look like" is the same.
|
|
141
|
+
export async function extractFrame(index, state, outFile) {
|
|
142
|
+
if (state?.videoAtMs != null && index.recording) {
|
|
143
|
+
await ffmpeg(["-y", "-loglevel", "error", "-ss", (state.videoAtMs / 1000).toFixed(3), "-i", index.recording.path, "-frames:v", "1", outFile]);
|
|
144
|
+
if (fs.existsSync(outFile)) return { file: outFile, from: "recording", atMs: state.videoAtMs };
|
|
145
|
+
}
|
|
146
|
+
if (state?.screenshot) {
|
|
147
|
+
const source = path.join(index.dir, state.screenshot);
|
|
148
|
+
if (fs.existsSync(source)) { fs.copyFileSync(source, outFile); return { file: outFile, from: "screenshot", atMs: state.t }; }
|
|
149
|
+
}
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Contact sheets: many frames in one image, so a run can be scanned at a glance instead of one
|
|
155
|
+
* costly frame at a time. Sampled across the recording when there is one; otherwise the
|
|
156
|
+
* screenshots the run already wrote are tiled.
|
|
157
|
+
*/
|
|
158
|
+
export async function contactSheets(index, outDir, { columns = 5, rows = 5, fps = 2, width = 320 } = {}) {
|
|
159
|
+
fs.mkdirSync(outDir, { recursive: true });
|
|
160
|
+
const pattern = path.join(outDir, "frames_%02d.png");
|
|
161
|
+
if (index.recording) {
|
|
162
|
+
await ffmpeg(["-y", "-loglevel", "error", "-i", index.recording.path,
|
|
163
|
+
"-vf", `fps=${fps},scale=${width}:-1,tile=${columns}x${rows}`, pattern]);
|
|
164
|
+
} else {
|
|
165
|
+
const shots = index.states.map((s) => s.screenshot).filter(Boolean);
|
|
166
|
+
if (!shots.length) return [];
|
|
167
|
+
const list = path.join(outDir, "shots.txt");
|
|
168
|
+
fs.writeFileSync(list, shots.map((name) => `file '${path.join(index.dir, name).replace(/'/g, "'\\''")}'`).join("\n"));
|
|
169
|
+
await ffmpeg(["-y", "-loglevel", "error", "-f", "concat", "-safe", "0", "-i", list,
|
|
170
|
+
"-vf", `scale=${width}:-1,tile=${columns}x${rows}`, pattern]);
|
|
171
|
+
fs.rmSync(list, { force: true });
|
|
172
|
+
}
|
|
173
|
+
return fs.readdirSync(outDir).filter((n) => /^frames_\d+\.png$/.test(n)).sort().map((n) => path.join(outDir, n));
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// A recording Playwright wrote as VP9 webm cannot be opened by QuickTime or Preview. Write an
|
|
177
|
+
// H.264 sibling so the evidence is playable without anyone converting it first.
|
|
178
|
+
export async function writePlayableCopy(videoPath) {
|
|
179
|
+
const target = videoPath.replace(/\.webm$/i, ".mp4");
|
|
180
|
+
if (!/\.webm$/i.test(videoPath) || fs.existsSync(target)) return fs.existsSync(target) ? target : null;
|
|
181
|
+
try {
|
|
182
|
+
await ffmpeg(["-y", "-loglevel", "error", "-i", videoPath, "-c:v", "libx264", "-preset", "veryfast",
|
|
183
|
+
"-crf", "23", "-pix_fmt", "yuv420p", "-movflags", "+faststart", target]);
|
|
184
|
+
return fs.existsSync(target) ? target : null;
|
|
185
|
+
} catch (error) {
|
|
186
|
+
if (error?.code === "NO_FFMPEG") return null;
|
|
187
|
+
throw error;
|
|
188
|
+
}
|
|
189
|
+
}
|