@aarwitz/tapp 0.21.2 → 0.23.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.
@@ -17,6 +17,9 @@ import { readCaptureProvenance } from "./capture-provenance.js";
17
17
  import { collectShots } from "./html-report.js";
18
18
  import { classifyPrompt } from "../../browser/view-model.js";
19
19
  import { JobLanes } from "./job-lanes.js";
20
+ import { AccountStore } from "./account-store.js";
21
+ import { ActorStore, hostKey } from "./actor-store.js";
22
+ import { createMailer, signInMessage } from "./mailer.js";
20
23
 
21
24
  const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
22
25
  const assetRoot = path.join(packageRoot, "browser");
@@ -116,6 +119,9 @@ function capturePath(captureId, relative = "report.html") {
116
119
  // only ever listed or served back to them. An unstamped capture belongs to the operator.
117
120
  const VISITOR_MARKER = ".visitor";
118
121
  const VISITOR_COOKIE = "tapp_visitor";
122
+ // A signed-in tapp account on a public Studio (ADR-0009 slice 2). The cookie is a session token
123
+ // whose hash the account store knows; see account-store.js.
124
+ const ACCOUNT_COOKIE = "tapp_account";
119
125
 
120
126
  // What a signed-out visitor on a public Studio may reach. Everything absent from this list is
121
127
  // refused, so a new route is private until someone deliberately opens it.
@@ -126,12 +132,29 @@ function anonymousAllows(method, pathname) {
126
132
  if (/^\/api\/captures\/[A-Za-z0-9._-]{1,128}\/files$/.test(pathname)) return true;
127
133
  if (/^\/evidence\/captures\//.test(pathname)) return true;
128
134
  if (/^\/api\/jobs\/[a-f0-9]{20}(\/frame)?$/.test(pathname)) return true;
135
+ // Following a sign-in link from an email.
136
+ if (/^\/auth\/[A-Za-z0-9_-]{20,}$/.test(pathname)) return true;
129
137
  return false;
130
138
  }
139
+ // Asking for a sign-in link is the one thing a stranger may post besides a run.
140
+ if (method === "POST" && pathname === "/api/auth/link") return true;
131
141
  // A visitor may start a read-only audit, and may *ask* about the other kinds of target so the
132
142
  // Studio can say where they actually run. A bare 401 reads as "broken" to someone who typed a
133
143
  // 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);
144
+ // `explore` is listed so a visitor receives the honest "run this on your own machine" answer
145
+ // from the handler, rather than a bare 401 that reads as broken.
146
+ return method === "POST" && ["/api/operations/audit", "/api/operations/open", "/api/operations/explore-build", "/api/operations/explore"].includes(pathname);
147
+ }
148
+
149
+ // A signed-in account may do what a visitor may, plus: start a real exploration (which can stop
150
+ // at a sign-in and ask), answer that ask, and see and forget the test accounts it has stored.
151
+ // Repositories, live sessions and the gate stay the operator's — they are this machine's.
152
+ function accountAllows(method, pathname) {
153
+ if (anonymousAllows(method, pathname)) return true;
154
+ if (method === "POST" && (pathname === "/api/auth/signout" || /^\/api\/jobs\/[a-f0-9]{20}\/input$/.test(pathname))) return true;
155
+ if (method === "GET" && pathname === "/api/actors") return true;
156
+ if (method === "DELETE" && /^\/api\/actors\/[A-Za-z0-9.:-]{1,253}\/[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(pathname)) return true;
157
+ return false;
135
158
  }
136
159
 
137
160
  // One visitor may start a bounded number of audits per hour. Each audit drives a real browser
@@ -139,7 +162,7 @@ function anonymousAllows(method, pathname) {
139
162
  const AUDIT_LIMIT_PER_HOUR = 10;
140
163
  const auditHistory = new Map();
141
164
  function auditRateLimit(visitorId, method, pathname) {
142
- if (method !== "POST" || pathname !== "/api/operations/audit") return 0;
165
+ if (method !== "POST" || !["/api/operations/audit", "/api/operations/explore"].includes(pathname)) return 0;
143
166
  const now = Date.now();
144
167
  const hour = 60 * 60 * 1000;
145
168
  const recent = (auditHistory.get(visitorId) || []).filter((at) => now - at < hour);
@@ -202,12 +225,13 @@ function captureFiles(captureId) {
202
225
 
203
226
  // Explorations started from the prompt (a bundle id, an .app or .apk) have no repository to list
204
227
  // them under; they are listed from their captures like audits are.
205
- function listBuildExplores(limit = 50) {
228
+ function listBuildExplores(limit = 50, owner = null) {
206
229
  const root = captureRoot();
207
230
  let names;
208
231
  try { names = fs.readdirSync(root); } catch { return []; }
209
232
  const runs = [];
210
233
  for (const name of names) {
234
+ if (!visibleToOwner(name, owner)) continue;
211
235
  const provenance = readCaptureProvenance(path.join(root, name));
212
236
  if (!provenance || provenance.kind !== "explore" || provenance.origin !== "studio-prompt") continue;
213
237
  let report = null;
@@ -217,6 +241,19 @@ function listBuildExplores(limit = 50) {
217
241
  return runs.sort((a, b) => b.createdAt.localeCompare(a.createdAt)).slice(0, limit);
218
242
  }
219
243
 
244
+ // Mark a capture as prompt-started so the Studio lists it in Runs without a repository. The
245
+ // report summary beside it is what the list row and detail read; the capture stays the evidence.
246
+ function markPromptStarted(structured) {
247
+ try {
248
+ const captureDir = structured?.capture?.path;
249
+ if (!captureDir) return;
250
+ const provenancePath = path.join(captureDir, "provenance.json");
251
+ const provenance = JSON.parse(fs.readFileSync(provenancePath, "utf8"));
252
+ fs.writeFileSync(provenancePath, JSON.stringify({ ...provenance, origin: "studio-prompt" }, null, 2));
253
+ fs.writeFileSync(path.join(captureDir, "report.json"), JSON.stringify({ headline: structured.headline, inconclusive: structured.inconclusive, screensExplored: structured.screensExplored, actionsPerformed: structured.actionsPerformed, findingCounts: structured.findingCounts, findings: structured.findings, checkedFor: structured.checkedFor, notChecked: structured.notChecked, platform: structured.platform, target: structured.target }, null, 2));
254
+ } catch { /* listing is a convenience; the capture is the evidence */ }
255
+ }
256
+
220
257
  function openBrowser(url) {
221
258
  const invocation = process.platform === "darwin" ? ["open", [url]]
222
259
  : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]]
@@ -231,6 +268,8 @@ function publicJob(job, { hosted = false } = {}) {
231
268
  createdAt: job.createdAt, completedAt: job.completedAt || null, progress: job.progress.slice(-80), frame: !!job.latestFrame || !!job.liveSimulator, platform: job.platform || null,
232
269
  result: hosted ? hostedPayload(job.result) : job.result || null,
233
270
  error: job.error || null,
271
+ // Fields only (labels, which are secure); what the person typed never travels back out.
272
+ input: job.input ? { requestId: job.input.requestId, screen: job.input.screen, fields: job.input.fields, askedAt: job.input.askedAt } : null,
234
273
  };
235
274
  }
236
275
 
@@ -447,6 +486,10 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
447
486
  process.env.TAPP_ENFORCE_PUBLIC_EGRESS = "1";
448
487
  }
449
488
  const registry = new BrowserWorkspaceRegistry({ initialProjectDir: projectDir, workspaceRoot, githubProvider });
489
+ // Accounts exist only on a public Studio: a local one has exactly one person, the operator.
490
+ const accounts = publicAccess ? new AccountStore() : null;
491
+ const mailer = publicAccess ? createMailer() : null;
492
+ const secureCookies = publicOrigins[0]?.startsWith("https:") ?? false;
450
493
  const serverStartedAt = new Date().toISOString();
451
494
  const sessionToken = crypto.randomBytes(32).toString("base64url");
452
495
  const csrfToken = crypto.randomBytes(24).toString("base64url");
@@ -509,6 +552,10 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
509
552
  // The engine names the screenshot it just wrote; the Studio device panel polls it as the
510
553
  // exploration feed. Only engine-supplied paths ever land here, never client input.
511
554
  if (normalized.screenshot && path.isAbsolute(normalized.screenshot)) job.latestFrame = normalized.screenshot;
555
+ // A pause-and-ask from the engine (OCQA_AWAIT_INPUT): keep the request on the job so the
556
+ // Studio can render it, and clear it once the engine says it was resolved.
557
+ if (normalized.awaitInput && typeof normalized.awaitInput === "object") job.input = { ...normalized.awaitInput, askedAt: new Date().toISOString() };
558
+ if (normalized.inputResolved) job.input = null;
512
559
  };
513
560
  jobs.set(job.id, job);
514
561
  Promise.resolve().then(() => work(progress)).then((result) => {
@@ -556,7 +603,13 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
556
603
  // machine's project all stay behind authentication.
557
604
  let visitorId = null;
558
605
  let anonymous = false;
559
- if (publicAccess && !authenticated) {
606
+ // A signed-in account sits between the two: more than a visitor, less than the operator.
607
+ const account = publicAccess && !authenticated ? accounts.sessionAccount(cookies(request)[ACCOUNT_COOKIE] || "") : null;
608
+ if (account && !accountAllows(request.method, url.pathname)) {
609
+ json(response, 401, { error: "That part of the Studio runs on your own machine: npx -y @aarwitz/tapp@latest app" });
610
+ return;
611
+ }
612
+ if (publicAccess && !authenticated && !account) {
560
613
  anonymous = true;
561
614
  visitorId = String(cookies(request)[VISITOR_COOKIE] || "");
562
615
  const returning = /^[a-f0-9]{32}$/.test(visitorId);
@@ -586,8 +639,17 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
586
639
  const limited = auditRateLimit(visitorId, request.method, url.pathname);
587
640
  if (limited) { usage.refusals += 1; logUsage("refused", { visitor: visitorId.slice(0, 8), reason: "rate-limit", retryAfterSec: limited, status: 429 }); 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; }
588
641
  }
589
- // The operator sees every capture; a visitor sees only captures stamped with their id.
590
- const evidenceOwner = anonymous ? visitorId : null;
642
+ // The operator sees every capture; a visitor sees only captures stamped with their id, an
643
+ // account only the ones stamped with its id. `ownerKey` is also the job lane: one person's
644
+ // runs queue behind each other, never behind a stranger's.
645
+ const ownerKey = anonymous ? visitorId : account ? `acct:${account.id}` : null;
646
+ const evidenceOwner = ownerKey;
647
+ if (account) {
648
+ const limited = auditRateLimit(ownerKey, request.method, url.pathname);
649
+ if (limited) { response.writeHead(429, { "content-type": "application/json; charset=utf-8", "retry-after": String(limited) }); response.end(JSON.stringify({ error: `Too many runs from this account. Try again in ${Math.ceil(limited / 60)} minute(s).` })); return; }
650
+ }
651
+ // A job belongs to whoever started it; the operator sees them all.
652
+ const jobVisible = (job) => !!job && (ownerKey === null || job.ownerKey === ownerKey);
591
653
  if (!authenticated && directLogin) {
592
654
  if (request.method === "GET" && url.pathname === "/login") { serveLoginPage(response, { failed: url.searchParams.has("failed"), next: safeReturnPath(url.searchParams.get("next")) }); return; }
593
655
  if (request.method === "POST" && url.pathname === "/api/auth") {
@@ -628,7 +690,7 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
628
690
  return;
629
691
  }
630
692
  }
631
- 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; }
693
+ if (!authenticated && !anonymous && !account) { 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; }
632
694
 
633
695
  if (request.method === "GET" && url.pathname === "/") {
634
696
  // Without a sign-in page there is nowhere to bounce an anonymous visitor to, and a
@@ -644,7 +706,73 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
644
706
  serveFile(response, file);
645
707
  return;
646
708
  }
709
+ // Signing in: an email address gets a link; the link, used once, becomes a session cookie.
710
+ // The response to the request is the same whether or not the address was ever seen, so
711
+ // this cannot be used to find out who has an account.
712
+ if (publicAccess && request.method === "POST" && url.pathname === "/api/auth/link") {
713
+ requireMutationAuth(request, publicOrigins, csrfToken);
714
+ const body = await readJsonBody(request);
715
+ let link;
716
+ try { link = accounts.requestLink(body.email); }
717
+ catch (error) { json(response, error.statusCode || 400, { error: error.message }); return; }
718
+ const message = signInMessage({ to: link.email, link: `${publicOrigins[0]}/auth/${link.token}`, origin: publicOrigins[0] });
719
+ try {
720
+ const sent = await mailer.send(message);
721
+ logUsage("signin.link", { transport: sent.transport });
722
+ } catch (error) {
723
+ logUsage("signin.link.failed", { transport: mailer.transport, error: String(error.message || error).slice(0, 200) });
724
+ json(response, 502, { error: "The sign-in email could not be sent right now. Try again in a minute." });
725
+ return;
726
+ }
727
+ json(response, 200, { ok: true, sent: true });
728
+ return;
729
+ }
730
+ const authLinkMatch = publicAccess && request.method === "GET" ? url.pathname.match(/^\/auth\/([A-Za-z0-9_-]{20,})$/) : null;
731
+ if (authLinkMatch) {
732
+ const signedIn = accounts.redeem(authLinkMatch[1]);
733
+ if (!signedIn) { response.writeHead(303, { location: "/?signin=expired" }); response.end(); return; }
734
+ logUsage("signin.done", { account: signedIn.account.id.slice(0, 8) });
735
+ response.writeHead(303, { location: "/?signin=done", "set-cookie": `${ACCOUNT_COOKIE}=${encodeURIComponent(signedIn.session)}; HttpOnly; SameSite=Lax;${secureCookies ? " Secure;" : ""} Path=/; Max-Age=7776000` });
736
+ response.end();
737
+ return;
738
+ }
739
+ if (account && request.method === "POST" && url.pathname === "/api/auth/signout") {
740
+ requireMutationAuth(request, publicOrigins, csrfToken);
741
+ accounts.signOut(cookies(request)[ACCOUNT_COOKIE] || "");
742
+ response.writeHead(200, { "content-type": "application/json; charset=utf-8", "set-cookie": `${ACCOUNT_COOKIE}=; HttpOnly; SameSite=Lax;${secureCookies ? " Secure;" : ""} Path=/; Max-Age=0` });
743
+ response.end(JSON.stringify({ ok: true }));
744
+ return;
745
+ }
746
+ // The test accounts tapp has been told about, by application: names and whether a password
747
+ // or a signed-in session is held — never the values. An account sees its own; the operator
748
+ // sees this machine's.
749
+ const actorRootFor = () => (account ? accounts.actorRoot(account.id) : undefined);
750
+ if (!anonymous && request.method === "GET" && url.pathname === "/api/actors") {
751
+ const store = new ActorStore(actorRootFor() ? { root: actorRootFor() } : {});
752
+ let hosts = [];
753
+ try { hosts = fs.readdirSync(store.root, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name); } catch { /* none yet */ }
754
+ json(response, 200, { apps: hosts.map((host) => ({ host, actors: store.list(`https://${host}/`) })).filter((app) => app.actors.length) });
755
+ return;
756
+ }
757
+ const actorForgetMatch = !anonymous && request.method === "DELETE" ? url.pathname.match(/^\/api\/actors\/([A-Za-z0-9.:-]{1,253})\/([A-Za-z][A-Za-z0-9_-]{0,63})$/) : null;
758
+ if (actorForgetMatch) {
759
+ requireMutationAuth(request, hosted ? publicOrigins : origin, csrfToken);
760
+ const store = new ActorStore(actorRootFor() ? { root: actorRootFor() } : {});
761
+ store.forget(`https://${actorForgetMatch[1]}/`, actorForgetMatch[2]);
762
+ json(response, 200, { ok: true });
763
+ return;
764
+ }
647
765
  if (request.method === "GET" && url.pathname === "/api/session") {
766
+ if (account) {
767
+ json(response, 200, {
768
+ csrfToken, mode: "public", product: "Tapp", root: null, repository: null, repositories: [],
769
+ contract: customerProductContract, supportedPlatforms: ["web"], runners: [],
770
+ access: "account", email: account.email,
771
+ accepts: ["url"],
772
+ selfHostOnly: ["path", "github", "bundle", "app", "apk"],
773
+ });
774
+ return;
775
+ }
648
776
  if (anonymous) {
649
777
  json(response, 200, {
650
778
  csrfToken, mode: "public", product: "Tapp", root: null, repository: null, repositories: [],
@@ -662,7 +790,7 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
662
790
  return;
663
791
  }
664
792
  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; }
665
- 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; }
793
+ if (request.method === "GET" && url.pathname === "/api/audits") { const audits = listAudits(50, evidenceOwner); const explores = anonymous ? [] : listBuildExplores(50, evidenceOwner); json(response, 200, { audits: hosted ? hostedPayload(audits) : audits, explores: hosted ? hostedPayload(explores) : explores }); return; }
666
794
  const filesMatch = url.pathname.match(/^\/api\/captures\/([A-Za-z0-9._-]{1,128})\/files$/);
667
795
  if (request.method === "GET" && filesMatch) {
668
796
  if (!visibleToOwner(filesMatch[1], evidenceOwner)) { response.writeHead(404); response.end("Not found"); return; }
@@ -687,13 +815,36 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
687
815
  const jobMatch = url.pathname.match(/^\/api\/jobs\/([a-f0-9]{20})$/);
688
816
  if (request.method === "GET" && jobMatch) {
689
817
  const job = jobs.get(jobMatch[1]);
690
- if (job && anonymous && job.visitorId !== visitorId) { response.writeHead(404); response.end("Not found"); return; }
818
+ if (job && !jobVisible(job)) { response.writeHead(404); response.end("Not found"); return; }
691
819
  if (!job) { json(response, 404, { error: "No such operation" }); return; }
692
820
  json(response, 200, publicJob(job, { hosted }));
693
821
  return;
694
822
  }
823
+ // Answering an ask. Only the operator may: an anonymous visitor is never asked (see the
824
+ // explore operation below), and this is the one place typed credentials pass through the
825
+ // server — straight to the engine's response file (0600), optionally into the encrypted
826
+ // actor store, and nowhere else. They are not logged and not kept on the job.
827
+ const jobInputMatch = url.pathname.match(/^\/api\/jobs\/([a-f0-9]{20})\/input$/);
828
+ if (request.method === "POST" && jobInputMatch) {
829
+ if (anonymous) { response.writeHead(401); response.end("Sign in to answer a run"); return; }
830
+ requireMutationAuth(request, hosted ? publicOrigins : origin, csrfToken);
831
+ const job = jobs.get(jobInputMatch[1]);
832
+ if (job && !jobVisible(job)) { response.writeHead(404); response.end("Not found"); return; }
833
+ if (!job || !job.input || !job.inputResponsePath) { json(response, 409, { error: "This run is not waiting for anything" }); return; }
834
+ const body = await readJsonBody(request);
835
+ const action = ["submit", "defaults", "skip", "dont_ask"].includes(body.action) ? body.action : "skip";
836
+ const values = action === "submit" && body.values && typeof body.values === "object"
837
+ ? Object.fromEntries(Object.entries(body.values).filter(([k, v]) => typeof k === "string" && typeof v === "string").map(([k, v]) => [k.slice(0, 64), v.slice(0, 512)]))
838
+ : {};
839
+ fs.writeFileSync(job.inputResponsePath, JSON.stringify({ requestId: job.input.requestId, action, values }), { mode: 0o600 });
840
+ if (action === "submit" && body.remember === true && job.actorTarget) {
841
+ new ActorStore(job.actorRoot ? { root: job.actorRoot } : {}).write(job.actorTarget, job.actorName || "default", { credentials: { email: values.email || "", password: values.password || "" } });
842
+ }
843
+ json(response, 200, { ok: true, action });
844
+ return;
845
+ }
695
846
  const jobFrameMatch = url.pathname.match(/^\/api\/jobs\/([a-f0-9]{20})\/frame$/);
696
- if (request.method === "GET" && jobFrameMatch && anonymous && jobs.get(jobFrameMatch[1])?.visitorId !== visitorId) { response.writeHead(404); response.end("Not found"); return; }
847
+ if (request.method === "GET" && jobFrameMatch && jobs.get(jobFrameMatch[1]) && !jobVisible(jobs.get(jobFrameMatch[1]))) { response.writeHead(404); response.end("Not found"); return; }
697
848
  if (request.method === "GET" && jobFrameMatch) {
698
849
  const job = jobs.get(jobFrameMatch[1]);
699
850
  if (job && !job.latestFrame && job.liveSimulator && job.status === "running") {
@@ -809,22 +960,81 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
809
960
  }
810
961
  if (result?.error) throw Object.assign(new Error(result.error), { details: result.details || {} });
811
962
  const structured = result.structured;
812
- // Mark the capture as prompt-started so the Studio lists it without a repository.
813
- try {
814
- const captureDir = structured?.capture?.path;
815
- if (captureDir) {
816
- const provenancePath = path.join(captureDir, "provenance.json");
817
- const provenance = JSON.parse(fs.readFileSync(provenancePath, "utf8"));
818
- fs.writeFileSync(provenancePath, JSON.stringify({ ...provenance, origin: "studio-prompt" }, null, 2));
819
- fs.writeFileSync(path.join(captureDir, "report.json"), JSON.stringify({ headline: structured.headline, inconclusive: structured.inconclusive, screensExplored: structured.screensExplored, actionsPerformed: structured.actionsPerformed, findingCounts: structured.findingCounts, findings: structured.findings, checkedFor: structured.checkedFor, notChecked: structured.notChecked, platform: structured.platform, target: structured.target }, null, 2));
820
- }
821
- } catch { /* listing is a convenience; the capture is the evidence */ }
963
+ markPromptStarted(structured);
822
964
  return structured;
823
965
  }, null);
824
966
  json(response, 202, { job: publicJob(job, { hosted }) });
825
967
  return;
826
968
  }
827
969
  // A website audit needs no repository: it is read-only against a URL and writes a capture.
970
+ // Going inside a website: a full exploration that can stop at a sign-in and ask. Operator
971
+ // only — a public Studio asking a stranger for their login to another site is
972
+ // phishing-shaped, so a visitor is told to run this on their own machine instead.
973
+ if (operation === "explore") {
974
+ if (anonymous) {
975
+ json(response, 200, { kind: "self-host", command: "npx -y @aarwitz/tapp@latest app",
976
+ message: "Going inside a site means signing in, and that is something to do on your own machine. Start the Studio there: npx -y @aarwitz/tapp@latest app" });
977
+ return;
978
+ }
979
+ let target;
980
+ try { target = new URL(String(body.url || "")); } catch { throw Object.assign(new Error("Explore needs a valid http(s) URL"), { statusCode: 400 }); }
981
+ if (!/^https?:$/.test(target.protocol)) throw Object.assign(new Error("Explore needs a valid http(s) URL"), { statusCode: 400 });
982
+ const actorName = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(String(body.actor || "")) ? String(body.actor) : "default";
983
+ const responsePath = path.join(os.tmpdir(), `tapp-input-${crypto.randomBytes(8).toString("hex")}.json`);
984
+ const actorRoot = actorRootFor() || "";
985
+ const job = startJob(operation, async (progress) => {
986
+ const engine = await import("./index.js");
987
+ const result = await engine.runQaWeb({
988
+ url: target.href, maxActions: Number(body.maxActions) || 40, timeout: Number(body.timeout) || 600,
989
+ interactive: true, inputResponsePath: responsePath, inputWaitSec: 180, actor: actorName, actorRoot,
990
+ onProgress: (entry) => progress({ phase: entry.awaitInput ? "ask" : "explore", text: entry.narrative || `${entry.action || 0}/${entry.max || 0} actions · ${entry.states || 0} screens`, ...(entry.action ? { current: entry.action, total: entry.max } : {}), ...(entry.screen ? { screen: entry.screen } : {}), ...(entry.screenshot ? { screenshot: entry.screenshot } : {}), ...(entry.awaitInput ? { awaitInput: entry.awaitInput } : {}), ...(entry.inputResolved ? { inputResolved: entry.inputResolved } : {}) }),
991
+ });
992
+ if (result?.error) throw Object.assign(new Error(result.error), { details: result.details || {} });
993
+ markPromptStarted(result.structured);
994
+ if (ownerKey && result.structured?.capture?.id) setCaptureOwner(result.structured.capture.id, ownerKey);
995
+ return result.structured;
996
+ }, null, { lane: ownerKey || OPERATOR_LANE });
997
+ if (account) logUsage("explore.start", { account: account.id.slice(0, 8), host: safeHost(target.href) });
998
+ job.ownerKey = ownerKey;
999
+ job.inputResponsePath = responsePath;
1000
+ job.actorTarget = target.href;
1001
+ job.actorName = actorName;
1002
+ job.actorRoot = actorRoot;
1003
+ json(response, 202, { job: publicJob(job, { hosted }) });
1004
+ return;
1005
+ }
1006
+ // Replay a committed journey from the open project's .tapp/flows/. Web journeys run here
1007
+ // with a recording; an iOS or Android journey needs the simulator or device, so it is
1008
+ // answered with the command to run it where that is.
1009
+ if (operation === "run-flow") {
1010
+ if (anonymous) { json(response, 401, { error: "Sign in to replay a journey" }); return; }
1011
+ const root = registry.currentRoot();
1012
+ if (!root) throw Object.assign(new Error("Open a repository first"), { statusCode: 409 });
1013
+ const name = String(body.name || "").replace(/\.ya?ml$/i, "");
1014
+ if (!/^[A-Za-z0-9][A-Za-z0-9._\/-]{0,120}$/.test(name) || name.includes("..")) throw Object.assign(new Error("That is not a journey name"), { statusCode: 400 });
1015
+ const flowPath = path.join(root, ".tapp", "flows", `${name}.yml`);
1016
+ if (!flowPath.startsWith(path.join(root, ".tapp", "flows") + path.sep) || !fs.existsSync(flowPath)) throw Object.assign(new Error(`No journey named ${name}`), { statusCode: 404 });
1017
+ const { loadFlowFile, inferFlowPlatform } = await import("./flow-runtime.js");
1018
+ const flow = loadFlowFile(flowPath);
1019
+ const platform = inferFlowPlatform(flow);
1020
+ if (platform !== "web") {
1021
+ json(response, 200, { kind: "self-host", command: `npx -y @aarwitz/tapp@latest run ${path.relative(root, flowPath)}`,
1022
+ message: `${flow.name || name} runs on ${platform === "android" ? "an Android device or emulator" : "an iOS simulator"}, which the Studio does not have. Run it where that is: npx -y @aarwitz/tapp@latest run ${path.relative(root, flowPath)}` });
1023
+ return;
1024
+ }
1025
+ const captureId = `flow-web-${Date.now().toString(36)}-${crypto.randomBytes(4).toString("hex")}`;
1026
+ const evidenceDir = path.join(captureRoot(), captureId);
1027
+ fs.mkdirSync(evidenceDir, { recursive: true });
1028
+ const job = startJob(operation, async (progress) => {
1029
+ progress({ phase: "runtime", text: `Replaying ${flow.name || name}` });
1030
+ const { runWebFlow } = await import("./web-flow.js");
1031
+ const result = await runWebFlow({ flow, logPath: path.join(evidenceDir, "flow.log"), screenshotDir: evidenceDir, recordVideoDir: evidenceDir });
1032
+ for (const line of result.lines || []) progress({ phase: "replay", text: typeof line === "string" ? line : (line.text || JSON.stringify(line)) });
1033
+ return { kind: "journey", name: flow.name || name, passed: result.passed, executed: result.executed, total: result.total, failed: result.failed, capture: { id: captureId, path: evidenceDir } };
1034
+ }, null);
1035
+ json(response, 202, { job: publicJob(job, { hosted }) });
1036
+ return;
1037
+ }
828
1038
  if (operation === "audit") {
829
1039
  let target;
830
1040
  try { target = new URL(String(body.url || "")); } catch { throw Object.assign(new Error("Audit needs a valid http(s) URL"), { statusCode: 400 }); }
@@ -837,9 +1047,9 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
837
1047
  // run writes anything; a capture that appeared first and was claimed afterwards would be
838
1048
  // briefly readable by everyone.
839
1049
  const auditCapture = `web-audit-${Date.now().toString(36)}-${crypto.randomBytes(6).toString("hex")}`;
840
- if (visitorId) {
1050
+ if (ownerKey) {
841
1051
  try { fs.mkdirSync(path.join(captureRoot(), auditCapture), { recursive: true }); } catch { /* the run reports its own failure */ }
842
- setCaptureOwner(auditCapture, visitorId);
1052
+ setCaptureOwner(auditCapture, ownerKey);
843
1053
  }
844
1054
  const auditStartedMs = Date.now();
845
1055
  usage.audits += 1;
@@ -861,8 +1071,8 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
861
1071
  seconds: Math.round((Date.now() - auditStartedMs) / 100) / 10,
862
1072
  });
863
1073
  return hosted ? hostedPayload(summary) : summary;
864
- }, null, { lane: visitorId || OPERATOR_LANE });
865
- job.visitorId = visitorId;
1074
+ }, null, { lane: ownerKey || OPERATOR_LANE });
1075
+ job.ownerKey = ownerKey;
866
1076
  json(response, 202, { job: publicJob(job, { hosted }) });
867
1077
  return;
868
1078
  }
@@ -1975,7 +1975,7 @@ export function formatScreen(screenTitle, elements, { full = false } = {}) {
1975
1975
  // `tapp` CLI verbs in bin/tapp.js — same pattern as report.js. Keep orchestration HERE so
1976
1976
  // the surfaces can't drift.)
1977
1977
 
1978
- export async function runQaWeb({ url, maxActions, timeout, testEmail, testPassword, baselineFindings, seedRoutes = [], seedTargets = [], watch = false, surface = "mcp", onProgress = () => {}, device = "", viewport = "" }) {
1978
+ export async function runQaWeb({ url, maxActions, timeout, testEmail, testPassword, baselineFindings, seedRoutes = [], seedTargets = [], watch = false, surface = "mcp", onProgress = () => {}, device = "", viewport = "", interactive = false, inputResponsePath = "", inputWaitSec = 120, actor = "", actorRoot = "" }) {
1979
1979
  const { storagePreflight } = await import("./environment-preflight.js");
1980
1980
  const storage = storagePreflight(capturesDir);
1981
1981
  if (!storage.ok) return { error: storage.message, details: { environment: "storage", storage } };
@@ -1984,6 +1984,24 @@ export async function runQaWeb({ url, maxActions, timeout, testEmail, testPasswo
1984
1984
  const id = "web-" + new Date().toISOString().replace(/[-:T]/g, "").slice(0, 14).replace(/^(\d{8})/, "$1-");
1985
1985
  const outDir = path.join(capturesDir, id);
1986
1986
  const provenance = writeCaptureProvenance(outDir, { kind: "explore", platform: "web", target: url.trim(), projectDir: workspaceRoot });
1987
+ // A named actor is an identity tapp remembers for this application: credentials it was told
1988
+ // once, and the signed-in session it built with them. With one, the run starts inside the
1989
+ // application; without one, and with a person to ask, it asks at the door.
1990
+ let store = null;
1991
+ let storageStatePath = "";
1992
+ let actorName = isNonEmptyString(actor) ? actor.trim() : "";
1993
+ let storedEmail = "";
1994
+ let storedPassword = "";
1995
+ if (actorName || interactive) {
1996
+ const { ActorStore } = await import("./actor-store.js");
1997
+ // A hosted Studio keeps each account's test accounts apart by giving the run its own root.
1998
+ store = new ActorStore(isNonEmptyString(actorRoot) ? { root: actorRoot.trim() } : {});
1999
+ actorName = actorName || "default";
2000
+ const record = store.read(url.trim(), actorName);
2001
+ storageStatePath = store.sessionFile(url.trim(), actorName) || "";
2002
+ storedEmail = record?.credentials?.email || "";
2003
+ storedPassword = record?.credentials?.password || "";
2004
+ }
1987
2005
  let webResult;
1988
2006
  try {
1989
2007
  const { exploreWeb } = await import("./web-explorer.js");
@@ -1992,8 +2010,13 @@ export async function runQaWeb({ url, maxActions, timeout, testEmail, testPasswo
1992
2010
  maxActions: actions,
1993
2011
  timeoutSec,
1994
2012
  outDir,
1995
- testEmail: isNonEmptyString(testEmail) ? testEmail.trim() : "",
1996
- testPassword: isNonEmptyString(testPassword) ? testPassword.trim() : "",
2013
+ testEmail: isNonEmptyString(testEmail) ? testEmail.trim() : storedEmail,
2014
+ testPassword: isNonEmptyString(testPassword) ? testPassword.trim() : storedPassword,
2015
+ interactive: interactive === true,
2016
+ inputResponsePath: isNonEmptyString(inputResponsePath) ? inputResponsePath.trim() : "",
2017
+ inputWaitSec: Math.max(10, Math.min(900, asInteger(inputWaitSec, 120))),
2018
+ storageStatePath,
2019
+ onSessionSaved: store ? (session) => { store.write(url.trim(), actorName, { session }); } : null,
1997
2020
  seedRoutes,
1998
2021
  seedTargets,
1999
2022
  watch: watch === true,
@@ -0,0 +1,70 @@
1
+ // How the hosted Studio sends a sign-in link. Two transports:
2
+ //
3
+ // TAPP_MAIL_RESEND_KEY + TAPP_MAIL_FROM → Resend's HTTP API (https://resend.com), the one
4
+ // paid-for path; the key is read off the environment
5
+ // and never logged.
6
+ // otherwise → an outbox directory (TAPP_MAIL_OUTBOX, default
7
+ // TAPP_HOME/mail-outbox), one 0600 .eml per message.
8
+ //
9
+ // The outbox is what tests and a local Studio use, and what a freshly deployed host falls back to
10
+ // before a mail provider is configured: the link is on disk for the operator, not lost, and
11
+ // never printed to a log that other people read.
12
+ import fs from "node:fs";
13
+ import os from "node:os";
14
+ import path from "node:path";
15
+ import crypto from "node:crypto";
16
+
17
+ export function createMailer(env = process.env) {
18
+ const key = (env.TAPP_MAIL_RESEND_KEY || "").trim();
19
+ const from = (env.TAPP_MAIL_FROM || "").trim();
20
+ if (key && from) return resendMailer({ key, from });
21
+ const home = (env.TAPP_HOME || "").trim() || path.join(os.homedir(), ".tapp");
22
+ return outboxMailer({ dir: (env.TAPP_MAIL_OUTBOX || "").trim() || path.join(home, "mail-outbox"), from: from || "tapp <no-reply@localhost>" });
23
+ }
24
+
25
+ export function signInMessage({ to, link, origin }) {
26
+ const host = (() => { try { return new URL(origin).host; } catch { return origin; } })();
27
+ return {
28
+ to,
29
+ subject: `Sign in to tapp`,
30
+ text: `Here is your sign-in link for ${host}:\n\n${link}\n\nIt works once and expires in 15 minutes. If you did not ask for it, ignore this email — nothing happens without the link.`,
31
+ html: `<p>Here is your sign-in link for <strong>${host}</strong>:</p><p><a href="${link}">${link}</a></p><p>It works once and expires in 15 minutes. If you did not ask for it, ignore this email — nothing happens without the link.</p>`,
32
+ };
33
+ }
34
+
35
+ function resendMailer({ key, from }) {
36
+ return {
37
+ transport: "resend",
38
+ from,
39
+ async send(message) {
40
+ const response = await fetch("https://api.resend.com/emails", {
41
+ method: "POST",
42
+ headers: { authorization: `Bearer ${key}`, "content-type": "application/json" },
43
+ body: JSON.stringify({ from, to: [message.to], subject: message.subject, text: message.text, html: message.html }),
44
+ });
45
+ if (!response.ok) {
46
+ const detail = await response.text().catch(() => "");
47
+ // The provider's error may quote the request; keep the status and drop the body.
48
+ throw new Error(`Mail provider refused the message (${response.status}${detail ? ", see provider dashboard" : ""})`);
49
+ }
50
+ const body = await response.json().catch(() => ({}));
51
+ return { transport: "resend", id: body.id || null };
52
+ },
53
+ };
54
+ }
55
+
56
+ function outboxMailer({ dir, from }) {
57
+ return {
58
+ transport: "outbox",
59
+ from,
60
+ dir,
61
+ async send(message) {
62
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
63
+ const id = `${new Date().toISOString().replace(/[:.]/g, "-")}-${crypto.randomBytes(4).toString("hex")}`;
64
+ const file = path.join(dir, `${id}.eml`);
65
+ const eml = [`From: ${from}`, `To: ${message.to}`, `Subject: ${message.subject}`, `Date: ${new Date().toUTCString()}`, "Content-Type: text/plain; charset=utf-8", "", message.text, ""].join("\r\n");
66
+ fs.writeFileSync(file, eml, { mode: 0o600 });
67
+ return { transport: "outbox", id, file };
68
+ },
69
+ };
70
+ }
@@ -182,12 +182,19 @@ function listProductRuns(root) {
182
182
  }
183
183
 
184
184
  function listRepositoryFlows(root) {
185
+ // Every committed journey, including the ones in subfolders — a real repository keeps dozens
186
+ // under sandbox/, mobile/, weekly/, and a flat listing hid all of them. YAML steps are counted
187
+ // from the list items under `steps:`; before, only JSON flows ever had a step count.
185
188
  const directory = path.join(root, projectArtifactDirectory(root), "flows");
186
189
  if (!fs.existsSync(directory)) return [];
187
- return fs.readdirSync(directory, { withFileTypes:true })
188
- .filter((entry) => entry.isFile() && /\.(?:ya?ml|json)$/i.test(entry.name))
189
- .map((entry) => {
190
- const file = path.join(directory, entry.name);
190
+ const out = [];
191
+ const walk = (dir, group) => {
192
+ let entries = [];
193
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
194
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
195
+ const file = path.join(dir, entry.name);
196
+ if (entry.isDirectory()) { walk(file, group ? `${group}/${entry.name}` : entry.name); continue; }
197
+ if (!entry.isFile() || !/\.(?:ya?ml|json)$/i.test(entry.name)) continue;
191
198
  const relativePath = path.relative(root, file).replaceAll(path.sep, "/");
192
199
  let name = entry.name.replace(/\.(?:ya?ml|json)$/i, "");
193
200
  let platform = "ios";
@@ -205,14 +212,22 @@ function listRepositoryFlows(root) {
205
212
  return match ? match[1].replace(/^["']|["']$/g, "") : "";
206
213
  };
207
214
  name = scalar("name") || name;
208
- platform = (scalar("platform") || (/^url:\s*https?:\/\//im.test(source) ? "web" : "ios")).toLowerCase();
209
- const block = source.split(/^steps:\s*$/m)[1] || "";
210
- steps = (block.match(/^\s{2}-\s/gm) || []).length;
215
+ const declared = scalar("platform").toLowerCase();
216
+ platform = declared || (/^https?:\/\//i.test(scalar("url") || scalar("app")) ? "web" : "ios");
217
+ const stepsAt = source.search(/^steps:\s*$/m);
218
+ if (stepsAt >= 0) {
219
+ const tail = source.slice(stepsAt);
220
+ const stop = tail.slice(7).search(/^[A-Za-z_][\w-]*:\s*/m);
221
+ const block = stop >= 0 ? tail.slice(0, 7 + stop) : tail;
222
+ steps = (block.match(/^\s*-\s/gm) || []).length;
223
+ }
211
224
  }
212
- } catch { /* Artifact remains inspectable; deterministic replay reports invalid syntax. */ }
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" };
214
- })
215
- .sort((left, right) => left.path.localeCompare(right.path));
225
+ } catch { /* an unreadable flow is still listed by file name */ }
226
+ out.push({ name, relativePath, platform, steps, group });
227
+ }
228
+ };
229
+ walk(directory, "");
230
+ return out;
216
231
  }
217
232
 
218
233
  export function readProductProject({ projectDir, outDir = ".tapp" } = {}) {