Overview

The phone stream relay lets any surface (ai.allternit.com phone layout, m.allternit.com PWA) view and control a linked Android through the account’s Desktop app. It mirrors the computer-lane VNC proxy minus VNC: the payload is the scrcpy H.264 stream (binary WebSocket frames) and JSON control envelopes (text frames), and the relay treats both as opaque — it never parses scrcpy, video, or control semantics. Two WebSockets plus two HTTPS endpoints make the plane:
Served by the node’s allternit-api (the Desktop’s gateway, default http://127.0.0.1:18013 in dev; the installed Desktop owns 8013). Device identity persists in cloud PG (registered_phones); the online registry is in-memory in the serving api instance, so online means “this node’s Desktop is attached”.The Desktop attaches its phone-link session to its own allternit-api, not to api.allternit.com: that host is the cloud control plane (allternit-cloud-api), which has no /ws/phone-link or /ws/phones routes and answers them 404. From ai.allternit.com and the m.allternit.com PWA, the HTTPS calls reach the node through the cloud data-plane fallback, and the stream socket goes through the runtime socket relay (POST /api/v1/runtime-devices/:id/socket-ticket, then /api/v1/runtime-devices/:id/socket), the same path the computer VNC viewer uses. Dev override for the Desktop side: ALLTERNIT_PHONE_LINK_API_URL=http://127.0.0.1:18013.

GET /api/v1/phones

online is true while a phone-link session for (account, serial) is attached to this api instance. A linked phone whose Desktop is asleep stays listed with online: false.

POST /api/v1/phones/:serial/ws-token

Body (both shapes accepted; readOnly is the canonical one):
Minting requires the phone row to exist for the caller’s account and a live phone-link session for it. Errors: 404 unknown phone, 503 desktop offline or registry unreachable. Response:
The token is HS256-signed (same secret as the computer ws tokens, ALLTERNIT_DESKTOP_WS_SECRET), TTL 300 s, claims:
readOnly defaults to true. A full-control token (readOnly: false) injects input into a personal phone, so minting one requires the ACI confirmation grant (confirmation_required denial with an approval_id; approve and retry with ?approval_id=) — the same explicit-request pattern as a full-control computer VNC token.

POST /api/v1/phones/:serial/viewer-token

Same checks as ws-token (phone row for the account, attached session), no ACI grant: the token is always view-only. Answers { "token", "expiresInSec": 600, "readOnly": true }. The stream route accepts purpose phone_view and forces it read-only whatever the claim says. cloud-api calls it for POST /v1/phones/:serial/live (Phones), keeps the token, and serves the viewer page at /phone-live/:view and its socket at /phone-live/:view/socket, which it tunnels to /ws/phones/:serial/stream?token=… over the runtime relay socket (a fresh 30 s socket ticket per connect).

WS /ws/phones/:serial/stream?token=…

Public mount: the HMAC token IS the credential (like the computer VNC route). If the browser also carries a same-origin Clerk session it must match the token’s sub. The token’s serial and purpose are enforced at upgrade.
  • Frames are passed through untouched, both directions, order preserved per direction.
  • Read-only tokens receive everything but the browser→desktop direction is dropped at the pipe (the payload is opaque, so read-only is enforced by not forwarding).
  • When the token crosses expiry mid-stream the relay sends a JSON text frame {"type":"end","reason":"token_expired"} and closes with code 4401. The remaining lifetime is computed at upgrade.
  • When the Desktop detaches, attached and waiting viewers get {"type":"end","reason":"desktop_offline"} (close code 1011). A viewer that connects while no session is attached waits (up to the token’s lifetime) for the Desktop to appear.
  • Backpressure: bounded channels both ways; a stalled side loses binary (video) frames first, control (text) frames wait up to 5 s.

WS /ws/phone-link/session

The Desktop’s session socket, one per streamed phone (scrcpy is one device per process). Authenticated with the Desktop credential (x-allternit-desktop-access-token + user headers); the account is resolved from that credential.
  1. Hello. The first frame (10 s window) must be:
    Every hello phone is upserted in cloud PG (registered_phones, last_seen_at touched — the same upsert re-runs at disconnect) and marked online. A malformed hello ends the socket with {"type":"end","reason":"invalid_hello"} (1011).
  2. Streaming. One active stream per socket: the socket’s desktop→browser output routes to viewers of a single serial at a time. A socket may hello several phones (they all register online), but to stream a phone concurrently the Desktop opens another socket. Relay-level notifications on the session socket tell the Desktop when to start/stop scrcpy:
    Everything else on the socket is the opaque data plane in both directions.
  3. Heartbeat. The relay pings every 30 s; a peer silent for 90 s is treated as gone and the session ends (phones marked offline, viewers get desktop_offline).

iPhones with the Allternit app

The App Store app (route iphone-app-store, serial app: plus the phone id) reaches the node without a Desktop phone-link session. User guide: Your iPhone with the Allternit app.
  • Listing. GET /api/v1/phones includes the app phones with route: "iphone-app-store" and screen: true while the broadcast extension’s ingest socket is open.
  • Pairing (WS /api/v1/phones/app/pair?phone=…). After the app’s hello the node answers {"type":"pending","pub"}, raises phone_app.pair_request {phoneId, name, model, code} on the runtime events feed, and Desktop shows the name and 6-digit code with Approve and Deny. Desktop answers with POST /api/v1/phones/app/pair/:phoneId/decision {"approve": bool} (desktop credential, loopback).
  • Viewers. The same ws-token and /ws/phones/:serial/stream as above. Binary frames are the broadcast’s plaintext iCTRL packets, one per frame: u8 type | u32 big-endian length | payload, with 0 status, 1 config ({width, height, scale, rotation}), 2 one H.264 Annex-B access unit, 3 ended, 4 audio config (AAC), 5 one AAC frame. Viewers mint read-only tokens; input frames are ignored. Taps on other apps go through a Phone Use route instead (iPhone Mirroring, or a Bluetooth keyboard from the Mac, an Android phone, a second iPhone or iPad, or the USB Agent board).
  • The app’s browser. POST /api/v1/phones/app/:id/rpc {method, params} (desktop credential) forwards to the app’s control socket. Methods: web.open {url}, web.snapshot ({url, title, elements, jpegBase64, viewport}), web.click {ref}, web.type {ref, text, submit?}, web.scroll {dy} ({ok, scrollY}), web.back (adds wentBack), web.wait {ms} and screen.prompt ({shown, live}). Errors: 409 app_not_open when the app isn’t open, and the app’s own codes stopped_by_user, browser_not_open, stale_ref, not_editable, bad_params, unknown_method, script_error, internal. Desktop exposes these to bots as phone.web.* and phone.screen.request.
Desktop code: surfaces/allternit-desktop/src/main/phone-app-store.ts (the lane, viewer session and node client) and phone-app-still.ts (screenshots: the last keyframe decoded with Chromium’s WebCodecs in a hidden window).

Cloud side

allternit-cloud-api holds the only persistence, one row per (account, serial):
  • PUT /api/v1/runtime-devices/me/registered-phones — body { "phones": [{ "serial", "model"?, "name"? }] }, upserts rows for the device’s account and touches last_seen_at. Runtime device credential only.
  • GET /api/v1/runtime-devices/me/registered-phones — the account’s rows.
No screen or input data is ever persisted or logged — only identity and timestamps.

iPhone via the App Store app (app: serials)

An iPhone running the Allternit iOS app joins the same plane as app:<phoneId> (route iphone-app-store). The phone only dials out: the app and its ReplayKit broadcast extension reach the node through the cloud runtime socket relay, and the node feeds the opened packets to the same viewer path as an Android. This round is screen only plus the app’s own ACI browser; taps on native apps are not supported.

Cloud: app phone keys and socket tickets

The broadcast extension cannot refresh a Clerk session, so pairing hands out an app phone key (32 random bytes, returned once as 64 lowercase hex characters). The cloud stores only its SHA-256 (app_phones, pg migration 110). The ticket path must be exactly /api/v1/phones/app/pair?phone=<phoneId>, /api/v1/phones/app/ingest?phone=<phoneId> or /api/v1/phones/app/control?phone=<phoneId> with the lowercase phone id; anything else is 403. An unknown, revoked or wrong key is 401, and a runtime that was removed is 404: the phone forgets its pairing on either. 403 and 503 (runtime offline or waking) are temporary. The phone then opens wss://api.allternit.com + socketPath (the existing /api/v1/runtime-devices/:id/socket?ticket=… relay socket) within 30 seconds. The route sits under the public rate limiter and touches last_seen_at.

Node sockets (relayed)

All three arrive through the Desktop relay with the Desktop’s credential, so the account is the Desktop’s signed-in account. WS /api/v1/phones/app/pair?phone=<phoneId> — plaintext JSON.
  1. App → {"type":"hello","phoneId","name","model","pub":"<X25519 public key, base64>"}.
  2. Node → {"type":"pending","pub":"<node X25519 public key, base64>"}. Both screens now show the code, and the Desktop’s /api/v1/events/stream gets the SSE event phone_app.pair_request with data { "type": "phone_app.pair_request", "phoneId", "serial", "name", "model", "code", "expiresAt" }.
  3. The person approves or denies on the Desktop within 120 s. Node → {"type":"approved","pub"} or {"type":"denied","reason"} (denied, timeout, replaced, bad_key, store_failed). The Desktop gets phone_app.pair_resolved { "phoneId", "approved", "reason"? }.
Code = the first 4 bytes of SHA-256(appPub ‖ nodePub) as a big-endian integer, mod 1 000 000, zero-padded to 6 digits. Session key = HKDF-SHA256(ikm = X25519 shared secret, salt = the lowercase phone id as UTF-8, info = allternit-app-phone v1, 32 bytes). The node keeps it sealed in its vault and registers app:<phoneId> in registered_phones. WS /api/v1/phones/app/ingest?phone=<phoneId> — the broadcast extension.
  • Binary frames, one iCTRL broadcast packet each (packet types 0–5). The frame bytes are that packet’s envelope JSON (below) as UTF-8; its plaintext is the raw packet. The node opens each and sends the plaintext packet to viewers of app:<phoneId> as a binary frame.
  • Node → extension text frames (plaintext): {"type":"resume"} when the first viewer attaches, {"type":"keyframe"} when another viewer joins, {"type":"pause"} when the last leaves. The extension starts paused.
  • The phone is online while this socket is open. Fifty packets in a row that fail to open end the socket with {"type":"end","reason":"bad_envelope"} and close code 4401 (pair again).
WS /api/v1/phones/app/control?phone=<phoneId> — the foreground app, sealed envelopes as text frames both ways. Node → app: {"id","method","params"}. App → node: {"id","result"}, {"id","error":{"code","message"}} or {"type":"state","foreground","browserOpen"}. Methods: web.open {url}, web.snapshot {}, web.click {ref}, web.type {ref,text,submit?}, web.scroll {dy}, web.back {}, web.wait {ms} (at most 10 000), and screen.prompt (show the broadcast picker). Ingest and control from a phone with no stored key get {"type":"end","reason":"not_paired"} and close code 4401.

Envelope (iCTRL protocol v1)

Byte-compatible with iCTRL’s SecureEnvelope.swift request construction, used in both directions (the node never uses iCTRL’s response form). With K the session key and a fresh 16-byte nonce per message: tok = first 4 bytes of SHA-256(K); K_mac = HMAC(K, "ictrl-v1|mac" ‖ nonce); K_enc = HMAC(K, "ictrl-v1|enc-req" ‖ nonce); ct = plaintext XOR the HMAC-SHA256 counter keystream (HMAC(K_enc, nonce ‖ be32(i))); tag = HMAC(K_mac, "v1" ‖ tok4 ‖ be64(ts) ‖ nonce ‖ ct).
The node checks the tag first, then |ts − now| ≤ 120 s, then refuses a nonce already seen inside that window. One window per phone is shared by ingest, control and the nonces the node itself seals, so a node message reflected back at the node is refused as a replay.

Desktop routes (loopback only)

These need the Desktop access token and refuse relayed requests (x-allternit-relayed) with 403 desktop_only. Viewers are unchanged: POST /api/v1/phones/app:<phoneId>/ws-token, then /ws/phones/app:<phoneId>/stream. In GET /api/v1/phones an app phone row also carries "route": "iphone-app-store", "screen": true, "appOpen", "foreground" and "browserOpen".

Android via the Allternit app (app: serials, route android-app)

An Android phone running the Allternit app uses the same app-phone lane, with the phone dialing out and sending the same sealed iCTRL packets (CONFIG, FRAME, ENDED) from MediaProjection and a MediaCodec H.264 Annex-B encoder. The cloud adds a one-time claim, so the phone needs no Desktop.
  • Claim. POST /api/v1/app-phones/:phoneId/claim (Clerk owner) returns a one-time 8 character code, held in memory for 120 s, single use. POST /api/v1/app-phones/claim/redeem trades the code for the app phone key. See Phones API.
  • Pairing. The pair hello carries platform (ios by default, or android), stored with the phone and included in phone_app.pair_request. GET /api/v1/phones/app/pair/pending and POST /api/v1/phones/app/pair/:phoneId/decision accept the local Desktop, or a request relayed by cloud-api (signed with the runtime relay key plus x-allternit-owner) whose owner is the runtime’s paired owner and the caller. They stay refused for any other relayed caller (403 desktop_only).
  • Listing. GET /api/v1/phones rows for an Android app phone carry platform: "android", route: "android-app", canTap, screen and consent (granted, needed, denied or unknown).
  • Viewers. Same ws-token and /ws/phones/app:<phoneId>/stream. A viewer waiting on an Android phone with no ingest socket makes the node send screen_request on the phone’s control socket (throttled to once per 10 s); tokens are minted for such a phone so the viewer can wait. Full-control viewer input frames become sealed input.events control RPCs. Read-only frames never reach the phone. iPhones still ignore input.
  • Viewer only. input.events is refused with 403 viewer_only on POST /api/v1/phones/app/:id/rpc, the route bots use, so bot actions keep going through the approval hold.
  • Ends. Stop, revoke, lock (Android 15 and later), reboot or 10 idle minutes with no viewer send ENDED with a reason. With no viewer the encoder pauses but the projection stays open.
  • Not on this lane. No audio. Windows that set FLAG_SECURE show black.

Bot runs in the in-app browser

POST /api/aci/run accepts targetDevice: "app:<phoneId>". Until the ACU planning loop has a phone-browser adapter, the node refuses such a run rather than drive its own browser: 409 app_not_open when the app’s control socket is closed, otherwise 501 phone_browser_runs_unavailable. Single browser steps work today through POST /api/v1/phones/app/:phoneId/rpc.