@aarwitz/tapp 0.35.7 → 0.35.9

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.
@@ -52,12 +52,24 @@
52
52
  </div>
53
53
  </section>
54
54
 
55
+ <!-- Setting this machine up (ADR-0012's journey): the runtime, the agent on your own plan,
56
+ what each target needs with the exact fix, and the account. Local only; collapses to one
57
+ line once this machine is ready. -->
58
+ <section class="setup-card hidden" id="setup-card" aria-live="polite">
59
+ <div class="setup-head">
60
+ <div><p class="eyebrow">This machine</p><h2 id="setup-title">Set up tapp here</h2><p id="setup-sub">Everything runs on this machine. Four things to check, once.</p></div>
61
+ <div class="button-row"><button class="quiet" type="button" id="setup-toggle">Hide</button><button class="quiet" type="button" id="setup-refresh">Check again</button></div>
62
+ </div>
63
+ <ol class="setup-steps" id="setup-steps"><li class="empty">Checking this machine…</li></ol>
64
+ </section>
55
65
  <section class="prompt-block">
56
66
  <h1>What should tapp test?</h1>
57
67
  <form class="prompt-form" id="prompt-form" autocomplete="off">
58
68
  <label class="prompt-field"><span class="sr-only">Website, repository, folder, or build</span><input id="prompt-input" name="input" placeholder="A website URL, a GitHub repo, a folder on this Mac, a bundle id, an .app or .apk…" spellcheck="false" required></label>
59
69
  <button class="primary prompt-go" type="submit" id="prompt-start" aria-label="Start">→</button>
60
70
  </form>
71
+ <small id="business-hint" class="prompt-note hidden">Search this name in Apple’s US App Store, or enter the website directly.</small>
72
+ <section id="business-results" class="hidden" aria-live="polite" aria-label="Matching apps"></section>
61
73
  <div class="platform-strip" id="platform-strip" hidden></div>
62
74
  <ul class="prompt-suggestions" aria-label="Examples">
63
75
  <li><button type="button" data-kind="url" data-prompt="https://example.com"><span>⌁</span><b>https://example.com</b><small>audit a website read-only — safe on production, nothing is clicked</small></button></li>
@@ -65,10 +77,25 @@
65
77
  <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>
66
78
  <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>
67
79
  </ul>
80
+ <!-- The front door (ADR-0011): on a hosted Studio, everything a website is not runs on the
81
+ person's own machine, and the page says so — with the command — before anyone types
82
+ one. Hidden on a local Studio, which is that machine. -->
83
+ <section class="selfhost-card hidden" id="selfhost-card">
84
+ <p class="selfhost-lead" id="selfhost-lead"><strong>Everything else runs on your own machine — connect it.</strong> Run this once in a terminal: it opens this page connected to your Mac or PC, and everything — your repositories, iOS and Android builds, macOS apps, staging and localhost — runs there. Nothing leaves it.</p>
85
+ <div class="selfhost-row"><code id="selfhost-command">npx -y @aarwitz/tapp@latest app --connect</code><button class="quiet" type="button" id="selfhost-copy">Copy</button></div>
86
+ <small id="selfhost-note">Needs Node.js 20 or newer. No account needed. If your browser refuses to reach your machine, the same Studio opens at the address the command prints.</small>
87
+ </section>
88
+ <!-- The cloud — tapp running it for you — is coming, not sold (ADR-0011 §3). An address to
89
+ tell, and a way in for an account that already exists. -->
90
+ <section class="selfhost-card hidden" id="cloud-card">
91
+ <p class="selfhost-lead"><strong>Cloud — tapp runs it for you — coming soon.</strong> Leave an address and we will tell you when it opens. <button type="button" class="linklike" data-signin>Have an account? Sign in</button></p>
92
+ <form class="selfhost-row" id="cloud-interest" autocomplete="email"><input name="email" type="email" placeholder="you@company.com" aria-label="Email" required><button class="quiet" type="submit">Tell me</button></form>
93
+ <p class="cloud-sent hidden" id="cloud-sent"></p>
94
+ </section>
68
95
  <!-- Signing in to a public Studio: an email address and a link, nothing else. Hidden on a
69
96
  local Studio, where the one person at the keyboard is the operator already. -->
70
97
  <section class="signin-card hidden" id="signin-card" aria-live="polite">
71
- <p class="signin-lead"><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>
98
+ <p class="signin-lead"><strong>Sign in to go inside a site from here.</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. The cloud is free for 14 days, no card; your own machine is never gated.</p>
72
99
  <div id="signin-providers"></div>
73
100
  <form id="signin-form" autocomplete="email">
74
101
  <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>
@@ -145,6 +172,13 @@
145
172
  <span class="chat-caret" aria-hidden="true">▾</span>
146
173
  </button>
147
174
  <div class="chat-transcript" id="chat-transcript"></div>
175
+ <!-- The person's own agent, driving tapp from here (ADR-0012). Local only, and only when
176
+ an engine on this machine is signed in. -->
177
+ <form class="chat-prompt hidden" id="chat-prompt" autocomplete="off">
178
+ <input id="chat-prompt-input" name="prompt" placeholder="Ask tapp to test something…" aria-label="Ask tapp" maxlength="4000" required>
179
+ <button class="primary" type="submit" id="chat-prompt-send">Send</button>
180
+ <button class="quiet hidden" type="button" id="chat-prompt-stop">Stop</button>
181
+ </form>
148
182
  </aside>
149
183
  </section>
150
184
 
@@ -219,6 +253,21 @@
219
253
  </div>
220
254
  <div id="token-list"><div class="empty">No tokens yet.</div></div>
221
255
  </section>
256
+ <!-- Results flow up, the browser never reaches down (ADR-0011 §4): a self-hosted Studio
257
+ reports journeys run here to an account on app.runtapp.com. Local only. -->
258
+ <section class="panel section hidden" id="link-panel">
259
+ <div class="section-heading compact">
260
+ <div><p class="eyebrow">Your tapp account</p><h2>Report what runs here to your account</h2><p id="link-note">Journeys you run on this machine — including against staging and localhost — show up on your account with how their last run went. Nothing else leaves this machine: not the journey, not a credential, not a screenshot.</p></div>
261
+ </div>
262
+ <div id="link-body"></div>
263
+ </section>
264
+ <!-- Which agent drives tapp from the chat, on whose plan (ADR-0012). Local only. -->
265
+ <section class="panel section hidden" id="engines-panel">
266
+ <div class="section-heading compact">
267
+ <div><p class="eyebrow">Your agent</p><h2>Who drives tapp from the chat</h2><p>tapp signs you in to nothing and holds no token: it finds the coding agent you already signed in to on this machine and drives it on your own plan. In the chat it gets tapp's tools and reading the project — never a shell, never an edit.</p></div>
268
+ </div>
269
+ <div id="engines-list"><div class="empty">Checking this machine…</div></div>
270
+ </section>
222
271
  <section class="panel section" id="journeys-panel">
223
272
  <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>
224
273
  <div id="journeys-list"><div class="empty">No journeys yet.</div></div>
@@ -31,7 +31,7 @@ export const customerProductContract = Object.freeze({
31
31
  { id: "platforms", label: "Platforms", capabilities: ["platform-matrix", "self-host-command", "platform-interest"] },
32
32
  { id: "admin", label: "Admin", capabilities: ["deployment-usage", "account-list", "platform-demand"] },
33
33
  ],
34
- operations: ["initialize", "session-start", "session-act", "session-save-flow", "session-end", "gate", "audit"],
34
+ operations: ["initialize", "session-start", "session-act", "session-save-flow", "session-end", "gate", "audit", "agent", "agent-stop"],
35
35
  invariants: [
36
36
  "The Studio shows runs; it never scores or judges them. Only the deterministic gate decides.",
37
37
  "Every run's evidence is the report.html the engine wrote; the Studio links to it rather than re-rendering it.",
@@ -64,6 +64,12 @@ const RULES = [
64
64
  export function narrate(entry = {}, { platform = "" } = {}) {
65
65
  const text = String(entry.text || "").trim().replace(/\s+/g, " ");
66
66
  if (!text) return null;
67
+ // The person's own agent talking (ADR-0012): its words, the tapp tool it reached for, a tool
68
+ // that answered with an error, and its final answer — each told apart at a glance.
69
+ if (entry.phase === "agent") return { kind: "agent", icon: "🤖", text };
70
+ if (entry.phase === "agent-tool") return { kind: "step", icon: "🛠️", text };
71
+ if (entry.phase === "agent-warning") return { kind: "warning", icon: "⚠️", text };
72
+ if (entry.phase === "agent-done") return { kind: "agent", icon: "✅", text };
67
73
  const progress = text.match(/^(\d+)\/(\d+) actions(?: · (\d+) (?:states?|pages?|screens?)[^·]*)?/i);
68
74
  if (progress) return { kind: "progress", icon: "⏳", text, current: Number(progress[1]), total: Number(progress[2]), states: progress[3] ? Number(progress[3]) : null };
69
75
  for (const [pattern, icon] of RULES) {
@@ -99,6 +105,11 @@ export function summarize(name, result = {}, { access = "" } = {}) {
99
105
  const noticedText = noticed ? ` It also found ${noticed} thing${noticed === 1 ? "" : "s"} a person would notice — faint text, controls too small to tap on a phone, copy nobody finished — listed under “Worth a look”.` : "";
100
106
  return { tone: issues ? "caution" : noticed ? "caution" : "ready", pill, text: `${result.pagesAudited || 0} page(s) rendered read-only — nothing was clicked. ${issues ? "Each issue is listed in the run detail with the pages it appears on." : "Nothing is broken."}${noticedText}${next}` };
101
107
  }
108
+ // A chat turn with the agent: what it said last, and how many turns it took. Never a verdict.
109
+ if (name === "agent") {
110
+ const turns = Number(result?.turns) || 0;
111
+ return { tone: result?.isError ? "caution" : "ready", pill: result?.isError ? "Stopped" : `✓ ${turns} turn${turns === 1 ? "" : "s"}`, text: String(result?.text || "Done.").slice(0, 600) };
112
+ }
102
113
  if (gateOutcome) {
103
114
  const tone = { pass: "ready", fail: "blocked", inconclusive: "caution" }[gateOutcome] || "caution";
104
115
  const pill = { pass: "✓ Ready to merge", fail: "× Do not merge", inconclusive: "◐ Inconclusive" }[gateOutcome];
@@ -293,3 +304,16 @@ export function coverageGraph(uiMap, shots = [], { platform = "" } = {}) {
293
304
  unreachable,
294
305
  };
295
306
  }
307
+
308
+ // app.runtapp.com driving the runtime on this person's machine (ADR-0011 §4, join B). The
309
+ // runtime opens the hosted page with its own address and the launch secret in the URL FRAGMENT,
310
+ // which a browser never sends to the server — so the hosted Studio learns where the machine is
311
+ // without the cloud ever seeing the secret.
312
+ export function parseConnectFragment(hash = "") {
313
+ const params = new URLSearchParams(String(hash || "").replace(/^#/, ""));
314
+ const origin = String(params.get("connect") || "").trim().replace(/\/$/, "");
315
+ const token = String(params.get("token") || "").trim();
316
+ if (!/^http:\/\/(?:127\.0\.0\.1|localhost|\[::1\])(?::\d{1,5})?$/.test(origin)) return null;
317
+ if (!/^[A-Za-z0-9_-]{20,}$/.test(token)) return null;
318
+ return { origin, token };
319
+ }
@@ -1,8 +1,9 @@
1
1
  # Browser Studio
2
2
 
3
- Status: current product contract as of 2026-11-15 (ADR-0006, owner decision, amended twice:
4
- 2026-10-19, and TM-794 on 2026-11-15 bringing Findings and Coverage back). Supersedes
5
- the "desktop-parity Command Center" framing of 2026-10-14.
3
+ Status: current product contract as of 2026-11-20 (ADR-0006, owner decision, amended three
4
+ times: 2026-10-19; TM-794 on 2026-11-15 bringing Findings and Coverage back; and ADR-0011 on
5
+ 2026-11-20 making the hosted first page the front door). Supersedes the "desktop-parity Command
6
+ Center" framing of 2026-10-14.
6
7
 
7
8
  The Studio in `browser/` is the one browser surface. It is a **run viewer**: point Tapp at a
8
9
  repository target or a website, watch the run live, open its evidence. It never scores or judges
@@ -34,11 +35,18 @@ looping animation of a device being driven (launch, tap, tap, screenshot, ✓).
34
35
  | `owner/repo`, `github.com/owner/repo` | Cloned with `gh` into an isolated workspace under `TAPP_HOME`, then the same. |
35
36
  | `com.company.app` | Explored on the booted iOS simulator as it is (no build). |
36
37
  | `/path/to/Demo.app`, `~/Downloads/app.apk` | Installed on the booted simulator / connected device, then explored. |
37
- | a business name | Answered honestly: nothing discovers surfaces from a name yet; paste its URL. |
38
+ | a business name | Searches Apple's US App Store. Choose a matching publisher's website to start a run, or supply a URL directly. The App Store link opens the listing. |
38
39
 
39
40
  The server classifies the input again (`classifyPrompt` in `browser/view-model.js` is shared) and
40
41
  refuses what the mode cannot do: a hosted Studio cannot open a path or a build on your machine.
41
42
 
43
+ **On a hosted Studio the page is the front door (ADR-0011).** The box takes a public website. A
44
+ self-host card under it names everything else — repositories, iOS and Android builds, macOS apps,
45
+ staging and localhost — with the command that opens this same Studio on the person's machine, and
46
+ the examples the deployment cannot start are not offered. Typing one anyway still gets the
47
+ structured `self-host` answer in the chat (ADR-0010). The platform chips are the same in both
48
+ modes; on a laptop most of them say "ready".
49
+
42
50
  ## What is on the page
43
51
 
44
52
  | View | What it shows | Operations |
@@ -101,6 +109,78 @@ an allowlist in `browser-product.js` (`anonymousAllows`, `accountAllows`):
101
109
  | Evidence | Captures stamped with their visitor cookie | Captures stamped `acct:<id>` | All captures on the machine |
102
110
  | Test accounts | None — a visitor is never asked | Encrypted, per account: `TAPP_HOME/accounts/actors/<id>/` | `TAPP_HOME/actors/` |
103
111
 
112
+ **The cloud beyond the visitor audit is for an account on a plan or in its free trial (ADR-0011
113
+ §3).** A new account starts a 14-day trial (`plan` on the account record; `account-store.js`
114
+ `entitlement`); an account from before plans existed gets its trial from the day it is next seen.
115
+ Starting a cloud run — `POST /api/operations/explore`, `/api/operations/run-flow`,
116
+ `/api/journeys`, `/api/captures/<id>/keep` — answers **402** with the reason once the trial has
117
+ lapsed, and the daily checks skip that account's journeys; reading what the account owns stays
118
+ open, so it can still see and forget its journeys, test accounts and tokens. The deployment's
119
+ owner (`TAPP_ADMIN_EMAILS`) is never gated and marks an account paid or extends its trial from the
120
+ Admin view (`POST /api/admin/plan`). There is no payment step yet: "paid" is the owner's word.
121
+ Nothing a local Studio does needs an account.
122
+
123
+ **Driven from app.runtapp.com (ADR-0011 §2/§4, join B).** `tapp app --connect` starts the runtime
124
+ on this machine and opens the hosted page with `#connect=<loopback origin>&token=<launch secret>`
125
+ — a fragment, so the hosted server never sees it. The page keeps the pair in this browser only
126
+ (`localStorage`, `tapp.connect`), takes it off the address bar, and from then on every `/api/*`
127
+ call goes to that origin with `Authorization: Bearer <secret>`; images and reports carry
128
+ `?token=` because an `<img>` cannot send a header. The runtime, started with `connectOrigin`,
129
+ answers CORS for exactly that origin (`Access-Control-Allow-Origin`, the preflight with
130
+ `Access-Control-Allow-Private-Network: true` for Chrome's local-network check), accepts the
131
+ bearer or the query token as the operator, still requires the CSRF token on mutations, and tells
132
+ every other origin nothing. The hosted page's CSP allows `http://127.0.0.1:*` and
133
+ `http://localhost:*` for `connect-src`, `img-src` and `media-src`; a local Studio's does not. The
134
+ header shows *Connected · your machine* with Disconnect, which forgets the pair. A runtime that
135
+ stops answering is said on the first screen, the pair is dropped, and the page carries on as a
136
+ visitor. A browser that refuses loopback from an https page (some do) is sent to the runtime's
137
+ own address, the same UI. For a visitor the cloud card says *coming soon* and takes an address
138
+ (`POST /api/cloud/interest` → `TAPP_HOME/cloud-interest.jsonl`, an address and a date, nothing
139
+ else); an existing account signs in from that card.
140
+
141
+ **Setting this machine up (ADR-0012's journey).** On a local Studio the first screen carries a
142
+ setup card above the prompt — *This machine* — with four steps, from one answer
143
+ (`GET /api/setup`): the **runtime** (tapp and Node versions, python3 and PyYAML for Flow replay,
144
+ disk); **your agent** (every engine found, how it is signed in, Use to choose which drives the
145
+ chat; a *Sign in with ChatGPT* button that runs `codex login --device-auth` and shows the link and
146
+ one-time code until Codex reports a plan, `POST/DELETE /api/engines/codex/sign-in`; and a field for
147
+ an Anthropic API key as the fallback brain, checked against Anthropic's models endpoint, kept 0600
148
+ under `TAPP_HOME/agent/`, shown by its last four characters, handed to Claude Code only when no
149
+ plan is signed in, `POST/DELETE /api/engines/api-key`); **what you'll test** (per target, what
150
+ `tapp doctor --json` found and the exact fix — "Install Xcode from the App Store and open it
151
+ once", "System Settings → Privacy & Security → Accessibility", "Install Android Studio…"); and
152
+ **your account** (the link, optional). It collapses to one line once an agent drives and more
153
+ than one target is ready, and *Check again* re-reads the machine (doctor's answer is reused for
154
+ 30 s). The Platforms view says the same thing per platform, and on the right kind of machine
155
+ missing one thing it names the thing — a Mac without Xcode is told to install Xcode, not to
156
+ find a Mac (`platforms.js`). Claude Code's own sign-in opens a browser from a terminal, so the
157
+ card says to run `claude` and sign in, then Check again.
158
+
159
+ **The chat drives the person's own agent (ADR-0012).** On a local Studio, *Your agent* lists the
160
+ coding agents found on this machine — Claude Code, Codex, Gemini CLI — and how each is signed in:
161
+ a plan, an API key that bills per use, or not at all, with the fix (`mcp-server/src/engines.js`;
162
+ `GET/POST /api/engines`). tapp signs nobody in and holds no token. With Claude Code signed in, the
163
+ chat grows an input: a prompt is one `agent` operation on the operator's lane that runs
164
+ `claude -p … --output-format stream-json` with tapp's own MCP server attached and the tapp skill
165
+ appended, allowed `mcp__tapp,Read,Glob,Grep` and nothing that touches the machine; its events
166
+ arrive as chat lines (🤖 its words, 🛠️ the tool it reached for, ⚠️ a tool error, ✅ its answer) and
167
+ the thread continues with `--resume`. Stop (`agent-stop`) sends `SIGINT`. Codex and Gemini are
168
+ reported but do not drive the chat yet. A hosted Studio answers 401 to all of it.
169
+
170
+ **A self-hosted Studio can report to an account (ADR-0011 §4).** Results flow up; the browser
171
+ never reaches down. Under *Your tapp account* on a local Studio, the owner pastes a token created
172
+ on the hosted one (under *Your coding agent*); the local Studio checks it against that Studio,
173
+ records whose it is, and keeps it in `TAPP_HOME/studio-link.json` (0600, this user only). From
174
+ then on every journey run on this machine — including against staging and localhost — posts its
175
+ name, platform, step count, machine name and result to `POST /api/journeys/report`; the journey
176
+ itself, credentials and screenshots never leave. The account's Journeys list shows it with "runs
177
+ on <machine>", no Run button (the cloud has no flow for it), and Forget; a pass↔fail change between
178
+ reports delivers the same alert a cloud check's would; the daily checks never pick it up. A Studio
179
+ that cannot be reached is said in the chat and never fails the run. `tapp run` on this machine
180
+ reports the same way — so an iOS or Android journey run from a terminal shows on the account too —
181
+ using the machine's link, or `TAPP_STUDIO` + `TAPP_TOKEN` when set; `--no-report` keeps one run to
182
+ itself.
183
+
104
184
  **Signing in** is `POST /api/auth/link` with an email, then `GET /auth/<token>` from the email.
105
185
  There is no password. Links work once and expire in 15 minutes; sessions last 90 days; only the
106
186
  SHA-256 of either token is on disk (`account-store.js`). One address may ask for five links per
@@ -213,3 +293,16 @@ Rules that keep it worth reading:
213
293
  delivery. Anyone holding the URL can post into that channel.
214
294
  - **Public https only.** The post comes from the server, so a webhook on localhost or a private
215
295
  range is refused, the same rule the egress proxy enforces for exploration.
296
+
297
+ ## Restricted runners: an approved browser (TM-1023)
298
+
299
+ Where the sandbox stops tapp starting Chromium itself (macOS: `bootstrap_check_in …
300
+ MachPortRendezvousServer: Permission denied (1100)`, SIGTRAP), use a browser started outside the
301
+ restriction:
302
+
303
+ - `TAPP_BROWSER_ENDPOINT=http://127.0.0.1:<port>` — tapp attaches to a Chromium already running with
304
+ `--remote-debugging-port=<port>`. Loopback only; refused under `TAPP_ENFORCE_PUBLIC_EGRESS=1`,
305
+ because tapp cannot enforce its proxy on a browser it did not start.
306
+ - `TAPP_BROWSER_EXECUTABLE=/path/to/chrome` — tapp starts that approved binary instead of its own.
307
+
308
+ Both apply to `tapp run`, `tapp look`, explore and audits.
@@ -10,7 +10,7 @@
10
10
  //
11
11
  // Layout: TAPP_HOME/accounts/
12
12
  // by-email/<sha256(email)> → account id
13
- // accounts/<id>.json { id, email, createdAt, lastSeenAt }
13
+ // accounts/<id>.json { id, email, createdAt, lastSeenAt, plan }
14
14
  // links/<sha256(token)>.json { email, expiresAt } (removed on use)
15
15
  // sessions/<sha256(token)>.json { accountId, createdAt, expiresAt }
16
16
  // tokens/<sha256(token)>.json { id, accountId, label, createdAt, lastUsedAt }
@@ -25,6 +25,10 @@ import path from "node:path";
25
25
  export const TOKEN_PREFIX = "tapp_";
26
26
  export const LINK_TTL_MS = 15 * 60 * 1000;
27
27
  export const SESSION_TTL_MS = 90 * 24 * 60 * 60 * 1000;
28
+ // The cloud beyond the visitor audit is for an account on a plan or in its free trial
29
+ // (ADR-0011 §3). A trial is a date, nothing more: no card, no counter of runs.
30
+ export const TRIAL_DAYS = 14;
31
+ export const TRIAL_MS = TRIAL_DAYS * 24 * 60 * 60 * 1000;
28
32
  // One address may ask for this many links in a ten-minute window; more is someone else's mailbox
29
33
  // being flooded through us.
30
34
  const LINKS_PER_WINDOW = 5;
@@ -171,6 +175,46 @@ export class AccountStore {
171
175
  return false;
172
176
  }
173
177
 
178
+ /** The account record by id, or null. */
179
+ getAccount(accountId) {
180
+ if (!/^[a-f0-9]{24}$/.test(String(accountId || ""))) return null;
181
+ return readJson(this.#file("accounts", accountId));
182
+ }
183
+
184
+ /**
185
+ * Whether this account may start a cloud run, and why. `paid` has no end; `trial` has one and
186
+ * is allowed until it; `lapsed` is a trial whose date has passed. An account from before plans
187
+ * existed has none on record — it is given a trial from the day it is next seen, not from the
188
+ * day it joined, so a change in the rules never locks out someone who was already here.
189
+ */
190
+ entitlement(accountOrId) {
191
+ const account = typeof accountOrId === "string" ? this.getAccount(accountOrId) : accountOrId;
192
+ if (!account) return { kind: "lapsed", allowed: false, endsAt: null, daysLeft: 0 };
193
+ if (!account.plan || typeof account.plan !== "object") {
194
+ account.plan = { kind: "trial", endsAt: new Date(this.now() + TRIAL_MS).toISOString() };
195
+ writeJson(this.#file("accounts", account.id), account);
196
+ }
197
+ if (account.plan.kind === "paid") return { kind: "paid", allowed: true, endsAt: null, daysLeft: null };
198
+ const endsAt = Date.parse(account.plan.endsAt);
199
+ const left = Number.isFinite(endsAt) ? endsAt - this.now() : -1;
200
+ if (left <= 0) return { kind: "lapsed", allowed: false, endsAt: account.plan.endsAt || null, daysLeft: 0 };
201
+ return { kind: "trial", allowed: true, endsAt: account.plan.endsAt, daysLeft: Math.ceil(left / 86_400_000) };
202
+ }
203
+
204
+ /** The owner of the deployment decides: mark an account paid, or give it a trial of so many days from now. */
205
+ setPlan(accountId, { kind, days } = {}) {
206
+ const account = this.getAccount(accountId);
207
+ if (!account) throw Object.assign(new Error("No such account"), { statusCode: 404 });
208
+ if (kind === "paid") account.plan = { kind: "paid" };
209
+ else if (kind === "trial") {
210
+ const length = Number(days);
211
+ if (!Number.isInteger(length) || length < 1 || length > 365) throw Object.assign(new Error("A trial is 1 to 365 days"), { statusCode: 400 });
212
+ account.plan = { kind: "trial", endsAt: new Date(this.now() + length * 86_400_000).toISOString() };
213
+ } else throw Object.assign(new Error("A plan is 'paid' or 'trial'"), { statusCode: 400 });
214
+ writeJson(this.#file("accounts", account.id), account);
215
+ return this.entitlement(account);
216
+ }
217
+
174
218
  /** Where this account's encrypted test accounts live. */
175
219
  actorRoot(accountId) {
176
220
  if (!/^[a-f0-9]{24}$/.test(String(accountId || ""))) throw new Error("Not an account id");
@@ -186,7 +230,7 @@ export class AccountStore {
186
230
  if (existing) return existing;
187
231
  }
188
232
  id = crypto.randomBytes(12).toString("hex");
189
- const account = { id, email, createdAt: new Date(this.now()).toISOString(), lastSeenAt: new Date(this.now()).toISOString() };
233
+ const account = { id, email, createdAt: new Date(this.now()).toISOString(), lastSeenAt: new Date(this.now()).toISOString(), plan: { kind: "trial", endsAt: new Date(this.now() + TRIAL_MS).toISOString() } };
190
234
  writeJson(this.#file("accounts", id), account);
191
235
  fs.mkdirSync(path.dirname(indexFile), { recursive: true, mode: 0o700 });
192
236
  fs.writeFileSync(indexFile, `${id}\n`, { mode: 0o600 });
@@ -107,6 +107,11 @@ export async function runAndroidFlow({ flow, appId, apkPath, serial, logPath, sc
107
107
  await d.swipe(target || "up");
108
108
  } else if (action === "back") {
109
109
  await d.back();
110
+ } else if (action === "open_url") {
111
+ // A journey starting from an email link ("tap the sign-in link in your receipt") opens it
112
+ // the way Android itself would hand it to the app — a VIEW intent, not a shell workaround.
113
+ const r = await d.adb(["shell", "am", "start", "-a", "android.intent.action.VIEW", "-d", target]);
114
+ if (r.code !== 0 || /Error:/i.test(r.stdout || "")) throw new Error(`could not open ‘${target}’: ${(r.stdout || r.stderr || "").trim() || "no app handled this link"}`);
110
115
  } else if (action === "wait_for") {
111
116
  const waited = await d.waitFor(target, timeout);
112
117
  if (!waited) throw new Error(`‘${target}’ never appeared within ${timeout}ms`);
@@ -0,0 +1,42 @@
1
+ // Search Apple's public US software catalog. A listing identifies a possible app.
2
+ // The visitor chooses a publisher's website before the existing audit starts.
3
+ const cache = new Map();
4
+ let searches = [];
5
+
6
+ function website(value) {
7
+ try {
8
+ const url = new URL(value);
9
+ if (["https:", "http:"].includes(url.protocol) && !url.username && !url.password) return url.href;
10
+ } catch { /* Some publishers omit their website. */ }
11
+ return "";
12
+ }
13
+
14
+ export async function discoverApps(input) {
15
+ const term = String(input).normalize("NFKC").trim();
16
+ if (!term || term.length > 80) return { matches: [], message: "Enter a shorter business name, or enter its website." };
17
+ const key = term.toLowerCase();
18
+ const now = Date.now();
19
+ const cached = cache.get(key);
20
+ if (cached?.until > now) return cached.result;
21
+ searches = searches.filter(time => now - time < 60_000);
22
+ if (searches.length >= 18) return { matches: [], message: "App Store search is busy. Enter the website or try again in a minute." };
23
+ searches.push(now);
24
+ try {
25
+ const url = new URL("https://itunes.apple.com/search");
26
+ url.search = new URLSearchParams({ country: "us", entity: "software", limit: "12", term });
27
+ const response = await fetch(url, { redirect: "error", signal: AbortSignal.timeout(6000) });
28
+ if (!response.ok) throw new Error("Catalog unavailable");
29
+ const { results } = await response.json();
30
+ const matches = results.filter(app => Number.isSafeInteger(app.trackId) && app.trackName &&
31
+ (app.trackName + " " + (app.sellerName || "")).toLowerCase().includes(key)).slice(0, 5).map(app => ({
32
+ name: String(app.trackName), publisher: String(app.sellerName || ""),
33
+ listing: "https://apps.apple.com/us/app/id" + app.trackId, website: website(app.sellerUrl),
34
+ }));
35
+ const result = { matches, message: matches.length ? "Which business did you mean?" : "No matching US App Store listing. Enter the business’s website to continue." };
36
+ if (cache.size >= 200) cache.delete(cache.keys().next().value);
37
+ cache.set(key, { until: now + 600_000, result });
38
+ return result;
39
+ } catch {
40
+ return { matches: [], message: "The App Store search is unavailable. You can still enter the business’s website." };
41
+ }
42
+ }