@aarwitz/tapp 0.18.3 → 0.19.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.
@@ -110,15 +110,72 @@ function capturePath(captureId, relative = "report.html") {
110
110
  return candidate === root || candidate.startsWith(root + path.sep) ? candidate : null;
111
111
  }
112
112
 
113
+ // Captures live in one flat directory shared by every run on this machine. A public Studio has
114
+ // many visitors in it, so an anonymous visitor's capture is stamped with their visitor id and
115
+ // only ever listed or served back to them. An unstamped capture belongs to the operator.
116
+ const VISITOR_MARKER = ".visitor";
117
+ const VISITOR_COOKIE = "tapp_visitor";
118
+
119
+ // What a signed-out visitor on a public Studio may reach. Everything absent from this list is
120
+ // refused, so a new route is private until someone deliberately opens it.
121
+ function anonymousAllows(method, pathname) {
122
+ if (method === "GET") {
123
+ if (pathname === "/" || pathname === "/api/version" || pathname === "/api/session" || pathname === "/api/audits") return true;
124
+ if (pathname.startsWith("/assets/")) return true;
125
+ if (/^\/api\/captures\/[A-Za-z0-9._-]{1,128}\/files$/.test(pathname)) return true;
126
+ if (/^\/evidence\/captures\//.test(pathname)) return true;
127
+ if (/^\/api\/jobs\/[a-f0-9]{20}(\/frame)?$/.test(pathname)) return true;
128
+ return false;
129
+ }
130
+ // A visitor may start a read-only audit, and may *ask* about the other kinds of target so the
131
+ // Studio can say where they actually run. A bare 401 reads as "broken" to someone who typed a
132
+ // repo into the landing page, which is how five of its six examples used to dead-end.
133
+ return method === "POST" && ["/api/operations/audit", "/api/operations/open", "/api/operations/explore-build"].includes(pathname);
134
+ }
135
+
136
+ // One visitor may start a bounded number of audits per hour. Each audit drives a real browser
137
+ // over as many as 20 pages, so this is about the machine, not about abuse alone.
138
+ const AUDIT_LIMIT_PER_HOUR = 10;
139
+ const auditHistory = new Map();
140
+ function auditRateLimit(visitorId, method, pathname) {
141
+ if (method !== "POST" || pathname !== "/api/operations/audit") return 0;
142
+ const now = Date.now();
143
+ const hour = 60 * 60 * 1000;
144
+ const recent = (auditHistory.get(visitorId) || []).filter((at) => now - at < hour);
145
+ if (auditHistory.size > 5000) auditHistory.clear();
146
+ if (recent.length >= AUDIT_LIMIT_PER_HOUR) return Math.ceil((hour - (now - recent[0])) / 1000);
147
+ recent.push(now);
148
+ auditHistory.set(visitorId, recent);
149
+ return 0;
150
+ }
151
+
152
+ function captureOwner(captureId) {
153
+ const marker = capturePath(captureId, VISITOR_MARKER);
154
+ if (!marker) return null;
155
+ try { return fs.readFileSync(marker, "utf8").trim() || null; } catch { return null; }
156
+ }
157
+
158
+ function setCaptureOwner(captureId, visitorId) {
159
+ const marker = capturePath(captureId, VISITOR_MARKER);
160
+ if (!marker || !visitorId) return;
161
+ try { fs.writeFileSync(marker, `${visitorId}\n`, { mode: 0o600 }); } catch { /* evidence is still written */ }
162
+ }
163
+
164
+ // `owner` null means the operator, who sees every capture; a visitor id sees only their own.
165
+ function visibleToOwner(captureId, owner) {
166
+ return owner === null || captureOwner(captureId) === owner;
167
+ }
168
+
113
169
  // Read-only website audits live in the captures directory like every other run; the Studio
114
170
  // lists the ones with a summary file. Newest first, bounded.
115
- function listAudits(limit = 50) {
171
+ function listAudits(limit = 50, owner = null) {
116
172
  const root = captureRoot();
117
173
  let names;
118
174
  try { names = fs.readdirSync(root); } catch { return []; }
119
175
  const audits = [];
120
176
  for (const name of names) {
121
177
  if (!name.startsWith("web-audit-")) continue;
178
+ if (!visibleToOwner(name, owner)) continue;
122
179
  const summaryPath = path.join(root, name, "audit.json");
123
180
  let summary;
124
181
  try { summary = JSON.parse(fs.readFileSync(summaryPath, "utf8")); } catch { continue; }
@@ -170,7 +227,7 @@ function openBrowser(url) {
170
227
  function publicJob(job, { hosted = false } = {}) {
171
228
  return {
172
229
  id: job.id, operation: job.operation, status: job.status, repositoryId: job.repositoryId || null,
173
- createdAt: job.createdAt, completedAt: job.completedAt || null, progress: job.progress.slice(-80), frame: !!job.latestFrame,
230
+ createdAt: job.createdAt, completedAt: job.completedAt || null, progress: job.progress.slice(-80), frame: !!job.latestFrame || !!job.liveSimulator, platform: job.platform || null,
174
231
  result: hosted ? hostedPayload(job.result) : job.result || null,
175
232
  error: job.error || null,
176
233
  };
@@ -311,7 +368,23 @@ function readFormBody(request) {
311
368
  });
312
369
  }
313
370
 
314
- function serveLoginPage(response, { failed = false } = {}) {
371
+ const escapeHtml = (value) => String(value)
372
+ .replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
373
+ .replace(/"/g, "&quot;").replace(/'/g, "&#39;");
374
+
375
+ // A path the sign-in flow may return to. Only a local path is ever accepted: anything with a
376
+ // scheme or authority (including the "//evil.com" protocol-relative form) would make /login an
377
+ // open redirect, so it is rejected rather than sanitized.
378
+ function safeReturnPath(raw) {
379
+ const value = String(raw || "");
380
+ if (!value.startsWith("/") || value.startsWith("//") || value.includes("\\")) return "";
381
+ if (value.startsWith("/login")) return "";
382
+ // "/" is where sign-in lands anyway; carrying it adds a querystring that says nothing.
383
+ if (value === "/") return "";
384
+ return value.slice(0, 2048);
385
+ }
386
+
387
+ function serveLoginPage(response, { failed = false, next = "" } = {}) {
315
388
  const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
316
389
  <title>tapp — sign in</title><style>
317
390
  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 +402,7 @@ function serveLoginPage(response, { failed = false } = {}) {
329
402
  <h1>tapp<span>.</span></h1><p class="tag">ship with proof.</p>
330
403
  ${failed ? '<p class="err" role="alert">That username or password did not match.</p>' : ""}
331
404
  <form method="post" action="/api/auth">
405
+ ${next ? `<input type="hidden" name="next" value="${escapeHtml(next)}">` : ""}
332
406
  <label>Username<input name="username" autocomplete="username" placeholder="username" required></label>
333
407
  <label>Password<input name="password" type="password" autocomplete="current-password" placeholder="password" required></label>
334
408
  <button type="submit">Launch Tapp →</button>
@@ -339,12 +413,38 @@ function serveLoginPage(response, { failed = false } = {}) {
339
413
  response.end(html);
340
414
  }
341
415
 
342
- export async function startBrowserProduct({ projectDir, port = 0, launch = false, workspaceRoot, githubProvider, publicOrigin = "", trustedProxyToken = "", directLogin = null } = {}) {
343
- const hosted = !!trustedProxyToken || !!directLogin;
416
+ export async function startBrowserProduct({ projectDir, port = 0, launch = false, workspaceRoot, githubProvider, publicOrigin = "", trustedProxyToken = "", directLogin = null, publicEgressOnly = null, publicAccess = false } = {}) {
417
+ const hosted = !!trustedProxyToken || !!directLogin || !!publicAccess;
344
418
  // publicOrigin accepts a comma-separated allowlist; the first entry is canonical.
345
419
  const publicOrigins = String(publicOrigin || "").split(",").map((value) => value.trim().replace(/\/$/, "")).filter(Boolean);
346
420
  if (hosted && !publicOrigins.length) throw new Error("Hosted browser mode requires an explicit publicOrigin");
347
421
  const loginFailures = { count: 0, windowStartedAt: 0 };
422
+ // A hosted Studio audits whatever URL a visitor types, from a machine that can also see its
423
+ // own loopback services and private network. Route the browser through the egress proxy, which
424
+ // resolves and pins every connection — redirects and subresources included — and refuses
425
+ // anything that is not a public address. TAPP_ENFORCE_PUBLIC_EGRESS makes a missing proxy fail
426
+ // the run rather than silently reaching the private network. On by default whenever hosted:
427
+ // forgetting to opt in is exactly the mistake that matters here.
428
+ const enforcePublicEgress = publicEgressOnly === null ? hosted : !!publicEgressOnly;
429
+ // The engine reads the proxy off process.env, so enabling it mutates process-wide state. Keep
430
+ // what was there and put it back on close: a local Studio started later in the same process
431
+ // would otherwise inherit a proxy that no longer exists and fail every run.
432
+ let egressProxy = null;
433
+ const previousEgressEnv = {
434
+ server: process.env.TAPP_BROWSER_PROXY_SERVER,
435
+ enforce: process.env.TAPP_ENFORCE_PUBLIC_EGRESS,
436
+ };
437
+ const restoreEgressEnv = () => {
438
+ for (const [key, value] of [["TAPP_BROWSER_PROXY_SERVER", previousEgressEnv.server], ["TAPP_ENFORCE_PUBLIC_EGRESS", previousEgressEnv.enforce]]) {
439
+ if (value === undefined) delete process.env[key]; else process.env[key] = value;
440
+ }
441
+ };
442
+ if (enforcePublicEgress) {
443
+ const { startPublicBrowserProxy } = await import("./public-network.js");
444
+ egressProxy = await startPublicBrowserProxy();
445
+ process.env.TAPP_BROWSER_PROXY_SERVER = egressProxy.url;
446
+ process.env.TAPP_ENFORCE_PUBLIC_EGRESS = "1";
447
+ }
348
448
  const registry = new BrowserWorkspaceRegistry({ initialProjectDir: projectDir, workspaceRoot, githubProvider });
349
449
  const serverStartedAt = new Date().toISOString();
350
450
  const sessionToken = crypto.randomBytes(32).toString("base64url");
@@ -409,8 +509,31 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
409
509
  }
410
510
  const proxyAuthenticated = !!trustedProxyToken && sameSecret(request.headers["x-tapp-proxy-token"], trustedProxyToken);
411
511
  const authenticated = proxyAuthenticated || sameSecret(cookies(request)[SESSION_COOKIE], sessionToken);
512
+
513
+ // A public Studio lets anyone in without an account, but an anonymous visitor gets a far
514
+ // smaller surface than the operator: audit a public website, and read back only the
515
+ // evidence from their own audits. Repositories, live sessions, the gate and this
516
+ // machine's project all stay behind authentication.
517
+ let visitorId = null;
518
+ let anonymous = false;
519
+ if (publicAccess && !authenticated) {
520
+ anonymous = true;
521
+ visitorId = String(cookies(request)[VISITOR_COOKIE] || "");
522
+ if (!/^[a-f0-9]{32}$/.test(visitorId)) {
523
+ visitorId = crypto.randomBytes(16).toString("hex");
524
+ response.setHeader("set-cookie", `${VISITOR_COOKIE}=${visitorId}; HttpOnly; SameSite=Lax; Secure; Path=/; Max-Age=2592000`);
525
+ }
526
+ if (!anonymousAllows(request.method, url.pathname)) {
527
+ 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." });
528
+ return;
529
+ }
530
+ const limited = auditRateLimit(visitorId, request.method, url.pathname);
531
+ 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; }
532
+ }
533
+ // The operator sees every capture; a visitor sees only captures stamped with their id.
534
+ const evidenceOwner = anonymous ? visitorId : null;
412
535
  if (!authenticated && directLogin) {
413
- if (request.method === "GET" && url.pathname === "/login") { serveLoginPage(response, { failed: url.searchParams.has("failed") }); return; }
536
+ if (request.method === "GET" && url.pathname === "/login") { serveLoginPage(response, { failed: url.searchParams.has("failed"), next: safeReturnPath(url.searchParams.get("next")) }); return; }
414
537
  if (request.method === "POST" && url.pathname === "/api/auth") {
415
538
  const now = Date.now();
416
539
  if (now - loginFailures.windowStartedAt > 10 * 60_000) { loginFailures.windowStartedAt = now; loginFailures.count = 0; }
@@ -431,20 +554,32 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
431
554
  if (!valid) {
432
555
  loginFailures.count += 1;
433
556
  await new Promise((resolve) => setTimeout(resolve, 400));
434
- response.writeHead(303, { location: "/login?failed=1" });
557
+ const retry = safeReturnPath(form.get("next"));
558
+ response.writeHead(303, { location: retry ? `/login?failed=1&next=${encodeURIComponent(retry)}` : "/login?failed=1" });
435
559
  response.end();
436
560
  return;
437
561
  }
438
- response.writeHead(303, { location: "/", "set-cookie": `${SESSION_COOKIE}=${encodeURIComponent(sessionToken)}; HttpOnly; SameSite=Strict; Secure; Path=/` });
562
+ response.writeHead(303, { location: safeReturnPath(form.get("next")) || "/", "set-cookie": `${SESSION_COOKIE}=${encodeURIComponent(sessionToken)}; HttpOnly; SameSite=Strict; Secure; Path=/` });
563
+ response.end();
564
+ return;
565
+ }
566
+ if (request.method === "GET" && !url.pathname.startsWith("/api/")) {
567
+ // Carry the destination through sign-in; landing on an empty Studio loses whatever
568
+ // the visitor asked for (the landing page sends ?target=... here).
569
+ const want = safeReturnPath(`${url.pathname}${url.search}`);
570
+ response.writeHead(302, { location: want ? `/login?next=${encodeURIComponent(want)}` : "/login" });
439
571
  response.end();
440
572
  return;
441
573
  }
442
- if (request.method === "GET" && !url.pathname.startsWith("/api/")) { response.writeHead(302, { location: "/login" }); response.end(); return; }
443
574
  }
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; }
575
+ 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
576
 
446
577
  if (request.method === "GET" && url.pathname === "/") {
447
- serveBrowserIndex(response, hosted ? (proxyAuthenticated ? { apiBase:"/api/tapp", loginUrl:"/solutions/tapp" } : { apiBase:"", loginUrl:"/login" }) : {});
578
+ // Without a sign-in page there is nowhere to bounce an anonymous visitor to, and a
579
+ // loginUrl would send them in a loop on their first privileged 401.
580
+ serveBrowserIndex(response, hosted
581
+ ? (proxyAuthenticated ? { apiBase:"/api/tapp", loginUrl:"/solutions/tapp" } : { apiBase:"", loginUrl: directLogin ? "/login" : "" })
582
+ : {});
448
583
  return;
449
584
  }
450
585
  if (request.method === "GET" && url.pathname.startsWith("/assets/")) {
@@ -454,13 +589,27 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
454
589
  return;
455
590
  }
456
591
  if (request.method === "GET" && url.pathname === "/api/session") {
592
+ if (anonymous) {
593
+ json(response, 200, {
594
+ csrfToken, mode: "public", product: "Tapp", root: null, repository: null, repositories: [],
595
+ contract: customerProductContract, supportedPlatforms: ["web"], runners: [],
596
+ access: "anonymous",
597
+ // The prompt screen offers folders, bundle ids and builds. None of them can work in
598
+ // a hosted Studio — there is no Mac, no simulator and no access to the visitor's
599
+ // disk — so say so here rather than letting the UI offer them.
600
+ accepts: ["url"],
601
+ selfHostOnly: ["path", "github", "bundle", "app", "apk"],
602
+ });
603
+ return;
604
+ }
457
605
  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
606
  return;
459
607
  }
460
608
  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(listAudits()) : listAudits(), explores: hosted ? hostedPayload(listBuildExplores()) : listBuildExplores() }); return; }
609
+ 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
610
  const filesMatch = url.pathname.match(/^\/api\/captures\/([A-Za-z0-9._-]{1,128})\/files$/);
463
611
  if (request.method === "GET" && filesMatch) {
612
+ if (!visibleToOwner(filesMatch[1], evidenceOwner)) { response.writeHead(404); response.end("Not found"); return; }
464
613
  const files = captureFiles(filesMatch[1]);
465
614
  if (!files) { json(response, 404, { error: "No such capture" }); return; }
466
615
  json(response, 200, files);
@@ -482,13 +631,26 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
482
631
  const jobMatch = url.pathname.match(/^\/api\/jobs\/([a-f0-9]{20})$/);
483
632
  if (request.method === "GET" && jobMatch) {
484
633
  const job = jobs.get(jobMatch[1]);
634
+ if (job && anonymous && job.visitorId !== visitorId) { response.writeHead(404); response.end("Not found"); return; }
485
635
  if (!job) { json(response, 404, { error: "No such operation" }); return; }
486
636
  json(response, 200, publicJob(job, { hosted }));
487
637
  return;
488
638
  }
489
639
  const jobFrameMatch = url.pathname.match(/^\/api\/jobs\/([a-f0-9]{20})\/frame$/);
640
+ if (request.method === "GET" && jobFrameMatch && anonymous && jobs.get(jobFrameMatch[1])?.visitorId !== visitorId) { response.writeHead(404); response.end("Not found"); return; }
490
641
  if (request.method === "GET" && jobFrameMatch) {
491
642
  const job = jobs.get(jobFrameMatch[1]);
643
+ if (job && !job.latestFrame && job.liveSimulator && job.status === "running") {
644
+ // An iOS exploration drives the booted simulator; photograph it (throttled) the way a
645
+ // live session does, so the stage shows the device while the run happens.
646
+ const engine = await import("./index.js");
647
+ const frame = await engine.captureScreenshotImage(1000);
648
+ if (frame?.error) { json(response, 404, { error: frame.error }); return; }
649
+ const data = Buffer.from(frame.data, "base64");
650
+ response.writeHead(200, { "content-type": frame.mimeType || "image/jpeg", "content-length": data.length, "cache-control": "no-store", "x-content-type-options": "nosniff" });
651
+ response.end(data);
652
+ return;
653
+ }
492
654
  if (!job?.latestFrame || !fs.existsSync(job.latestFrame)) { json(response, 404, { error: "No exploration frame yet" }); return; }
493
655
  const data = fs.readFileSync(job.latestFrame);
494
656
  response.writeHead(200, { "content-type": job.latestFrame.endsWith(".jpg") || job.latestFrame.endsWith(".jpeg") ? "image/jpeg" : "image/png", "content-length": data.length, "cache-control": "no-store", "x-content-type-options": "nosniff" });
@@ -497,6 +659,7 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
497
659
  }
498
660
  const captureMatch = url.pathname.match(/^\/evidence\/captures\/([A-Za-z0-9._-]{1,128})(?:\/(.*))?$/);
499
661
  if (request.method === "GET" && captureMatch) {
662
+ if (!visibleToOwner(captureMatch[1], evidenceOwner)) { response.writeHead(404); response.end("Not found"); return; }
500
663
  const file = capturePath(captureMatch[1], captureMatch[2] || "report.html");
501
664
  if (!file) { response.writeHead(404); response.end("Not found"); return; }
502
665
  serveFile(response, file);
@@ -524,6 +687,11 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
524
687
  const prompt = classifyPrompt(body.input);
525
688
  if (liveSession?.active) throw Object.assign(new Error("End the active live session before opening another project"), { statusCode: 409 });
526
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
+ }
527
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 });
528
696
  const resolved = prompt.value.startsWith("~") ? path.join(os.homedir(), prompt.value.slice(1)) : path.resolve(prompt.value);
529
697
  if (!fs.existsSync(resolved) || !fs.statSync(resolved).isDirectory()) throw Object.assign(new Error(`No folder at ${resolved}`), { statusCode: 400 });
@@ -532,6 +700,11 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
532
700
  return;
533
701
  }
534
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
+ }
535
708
  const job = startJob(operation, async (progress) => ({ kind: "repository", repository: await registry.cloneGithub(prompt.value, progress) }), null);
536
709
  json(response, 202, { job: publicJob(job, { hosted }) });
537
710
  return;
@@ -544,11 +717,20 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
544
717
  return;
545
718
  }
