diff --git a/README.md b/README.md index 16ec712..ddc5c3f 100644 --- a/README.md +++ b/README.md @@ -178,6 +178,7 @@ Each creates a phone, checks one outcome and deletes the phone, also when the ch | [typescript/mobilebox.ts](examples/typescript/mobilebox.ts) | minimal client + Settings check | Node 24 | | [claude-code/](examples/claude-code) | Claude Code tests the APK you just built | an arm64 or universal APK | | [github-actions/](examples/github-actions) | APK smoke test in a workflow | a repo secret with your key | +| [app-builder-preview/](examples/app-builder-preview) | your product shows each user their app on a live phone: a phone per end user, Expo or APK, embed, signed webhooks, usage per user | Node 20+, a public URL (a tunnel) | | [proof-demo-calculator](https://github.com/mobilebox-dev/proof-demo-calculator/pulls?q=is%3Apr) | a real app (a Fossify Calculator fork) where every PR gets a proof comment: last screen, steps, time, cost | nothing: open its pull requests | | [packages/python/](packages/python) | `mobilebox` Python client and `langchain-mobilebox` LangChain tools | Python 3.10+ | | [integrations/](examples/integrations) | OpenAI Agents SDK, LangGraph, CrewAI, browser-use, Mastra, Vercel AI SDK, Claude Agent SDK, OpenHands, Haystack | the framework and a model key | diff --git a/examples/RUNS.md b/examples/RUNS.md index f141c85..8ed775b 100644 --- a/examples/RUNS.md +++ b/examples/RUNS.md @@ -93,3 +93,16 @@ deleted: ph_on7c4dcbzlnk 17 s from the first step to the report, 15 s of phone time; the phone was deleted. The API key was absent from every log and file afterwards (OpenHands masks secrets and the example keeps the shell history off disk). +## App-builder preview + +**2026-11-25**, Node 24 on Linux, `examples/app-builder-preview` against production through a Cloudflare quick tunnel, driven in Chrome. Details and the recording: [app-builder-preview/README.md](app-builder-preview/README.md#recorded-run). + +| Step | Result | Time | +|---|---|---| +| Preview `user_42`, F-Droid Editor 1.98 APK, new phone | installed, live in the page at 30 Hz | 29 s | +| Preview `user_42` again, parked phone | started, `phone.ready` webhook, live | 15 s | +| Preview `user_7`, Expo SDK 58 tunnel link, new phone | Expo Go 58.0.6 installed itself, app live, Fast Refresh in the embed | 30 s | +| Park | `phone.parked` webhooks (signature checked), usage per end user updated | 2 s | + +Afterwards both phones were deleted, the webhook removed and the page's origin taken off the list. + diff --git a/examples/app-builder-preview/README.md b/examples/app-builder-preview/README.md new file mode 100644 index 0000000..6b29ef6 --- /dev/null +++ b/examples/app-builder-preview/README.md @@ -0,0 +1,81 @@ +# App-builder preview + +Show each of your users their app on a cloud Android phone, live in your own page. The whole integration is two files and no dependencies: `server.mjs` (about 150 lines) and `index.html`. + +![The example running against production: an APK and an Expo app previewed for two end users, webhooks arriving, usage per end user](demo.gif) + +What it does: + +1. **Keeps your API key on the server.** The browser only ever gets a short-lived embed URL. +2. **One phone per end user.** It creates the phone with `end_user` (your id for the person) and `display_hz: 30` for smooth scrolling, reuses it next time and starts it again if it's parked. +3. **Loads the app.** An APK URL installs and opens. An Expo link (`exp://`, `exps://`, `https://expo.dev/…`) opens in Expo Go, and Mobilebox installs the Expo Go that matches the project's SDK. +4. **Embeds the live phone** through `/embed`, locked to your page's origin. Your user can tap, swipe and type on it. +5. **Receives signed webhooks** (`phone.ready`, `phone.parked`, `phone.deleted`, `phone.failed`), checks the signature and shows each phone's state. +6. **Shows usage per end user**, the minutes and cost you can bill them for. + +## Run it in 10 minutes + +You need Node 20 or newer, a Mobilebox API key ([sign up](https://mobilebox.dev/signup)), and a public URL for this server so Mobilebox can send it webhooks. A Cloudflare quick tunnel works without an account: + +```bash +git clone https://github.com/mobilebox-dev/mobilebox && cd mobilebox/examples/app-builder-preview +cloudflared tunnel --url http://localhost:3000 # prints https://….trycloudflare.com; leave it running +``` + +In a second terminal: + +```bash +export MOBILESANDBOX_API_KEY=… # from https://mobilebox.dev/dashboard +export PUBLIC_URL=https://….trycloudflare.com # the URL the tunnel printed +node server.mjs +``` + +Open `PUBLIC_URL` in your browser. Pick an end user id, paste an APK URL (or press **an F-Droid APK**), and press **Preview**. A fresh phone takes about 30 s to boot and install; a parked one comes back in about 15 s. + +For an Expo project, run `npx expo start --tunnel` and paste the `exp://` link it prints. + +On start the server: + +- adds your page's origin to the workspace's embed origins (`PUT /v1/embed/origins`, keeping the ones you have); +- points the workspace's webhook at `PUBLIC_URL/webhooks/mobilebox`. + +A workspace has one webhook URL, so if yours already points somewhere else the server leaves it alone and says so. Use a separate workspace for this example, or set `MOBILEBOX_TAKE_WEBHOOK=1`. + +## How it works + +| Step | Code | Mobilebox API | +|---|---|---| +| A phone per end user | `phoneFor()` | `GET /v1/phones?end_user=…`, `POST /v1/phones {end_user, display_hz: 30}`, `POST /v1/phones/{id}/start` | +| The app on it | `load()` | `POST /v1/phones/{id}/apps {url}` + `open_app`, or `open_url` for Expo | +| The live phone in your page | `/api/preview` | `POST /v1/phones/{id}/embed {origin, interactive: true, ttl: 900}` | +| Phone state | `verify()`, `onWebhook()` | `PUT /v1/webhooks {url}`; events signed `Mobilebox-Signature: t=…,v1=…` | +| Usage per end user | `/api/usage` | `GET /v1/account/usage?by=end_user` | +| Done | `/api/park` | `DELETE /v1/phones/{id}/embed`, `POST /v1/phones/{id}/park` | + +`node server.mjs --self-check` tests the signature check without a key. + +## Before you ship it + +- **Store state in your database.** This example keeps webhook events in memory. Keep the phone id and its last state per end user, and drop repeats by the event `id` (a retry sends the same one). +- **Answer webhooks fast.** Return 2xx within 10 s and do the work after. We retry after 10 s, 1 min, 10 min and 1 h. +- **Keep embed links short-lived.** Make a new link when one ends (the iframe tells your page with `mobilebox:end`). Revoke the link when your user leaves. +- **Park idle phones.** A parked phone keeps its apps and data and costs nothing. Phones also park by themselves after their idle timeout. +- **Plan for more users.** A workspace runs 3 phones at once to start. `POST /v1/account/limits {"running": n}` asks for more, and we answer within a day. + +The page polls `/api/events` every 2 s instead of holding a server-sent event stream, because tunnels and proxies, Cloudflare's quick tunnels among them, often hold such a stream back. + +Reference: [embed](https://mobilebox.dev/docs/embed), [Expo](https://mobilebox.dev/docs/expo), [labels, usage, webhooks and limits](https://mobilebox.dev/docs/reference#one-phone-per-end-user-labels-usage-webhooks-limits). + +## Recorded run + +**2026-11-25**, Node 24 on Linux, against production through a Cloudflare quick tunnel, Chrome: + +| Step | Result | Time | +|---|---|---| +| Preview, `user_42`, F-Droid Editor 1.98 APK, new phone | installed, live in the page at 30 Hz, a click in the page reached the phone | 29 s | +| Park phone | `phone.parked` (manual) arrived signed; usage: user_42 2.2 min, $0.02 | 2 s | +| Preview again, `user_42` | parked phone started, `phone.ready`, app reinstalled, live | 15 s | +| Preview, `user_7`, Expo SDK 58 project (`exps://…exp.direct`), new phone | Expo Go 58.0.6 installed itself, app live; an edit showed by Fast Refresh in the embed | 30 s | +| Park phone, `user_7` | `phone.parked` arrived, the embed showed "This preview was closed", usage: user_7 1 min, $0.01 | 2 s | + +An unsigned POST to the webhook URL got 401. Expo Go shows its developer menu once on a new phone; your user closes it in the embed. diff --git a/examples/app-builder-preview/demo.gif b/examples/app-builder-preview/demo.gif new file mode 100644 index 0000000..1ec46fc Binary files /dev/null and b/examples/app-builder-preview/demo.gif differ diff --git a/examples/app-builder-preview/index.html b/examples/app-builder-preview/index.html new file mode 100644 index 0000000..5ff5bdf --- /dev/null +++ b/examples/app-builder-preview/index.html @@ -0,0 +1,135 @@ + + + + + +App preview · Mobilebox example + + + +
+

Preview your user's app on a cloud phone

+

A cloud Android phone per end user, live in this page. The API key never leaves the server.

+ +
+ + +
Your id for the person this preview is for. Their phone is reused, and their minutes add up under it. Park it when they're done.
+ + + +
An APK download URL, or the link npx expo start --tunnel prints. Try + .
+ +
+ + +
+
+
+ +

Phone state

+
  1. No phone events yet.
+ +

Usage per end user, last 30 days

+
End userMinutesCost
Loading…
+
+ +
Your user's phone shows here.
+ + + + diff --git a/examples/app-builder-preview/server.mjs b/examples/app-builder-preview/server.mjs new file mode 100644 index 0000000..ee19300 --- /dev/null +++ b/examples/app-builder-preview/server.mjs @@ -0,0 +1,145 @@ +// App-builder preview: one cloud phone per end user, embedded live in your own page. +// Zero dependencies, Node 20+. Your API key stays here on the server; the browser only ever gets a short-lived embed URL. +// +// MOBILESANDBOX_API_KEY=… PUBLIC_URL=https://your-tunnel.example node server.mjs +// +// PUBLIC_URL is where Mobilebox can reach this server for webhooks, and the page origin the embed is locked to. +import { createServer } from 'node:http' +import { readFileSync } from 'node:fs' +import { createHmac, timingSafeEqual } from 'node:crypto' +import assert from 'node:assert/strict' + +const API = process.env.MOBILEBOX_API ?? 'https://mobilebox.dev/v1' +const KEY = process.env.MOBILESANDBOX_API_KEY +const PORT = Number(process.env.PORT ?? 3000) +const PUBLIC_URL = (process.env.PUBLIC_URL ?? `http://localhost:${PORT}`).replace(/\/$/, '') +const ORIGIN = new URL(PUBLIC_URL).origin +const HOOK_URL = `${PUBLIC_URL}/webhooks/mobilebox` + +// --- Mobilebox REST, server-side only ----------------------------------------------------------------------------- +async function mb(method, path, body) { + const res = await fetch(API + path, { + method, headers: { authorization: `Bearer ${KEY}`, ...(body && { 'content-type': 'application/json' }) }, + ...(body && { body: JSON.stringify(body) }), + }) + const data = res.status === 204 ? null : await res.json() + if (!res.ok) throw Object.assign(new Error(data?.error?.message ?? `${res.status}`), { status: res.status, mb: data?.error }) + return data +} +// Waits cap at 55 s per call; a phone still booting is normal, so ask again. +async function ready(phone) { + while (phone.status === 'creating' || phone.status === 'starting') phone = await mb('GET', `/phones/${phone.id}?wait=ready`) + if (phone.status !== 'ready') throw new Error(`phone ${phone.id} is ${phone.status}`) + return phone +} + +// One phone per end user: reuse it (start it if parked), or make it with the end_user label and a 30 Hz display. +async function phoneFor(endUser) { + const [mine] = (await mb('GET', `/phones?end_user=${encodeURIComponent(endUser)}`)).data + if (mine?.status === 'parked') return ready(await mb('POST', `/phones/${mine.id}/start?wait=ready`)) + if (mine) return ready(mine) + return ready(await mb('POST', '/phones?wait=ready', { end_user: endUser, display_hz: 30, name: `preview-${endUser}`.slice(0, 64) })) +} + +// The builder's app on the phone: an Expo link opens in Expo Go (Mobilebox installs the matching one), an APK URL installs. +async function load(phone, source) { + if (/^exps?:\/\/|^https:\/\/(\w+\.)?expo\.dev\//.test(source)) { + const { results } = await mb('POST', `/phones/${phone.id}/actions`, { actions: [{ type: 'open_url', url: source }] }) + if (!results[0].ok) throw new Error(results[0].error.message) + return results[0].note ?? 'Opened the Expo link.' + } + const app = await mb('POST', `/phones/${phone.id}/apps`, { url: source, replace: true }) + await mb('POST', `/phones/${phone.id}/actions`, { actions: [{ type: 'open_app', package: app.package }] }) + return `Installed ${app.package} ${app.version_name ?? ''}`.trim() + '.' +} + +// --- Webhooks: verify, keep the latest 200 events for the page to poll ----------------------------------------------- +// ponytail: in memory; a real app stores phone state per end user in its database. +let secret = null +const events = [] // { seq, type, end_user, phone, status, reason, at } +let seq = 0 + +// Mobilebox-Signature: t=,v1=.">; reject anything older than 5 minutes. +export function verify(secret, header, raw, now = Date.now()) { + const [, t, v1] = /^t=(\d+),v1=([0-9a-f]{64})$/.exec(header ?? '') ?? [] + if (!t || Math.abs(now / 1000 - Number(t)) > 300) return false + const want = createHmac('sha256', secret).update(`${t}.${raw}`).digest('hex') + return timingSafeEqual(Buffer.from(want), Buffer.from(v1)) +} + +function onWebhook(raw, signature) { + if (!secret || !verify(secret, signature, raw)) return 401 + const event = JSON.parse(raw) + if (events.some((e) => e.id === event.id)) return 204 // a retry of one we have: same Mobilebox-Delivery id + const phone = event.data?.phone + events.push({ seq: ++seq, id: event.id, type: event.type, end_user: phone?.end_user ?? null, phone: phone?.id ?? null, status: phone?.status ?? null, reason: event.data?.reason ?? null, at: event.created_at }) + if (events.length > 200) events.shift() + return 204 +} + +// --- One-time setup: allow this page to frame phones, and point the workspace's webhook here -------------------------- +async function setup() { + const { origins } = await mb('GET', '/embed/origins') + const want = [...new Set([...origins, ORIGIN, `http://localhost:${PORT}`])].slice(0, 20) + if (want.length !== origins.length) await mb('PUT', '/embed/origins', { origins: want }) + const hook = await mb('GET', '/webhooks') + // A workspace has one webhook URL. Don't take over one that points elsewhere unless asked. + if (hook.url && hook.url !== HOOK_URL && process.env.MOBILEBOX_TAKE_WEBHOOK !== '1') { + console.warn(`This workspace's webhook goes to ${hook.url}; phone states won't update here. Use a separate workspace, or MOBILEBOX_TAKE_WEBHOOK=1 to point it here.`) + return + } + secret = hook.url === HOOK_URL ? hook.secret : (await mb('PUT', '/webhooks', { url: HOOK_URL })).secret +} + +// --- HTTP ---------------------------------------------------------------------------------------------------------- +const page = readFileSync(new URL('./index.html', import.meta.url)) +const json = (res, status, body) => { res.writeHead(status, { 'content-type': 'application/json' }); res.end(JSON.stringify(body)) } +const read = (req) => new Promise((done, fail) => { let s = ''; req.on('data', (c) => { s += c; if (s.length > 1e5) req.destroy() }).on('end', () => done(s)).on('error', fail) }) +const END_USER = /^[\w.@:+-]{1,128}$/ + +const server = createServer(async (req, res) => { + const url = new URL(req.url, PUBLIC_URL) + try { + if (req.method === 'GET' && url.pathname === '/') { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); return res.end(page) } + if (req.method === 'POST' && url.pathname === '/webhooks/mobilebox') { res.writeHead(onWebhook(await read(req), req.headers['mobilebox-signature'])); return res.end() } + // Polled every 2 s by the page: an event stream would be simpler, but tunnels and proxies often hold it back. + if (req.method === 'GET' && url.pathname === '/api/events') return json(res, 200, { webhooks: Boolean(secret), events: events.filter((e) => e.seq > Number(url.searchParams.get('since') ?? 0)) }) + if (req.method === 'POST' && url.pathname === '/api/preview') { + const { endUser, source } = JSON.parse(await read(req)) + if (!END_USER.test(endUser ?? '') || !/^(https?|exps?):\/\/\S+$/.test(source ?? '')) return json(res, 400, { error: 'An end user id (letters, digits, . _ - @ : +) and an APK or Expo URL.' }) + // The page that will hold the iframe: this server's own origin (locked by Mobilebox with frame-ancestors). + const origin = req.headers.origin === `http://localhost:${PORT}` ? req.headers.origin : ORIGIN + const phone = await phoneFor(endUser) + const loaded = await load(phone, source) + const embed = await mb('POST', `/phones/${phone.id}/embed`, { origin, interactive: true, ttl: 900 }) + return json(res, 200, { phone: phone.id, display_hz: phone.display_hz, notice: phone.notice ?? null, loaded, url: embed.url, expires_at: embed.expires_at }) + } + if (req.method === 'POST' && url.pathname === '/api/park') { + const { endUser } = JSON.parse(await read(req)) + const [mine] = END_USER.test(endUser ?? '') ? (await mb('GET', `/phones?end_user=${encodeURIComponent(endUser)}`)).data : [] + if (!mine) return json(res, 404, { error: 'No phone for that end user.' }) + await mb('DELETE', `/phones/${mine.id}/embed`) // the open iframe ends now + return json(res, 200, { phone: (await mb('POST', `/phones/${mine.id}/park`)).id }) + } + if (req.method === 'GET' && url.pathname === '/api/usage') return json(res, 200, (await mb('GET', '/account/usage?by=end_user')).end_users) + json(res, 404, { error: 'not found' }) + } catch (e) { + console.error(req.url, e.message) + json(res, e.status && e.status < 500 ? e.status : 502, { error: e.message, ...(e.mb?.next && { next: e.mb.next }) }) + } +}) + +if (process.argv.includes('--self-check')) { + const raw = '{"type":"phone.ready"}', t = Math.floor(Date.now() / 1000), sig = createHmac('sha256', 'whsec_x').update(`${t}.${raw}`).digest('hex') + assert.ok(verify('whsec_x', `t=${t},v1=${sig}`, raw), 'a signed body verifies') + assert.ok(!verify('whsec_x', `t=${t},v1=${sig}`, raw + ' '), 'a changed body fails') + assert.ok(!verify('whsec_x', `t=${t - 600},v1=${sig}`, raw), 'an old one fails') + assert.ok(!verify('whsec_y', `t=${t},v1=${sig}`, raw), 'another secret fails') + console.log('self-check ok') +} else if (!KEY) { + console.error('Set MOBILESANDBOX_API_KEY (https://mobilebox.dev/signup).') + process.exit(1) +} else { + await setup() + server.listen(PORT, () => console.log(`Preview on http://localhost:${PORT} (embeds locked to ${ORIGIN}; webhooks ${secret ? `to ${HOOK_URL}` : 'off'})`)) +} diff --git a/package.json b/package.json index 68b9793..3b7b5fe 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ "node": ">=24" }, "scripts": { - "lint": "tsc -p . && node --check examples/github-actions/smoke.mjs && node --check scripts/check-mcp.mjs && python3 -m py_compile examples/python/mobilebox.py examples/integrations/*/agent.py && node --check examples/integrations/mastra/agent.ts && node --check examples/integrations/vercel-ai-sdk/agent.ts && node --check examples/integrations/claude-agent-sdk/agent.ts && for f in benchmarks/*.mjs; do node --check \"$f\" || exit 1; done && node benchmarks/summarize.mjs > /dev/null", + "lint": "tsc -p . && node --check examples/github-actions/smoke.mjs && node examples/app-builder-preview/server.mjs --self-check && node --check scripts/check-mcp.mjs && python3 -m py_compile examples/python/mobilebox.py examples/integrations/*/agent.py && node --check examples/integrations/mastra/agent.ts && node --check examples/integrations/vercel-ai-sdk/agent.ts && node --check examples/integrations/claude-agent-sdk/agent.ts && for f in benchmarks/*.mjs; do node --check \"$f\" || exit 1; done && node benchmarks/summarize.mjs > /dev/null", "check:mcp": "node scripts/check-mcp.mjs" }, "devDependencies": {