@aarwitz/tapp 0.23.0 → 0.24.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.
- package/.claude-plugin/plugin.json +2 -2
- package/browser/app.css +9 -0
- package/browser/app.js +91 -13
- package/browser/index.html +2 -2
- package/docs/BROWSER-PRODUCT.md +32 -0
- package/mcp-server/src/access-jwt.js +60 -0
- package/mcp-server/src/account-store.js +7 -1
- package/mcp-server/src/browser-product.js +132 -19
- package/mcp-server/src/journeys.js +189 -0
- package/mcp-server/src/web-explorer.js +3 -1
- package/mcp-server/src/web-flow.js +3 -1
- package/package.json +2 -2
- package/scripts/flow_lib.py +3 -1
|
@@ -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.24.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.
|
|
27
|
+
"@aarwitz/tapp@0.24.0",
|
|
28
28
|
"mcp"
|
|
29
29
|
],
|
|
30
30
|
"cwd": "${CLAUDE_PROJECT_DIR}"
|
package/browser/app.css
CHANGED
|
@@ -573,3 +573,12 @@ dialog::backdrop { background:rgba(0,0,0,.6); }
|
|
|
573
573
|
.actor-row:last-child { border-bottom:0; }
|
|
574
574
|
.actor-row small { color:var(--muted); }
|
|
575
575
|
.actor-app { padding:8px 10px 2px; font-weight:600; font-size:12px; color:var(--muted); border-top:1px solid var(--tapp-border); }
|
|
576
|
+
|
|
577
|
+
/* Journeys with status (ADR-0009 slice 3). */
|
|
578
|
+
.journey-row .journey-name small { color:var(--muted); font-size:11px; }
|
|
579
|
+
.journey-status { display:inline-block; padding:1px 7px; border-radius:999px; font-size:10px; font-weight:600; letter-spacing:.02em; }
|
|
580
|
+
.journey-status.passing { background:rgba(46,160,67,.18); color:#4ade80; }
|
|
581
|
+
.journey-status.failing { background:rgba(220,38,38,.18); color:#f87171; }
|
|
582
|
+
.journey-status.never { background:var(--control); color:var(--muted); }
|
|
583
|
+
.journey-actions { display:flex; gap:6px; }
|
|
584
|
+
.chat-keep .ask-field input { font:inherit; font-size:13px; padding:8px 10px; border-radius:8px; border:1px solid var(--tapp-border); background:rgba(0,0,0,.25); color:var(--tapp-text); }
|
package/browser/app.js
CHANGED
|
@@ -155,6 +155,7 @@ function applyAccessMode() {
|
|
|
155
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
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
157
|
$("#actors-panel")?.classList.toggle("hidden", !signedIn);
|
|
158
|
+
$("#journeys-panel")?.classList.toggle("hidden", !signedIn);
|
|
158
159
|
}
|
|
159
160
|
|
|
160
161
|
// The test accounts tapp holds, by application — names and what is held, never a value.
|
|
@@ -352,17 +353,27 @@ function allRuns() {
|
|
|
352
353
|
|
|
353
354
|
// The journeys the open repository has committed under .tapp/flows/. This is the thing a
|
|
354
355
|
// person owns; the engine has listed them all along and the Studio never showed them.
|
|
356
|
+
// The journeys this person owns, with how the last replay went. A repository's committed flows
|
|
357
|
+
// come grouped by folder; kept journeys (from a run that got somewhere) are flat. Both replay
|
|
358
|
+
// the same way and both show the same status pill.
|
|
359
|
+
function journeyStatus(status) {
|
|
360
|
+
if (!status) return '<span class="journey-status never">never run</span>';
|
|
361
|
+
return `<span class="journey-status ${status.passed ? "passing" : "failing"}">${status.passed ? "passing" : "failing"} · ${esc(compactDate(status.at))}</span>`;
|
|
362
|
+
}
|
|
363
|
+
|
|
355
364
|
function renderJourneys() {
|
|
356
365
|
const node = $("#journeys-list");
|
|
357
366
|
if (!node) return;
|
|
358
|
-
const
|
|
359
|
-
setCount("#journey-count",
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
367
|
+
const journeys = state.journeys || [];
|
|
368
|
+
setCount("#journey-count", journeys.length);
|
|
369
|
+
const note = $("#journeys-note");
|
|
370
|
+
if (note) note.textContent = journeys.some((j) => j.source === "repo")
|
|
371
|
+
? "Committed under .tapp/flows/. Each replays exactly as written — no model, no key — and is what the release gate guards."
|
|
372
|
+
: "Each replays exactly as written — no model, no key. Keep one from any run that got somewhere; run it any time to prove it still works.";
|
|
373
|
+
if (!journeys.length) { node.innerHTML = '<div class="empty">No journeys yet. Explore a site — when a run gets somewhere, tapp offers to keep it.</div>'; return; }
|
|
363
374
|
const groups = new Map();
|
|
364
|
-
for (const
|
|
365
|
-
const row = (
|
|
375
|
+
for (const journey of journeys) { const key = journey.group || ""; if (!groups.has(key)) groups.set(key, []); groups.get(key).push(journey); }
|
|
376
|
+
const row = (j) => `<div class="journey-row"><span class="journey-platform ${esc(j.platform || "web")}">${esc(j.platform || "web")}</span><span class="journey-name">${esc(j.name)}<br><small>${j.steps || 0} steps · ${journeyStatus(j.status)}</small></span><span></span><span class="journey-actions"><button class="quiet" data-run-journey="${esc(j.slug)}" title="Replay this journey">▶ Run</button>${j.source === "kept" ? `<button class="quiet" data-forget-journey="${esc(j.slug)}" title="Forget this journey">Forget</button>` : ""}</span></div>`;
|
|
366
377
|
node.innerHTML = [...groups.entries()].sort(([a], [b]) => (a === "" ? -1 : b === "" ? 1 : a.localeCompare(b))).map(([group, items]) =>
|
|
367
378
|
group === ""
|
|
368
379
|
? items.map(row).join("")
|
|
@@ -370,18 +381,68 @@ function renderJourneys() {
|
|
|
370
381
|
).join("");
|
|
371
382
|
}
|
|
372
383
|
|
|
373
|
-
async function
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
384
|
+
async function loadJourneys() {
|
|
385
|
+
if (!state.session || state.session.access === "anonymous") { state.journeys = []; return; }
|
|
386
|
+
state.journeys = (await api("/api/journeys").catch(() => ({ journeys: [] }))).journeys || [];
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
async function runJourney(slug) {
|
|
390
|
+
const name = String(slug).replace(/^\.tapp\/flows\//, "").replace(/\.ya?ml$/i, "");
|
|
391
|
+
const known = (state.journeys || []).find((j) => j.slug === name);
|
|
392
|
+
state.promptRun = true; state.promptPlatform = "web";
|
|
393
|
+
showProduct(); activateView("overview"); renderDeviceChrome(); renderChat();
|
|
394
|
+
document.querySelector(".device-stage")?.classList.remove("hidden");
|
|
395
|
+
setHeading(known?.name || name, "Replaying the journey exactly as kept.", { owned: true });
|
|
377
396
|
const result = await runOperation("run-flow", { name }, { input: name });
|
|
378
397
|
if (result?.kind === "self-host") { answerSelfHost(result); return; }
|
|
379
398
|
if (result?.kind === "journey") {
|
|
380
399
|
pushLine({ kind: "summary", tone: result.passed ? "ready" : "blocked", pill: result.passed ? "Passed" : "Failed", text: `${result.name}: ${result.executed}/${result.total} steps${result.failed ? `, ${result.failed} failed` : ""}.` });
|
|
381
400
|
renderChat();
|
|
401
|
+
await loadJourneys(); renderJourneys();
|
|
382
402
|
}
|
|
383
403
|
}
|
|
384
404
|
|
|
405
|
+
async function forgetJourney(slug) {
|
|
406
|
+
await api(`/api/journeys/${encodeURIComponent(slug)}`, { method:"DELETE" });
|
|
407
|
+
await loadJourneys(); renderJourneys();
|
|
408
|
+
toast("Forgot that journey.");
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
// A run that got somewhere is worth keeping: offer it in the chat, with a name to edit.
|
|
412
|
+
async function offerJourney(result) {
|
|
413
|
+
const captureId = result?.capture?.id;
|
|
414
|
+
if (!captureId || !(result?.actionsPerformed > 0)) return;
|
|
415
|
+
// Ask the server what the journey would be — its name comes from where the run went.
|
|
416
|
+
let preview = null;
|
|
417
|
+
try { preview = await api(`/api/captures/${encodeURIComponent(captureId)}/keep`, { method:"POST", body:JSON.stringify({ preview: true }) }); }
|
|
418
|
+
catch { return; /* a run that only looked around is not offered */ }
|
|
419
|
+
state.pendingKeep = { captureId, suggested: preview.name, steps: preview.steps, screens: preview.screens || [], signedIn: preview.signedIn };
|
|
420
|
+
renderChat();
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
function renderKeepCard() {
|
|
424
|
+
const keep = state.pendingKeep;
|
|
425
|
+
if (!keep || state.activeJob) return "";
|
|
426
|
+
return `<form class="chat-ask chat-keep" id="chat-keep" data-capture="${esc(keep.captureId)}">
|
|
427
|
+
<div class="chat-ask-head"><span class="chat-icon">🧭</span><span>This run got somewhere${keep.signedIn ? ", signed in" : ""}: <b>${esc((keep.screens || []).join(" → "))}</b> (${keep.steps} steps). Keep it as a journey? It will replay exactly this path and tell you when it stops working.</span></div>
|
|
428
|
+
<label class="ask-field"><span>Name</span><input name="name" type="text" value="${esc(keep.suggested)}" maxlength="120"></label>
|
|
429
|
+
<div class="ask-actions"><button type="submit" class="primary">Keep</button><button type="button" class="quiet" data-keep="dismiss">Not now</button></div>
|
|
430
|
+
</form>`;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
async function keepJourney(form) {
|
|
434
|
+
const captureId = form.dataset.capture;
|
|
435
|
+
const name = form.elements.name.value.trim();
|
|
436
|
+
try {
|
|
437
|
+
const kept = await api(`/api/captures/${encodeURIComponent(captureId)}/keep`, { method:"POST", body:JSON.stringify({ name }) });
|
|
438
|
+
state.pendingKeep = null;
|
|
439
|
+
pushLine({ kind: "step", icon: "🧭", text: `Kept as “${kept.name}” — ${kept.steps} steps${kept.signedIn ? ", signs in as your test account" : ""}. Run it any time from Journeys.` });
|
|
440
|
+
renderChat();
|
|
441
|
+
await loadJourneys(); renderJourneys();
|
|
442
|
+
toast(`Kept “${kept.name}”.`);
|
|
443
|
+
} catch (error) { toast(error.message, true); }
|
|
444
|
+
}
|
|
445
|
+
|
|
385
446
|
function renderRuns() {
|
|
386
447
|
renderJourneys();
|
|
387
448
|
renderActors();
|
|
@@ -446,6 +507,8 @@ function renderChat() {
|
|
|
446
507
|
// engine waits, so leave the DOM alone until the ask is answered or withdrawn.
|
|
447
508
|
const openAsk = node.querySelector("#chat-ask");
|
|
448
509
|
if (openAsk && state.pendingInput && openAsk.dataset.request === String(state.pendingInput.requestId)) return;
|
|
510
|
+
const openKeep = node.querySelector("#chat-keep");
|
|
511
|
+
if (openKeep && state.pendingKeep && openKeep.dataset.capture === state.pendingKeep.captureId && !state.activeJob) return;
|
|
449
512
|
const stickToBottom = node.scrollTop + node.clientHeight >= node.scrollHeight - 24;
|
|
450
513
|
const lines = state.transcript.map((entry) => {
|
|
451
514
|
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>`;
|
|
@@ -454,7 +517,7 @@ function renderChat() {
|
|
|
454
517
|
if (entry.kind === "finding") return `<div class="chat-line finding ${esc(entry.severity)}"><span class="chat-icon">${entry.icon}</span><span>${esc(entry.text)}</span></div>`;
|
|
455
518
|
if (entry.kind === "progress") return "";
|
|
456
519
|
return `<div class="chat-line ${esc(entry.kind || "")}"><span class="chat-icon">${entry.icon || "•"}</span><span>${esc(entry.text)}${entry.detail ? ` <em>— ${esc(entry.detail)}</em>` : ""}</span></div>`;
|
|
457
|
-
}).join("") + renderAskCard() + (state.activeJob && !state.pendingInput ? '<div class="chat-line typing"><span class="chat-icon">✨</span><span>tapp is working<i>…</i></span></div>' : "");
|
|
520
|
+
}).join("") + renderAskCard() + renderKeepCard() + (state.activeJob && !state.pendingInput ? '<div class="chat-line typing"><span class="chat-icon">✨</span><span>tapp is working<i>…</i></span></div>' : "");
|
|
458
521
|
node.innerHTML = lines;
|
|
459
522
|
if (stickToBottom) node.scrollTop = node.scrollHeight;
|
|
460
523
|
const progress = [...state.transcript].reverse().find((entry) => entry.kind === "progress");
|
|
@@ -662,6 +725,7 @@ async function refresh() {
|
|
|
662
725
|
state.audits = runs.audits || [];
|
|
663
726
|
state.explores = runs.explores || [];
|
|
664
727
|
state.actors = actors.apps || [];
|
|
728
|
+
await loadJourneys();
|
|
665
729
|
renderProject();
|
|
666
730
|
return;
|
|
667
731
|
}
|
|
@@ -670,6 +734,7 @@ async function refresh() {
|
|
|
670
734
|
state.live = live;
|
|
671
735
|
state.audits = runs.audits || [];
|
|
672
736
|
state.explores = runs.explores || [];
|
|
737
|
+
await loadJourneys();
|
|
673
738
|
renderProject();
|
|
674
739
|
}
|
|
675
740
|
|
|
@@ -774,6 +839,8 @@ async function startFromPrompt(raw) {
|
|
|
774
839
|
}
|
|
775
840
|
if (result?.kind === "self-host") { answerSelfHost(result); return; }
|
|
776
841
|
state.selectedRunId = result?.capture?.id || state.selectedRunId;
|
|
842
|
+
state.pendingKeep = null;
|
|
843
|
+
await offerJourney(result);
|
|
777
844
|
return;
|
|
778
845
|
}
|
|
779
846
|
state.promptRun = true; state.promptPlatform = "web";
|
|
@@ -844,14 +911,25 @@ document.addEventListener("submit", (event) => {
|
|
|
844
911
|
if (ask) { event.preventDefault(); answerAsk(ask, "submit"); }
|
|
845
912
|
const signin = event.target.closest("#signin-form");
|
|
846
913
|
if (signin) { event.preventDefault(); requestSignInLink(signin.elements.email.value.trim()); }
|
|
914
|
+
const keep = event.target.closest("#chat-keep");
|
|
915
|
+
if (keep) { event.preventDefault(); keepJourney(keep); }
|
|
847
916
|
});
|
|
848
917
|
document.addEventListener("click", (event) => {
|
|
849
918
|
const button = event.target.closest("#chat-ask [data-ask]");
|
|
850
919
|
if (button && button.type === "button") { event.preventDefault(); answerAsk(button.closest("#chat-ask"), button.dataset.ask); }
|
|
851
920
|
const play = event.target.closest("[data-run-journey]");
|
|
852
921
|
if (play) { event.preventDefault(); runJourney(play.dataset.runJourney).catch((error) => toast(error.message, true)); }
|
|
853
|
-
if (event.target.closest("[data-signin]")) {
|
|
922
|
+
if (event.target.closest("[data-signin]")) {
|
|
923
|
+
event.preventDefault();
|
|
924
|
+
// With Cloudflare Access in front, the sign-in page is Cloudflare's; otherwise ask for an
|
|
925
|
+
// address here and mail a link.
|
|
926
|
+
if (state.session?.signInProvider === "cloudflare") { location.href = "/auth/cloudflare"; return; }
|
|
927
|
+
state.signInOpen = true; renderAccount(); showPrompt(); setTimeout(() => $("#signin-email")?.focus(), 50);
|
|
928
|
+
}
|
|
854
929
|
if (event.target.closest("[data-signout]")) { event.preventDefault(); signOut(); }
|
|
930
|
+
if (event.target.closest("[data-keep=dismiss]")) { event.preventDefault(); state.pendingKeep = null; renderChat(); }
|
|
931
|
+
const forgetJ = event.target.closest("[data-forget-journey]");
|
|
932
|
+
if (forgetJ) { event.preventDefault(); forgetJourney(forgetJ.dataset.forgetJourney).catch((error) => toast(error.message, true)); }
|
|
855
933
|
const forget = event.target.closest("[data-forget-actor]");
|
|
856
934
|
if (forget) { event.preventDefault(); forgetActor(forget.dataset.forgetHost, forget.dataset.forgetActor).catch((error) => toast(error.message, true)); }
|
|
857
935
|
});
|
package/browser/index.html
CHANGED
|
@@ -176,8 +176,8 @@
|
|
|
176
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
177
|
<div id="actors-list"><div class="empty">None yet. Explore a site with a sign-in and tapp will ask.</div></div>
|
|
178
178
|
</section>
|
|
179
|
-
<section class="panel section" id="journeys-panel"
|
|
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>
|
|
179
|
+
<section class="panel section" id="journeys-panel">
|
|
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 id="journeys-note">Each replays exactly as written — no model, no key. Keep one from any run that got somewhere; run it any time to prove it still works.</p></div></div>
|
|
181
181
|
<div id="journeys-list"><div class="empty">No journeys yet.</div></div>
|
|
182
182
|
</section>
|
|
183
183
|
<div class="split-view">
|
package/docs/BROWSER-PRODUCT.md
CHANGED
|
@@ -93,6 +93,15 @@ There is no password. Links work once and expire in 15 minutes; sessions last 90
|
|
|
93
93
|
SHA-256 of either token is on disk (`account-store.js`). One address may ask for five links per
|
|
94
94
|
ten minutes, and the reply is the same whether or not the address has an account.
|
|
95
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
|
+
|
|
96
105
|
**Mail** is sent through Resend when `TAPP_MAIL_RESEND_KEY` and `TAPP_MAIL_FROM` are set
|
|
97
106
|
(`mailer.js`). Without them, each message is written as a 0600 `.eml` into `TAPP_MAIL_OUTBOX`
|
|
98
107
|
(default `TAPP_HOME/mail-outbox`) — what tests and a local trial use, and what a freshly deployed
|
|
@@ -105,3 +114,26 @@ write-only from the UI, encrypted at rest, decrypted only inside the run that si
|
|
|
105
114
|
|
|
106
115
|
A local trial of the public mode (`--origin http://127.0.0.1:PORT`) does not pin browser egress
|
|
107
116
|
to public addresses, so it can reach a site on the same machine; a real origin always does.
|
|
117
|
+
|
|
118
|
+
## Journeys: keeping a proven run
|
|
119
|
+
|
|
120
|
+
A run that got somewhere is offered in the chat as a journey (`journeys.js`). Keeping it writes a
|
|
121
|
+
Flow in the runner's vocabulary — `wait_for` each screen, `tap` each control and navigation link,
|
|
122
|
+
`login: $TEST_EMAIL / $TEST_PASSWORD` for a sign-in, `assert_screen` on the last screen — to the
|
|
123
|
+
place this person owns:
|
|
124
|
+
|
|
125
|
+
| Who | Where | Replayed by |
|
|
126
|
+
|---|---|---|
|
|
127
|
+
| Operator with a repository open | `<repo>/.tapp/flows/<slug>.yml` | the Studio, `tapp run`, `tapp ci` |
|
|
128
|
+
| Account on a public Studio | `TAPP_HOME/accounts/journeys/<id>/<slug>.yml` | the Studio |
|
|
129
|
+
| Operator without a repository | `TAPP_HOME/journeys/<slug>.yml` | the Studio |
|
|
130
|
+
|
|
131
|
+
The last replay's result sits beside it in `.status/<slug>.json` and shows in the Journeys panel
|
|
132
|
+
as *passing · 2h ago*, *failing* or *never run*. A replay resolves `$TEST_EMAIL`/`$TEST_PASSWORD`
|
|
133
|
+
from the encrypted actor store for the journey's `actor` (never from the file) and, for a journey
|
|
134
|
+
kept from a run that started signed in, opens the browser from that actor's saved session.
|
|
135
|
+
|
|
136
|
+
Endpoints: `POST /api/captures/:id/keep` (`{ name, actor, replace, preview }` — `preview` names
|
|
137
|
+
the journey and lists its screens without keeping it), `GET /api/journeys`,
|
|
138
|
+
`DELETE /api/journeys/:slug` (kept journeys only; committed flows are the repository's),
|
|
139
|
+
`POST /api/operations/run-flow` (`{ name }`).
|
|
@@ -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
|
+
}
|
|
@@ -83,7 +83,13 @@ export class AccountStore {
|
|
|
83
83
|
const link = readJson(file);
|
|
84
84
|
try { fs.rmSync(file, { force: true }); } catch { /* spent either way */ }
|
|
85
85
|
if (!link || Date.parse(link.expiresAt) < this.now()) return null;
|
|
86
|
-
|
|
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));
|
|
87
93
|
const session = token();
|
|
88
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() });
|
|
89
95
|
return { session, account };
|
|
@@ -20,6 +20,8 @@ import { JobLanes } from "./job-lanes.js";
|
|
|
20
20
|
import { AccountStore } from "./account-store.js";
|
|
21
21
|
import { ActorStore, hostKey } from "./actor-store.js";
|
|
22
22
|
import { createMailer, signInMessage } from "./mailer.js";
|
|
23
|
+
import { accessConfig, createAccessVerifier } from "./access-jwt.js";
|
|
24
|
+
import { journeyFromCapture, JourneyStore, slugify } from "./journeys.js";
|
|
23
25
|
|
|
24
26
|
const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
|
|
25
27
|
const assetRoot = path.join(packageRoot, "browser");
|
|
@@ -132,8 +134,8 @@ function anonymousAllows(method, pathname) {
|
|
|
132
134
|
if (/^\/api\/captures\/[A-Za-z0-9._-]{1,128}\/files$/.test(pathname)) return true;
|
|
133
135
|
if (/^\/evidence\/captures\//.test(pathname)) return true;
|
|
134
136
|
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;
|
|
137
|
+
// Following a sign-in link from an email, or arriving back from Cloudflare Access.
|
|
138
|
+
if (pathname === "/auth/cloudflare" || /^\/auth\/[A-Za-z0-9_-]{20,}$/.test(pathname)) return true;
|
|
137
139
|
return false;
|
|
138
140
|
}
|
|
139
141
|
// Asking for a sign-in link is the one thing a stranger may post besides a run.
|
|
@@ -152,8 +154,11 @@ function anonymousAllows(method, pathname) {
|
|
|
152
154
|
function accountAllows(method, pathname) {
|
|
153
155
|
if (anonymousAllows(method, pathname)) return true;
|
|
154
156
|
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;
|
|
157
|
+
if (method === "GET" && (pathname === "/api/actors" || pathname === "/api/journeys")) return true;
|
|
156
158
|
if (method === "DELETE" && /^\/api\/actors\/[A-Za-z0-9.:-]{1,253}\/[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(pathname)) return true;
|
|
159
|
+
// Journeys: keep a proven run, replay it, forget it (ADR-0009 slice 3).
|
|
160
|
+
if (method === "POST" && (/^\/api\/captures\/[A-Za-z0-9._-]{1,128}\/keep$/.test(pathname) || pathname === "/api/operations/run-flow")) return true;
|
|
161
|
+
if (method === "DELETE" && /^\/api\/journeys\/[a-z0-9-]{1,60}$/.test(pathname)) return true;
|
|
157
162
|
return false;
|
|
158
163
|
}
|
|
159
164
|
|
|
@@ -453,7 +458,7 @@ function serveLoginPage(response, { failed = false, next = "" } = {}) {
|
|
|
453
458
|
response.end(html);
|
|
454
459
|
}
|
|
455
460
|
|
|
456
|
-
export async function startBrowserProduct({ projectDir, port = 0, launch = false, workspaceRoot, githubProvider, publicOrigin = "", trustedProxyToken = "", directLogin = null, publicEgressOnly = null, publicAccess = false } = {}) {
|
|
461
|
+
export async function startBrowserProduct({ projectDir, port = 0, launch = false, workspaceRoot, githubProvider, publicOrigin = "", trustedProxyToken = "", directLogin = null, publicEgressOnly = null, publicAccess = false, accessVerifier = undefined } = {}) {
|
|
457
462
|
const hosted = !!trustedProxyToken || !!directLogin || !!publicAccess;
|
|
458
463
|
// publicOrigin accepts a comma-separated allowlist; the first entry is canonical.
|
|
459
464
|
const publicOrigins = String(publicOrigin || "").split(",").map((value) => value.trim().replace(/\/$/, "")).filter(Boolean);
|
|
@@ -489,6 +494,16 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
489
494
|
// Accounts exist only on a public Studio: a local one has exactly one person, the operator.
|
|
490
495
|
const accounts = publicAccess ? new AccountStore() : null;
|
|
491
496
|
const mailer = publicAccess ? createMailer() : null;
|
|
497
|
+
// With Cloudflare Access in front of /auth/cloudflare, identity comes from Cloudflare's signed
|
|
498
|
+
// assertion and tapp sends no email at all. Configured by TAPP_ACCESS_TEAM_DOMAIN + TAPP_ACCESS_AUD;
|
|
499
|
+
// tests inject a verifier. The email link stays available as the provider-free path.
|
|
500
|
+
const access = accessVerifier !== undefined ? accessVerifier : (publicAccess && accessConfig() ? createAccessVerifier(accessConfig()) : null);
|
|
501
|
+
const signInProvider = access ? "cloudflare" : "email";
|
|
502
|
+
const openAccountSession = (response, signedIn, location = "/?signin=done") => {
|
|
503
|
+
logUsage("signin.done", { account: signedIn.account.id.slice(0, 8), provider: signInProvider });
|
|
504
|
+
response.writeHead(303, { location, "set-cookie": `${ACCOUNT_COOKIE}=${encodeURIComponent(signedIn.session)}; HttpOnly; SameSite=Lax;${secureCookies ? " Secure;" : ""} Path=/; Max-Age=7776000` });
|
|
505
|
+
response.end();
|
|
506
|
+
};
|
|
492
507
|
const secureCookies = publicOrigins[0]?.startsWith("https:") ?? false;
|
|
493
508
|
const serverStartedAt = new Date().toISOString();
|
|
494
509
|
const sessionToken = crypto.randomBytes(32).toString("base64url");
|
|
@@ -731,9 +746,23 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
731
746
|
if (authLinkMatch) {
|
|
732
747
|
const signedIn = accounts.redeem(authLinkMatch[1]);
|
|
733
748
|
if (!signedIn) { response.writeHead(303, { location: "/?signin=expired" }); response.end(); return; }
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
749
|
+
openAccountSession(response, signedIn);
|
|
750
|
+
return;
|
|
751
|
+
}
|
|
752
|
+
// Back from Cloudflare Access: the assertion header is only ever set by Cloudflare on a
|
|
753
|
+
// request that passed its policy, and the signature proves it. Without Access configured
|
|
754
|
+
// the path says so instead of pretending.
|
|
755
|
+
if (publicAccess && request.method === "GET" && url.pathname === "/auth/cloudflare") {
|
|
756
|
+
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; }
|
|
757
|
+
const assertion = String(request.headers["cf-access-jwt-assertion"] || cookies(request).CF_Authorization || "");
|
|
758
|
+
try {
|
|
759
|
+
const { email } = await access.verify(assertion);
|
|
760
|
+
openAccountSession(response, accounts.signIn(email));
|
|
761
|
+
} catch (error) {
|
|
762
|
+
logUsage("signin.access.refused", { reason: String(error.message || error).slice(0, 120) });
|
|
763
|
+
response.writeHead(303, { location: "/?signin=expired" });
|
|
764
|
+
response.end();
|
|
765
|
+
}
|
|
737
766
|
return;
|
|
738
767
|
}
|
|
739
768
|
if (account && request.method === "POST" && url.pathname === "/api/auth/signout") {
|
|
@@ -762,12 +791,62 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
762
791
|
json(response, 200, { ok: true });
|
|
763
792
|
return;
|
|
764
793
|
}
|
|
794
|
+
// Where this person's journeys live: the open repository's .tapp/flows/ for the operator,
|
|
795
|
+
// the account's own store on a public Studio, this machine's store otherwise.
|
|
796
|
+
const journeyStore = () => {
|
|
797
|
+
if (account) return JourneyStore.forAccount(account.id);
|
|
798
|
+
const root = registry.currentRoot();
|
|
799
|
+
return root ? JourneyStore.forRepository(root) : JourneyStore.forMachine();
|
|
800
|
+
};
|
|
801
|
+
const keepMatch = !anonymous && request.method === "POST" ? url.pathname.match(/^\/api\/captures\/([A-Za-z0-9._-]{1,128})\/keep$/) : null;
|
|
802
|
+
if (keepMatch) {
|
|
803
|
+
requireMutationAuth(request, hosted ? publicOrigins : origin, csrfToken);
|
|
804
|
+
if (!visibleToOwner(keepMatch[1], evidenceOwner)) { response.writeHead(404); response.end("Not found"); return; }
|
|
805
|
+
const captureDir = capturePath(keepMatch[1], ".");
|
|
806
|
+
if (!captureDir || !fs.existsSync(captureDir)) { json(response, 404, { error: "No such capture" }); return; }
|
|
807
|
+
const body = await readJsonBody(request);
|
|
808
|
+
const journey = journeyFromCapture(captureDir, { name: String(body.name || "").slice(0, 120), actor: /^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(String(body.actor || "")) ? String(body.actor) : "default" });
|
|
809
|
+
if (!journey) { json(response, 409, { error: "That run only looked around; there is no path to keep." }); return; }
|
|
810
|
+
// A preview names the journey and lists where it went without keeping anything, so the
|
|
811
|
+
// Studio can offer it with the right name instead of a guess.
|
|
812
|
+
if (body.preview === true) { json(response, 200, { name: journey.flow.name, slug: slugify(journey.flow.name), steps: journey.steps, screens: journey.screens, signedIn: journey.signedIn, preview: true }); return; }
|
|
813
|
+
let kept;
|
|
814
|
+
try { kept = journeyStore().keep(journey, { replace: body.replace === true }); }
|
|
815
|
+
catch (error) { json(response, error.statusCode || 500, { error: error.message }); return; }
|
|
816
|
+
logUsage("journey.kept", { owner: (ownerKey || "operator").slice(0, 13), steps: journey.steps, signedIn: journey.signedIn });
|
|
817
|
+
json(response, 200, { name: journey.flow.name, slug: kept.slug, steps: journey.steps, screens: journey.screens, signedIn: journey.signedIn, path: registry.currentRoot() && !account ? path.relative(registry.currentRoot(), kept.path) : null });
|
|
818
|
+
return;
|
|
819
|
+
}
|
|
820
|
+
if (!anonymous && request.method === "GET" && url.pathname === "/api/journeys") {
|
|
821
|
+
const store = journeyStore();
|
|
822
|
+
const root = !account ? registry.currentRoot() : null;
|
|
823
|
+
let journeys;
|
|
824
|
+
if (root) {
|
|
825
|
+
// The repository's committed flows, recursively, with the last Studio replay beside each.
|
|
826
|
+
const { readProductProject } = await import("./product-operations.js");
|
|
827
|
+
const flows = readProductProject({ projectDir: root }).flows || [];
|
|
828
|
+
journeys = flows.map((flow) => ({ name: flow.name, slug: flow.relativePath.replace(/^\.tapp\/flows\//, "").replace(/\.(?:ya?ml|json)$/i, ""), group: flow.group || "", platform: flow.platform, steps: flow.steps, source: "repo", status: store.status(flow.relativePath.replace(/^\.tapp\/flows\//, "").replace(/\.(?:ya?ml|json)$/i, "")) }));
|
|
829
|
+
} else {
|
|
830
|
+
journeys = store.list().map((journey) => ({ ...journey, group: "" }));
|
|
831
|
+
}
|
|
832
|
+
json(response, 200, { journeys });
|
|
833
|
+
return;
|
|
834
|
+
}
|
|
835
|
+
const forgetJourneyMatch = !anonymous && request.method === "DELETE" ? url.pathname.match(/^\/api\/journeys\/([a-z0-9-]{1,60})$/) : null;
|
|
836
|
+
if (forgetJourneyMatch) {
|
|
837
|
+
requireMutationAuth(request, hosted ? publicOrigins : origin, csrfToken);
|
|
838
|
+
// Committed flows are the repository's; only kept journeys are forgotten from here.
|
|
839
|
+
if (!account && registry.currentRoot()) { json(response, 409, { error: "That journey is committed in the repository; remove the file there." }); return; }
|
|
840
|
+
journeyStore().forget(forgetJourneyMatch[1]);
|
|
841
|
+
json(response, 200, { ok: true });
|
|
842
|
+
return;
|
|
843
|
+
}
|
|
765
844
|
if (request.method === "GET" && url.pathname === "/api/session") {
|
|
766
845
|
if (account) {
|
|
767
846
|
json(response, 200, {
|
|
768
847
|
csrfToken, mode: "public", product: "Tapp", root: null, repository: null, repositories: [],
|
|
769
848
|
contract: customerProductContract, supportedPlatforms: ["web"], runners: [],
|
|
770
|
-
access: "account", email: account.email,
|
|
849
|
+
access: "account", email: account.email, signInProvider,
|
|
771
850
|
accepts: ["url"],
|
|
772
851
|
selfHostOnly: ["path", "github", "bundle", "app", "apk"],
|
|
773
852
|
});
|
|
@@ -777,7 +856,7 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
777
856
|
json(response, 200, {
|
|
778
857
|
csrfToken, mode: "public", product: "Tapp", root: null, repository: null, repositories: [],
|
|
779
858
|
contract: customerProductContract, supportedPlatforms: ["web"], runners: [],
|
|
780
|
-
access: "anonymous",
|
|
859
|
+
access: "anonymous", signInProvider,
|
|
781
860
|
// The prompt screen offers folders, bundle ids and builds. None of them can work in
|
|
782
861
|
// a hosted Studio — there is no Mac, no simulator and no access to the visitor's
|
|
783
862
|
// disk — so say so here rather than letting the UI offer them.
|
|
@@ -1008,30 +1087,64 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
|
|
|
1008
1087
|
// answered with the command to run it where that is.
|
|
1009
1088
|
if (operation === "run-flow") {
|
|
1010
1089
|
if (anonymous) { json(response, 401, { error: "Sign in to replay a journey" }); return; }
|
|
1011
|
-
const
|
|
1012
|
-
|
|
1090
|
+
const store = journeyStore();
|
|
1091
|
+
const root = !account ? registry.currentRoot() : null;
|
|
1013
1092
|
const name = String(body.name || "").replace(/\.ya?ml$/i, "");
|
|
1014
1093
|
if (!/^[A-Za-z0-9][A-Za-z0-9._\/-]{0,120}$/.test(name) || name.includes("..")) throw Object.assign(new Error("That is not a journey name"), { statusCode: 400 });
|
|
1015
|
-
|
|
1016
|
-
|
|
1094
|
+
// A repository journey may sit in a subfolder; a kept one is a flat slug in its store.
|
|
1095
|
+
const flowPath = root ? path.join(root, ".tapp", "flows", `${name}.yml`) : store.flowPath(name);
|
|
1096
|
+
if (!flowPath.startsWith(store.root + path.sep) || !fs.existsSync(flowPath)) throw Object.assign(new Error(`No journey named ${name}`), { statusCode: 404 });
|
|
1017
1097
|
const { loadFlowFile, inferFlowPlatform } = await import("./flow-runtime.js");
|
|
1018
1098
|
const flow = loadFlowFile(flowPath);
|
|
1019
1099
|
const platform = inferFlowPlatform(flow);
|
|
1100
|
+
const shown = root ? path.relative(root, flowPath) : `${name}.yml`;
|
|
1020
1101
|
if (platform !== "web") {
|
|
1021
|
-
json(response, 200, { kind: "self-host", command: `npx -y @aarwitz/tapp@latest run ${
|
|
1022
|
-
message: `${flow.name || name} runs on ${platform === "android" ? "an Android device or emulator" : "an iOS simulator"}, which the Studio does not have. Run it where that is: npx -y @aarwitz/tapp@latest run ${
|
|
1102
|
+
json(response, 200, { kind: "self-host", command: `npx -y @aarwitz/tapp@latest run ${shown}`,
|
|
1103
|
+
message: `${flow.name || name} runs on ${platform === "android" ? "an Android device or emulator" : "an iOS simulator"}, which the Studio does not have. Run it where that is: npx -y @aarwitz/tapp@latest run ${shown}` });
|
|
1023
1104
|
return;
|
|
1024
1105
|
}
|
|
1106
|
+
// A journey that signs in does so as the test account tapp was told about for that
|
|
1107
|
+
// site: the values come from the encrypted actor store at replay and never from the file.
|
|
1108
|
+
const variables = {};
|
|
1109
|
+
let storageStatePath = "";
|
|
1110
|
+
if (flow.url && (flow.actor || (flow.steps || []).some((step) => step && typeof step === "object" && "login" in step))) {
|
|
1111
|
+
const actors = new ActorStore(actorRootFor() ? { root: actorRootFor() } : {});
|
|
1112
|
+
const record = actors.read(flow.url, flow.actor || "default");
|
|
1113
|
+
if (record?.credentials?.email) variables.TEST_EMAIL = record.credentials.email;
|
|
1114
|
+
if (record?.credentials?.password) variables.TEST_PASSWORD = record.credentials.password;
|
|
1115
|
+
// A journey that began inside replays from the actor's saved session, like the run did.
|
|
1116
|
+
if (flow.actor) storageStatePath = actors.sessionFile(flow.url, flow.actor) || "";
|
|
1117
|
+
}
|
|
1025
1118
|
const captureId = `flow-web-${Date.now().toString(36)}-${crypto.randomBytes(4).toString("hex")}`;
|
|
1026
1119
|
const evidenceDir = path.join(captureRoot(), captureId);
|
|
1027
1120
|
fs.mkdirSync(evidenceDir, { recursive: true });
|
|
1028
1121
|
const job = startJob(operation, async (progress) => {
|
|
1029
1122
|
progress({ phase: "runtime", text: `Replaying ${flow.name || name}` });
|
|
1030
1123
|
const { runWebFlow } = await import("./web-flow.js");
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1124
|
+
let result;
|
|
1125
|
+
try { result = await runWebFlow({ flow, variables, storageStatePath, logPath: path.join(evidenceDir, "flow.log"), screenshotDir: evidenceDir, recordVideoDir: evidenceDir }); }
|
|
1126
|
+
finally { if (storageStatePath) { try { fs.rmSync(storageStatePath, { force: true }); } catch { /* temp */ } } }
|
|
1127
|
+
// The runner's log is marker lines; the chat wants one plain sentence per step.
|
|
1128
|
+
for (const line of result.lines || []) {
|
|
1129
|
+
const raw = typeof line === "string" ? line : (line.text || "");
|
|
1130
|
+
const step = raw.match(/^OCQA_FLOW_STEP:(\{.*\})$/);
|
|
1131
|
+
if (step) {
|
|
1132
|
+
try {
|
|
1133
|
+
const s = JSON.parse(step[1]);
|
|
1134
|
+
const what = s.action === "login" ? "Signed in" : s.action === "wait_for" ? `Reached ${s.target}` : s.action === "assert_screen" ? `On ${s.target}` : s.action === "tap" ? `Tapped "${s.target}"` : `${s.action} ${s.target || ""}`.trim();
|
|
1135
|
+
progress({ phase: "replay", text: s.status === "pass" ? `${what}` : `Step ${s.index}: ${what} — ${s.detail || "failed"}` });
|
|
1136
|
+
} catch { progress({ phase: "replay", text: raw }); }
|
|
1137
|
+
continue;
|
|
1138
|
+
}
|
|
1139
|
+
if (/^OCQA_(FLOW_RESULT|ISSUE):/.test(raw)) continue;
|
|
1140
|
+
if (raw) progress({ phase: "replay", text: raw });
|
|
1141
|
+
}
|
|
1142
|
+
const status = store.recordRun(root ? name : slugify(name), { passed: result.passed, captureId, executed: result.executed, total: result.total, failed: result.failed });
|
|
1143
|
+
if (ownerKey) setCaptureOwner(captureId, ownerKey);
|
|
1144
|
+
logUsage("journey.run", { owner: (ownerKey || "operator").slice(0, 13), passed: result.passed });
|
|
1145
|
+
return { kind: "journey", name: flow.name || name, slug: root ? name : slugify(name), passed: result.passed, executed: result.executed, total: result.total, failed: result.failed, status, capture: { id: captureId, path: evidenceDir } };
|
|
1146
|
+
}, null, { lane: ownerKey || OPERATOR_LANE });
|
|
1147
|
+
job.ownerKey = ownerKey;
|
|
1035
1148
|
json(response, 202, { job: publicJob(job, { hosted }) });
|
|
1036
1149
|
return;
|
|
1037
1150
|
}
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
// A proven run becomes a journey you own (ADR-0009 slice 3).
|
|
2
|
+
//
|
|
3
|
+
// An exploration that got somewhere — through a sign-in, across a few screens — is worth more
|
|
4
|
+
// than its report: replayed, it is a test of that path through the real application. This
|
|
5
|
+
// module turns the capture's action log (OCQA_ACTION / OCQA_STATE markers) into a Flow in the
|
|
6
|
+
// vocabulary the deterministic runner already speaks, keeps it where it belongs, and remembers
|
|
7
|
+
// how its last replay went.
|
|
8
|
+
//
|
|
9
|
+
// Where a journey lives:
|
|
10
|
+
// a repository → <repo>/.tapp/flows/<slug>.yml (committed, guarded by `tapp ci`)
|
|
11
|
+
// an account → TAPP_HOME/accounts/journeys/<id>/<slug>.yml
|
|
12
|
+
// a local prompt run → TAPP_HOME/journeys/<slug>.yml
|
|
13
|
+
// Its last result lives beside it in .status/<slug>.json. Credentials never enter a journey: a
|
|
14
|
+
// sign-in is `login: $TEST_EMAIL / $TEST_PASSWORD`, resolved at replay from the actor store.
|
|
15
|
+
import fs from "node:fs";
|
|
16
|
+
import os from "node:os";
|
|
17
|
+
import path from "node:path";
|
|
18
|
+
|
|
19
|
+
const MAX_STEPS = 40;
|
|
20
|
+
|
|
21
|
+
export function slugify(name) {
|
|
22
|
+
return String(name || "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 60) || "journey";
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function readMarkers(captureDir) {
|
|
26
|
+
let text = "";
|
|
27
|
+
try { text = fs.readFileSync(path.join(captureDir, "ocqa-markers.txt"), "utf8"); } catch { return []; }
|
|
28
|
+
const out = [];
|
|
29
|
+
for (const line of text.split("\n")) {
|
|
30
|
+
const match = line.match(/^(OCQA_ACTION|OCQA_STATE):(\{.*\})\s*$/);
|
|
31
|
+
if (!match) continue;
|
|
32
|
+
try { out.push({ kind: match[1], ...JSON.parse(match[2]) }); } catch { /* a torn line */ }
|
|
33
|
+
}
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// tapp names a revisited screen "Orders (refreshed)"; the page itself still says "Orders".
|
|
38
|
+
const pageName = (screen) => String(screen || "").replace(/\s*\((?:refreshed|again|\d+)\)\s*$/i, "").trim();
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Build a Flow from an exploration capture. Returns null when the run did nothing worth
|
|
42
|
+
* replaying (no action but the opening).
|
|
43
|
+
*/
|
|
44
|
+
export function journeyFromCapture(captureDir, { name = "", actor = "default" } = {}) {
|
|
45
|
+
let provenance = null;
|
|
46
|
+
try { provenance = JSON.parse(fs.readFileSync(path.join(captureDir, "provenance.json"), "utf8")); } catch { /* older capture */ }
|
|
47
|
+
const target = String(provenance?.target || "");
|
|
48
|
+
if (!/^https?:\/\//i.test(target)) return null;
|
|
49
|
+
const markers = readMarkers(captureDir);
|
|
50
|
+
const steps = [];
|
|
51
|
+
const screens = [];
|
|
52
|
+
let lastWaited = "";
|
|
53
|
+
const waitFor = (screen) => {
|
|
54
|
+
const page = pageName(screen);
|
|
55
|
+
if (!page || page === lastWaited) return;
|
|
56
|
+
steps.push({ wait_for: page });
|
|
57
|
+
lastWaited = page;
|
|
58
|
+
screens.push(page);
|
|
59
|
+
};
|
|
60
|
+
let acted = false;
|
|
61
|
+
let signedIn = false;
|
|
62
|
+
for (let i = 0; i < markers.length && steps.length < MAX_STEPS; i += 1) {
|
|
63
|
+
const marker = markers[i];
|
|
64
|
+
if (marker.kind === "OCQA_STATE") { waitFor(marker.screen); continue; }
|
|
65
|
+
switch (marker.type) {
|
|
66
|
+
case "open":
|
|
67
|
+
// The first open is the journey's URL; a later one came through a navigation link.
|
|
68
|
+
if (marker.via && marker.via !== marker.target && marker.via !== "/") { steps.push({ tap: marker.via }); acted = true; }
|
|
69
|
+
break;
|
|
70
|
+
case "login":
|
|
71
|
+
steps.push({ login: { email: "$TEST_EMAIL", password: "$TEST_PASSWORD" } });
|
|
72
|
+
signedIn = true; acted = true;
|
|
73
|
+
break;
|
|
74
|
+
case "session":
|
|
75
|
+
// The run started inside from a saved session; the replay will too (storageState).
|
|
76
|
+
signedIn = true;
|
|
77
|
+
break;
|
|
78
|
+
case "tap":
|
|
79
|
+
if (marker.target) { steps.push({ tap: marker.target }); acted = true; }
|
|
80
|
+
break;
|
|
81
|
+
case "type":
|
|
82
|
+
// What was typed during exploration is not part of the path; the field is.
|
|
83
|
+
if (marker.target && !marker.secure) { steps.push({ type: { field: marker.target, value: String(marker.value || "") } }); acted = true; }
|
|
84
|
+
break;
|
|
85
|
+
default:
|
|
86
|
+
break;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
if (!acted) return null;
|
|
90
|
+
// End on the screen the run ended on, so a replay that drifts is a failure, not a pass.
|
|
91
|
+
if (lastWaited) { steps.pop(); steps.push({ assert_screen: lastWaited }); }
|
|
92
|
+
const host = (() => { try { return new URL(target).host; } catch { return "site"; } })();
|
|
93
|
+
const journeyName = String(name || "").trim() || `${host} — ${screens[0] || "start"}${screens.length > 1 ? ` to ${screens[screens.length - 1]}` : ""}`;
|
|
94
|
+
const flow = { name: journeyName, platform: "web", url: target, ...(signedIn ? { actor } : {}), steps };
|
|
95
|
+
return { flow, yaml: flowToYaml(flow), steps: steps.length, screens, signedIn };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// The Flow vocabulary is small and flat; a dependency-free emitter keeps the hosted Studio from
|
|
99
|
+
// needing python for this. Strings are JSON-quoted, which YAML accepts verbatim.
|
|
100
|
+
const q = (value) => JSON.stringify(String(value));
|
|
101
|
+
export function flowToYaml(flow) {
|
|
102
|
+
const lines = [`name: ${q(flow.name)}`, `platform: ${flow.platform || "web"}`];
|
|
103
|
+
if (flow.url) lines.push(`url: ${q(flow.url)}`);
|
|
104
|
+
if (flow.actor) lines.push(`actor: ${q(flow.actor)}`);
|
|
105
|
+
lines.push("steps:");
|
|
106
|
+
for (const step of flow.steps || []) {
|
|
107
|
+
const [action, value] = Object.entries(step)[0];
|
|
108
|
+
if (value && typeof value === "object") {
|
|
109
|
+
lines.push(`- ${action}:`);
|
|
110
|
+
for (const [key, inner] of Object.entries(value)) lines.push(` ${key}: ${/^\$[A-Z_]+$/.test(String(inner)) ? inner : q(inner)}`);
|
|
111
|
+
} else {
|
|
112
|
+
lines.push(`- ${action}: ${q(value)}`);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return `${lines.join("\n")}\n`;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Where kept journeys and their statuses live for one owner. */
|
|
119
|
+
export class JourneyStore {
|
|
120
|
+
constructor({ root }) {
|
|
121
|
+
this.root = root;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
static forAccount(accountId, env = process.env) {
|
|
125
|
+
const home = (env.TAPP_HOME || "").trim() || path.join(os.homedir(), ".tapp");
|
|
126
|
+
if (!/^[a-f0-9]{24}$/.test(String(accountId || ""))) throw new Error("Not an account id");
|
|
127
|
+
return new JourneyStore({ root: path.join(home, "accounts", "journeys", accountId) });
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
static forMachine(env = process.env) {
|
|
131
|
+
const home = (env.TAPP_HOME || "").trim() || path.join(os.homedir(), ".tapp");
|
|
132
|
+
return new JourneyStore({ root: path.join(home, "journeys") });
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
static forRepository(repoRoot) {
|
|
136
|
+
return new JourneyStore({ root: path.join(repoRoot, ".tapp", "flows") });
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
flowPath(slug) {
|
|
140
|
+
const safe = slugify(slug);
|
|
141
|
+
return path.join(this.root, `${safe}.yml`);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
keep(journey, { replace = false } = {}) {
|
|
145
|
+
const slug = slugify(journey.flow.name);
|
|
146
|
+
const file = this.flowPath(slug);
|
|
147
|
+
if (fs.existsSync(file) && !replace) throw Object.assign(new Error(`A journey named '${journey.flow.name}' already exists. Pick another name or replace it.`), { statusCode: 409 });
|
|
148
|
+
fs.mkdirSync(this.root, { recursive: true, mode: 0o700 });
|
|
149
|
+
fs.writeFileSync(file, journey.yaml, { mode: 0o600 });
|
|
150
|
+
return { slug, path: file };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
forget(slug) {
|
|
154
|
+
try { fs.rmSync(this.flowPath(slug), { force: true }); fs.rmSync(this.statusPath(slug), { force: true }); return true; } catch { return false; }
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
statusPath(slug) {
|
|
158
|
+
return path.join(this.root, ".status", `${slugify(slug)}.json`);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
recordRun(slug, { passed, captureId = null, executed = 0, total = 0, failed = 0 }) {
|
|
162
|
+
const file = this.statusPath(slug);
|
|
163
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
164
|
+
const status = { passed: !!passed, at: new Date().toISOString(), captureId, executed, total, failed };
|
|
165
|
+
fs.writeFileSync(file, JSON.stringify(status), { mode: 0o600 });
|
|
166
|
+
return status;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
status(slug) {
|
|
170
|
+
try { return JSON.parse(fs.readFileSync(this.statusPath(slug), "utf8")); } catch { return null; }
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Every journey here, with its last result. Names only; never the file contents. */
|
|
174
|
+
list() {
|
|
175
|
+
let entries = [];
|
|
176
|
+
try { entries = fs.readdirSync(this.root, { withFileTypes: true }); } catch { return []; }
|
|
177
|
+
const out = [];
|
|
178
|
+
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
179
|
+
if (!entry.isFile() || !/\.ya?ml$/i.test(entry.name)) continue;
|
|
180
|
+
const slug = entry.name.replace(/\.ya?ml$/i, "");
|
|
181
|
+
let source = "";
|
|
182
|
+
try { source = fs.readFileSync(path.join(this.root, entry.name), "utf8"); } catch { continue; }
|
|
183
|
+
const scalar = (key) => { const m = source.match(new RegExp(`^${key}:\\s*(.+?)\\s*$`, "m")); return m ? m[1].replace(/^["']|["']$/g, "") : ""; };
|
|
184
|
+
const steps = (source.match(/^- [a-z_]+:/gm) || []).length;
|
|
185
|
+
out.push({ name: scalar("name") || slug, slug, platform: scalar("platform") || "web", url: scalar("url"), actor: scalar("actor"), steps, status: this.status(slug), source: "kept" });
|
|
186
|
+
}
|
|
187
|
+
return out;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
@@ -879,7 +879,9 @@ export async function exploreWeb({ url, maxActions = 40, timeoutSec = 300, outDi
|
|
|
879
879
|
let probeCapHit = false;
|
|
880
880
|
let actions = 0;
|
|
881
881
|
let screenCount = 0;
|
|
882
|
-
|
|
882
|
+
// A marker as well as a line, so a journey kept from this run knows it began inside and
|
|
883
|
+
// replays from the same saved session rather than at a sign-in it never saw.
|
|
884
|
+
if (startedSignedIn) emitAction({ type: "session", target: "saved session", narrative: "Starting signed in from the saved session" });
|
|
883
885
|
// Which distinct on-screen states each route has produced, so one route cannot mint states
|
|
884
886
|
// without limit when something on it never settles.
|
|
885
887
|
const signaturesByRoute = new Map();
|
|
@@ -290,7 +290,7 @@ export function resolveGateFlowUrl(declared, gateUrl) {
|
|
|
290
290
|
}
|
|
291
291
|
}
|
|
292
292
|
|
|
293
|
-
export async function runWebFlow({ flow, url, logPath, screenshotDir, recordVideoDir, variables = {}, strictOrigin = false, playwright, device = "", viewport = "", urlIsFallback = false }) {
|
|
293
|
+
export async function runWebFlow({ flow, url, logPath, screenshotDir, recordVideoDir, variables = {}, strictOrigin = false, playwright, device = "", viewport = "", urlIsFallback = false, storageStatePath = "" }) {
|
|
294
294
|
// urlIsFallback = the caller is a gate: the Flow's own page wins, rebased onto the gate's
|
|
295
295
|
// deployment (see resolveGateFlowUrl). An explicit caller url (CLI positional) still overrides.
|
|
296
296
|
const declaredUrl = flow.url || (/^https?:\/\//i.test(flow.app || "") ? flow.app : "");
|
|
@@ -311,6 +311,8 @@ export async function runWebFlow({ flow, url, logPath, screenshotDir, recordVide
|
|
|
311
311
|
const context = await browser.newContext({
|
|
312
312
|
...contextOptions,
|
|
313
313
|
...(recordVideoDir ? { recordVideo: { dir: recordVideoDir, ...(contextOptions.viewport ? { size: contextOptions.viewport } : {}) } } : {}),
|
|
314
|
+
// A journey kept from a run that started signed in replays from the same saved session.
|
|
315
|
+
...(storageStatePath ? { storageState: storageStatePath } : {}),
|
|
314
316
|
});
|
|
315
317
|
const page = await context.newPage();
|
|
316
318
|
const timeout = Number(flow.timeoutMs ?? flow.timeout) || DEFAULT_TIMEOUT;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aarwitz/tapp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.24.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/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",
|
|
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/journeys.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
|
}
|
package/scripts/flow_lib.py
CHANGED
|
@@ -37,7 +37,7 @@ def to_yaml(json_str):
|
|
|
37
37
|
# Order keys for readability. `platform` + `url` make the same repository-native
|
|
38
38
|
# Flow format portable across the XCUITest, Playwright, and Android drivers.
|
|
39
39
|
ordered = {}
|
|
40
|
-
for k in ("name", "platform", "app", "url", "vars", "reset"):
|
|
40
|
+
for k in ("name", "platform", "app", "url", "actor", "vars", "reset"):
|
|
41
41
|
if flow.get(k):
|
|
42
42
|
ordered[k] = flow[k]
|
|
43
43
|
ordered["steps"] = flow.get("steps", [])
|
|
@@ -54,6 +54,8 @@ def to_json(path):
|
|
|
54
54
|
"platform": flow.get("platform", ""),
|
|
55
55
|
"app": flow.get("app", ""),
|
|
56
56
|
"url": flow.get("url", ""),
|
|
57
|
+
# Which test account a journey signs in as (ADR-0009); the Studio resolves it at replay.
|
|
58
|
+
"actor": str(flow.get("actor", "") or ""),
|
|
57
59
|
"steps": flow.get("steps", []),
|
|
58
60
|
"vars": flow.get("vars", {}),
|
|
59
61
|
"reset": flow.get("reset", "launch"),
|