Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Phone screen: read scrcpy's video stream and fetch its pinned server file

Xiaolei Shic58be3cd01b6
diff --git a/server/phone-screen/scrcpy-server-file.test.ts b/server/phone-screen/scrcpy-server-file.test.ts
new file mode 100644
index 0000000000..087173521d
--- /dev/null
+++ b/server/phone-screen/scrcpy-server-file.test.ts
@@ -0,0 +1,129 @@
+import { createHash } from "node:crypto";
+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
+import { createServer, type Server } from "node:http";
+import type { AddressInfo } from "node:net";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { afterEach, describe, expect, it } from "vitest";
+
+import { removeTempDir } from "../testing/cleanup.ts";
+import { ensureScrcpyServer } from "./scrcpy-server-file.ts";
+
+const sha256 = (bytes: Buffer) => createHash("sha256").update(bytes).digest("hex");
+const SERVER_FILE = Buffer.from("the scrcpy server file");
+const noNetwork: typeof fetch = async () => {
+ throw new Error("no request was expected");
+};
+
+describe("ensureScrcpyServer", () => {
+ let dataDir = "";
+ let release: Server | undefined;
+
+ afterEach(async () => {
+ release?.closeAllConnections();
+ release?.close();
+ release = undefined;
+ await removeTempDir(dataDir);
+ });
+
+ /** A release page that redirects /download to the file, as GitHub's does, and counts the downloads it served. */
+ async function releaseOf(body: Buffer | { status: number }, digest = sha256(SERVER_FILE)) {
+ dataDir = mkdtempSync(join(tmpdir(), "omb-scrcpy-file-"));
+ const served = { downloads: 0 };
+ release = createServer((request, response) => {
+ if (request.url === "/download") {
+ response.writeHead(302, { location: "/file" }).end();
+ return;
+ }
+ served.downloads += 1;
+ if (Buffer.isBuffer(body)) response.end(body);
+ else response.writeHead(body.status).end();
+ });
+ await new Promise<void>((resolve) => release!.listen(0, "127.0.0.1", resolve));
+ const { port } = release.address() as AddressInfo;
+ const source = { version: "9.9.9", sha256: digest, url: `http://127.0.0.1:${port}/download` };
+ return { served, source, file: join(dataDir, "scrcpy", "scrcpy-server-v9.9.9") };
+ }
+
+ const filesIn = (dir: string) => readdirSync(dir, { recursive: true }).map(String).sort();
+
+ it("downloads the file once, verifies it and keeps it private", async () => {
+ const { served, source, file } = await releaseOf(SERVER_FILE);
+
+ await expect(ensureScrcpyServer(dataDir, { source })).resolves.toBe(file);
+ expect(readFileSync(file)).toEqual(SERVER_FILE);
+ expect(filesIn(dataDir)).toEqual(["scrcpy", join("scrcpy", "scrcpy-server-v9.9.9")]);
+ if (process.platform !== "win32") {
+ expect(statSync(file).mode & 0o777).toBe(0o600);
+ expect(statSync(join(dataDir, "scrcpy")).mode & 0o777).toBe(0o700);
+ }
+
+ await expect(ensureScrcpyServer(dataDir, { source, fetch: noNetwork })).resolves.toBe(file);
+ expect(served.downloads).toBe(1);
+ });
+
+ it("shares one download between two first calls", async () => {
+ const { served, source, file } = await releaseOf(SERVER_FILE);
+
+ await expect(Promise.all([ensureScrcpyServer(dataDir, { source }), ensureScrcpyServer(dataDir, { source })])).resolves.toEqual([file, file]);
+ expect(served.downloads).toBe(1);
+ });
+
+ it("replaces a file with the wrong digest once a verified download arrived", async () => {
+ const { served, source, file } = await releaseOf(SERVER_FILE);
+ mkdirSync(join(dataDir, "scrcpy"));
+ writeFileSync(file, "another version", { mode: 0o644 });
+
+ await expect(ensureScrcpyServer(dataDir, { source })).resolves.toBe(file);
+ expect(readFileSync(file)).toEqual(SERVER_FILE);
+ if (process.platform !== "win32") expect(statSync(file).mode & 0o777).toBe(0o600);
+ expect(served.downloads).toBe(1);
+ });
+
+ it("removes a file with the wrong digest when no verified download replaces it", async () => {
+ const { source, file } = await releaseOf({ status: 404 });
+ mkdirSync(join(dataDir, "scrcpy"));
+ writeFileSync(file, "another version");
+
+ await expect(ensureScrcpyServer(dataDir, { source })).rejects.toThrow("HTTP 404");
+ expect(filesIn(dataDir)).toEqual(["scrcpy"]);
+ });
+
+ it("leaves a saved file it cannot read where it is, and downloads nothing", async () => {
+ const { served, source, file } = await releaseOf(SERVER_FILE);
+ mkdirSync(file, { recursive: true });
+
+ await expect(ensureScrcpyServer(dataDir, { source })).rejects.toThrow(`Could not read ${file}, so it was left as it is: EISDIR`);
+ expect(filesIn(dataDir)).toEqual(["scrcpy", join("scrcpy", "scrcpy-server-v9.9.9")]);
+ expect(served.downloads).toBe(0);
+ });
+
+ it("downloads again after a download failed", async () => {
+ const { served, source } = await releaseOf({ status: 404 });
+
+ await expect(ensureScrcpyServer(dataDir, { source })).rejects.toThrow("HTTP 404");
+ await expect(ensureScrcpyServer(dataDir, { source })).rejects.toThrow("HTTP 404");
+ expect(served.downloads).toBe(2);
+ });
+
+ it("accepts a file of exactly 4 MiB", async () => {
+ const largest = Buffer.alloc(4 * 1024 * 1024);
+ const { source, file } = await releaseOf(largest, sha256(largest));
+
+ await expect(ensureScrcpyServer(dataDir, { source })).resolves.toBe(file);
+ });
+
+ it.each([
+ ["has another digest than the pinned one", Buffer.from("tampered"), `has SHA-256 ${sha256(Buffer.from("tampered"))}, not the expected ${sha256(SERVER_FILE)}`],
+ ["cannot be downloaded", { status: 404 }, "HTTP 404"],
+ ["is larger than 4 MiB", Buffer.alloc(4 * 1024 * 1024 + 1), "the file is larger than 4 MiB"],
+ ])("saves nothing when the file %s, and says where to put a copy by hand", async (_what, body, reason) => {
+ const { source, file } = await releaseOf(body);
+
+ const failure = await ensureScrcpyServer(dataDir, { source }).then(() => "", (error: Error) => error.message);
+ expect(failure).toContain(reason);
+ expect(failure).toContain(`save scrcpy-server 9.9.9 as ${file}`);
+ expect(filesIn(dataDir)).toEqual([]);
+ });
+});
diff --git a/server/phone-screen/scrcpy-server-file.ts b/server/phone-screen/scrcpy-server-file.ts
new file mode 100644
index 0000000000..31f53cb112
--- /dev/null
+++ b/server/phone-screen/scrcpy-server-file.ts
@@ -0,0 +1,76 @@
+import { createHash } from "node:crypto";
+import { mkdirSync } from "node:fs";
+import { readFile, rm } from "node:fs/promises";
+import { dirname, join } from "node:path";
+
+import { writeFileAtomic } from "../atomic.ts";
+import { SCRCPY_SERVER } from "./scrcpy-wire.ts";
+
+export type ScrcpyServerOptions = {
+ source?: typeof SCRCPY_SERVER;
+ fetch?: typeof fetch;
+};
+
+const DOWNLOAD_TIMEOUT_MS = 120_000;
+const MAX_DOWNLOAD_BYTES = 4 * 1024 * 1024;
+
+const inFlight = new Map<string, Promise<string>>();
+
+const sha256 = (bytes: Uint8Array) => createHash("sha256").update(bytes).digest("hex");
+
+/** The path of the pinned scrcpy server file under `dataDir`, downloaded first unless a verified copy is already there. */
+export function ensureScrcpyServer(dataDir: string, options: ScrcpyServerOptions = {}): Promise<string> {
+ const source = options.source ?? SCRCPY_SERVER;
+ const file = join(dataDir, "scrcpy", `scrcpy-server-v${source.version}`);
+ let staging = inFlight.get(file);
+ if (!staging) {
+ staging = stage(file, source, options.fetch ?? fetch).finally(() => inFlight.delete(file));
+ inFlight.set(file, staging);
+ }
+ return staging;
+}
+
+async function stage(file: string, source: typeof SCRCPY_SERVER, fetchImpl: typeof fetch): Promise<string> {
+ const saved = await savedDigest(file);
+ if (saved === source.sha256) return file;
+ if (saved !== undefined) await rm(file, { force: true });
+ const byHand = `To use a copy you downloaded yourself, save scrcpy-server ${source.version} as ${file}.`;
+ let bytes: Buffer;
+ try {
+ bytes = await download(source.url, fetchImpl);
+ } catch (error) {
+ throw new Error(`Could not download scrcpy-server ${source.version} from ${source.url}: ${error instanceof Error ? error.message : String(error)}. ${byHand}`);
+ }
+ const digest = sha256(bytes);
+ if (digest !== source.sha256) {
+ throw new Error(`The scrcpy-server ${source.version} downloaded from ${source.url} has SHA-256 ${digest}, not the expected ${source.sha256}, so it was not saved. ${byHand}`);
+ }
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
+ writeFileAtomic(file, bytes, { mode: 0o600 });
+ return file;
+}
+
+async function savedDigest(file: string): Promise<string | undefined> {
+ try {
+ return sha256(await readFile(file));
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
+ throw new Error(`Could not read ${file}, so it was left as it is: ${error instanceof Error ? error.message : String(error)}`);
+ }
+}
+
+async function download(url: string, fetchImpl: typeof fetch): Promise<Buffer> {
+ const response = await fetchImpl(url, { redirect: "follow", signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS) });
+ if (!response.ok || !response.body) {
+ await response.body?.cancel().catch(() => {});
+ throw new Error(`HTTP ${response.status}`);
+ }
+ const chunks: Uint8Array[] = [];
+ let size = 0;
+ for await (const chunk of response.body) {
+ size += chunk.length;
+ if (size > MAX_DOWNLOAD_BYTES) throw new Error("the file is larger than 4 MiB");
+ chunks.push(chunk);
+ }
+ return Buffer.concat(chunks);
+}
diff --git a/server/phone-screen/scrcpy-wire.test.ts b/server/phone-screen/scrcpy-wire.test.ts
new file mode 100644
index 0000000000..3ae58d8a85
--- /dev/null
+++ b/server/phone-screen/scrcpy-wire.test.ts
@@ -0,0 +1,94 @@
+import { isDeepStrictEqual } from "node:util";
+
+import { describe, expect, it } from "vitest";
+
+import { SCRCPY_VIDEO, SCRCPY_VIDEO_PACKETS } from "../testing/scrcpy-video.ts";
+import { deviceSocket, SCRCPY_SERVER, ScrcpyProtocolError, serverArgs, VideoReader, type VideoPacket } from "./scrcpy-wire.ts";
+
+const PREAMBLE = Buffer.from("0068323634", "hex");
+const hex = (packet: VideoPacket | undefined, bytes: number) =>
+ packet && packet.kind !== "session" ? packet.data.subarray(0, bytes).toString("hex") : "";
+const size = (packet: VideoPacket | undefined) => (packet && packet.kind !== "session" ? packet.data.length : 0);
+const same = (packets: VideoPacket[]) => isDeepStrictEqual(packets, SCRCPY_VIDEO_PACKETS);
+
+describe("the scrcpy server this client is written for", () => {
+ it("is release 5.0.1 by digest", () => {
+ expect(SCRCPY_SERVER).toEqual({
+ version: "5.0.1",
+ sha256: "764eb6f79811d5211fe9df341120882ba9994c7a61b897d7bf3fb662e53bc536",
+ url: "https://github.com/Genymobile/scrcpy/releases/download/v5.0.1/scrcpy-server-v5.0.1",
+ });
+ });
+
+ it("starts view-only, without waking the phone, syncing its clipboard or logging below errors", () => {
+ expect(serverArgs(0x1a2b3c)).toEqual([
+ "5.0.1",
+ "scid=001a2b3c",
+ "log_level=error",
+ "tunnel_forward=true",
+ "audio=false",
+ "control=false",
+ "send_device_meta=false",
+ "clipboard_autosync=false",
+ "power_on=false",
+ "max_size=1280",
+ "max_fps=30",
+ "video_bit_rate=4000000",
+ ]);
+ expect(serverArgs(0x7fffffff)[1]).toBe("scid=7fffffff");
+ });
+
+ it("listens on the phone under the same scid", () => {
+ expect(deviceSocket(0x1a2b3c)).toBe("localabstract:scrcpy_001a2b3c");
+ });
+});
+
+describe("VideoReader", () => {
+ it("reads a real phone's stream: its size, the encoder's parameters, a key frame, then the frames after it", () => {
+ const reader = new VideoReader();
+ const packets = reader.push(SCRCPY_VIDEO);
+
+ expect(SCRCPY_VIDEO).toHaveLength(3006);
+ expect(packets.map((packet) => packet.kind)).toEqual(["session", "config", "key", ...Array<string>(10).fill("delta")]);
+ expect(packets[0]).toEqual({ kind: "session", width: 720, height: 1280 });
+ expect([size(packets[1]), hex(packets[1], 8)]).toEqual([21, "000000016742c020"]);
+ expect([size(packets[2]), hex(packets[2], 5)]).toEqual([2717, "0000000165"]);
+ for (const delta of packets.slice(3)) {
+ expect([10, 11]).toContain(size(delta));
+ expect(hex(delta, 5)).toBe("0000000161");
+ }
+ expect(PREAMBLE.length + packets.length * 12 + packets.reduce((bytes, packet) => bytes + size(packet), 0)).toBe(3006);
+ expect(packets).toEqual(SCRCPY_VIDEO_PACKETS);
+ // Nothing is left over: the reader is at a packet boundary, so the same packets parse again.
+ expect(reader.push(SCRCPY_VIDEO.subarray(PREAMBLE.length))).toEqual(SCRCPY_VIDEO_PACKETS);
+ });
+
+ it("reads the same packets wherever the stream is cut in two", () => {
+ const wrongCuts: number[] = [];
+ for (let cut = 0; cut < SCRCPY_VIDEO.length; cut++) {
+ const reader = new VideoReader();
+ const packets = [...reader.push(SCRCPY_VIDEO.subarray(0, cut)), ...reader.push(SCRCPY_VIDEO.subarray(cut))];
+ if (!same(packets)) wrongCuts.push(cut);
+ }
+ expect(wrongCuts).toEqual([]);
+ });
+
+ const header = (payloadBytes: number) => {
+ const bytes = Buffer.alloc(12);
+ bytes.writeUInt32BE(payloadBytes, 8);
+ return bytes;
+ };
+
+ it.each([
+ ["does not start with scrcpy's dummy byte", Buffer.from([1])],
+ ["starts with another byte than 00", Buffer.concat([Buffer.from([1]), SCRCPY_VIDEO.subarray(1)])],
+ ["carries another codec than H.264", Buffer.concat([Buffer.from("0068323635", "hex"), SCRCPY_VIDEO.subarray(5)])],
+ ["announces a frame over 8 MiB", Buffer.concat([PREAMBLE, header(8 * 1024 * 1024 + 1)])],
+ ])("refuses a stream that %s", (_what, stream) => {
+ expect(() => new VideoReader().push(stream)).toThrow(ScrcpyProtocolError);
+ });
+
+ it("waits for the rest of a frame of exactly 8 MiB", () => {
+ expect(new VideoReader().push(Buffer.concat([PREAMBLE, header(8 * 1024 * 1024)]))).toEqual([]);
+ });
+});
diff --git a/server/phone-screen/scrcpy-wire.ts b/server/phone-screen/scrcpy-wire.ts
new file mode 100644
index 0000000000..f708dff526
--- /dev/null
+++ b/server/phone-screen/scrcpy-wire.ts
@@ -0,0 +1,83 @@
+// scrcpy's protocol is private to each release (https://github.com/Genymobile/scrcpy/blob/master/doc/develop.md):
+// the arguments and stream layout here match scrcpy-server 5.0.1 and no other version.
+
+export const SCRCPY_SERVER = {
+ version: "5.0.1",
+ sha256: "764eb6f79811d5211fe9df341120882ba9994c7a61b897d7bf3fb662e53bc536",
+ url: "https://github.com/Genymobile/scrcpy/releases/download/v5.0.1/scrcpy-server-v5.0.1",
+};
+
+const scidHex = (scid: number) => scid.toString(16).padStart(8, "0");
+
+export const deviceSocket = (scid: number) => `localabstract:scrcpy_${scidHex(scid)}`;
+
+export const deviceDir = (scid: number) => `/data/local/tmp/openmausbot-scrcpy-${scidHex(scid)}`;
+
+/** The arguments after `com.genymobile.scrcpy.Server`. `scid` is a 31-bit number. */
+export function serverArgs(scid: number): string[] {
+ return [
+ SCRCPY_SERVER.version,
+ `scid=${scidHex(scid)}`,
+ "log_level=error",
+ "tunnel_forward=true",
+ "audio=false",
+ "control=false",
+ "send_device_meta=false",
+ "clipboard_autosync=false",
+ "power_on=false",
+ "max_size=1280",
+ "max_fps=30",
+ "video_bit_rate=4000000",
+ ];
+}
+
+export type VideoPacket =
+ | { kind: "session"; width: number; height: number }
+ | { kind: "config" | "key" | "delta"; data: Buffer };
+
+export class ScrcpyProtocolError extends Error {}
+
+const CODEC_H264 = Buffer.from("h264");
+const PREAMBLE_BYTES = 1 + CODEC_H264.length;
+const HEADER_BYTES = 12;
+const SESSION_FLAG = 0x80;
+const CONFIG_FLAG = 0x40;
+const KEY_FRAME_FLAG = 0x20;
+// Security: a corrupt length field must not make the server buffer without bound.
+const MAX_PAYLOAD_BYTES = 8 * 1024 * 1024;
+
+/** Splits the video socket's bytes into packets, however the bytes were chunked. `data` is H.264 Annex B. */
+export class VideoReader {
+ #pending: Buffer = Buffer.alloc(0);
+ #preambleRead = false;
+
+ push(chunk: Buffer): VideoPacket[] {
+ let rest = this.#pending.length ? Buffer.concat([this.#pending, chunk]) : chunk;
+ this.#pending = rest;
+ if (!this.#preambleRead) {
+ if (rest.length > 0 && rest[0] !== 0) throw new ScrcpyProtocolError("The phone's video stream did not start as scrcpy 5.0.1 starts it.");
+ if (rest.length < PREAMBLE_BYTES) return [];
+ if (!rest.subarray(1, PREAMBLE_BYTES).equals(CODEC_H264)) throw new ScrcpyProtocolError("The phone did not send H.264 video.");
+ rest = rest.subarray(PREAMBLE_BYTES);
+ this.#preambleRead = true;
+ }
+ const packets: VideoPacket[] = [];
+ while (rest.length >= HEADER_BYTES) {
+ const flags = rest[0];
+ let end = HEADER_BYTES;
+ if (flags & SESSION_FLAG) {
+ packets.push({ kind: "session", width: rest.readUInt32BE(4), height: rest.readUInt32BE(8) });
+ } else {
+ const size = rest.readUInt32BE(8);
+ if (size > MAX_PAYLOAD_BYTES) throw new ScrcpyProtocolError("The phone's video stream announced a frame over 8 MiB.");
+ end += size;
+ if (rest.length < end) break;
+ const kind = flags & CONFIG_FLAG ? "config" : flags & KEY_FRAME_FLAG ? "key" : "delta";
+ packets.push({ kind, data: rest.subarray(HEADER_BYTES, end) });
+ }
+ rest = rest.subarray(end);
+ }
+ this.#pending = rest;
+ return packets;
+ }
+}
diff --git a/server/testing/scrcpy-video.ts b/server/testing/scrcpy-video.ts
new file mode 100644
index 0000000000..131de3ecf9
--- /dev/null
+++ b/server/testing/scrcpy-video.ts
@@ -0,0 +1,60 @@
+import type { VideoPacket } from "../phone-screen/scrcpy-wire.ts";
+
+// Recorded from scrcpy-server 5.0.1 on a Huawei MHA-AL00 (Android 9) with the screen off.
+export const SCRCPY_VIDEO = Buffer.from([
+ "AGgyNjSAAAAAAAAC0AAABQBAAAAAAAAAAAAAABUAAAABZ0LAINoC0ChEAAAAAWjKjyAgAAA47Jp5FgAACp0AAAABZbhF///w8JFAAEEP3333333333333333",
+ "33333333333333333333333333331111111111111111111111111111111111111111111111dddddddddddddddddddddddddddddddddddddddddddddX",
+ "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
+ "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
+ "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
+ "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX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XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXgAAAADjsm/+2AAAA",
+ "CwAAAAFh44K4AOEYAAAAOOydhlYAAAAKAAAAAWHlngA4RgAAADjsnwz2AAAACgAAAAFh554AOEYAAAA47KCTlgAAAAoAAAABYemeADhGAAAAOOyiGjYAAAAL",
+ "AAAAAWHrj4AOEYAAAAA47KOg1gAAAAsAAAABYe2C+ADhGAAAADjspSd2AAAACwAAAAFh74E+ADhGAAAAOOymrhYAAAALAAAAAWHxgV4AOEYAAAA47Kg0tgAA",
+ "AAsAAAABYfOBXgA4RgAAADjsqbtWAAAACwAAAAFh9YFeADhG",
+].join(""), "base64");
+
+const PAYLOADS: Array<[kind: "config" | "key" | "delta", offset: number, length: number]> = [
+ ["config", 29, 21],
+ ["key", 62, 2717],
+ ["delta", 2791, 11],
+ ["delta", 2814, 10],
+ ["delta", 2836, 10],
+ ["delta", 2858, 10],
+ ["delta", 2880, 11],
+ ["delta", 2903, 11],
+ ["delta", 2926, 11],
+ ["delta", 2949, 11],
+ ["delta", 2972, 11],
+ ["delta", 2995, 11],
+];
+
+/** The recording's packets, located in it by hand. */
+export const SCRCPY_VIDEO_PACKETS: VideoPacket[] = [
+ { kind: "session", width: 720, height: 1280 },
+ ...PAYLOADS.map(([kind, offset, length]) => ({ kind, data: SCRCPY_VIDEO.subarray(offset, offset + length) })),
+];
diff --git a/third_party/scrcpy/README.md b/third_party/scrcpy/README.md
new file mode 100644
index 0000000000..667f680aae
--- /dev/null
+++ b/third_party/scrcpy/README.md
@@ -0,0 +1,31 @@
+# scrcpy server provenance
+
+OpenMausBot shows the screen of a USB Android phone with the official scrcpy
+server 5.0.1. The server file comes from Genymobile's GitHub release:
+
+<https://github.com/Genymobile/scrcpy/releases/tag/v5.0.1>
+
+| Release asset | SHA-256 |
+| --- | --- |
+| `scrcpy-server-v5.0.1` | `764eb6f79811d5211fe9df341120882ba9994c7a61b897d7bf3fb662e53bc536` |
+
+The file is not checked into git and is not part of any package. The server
+downloads it on first use from
+
+<https://github.com/Genymobile/scrcpy/releases/download/v5.0.1/scrcpy-server-v5.0.1>
+
+into `scrcpy/scrcpy-server-v5.0.1` in its data directory (`~/.openmausbot`
+unless `OMB_DATA_DIR` says otherwise), and uses it only when its SHA-256
+equals the digest above. Every later use verifies the saved file again.
+
+On a server without internet access, download the release asset on another
+machine, check its digest, and save it at that path under that name.
+
+OpenMausBot copies the file to the phone with `adb push`, runs it there with
+`app_process`, and removes it when the view closes. Nothing is installed on
+the phone. The file is used unmodified; OpenMausBot's own client
+(`server/phone-screen/`) speaks the protocol of this one release, so a new
+scrcpy version needs the client checked against it before the pin moves.
+
+scrcpy is licensed under the Apache License 2.0:
+<https://github.com/Genymobile/scrcpy/blob/v5.0.1/LICENSE>.