Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
@@ -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
Expand Down
46 changes: 46 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -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).
393 changes: 120 additions & 273 deletions README.md

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions SECURITY.md
Original file line number Diff line number Diff line change
@@ -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.
4 changes: 2 additions & 2 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

52 changes: 52 additions & 0 deletions docs/default-ui.md
Original file line number Diff line number Diff line change
@@ -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:

- **`<DeviceStream />`** — 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.
- **`<TaskApproval />`** + **`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).
- **`<NavigationBar />`**, **`<StreamStatusPill />`**, **`<RemoteControl />`** — 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).
125 changes: 125 additions & 0 deletions docs/publish.md
Original file line number Diff line number Diff line change
@@ -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<string>;
capabilities: DevicePublishCapabilities;
}) {
const stream = useRef<DeviceStreamHandle>(null);
return <div style={{ width: 360, height: 780 }}>
<DeviceStream ref={stream} streamUrl={streamUrl} tokenProvider={tokenProvider} hasControl
publishCapabilities={capabilities}
onPublishStateChange={state => console.info('Publish phase', state.phase)}
onError={error => {
if (error.operation === 'publish') console.info(error.reason, error.detail);
}}
/>
</div>;
}
```

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.
1 change: 1 addition & 0 deletions docs/stream-keys.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[Stream tokens guide](stream-tokens.md)
Loading
Loading