diff --git a/.env.example b/.env.example
index 019c098..61633fa 100644
--- a/.env.example
+++ b/.env.example
@@ -1,7 +1,10 @@
# Example dev harness config. Copy to .env and fill in.
# Bun auto-loads .env β these are read ONLY by example/server.ts (server-side).
# The secret key never reaches the browser; the SDK helper uses it server-side.
-# Stream WebSockets are direct browser connections authenticated with ?token=.
+# The server mints through POST /v1/identity/stream-keys for every socket attempt.
+# The browser receives only { key, keyId, expiresAt } with Cache-Control: no-store;
+# stream WebSockets connect directly with the single-use key in ?token=.
+# Local-only helpers are unauthenticated: add caller/device authorization for production.
# Required: your mobilerun secret API key (dr_sk_β¦).
MOBILERUN_API_KEY=dr_sk_your_key_here
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..d4ba83c
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,46 @@
+# Contributing
+
+## Build and test
+
+For source builds: Bun 1.4.4 and TypeScript 6.0.3 (the CI toolchain).
+
+```sh
+bun install
+bun run build # tsup (JS + d.ts) + Tailwind (styles.css) β dist/
+bun run typecheck
+bun test
+```
+
+## Conformance
+
+The control messages, signalling frames, reconnect policy and input routing are replayed against the shared [conformance fixtures](https://github.com/droidrun/mobilerun-sdk-conformance) that the native SDKs also pass. The vendored copy lives in `conformance/fixtures` (release tag in `conformance/VERSION`) and runs with `bun test`. To move to another release, run `scripts/sync-conformance.sh TAG`.
+
+## Example app
+
+The repo ships the playground shown in the [README](README.md). Set the API key server-side and enter a device id;
+manual URL/token mode remains available for diagnostics with the legacy `streamToken` prop (device token):
+
+```sh
+bun install
+bun run example # serves the playground at http://localhost:3000
+```
+
+In SDK mode the example server returns only `id`, `state`, and `streamUrl` from
+`GET /api/v1/devices/:id`. Its `POST /api/v1/devices/:id/stream-key` helper calls the public mint
+API through `sdk.api.post('/identity/stream-keys', ...)`, returning only `{ key, keyId, expiresAt }`
+with `Cache-Control: no-store`. The browser's provider calls it for each connection attempt; the
+API key stays server-side. The stream WebSocket connects directly with the fresh stream token in `?token=`.
+The route names and `key` / `keyId` DTO fields remain transitional wire names until the identity API
+cutover; the credential is a stream token. See [Stream tokens](docs/stream-tokens.md).
+The same server also demonstrates [task approvals](docs/task-approvals.md) (set `MOBILERUN_WEBHOOK_SECRET`
+for the webhook route). All example helpers are unauthenticated and **local-only**, bound to
+`127.0.0.1`. Before adapting them for production, add application authentication and device
+authorization. If you need webhook delivery, expose only `/webhooks/mobilerun`, never the whole server.
+The helper routes only answer loopback Host headers and same-origin requests.
+
+## Pull requests
+
+Use commit messages in the form `type(scope): message` and open pull requests against `main`.
+Run the build, type check and tests before submitting.
+
+For security reports, follow [SECURITY.md](SECURITY.md).
diff --git a/README.md b/README.md
index 561d812..beb3a65 100644
--- a/README.md
+++ b/README.md
@@ -1,8 +1,8 @@
+**React** Β· [Android](https://github.com/droidrun/mobilerun-android) Β· [iOS](https://github.com/droidrun/mobilerun-swift) Β· [Flutter](https://github.com/droidrun/mobilerun-flutter)
-## β¨ What you get
-
-Drop a live, controllable cloud device (iOS/ Android) into any React app:
-
-- πΊ **``** β WebRTC video with touch, swipe and keyboard control, plus automatic reconnects with exponential backoff and a retry UI once attempts are exhausted.
-- πͺ **`useDeviceStream()`** β resolves a device's stream credentials from [`@mobilerun/sdk`](https://www.npmjs.com/package/@mobilerun/sdk), polling while it boots.
-- β **``** + **`useTaskApproval()`** β show a task's pending human approval (e.g. "enter payment card X into app Y") with a countdown and Approve/Deny buttons. See [Task approvals](#-task-approvals).
-- π§ **``**, **``**, **``** β the surrounding chrome and a lower-level escape hatch.
-- π¨ **Prebuilt stylesheet** β no Tailwind setup required, themeable via CSS variables.
-- π¦ **Typed** β ships its own `.d.ts`; React and the SDK are peer dependencies.
+
-## π¦ Install
+> **Building Mobilerun phones into your platform?** Start with the [Partner guide](https://docs.mobilerun.ai/partners). It walks through the API key, one phone per user, stream tokens and live viewing step by step.
+
+
+
+
+
+
+
+In this package
+
+
DeviceStream β video, touch, keyboard control and automatic reconnects.
+
useDeviceStream β stream URL and device state, with boot polling.
+
TaskApproval / useTaskApproval β approval cards and decisions.
+
NavigationBar / StreamStatusPill β stream controls and status.
+
RemoteControl β lower-level stream and input control.
+
Prebuilt stylesheet β themeable with CSS variables.
React and React DOM 18 or 19, in a browser with WebRTC.
+
@mobilerun/sdk >=2.0.0; object helpers need 6.2+, webhook example 6.2.1+, stream-token examples 6.3.0+.
+
A Mobilerun API key on your server.
+
+
+
+
+
+## Install
```sh
npm install @mobilerun/react @mobilerun/sdk react react-dom
@@ -50,291 +62,126 @@ npm install @mobilerun/react @mobilerun/sdk react react-dom
`react`, `react-dom` and `@mobilerun/sdk` are peer dependencies.
-## π Quick start
-
-The object API helpers (`MobilerunSDK`, `devices.fromId`, `verifyWebhook`) require `@mobilerun/sdk` 6.2 or later. The `{ client, deviceId }` hook form works with older SDKs; the peer dependency range remains `>=2.0.0`.
+## Quick start
-Keep the API key on your backend. The browser's SDK calls your backend for the device's stream credentials, and `useDeviceStream` refreshes them when the stream reconnects.
+1. Your server mints a short-lived stream token for one device with your API key
+ using `client.streamTokens.create` from `@mobilerun/sdk` 6.3.0+. Follow the [Partner guide](https://docs.mobilerun.ai/partners).
+2. Your app's `tokenProvider` asks your server for a stream token before each connection.
+3. The SDK opens the stream with that token, one token per connection, and reconnects with a fresh one.
-> β οΈ **`MOBILERUN_API_KEY` is a secret API key β never ship it to the browser.** Only the server reads it. The device endpoint returns only `id`, `state`, `streamUrl`, and `streamToken` to the browser, with missing values set to `null`. The stream token is short-lived and scoped to that device; the browser SDK uses a placeholder key to call your backend.
-
-On your backend, register this handler for `GET /api/v1/devices/:id`, passing the routed device ID:
+Use this Node backend helper with `@mobilerun/sdk` 6.3.0 or later. It reads
+`MOBILERUN_API_KEY` on the server;
+see [Stream tokens](https://github.com/droidrun/mobilerun-react/blob/main/docs/stream-tokens.md) for route setup, metadata fetching and error handling.
```ts
import { MobilerunSDK } from '@mobilerun/sdk';
-
-const sdk = new MobilerunSDK(); // reads MOBILERUN_API_KEY, server only
-
-export async function getDevice(id: string): Promise {
- // Authenticate the caller and check the device belongs to them before returning stream credentials.
- const device = await sdk.devices.get(id);
- return Response.json({
- id: device.info?.id ?? null,
- state: device.info?.state ?? null,
- streamUrl: device.info?.streamUrl ?? null,
- streamToken: device.info?.streamToken ?? null,
- });
+const client = new MobilerunSDK({ logLevel: 'off' }); // reads MOBILERUN_API_KEY on the Node server
+export async function mintStreamToken(deviceId: string): Promise {
+ // Authenticate your user and check they own the device before minting.
+ const { key, keyId, expiresAt } = await client.streamTokens.create({
+ deviceId,
+ ttlSeconds: 120,
+ allowedOrigins: ['https://partner.example'], // replace with your browser app's origin
+ }, { maxRetries: 0 });
+ return Response.json({ key, keyId, expiresAt }, { status: 201, headers: { 'Cache-Control': 'no-store' } });
}
```
-In your client component, point the SDK at that backend route, as in the example app:
-
-```tsx
-'use client';
-
-import { useMemo } from 'react';
-import { MobilerunSDK } from '@mobilerun/sdk';
-import { DeviceStream, useDeviceStream } from '@mobilerun/react';
-import '@mobilerun/react/styles.css';
-
-export function DevicePanel({ deviceId }: { deviceId: string }) {
- const sdk = useMemo(() => new MobilerunSDK({
- apiKey: 'example-sdk-helper', // placeholder, not a Mobilerun API key
- baseURL: typeof window === 'undefined' ? '/api/v1' : `${window.location.origin}/api/v1`, // SSR placeholder; the hook only fetches in the browser
- }), []);
- const { streamUrl, streamToken, state, refetch } = useDeviceStream({
- device: sdk.devices.fromId(deviceId), // no request yet
- });
-
- return (
-
-
-
- );
-}
-```
-
-### Without the hook
-
-Already have the device? Feed its fields straight in β no hook required:
-
-```tsx
-const device = await sdk.devices.get(deviceId);
-
-;
-```
-
-`useDeviceStream` also still accepts `{ client, deviceId }` with a plain `Mobilerun` client, so existing code keeps working.
-
-## β Task approvals
-
-A task can pause and wait for a human to approve a step, for example entering a payment card into an app. `useTaskApproval()` loads the pending approval and `` renders it with a countdown and Approve/Deny buttons.
-
-**The decision goes through your backend.** The API key that may approve is a secret and must never reach the browser, so the browser only talks to your own routes. The Mobilerun API owns the approval state and decides: the component renders what it is given and forwards the decision, and the countdown is display only. A 404/409 from the decide call (unknown, already resolved or expired) comes back as an error and triggers a refetch.
-
-### 1. Subscribe a webhook
-
-In your Mobilerun webhook settings, point an endpoint at your backend and filter it to the two approval events: `task.run.approval_requested` and `task.run.approval_resolved`. Events only tell the browser to reload; the fetched approval is the source of truth.
-
-Each delivery carries `X-Mobilerun-Timestamp` (Unix ms) and `X-Mobilerun-Signature: sha256=`, an HMAC-SHA256 of `"{timestamp}.{rawBody}"` with the endpoint secret. `verifyWebhook` from `@mobilerun/sdk` checks the signature and the 5-minute timestamp window and returns the parsed payload; pass it the body bytes exactly as received. SDK 6.2.1 or later distinguishes `invalid_json` (a signed but unparsable body), which the handler answers with HTTP 400.
-
-### 2. Backend sketch
-
-```ts
-import { MobilerunSDK, verifyWebhook, WebhookVerificationError } from '@mobilerun/sdk';
-
-const sdk = new MobilerunSDK(); // reads MOBILERUN_API_KEY
-const APPROVAL_EVENTS = new Set(['task.run.approval_requested', 'task.run.approval_resolved']);
-const ID = /^[A-Za-z0-9_-]+$/;
-
-// Device credentials: return only the fields needed for streaming.
-app.get('/api/v1/devices/:id', async (c) => {
- const id = c.req.param('id');
- // Authenticate the caller and check the device belongs to them before returning stream credentials.
- const device = await sdk.devices.get(id);
- return c.json({
- id: device.info?.id ?? null,
- state: device.info?.state ?? null,
- streamUrl: device.info?.streamUrl ?? null,
- streamToken: device.info?.streamToken ?? null,
- });
-});
-
-// 1. Webhook: verify the raw bytes, then push a change signal to the user's browser (SSE, ...)
-app.post('/webhooks/mobilerun', async (c) => {
- const secret = process.env.MOBILERUN_WEBHOOK_SECRET;
- if (!secret) return c.json({ error: 'missing_webhook_secret' }, 500);
- const bytes = new Uint8Array(await c.req.arrayBuffer());
- let event;
- try {
- event = await verifyWebhook({
- body: bytes,
- headers: c.req.raw.headers,
- secret,
- }) as { type?: string; data?: { taskId?: string } } | null;
- } catch (err) {
- if (err instanceof WebhookVerificationError) {
- if (err.reason === 'invalid_json') return c.json({ error: 'invalid_json' }, 400);
- return c.json({ error: 'invalid_signature' }, 401);
- }
- throw err;
- }
- const taskId = event?.data?.taskId;
- if (taskId && APPROVAL_EVENTS.has(event?.type ?? '')) push({ taskId });
- return c.body(null, 204);
-});
-
-// 2. Pending approval: GET /tasks/{id} β task.pendingApproval (null when none)
-app.get('/api/tasks/:id', async (c) => {
- const id = c.req.param('id');
- if (!ID.test(id)) return c.json({ error: 'invalid_id' }, 400);
- // Authenticate the caller and check the task belongs to their user/org first.
- const { task } = await sdk.api.get<{ task?: { pendingApproval?: unknown } }>(`/tasks/${encodeURIComponent(id)}`);
- return c.json({ pendingApproval: task?.pendingApproval ?? null });
-});
-
-// 3. Decision: POST /tasks/{id}/approvals/{approvalId} { decision: 'approve' | 'deny' }
-app.post('/api/tasks/:id/approvals/:approvalId', async (c) => {
- const id = c.req.param('id');
- const approvalId = c.req.param('approvalId');
- if (!ID.test(id) || !ID.test(approvalId)) return c.json({ error: 'invalid_id' }, 400);
- const { decision } = await c.req.json();
- if (decision !== 'approve' && decision !== 'deny') return c.json({ error: 'invalid_decision' }, 422);
- // Authenticate the caller and check the task belongs to their user/org first.
- const url = `/tasks/${encodeURIComponent(id)}/approvals/${encodeURIComponent(approvalId)}`;
- await sdk.api.post(url, { body: { decision } });
- return c.body(null, 204);
-});
-```
-
-Authenticate every route and check that the task belongs to the signed-in user or organization before forwarding. A delivery can be replayed within the 5-minute window; that is harmless here because events only trigger a refetch. Dedupe on the event `id` if your handler does more.
+REST fallback: `POST /v1/identity/stream-keys` with the same body and your server-held API key.
-`bun run example` runs a working version of all three plus an SSE endpoint. It is for local use only: it binds to `127.0.0.1` and its task and SSE routes are unauthenticated.
+Revoke a token on the server with `await client.streamTokens.delete(keyId)`.
-### 3. Client
+Pass a stream URL fetched through your backend and a callback that calls your mint route:
```tsx
-import { TaskApproval, useTaskApproval, type PendingApproval } from '@mobilerun/react';
+import { DeviceStream } from '@mobilerun/react';
import '@mobilerun/react/styles.css';
-
-export function Approval({ taskId }: { taskId: string }) {
- const { approval, decide, isDeciding, decision, error } = useTaskApproval({
- taskId,
- fetchApproval: async (id) => {
- const res = await fetch(`/api/tasks/${encodeURIComponent(id)}`);
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- return ((await res.json()) as { pendingApproval: PendingApproval | null }).pendingApproval;
- },
- decide: async ({ taskId, approvalId, decision }) => {
- const url = `/api/tasks/${encodeURIComponent(taskId)}/approvals/${encodeURIComponent(approvalId)}`;
- const res = await fetch(url, {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ decision }),
- });
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- },
- // Optional push: reload when your backend signals a change. Without it the hook polls every 3 s.
- subscribe: (taskId, onChange) => {
- const source = new EventSource(`/api/events?taskId=${encodeURIComponent(taskId)}`);
- source.onmessage = onChange;
- return () => source.close();
- },
- });
-
- return (
- } // optional live device next to the details
- />
- );
+export function DevicePanel({ deviceId, streamUrl }: { deviceId: string; streamUrl: string }) {
+ const tokenProvider = async () => {
+ const res = await fetch(`/api/v1/devices/${encodeURIComponent(deviceId)}/stream-key`, { method: 'POST', cache: 'no-store' });
+ if (!res.ok) throw new Error('Stream token request failed');
+ return (await res.json()).key;
+ };
+ return
;
}
```
-`` renders an inline card (wrap it in your own dialog if you want one) and nothing when `approval` is `null`. When you pass `device`, the card shows it next to the details from `md` up; below `md` a Details/Device switch toggles between the two while the device stays mounted, so a live stream never reconnects. The device slot has a fixed height and clips overflow, so the device element should fill it (`height: 100%`). For an unknown `kind` or unexpected `details` it shows a generic "Waiting for approval" body with the same buttons.
+Never log or cache stream tokens. Your backend must authenticate callers and authorize the device.
+The [full example](https://github.com/droidrun/mobilerun-react/blob/main/docs/stream-tokens.md) also shows `useDeviceStream` and device token (legacy) compatibility.
-### Show it as a bottom sheet
+`tokenProvider` runs before every connection attempt, the first one and each reconnect, and the SDK
+never reuses a token it returns. **Use it: stream tokens are single-use, so only a provider can reconnect.**
-The host owns the sheet or dialog; the library ships only the card. Render `` inside your own wrapper while `approval` is non-null. The CSS below turns the wrapper into a sheet below `md` (767px) and leaves it unstyled above:
-
-```tsx
-{approval && (
-
-
-
-
-
-)}
-```
-
-```css
-@media (max-width: 767px) {
- .sheet-backdrop { position: fixed; inset: 0; z-index: 50; display: flex; align-items: flex-end; background: rgba(0,0,0,.45); }
- .sheet { width: 100%; max-height: 92vh; overflow-y: auto; border-radius: 24px 24px 0 0; background: var(--background); animation: sheet-up .35s cubic-bezier(.2,.7,.2,1); }
- @keyframes sheet-up { from { transform: translateY(100%); } }
- @media (prefers-reduced-motion: reduce) { .sheet { animation: none; } }
-}
-```
+The legacy `streamToken` prop (device token) is **deprecated** and an explicit exception to that rule: it is kept until the
+device token (legacy) is removed, and the SDK passes the same value again on every reconnect. A single-use stream token
+given this way is rejected on the second attempt, so the stream ends in the Retry state
+(`connection_refused`). The component logs one console warning per mount.
-As a modal, the host moves focus into the sheet and makes the page behind it inert, or uses its own dialog component.
-
-For dark mode put `.dark` on any ancestor, or override the CSS variables (`--background`, `--card`, `--destructive`, β¦).
-
-### Labels and i18n
-
-Every user-visible string can be replaced through the `labels` prop; see `TaskApprovalLabels` for all keys. `{time}` in `timeLeft` is replaced with the remaining time.
+React to failures and white-label the texts:
```tsx
- report(reason, attempt, final)}
+ labels={{ connecting: 'Startingβ¦', disconnected: 'Reconnecting', unavailable: 'Phone unavailable', retry: 'Try again' }}
/>
```
-## π§ͺ Try it locally
-
-The repo ships the playground shown above β paste an API key + device id, or a raw `streamUrl` + `streamToken`, and stream a real device:
-
-```sh
-bun install
-bun run example # serves the playground at http://localhost:3000
-```
+`reason` is `credentials_unavailable` (your provider threw or took longer than 10 s),
+`connection_refused` (the socket closed before it opened: a used, expired or wrong stream token, a wrong
+device or a refused origin; browsers cannot see the HTTP status), `disconnected` (an open session
+dropped, including the 30-minute server cap) or `unknown`. `final: true` means retries stopped and
+the Retry button is showing. `labels` replaces every text the component renders.
-In SDK mode the example server exposes one narrow helper endpoint backed by `@mobilerun/sdk` (`sdk.devices.get(id)`) so the API key can stay server-side while retrieving `streamUrl` and `streamToken`. The stream WebSocket itself is opened directly by the browser against `streamUrl`; the component appends `streamToken` as `?token=`. The same server also demonstrates [task approvals](#-task-approvals) (set `MOBILERUN_WEBHOOK_SECRET` for the webhook route). The server binds to `127.0.0.1` and its task and SSE routes are unauthenticated by design. If you need webhooks delivered to your machine, expose only `/webhooks/mobilerun` (for example through a tunnel that forwards just that path), never the whole server.
+## Microphone and camera publishing
-## π¨ Styling & theming
+Pass your backend's per-device `publishCapabilities` snapshot to enable microphone injection
+(and camera injection when supported). A floating pill over the stream provides both toggles;
+active inputs show red. Set `hidePublishControls` for your own controls and use a
+`DeviceStreamHandle` ref's `startPublish({ audio: true, video: true })`, `stopPublish()` and
+`getPublishState()`. Audio is required; the SDK never silently starts a video-only session.
-Import the prebuilt stylesheet once, anywhere:
+`onPublishStateChange` observes this separate state. Publish errors carry `operation: 'publish'`
+in `onError`; an explicit server `forbidden` maps to `publish_not_allowed`, while a silent server
+maps to `publish_unsupported` after 5 seconds. Permission prompts happen only after the device accepts an explicit start; the 30-second active
+window includes the prompt. Refused or silent requests never capture.
+Stopping or reconnecting releases capture; publication never resumes automatically.
+See [Publishing inputs](https://github.com/droidrun/mobilerun-react/blob/main/docs/publish.md)
+for capabilities, permissions, ref types and labels.
-```ts
-import '@mobilerun/react/styles.css';
-```
+## Theming
-It bundles the design tokens, only the Tailwind utilities the components use, the animations, and the structural CSS. It does **not** include Tailwind's preflight/reset, so it won't touch your base styles β and you don't need Tailwind installed.
+The stylesheet defines no unprefixed CSS variable, so it cannot clash with your own `--background`. Set
+these on any ancestor of the component or on its root (`.mobilerun-device-stream`):
+`--mr-background`, `--mr-foreground`, `--mr-card`, `--mr-card-foreground`, `--mr-muted`,
+`--mr-muted-foreground`, `--mr-border`, `--mr-ring`, `--mr-primary`, `--mr-primary-foreground`,
+`--mr-accent`, `--mr-accent-foreground`, `--mr-destructive`.
-Retheme by overriding the CSS variables on an ancestor (e.g. `--background`, `--card`, `--muted-foreground`, `--border`, `--primary`), or add a `.dark` ancestor for the bundled dark palette:
+Each color resolves in this order: `--mr-`, then the old unprefixed `--` (kept for one more
+minor release, so a host theme that already defines `--background` keeps working), then the bundled
+default. Add `.dark` to an ancestor, or to the component root, for the bundled dark defaults.
```css
-:root {
- --primary: oklch(0.55 0.18 268);
- --background: oklch(0.985 0.004 85);
-}
+.mobilerun-device-stream { --mr-primary: oklch(0.55 0.18 268); --mr-background: oklch(0.985 0.004 85); }
```
-## π Building locally
+## Guides
-```sh
-bun install
-bun run build # tsup (JS + d.ts) + Tailwind (styles.css) β dist/
-bun run typecheck
-bun test
-```
+Coding agents: [Mobilerun device stream skill](https://github.com/droidrun/mobilerun-react/blob/main/skills/mobilerun-device-stream/SKILL.md).
+
+| Guide | Covers |
+| --- | --- |
+| [Stream tokens](https://github.com/droidrun/mobilerun-react/blob/main/docs/stream-tokens.md) | Server routes, device metadata, `tokenProvider`, retries and device tokens (legacy). |
+| [Components and styling](https://github.com/droidrun/mobilerun-react/blob/main/docs/default-ui.md) | Components, prebuilt CSS, theme variables and dark mode. |
+| [Task approvals](https://github.com/droidrun/mobilerun-react/blob/main/docs/task-approvals.md) | Webhooks, backend decisions, cards, bottom sheets and labels. |
-## 𧬠Conformance
+## Contributing
-The control messages, signalling frames, reconnect policy and input routing are replayed against the shared [conformance fixtures](https://github.com/droidrun/mobilerun-sdk-conformance) that the native SDKs also pass. The vendored copy lives in `conformance/fixtures` (release tag in `conformance/VERSION`) and runs with `bun test`. To move to another release, run `scripts/sync-conformance.sh TAG`.
+See [CONTRIBUTING.md](https://github.com/droidrun/mobilerun-react/blob/main/CONTRIBUTING.md) for builds, tests, conformance fixtures and the example app.
+Report vulnerabilities privately as described in [SECURITY.md](https://github.com/droidrun/mobilerun-react/blob/main/SECURITY.md).
-## π License
+## License
-[Apache-2.0](./LICENSE)
+[Apache-2.0](https://github.com/droidrun/mobilerun-react/blob/main/LICENSE)
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 0000000..eee586d
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,5 @@
+# Security
+
+Report vulnerabilities privately through this repositoryβs GitHub **Security** tab β **Report a vulnerability**. Do not open public issues for security problems.
+
+This policy covers the SDK and its example helper; the Mobilerun API itself is out of scope here, but reports about it go through the same private channel.
diff --git a/bun.lock b/bun.lock
index e43328a..20fcd24 100644
--- a/bun.lock
+++ b/bun.lock
@@ -12,7 +12,7 @@
"tailwind-merge": "^3.2.0",
},
"devDependencies": {
- "@mobilerun/sdk": "^6.2.1",
+ "@mobilerun/sdk": "^6.3.0",
"@tailwindcss/cli": "^4.1.5",
"@types/bun": "1.4.3",
"@types/node": "^24",
@@ -100,7 +100,7 @@
"@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
- "@mobilerun/sdk": ["@mobilerun/sdk@6.2.1", "", { "peerDependencies": { "zod": ">=4.0.0 <5" }, "optionalPeers": ["zod"] }, "sha512-ELhSHYur/E7StYvtC1pTyQkKl73BLYBkWETIdFrST3YDLBW6XYG3Lp9nlQhQ6L3V9wWRni2WjoLZj9m1sG3Qvg=="],
+ "@mobilerun/sdk": ["@mobilerun/sdk@6.3.0", "", { "peerDependencies": { "zod": ">=4.0.0 <5" }, "optionalPeers": ["zod"] }, "sha512-nJvX7t+zk9/G/KBK7094KzT+rGV5dfVIXgEBvw4C+hiqLswGDAMsqKyGzm8UX6NEiC+1DBuXBWM6Bt1dM0sLUA=="],
"@napi-rs/lzma-linux-x64-gnu": ["@napi-rs/lzma-linux-x64-gnu@1.5.1", "", { "os": "linux", "cpu": "x64" }, "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ=="],
diff --git a/docs/default-ui.md b/docs/default-ui.md
new file mode 100644
index 0000000..b3bf9ec
--- /dev/null
+++ b/docs/default-ui.md
@@ -0,0 +1,52 @@
+β [README](../README.md) Β· [Partner guide](https://docs.mobilerun.ai/partners)
+
+# Components and styling
+
+Drop a live, controllable cloud device (iOS/ Android) into any React app:
+
+- **``** β WebRTC video with touch, swipe and keyboard control, plus automatic reconnects with exponential backoff and a retry UI once attempts are exhausted.
+- **`useDeviceStream()`** β resolves a device's stream URL and state from
+ [`@mobilerun/sdk`](https://www.npmjs.com/package/@mobilerun/sdk), polling while it boots.
+- **``** + **`useTaskApproval()`** β show a task's pending human approval (e.g. "enter payment card X into app Y") with a countdown and Approve/Deny buttons. See [Task approvals](task-approvals.md).
+- **``**, **``**, **``** β the surrounding chrome and a lower-level escape hatch.
+- **Prebuilt stylesheet** β no Tailwind setup required, themeable via CSS variables.
+- **Typed** β ships its own `.d.ts`; React and the SDK are peer dependencies.
+
+## Lower-level exports
+
+- `Button` / `cn` β shared button and class-name utilities.
+- `useWebRtcConnection` β lower-level WebRTC connection state.
+- `useStreamReconnect` β bounded retries and reconnect state.
+- `useDeviceGridSelfHeal` β coordinate stream recovery in a device grid.
+- `useScrcpyInput` β send touch and keyboard input.
+- scrcpy protocol helpers and constants β encode remote-control messages.
+
+## Styling and theming
+
+Import the prebuilt stylesheet once, anywhere:
+
+```ts
+import '@mobilerun/react/styles.css';
+```
+
+It bundles the design tokens, only the Tailwind utilities the components use, the animations, and the structural CSS. It does **not** include Tailwind's preflight/reset, so it won't touch your base styles β and you don't need Tailwind installed.
+
+Retheme by setting the `--mr-*` variables on an ancestor or on the component root
+(`.mobilerun-device-stream`, `.mobilerun-task-approval`, `.mobilerun-navigation-bar`). The package
+defines no unprefixed variable globally, so it cannot clash with your own `--background`. Add a
+`.dark` ancestor (or class on the component root) for the bundled dark palette:
+
+```css
+.mobilerun-device-stream {
+ --mr-primary: oklch(0.55 0.18 268);
+ --mr-background: oklch(0.985 0.004 85);
+}
+```
+
+Available tokens: `--mr-background`, `--mr-foreground`, `--mr-card`, `--mr-card-foreground`,
+`--mr-muted`, `--mr-muted-foreground`, `--mr-border`, `--mr-ring`, `--mr-primary`,
+`--mr-primary-foreground`, `--mr-accent`, `--mr-accent-foreground`, `--mr-destructive`.
+
+The old unprefixed names (`--background`, `--card`, ...) are still read as a fallback for one more
+minor release, so themes written for 0.3 keep working; move them to `--mr-*`. User-visible texts are
+set with the `labels` prop, see [Stream tokens](stream-tokens.md#labels).
diff --git a/docs/publish.md b/docs/publish.md
new file mode 100644
index 0000000..c3acdb0
--- /dev/null
+++ b/docs/publish.md
@@ -0,0 +1,125 @@
+β [README](../README.md) Β· [Components and styling](default-ui.md)
+
+# Publishing microphone and camera inputs
+
+Publishing sends your local microphone and optionally camera into the remote device's virtual
+inputs. It uses the existing viewer connection, independently of received device audio and its
+`muted` prop. It does not create a preview or another connection.
+
+Your authorized backend fetches `GET /v1/devices/{deviceId}/capabilities` and returns its
+`.capabilities` snapshot to your app. Pass that as `publishCapabilities`; do not use a stream token
+to call this endpoint or expose a privileged API key. The snapshot describes device support,
+not the viewer's permission. Every start is admitted or refused by the server.
+
+```tsx
+import { useRef } from 'react';
+import { DeviceStream, type DeviceStreamHandle, type DevicePublishCapabilities } from '@mobilerun/react';
+import '@mobilerun/react/styles.css';
+
+export function Phone({ streamUrl, tokenProvider, capabilities }: {
+ streamUrl: string;
+ tokenProvider: () => Promise;
+ capabilities: DevicePublishCapabilities;
+}) {
+ const stream = useRef(null);
+ return
;
+}
+```
+
+The default pill floats at the bottom centre without changing the video layout. Only its buttons receive taps; the background and separate status
+text above the pill pass taps through. After 3 seconds without nearby interaction it fades to 50%;
+nearby pointer/touch input or button focus restores full opacity. Microphone toggles
+publication on/off. Camera starts microphone+camera; toggling it off restarts microphone-only.
+Live inputs show red. Both controls are disabled during setup. The pill is hidden without a snapshot
+with `microphoneInjection: true` and `mediaInjectionTransport: 'direct'`; camera also requires
+`cameraInjection: true` and a compatible browser H.264 encoder. `hasControl` controls remote input
+UI only and does not grant or revoke publishing authority.
+
+Set `hidePublishControls` to hide the pill and call the ref methods from your own user actions:
+
+- `startPublish({ audio: true })`: microphone only. `video: true` requests both inputs atomically.
+ `audio` is required; false, missing audio and video-only requests reject before capture/signaling.
+ The promise resolves with an `active` snapshot only after server activation and track attachment.
+- `stopPublish()`: cancels setup or stops active capture, idempotently. It completes local teardown
+ without waiting for a server acknowledgement. Cancellation rejects a pending start with
+ `publish_cancelled` and emits a stopped snapshot, without `onError`.
+- `getPublishState()`: current immutable snapshot, initially
+ `{ phase: 'idle', mediaSessionId: null, kinds: [] }`.
+
+`DeviceStreamHandle` extends `RemoteControlHandle`; existing ref operations remain supported.
+`onPublishStateChange` observes `starting β accepted β capturing β active` and terminal
+`stopped`/`error` states. The SDK sends the start request before opening inputs; refused and silent requests never prompt
+or capture. Acceptance starts a 30-second window covering the permission prompt, capture and activation. Only one operation is
+allowed; a concurrent start rejects without changing it. Explicitly stop then start to change kinds.
+When capabilities arrive or their values change, the SDK renews the viewer connection and obtains
+a fresh token through `tokenProvider` to reserve the inputs in its first offer. Equivalent snapshots
+do not reconnect. The camera button follows the verified offer reservation. No publish-time SDP renegotiation or automatic resume occurs.
+Browsers unable to produce compatible SSRC-bearing trackless sender reservations keep viewing
+and reject publication with `publish_unsupported`.
+
+## Permissions and cleanup
+
+Use HTTPS or localhost and permit the required inputs in your site's Permissions Policy. For
+cross-origin iframe embeds configure the parent policy and `allow="microphone; camera"` on the
+iframe. Only an explicit start accepted by the device requests capture permission; mounting, connecting and reconnecting
+never prompt. Audio-only does not request camera permission. The default browser input devices
+are used. The capture profile targets 720p at 24β30 fps with a 1 Mbps uplink cap where supported.
+
+Viewer replacement/remount emits terminal `disconnected` once through state and `onError`. A
+throwing start/stop signaling write also reports `disconnected` and releases capture.
+
+Capture is released on cancellation, failure, source loss, signaling/peer loss, pagehide and
+unmount. A pending permission prompt may remain visible, but any later tracks are stopped without
+attachment. Reconnection never resumes publication; start again explicitly. An ICE credential
+refresh on the same socket/peer preserves publication. Stopping publish leaves viewing and
+downstream mute unchanged.
+
+## Failures
+
+A rejected start throws `PublishError`, carrying `reason`, `message`, optional `detail` and
+`serverReason`. Branch on structured fields, not display text. Terminal failures also update
+publish state and emit one `onError` with `operation: 'publish'`, the current viewer attempt,
+`final: true`, and an allocated `mediaSessionId` when available. `final` applies to publishing;
+viewer reconnect and later explicit starts remain available. A publish refusal never marks the
+viewer unavailable.
+
+| Reason | Cause |
+| --- | --- |
+| `publish_not_allowed` | Explicit server `forbidden`; support never overrides this decision. |
+| `publish_unsupported` | Missing/incompatible capabilities, codecs/reservations, or no acceptance within 5 s (`response_timeout`). Silence is not proof of denial. |
+| `permission_denied` | Browser `NotAllowedError`/`SecurityError` (`capture_permission`). |
+| `publish_busy` | Another publisher holds the device's lease. No stealing or retry. |
+| `publish_failed` | Invalid options, concurrent start, missing/busy inputs, source loss, attachment/injection failure or unexpected terminal server response. |
+| `publish_timeout` | Accepted but no server active within 30 s (including the permission prompt) (`active_timeout`). |
+| `publish_cancelled` | Pending start cancelled locally; no error callback. |
+| `disconnected` | Viewer is not connected, is closed, or loses its socket/peer. |
+
+Original string wire reasons are preserved as `serverReason`. Unknown reasons become
+`publish_failed`; stale/malformed/foreign-session messages are ignored.
+
+## Labels and styling
+
+All pill text uses `labels` with English defaults:
+
+| Key | Default |
+| --- | --- |
+| `microphone` | Microphone |
+| `camera` | Camera |
+| `stopMicrophone` | Stop microphone |
+| `stopCamera` | Stop camera |
+| `publishStarting` | Starting inputs |
+| `publishPermissionDenied` | Microphone or camera permission denied |
+| `publishNotAllowed` | Publishing is not allowed |
+| `publishFailed` | Could not publish inputs |
+
+The pill uses the existing card, foreground, border and ring tokens. Override the red live state
+with `--mr-publish-live` and `--mr-publish-live-foreground` on `.mobilerun-device-stream` or an
+ancestor, keeping sufficient contrast.
diff --git a/docs/stream-keys.md b/docs/stream-keys.md
new file mode 100644
index 0000000..1366a6b
--- /dev/null
+++ b/docs/stream-keys.md
@@ -0,0 +1 @@
+[Stream tokens guide](stream-tokens.md)
diff --git a/docs/stream-tokens.md b/docs/stream-tokens.md
new file mode 100644
index 0000000..7750fa4
--- /dev/null
+++ b/docs/stream-tokens.md
@@ -0,0 +1,202 @@
+β [README](../README.md) Β· [Partner guide](https://docs.mobilerun.ai/partners)
+
+# Stream tokens
+
+The object API helpers (`MobilerunSDK`, `devices.fromId`, `verifyWebhook`) require `@mobilerun/sdk` 6.2 or later. The backend stream-token helpers below require `@mobilerun/sdk` 6.3.0 or later on Node. The `{ client, deviceId }` hook form works with older SDKs; the peer dependency range remains `>=2.0.0`.
+
+Keep the API key on your backend. Use `useDeviceStream` for the URL and device state, and supply a
+`tokenProvider` that calls your backend for a fresh single-use stream token before every WebSocket
+attempt, including retries.
+
+> **`MOBILERUN_API_KEY` is a secret API key β never ship it to the browser.** Only the server reads it.
+> The device endpoint returns only `id`, `state`, and `streamUrl`, with missing values set to `null`.
+> A separate POST endpoint returns a short-lived stream token scoped to that device; the browser SDK
+> uses a placeholder key to call your backend.
+
+On your backend, register this handler for `GET /api/v1/devices/:id`, passing the routed device ID:
+
+```ts
+import { MobilerunSDK } from '@mobilerun/sdk';
+
+const client = new MobilerunSDK({ logLevel: 'off' }); // reads MOBILERUN_API_KEY on the Node server
+
+export async function getDevice(id: string): Promise {
+ // Authenticate the caller and check the device belongs to them before returning device metadata.
+ const device = await client.devices.get(id);
+ return Response.json({
+ id: device.info?.id ?? null,
+ state: device.info?.state ?? null,
+ streamUrl: device.info?.streamUrl ?? null,
+ });
+}
+
+// Register for POST /api/v1/devices/:id/stream-key.
+export async function mintStreamToken(deviceId: string): Promise {
+ // Authenticate the caller and authorize this device in your application first.
+ try {
+ const { key, keyId, expiresAt } = await client.streamTokens.create({
+ deviceId,
+ ttlSeconds: 120,
+ allowedOrigins: ['https://partner.example'], // replace with your browser app's origin
+ }, { maxRetries: 0 });
+ return Response.json({ key, keyId, expiresAt }, {
+ status: 201,
+ headers: { 'Cache-Control': 'no-store' },
+ });
+ } catch (err) {
+ const { status } = err as { status?: number };
+ const isUpstreamError = typeof status === 'number' && status >= 400 && status < 600;
+ return Response.json({ error: 'stream_key_mint_failed' }, {
+ status: isUpstreamError ? status : 502,
+ headers: { 'Cache-Control': 'no-store' },
+ });
+ }
+}
+```
+
+`client.streamTokens.create({ deviceId, ttlSeconds, allowedOrigins })` returns
+`{ key, keyId, expiresAt }`. TTL is 60β300 seconds, default 120. Configure `allowedOrigins` on
+the server with your browser app's exact origins. Each stream token is single-use and device-scoped.
+Revoke it on the server with `await client.streamTokens.delete(keyId)`. `expiresAt` is diagnostic
+metadata, not a browser permission or validity check. Do not log or cache stream tokens.
+
+REST fallback: `POST /v1/identity/stream-keys` with the same body, or `DELETE /v1/identity/stream-keys/{keyId}`, authenticated with your server-held API key.
+
+Your backend must authenticate callers and authorize the requested device; never accept an arbitrary
+target URL or owner from the browser. Propagate mint refusal without returning upstream credential details.
+
+In your client component, point the SDK at that backend route, as in the example app:
+
+```tsx
+'use client';
+
+import { useCallback, useMemo } from 'react';
+import { MobilerunSDK } from '@mobilerun/sdk';
+import { DeviceStream, useDeviceStream } from '@mobilerun/react';
+import '@mobilerun/react/styles.css';
+
+export function DevicePanel({ deviceId }: { deviceId: string }) {
+ const sdk = useMemo(() => new MobilerunSDK({
+ apiKey: 'example-sdk-helper', // placeholder, not a Mobilerun API key
+ baseURL: typeof window === 'undefined' ? '/api/v1' : `${window.location.origin}/api/v1`, // SSR placeholder; the hook only fetches in the browser
+ }), []);
+ const { streamUrl, state, refetch } = useDeviceStream({
+ device: sdk.devices.fromId(deviceId), // no request yet
+ });
+ const getFreshStreamToken = useCallback(async () => {
+ const response = await fetch(`/api/v1/devices/${encodeURIComponent(deviceId)}/stream-key`, {
+ method: 'POST',
+ cache: 'no-store',
+ });
+ if (!response.ok) throw new Error('Stream token request failed');
+ const { key } = await response.json();
+ return key;
+ }, [deviceId]);
+
+ return (
+
+
+
+ );
+}
+```
+
+### Without the hook
+
+Supply an existing stream URL and the same server-backed callback:
+
+```tsx
+
+```
+
+`tokenProvider?: () => Promise` is supported by `DeviceStream` and `RemoteControl`.
+It is awaited once immediately before each socket allocation. It takes precedence over static
+`streamToken`/`token`; a rejection or empty stream token fails that attempt with no fallback. Pending results
+after stop, device switch or unmount are ignored. Changing callback identity does not reconnect a
+healthy stream. An ICE credential refresh on an existing socket does not call it again.
+A server signaling close with code 1001 ends media/control in every mode and triggers the existing
+bounded reconnect policy. Other signaling closes keep a connected media path running. Provider mode
+mints a fresh stream token for each new socket. `onStreamHealed` can refresh URL/state; it is not per retry
+and must not be used to cache a stream token.
+
+## Device token (legacy)
+
+Static `DeviceStream.streamToken`, `RemoteControl.token`, and the hook's returned `streamToken` are
+**deprecated**, retained for existing consumers. `DeviceStream` logs one console warning per mount
+when it runs on a static token; `tokenProvider` wins when both are given.
+
+**Exception to the no-reuse rule:** with a static token the SDK does not fetch anything new; it sends
+the same value on the first connect and on every reconnect, until the device token (legacy) is removed. Stream
+tokens are single-use, so a stream token passed statically that was already admitted or rejected fails the retry attempts
+(`connection_refused`) and ends in the Retry state. A long-lived device token (legacy) keeps reconnecting.
+`tokenProvider` is the recommended path and the only one that works with single-use stream tokens. Manual
+URL/token mode is a device token (legacy) diagnostic path; a pasted single-use stream token cannot reconnect after admission. `useDeviceStream` also still accepts
+`{ client, deviceId }` with a plain `Mobilerun` client.
+
+## Network recovery
+
+While the browser reports offline (`navigator.onLine === false` or an `offline` event), no new
+`tokenProvider` call or socket allocation starts. Pending acquisition, retry waits and connect
+watchdogs are cancelled; late provider results are ignored without an error. An explicit Retry overrides
+this hint for one fresh attempt (direct `useStreamReconnect` consumers forward its `allowOffline`
+value to the socket hook/component); if it fails offline, the failure is reported once and automatic
+retries, visibility wake and target changes remain gated until online. An advisory offline notification preserves
+healthy media until its transport actually fails. Retry is ignored while connected or while an explicit
+attempt is still live; otherwise an offline pause shows `unavailable` with the default Retry action.
+
+A false-to-true network transition starts one immediate fresh attempt when a connection is needed,
+resets backoff to attempt 0, and calls the latest provider for a new stream token. Duplicate online
+events do nothing; a healthy stream is not remounted. Connectivity is only a scheduling hint,
+not proof that the server is reachable. A forced attempt with an allocated socket continues when online
+returns, while a forced provider wait is discarded for a fresh attempt. Existing labels and bounded
+retries still apply.
+
+`DeviceStream` manages this through `useStreamReconnect`. Direct `RemoteControl` or
+`useWebRtcConnection` consumers get offline gating and cancellation, but must own remounting and
+recovery (for example, with `useStreamReconnect`); the low-level socket hook does not retry on its
+own. Observers detach on unmount. Custom lifecycle owners that remove an observer while a session
+continues must replace that network source or forward availability to the controller themselves.
+
+## Errors
+
+`DeviceStream` calls `onError` once per failed connection attempt:
+
+```ts
+onError?: (error: {
+ reason: 'credentials_unavailable' | 'connection_refused' | 'disconnected' | 'device_unavailable' | 'unknown';
+ message: string; // fixed SDK text for logs, never exception text from your provider or the socket
+ attempt: number; // consecutive failed attempts in this cycle, from 1; the pill shows the same n as "(n/6)"
+ final: boolean; // true when the SDK stops retrying; the Retry button stays available
+}) => void;
+```
+
+| `reason` | Meaning |
+| --- | --- |
+| `credentials_unavailable` | `tokenProvider` threw, rejected, returned an empty stream token or took longer than 10 s. Normal backoff applies. |
+| `connection_refused` | The signaling socket closed before it opened. A browser cannot read the HTTP status, so a used, expired or revoked stream token, a wrong device and a refused origin all land here. Check the mint call first. |
+| `disconnected` | An open session dropped, including the 30-minute server session cap. |
+| `device_unavailable` | Reserved for a server message that the device is offline or not ready. The current signaling protocol has none, so React does not report it yet. |
+| `unknown` | Anything else, for example a handshake that never finished. |
+
+## Labels
+
+Every text the component renders comes from `labels`, with English defaults:
+
+```tsx
+
+```
+
+A `placeholderLabel` (for example the device state) still takes precedence over `labels.connecting`.
diff --git a/docs/task-approvals.md b/docs/task-approvals.md
new file mode 100644
index 0000000..8e89678
--- /dev/null
+++ b/docs/task-approvals.md
@@ -0,0 +1,170 @@
+β [README](../README.md) Β· [Partner guide](https://docs.mobilerun.ai/partners)
+
+# Task approvals
+
+A task can pause and wait for a human to approve a step, for example entering a payment card into an app. `useTaskApproval()` loads the pending approval and `` renders it with a countdown and Approve/Deny buttons.
+
+**The decision goes through your backend.** The API key that may approve is a secret and must never reach the browser, so the browser only talks to your own routes. The Mobilerun API owns the approval state and decides: the component renders what it is given and forwards the decision, and the countdown is display only. A 404/409 from the decide call (unknown, already resolved or expired) comes back as an error and triggers a refetch.
+
+### 1. Subscribe a webhook
+
+In your Mobilerun webhook settings, point an endpoint at your backend and filter it to the two approval events: `task.run.approval_requested` and `task.run.approval_resolved`. Events only tell the browser to reload; the fetched approval is the source of truth.
+
+Each delivery carries `X-Mobilerun-Timestamp` (Unix ms) and `X-Mobilerun-Signature: sha256=`, an HMAC-SHA256 of `"{timestamp}.{rawBody}"` with the endpoint secret. `verifyWebhook` from `@mobilerun/sdk` checks the signature and the 5-minute timestamp window and returns the parsed payload; pass it the body bytes exactly as received. SDK 6.2.1 or later distinguishes `invalid_json` (a signed but unparsable body), which the handler answers with HTTP 400.
+
+### 2. Backend sketch
+
+```ts
+import { MobilerunSDK, verifyWebhook, WebhookVerificationError } from '@mobilerun/sdk';
+
+const sdk = new MobilerunSDK(); // reads MOBILERUN_API_KEY
+const APPROVAL_EVENTS = new Set(['task.run.approval_requested', 'task.run.approval_resolved']);
+const ID = /^[A-Za-z0-9_-]+$/;
+
+// Device metadata: return only the fields needed for streaming.
+app.get('/api/v1/devices/:id', async (c) => {
+ const id = c.req.param('id');
+ // Authenticate the caller and check the device belongs to them before returning device metadata.
+ const device = await sdk.devices.get(id);
+ return c.json({
+ id: device.info?.id ?? null,
+ state: device.info?.state ?? null,
+ streamUrl: device.info?.streamUrl ?? null,
+ });
+});
+
+// 1. Webhook: verify the raw bytes, then push a change signal to the user's browser (SSE, ...)
+app.post('/webhooks/mobilerun', async (c) => {
+ const secret = process.env.MOBILERUN_WEBHOOK_SECRET;
+ if (!secret) return c.json({ error: 'missing_webhook_secret' }, 500);
+ const bytes = new Uint8Array(await c.req.arrayBuffer());
+ let event;
+ try {
+ event = await verifyWebhook({
+ body: bytes,
+ headers: c.req.raw.headers,
+ secret,
+ }) as { type?: string; data?: { taskId?: string } } | null;
+ } catch (err) {
+ if (err instanceof WebhookVerificationError) {
+ if (err.reason === 'invalid_json') return c.json({ error: 'invalid_json' }, 400);
+ return c.json({ error: 'invalid_signature' }, 401);
+ }
+ throw err;
+ }
+ const taskId = event?.data?.taskId;
+ if (taskId && APPROVAL_EVENTS.has(event?.type ?? '')) push({ taskId });
+ return c.body(null, 204);
+});
+
+// 2. Pending approval: GET /tasks/{id} β task.pendingApproval (null when none)
+app.get('/api/tasks/:id', async (c) => {
+ const id = c.req.param('id');
+ if (!ID.test(id)) return c.json({ error: 'invalid_id' }, 400);
+ // Authenticate the caller and check the task belongs to their user/org first.
+ const { task } = await sdk.api.get<{ task?: { pendingApproval?: unknown } }>(`/tasks/${encodeURIComponent(id)}`);
+ return c.json({ pendingApproval: task?.pendingApproval ?? null });
+});
+
+// 3. Decision: POST /tasks/{id}/approvals/{approvalId} { decision: 'approve' | 'deny' }
+app.post('/api/tasks/:id/approvals/:approvalId', async (c) => {
+ const id = c.req.param('id');
+ const approvalId = c.req.param('approvalId');
+ if (!ID.test(id) || !ID.test(approvalId)) return c.json({ error: 'invalid_id' }, 400);
+ const { decision } = await c.req.json();
+ if (decision !== 'approve' && decision !== 'deny') return c.json({ error: 'invalid_decision' }, 422);
+ // Authenticate the caller and check the task belongs to their user/org first.
+ const url = `/tasks/${encodeURIComponent(id)}/approvals/${encodeURIComponent(approvalId)}`;
+ await sdk.api.post(url, { body: { decision } });
+ return c.body(null, 204);
+});
+```
+
+Authenticate every route and check that the task belongs to the signed-in user or organization before forwarding. A delivery can be replayed within the 5-minute window; that is harmless here because events only trigger a refetch. Dedupe on the event `id` if your handler does more.
+
+`bun run example` runs a working version of all three plus an SSE endpoint. It is for local use only: it binds to `127.0.0.1` and its task and SSE routes are unauthenticated.
+
+### 3. Client
+
+```tsx
+import { TaskApproval, useTaskApproval, type PendingApproval } from '@mobilerun/react';
+import '@mobilerun/react/styles.css';
+
+export function Approval({ taskId }: { taskId: string }) {
+ const { approval, decide, isDeciding, decision, error } = useTaskApproval({
+ taskId,
+ fetchApproval: async (id) => {
+ const res = await fetch(`/api/tasks/${encodeURIComponent(id)}`);
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ return ((await res.json()) as { pendingApproval: PendingApproval | null }).pendingApproval;
+ },
+ decide: async ({ taskId, approvalId, decision }) => {
+ const url = `/api/tasks/${encodeURIComponent(taskId)}/approvals/${encodeURIComponent(approvalId)}`;
+ const res = await fetch(url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ decision }),
+ });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ },
+ // Optional push: reload when your backend signals a change. Without it the hook polls every 3 s.
+ subscribe: (taskId, onChange) => {
+ const source = new EventSource(`/api/events?taskId=${encodeURIComponent(taskId)}`);
+ source.onmessage = onChange;
+ return () => source.close();
+ },
+ });
+
+ return (
+ } // optional live device next to the details
+ />
+ );
+}
+```
+
+`` renders an inline card (wrap it in your own dialog if you want one) and nothing when `approval` is `null`. When you pass `device`, the card shows it next to the details from `md` up; below `md` a Details/Device switch toggles between the two while the device stays mounted, so a live stream never reconnects. The device slot has a fixed height and clips overflow, so the device element should fill it (`height: 100%`). For an unknown `kind` or unexpected `details` it shows a generic "Waiting for approval" body with the same buttons.
+
+### Show it as a bottom sheet
+
+The host owns the sheet or dialog; the library ships only the card. Render `` inside your own wrapper while `approval` is non-null. The CSS below turns the wrapper into a sheet below `md` (767px) and leaves it unstyled above:
+
+```tsx
+{approval && (
+
+
+
+
+
+)}
+```
+
+```css
+@media (max-width: 767px) {
+ .sheet-backdrop { position: fixed; inset: 0; z-index: 50; display: flex; align-items: flex-end; background: rgba(0,0,0,.45); }
+ .sheet { width: 100%; max-height: 92vh; overflow-y: auto; border-radius: 24px 24px 0 0; background: var(--mr-background, var(--background, white)); animation: sheet-up .35s cubic-bezier(.2,.7,.2,1); }
+ @keyframes sheet-up { from { transform: translateY(100%); } }
+ @media (prefers-reduced-motion: reduce) { .sheet { animation: none; } }
+}
+```
+
+As a modal, the host moves focus into the sheet and makes the page behind it inert, or uses its own dialog component.
+
+For dark mode put `.dark` on any ancestor, or override the CSS variables (`--mr-background`, `--mr-card`, `--mr-destructive`, β¦; see [Components and styling](default-ui.md#styling-and-theming)).
+
+### Labels and i18n
+
+Every user-visible string can be replaced through the `labels` prop; see `TaskApprovalLabels` for all keys. `{time}` in `timeLeft` is replaced with the remaining time.
+
+```tsx
+
+```
diff --git a/example/main.tsx b/example/main.tsx
index c0208b4..16f4714 100644
--- a/example/main.tsx
+++ b/example/main.tsx
@@ -15,6 +15,7 @@ import {
type ApprovalDecision,
type PendingApproval,
type RemoteControlHandle,
+ type StreamError,
} from '../src/index';
// Prebuilt themed stylesheet (run `bun run build:css` once to generate it).
import '../dist/styles.css';
@@ -28,9 +29,10 @@ import logoUrl from '../assets/mobilerun-logo.png';
const HARNESS_CSS = `
*, *::before, *::after { box-sizing: border-box; }
html, body { margin: 0; }
- /* Cloud app theme tokens. Uses the SAME variable names the package reads
- * (--background, --card, --muted-foreground, --border, --primary, ...), so
- * the embedded DeviceStream/NavigationBar pick up the cloud palette too. */
+ /* Cloud app theme tokens. The package reads --mr- first and then these
+ * unprefixed names (--background, --card, --muted-foreground, ...), which stay
+ * supported for one more minor release, so the embedded DeviceStream and
+ * NavigationBar pick up the cloud palette too. New code sets --mr-. */
.app {
--background: oklch(0.985 0.004 85); --foreground: oklch(0.26 0.008 65);
--card: oklch(0.995 0.005 85); --card-foreground: oklch(0.26 0.008 65);
@@ -183,12 +185,13 @@ interface Status {
isLoading: boolean;
error?: unknown;
connected: boolean;
+ streamError?: StreamError;
}
/**
* Drives streaming from a device id via @mobilerun/sdk. `useDeviceStream`
- * resolves the device's `streamUrl` + `streamToken`; the component connects the
- * WebSocket directly (the token rides in the URL).
+ * resolves the device's URL/state; tokenProvider mints through our server
+ * immediately before each direct WebSocket attempt.
*/
function SdkStream({
apiKey,
@@ -211,10 +214,20 @@ function SdkStream({
[apiKey, baseURL],
);
// `fromId` makes no request; a fresh handle each render is fine, the hook keys by id.
- const { streamUrl, streamToken, state, error, isLoading, refetch } = useDeviceStream({
+ const { streamUrl, state, error, isLoading, refetch } = useDeviceStream({
device: sdk.devices.fromId(deviceId),
});
+ const getFreshStreamToken = useCallback(async () => {
+ const res = await fetch(`/api/v1/devices/${encodeURIComponent(deviceId)}/stream-key`, {
+ method: 'POST',
+ cache: 'no-store',
+ });
+ if (!res.ok) throw await readError(res);
+ const minted = await res.json() as { key: string };
+ return minted.key;
+ }, [deviceId]);
+
React.useEffect(() => onStatus({ state, error, isLoading }), [state, error, isLoading, onStatus]);
const streamRef = useRef(null);
@@ -224,12 +237,14 @@ function SdkStream({
onStatus({ connected: c })}
+ // `reason` tells a refused stream token from a dropped session; `final` means the Retry button is showing.
+ onError={(streamError) => onStatus({ streamError })}
+ onConnectionStateChange={(c) => onStatus({ connected: c, ...(c ? { streamError: undefined } : {}) })}
/>
);
@@ -239,17 +254,23 @@ type Mode = 'sdk' | 'manual';
function StatusLine({ s, active }: { s: Status; active: boolean }) {
const errText = s.error ? (s.error as { message?: string })?.message ?? String(s.error) : null;
+ const streamError = active && !s.connected ? s.streamError : undefined;
let tone: 'idle' | 'warn' | 'ok' | 'err' = 'idle';
let text = 'idle';
if (errText) {
tone = 'err';
text = 'error';
+ } else if (streamError?.final) {
+ tone = 'err';
+ text = `stream failed: ${streamError.reason}`;
} else if (active && s.connected) {
tone = 'ok';
text = 'live';
} else if (active) {
tone = 'warn';
- text = s.state ? `${s.state}β¦` : s.isLoading ? 'loadingβ¦' : 'connectingβ¦';
+ text = streamError
+ ? `retrying after ${streamError.reason} (attempt ${streamError.attempt})`
+ : s.state ? `${s.state}β¦` : s.isLoading ? 'loadingβ¦' : 'connectingβ¦';
}
return (
@@ -424,9 +445,8 @@ function ApprovalSection() {
function App() {
const [mode, setMode] = useState('sdk');
- // SDK mode uses the local server endpoint only to retrieve stream credentials
- // without exposing the API key. The WebSocket itself opens the returned streamUrl
- // directly in the browser with streamToken appended as ?token=.
+ // SDK mode retrieves URL/state and mints per connection through the local server.
+ // The parent API key stays server-side; stream WebSockets connect directly.
const apiKey = '';
const baseURL = typeof window === 'undefined' ? '/api/v1' : `${window.location.origin}/api/v1`;
const [deviceId, setDeviceId] = useState('');
@@ -434,7 +454,7 @@ function App() {
const [status, setStatus] = useState({ isLoading: false, connected: false });
const onStatus = useCallback((p: Partial) => setStatus((s) => ({ ...s, ...p })), []);
- // Manual mode: paste a streamUrl + streamToken directly.
+ // Device token (legacy) diagnostic mode: pasted tokens cannot renew single-use stream tokens on retries.
const [streamUrl, setStreamUrl] = useState('');
const [streamToken, setStreamToken] = useState('');
const [applied, setApplied] = useState<{ url?: string; token?: string }>({});
@@ -497,7 +517,7 @@ function App() {
SDK
@@ -544,7 +564,7 @@ function App() {
setStreamUrl(e.target.value)} placeholder="wss://β¦" />
diff --git a/example/server.test.ts b/example/server.test.ts
new file mode 100644
index 0000000..d9e5cc2
--- /dev/null
+++ b/example/server.test.ts
@@ -0,0 +1,165 @@
+// Copyright 2026 Mobilerun
+// SPDX-License-Identifier: Apache-2.0
+
+import { expect, spyOn, test } from 'bun:test';
+import { MobilerunSDK } from '@mobilerun/sdk';
+import { createExampleApp } from './server';
+
+const deviceId = '11111111-1111-4111-8111-111111111111';
+
+// Fake only the external HTTP API; routes and the SDK's request handling stay real.
+function upstream(response: object, status = 200) {
+ const requests: Request[] = [];
+ const sdk = new MobilerunSDK({
+ apiKey: 'test-only-placeholder',
+ baseURL: 'https://api.example.invalid/v1',
+ logLevel: 'off',
+ fetch: async (input, init) => {
+ requests.push(new Request(input, init));
+ return Response.json(response, { status });
+ },
+ });
+ return { app: createExampleApp(sdk), requests };
+}
+
+test('stream key helper GET returns URL and state without old credentials', async () => {
+ const f = upstream({
+ id: deviceId,
+ state: 'ready',
+ streamUrl: 'wss://stream.example.invalid/device',
+ streamToken: 'legacy-static',
+ });
+ const response = await f.app.request(`/api/v1/devices/${deviceId}`, {
+ headers: { Host: 'localhost:3000' },
+ });
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual({
+ id: '11111111-1111-4111-8111-111111111111',
+ state: 'ready',
+ streamUrl: 'wss://stream.example.invalid/device',
+ });
+ expect(f.requests).toHaveLength(1);
+ expect(f.requests[0].url).toBe(
+ 'https://api.example.invalid/v1/devices/11111111-1111-4111-8111-111111111111',
+ );
+});
+
+test('stream key helper POST mints once and returns only the flat no-store DTO', async () => {
+ // Literal public identity contract, with extra upstream data to verify the projection.
+ const f = upstream({
+ key: 'single-use-key',
+ keyId: 'key-id',
+ expiresAt: '2026-11-18T12:02:00.000Z',
+ extra: 'must-not-be-forwarded',
+ }, 201);
+ const response = await f.app.request(`/api/v1/devices/${deviceId}/stream-key`, {
+ method: 'POST',
+ headers: { Host: 'localhost:3000', 'Content-Type': 'application/json' },
+ body: JSON.stringify({ deviceId: 'ignored-device', ttlSeconds: 300, owner: 'ignored' }),
+ });
+ expect(response.status).toBe(201);
+ expect(response.headers.get('Cache-Control')).toBe('no-store');
+ expect(await response.json()).toEqual({
+ key: 'single-use-key',
+ keyId: 'key-id',
+ expiresAt: '2026-11-18T12:02:00.000Z',
+ });
+ expect(f.requests).toHaveLength(1);
+ expect(f.requests[0].method).toBe('POST');
+ expect(f.requests[0].url).toBe('https://api.example.invalid/v1/identity/stream-keys');
+ expect(await f.requests[0].json()).toEqual({
+ deviceId: '11111111-1111-4111-8111-111111111111', ttlSeconds: 120,
+ });
+ expect(f.requests[0].headers.get('Authorization')).toBe('Bearer test-only-placeholder');
+});
+
+test.each([403, 503])('stream key helper propagates refusal %i without retry or error detail', async (status) => {
+ const f = upstream({ message: 'sensitive upstream detail' }, status);
+ const log = spyOn(console, 'error').mockImplementation(() => {});
+ let response: Response;
+ try {
+ response = await f.app.request(`/api/v1/devices/${deviceId}/stream-key`, {
+ method: 'POST',
+ headers: { Host: 'localhost:3000' },
+ });
+ expect(log.mock.calls).toEqual([['stream_key_mint_failed', status]]);
+ } finally {
+ log.mockRestore();
+ }
+ expect(response.status).toBe(status);
+ expect(response.headers.get('Cache-Control')).toBe('no-store');
+ expect(await response.json()).toEqual({ error: 'stream_key_mint_failed' });
+ expect(f.requests).toHaveLength(1);
+});
+
+test('stream key helper rejects an invalid device id before calling upstream', async () => {
+ const f = upstream({ key: 'unused' }, 201);
+ const response = await f.app.request('/api/v1/devices/invalid.id/stream-key', {
+ method: 'POST',
+ headers: { Host: 'localhost:3000' },
+ });
+ expect(response.status).toBe(400);
+ expect(response.headers.get('Cache-Control')).toBe('no-store');
+ expect(await response.json()).toEqual({ error: 'invalid_id' });
+ expect(f.requests).toEqual([]);
+});
+
+test('stream key helper rejects a foreign Host before calling upstream', async () => {
+ const f = upstream({ key: 'unused' }, 201);
+ const response = await f.app.request(`/api/v1/devices/${deviceId}/stream-key`, {
+ method: 'POST',
+ headers: { Host: 'attacker.example:3000' },
+ });
+ expect(response.status).toBe(403);
+ expect(response.headers.get('Cache-Control')).toBe('no-store');
+ expect(await response.json()).toEqual({ error: 'forbidden' });
+ expect(f.requests).toEqual([]);
+});
+
+test('stream key helper rejects a foreign Origin before calling upstream', async () => {
+ const f = upstream({ key: 'unused' }, 201);
+ const response = await f.app.request(`/api/v1/devices/${deviceId}/stream-key`, {
+ method: 'POST',
+ headers: { Host: 'localhost:3000', Origin: 'http://attacker.example:3000' },
+ });
+ expect(response.status).toBe(403);
+ expect(response.headers.get('Cache-Control')).toBe('no-store');
+ expect(await response.json()).toEqual({ error: 'forbidden' });
+ expect(f.requests).toEqual([]);
+});
+
+test.each([
+ ['127.0.0.1:3000', 'http://127.0.0.1:3000'],
+ ['localhost:3000', 'http://localhost:3000'],
+ ['[::1]:3000', 'http://[::1]:3000'],
+])('stream key helper accepts same-origin requests for %s', async (host, origin) => {
+ const f = upstream({ key: 'single-use-key', keyId: 'key-id', expiresAt: '2026-11-18T12:02:00.000Z' }, 201);
+ const response = await f.app.request(`/api/v1/devices/${deviceId}/stream-key`, {
+ method: 'POST',
+ headers: { Host: host, Origin: origin },
+ });
+ expect(response.status).toBe(201);
+ expect(response.headers.get('Cache-Control')).toBe('no-store');
+ expect(await response.json()).toEqual({
+ key: 'single-use-key', keyId: 'key-id', expiresAt: '2026-11-18T12:02:00.000Z',
+ });
+ expect(f.requests).toHaveLength(1);
+});
+
+test('webhook validation is unaffected by foreign Host and Origin headers', async () => {
+ const f = upstream({});
+ const local = await f.app.request('/webhooks/mobilerun', {
+ method: 'POST',
+ headers: { Host: 'localhost:3000' },
+ body: '{}',
+ });
+ const tunneled = await f.app.request('/webhooks/mobilerun', {
+ method: 'POST',
+ headers: { Host: 'tunnel.example', Origin: 'https://sender.example' },
+ body: '{}',
+ });
+ expect([401, 500]).toContain(local.status);
+ expect(tunneled.status).toBe(local.status);
+ expect(await tunneled.json()).toEqual(await local.json());
+ expect(f.requests).toEqual([]);
+});
diff --git a/example/server.ts b/example/server.ts
index aeeab26..3199bb9 100644
--- a/example/server.ts
+++ b/example/server.ts
@@ -4,15 +4,16 @@
// Dev harness server for the @mobilerun/react example.
//
// The stream WebSocket is not proxied: the browser connects to the SDK-provided
-// streamUrl directly, and @mobilerun/react appends streamToken as ?token=.
+// streamUrl directly, and @mobilerun/react appends a fresh stream token as ?token=.
//
-// For SDK mode, this Bun + Hono server exposes one narrow endpoint that uses the
-// official SDK to retrieve streamUrl + streamToken without exposing a secret API key:
+// For SDK mode, this Bun + Hono server exposes narrow endpoints that uses the
+// official SDK to retrieve streamUrl and mint a stream token without exposing the parent API key:
//
// browser ββ(same-origin)βββΆ this server ββ(@mobilerun/sdk)βββΆ API
//
// β’ Serves the example UI (Bun bundles index.html + main.tsx).
-// β’ Handles GET /api/v1/devices/:deviceId via sdk.devices.get() (SDK object API).
+// β’ GET /api/v1/devices/:deviceId returns id/state/streamUrl only.
+// β’ POST /api/v1/devices/:deviceId/stream-key mints one single-use stream token per attempt.
// β’ Local use only: the server binds to 127.0.0.1 and its task routes and SSE
// route are unauthenticated by design. If you expose anything publicly (e.g. a
// tunnel for webhook testing), forward only /webhooks/mobilerun, never the
@@ -35,9 +36,13 @@ const API_KEY = process.env.MOBILERUN_API_KEY;
const UPSTREAM = process.env.MOBILERUN_API_URL?.replace(/\/+$/, '');
const WEBHOOK_SECRET = process.env.MOBILERUN_WEBHOOK_SECRET;
const PORT = Number(process.env.PORT ?? 3000);
-const sdk = API_KEY ? new MobilerunSDK({ apiKey: API_KEY, ...(UPSTREAM ? { baseURL: `${UPSTREAM}/v1` } : {}) }) : null;
+const sdk = API_KEY ? new MobilerunSDK({
+ apiKey: API_KEY,
+ logLevel: 'off',
+ ...(UPSTREAM ? { baseURL: `${UPSTREAM}/v1` } : {}),
+}) : null;
-if (!API_KEY) {
+if (import.meta.main && !API_KEY) {
console.warn(
'\n ! MOBILERUN_API_KEY is not set.\n' +
' Manual URL mode still works. SDK mode needs a key in .env or:\n' +
@@ -45,34 +50,105 @@ if (!API_KEY) {
);
}
-const app = new Hono<{ Bindings: Server }>();
+/** Local-only helpers. Production apps must authenticate callers and authorize each device. */
+export function createExampleApp(sdk: MobilerunSDK | null) {
+ const app = new Hono<{ Bindings: Server }>();
+
+ app.use('/api/*', async (c, next) => {
+ const host = c.req.header('Host');
+ const allowedHosts = [`127.0.0.1:${PORT}`, `localhost:${PORT}`, `[::1]:${PORT}`];
+ const isLoopbackHost = host !== undefined && allowedHosts.includes(host);
+ const origin = c.req.header('Origin');
+ const isSameOrigin = origin === undefined || origin === `http://${host}`;
+ const isAllowed = isLoopbackHost && isSameOrigin;
+ if (!isAllowed) {
+ c.header('Cache-Control', 'no-store');
+ return c.json({ error: 'forbidden' }, 403);
+ }
+ await next();
+ });
-app.get('/api/v1/devices/:deviceId', async (c) => {
- if (!sdk) {
- return c.json({ error: 'missing_api_key', detail: 'Set MOBILERUN_API_KEY to use SDK mode.' }, 500);
- }
+ app.get('/api/v1/devices/:deviceId', async (c) => {
+ if (!sdk) {
+ return c.json({ error: 'missing_api_key', detail: 'Set MOBILERUN_API_KEY to use SDK mode.' }, 500);
+ }
- try {
- const device = await sdk.devices.get(c.req.param('deviceId'));
- return c.json({
- id: device.info?.id ?? null,
- state: device.info?.state ?? null,
- streamUrl: device.info?.streamUrl ?? null,
- streamToken: device.info?.streamToken ?? null,
- });
- } catch (err) {
- return upstreamFailure(c, 'device_retrieve_failed', err);
- }
-});
+ try {
+ const device = await sdk.devices.get(c.req.param('deviceId'));
+ return c.json({
+ id: device.info?.id ?? null,
+ state: device.info?.state ?? null,
+ streamUrl: device.info?.streamUrl ?? null,
+ });
+ } catch (err) {
+ return upstreamFailure(c, 'device_retrieve_failed', err);
+ }
+ });
+
+ app.post('/api/v1/devices/:deviceId/stream-key', async (c) => {
+ c.header('Cache-Control', 'no-store');
+ const deviceId = c.req.param('deviceId');
+ if (!ID_PATTERN.test(deviceId)) return c.json({ error: 'invalid_id' }, 400);
+ if (!sdk) {
+ return c.json({ error: 'missing_api_key', detail: 'Set MOBILERUN_API_KEY to use SDK mode.' }, 500);
+ }
+ try {
+ const minted = await sdk.streamTokens.create(
+ { deviceId, ttlSeconds: 120 },
+ { maxRetries: 0 },
+ );
+ const { key, keyId, expiresAt } = minted;
+ return c.json({ key, keyId, expiresAt }, 201);
+ } catch (err) {
+ return upstreamFailure(c, 'stream_key_mint_failed', err, true);
+ }
+ });
+
+ app.post('/webhooks/mobilerun', async (c) => {
+ if (!WEBHOOK_SECRET) return c.json({ error: 'missing_webhook_secret' }, 500);
+ if (Number(c.req.header('Content-Length') ?? 0) > MAX_WEBHOOK_BODY_BYTES) {
+ return c.json({ error: 'payload_too_large' }, 413);
+ }
+ // Raw bytes exactly as received; the SDK verifies before parsing.
+ const bytes = new Uint8Array(await c.req.arrayBuffer());
+ let event: WebhookEvent;
+ try {
+ event = (await verifyWebhook({
+ body: bytes,
+ headers: c.req.raw.headers,
+ secret: WEBHOOK_SECRET,
+ })) as WebhookEvent;
+ } catch (err) {
+ if (err instanceof WebhookVerificationError) {
+ if (err.reason === 'invalid_json') return c.json({ error: 'invalid_json' }, 400);
+ return c.json({ error: 'invalid_signature' }, 401);
+ }
+ throw err;
+ }
+ const taskId = event?.data?.taskId;
+ if (typeof event?.type === 'string' && APPROVAL_EVENTS.has(event.type) && typeof taskId === 'string') {
+ for (const send of subscribers) send({ taskId });
+ }
+ return c.body(null, 204);
+ });
+ return app;
+}
+
+const app = createExampleApp(sdk);
const ID_PATTERN = /^[A-Za-z0-9_-]+$/;
const MAX_WEBHOOK_BODY_BYTES = 1024 * 1024;
/** Maps an upstream API error to a response, passing 4xx/5xx through (404/409 let the UI refetch). */
-function upstreamFailure(c: Context, error: string, err: unknown) {
+function upstreamFailure(c: Context, error: string, err: unknown, redact = false) {
const { status, message } = err as { status?: number; message?: string };
+ const isUpstreamError = status && status >= 400 && status < 600;
+ const code = (isUpstreamError ? status : 502) as ContentfulStatusCode;
+ if (redact) {
+ console.error(error, code);
+ return c.json({ error }, code);
+ }
console.error(`β ${error}`, JSON.stringify(c.req.param()), message ?? String(err));
- const code = (status && status >= 400 && status < 600 ? status : 502) as ContentfulStatusCode;
return c.json({ error, detail: message ?? String(err) }, code);
}
@@ -142,43 +218,21 @@ type WebhookEvent = { type?: unknown; data?: { taskId?: unknown } } | null;
const APPROVAL_EVENTS = new Set(['task.run.approval_requested', 'task.run.approval_resolved']);
-app.post('/webhooks/mobilerun', async (c) => {
- if (!WEBHOOK_SECRET) return c.json({ error: 'missing_webhook_secret' }, 500);
- if (Number(c.req.header('Content-Length') ?? 0) > MAX_WEBHOOK_BODY_BYTES) {
- return c.json({ error: 'payload_too_large' }, 413);
- }
- // Raw bytes exactly as received; the SDK verifies before parsing.
- const bytes = new Uint8Array(await c.req.arrayBuffer());
- let event: WebhookEvent;
- try {
- event = (await verifyWebhook({
- body: bytes,
- headers: c.req.raw.headers,
- secret: WEBHOOK_SECRET,
- })) as WebhookEvent;
- } catch (err) {
- if (err instanceof WebhookVerificationError) {
- if (err.reason === 'invalid_json') return c.json({ error: 'invalid_json' }, 400);
- return c.json({ error: 'invalid_signature' }, 401);
- }
- throw err;
- }
- const taskId = event?.data?.taskId;
- if (typeof event?.type === 'string' && APPROVAL_EVENTS.has(event.type) && typeof taskId === 'string') {
- for (const send of subscribers) send({ taskId });
- }
- return c.body(null, 204);
-});
-
-Bun.serve({
- hostname: '127.0.0.1',
- port: PORT,
- routes: { '/': index }, // Bun bundles + serves the React UI and its assets
- development: { hmr: true, console: true },
- fetch: app.fetch,
-});
+if (import.meta.main) {
+ Bun.serve({
+ hostname: '127.0.0.1',
+ port: PORT,
+ routes: { '/': index }, // Bun bundles + serves the React UI and its assets
+ development: { hmr: true, console: true },
+ fetch: app.fetch,
+ });
-console.log(`\n βΈ @mobilerun/react dev harness http://localhost:${PORT}`);
-console.log(` βΈ SDK helper GET /api/v1/devices/:id β ${sdk?.api.baseURL ?? 'https://api.mobilerun.ai/v1'}/devices/:id`);
-console.log(' ⸠approvals GET/POST /api/v1/tasks/:id⦠· POST /webhooks/mobilerun · GET /api/v1/events');
-console.log(' βΈ stream WS direct browser connection using ?token=\n');
+ console.log(`\n βΈ @mobilerun/react dev harness http://localhost:${PORT}`);
+ const upstreamUrl = sdk?.api.baseURL ?? 'https://api.mobilerun.ai/v1';
+ console.log(` βΈ SDK helper GET /api/v1/devices/:id β ${upstreamUrl}/devices/:id`);
+ console.log(' βΈ stream token POST /api/v1/devices/:id/stream-key');
+ console.log(
+ ' ⸠approvals GET/POST /api/v1/tasks/:id⦠· POST /webhooks/mobilerun · GET /api/v1/events',
+ );
+ console.log(' βΈ stream WS direct browser connection using ?token=\n');
+}
diff --git a/package.json b/package.json
index d9c69a9..41d28d8 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "@mobilerun/react",
- "version": "0.3.0",
+ "version": "0.4.0",
"description": "React components for embedding Mobilerun's native device streaming (WebRTC + scrcpy) and task approvals β plug-and-play with @mobilerun/sdk.",
"license": "Apache-2.0",
"author": "Mobilerun ",
@@ -64,7 +64,7 @@
"react-dom": "^18.0.0 || ^19.0.0"
},
"devDependencies": {
- "@mobilerun/sdk": "^6.2.1",
+ "@mobilerun/sdk": "^6.3.0",
"@tailwindcss/cli": "^4.1.5",
"@types/bun": "1.4.3",
"@types/node": "^24",
diff --git a/skills/mobilerun-device-stream/SKILL.md b/skills/mobilerun-device-stream/SKILL.md
new file mode 100644
index 0000000..03fc96e
--- /dev/null
+++ b/skills/mobilerun-device-stream/SKILL.md
@@ -0,0 +1,209 @@
+---
+name: mobilerun-device-stream
+description: Use when integrating a live Mobilerun device into a React partner app with server-minted stream tokens, reconnect handling, labels and theming.
+---
+
+# Mobilerun device stream for React
+
+## When to use
+
+Use `@mobilerun/react` to embed live WebRTC video and device control in a React 18 or 19 app.
+Install `@mobilerun/react`, its peer `@mobilerun/sdk`, `react` and `react-dom`.
+Use a browser with WebRTC. Keep device authorization and token minting on your backend.
+
+## Backend: mint one token per connect
+
+On your Node backend, use `client.streamTokens.create({ deviceId, ttlSeconds, allowedOrigins })`
+from `@mobilerun/sdk` 6.3.0 or later. The client reads the server's `MOBILERUN_API_KEY`; the method
+returns `{ key, keyId, expiresAt }`. `ttlSeconds` defaults to 120 seconds (range 60β300).
+Tokens start with `dr_st_`; `dr_sk_` can appear during the prefix transition. Treat both as opaque.
+Each token is single-use. `allowedOrigins` binds browser use to the listed sites, for example
+`['https://partner.example']`; configure the list on the server.
+
+The following server-only helper uses `MobilerunSDK` from `@mobilerun/sdk` 6.3.0+.
+Register it behind your application's authenticated
+`POST /api/v1/devices/:id/stream-key` route. **Before calling it, authorize the caller for that
+device.** This helper is not an authentication implementation.
+
+```ts
+import { MobilerunSDK } from '@mobilerun/sdk';
+
+const client = new MobilerunSDK({ logLevel: 'off' }); // reads MOBILERUN_API_KEY on the Node server
+
+export async function mintStreamToken(deviceId: string): Promise {
+ const { key, keyId, expiresAt } = await client.streamTokens.create({
+ deviceId,
+ ttlSeconds: 120,
+ allowedOrigins: ['https://partner.example'], // replace with your browser app's origin
+ }, { maxRetries: 0 });
+ return Response.json({ key, keyId, expiresAt }, {
+ status: 201,
+ headers: { 'Cache-Control': 'no-store' },
+ });
+}
+```
+
+Revoke a token on the server with `await client.streamTokens.delete(keyId)`.
+
+REST fallback: `POST /v1/identity/stream-keys` with the same body, or `DELETE /v1/identity/stream-keys/{keyId}`, authenticated with your server-held API key.
+
+Handle mint errors in your route without exposing upstream credential details.
+
+## Client: a fresh token for every connection
+
+Supply the device's `streamUrl` obtained through your authorized backend. Its usual form is
+`wss://api.mobilerun.ai/v1/devices/{deviceId}/stream`; the component appends `?token=` itself.
+The application route below is your own backend route, not a React SDK endpoint.
+
+```tsx
+'use client';
+
+import { useCallback } from 'react';
+import { DeviceStream } from '@mobilerun/react';
+import '@mobilerun/react/styles.css';
+
+export function DevicePanel({ deviceId, streamUrl }: {
+ deviceId: string;
+ streamUrl: string;
+}) {
+ const tokenProvider = useCallback(async (): Promise => {
+ const res = await fetch(`/api/v1/devices/${encodeURIComponent(deviceId)}/stream-key`, {
+ method: 'POST',
+ cache: 'no-store',
+ });
+ if (!res.ok) throw new Error('Stream token request failed');
+ const { key } = await res.json();
+ if (typeof key !== 'string' || !key) throw new Error('Missing stream token');
+ return key;
+ }, [deviceId]);
+
+ return (
+
+ {
+ // Fixed SDK text; never include tokens or connection URLs in diagnostics.
+ console.warn('Device stream', { reason, message, attempt, final });
+ }}
+ labels={{ connecting: 'Startingβ¦', disconnected: 'Reconnecting',
+ unavailable: 'Phone unavailable', retry: 'Try again' }}
+ />
+
+ );
+}
+```
+
+`tokenProvider: () => Promise` runs before every WebSocket connect attempt, including
+reconnects. Never cache, memoize the returned token, or reuse it; memoizing the callback is fine.
+A throw, rejection, empty result or 10-second timeout fails the attempt and uses normal backoff.
+If both credentials are supplied, `tokenProvider` wins without falling back to `streamToken`.
+The component handles bounded retries; do not mint through `onStreamHealed`, which is not per attempt.
+While offline, automatic attempts pause; the Retry button can request a fresh attempt.
+
+## Errors and recovery
+
+`onError` receives the exported `StreamError` shape `{ reason, message, attempt, final }`.
+`message` is fixed SDK text; `attempt` counts consecutive failures from 1.
+`final: true` means automatic retries stopped; keep the component's Retry button available.
+
+| `reason` (`StreamErrorReason`) | Meaning and action |
+| --- | --- |
+| `credentials_unavailable` | Provider threw, rejected, returned an empty token or exceeded 10 s. Check your backend route, caller session and mint response; let normal backoff run. |
+| `connection_refused` | Socket closed before opening. Check fresh minting, device ID, expiry, revocation and allowed origin. React cannot inspect the upgrade HTTP status, so it does not report `token_rejected`. |
+| `disconnected` | An open session dropped, including the 30-minute server session cap. Let the SDK reconnect with a newly minted token; check network/device state if persistent. |
+| `device_unavailable` | Reserved for a server report of an offline/not-ready device. The current signaling protocol has no such message, so React does not emit it yet. Fetch device state through your backend when diagnosing availability. |
+| `unknown` | Other failure, such as a handshake timeout. Check connectivity and device state, then retry. |
+
+## Labels and theming
+
+`labels?: Partial` accepts the following connection keys and the publish keys below, all optional:
+
+| Key | English default |
+| --- | --- |
+| `connecting` | `connecting` |
+| `disconnected` | `reconnecting` (retry counters such as ` (1/6)` are appended) |
+| `unavailable` | `device stream unavailable` |
+| `retry` | `Retry` |
+
+`placeholderLabel` overrides `connecting` while waiting for a URL/connection; the reconnect label
+takes precedence after a drop. Use `className` on `DeviceStream` for host styling and a parent with
+explicit dimensions. Import `@mobilerun/react/styles.css` once.
+
+Set variables on `.mobilerun-device-stream` or an ancestor:
+`--mr-background`, `--mr-foreground`, `--mr-card`, `--mr-card-foreground`, `--mr-muted`,
+`--mr-muted-foreground`, `--mr-border`, `--mr-ring`, `--mr-primary`, `--mr-primary-foreground`,
+`--mr-accent`, `--mr-accent-foreground`, `--mr-destructive`.
+
+```css
+.mobilerun-device-stream {
+ --mr-primary: oklch(0.55 0.18 268);
+ --mr-primary-foreground: white;
+ --mr-background: oklch(0.985 0.004 85);
+}
+```
+
+Add `.dark` on an ancestor or the root for bundled dark defaults. Colors resolve from `--mr-*`,
+then legacy unprefixed variables (supported for one more minor release), then bundled defaults.
+The package does not define generic variables on `:root`. Keep retry text/button contrast at WCAG AA.
+
+## Microphone and camera publishing
+
+Get the specific device's `GET /v1/devices/{deviceId}/capabilities` response through the authorized
+backend and pass its `.capabilities` as `publishCapabilities`. A stream token cannot call that API.
+`microphoneInjection: true` and `mediaInjectionTransport: 'direct'` enable the floating publish pill;
+camera additionally requires `cameraInjection: true` and a compatible local H.264 encoder.
+Capabilities describe support; the server decides admission on every start, independently of `hasControl`.
+
+Use a `DeviceStreamHandle` ref for `startPublish({ audio: true, video?: boolean })`,
+`stopPublish()` and `getPublishState()`. Start resolves only after server `active` and successful
+track attachment. Audio is required. To change camera mode, stop then start. Set
+`hidePublishControls` to use your own controls. Observe `onPublishStateChange` separately from
+connection state; `onError` publish events have `operation: 'publish'`, the viewer attempt index,
+`final: true`, and optional `mediaSessionId`, `detail`, `serverReason`. Handle rejected starts with
+`PublishError.reason`. `forbidden` β `publish_not_allowed`; silence after 5 s β
+`publish_unsupported`; acceptance without active after 30 s (including the permission prompt) β `publish_timeout`. There is no retry.
+
+Use HTTPS (or localhost), permit microphone/camera in Permissions Policy and set iframe
+`allow="microphone; camera"` when embedding. Capture only starts after an explicit action is accepted by the device and is stopped
+on stop, pagehide, disconnection or unmount. Reconnect never resumes it. Receiving audio mute
+is independent. Arriving or changed capabilities automatically renew the viewer with a fresh token; equivalent
+snapshots do not reconnect. Camera controls follow verified first-offer reservations. No privileged API key belongs in the browser.
+
+Publish labels and English defaults: `microphone` (βMicrophoneβ), `camera` (βCameraβ),
+`stopMicrophone` (βStop microphoneβ), `stopCamera` (βStop cameraβ), `publishStarting` (βStarting inputsβ), `publishPermissionDenied` (βMicrophone or camera permission deniedβ),
+`publishNotAllowed` (βPublishing is not allowedβ), `publishFailed` (βCould not publish inputsβ).
+Only pill buttons receive input; its background/status text pass through. It fades to 50% after
+3 s and restores on nearby pointer/touch input. Status text stays above it. A viewer replacement or
+throwing start/stop socket write emits `disconnected` once and releases capture.
+Style the pill with existing card/border tokens and `--mr-publish-live` / `--mr-publish-live-foreground`.
+See [Publishing inputs](../../docs/publish.md) for the full API and failure details.
+
+## Security rules
+
+- Never ship `MOBILERUN_API_KEY` to a client or use it as a stream credential.
+- Authenticate callers and authorize the device before minting or returning device metadata.
+ Use a server-configured API target and origin list, never an arbitrary browser-provided upstream URL.
+- A stream token grants view and control of one device. It can be redeemed until first connect or
+ expiry; consuming it does not end the admitted session when the mint TTL elapses.
+ `hasControl={false}` is only a UI input overlay, not a server-enforced view-only permission.
+- Never log tokens, store them in local storage, cache mint responses or expose `?token=` URLs in logs.
+ `expiresAt` is metadata, not a client-side authorization check.
+- Static `streamToken` is deprecated, only for existing integrations until retired. It warns once
+ per mount and reuses the same value on reconnect. A single-use token passed statically fails on
+ reuse; migrate to `tokenProvider`.
+
+## Troubleshooting
+
+- **401 at connect:** the token may be used, expired, revoked or bound to the wrong origin/device.
+ Mint a new token for every attempt and check the server-configured `allowedOrigins` against the
+ browser origin. React surfaces this as `connection_refused`, not an HTTP status.
+- **422 on mint:** read the response's `issues` on the server; correct the invalid request fields
+ (including TTL/origin format) before retrying. Do not expose credential details to the browser.
+- **Provider failures:** check the same-origin backend route, application authentication, response
+ status and nonempty `key`; keep it within 10 seconds. Never return a previously minted token as
+ a fallback. Look for `credentials_unavailable` and `final` in `onError`.
+
+For full route/hook examples see [Stream tokens](../../docs/stream-tokens.md);
+for styling see [Components and styling](../../docs/default-ui.md).
diff --git a/src/components/device-stream.test.tsx b/src/components/device-stream.test.tsx
new file mode 100644
index 0000000..79ec5a5
--- /dev/null
+++ b/src/components/device-stream.test.tsx
@@ -0,0 +1,60 @@
+// Copyright 2026 Mobilerun
+// SPDX-License-Identifier: Apache-2.0
+
+import { describe, expect, test } from 'bun:test';
+import { renderToStaticMarkup } from 'react-dom/server';
+import { resolveDeviceStreamLabels } from '../lib/stream-error';
+import { DeviceStream } from './device-stream';
+import { StreamUnavailable } from './stream-unavailable';
+
+const custom = { unavailable: 'Telefon nicht erreichbar', retry: 'Nochmal', connecting: 'Verbinde', disconnected: 'Getrennt' };
+
+describe('labels', () => {
+ test('defaults stay English and an undefined override falls back', () => {
+ expect(resolveDeviceStreamLabels()).toEqual({
+ connecting: 'connecting',
+ disconnected: 'reconnecting',
+ unavailable: 'device stream unavailable',
+ retry: 'Retry',
+ microphone: 'Microphone',
+ camera: 'Camera',
+ stopMicrophone: 'Stop microphone',
+ stopCamera: 'Stop camera',
+ publishStarting: 'Starting inputs',
+ publishPermissionDenied: 'Microphone or camera permission denied',
+ publishNotAllowed: 'Publishing is not allowed',
+ publishFailed: 'Could not publish inputs',
+ });
+ expect(resolveDeviceStreamLabels({ retry: undefined, unavailable: 'x' })).toMatchObject({ retry: 'Retry', unavailable: 'x' });
+ });
+
+ test('the idle and the connecting pill come from labels', () => {
+ const idle = renderToStaticMarkup();
+ expect(idle).toContain('Verbinde');
+ expect(idle).not.toContain('>connecting<');
+ const connecting = renderToStaticMarkup( 'k'} labels={custom} />);
+ expect(connecting).toContain('Verbinde');
+ expect(connecting).not.toContain('>connecting<');
+ });
+
+ test('an explicit placeholderLabel still wins over labels.connecting', () => {
+ expect(renderToStaticMarkup()).toContain('booting');
+ });
+
+ test('the unavailable view renders both strings from labels with no English left', () => {
+ const html = renderToStaticMarkup( {}} />);
+ expect(html).toContain('Telefon nicht erreichbar');
+ expect(html).toContain('Nochmal');
+ expect(html).not.toContain('Retry');
+ expect(html).not.toContain('unavailable');
+ });
+
+ test('the Retry button sets a foreground color of its own', () => {
+ const html = renderToStaticMarkup( {}} />);
+ expect(html).toMatch(/