@aarwitz/tapp 0.22.0 → 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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tapp",
3
3
  "description": "Give Claude hands and eyes on iOS, Android, and web apps, with exploration, replayable flows, evidence, and deterministic CI gates.",
4
- "version": "0.22.0",
4
+ "version": "0.23.0",
5
5
  "author": {
6
6
  "name": "Aaron Horowitz",
7
7
  "url": "https://github.com/aarwitz"
@@ -24,7 +24,7 @@
24
24
  "command": "npx",
25
25
  "args": [
26
26
  "-y",
27
- "@aarwitz/tapp@0.22.0",
27
+ "@aarwitz/tapp@0.23.0",
28
28
  "mcp"
29
29
  ],
30
30
  "cwd": "${CLAUDE_PROJECT_DIR}"
package/bin/tapp.js CHANGED
@@ -2179,14 +2179,16 @@ switch (command) {
2179
2179
  const product = await startBrowserProduct({
2180
2180
  projectDir, port,
2181
2181
  launch: !publicAccess && flags.open !== false && flags["no-open"] !== true,
2182
- ...(publicAccess ? { publicAccess: true, publicOrigin } : {}),
2182
+ // A loopback origin is a trial of the public Studio on your own machine; pinning its
2183
+ // browser to public addresses would stop it reaching the very thing you are trying.
2184
+ ...(publicAccess ? { publicAccess: true, publicOrigin, publicEgressOnly: !localOrigin } : {}),
2183
2185
  });
2184
2186
  if (publicAccess) {
2185
2187
  console.log(`Tapp · public Studio for ${publicOrigin}`);
2186
2188
  console.log(`Listening on ${product.origin} — put a TLS terminator or tunnel in front of it.`);
2187
2189
  console.log("Anonymous visitors may audit a public website read-only. Repositories, live");
2188
2190
  console.log("sessions and the release gate require an authenticated local session.");
2189
- console.log("Browser egress is pinned to public addresses; private ranges are refused.");
2191
+ console.log(localOrigin ? "Local trial: browser egress is not pinned, so this can reach services on this machine." : "Browser egress is pinned to public addresses; private ranges are refused.");
2190
2192
  } else {
2191
2193
  console.log(`Tapp · ${product.root || "choose a local folder or GitHub repository in the browser"}`);
2192
2194
  console.log(`Open: ${product.launchUrl}`);
package/browser/app.css CHANGED
@@ -553,3 +553,23 @@ dialog::backdrop { background:rgba(0,0,0,.6); }
553
553
  .journey-group > summary { cursor:pointer; list-style:none; display:flex; justify-content:space-between; align-items:center; padding:9px 10px; font-size:12px; letter-spacing:.06em; text-transform:uppercase; color:var(--tapp-text-soft); }
554
554
  .journey-group > summary::-webkit-details-marker { display:none; }
555
555
  .journey-group[open] > summary { color:var(--tapp-text); }
556
+
557
+ /* Accounts on a public Studio (ADR-0009 slice 2). */
558
+ .account-slot { display:flex; gap:8px; align-items:center; font-size:12px; color:var(--muted); flex-wrap:wrap; }
559
+ #account-slot-side { margin-top:8px; }
560
+ #account-slot-side .account-email { max-width:100%; flex:1 1 100%; }
561
+ #account-slot-side button { white-space:nowrap; }
562
+ .account-slot .account-email { max-width:220px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
563
+ .account-slot button { font:inherit; font-size:12px; padding:5px 10px; border-radius:999px; border:1px solid var(--line); background:var(--control); color:inherit; cursor:pointer; }
564
+ .account-slot button.primary { background:var(--tapp-accent, #4f6cf7); border-color:transparent; color:#fff; }
565
+ .signin-card { max-width:560px; margin:14px auto 0; padding:14px 16px; border-radius:var(--tapp-radius-lg, 14px); border:1px solid var(--line); background:var(--control); font-size:13px; line-height:1.5; }
566
+ .signin-card p { margin:0 0 10px; }
567
+ .signin-card small { display:block; margin-top:8px; color:var(--tapp-text-faint); }
568
+ .signin-row { display:flex; gap:8px; flex-wrap:wrap; }
569
+ .signin-row input { flex:1 1 220px; font:inherit; padding:9px 12px; border-radius:10px; border:1px solid var(--line); background:rgba(0,0,0,.15); color:inherit; }
570
+ .signin-row button { font:inherit; padding:9px 14px; border-radius:10px; cursor:pointer; }
571
+ .signin-sent { margin:0; }
572
+ .actor-row { display:grid; grid-template-columns:1fr auto auto; gap:10px; align-items:center; padding:8px 10px; border-bottom:1px solid var(--tapp-border); font-size:13px; }
573
+ .actor-row:last-child { border-bottom:0; }
574
+ .actor-row small { color:var(--muted); }
575
+ .actor-app { padding:8px 10px 2px; font-weight:600; font-size:12px; color:var(--muted); border-top:1px solid var(--tapp-border); }
package/browser/app.js CHANGED
@@ -91,9 +91,47 @@ function activateView(view) {
91
91
  // A hosted Studio has no Mac, no simulator and no access to the visitor's disk, so folders,
92
92
  // bundle ids and builds cannot work there however the prompt is worded. Offer only what this
93
93
  // deployment can actually do, and say where the rest runs, rather than failing after the ask.
94
+ // On a public Studio a person is a visitor until they sign in, and an account after. Both slots
95
+ // (prompt screen and sidebar) show the same thing. A local Studio has neither: the one person at
96
+ // the keyboard is the operator.
97
+ function renderAccount() {
98
+ const session = state.session || {};
99
+ const isPublic = session.access === "anonymous" || session.access === "account";
100
+ for (const slot of document.querySelectorAll("#account-slot, #account-slot-side")) {
101
+ slot.classList.toggle("hidden", !isPublic);
102
+ if (!isPublic) continue;
103
+ slot.innerHTML = session.access === "account"
104
+ ? `<span class="account-email" title="${esc(session.email || "")}">${esc(session.email || "")}</span><button type="button" data-signout>Sign out</button>`
105
+ : `<button type="button" class="primary" data-signin>Sign in</button>`;
106
+ }
107
+ $("#signin-card")?.classList.toggle("hidden", session.access !== "anonymous" || !state.signInOpen);
108
+ }
109
+
110
+ async function requestSignInLink(email) {
111
+ const button = $("#signin-send");
112
+ if (button) button.disabled = true;
113
+ try {
114
+ await api("/api/auth/link", { method:"POST", body:JSON.stringify({ email }) });
115
+ $("#signin-form")?.classList.add("hidden");
116
+ const sent = $("#signin-sent");
117
+ if (sent) { sent.textContent = `Check your email — a sign-in link is on its way to ${email}. It works once, for 15 minutes.`; sent.classList.remove("hidden"); }
118
+ } catch (error) {
119
+ toast(error.message, true);
120
+ } finally {
121
+ if (button) button.disabled = false;
122
+ }
123
+ }
124
+
125
+ async function signOut() {
126
+ try { await api("/api/auth/signout", { method:"POST", body:"{}" }); } catch { /* the cookie is gone either way */ }
127
+ location.replace("/");
128
+ }
129
+
94
130
  function applyAccessMode() {
95
131
  const session = state.session || {};
96
- if (session.access !== "anonymous") return;
132
+ renderAccount();
133
+ if (session.access !== "anonymous" && session.access !== "account") return;
134
+ const signedIn = session.access === "account";
97
135
  const accepts = new Set(session.accepts || ["url"]);
98
136
  for (const button of document.querySelectorAll("[data-kind]")) {
99
137
  const kind = button.dataset.kind;
@@ -111,9 +149,33 @@ function applyAccessMode() {
111
149
  document.querySelector(".summary-panel")?.classList.add("hidden");
112
150
  // refreshSession() runs on every poll, so this must not overwrite a heading the current run
113
151
  // already set — that is what made "Website audit" revert to "tapp" when a run finished.
114
- if (!state.headingOwnedByRun) setHeading("tapp", "Give it a public website and it will audit the pages read-only.");
152
+ if (!state.headingOwnedByRun) setHeading("tapp", signedIn ? "Give it a website. If there is a sign-in, I will ask you for a test account and remember it." : "Give it a public website and it will audit the pages read-only.");
115
153
  const note = $("#privacy-note-detail");
116
- if (note) note.textContent = "Websites are audited read-only in the cloud; nothing is clicked. iOS, Android and folders on your own machine need tapp there: npx -y @aarwitz/tapp@latest app";
154
+ if (note) note.textContent = signedIn
155
+ ? "Websites are explored in the cloud. Test accounts you give tapp are kept encrypted, used only to sign in, and never shown again. iOS, Android and folders on your own machine need tapp there: npx -y @aarwitz/tapp@latest app"
156
+ : "Websites are audited read-only in the cloud; nothing is clicked. Sign in to go inside a site. iOS, Android and folders on your own machine need tapp there: npx -y @aarwitz/tapp@latest app";
157
+ $("#actors-panel")?.classList.toggle("hidden", !signedIn);
158
+ }
159
+
160
+ // The test accounts tapp holds, by application — names and what is held, never a value.
161
+ function renderActors() {
162
+ const node = $("#actors-list");
163
+ if (!node) return;
164
+ const apps = state.actors || [];
165
+ const total = apps.reduce((sum, app) => sum + app.actors.length, 0);
166
+ setCount("#actor-count", total);
167
+ if (!total) { node.innerHTML = '<div class="empty">None yet. Explore a site with a sign-in and tapp will ask.</div>'; return; }
168
+ node.innerHTML = apps.map((app) => `<div class="actor-app">${esc(app.host)}</div>${app.actors.map((actor) => {
169
+ const held = [actor.hasCredentials ? "password set" : "", actor.hasSession ? `signed-in session · ${compactDate(actor.sessionSavedAt)}` : ""].filter(Boolean).join(" · ") || "nothing held";
170
+ return `<div class="actor-row"><span><strong>${esc(actor.actor)}</strong><br><small>${esc(held)}</small></span><span></span><button class="quiet" type="button" data-forget-host="${esc(app.host)}" data-forget-actor="${esc(actor.actor)}">Forget</button></div>`;
171
+ }).join("")}`).join("");
172
+ }
173
+
174
+ async function forgetActor(host, actor) {
175
+ await api(`/api/actors/${encodeURIComponent(host)}/${encodeURIComponent(actor)}`, { method:"DELETE" });
176
+ state.actors = (state.actors || []).map((app) => app.host === host ? { ...app, actors: app.actors.filter((a) => a.actor !== actor) } : app).filter((app) => app.actors.length);
177
+ renderActors();
178
+ toast(`Forgot ${actor} on ${host}. tapp will ask again next time.`);
117
179
  }
118
180
 
119
181
  function showPrompt() {
@@ -322,6 +384,7 @@ async function runJourney(relativePath) {
322
384
 
323
385
  function renderRuns() {
324
386
  renderJourneys();
387
+ renderActors();
325
388
  const runs = allRuns();
326
389
  setCount("#run-count", runs.length);
327
390
  $("#runs-list").innerHTML = runs.length ? runs.map((run) => {
@@ -378,6 +441,11 @@ function renderRunDetail(run) {
378
441
  // ---- tapp chat: the engine's progress log, rendered as a transcript -------------------------
379
442
  function renderChat() {
380
443
  const node = $("#chat-transcript");
444
+ // While an ask is on screen the transcript is rebuilt on every poll, and rebuilding it throws
445
+ // away whatever the person has typed into the ask so far. Nothing else changes while the
446
+ // engine waits, so leave the DOM alone until the ask is answered or withdrawn.
447
+ const openAsk = node.querySelector("#chat-ask");
448
+ if (openAsk && state.pendingInput && openAsk.dataset.request === String(state.pendingInput.requestId)) return;
381
449
  const stickToBottom = node.scrollTop + node.clientHeight >= node.scrollHeight - 24;
382
450
  const lines = state.transcript.map((entry) => {
383
451
  if (entry.kind === "shots") return `<div class="chat-shots">${entry.shots.map((shot) => `<a href="${esc(shot.href)}" target="_blank" rel="noreferrer" title="${esc(shot.caption)}"><img src="${esc(shot.src)}" alt="${esc(shot.caption)}"></a>`).join("")}</div>`;
@@ -584,12 +652,16 @@ async function refreshSession() {
584
652
  async function refresh() {
585
653
  // A public visitor has no project and no live session, and asking for them would only earn a
586
654
  // 401 on every poll.
587
- if (state.session?.access === "anonymous") {
588
- const runs = await api("/api/audits").catch(() => ({ audits: [], explores: [] }));
655
+ if (state.session?.access === "anonymous" || state.session?.access === "account") {
656
+ const [runs, actors] = await Promise.all([
657
+ api("/api/audits").catch(() => ({ audits: [], explores: [] })),
658
+ state.session.access === "account" ? api("/api/actors").catch(() => ({ apps: [] })) : Promise.resolve({ apps: [] }),
659
+ ]);
589
660
  state.project = { connected:false };
590
661
  state.live = { active:false };
591
662
  state.audits = runs.audits || [];
592
663
  state.explores = runs.explores || [];
664
+ state.actors = actors.apps || [];
593
665
  renderProject();
594
666
  return;
595
667
  }
@@ -685,14 +757,21 @@ async function startFromPrompt(raw) {
685
757
  const prompt = classifyPrompt(raw);
686
758
  if (prompt.kind === "empty") return;
687
759
  if (prompt.kind === "url") {
688
- // On your own machine a website is explored for real — it can stop at a sign-in and ask
689
- // you. A public Studio only ever reads.
690
- if (state.session?.mode === "local") {
760
+ // On your own machine, or signed in to a public Studio, a website is explored for real — it
761
+ // can stop at a sign-in and ask you. A visitor only ever reads.
762
+ if (state.session?.mode === "local" || state.session?.access === "account") {
691
763
  state.promptRun = true; state.promptPlatform = "web";
692
764
  showProduct(); activateView("overview"); renderDeviceChrome(); renderChat();
693
765
  document.querySelector(".device-stage")?.classList.remove("hidden");
694
766
  setHeading("Exploring", "Going inside. If there is a sign-in, I will ask.", { owned: true });
695
- const result = await runOperation("explore", { url: prompt.value }, { input: prompt.value });
767
+ let result;
768
+ try { result = await runOperation("explore", { url: prompt.value }, { input: prompt.value }); }
769
+ catch (error) {
770
+ // A refused start (your previous run is still finishing, or this Studio is busy) must not
771
+ // leave "Exploring" over an empty stage.
772
+ setHeading("Not started", error.message, { owned: true });
773
+ throw error;
774
+ }
696
775
  if (result?.kind === "self-host") { answerSelfHost(result); return; }
697
776
  state.selectedRunId = result?.capture?.id || state.selectedRunId;
698
777
  return;
@@ -763,12 +842,18 @@ document.addEventListener("submit", (event) => {
763
842
  if (prompt) { event.preventDefault(); startFromPrompt(prompt.elements.input.value).catch((error) => toast(error.message, true)); }
764
843
  const ask = event.target.closest("#chat-ask");
765
844
  if (ask) { event.preventDefault(); answerAsk(ask, "submit"); }
845
+ const signin = event.target.closest("#signin-form");
846
+ if (signin) { event.preventDefault(); requestSignInLink(signin.elements.email.value.trim()); }
766
847
  });
767
848
  document.addEventListener("click", (event) => {
768
849
  const button = event.target.closest("#chat-ask [data-ask]");
769
850
  if (button && button.type === "button") { event.preventDefault(); answerAsk(button.closest("#chat-ask"), button.dataset.ask); }
770
851
  const play = event.target.closest("[data-run-journey]");
771
852
  if (play) { event.preventDefault(); runJourney(play.dataset.runJourney).catch((error) => toast(error.message, true)); }
853
+ if (event.target.closest("[data-signin]")) { event.preventDefault(); state.signInOpen = true; renderAccount(); showPrompt(); setTimeout(() => $("#signin-email")?.focus(), 50); }
854
+ if (event.target.closest("[data-signout]")) { event.preventDefault(); signOut(); }
855
+ const forget = event.target.closest("[data-forget-actor]");
856
+ if (forget) { event.preventDefault(); forgetActor(forget.dataset.forgetHost, forget.dataset.forgetActor).catch((error) => toast(error.message, true)); }
772
857
  });
773
858
 
774
859
  $$("[data-brand-home]").forEach((button) => button.addEventListener("click", () => state.project?.connected ? (showProduct(), activateView("overview")) : showPrompt()));
@@ -794,6 +879,16 @@ $("#run-gate").addEventListener("click", () => runOperation("gate", operationPay
794
879
  // ?target=... Prefill it and start the run, so arriving here does not mean retyping what was
795
880
  // already typed on the landing page. The URL is cleaned up either way so a refresh does not
796
881
  // silently re-run it.
882
+ // Coming back from a sign-in link: say what happened, then clean the URL.
883
+ function signInOutcome() {
884
+ let outcome = "";
885
+ try { outcome = new URLSearchParams(window.location.search).get("signin") || ""; } catch { return; }
886
+ if (!outcome) return;
887
+ try { window.history.replaceState({}, "", window.location.pathname); } catch { /* history may be unavailable */ }
888
+ if (outcome === "done") toast(`Signed in${state.session?.email ? ` as ${state.session.email}` : ""}.`);
889
+ if (outcome === "expired") { toast("That sign-in link has expired or was already used — ask for a new one.", true); state.signInOpen = true; renderAccount(); }
890
+ }
891
+
797
892
  function handoffTarget() {
798
893
  let target = "";
799
894
  try { target = new URLSearchParams(window.location.search).get("target") || ""; } catch { return ""; }
@@ -808,6 +903,7 @@ try {
808
903
  await refreshSession();
809
904
  await refresh();
810
905
  if (state.project?.connected && !state.project?.state?.inspected) await runOperation("initialize", { write:true });
906
+ signInOutcome();
811
907
 
812
908
  const handoff = handoffTarget();
813
909
  if (handoff) {
@@ -25,6 +25,7 @@
25
25
  <header class="onboarding-topbar">
26
26
  <button class="brand" data-brand-home aria-label="Tapp overview">tapp<span class="brand-mark"></span><small>ship with proof</small></button>
27
27
  <span class="mode-pill" id="onboarding-mode-pill">Self-host · this machine</span>
28
+ <div class="account-slot hidden" id="account-slot"></div>
28
29
  </header>
29
30
 
30
31
  <section class="prompt-hero" aria-hidden="true">
@@ -61,6 +62,16 @@
61
62
  <li><button type="button" data-kind="github" data-prompt="owner/repo"><span>🐙</span><b>owner/repo</b><small>clone from GitHub into an isolated workspace, then the same</small></button></li>
62
63
  <li><button type="button" data-kind="build" data-prompt="com.company.app"><span>📱</span><b>com.company.app</b><small>explore a build already on the booted simulator (or give a .app / .apk)</small></button></li>
63
64
  </ul>
65
+ <!-- Signing in to a public Studio: an email address and a link, nothing else. Hidden on a
66
+ local Studio, where the one person at the keyboard is the operator already. -->
67
+ <section class="signin-card hidden" id="signin-card" aria-live="polite">
68
+ <form id="signin-form" autocomplete="email">
69
+ <p><strong>Sign in to go inside a site.</strong> tapp can stop at a sign-in and ask you for a test account, then remember it — for that it needs to know it is you.</p>
70
+ <div class="signin-row"><input id="signin-email" name="email" type="email" placeholder="you@company.com" required><button class="primary" type="submit" id="signin-send">Email me a link</button></div>
71
+ <small>No password. The link works once and expires in 15 minutes.</small>
72
+ </form>
73
+ <p class="signin-sent hidden" id="signin-sent"></p>
74
+ </section>
64
75
  <p class="prompt-note" id="privacy-note-detail">Everything runs on this machine. Exploration, replay and merge decisions are deterministic and need no API key.</p>
65
76
  <span class="sr-only" id="privacy-note-title">Your code stays on this machine.</span>
66
77
  </section>
@@ -85,6 +96,7 @@
85
96
  <div class="row" data-repo-only><span><svg><use href="#i-server"/></svg></span><span id="sidebar-runner">Runner not checked</span></div>
86
97
  <div class="row hidden" id="sidebar-app-row"><span><svg><use href="#i-app"/></svg></span><span><code id="sidebar-app-id"></code></span></div>
87
98
  <span class="mode-pill" id="mode-pill">Self-host · this machine</span>
99
+ <div class="account-slot hidden" id="account-slot-side"></div>
88
100
  </div>
89
101
  <div class="sidebar-footer">
90
102
  <button class="quiet" id="change-source">+ Test something else</button>
@@ -154,13 +166,17 @@
154
166
  <section class="workspace-view" data-view-panel="runs">
155
167
  <div class="view-heading simple"><div><p class="eyebrow">Runs</p><h1>Every run, with its evidence</h1><p>Release checks, explorations and read-only website audits. Each opens the report page the engine wrote.</p></div><button class="primary" id="run-gate" data-repo-only>Run release gate</button></div>
156
168
  <section class="panel section audit-panel">
157
- <div class="section-heading compact"><div><p class="eyebrow">Website</p><h2>Audit a website — read-only</h2><p>Up to six pages, nothing clicked. Safe on production or a site you do not own; no release verdict without source.</p></div></div>
169
+ <div class="section-heading compact"><div><p class="eyebrow">Website</p><h2>Audit a website — read-only</h2><p>Up to twenty pages, nothing clicked. Safe on production or a site you do not own; no release verdict without source.</p></div></div>
158
170
  <form class="audit-form" id="runs-audit-form">
159
171
  <label class="field"><span>Website URL</span><input id="audit-url" name="url" type="url" inputmode="url" placeholder="https://example.com" required autocomplete="off"></label>
160
172
  <button class="primary" type="submit" id="audit-start">Audit read-only</button>
161
173
  </form>
162
174
  </section>
163
- <section class="panel section" id="journeys-panel">
175
+ <section class="panel section hidden" id="actors-panel">
176
+ <div class="section-heading compact"><div><p class="eyebrow">Test accounts</p><h2>What tapp can sign in as <i id="actor-count" class="zero">0</i></h2><p>Kept encrypted. Shown here is only the name and whether a password or a signed-in session is held — never the values. Forget one and tapp will ask again next time.</p></div></div>
177
+ <div id="actors-list"><div class="empty">None yet. Explore a site with a sign-in and tapp will ask.</div></div>
178
+ </section>
179
+ <section class="panel section" id="journeys-panel" data-repo-only>
164
180
  <div class="section-heading compact"><div><p class="eyebrow">Journeys</p><h2>What this app has proven <i id="journey-count" class="zero">0</i></h2><p>Committed under <code>.tapp/flows/</code>. Each replays exactly as written — no model, no key — and is what the release gate guards.</p></div></div>
165
181
  <div id="journeys-list"><div class="empty">No journeys yet.</div></div>
166
182
  </section>
@@ -45,7 +45,7 @@ refuses what the mode cannot do: a hosted Studio cannot open a path or a build o
45
45
  | Overview | The **stage**: the device as large as the window allows, in its platform's aspect ratio (phone portrait for iOS and Android, browser landscape for web), showing the live frame or the newest screenshot the run wrote. The **chat** floats over its corner on a translucent ground, collapses to a pill, and narrates the engine's own progress log one emoji-led line at a time (👆 Tapped, ⌨️ Typed, 🔐 Signed in, 📍 Opened, 🧭 Reached, 📸 screenshots inline), then attaches the recording and `report.html` and ends with a pill — `✓ Ready to merge`, `× Do not merge`, `◐ Inconclusive`, or for an exploration its counts — and the headline. Nothing is generated after the fact and nothing is a score. Below the stage: the detected targets (an explicit choice when there are several), the live-session controls, and the current decision from the last gate. | `open`, `initialize` (inspect, then build + explore), `explore-build`, live session `start / act / save-flow / end`, release check |
46
46
  | Runs | Every run on this repository, every exploration started from the prompt, and every read-only website audit, newest first; each opens its evidence page. A URL field runs an audit from here. | `gate`, `audit` |
47
47
 
48
- A **website audit** is `explore --read-only`: up to six same-origin pages are rendered and read —
48
+ A **website audit** is `explore --read-only`: up to twenty same-origin pages (twelve by default) are rendered and read —
49
49
  dead controls, broken images/assets/links, failed requests, JS exceptions, mixed content,
50
50
  horizontal overflow — and nothing is clicked, typed, submitted or hovered, so it is safe on
51
51
  production or a site you do not own. A website has no source revision, so it has no release
@@ -75,3 +75,33 @@ the chat's narration and summary without a browser.
75
75
  `saas/` serves the same `browser/` assets through `/api/studio` with an API base and login URL
76
76
  injected. It is frozen at its current commit (ADR-0006, owner decision) and will embed the
77
77
  simplified Studio when it is next deployed. Nothing in the Studio depends on it.
78
+
79
+ ## Accounts on a public Studio
80
+
81
+ A public Studio (`tapp app --public`) has three kinds of person, and the boundary between them is
82
+ an allowlist in `browser-product.js` (`anonymousAllows`, `accountAllows`):
83
+
84
+ | | Visitor | Account | Operator |
85
+ |---|---|---|---|
86
+ | Who | Anyone who opens the page | Signed in with an email link | The machine's owner (`tapp app` launch URL) |
87
+ | May | Audit a public website read-only; see their own audits | Everything a visitor may, plus: explore a website for real (it stops at a sign-in and **asks** in the chat), answer the ask, and see / forget the **test accounts** tapp holds for them | Everything, including repositories, live sessions and the gate |
88
+ | Evidence | Captures stamped with their visitor cookie | Captures stamped `acct:<id>` | All captures on the machine |
89
+ | Test accounts | None — a visitor is never asked | Encrypted, per account: `TAPP_HOME/accounts/actors/<id>/` | `TAPP_HOME/actors/` |
90
+
91
+ **Signing in** is `POST /api/auth/link` with an email, then `GET /auth/<token>` from the email.
92
+ There is no password. Links work once and expire in 15 minutes; sessions last 90 days; only the
93
+ SHA-256 of either token is on disk (`account-store.js`). One address may ask for five links per
94
+ ten minutes, and the reply is the same whether or not the address has an account.
95
+
96
+ **Mail** is sent through Resend when `TAPP_MAIL_RESEND_KEY` and `TAPP_MAIL_FROM` are set
97
+ (`mailer.js`). Without them, each message is written as a 0600 `.eml` into `TAPP_MAIL_OUTBOX`
98
+ (default `TAPP_HOME/mail-outbox`) — what tests and a local trial use, and what a freshly deployed
99
+ host does before a provider is configured. A link is never printed to a log.
100
+
101
+ **What an account's test accounts look like.** The Runs view lists them by application: the
102
+ actor's name, whether a password is held, and whether a signed-in session is held and since when.
103
+ Never a value. *Forget* removes one; tapp asks again next time. This is the CI-secrets model —
104
+ write-only from the UI, encrypted at rest, decrypted only inside the run that signs in with it.
105
+
106
+ A local trial of the public mode (`--origin http://127.0.0.1:PORT`) does not pin browser egress
107
+ to public addresses, so it can reach a site on the same machine; a real origin always does.
@@ -0,0 +1,131 @@
1
+ // A tapp account is an email address, nothing more. It exists so the hosted Studio can do what
2
+ // the local one does — stop at a sign-in and ask, and remember the answer — for a person it can
3
+ // tell apart from the next visitor. There are no passwords here: a sign-in is a link mailed to
4
+ // the address, used once, and a session cookie after that.
5
+ //
6
+ // Nothing secret is stored in the clear. A link token and a session token are random; only their
7
+ // SHA-256 lands on disk, so a copy of this directory cannot sign anyone in. Each account gets its
8
+ // own encrypted actor store (see actor-store.js) under its directory, so one person's test
9
+ // accounts are never listed under another's.
10
+ //
11
+ // Layout: TAPP_HOME/accounts/
12
+ // by-email/<sha256(email)> → account id
13
+ // accounts/<id>.json { id, email, createdAt, lastSeenAt }
14
+ // links/<sha256(token)>.json { email, expiresAt } (removed on use)
15
+ // sessions/<sha256(token)>.json { accountId, createdAt, expiresAt }
16
+ // actors/<id>/ that account's ActorStore root
17
+ import crypto from "node:crypto";
18
+ import fs from "node:fs";
19
+ import os from "node:os";
20
+ import path from "node:path";
21
+
22
+ export const LINK_TTL_MS = 15 * 60 * 1000;
23
+ export const SESSION_TTL_MS = 90 * 24 * 60 * 60 * 1000;
24
+ // One address may ask for this many links in a ten-minute window; more is someone else's mailbox
25
+ // being flooded through us.
26
+ const LINKS_PER_WINDOW = 5;
27
+ const LINK_WINDOW_MS = 10 * 60 * 1000;
28
+
29
+ export function accountStoreRoot(env = process.env) {
30
+ const home = (env.TAPP_HOME || "").trim() || path.join(os.homedir(), ".tapp");
31
+ return path.join(home, "accounts");
32
+ }
33
+
34
+ const EMAIL = /^[^\s@]{1,64}@[^\s@]{1,255}\.[^\s@]{2,}$/;
35
+ export function normalizeEmail(value) {
36
+ const email = String(value || "").trim().toLowerCase();
37
+ if (!EMAIL.test(email)) throw Object.assign(new Error("That does not look like an email address"), { statusCode: 400 });
38
+ return email;
39
+ }
40
+
41
+ const sha = (value) => crypto.createHash("sha256").update(String(value)).digest("hex");
42
+ const token = () => crypto.randomBytes(32).toString("base64url");
43
+
44
+ function readJson(file) {
45
+ try { return JSON.parse(fs.readFileSync(file, "utf8")); } catch { return null; }
46
+ }
47
+
48
+ function writeJson(file, value) {
49
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
50
+ const tmp = `${file}.${process.pid}.tmp`;
51
+ fs.writeFileSync(tmp, JSON.stringify(value), { mode: 0o600 });
52
+ fs.renameSync(tmp, file);
53
+ }
54
+
55
+ export class AccountStore {
56
+ constructor({ root = accountStoreRoot(), now = () => Date.now() } = {}) {
57
+ this.root = root;
58
+ this.now = now;
59
+ this.linkRequests = new Map();
60
+ }
61
+
62
+ #file(kind, key) { return path.join(this.root, kind, `${key}.json`); }
63
+
64
+ /** Ask for a sign-in link. Returns the token to mail — the only time it exists in the clear. */
65
+ requestLink(rawEmail) {
66
+ const email = normalizeEmail(rawEmail);
67
+ const now = this.now();
68
+ const recent = (this.linkRequests.get(email) || []).filter((at) => now - at < LINK_WINDOW_MS);
69
+ if (recent.length >= LINKS_PER_WINDOW) {
70
+ throw Object.assign(new Error("A few links were already sent to that address. Check your inbox, then try again in a little while."), { statusCode: 429 });
71
+ }
72
+ recent.push(now);
73
+ this.linkRequests.set(email, recent);
74
+ const value = token();
75
+ writeJson(this.#file("links", sha(value)), { email, expiresAt: new Date(now + LINK_TTL_MS).toISOString() });
76
+ return { email, token: value };
77
+ }
78
+
79
+ /** Use a link once. Returns a session token and the account, or null for a bad or spent link. */
80
+ redeem(value) {
81
+ if (!/^[A-Za-z0-9_-]{20,}$/.test(String(value || ""))) return null;
82
+ const file = this.#file("links", sha(value));
83
+ const link = readJson(file);
84
+ try { fs.rmSync(file, { force: true }); } catch { /* spent either way */ }
85
+ if (!link || Date.parse(link.expiresAt) < this.now()) return null;
86
+ const account = this.#ensureAccount(link.email);
87
+ const session = token();
88
+ writeJson(this.#file("sessions", sha(session)), { accountId: account.id, createdAt: new Date(this.now()).toISOString(), expiresAt: new Date(this.now() + SESSION_TTL_MS).toISOString() });
89
+ return { session, account };
90
+ }
91
+
92
+ /** The account behind a session cookie, or null. */
93
+ sessionAccount(value) {
94
+ if (!/^[A-Za-z0-9_-]{20,}$/.test(String(value || ""))) return null;
95
+ const session = readJson(this.#file("sessions", sha(value)));
96
+ if (!session || Date.parse(session.expiresAt) < this.now()) return null;
97
+ const account = readJson(this.#file("accounts", session.accountId));
98
+ if (!account) return null;
99
+ // lastSeenAt is coarse on purpose: a day, not a request log.
100
+ const day = new Date(this.now()).toISOString().slice(0, 10);
101
+ if ((account.lastSeenAt || "").slice(0, 10) !== day) { account.lastSeenAt = new Date(this.now()).toISOString(); writeJson(this.#file("accounts", account.id), account); }
102
+ return account;
103
+ }
104
+
105
+ signOut(value) {
106
+ if (!/^[A-Za-z0-9_-]{20,}$/.test(String(value || ""))) return;
107
+ try { fs.rmSync(this.#file("sessions", sha(value)), { force: true }); } catch { /* already gone */ }
108
+ }
109
+
110
+ /** Where this account's encrypted test accounts live. */
111
+ actorRoot(accountId) {
112
+ if (!/^[a-f0-9]{24}$/.test(String(accountId || ""))) throw new Error("Not an account id");
113
+ return path.join(this.root, "actors", accountId);
114
+ }
115
+
116
+ #ensureAccount(email) {
117
+ const indexFile = path.join(this.root, "by-email", sha(email));
118
+ let id = null;
119
+ try { id = fs.readFileSync(indexFile, "utf8").trim(); } catch { /* new */ }
120
+ if (id) {
121
+ const existing = readJson(this.#file("accounts", id));
122
+ if (existing) return existing;
123
+ }
124
+ id = crypto.randomBytes(12).toString("hex");
125
+ const account = { id, email, createdAt: new Date(this.now()).toISOString(), lastSeenAt: new Date(this.now()).toISOString() };
126
+ writeJson(this.#file("accounts", id), account);
127
+ fs.mkdirSync(path.dirname(indexFile), { recursive: true, mode: 0o700 });
128
+ fs.writeFileSync(indexFile, `${id}\n`, { mode: 0o600 });
129
+ return account;
130
+ }
131
+ }
@@ -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,8 +132,12 @@ 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.
@@ -136,12 +146,23 @@ function anonymousAllows(method, pathname) {
136
146
  return method === "POST" && ["/api/operations/audit", "/api/operations/open", "/api/operations/explore-build", "/api/operations/explore"].includes(pathname);
137
147
  }
138
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;
158
+ }
159
+
139
160
  // One visitor may start a bounded number of audits per hour. Each audit drives a real browser
140
161
  // over as many as 20 pages, so this is about the machine, not about abuse alone.
141
162
  const AUDIT_LIMIT_PER_HOUR = 10;
142
163
  const auditHistory = new Map();
143
164
  function auditRateLimit(visitorId, method, pathname) {
144
- if (method !== "POST" || pathname !== "/api/operations/audit") return 0;
165
+ if (method !== "POST" || !["/api/operations/audit", "/api/operations/explore"].includes(pathname)) return 0;
145
166
  const now = Date.now();
146
167
  const hour = 60 * 60 * 1000;
147
168
  const recent = (auditHistory.get(visitorId) || []).filter((at) => now - at < hour);
@@ -204,12 +225,13 @@ function captureFiles(captureId) {
204
225
 
205
226
  // Explorations started from the prompt (a bundle id, an .app or .apk) have no repository to list
206
227
  // them under; they are listed from their captures like audits are.
207
- function listBuildExplores(limit = 50) {
228
+ function listBuildExplores(limit = 50, owner = null) {
208
229
  const root = captureRoot();
209
230
  let names;
210
231
  try { names = fs.readdirSync(root); } catch { return []; }
211
232
  const runs = [];
212
233
  for (const name of names) {
234
+ if (!visibleToOwner(name, owner)) continue;
213
235
  const provenance = readCaptureProvenance(path.join(root, name));
214
236
  if (!provenance || provenance.kind !== "explore" || provenance.origin !== "studio-prompt") continue;
215
237
  let report = null;
@@ -464,6 +486,10 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
464
486
  process.env.TAPP_ENFORCE_PUBLIC_EGRESS = "1";
465
487
  }
466
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;
467
493
  const serverStartedAt = new Date().toISOString();
468
494
  const sessionToken = crypto.randomBytes(32).toString("base64url");
469
495
  const csrfToken = crypto.randomBytes(24).toString("base64url");
@@ -577,7 +603,13 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
577
603
  // machine's project all stay behind authentication.
578
604
  let visitorId = null;
579
605
  let anonymous = false;
580
- 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) {
581
613
  anonymous = true;
582
614
  visitorId = String(cookies(request)[VISITOR_COOKIE] || "");
583
615
  const returning = /^[a-f0-9]{32}$/.test(visitorId);
@@ -607,8 +639,17 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
607
639
  const limited = auditRateLimit(visitorId, request.method, url.pathname);
608
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; }
609
641
  }
610
- // The operator sees every capture; a visitor sees only captures stamped with their id.
611
- 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);
612
653
  if (!authenticated && directLogin) {
613
654
  if (request.method === "GET" && url.pathname === "/login") { serveLoginPage(response, { failed: url.searchParams.has("failed"), next: safeReturnPath(url.searchParams.get("next")) }); return; }
614
655
  if (request.method === "POST" && url.pathname === "/api/auth") {
@@ -649,7 +690,7 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
649
690
  return;
650
691
  }
651
692
  }
652
- 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; }
653
694
 
654
695
  if (request.method === "GET" && url.pathname === "/") {
655
696
  // Without a sign-in page there is nowhere to bounce an anonymous visitor to, and a
@@ -665,7 +706,73 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
665
706
  serveFile(response, file);
666
707
  return;
667
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
+ }
668
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
+ }
669
776
  if (anonymous) {
670
777
  json(response, 200, {
671
778
  csrfToken, mode: "public", product: "Tapp", root: null, repository: null, repositories: [],
@@ -683,7 +790,7 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
683
790
  return;
684
791
  }
685
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; }
686
- 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; }
687
794
  const filesMatch = url.pathname.match(/^\/api\/captures\/([A-Za-z0-9._-]{1,128})\/files$/);
688
795
  if (request.method === "GET" && filesMatch) {
689
796
  if (!visibleToOwner(filesMatch[1], evidenceOwner)) { response.writeHead(404); response.end("Not found"); return; }
@@ -708,7 +815,7 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
708
815
  const jobMatch = url.pathname.match(/^\/api\/jobs\/([a-f0-9]{20})$/);
709
816
  if (request.method === "GET" && jobMatch) {
710
817
  const job = jobs.get(jobMatch[1]);
711
- 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; }
712
819
  if (!job) { json(response, 404, { error: "No such operation" }); return; }
713
820
  json(response, 200, publicJob(job, { hosted }));
714
821
  return;
@@ -722,6 +829,7 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
722
829
  if (anonymous) { response.writeHead(401); response.end("Sign in to answer a run"); return; }
723
830
  requireMutationAuth(request, hosted ? publicOrigins : origin, csrfToken);
724
831
  const job = jobs.get(jobInputMatch[1]);
832
+ if (job && !jobVisible(job)) { response.writeHead(404); response.end("Not found"); return; }
725
833
  if (!job || !job.input || !job.inputResponsePath) { json(response, 409, { error: "This run is not waiting for anything" }); return; }
726
834
  const body = await readJsonBody(request);
727
835
  const action = ["submit", "defaults", "skip", "dont_ask"].includes(body.action) ? body.action : "skip";
@@ -730,14 +838,13 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
730
838
  : {};
731
839
  fs.writeFileSync(job.inputResponsePath, JSON.stringify({ requestId: job.input.requestId, action, values }), { mode: 0o600 });
732
840
  if (action === "submit" && body.remember === true && job.actorTarget) {
733
- const { ActorStore } = await import("./actor-store.js");
734
- new ActorStore().write(job.actorTarget, job.actorName || "default", { credentials: { email: values.email || "", password: values.password || "" } });
841
+ new ActorStore(job.actorRoot ? { root: job.actorRoot } : {}).write(job.actorTarget, job.actorName || "default", { credentials: { email: values.email || "", password: values.password || "" } });
735
842
  }
736
843
  json(response, 200, { ok: true, action });
737
844
  return;
738
845
  }
739
846
  const jobFrameMatch = url.pathname.match(/^\/api\/jobs\/([a-f0-9]{20})\/frame$/);
740
- 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; }
741
848
  if (request.method === "GET" && jobFrameMatch) {
742
849
  const job = jobs.get(jobFrameMatch[1]);
743
850
  if (job && !job.latestFrame && job.liveSimulator && job.status === "running") {
@@ -874,20 +981,25 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
874
981
  if (!/^https?:$/.test(target.protocol)) throw Object.assign(new Error("Explore needs a valid http(s) URL"), { statusCode: 400 });
875
982
  const actorName = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(String(body.actor || "")) ? String(body.actor) : "default";
876
983
  const responsePath = path.join(os.tmpdir(), `tapp-input-${crypto.randomBytes(8).toString("hex")}.json`);
984
+ const actorRoot = actorRootFor() || "";
877
985
  const job = startJob(operation, async (progress) => {
878
986
  const engine = await import("./index.js");
879
987
  const result = await engine.runQaWeb({
880
988
  url: target.href, maxActions: Number(body.maxActions) || 40, timeout: Number(body.timeout) || 600,
881
- interactive: true, inputResponsePath: responsePath, inputWaitSec: 180, actor: actorName,
989
+ interactive: true, inputResponsePath: responsePath, inputWaitSec: 180, actor: actorName, actorRoot,
882
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 } : {}) }),
883
991
  });
884
992
  if (result?.error) throw Object.assign(new Error(result.error), { details: result.details || {} });
885
993
  markPromptStarted(result.structured);
994
+ if (ownerKey && result.structured?.capture?.id) setCaptureOwner(result.structured.capture.id, ownerKey);
886
995
  return result.structured;
887
- }, null);
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;
888
999
  job.inputResponsePath = responsePath;
889
1000
  job.actorTarget = target.href;
890
1001
  job.actorName = actorName;
1002
+ job.actorRoot = actorRoot;
891
1003
  json(response, 202, { job: publicJob(job, { hosted }) });
892
1004
  return;
893
1005
  }
@@ -935,9 +1047,9 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
935
1047
  // run writes anything; a capture that appeared first and was claimed afterwards would be
936
1048
  // briefly readable by everyone.
937
1049
  const auditCapture = `web-audit-${Date.now().toString(36)}-${crypto.randomBytes(6).toString("hex")}`;
938
- if (visitorId) {
1050
+ if (ownerKey) {
939
1051
  try { fs.mkdirSync(path.join(captureRoot(), auditCapture), { recursive: true }); } catch { /* the run reports its own failure */ }
940
- setCaptureOwner(auditCapture, visitorId);
1052
+ setCaptureOwner(auditCapture, ownerKey);
941
1053
  }
942
1054
  const auditStartedMs = Date.now();
943
1055
  usage.audits += 1;
@@ -959,8 +1071,8 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
959
1071
  seconds: Math.round((Date.now() - auditStartedMs) / 100) / 10,
960
1072
  });
961
1073
  return hosted ? hostedPayload(summary) : summary;
962
- }, null, { lane: visitorId || OPERATOR_LANE });
963
- job.visitorId = visitorId;
1074
+ }, null, { lane: ownerKey || OPERATOR_LANE });
1075
+ job.ownerKey = ownerKey;
964
1076
  json(response, 202, { job: publicJob(job, { hosted }) });
965
1077
  return;
966
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 = "", interactive = false, inputResponsePath = "", inputWaitSec = 120, actor = "" }) {
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 } };
@@ -1994,7 +1994,8 @@ export async function runQaWeb({ url, maxActions, timeout, testEmail, testPasswo
1994
1994
  let storedPassword = "";
1995
1995
  if (actorName || interactive) {
1996
1996
  const { ActorStore } = await import("./actor-store.js");
1997
- store = new ActorStore();
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() } : {});
1998
1999
  actorName = actorName || "default";
1999
2000
  const record = store.read(url.trim(), actorName);
2000
2001
  storageStatePath = store.sessionFile(url.trim(), actorName) || "";
@@ -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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aarwitz/tapp",
3
- "version": "0.22.0",
3
+ "version": "0.23.0",
4
4
  "mcpName": "io.github.aarwitz/tapp",
5
5
  "description": "Let coding agents verify UI changes on real iOS, Android, and web surfaces, then enforce reviewed proof in deterministic CI.",
6
6
  "license": "MIT",
@@ -96,7 +96,7 @@
96
96
  "mobile"
97
97
  ],
98
98
  "scripts": {
99
- "test": "node --test tests/report.test.js tests/regression.test.js tests/engine.test.js tests/project-config.test.js tests/application-model.test.js tests/ui-map.test.js tests/focused-navigation.test.js tests/task-runtime.test.js tests/release-contract.test.js tests/pr-selection.test.js tests/flow-runtime.test.js tests/web-explorer.test.js tests/web-session.test.js tests/web-link-audit.test.js tests/web-audit.test.js tests/capture-provenance.test.js tests/capture-frames.test.js tests/actor-store.test.js tests/ios-crash-attribution.test.js tests/ios-simulator-selection.test.js tests/ios-recording-stop.test.js tests/web-flow.test.js tests/scenario-runtime.test.js tests/android-driver.test.js tests/android-explorer.test.js tests/android-flow.test.js tests/android-primitives-protocol.test.js tests/managed-web.test.js tests/product-operations.test.js tests/job-lanes.test.js tests/browser-product.test.js tests/browser-chat-narration.test.js tests/browser-onboarding.test.js tests/managed-operation.test.js tests/ci-setup.test.js tests/ci-install.test.js tests/cli.test.js tests/mcp-workspace.test.js tests/action.test.js tests/package-surface.test.js tests/agent-surface.test.js tests/presentation-contract.test.js tests/landing-brand.test.js tests/ci-gate.test.js tests/ci-report.test.js tests/desktop-protocol.test.js tests/ios-flow-protocol.test.js tests/feedback-triage-0919.test.js vscode-extension/test/bridge.test.js",
99
+ "test": "node --test tests/report.test.js tests/regression.test.js tests/engine.test.js tests/project-config.test.js tests/application-model.test.js tests/ui-map.test.js tests/focused-navigation.test.js tests/task-runtime.test.js tests/release-contract.test.js tests/pr-selection.test.js tests/flow-runtime.test.js tests/web-explorer.test.js tests/web-session.test.js tests/web-link-audit.test.js tests/web-audit.test.js tests/capture-provenance.test.js tests/capture-frames.test.js tests/actor-store.test.js tests/account-store.test.js tests/ios-crash-attribution.test.js tests/ios-simulator-selection.test.js tests/ios-recording-stop.test.js tests/web-flow.test.js tests/scenario-runtime.test.js tests/android-driver.test.js tests/android-explorer.test.js tests/android-flow.test.js tests/android-primitives-protocol.test.js tests/managed-web.test.js tests/product-operations.test.js tests/job-lanes.test.js tests/browser-product.test.js tests/browser-chat-narration.test.js tests/browser-onboarding.test.js tests/managed-operation.test.js tests/ci-setup.test.js tests/ci-install.test.js tests/cli.test.js tests/mcp-workspace.test.js tests/action.test.js tests/package-surface.test.js tests/agent-surface.test.js tests/presentation-contract.test.js tests/landing-brand.test.js tests/ci-gate.test.js tests/ci-report.test.js tests/desktop-protocol.test.js tests/ios-flow-protocol.test.js tests/feedback-triage-0919.test.js vscode-extension/test/bridge.test.js",
100
100
  "test:browser-journey": "node --test tests/browser-journey.test.js",
101
101
  "test:browser-native": "TAPP_RUN_NATIVE_BROWSER=1 node --test tests/browser-native-journey.test.js"
102
102
  }