546
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
+ }
547
727
  if (hosted) throw Object.assign(new Error("Builds are explored on the machine that has the simulator; run the Studio locally"), { statusCode: 400 });
548
728
  const prompt = classifyPrompt(body.input);
549
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 });
550
730
  const job = startJob(operation, async (progress) => {
551
731
  const engine = await import("./index.js");
732
+ job.platform = prompt.kind === "apk" ? "android" : "ios";
733
+ job.liveSimulator = job.platform === "ios";
552
734
  const forward = (entry) => progress({ phase: "explore", text: entry.narrative || `${entry.action || 0}/${entry.max || 0} actions · ${entry.states || 0} states`, ...(entry.action ? { current: entry.action, total: entry.max } : {}), ...(entry.screen ? { screen: entry.screen } : {}), ...(entry.screenshot ? { screenshot: entry.screenshot } : {}) });
553
735
  let result;
554
736
  if (prompt.kind === "apk") {
@@ -588,15 +770,27 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
588
770
  try { target = new URL(String(body.url || "")); } catch { throw Object.assign(new Error("Audit needs a valid http(s) URL"), { statusCode: 400 }); }
589
771
  if (!/^https?:$/.test(target.protocol)) throw Object.assign(new Error("Audit needs a valid http(s) URL"), { statusCode: 400 });
590
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
+ }
591
781
  const job = startJob(operation, async (progress) => {
592
782
  const { auditWebSite } = await import("./web-audit.js");
593
783
  progress({ phase: "runtime", text: `Opening ${target.href} read-only (up to ${pages} pages, nothing will be clicked)` });
594
784
  const summary = await auditWebSite({
595
- url: target.href, pages, delayMs: 750, capturesDir: captureRoot(),
596
- onPage: (page, n) => progress({ phase: "explore", text: `Audited ${page.url} — ${page.findings.length} finding(s)`, current: n, total: pages }),
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 } : {}) }),
597
790
  });
598
791
  return hosted ? hostedPayload(summary) : summary;
599
792
  }, null);
793
+ job.visitorId = visitorId;
600
794
  json(response, 202, { job: publicJob(job, { hosted }) });
601
795
  return;
602
796
  }
@@ -737,6 +931,7 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
737
931
  if (liveManagedRuntime) await engine.stopManagedWebTarget(liveManagedRuntime).catch(() => {});
738
932
  }
739
933
  await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
934
+ if (egressProxy) { await egressProxy.close().catch(() => {}); restoreEgressEnv(); }
740
935
  registry.close();
741
936
  },
742
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
+ }