@aarwitz/tapp 0.22.0 → 0.23.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +2 -2
- package/bin/tapp.js +4 -2
- package/browser/app.css +20 -0
- package/browser/app.js +111 -9
- package/browser/index.html +18 -2
- package/docs/BROWSER-PRODUCT.md +40 -1
- package/mcp-server/src/access-jwt.js +60 -0
- package/mcp-server/src/account-store.js +137 -0
- package/mcp-server/src/browser-product.js +156 -19
- package/mcp-server/src/index.js +3 -2
- package/mcp-server/src/mailer.js +70 -0
- package/package.json +2 -2
|
@@ -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.
|
|
4
|
+
"version": "0.23.1",
|
|
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.
|
|
27
|
+
"@aarwitz/tapp@0.23.1",
|
|
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
|
-
|
|
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
|
-
|
|
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 =
|
|
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
|
|
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
|
|
689
|
-
// you. A
|
|
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
|
-
|
|
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,24 @@ 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]")) {
|
|
854
|
+
event.preventDefault();
|
|
855
|
+
// With Cloudflare Access in front, the sign-in page is Cloudflare's; otherwise ask for an
|
|
856
|
+
// address here and mail a link.
|
|
857
|
+
if (state.session?.signInProvider === "cloudflare") { location.href = "/auth/cloudflare"; return; }
|
|
858
|
+
state.signInOpen = true; renderAccount(); showPrompt(); setTimeout(() => $("#signin-email")?.focus(), 50);
|
|
859
|
+
}
|
|
860
|
+
if (event.target.closest("[data-signout]")) { event.preventDefault(); signOut(); }
|
|
861
|
+
const forget = event.target.closest("[data-forget-actor]");
|
|
862
|
+
if (forget) { event.preventDefault(); forgetActor(forget.dataset.forgetHost, forget.dataset.forgetActor).catch((error) => toast(error.message, true)); }
|
|
772
863
|
});
|
|
773
864
|
|
|
774
865
|
$$("[data-brand-home]").forEach((button) => button.addEventListener("click", () => state.project?.connected ? (showProduct(), activateView("overview")) : showPrompt()));
|
|
@@ -794,6 +885,16 @@ $("#run-gate").addEventListener("click", () => runOperation("gate", operationPay
|
|
|
794
885
|
// ?target=... Prefill it and start the run, so arriving here does not mean retyping what was
|
|
795
886
|
// already typed on the landing page. The URL is cleaned up either way so a refresh does not
|
|
796
887
|
// silently re-run it.
|
|
888
|
+
// Coming back from a sign-in link: say what happened, then clean the URL.
|
|
889
|
+
function signInOutcome() {
|
|
890
|
+
let outcome = "";
|
|
891
|
+
try { outcome = new URLSearchParams(window.location.search).get("signin") || ""; } catch { return; }
|
|
892
|
+
if (!outcome) return;
|
|
893
|
+
try { window.history.replaceState({}, "", window.location.pathname); } catch { /* history may be unavailable */ }
|
|
894
|
+
if (outcome === "done") toast(`Signed in${state.session?.email ? ` as ${state.session.email}` : ""}.`);
|
|
895
|
+
if (outcome === "expired") { toast("That sign-in link has expired or was already used — ask for a new one.", true); state.signInOpen = true; renderAccount(); }
|
|
896
|
+
}
|
|
897
|
+
|
|
797
898
|
function handoffTarget() {
|
|
798
899
|
let target = "";
|
|
799
900
|
try { target = new URLSearchParams(window.location.search).get("target") || ""; } catch { return ""; }
|
|
@@ -808,6 +909,7 @@ try {
|
|
|
808
909
|
await refreshSession();
|
|
809
910
|
await refresh();
|
|
810
911
|
if (state.project?.connected && !state.project?.state?.inspected) await runOperation("initialize", { write:true });
|
|
912
|
+
signInOutcome();
|
|
811
913
|
|
|
812
914
|
const handoff = handoffTarget();
|
|
813
915
|
if (handoff) {
|
package/browser/index.html
CHANGED
|
@@ -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
|
|
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="
|
|
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>
|
package/docs/BROWSER-PRODUCT.md
CHANGED
|
@@ -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
|
|
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,42 @@ 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
|
+
**Cloudflare Access instead of mail.** When the host is fronted by Cloudflare, put an Access
|
|
97
|
+
application on exactly `app.runtapp.com/auth/cloudflare` (policy: allow everyone; login method:
|
|
98
|
+
one-time PIN or Google) and set `TAPP_ACCESS_TEAM_DOMAIN` (`<team>.cloudflareaccess.com`) and
|
|
99
|
+
`TAPP_ACCESS_AUD` (the application's audience tag). *Sign in* then goes to Cloudflare, which
|
|
100
|
+
proves the address itself and returns with a signed assertion (`Cf-Access-Jwt-Assertion`);
|
|
101
|
+
`access-jwt.js` checks the RS256 signature against the team's published keys, the audience, the
|
|
102
|
+
issuer and the expiry, and opens the same session the link flow would. tapp sends no email.
|
|
103
|
+
`/api/session.signInProvider` tells the Studio which of the two to offer.
|
|
104
|
+
|
|
105
|
+
**Mail** is sent through Resend when `TAPP_MAIL_RESEND_KEY` and `TAPP_MAIL_FROM` are set
|
|
106
|
+
(`mailer.js`). Without them, each message is written as a 0600 `.eml` into `TAPP_MAIL_OUTBOX`
|
|
107
|
+
(default `TAPP_HOME/mail-outbox`) — what tests and a local trial use, and what a freshly deployed
|
|
108
|
+
host does before a provider is configured. A link is never printed to a log.
|
|
109
|
+
|
|
110
|
+
**What an account's test accounts look like.** The Runs view lists them by application: the
|
|
111
|
+
actor's name, whether a password is held, and whether a signed-in session is held and since when.
|
|
112
|
+
Never a value. *Forget* removes one; tapp asks again next time. This is the CI-secrets model —
|
|
113
|
+
write-only from the UI, encrypted at rest, decrypted only inside the run that signs in with it.
|
|
114
|
+
|
|
115
|
+
A local trial of the public mode (`--origin http://127.0.0.1:PORT`) does not pin browser egress
|
|
116
|
+
to public addresses, so it can reach a site on the same machine; a real origin always does.
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// Signing in through Cloudflare Access.
|
|
2
|
+
//
|
|
3
|
+
// When app.runtapp.com puts Cloudflare Access in front of one path (/auth/cloudflare), Cloudflare
|
|
4
|
+
// does the whole identity dance itself — one-time PIN to the address, or Google — and forwards
|
|
5
|
+
// the request with a signed JWT (`Cf-Access-Jwt-Assertion`) that names the email. tapp then never
|
|
6
|
+
// sends an email of its own; it just checks the signature against the team's published keys and
|
|
7
|
+
// opens a session for that address.
|
|
8
|
+
//
|
|
9
|
+
// Verification is deliberately plain Node: RS256 over the JWT's signing input, keys fetched from
|
|
10
|
+
// https://<team>.cloudflareaccess.com/cdn-cgi/access/certs and cached for an hour, `aud` pinned
|
|
11
|
+
// to this application's tag, `iss` pinned to the team, `exp` honoured. Nothing else is trusted.
|
|
12
|
+
import crypto from "node:crypto";
|
|
13
|
+
|
|
14
|
+
const b64url = (value) => Buffer.from(String(value).replace(/-/g, "+").replace(/_/g, "/"), "base64");
|
|
15
|
+
const JWKS_TTL_MS = 60 * 60 * 1000;
|
|
16
|
+
|
|
17
|
+
export function accessConfig(env = process.env) {
|
|
18
|
+
const teamDomain = (env.TAPP_ACCESS_TEAM_DOMAIN || "").trim().replace(/^https?:\/\//, "").replace(/\/$/, "");
|
|
19
|
+
const aud = (env.TAPP_ACCESS_AUD || "").trim();
|
|
20
|
+
return teamDomain && aud ? { teamDomain, aud } : null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function createAccessVerifier({ teamDomain, aud, fetchImpl = fetch, now = () => Date.now() }) {
|
|
24
|
+
const issuer = `https://${teamDomain}`;
|
|
25
|
+
let cache = { keys: null, fetchedAt: 0 };
|
|
26
|
+
|
|
27
|
+
async function keys(force = false) {
|
|
28
|
+
if (!force && cache.keys && now() - cache.fetchedAt < JWKS_TTL_MS) return cache.keys;
|
|
29
|
+
const response = await fetchImpl(`${issuer}/cdn-cgi/access/certs`);
|
|
30
|
+
if (!response.ok) throw new Error(`Access keys unavailable (${response.status})`);
|
|
31
|
+
const body = await response.json();
|
|
32
|
+
cache = { keys: (body.keys || []).filter((k) => k.kty === "RSA"), fetchedAt: now() };
|
|
33
|
+
return cache.keys;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Returns { email } for a valid assertion, or throws with a one-line reason. */
|
|
37
|
+
async function verify(token) {
|
|
38
|
+
const parts = String(token || "").split(".");
|
|
39
|
+
if (parts.length !== 3) throw new Error("Not an Access token");
|
|
40
|
+
let header, claims;
|
|
41
|
+
try { header = JSON.parse(b64url(parts[0]).toString("utf8")); claims = JSON.parse(b64url(parts[1]).toString("utf8")); }
|
|
42
|
+
catch { throw new Error("Malformed Access token"); }
|
|
43
|
+
if (header.alg !== "RS256" || !header.kid) throw new Error("Unexpected Access token algorithm");
|
|
44
|
+
let jwk = (await keys()).find((k) => k.kid === header.kid);
|
|
45
|
+
if (!jwk) jwk = (await keys(true)).find((k) => k.kid === header.kid); // rotated since we cached
|
|
46
|
+
if (!jwk) throw new Error("Access token signed by an unknown key");
|
|
47
|
+
const key = crypto.createPublicKey({ key: jwk, format: "jwk" });
|
|
48
|
+
const valid = crypto.verify("sha256", Buffer.from(`${parts[0]}.${parts[1]}`), { key, padding: crypto.constants.RSA_PKCS1_PADDING }, b64url(parts[2]));
|
|
49
|
+
if (!valid) throw new Error("Access token signature does not verify");
|
|
50
|
+
const audience = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
|
|
51
|
+
if (!audience.includes(aud)) throw new Error("Access token is for a different application");
|
|
52
|
+
if (claims.iss !== issuer) throw new Error("Access token is from a different team");
|
|
53
|
+
if (typeof claims.exp !== "number" || claims.exp * 1000 < now()) throw new Error("Access token has expired");
|
|
54
|
+
const email = String(claims.email || "").trim().toLowerCase();
|
|
55
|
+
if (!email) throw new Error("Access token carries no email");
|
|
56
|
+
return { email };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
return { verify, issuer };
|
|
60
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
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
|
+
return this.signIn(link.email);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Open a session for an address whose owner has already been verified (a redeemed link, or
|
|
90
|
+
* an identity provider such as Cloudflare Access). */
|
|
91
|
+
signIn(rawEmail) {
|
|
92
|
+
const account = this.#ensureAccount(normalizeEmail(rawEmail));
|
|
93
|
+
const session = token();
|
|
94
|
+
writeJson(this.#file("sessions", sha(session)), { accountId: account.id, createdAt: new Date(this.now()).toISOString(), expiresAt: new Date(this.now() + SESSION_TTL_MS).toISOString() });
|
|
95
|
+
return { session, account };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** The account behind a session cookie, or null. */
|
|
99
|
+
sessionAccount(value) {
|
|
100
|
+
if (!/^[A-Za-z0-9_-]{20,}$/.test(String(value || ""))) return null;
|
|
101
|
+
const session = readJson(this.#file("sessions", sha(value)));
|
|
102
|
+
if (!session || Date.parse(session.expiresAt) < this.now()) return null;
|
|
103
|
+
const account = readJson(this.#file("accounts", session.accountId));
|
|
104
|
+
if (!account) return null;
|
|
105
|
+
// lastSeenAt is coarse on purpose: a day, not a request log.
|
|
106
|
+
const day = new Date(this.now()).toISOString().slice(0, 10);
|
|
107
|
+
if ((account.lastSeenAt || "").slice(0, 10) !== day) { account.lastSeenAt = new Date(this.now()).toISOString(); writeJson(this.#file("accounts", account.id), account); }
|
|
108
|
+
return account;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
signOut(value) {
|
|
112
|
+
if (!/^[A-Za-z0-9_-]{20,}$/.test(String(value || ""))) return;
|
|
113
|
+
try { fs.rmSync(this.#file("sessions", sha(value)), { force: true }); } catch { /* already gone */ }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Where this account's encrypted test accounts live. */
|
|
117
|
+
actorRoot(accountId) {
|
|
118
|
+
if (!/^[a-f0-9]{24}$/.test(String(accountId || ""))) throw new Error("Not an account id");
|
|
119
|
+
return path.join(this.root, "actors", accountId);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
#ensureAccount(email) {
|
|
123
|
+
const indexFile = path.join(this.root, "by-email", sha(email));
|
|
124
|
+
let id = null;
|
|
125
|
+
try { id = fs.readFileSync(indexFile, "utf8").trim(); } catch { /* new */ }
|
|
126
|
+
if (id) {
|
|
127
|
+
const existing = readJson(this.#file("accounts", id));
|
|
128
|
+
if (existing) return existing;
|
|
129
|
+
}
|
|
130
|
+
id = crypto.randomBytes(12).toString("hex");
|
|
131
|
+
const account = { id, email, createdAt: new Date(this.now()).toISOString(), lastSeenAt: new Date(this.now()).toISOString() };
|
|
132
|
+
writeJson(this.#file("accounts", id), account);
|
|
133
|
+
fs.mkdirSync(path.dirname(indexFile), { recursive: true, mode: 0o700 });
|
|
134
|
+
fs.writeFileSync(indexFile, `${id}\n`, { mode: 0o600 });
|
|
135
|
+
return account;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
@@ -17,6 +17,10 @@ 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";
|
|
23
|
+
import { accessConfig, createAccessVerifier } from "./access-jwt.js";
|
|
20
24
|
|
|
21
25
|
const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
|
|
22
26
|
const assetRoot = path.join(packageRoot, "browser");
|
|
@@ -116,6 +120,9 @@ function capturePath(captureId, relative = "report.html") {
|
|
|
116
120
|
// only ever listed or served back to them. An unstamped capture belongs to the operator.
|
|
117
121
|
const VISITOR_MARKER = ".visitor";
|
|
118
122
|
const VISITOR_COOKIE = "tapp_visitor";
|
|
123
|
+
// A signed-in tapp account on a public Studio (ADR-0009 slice 2). The cookie is a session token
|
|
124
|
+
// whose hash the account store knows; see account-store.js.
|
|
125
|
+
const ACCOUNT_COOKIE = "tapp_account";
|
|
119
126
|
|
|
120
127
|
// What a signed-out visitor on a public Studio may reach. Everything absent from this list is
|
|
121
128
|
// refused, so a new route is private until someone deliberately opens it.
|
|
@@ -126,8 +133,12 @@ function anonymousAllows(method, pathname) {
|
|
|
126
133
|
if (/^\/api\/captures\/[A-Za-z0-9._-]{1,128}\/files$/.test(pathname)) return true;
|
|
127
134
|
if (/^\/evidence\/captures\//.test(pathname)) return true;
|
|
128
135
|
if (/^\/api\/jobs\/[a-f0-9]{20}(\/frame)?$/.test(pathname)) return true;
|
|
136
|
+
// Following a sign-in link from an email, or arriving back from Cloudflare Access.
|
|
137
|
+
if (pathname === "/auth/cloudflare" || /^\/auth\/[A-Za-z0-9_-]{20,}$/.test(pathname)) return true;
|
|
129
138
|
return false;
|
|
130
139
|
}
|
|
140
|
+
// Asking for a sign-in link is the one thing a stranger may post besides a run.
|
|
141
|
+
if (method === "POST" && pathname === "/api/auth/link") return true;
|
|
131
142
|
// A visitor may start a read-only audit, and may *ask* about the other kinds of target so the
|
|
132
143
|
// Studio can say where they actually run. A bare 401 reads as "broken" to someone who typed a
|
|
133
144
|
// repo into the landing page, which is how five of its six examples used to dead-end.
|
|
@@ -136,12 +147,23 @@ function anonymousAllows(method, pathname) {
|
|
|
136
147
|
return method === "POST" && ["/api/operations/audit", "/api/operations/open", "/api/operations/explore-build", "/api/operations/explore"].includes(pathname);
|
|
137
148
|
}
|
|
138
149
|
|
|
150
|
+
// A signed-in account may do what a visitor may, plus: start a real exploration (which can stop
|
|
151
|
+
// at a sign-in and ask), answer that ask, and see and forget the test accounts it has stored.
|
|
152
|
+
// Repositories, live sessions and the gate stay the operator's — they are this machine's.
|
|
153
|
+
function accountAllows(method, pathname) {
|
|
154
|
+
if (anonymousAllows(method, pathname)) return true;
|
|
155
|
+
if (method === "POST" && (pathname === "/api/auth/signout" || /^\/api\/jobs\/[a-f0-9]{20}\/input$/.test(pathname))) return true;
|
|
156
|
+
if (method === "GET" && pathname === "/api/actors") return true;
|
|
157
|
+
if (method === "DELETE" && /^\/api\/actors\/[A-Za-z0-9.:-]{1,253}\/[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(pathname)) return true;
|
|
158
|
+
return false;
|
|
159
|
+
}
|
|
160
|
+
|
|
139
161
|
// One visitor may start a bounded number of audits per hour. Each audit drives a real browser
|
|
140
162
|
// over as many as 20 pages, so this is about the machine, not about abuse alone.
|
|
141
163
|
const AUDIT_LIMIT_PER_HOUR = 10;
|
|
142
164
|
const auditHistory = new Map();
|
|
143
165
|
function auditRateLimit(visitorId, method, pathname) {
|
|
144
|
-
if (method !== "POST" ||
|
|
166
|
+
if (method !== "POST" || !["/api/operations/audit", "/api/operations/explore"].includes(pathname)) return 0;
|
|
145
167
|
const now = Date.now();
|
|
146
168
|
const hour = 60 * 60 * 1000;
|
|
147
169
|
const recent = (auditHistory.get(visitorId) || []).filter((at) => now - at < hour);
|
|
@@ -204,12 +226,13 @@ function captureFiles(captureId) {
|
|
|
204
226
|
|
|
205
227
|
// Explorations started from the prompt (a bundle id, an .app or .apk) have no repository to list
|
|
206
228
|
// them under; they are listed from their captures like audits are.
|
|
207
|
-
function listBuildExplores(limit = 50) {
|
|
229
|
+
function listBuildExplores(limit = 50, owner = null) {
|
|
208
230
|
const root = captureRoot();
|
|
209
231
|
let names;
|
|
210
232
|
try { names = fs.readdirSync(root); } catch { return []; }
|
|
211
233
|
const runs = [];
|
|
212
234
|
for (const name of names) {
|
|
235
|
+
if (!visibleToOwner(name, owner)) continue;
|
|
213
236
|
const provenance = readCaptureProvenance(path.join(root, name));
|
|
214
237
|
if (!provenance || provenance.kind !== "explore" || provenance.origin !== "studio-prompt") continue;
|
|
215
238
|
let report = null;
|
|
@@ -431,7 +454,7 @@ function serveLoginPage(response, { failed = false, next = "" } = {}) {
|
|
|
431
454
|
response.end(html);
|
|
432
455
|
}
|
|
433
456
|
|
|
434
|
-
export async function startBrowserProduct({ projectDir, port = 0, launch = false, workspaceRoot, githubProvider, publicOrigin = "", trustedProxyToken = "", directLogin = null, publicEgressOnly = null, publicAccess = false } = {}) {
|
|
457
|
+
export async function startBrowserProduct({ projectDir, port = 0, launch = false, workspaceRoot, githubProvider, publicOrigin = "", trustedProxyToken = "", directLogin = null, publicEgressOnly = null, publicAccess = false, accessVerifier = undefined } = {}) {
|
|
435
458
|
const hosted = !!trustedProxyToken || !!directLogin || !!publicAccess;
|
|
436
459
|
// publicOrigin accepts a comma-separated allowlist; the first entry is canonical.
|
|
437
460
|
const publicOrigins = String(publicOrigin || "").split(",").map((value) => value.trim().replace(/\/$/, "")).filter(Boolean);
|
|
@@ -464,6 +487,20 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
464
487
|
process.env.TAPP_ENFORCE_PUBLIC_EGRESS = "1";
|
|
465
488
|
}
|
|
466
489
|
const registry = new BrowserWorkspaceRegistry({ initialProjectDir: projectDir, workspaceRoot, githubProvider });
|
|
490
|
+
// Accounts exist only on a public Studio: a local one has exactly one person, the operator.
|
|
491
|
+
const accounts = publicAccess ? new AccountStore() : null;
|
|
492
|
+
const mailer = publicAccess ? createMailer() : null;
|
|
493
|
+
// With Cloudflare Access in front of /auth/cloudflare, identity comes from Cloudflare's signed
|
|
494
|
+
// assertion and tapp sends no email at all. Configured by TAPP_ACCESS_TEAM_DOMAIN + TAPP_ACCESS_AUD;
|
|
495
|
+
// tests inject a verifier. The email link stays available as the provider-free path.
|
|
496
|
+
const access = accessVerifier !== undefined ? accessVerifier : (publicAccess && accessConfig() ? createAccessVerifier(accessConfig()) : null);
|
|
497
|
+
const signInProvider = access ? "cloudflare" : "email";
|
|
498
|
+
const openAccountSession = (response, signedIn, location = "/?signin=done") => {
|
|
499
|
+
logUsage("signin.done", { account: signedIn.account.id.slice(0, 8), provider: signInProvider });
|
|
500
|
+
response.writeHead(303, { location, "set-cookie": `${ACCOUNT_COOKIE}=${encodeURIComponent(signedIn.session)}; HttpOnly; SameSite=Lax;${secureCookies ? " Secure;" : ""} Path=/; Max-Age=7776000` });
|
|
501
|
+
response.end();
|
|
502
|
+
};
|
|
503
|
+
const secureCookies = publicOrigins[0]?.startsWith("https:") ?? false;
|
|
467
504
|
const serverStartedAt = new Date().toISOString();
|
|
468
505
|
const sessionToken = crypto.randomBytes(32).toString("base64url");
|
|
469
506
|
const csrfToken = crypto.randomBytes(24).toString("base64url");
|
|
@@ -577,7 +614,13 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
577
614
|
// machine's project all stay behind authentication.
|
|
578
615
|
let visitorId = null;
|
|
579
616
|
let anonymous = false;
|
|
580
|
-
|
|
617
|
+
// A signed-in account sits between the two: more than a visitor, less than the operator.
|
|
618
|
+
const account = publicAccess && !authenticated ? accounts.sessionAccount(cookies(request)[ACCOUNT_COOKIE] || "") : null;
|
|
619
|
+
if (account && !accountAllows(request.method, url.pathname)) {
|
|
620
|
+
json(response, 401, { error: "That part of the Studio runs on your own machine: npx -y @aarwitz/tapp@latest app" });
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
if (publicAccess && !authenticated && !account) {
|
|
581
624
|
anonymous = true;
|
|
582
625
|
visitorId = String(cookies(request)[VISITOR_COOKIE] || "");
|
|
583
626
|
const returning = /^[a-f0-9]{32}$/.test(visitorId);
|
|
@@ -607,8 +650,17 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
607
650
|
const limited = auditRateLimit(visitorId, request.method, url.pathname);
|
|
608
651
|
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
652
|
}
|
|
610
|
-
// The operator sees every capture; a visitor sees only captures stamped with their id
|
|
611
|
-
|
|
653
|
+
// The operator sees every capture; a visitor sees only captures stamped with their id, an
|
|
654
|
+
// account only the ones stamped with its id. `ownerKey` is also the job lane: one person's
|
|
655
|
+
// runs queue behind each other, never behind a stranger's.
|
|
656
|
+
const ownerKey = anonymous ? visitorId : account ? `acct:${account.id}` : null;
|
|
657
|
+
const evidenceOwner = ownerKey;
|
|
658
|
+
if (account) {
|
|
659
|
+
const limited = auditRateLimit(ownerKey, request.method, url.pathname);
|
|
660
|
+
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; }
|
|
661
|
+
}
|
|
662
|
+
// A job belongs to whoever started it; the operator sees them all.
|
|
663
|
+
const jobVisible = (job) => !!job && (ownerKey === null || job.ownerKey === ownerKey);
|
|
612
664
|
if (!authenticated && directLogin) {
|
|
613
665
|
if (request.method === "GET" && url.pathname === "/login") { serveLoginPage(response, { failed: url.searchParams.has("failed"), next: safeReturnPath(url.searchParams.get("next")) }); return; }
|
|
614
666
|
if (request.method === "POST" && url.pathname === "/api/auth") {
|
|
@@ -649,7 +701,7 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
649
701
|
return;
|
|
650
702
|
}
|
|
651
703
|
}
|
|
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; }
|
|
704
|
+
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
705
|
|
|
654
706
|
if (request.method === "GET" && url.pathname === "/") {
|
|
655
707
|
// Without a sign-in page there is nowhere to bounce an anonymous visitor to, and a
|
|
@@ -665,12 +717,92 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
665
717
|
serveFile(response, file);
|
|
666
718
|
return;
|
|
667
719
|
}
|
|
720
|
+
// Signing in: an email address gets a link; the link, used once, becomes a session cookie.
|
|
721
|
+
// The response to the request is the same whether or not the address was ever seen, so
|
|
722
|
+
// this cannot be used to find out who has an account.
|
|
723
|
+
if (publicAccess && request.method === "POST" && url.pathname === "/api/auth/link") {
|
|
724
|
+
requireMutationAuth(request, publicOrigins, csrfToken);
|
|
725
|
+
const body = await readJsonBody(request);
|
|
726
|
+
let link;
|
|
727
|
+
try { link = accounts.requestLink(body.email); }
|
|
728
|
+
catch (error) { json(response, error.statusCode || 400, { error: error.message }); return; }
|
|
729
|
+
const message = signInMessage({ to: link.email, link: `${publicOrigins[0]}/auth/${link.token}`, origin: publicOrigins[0] });
|
|
730
|
+
try {
|
|
731
|
+
const sent = await mailer.send(message);
|
|
732
|
+
logUsage("signin.link", { transport: sent.transport });
|
|
733
|
+
} catch (error) {
|
|
734
|
+
logUsage("signin.link.failed", { transport: mailer.transport, error: String(error.message || error).slice(0, 200) });
|
|
735
|
+
json(response, 502, { error: "The sign-in email could not be sent right now. Try again in a minute." });
|
|
736
|
+
return;
|
|
737
|
+
}
|
|
738
|
+
json(response, 200, { ok: true, sent: true });
|
|
739
|
+
return;
|
|
740
|
+
}
|
|
741
|
+
const authLinkMatch = publicAccess && request.method === "GET" ? url.pathname.match(/^\/auth\/([A-Za-z0-9_-]{20,})$/) : null;
|
|
742
|
+
if (authLinkMatch) {
|
|
743
|
+
const signedIn = accounts.redeem(authLinkMatch[1]);
|
|
744
|
+
if (!signedIn) { response.writeHead(303, { location: "/?signin=expired" }); response.end(); return; }
|
|
745
|
+
openAccountSession(response, signedIn);
|
|
746
|
+
return;
|
|
747
|
+
}
|
|
748
|
+
// Back from Cloudflare Access: the assertion header is only ever set by Cloudflare on a
|
|
749
|
+
// request that passed its policy, and the signature proves it. Without Access configured
|
|
750
|
+
// the path says so instead of pretending.
|
|
751
|
+
if (publicAccess && request.method === "GET" && url.pathname === "/auth/cloudflare") {
|
|
752
|
+
if (!access) { response.writeHead(404, { "content-type": "text/plain; charset=utf-8" }); response.end("Cloudflare Access sign-in is not configured here; use the email link."); return; }
|
|
753
|
+
const assertion = String(request.headers["cf-access-jwt-assertion"] || cookies(request).CF_Authorization || "");
|
|
754
|
+
try {
|
|
755
|
+
const { email } = await access.verify(assertion);
|
|
756
|
+
openAccountSession(response, accounts.signIn(email));
|
|
757
|
+
} catch (error) {
|
|
758
|
+
logUsage("signin.access.refused", { reason: String(error.message || error).slice(0, 120) });
|
|
759
|
+
response.writeHead(303, { location: "/?signin=expired" });
|
|
760
|
+
response.end();
|
|
761
|
+
}
|
|
762
|
+
return;
|
|
763
|
+
}
|
|
764
|
+
if (account && request.method === "POST" && url.pathname === "/api/auth/signout") {
|
|
765
|
+
requireMutationAuth(request, publicOrigins, csrfToken);
|
|
766
|
+
accounts.signOut(cookies(request)[ACCOUNT_COOKIE] || "");
|
|
767
|
+
response.writeHead(200, { "content-type": "application/json; charset=utf-8", "set-cookie": `${ACCOUNT_COOKIE}=; HttpOnly; SameSite=Lax;${secureCookies ? " Secure;" : ""} Path=/; Max-Age=0` });
|
|
768
|
+
response.end(JSON.stringify({ ok: true }));
|
|
769
|
+
return;
|
|
770
|
+
}
|
|
771
|
+
// The test accounts tapp has been told about, by application: names and whether a password
|
|
772
|
+
// or a signed-in session is held — never the values. An account sees its own; the operator
|
|
773
|
+
// sees this machine's.
|
|
774
|
+
const actorRootFor = () => (account ? accounts.actorRoot(account.id) : undefined);
|
|
775
|
+
if (!anonymous && request.method === "GET" && url.pathname === "/api/actors") {
|
|
776
|
+
const store = new ActorStore(actorRootFor() ? { root: actorRootFor() } : {});
|
|
777
|
+
let hosts = [];
|
|
778
|
+
try { hosts = fs.readdirSync(store.root, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name); } catch { /* none yet */ }
|
|
779
|
+
json(response, 200, { apps: hosts.map((host) => ({ host, actors: store.list(`https://${host}/`) })).filter((app) => app.actors.length) });
|
|
780
|
+
return;
|
|
781
|
+
}
|
|
782
|
+
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;
|
|
783
|
+
if (actorForgetMatch) {
|
|
784
|
+
requireMutationAuth(request, hosted ? publicOrigins : origin, csrfToken);
|
|
785
|
+
const store = new ActorStore(actorRootFor() ? { root: actorRootFor() } : {});
|
|
786
|
+
store.forget(`https://${actorForgetMatch[1]}/`, actorForgetMatch[2]);
|
|
787
|
+
json(response, 200, { ok: true });
|
|
788
|
+
return;
|
|
789
|
+
}
|
|
668
790
|
if (request.method === "GET" && url.pathname === "/api/session") {
|
|
791
|
+
if (account) {
|
|
792
|
+
json(response, 200, {
|
|
793
|
+
csrfToken, mode: "public", product: "Tapp", root: null, repository: null, repositories: [],
|
|
794
|
+
contract: customerProductContract, supportedPlatforms: ["web"], runners: [],
|
|
795
|
+
access: "account", email: account.email, signInProvider,
|
|
796
|
+
accepts: ["url"],
|
|
797
|
+
selfHostOnly: ["path", "github", "bundle", "app", "apk"],
|
|
798
|
+
});
|
|
799
|
+
return;
|
|
800
|
+
}
|
|
669
801
|
if (anonymous) {
|
|
670
802
|
json(response, 200, {
|
|
671
803
|
csrfToken, mode: "public", product: "Tapp", root: null, repository: null, repositories: [],
|
|
672
804
|
contract: customerProductContract, supportedPlatforms: ["web"], runners: [],
|
|
673
|
-
access: "anonymous",
|
|
805
|
+
access: "anonymous", signInProvider,
|
|
674
806
|
// The prompt screen offers folders, bundle ids and builds. None of them can work in
|
|
675
807
|
// a hosted Studio — there is no Mac, no simulator and no access to the visitor's
|
|
676
808
|
// disk — so say so here rather than letting the UI offer them.
|
|
@@ -683,7 +815,7 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
683
815
|
return;
|
|
684
816
|
}
|
|
685
817
|
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; }
|
|
818
|
+
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
819
|
const filesMatch = url.pathname.match(/^\/api\/captures\/([A-Za-z0-9._-]{1,128})\/files$/);
|
|
688
820
|
if (request.method === "GET" && filesMatch) {
|
|
689
821
|
if (!visibleToOwner(filesMatch[1], evidenceOwner)) { response.writeHead(404); response.end("Not found"); return; }
|
|
@@ -708,7 +840,7 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
708
840
|
const jobMatch = url.pathname.match(/^\/api\/jobs\/([a-f0-9]{20})$/);
|
|
709
841
|
if (request.method === "GET" && jobMatch) {
|
|
710
842
|
const job = jobs.get(jobMatch[1]);
|
|
711
|
-
if (job &&
|
|
843
|
+
if (job && !jobVisible(job)) { response.writeHead(404); response.end("Not found"); return; }
|
|
712
844
|
if (!job) { json(response, 404, { error: "No such operation" }); return; }
|
|
713
845
|
json(response, 200, publicJob(job, { hosted }));
|
|
714
846
|
return;
|
|
@@ -722,6 +854,7 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
722
854
|
if (anonymous) { response.writeHead(401); response.end("Sign in to answer a run"); return; }
|
|
723
855
|
requireMutationAuth(request, hosted ? publicOrigins : origin, csrfToken);
|
|
724
856
|
const job = jobs.get(jobInputMatch[1]);
|
|
857
|
+
if (job && !jobVisible(job)) { response.writeHead(404); response.end("Not found"); return; }
|
|
725
858
|
if (!job || !job.input || !job.inputResponsePath) { json(response, 409, { error: "This run is not waiting for anything" }); return; }
|
|
726
859
|
const body = await readJsonBody(request);
|
|
727
860
|
const action = ["submit", "defaults", "skip", "dont_ask"].includes(body.action) ? body.action : "skip";
|
|
@@ -730,14 +863,13 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
730
863
|
: {};
|
|
731
864
|
fs.writeFileSync(job.inputResponsePath, JSON.stringify({ requestId: job.input.requestId, action, values }), { mode: 0o600 });
|
|
732
865
|
if (action === "submit" && body.remember === true && job.actorTarget) {
|
|
733
|
-
|
|
734
|
-
new ActorStore().write(job.actorTarget, job.actorName || "default", { credentials: { email: values.email || "", password: values.password || "" } });
|
|
866
|
+
new ActorStore(job.actorRoot ? { root: job.actorRoot } : {}).write(job.actorTarget, job.actorName || "default", { credentials: { email: values.email || "", password: values.password || "" } });
|
|
735
867
|
}
|
|
736
868
|
json(response, 200, { ok: true, action });
|
|
737
869
|
return;
|
|
738
870
|
}
|
|
739
871
|
const jobFrameMatch = url.pathname.match(/^\/api\/jobs\/([a-f0-9]{20})\/frame$/);
|
|
740
|
-
if (request.method === "GET" && jobFrameMatch &&
|
|
872
|
+
if (request.method === "GET" && jobFrameMatch && jobs.get(jobFrameMatch[1]) && !jobVisible(jobs.get(jobFrameMatch[1]))) { response.writeHead(404); response.end("Not found"); return; }
|
|
741
873
|
if (request.method === "GET" && jobFrameMatch) {
|
|
742
874
|
const job = jobs.get(jobFrameMatch[1]);
|
|
743
875
|
if (job && !job.latestFrame && job.liveSimulator && job.status === "running") {
|
|
@@ -874,20 +1006,25 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
874
1006
|
if (!/^https?:$/.test(target.protocol)) throw Object.assign(new Error("Explore needs a valid http(s) URL"), { statusCode: 400 });
|
|
875
1007
|
const actorName = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(String(body.actor || "")) ? String(body.actor) : "default";
|
|
876
1008
|
const responsePath = path.join(os.tmpdir(), `tapp-input-${crypto.randomBytes(8).toString("hex")}.json`);
|
|
1009
|
+
const actorRoot = actorRootFor() || "";
|
|
877
1010
|
const job = startJob(operation, async (progress) => {
|
|
878
1011
|
const engine = await import("./index.js");
|
|
879
1012
|
const result = await engine.runQaWeb({
|
|
880
1013
|
url: target.href, maxActions: Number(body.maxActions) || 40, timeout: Number(body.timeout) || 600,
|
|
881
|
-
interactive: true, inputResponsePath: responsePath, inputWaitSec: 180, actor: actorName,
|
|
1014
|
+
interactive: true, inputResponsePath: responsePath, inputWaitSec: 180, actor: actorName, actorRoot,
|
|
882
1015
|
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
1016
|
});
|
|
884
1017
|
if (result?.error) throw Object.assign(new Error(result.error), { details: result.details || {} });
|
|
885
1018
|
markPromptStarted(result.structured);
|
|
1019
|
+
if (ownerKey && result.structured?.capture?.id) setCaptureOwner(result.structured.capture.id, ownerKey);
|
|
886
1020
|
return result.structured;
|
|
887
|
-
}, null);
|
|
1021
|
+
}, null, { lane: ownerKey || OPERATOR_LANE });
|
|
1022
|
+
if (account) logUsage("explore.start", { account: account.id.slice(0, 8), host: safeHost(target.href) });
|
|
1023
|
+
job.ownerKey = ownerKey;
|
|
888
1024
|
job.inputResponsePath = responsePath;
|
|
889
1025
|
job.actorTarget = target.href;
|
|
890
1026
|
job.actorName = actorName;
|
|
1027
|
+
job.actorRoot = actorRoot;
|
|
891
1028
|
json(response, 202, { job: publicJob(job, { hosted }) });
|
|
892
1029
|
return;
|
|
893
1030
|
}
|
|
@@ -935,9 +1072,9 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
935
1072
|
// run writes anything; a capture that appeared first and was claimed afterwards would be
|
|
936
1073
|
// briefly readable by everyone.
|
|
937
1074
|
const auditCapture = `web-audit-${Date.now().toString(36)}-${crypto.randomBytes(6).toString("hex")}`;
|
|
938
|
-
if (
|
|
1075
|
+
if (ownerKey) {
|
|
939
1076
|
try { fs.mkdirSync(path.join(captureRoot(), auditCapture), { recursive: true }); } catch { /* the run reports its own failure */ }
|
|
940
|
-
setCaptureOwner(auditCapture,
|
|
1077
|
+
setCaptureOwner(auditCapture, ownerKey);
|
|
941
1078
|
}
|
|
942
1079
|
const auditStartedMs = Date.now();
|
|
943
1080
|
usage.audits += 1;
|
|
@@ -959,8 +1096,8 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
959
1096
|
seconds: Math.round((Date.now() - auditStartedMs) / 100) / 10,
|
|
960
1097
|
});
|
|
961
1098
|
return hosted ? hostedPayload(summary) : summary;
|
|
962
|
-
}, null, { lane:
|
|
963
|
-
job.
|
|
1099
|
+
}, null, { lane: ownerKey || OPERATOR_LANE });
|
|
1100
|
+
job.ownerKey = ownerKey;
|
|
964
1101
|
json(response, 202, { job: publicJob(job, { hosted }) });
|
|
965
1102
|
return;
|
|
966
1103
|
}
|
package/mcp-server/src/index.js
CHANGED
|
@@ -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
|
-
|
|
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.
|
|
3
|
+
"version": "0.23.1",
|
|
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/access-jwt.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
|
}
|