diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json new file mode 100644 index 0000000..26bbcad --- /dev/null +++ b/.claude-plugin/marketplace.json @@ -0,0 +1,14 @@ +{ + "name": "idevbench", + "description": "iDevBench: use a real iPhone from Claude", + "owner": { + "name": "YK3D" + }, + "plugins": [ + { + "name": "idevbench", + "source": "./plugins/idevbench", + "description": "See and control an iPhone's screen and set its GPS location through the iDevBench app." + } + ] +} diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md index 03525df..b9f5437 100644 --- a/.claude/CLAUDE.md +++ b/.claude/CLAUDE.md @@ -19,7 +19,7 @@ - `browser/` is the Python edition (FastAPI); `standalone/` is the Rust edition (axum, native window). Backend behaviour must stay the same in both: port every API or engine change to the other edition, with tests. - `assets/icon/source.jpg` is the original icon artwork. Never edit it; `assets/icon/make_icons.py` regenerates every icon file from it. - `docs/screenshots/capture.js` makes the README screenshots with the default look (Graphite theme, dark OpenFreeMap map). -- `website/` is the showcase site (Vite + React, on Vercel at https://iphone-spoofer.vercel.app from `main`, https://iphone-spoofer-dev.vercel.app from `dev`; root directory `website`). It renders TERMS.md, PRIVACY.md, LICENSE, THIRD_PARTY_NOTICES.md and CHANGELOG.md as its pages and reads release versions live, so keep those files as the source of truth; the app links to those pages. The video at the top of the site is made by `website/scripts/showreel/` (record the real app frame by frame, then `edit.cjs` cuts it; see `website/README.md`). `website/src/sim/engine.js` is a compact port of the speed engine for its demo: when the cornering or acceleration constants change in the app, update it too and run `cd website && npm test`. Pushes that only touch `website/` don't publish test builds. +- `website/` is the showcase site (Vite + React, on Vercel at https://idevbench.vercel.app from `main`, https://iphone-spoofer-dev.vercel.app from `dev`; root directory `website`). It renders TERMS.md, PRIVACY.md, LICENSE, THIRD_PARTY_NOTICES.md and CHANGELOG.md as its pages and reads release versions live, so keep those files as the source of truth; the app links to those pages. The video at the top of the site is made by `website/scripts/showreel/` (record the real app frame by frame, then `edit.cjs` cuts it; see `website/README.md`). `website/src/sim/engine.js` is a compact port of the speed engine for its demo: when the cornering or acceleration constants change in the app, update it too and run `cd website && npm test`. Pushes that only touch `website/` don't publish test builds. ## Checks before pushing diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000..554391e --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,10 @@ +{ + "extraKnownMarketplaces": { + "midstream": { + "source": { "source": "github", "repo": "YK3D/midstream" } + } + }, + "enabledPlugins": { + "midstream@midstream": true + } +} diff --git a/.claude/skills/ponytail-audit/SKILL.md b/.claude/skills/ponytail-audit/SKILL.md new file mode 100644 index 0000000..ff9a954 --- /dev/null +++ b/.claude/skills/ponytail-audit/SKILL.md @@ -0,0 +1,103 @@ +--- +name: ponytail-audit +description: > + Quality audit of a whole repo: bugs, security holes, what breaks under real + load, risky code without tests, slow paths, and what to delete, merge or + split. Ranked, each finding explained in plain English. One-shot report, + changes nothing. Use for "audit this codebase", "review the whole repo", + "find bloat", "what can I delete", /ponytail-audit. +--- + +Audit the whole repo like the senior developer who just inherited it and +will be paged when it breaks. Order of importance: correct, safe, holds under +load, tested, fast, lean. Lean still matters: every extra line must be read, +tested and fixed later. This is a report the user asked for, so give it in full. + +## 1. Map first + +- Audit what the user names: a folder, a package, or the whole repo. + Nothing named: the whole repo. +- Read the README, the deploy and build config, the dependency list, the + entry points (main, routes, handlers, jobs, CLI commands) and the tests. +- Find the expected load: one person running a script, or many users and + processes at once. Judge scale against that, and say which load you assumed. +- Trace the main flows end to end: where data comes in, what is stored, + what goes out. Read those paths fully: input from users, money, auth, + data writes, background jobs, anything shared between processes. +- Big repo: go deep where a mistake costs the most, not file by file. Say + which parts you did not read. + +## 2. Look for + +1. **Bug:** wrong result, crash, missed edge case (empty, zero, last item, + rounding, time zones), callers that disagree with what a function returns, + the same rule applied differently in two places. +2. **Risk:** security holes (injection, weak randomness, secrets in code, + missing checks on input from users), data loss (errors swallowed, writes + in the wrong order, no transaction). +3. **Scale:** fine for one user, wrong for many: check-then-write races, the + same work done by every process, memory or lists that only grow, a query + per item, O(n^2) on big input, per-process state that must be shared. +4. **Missing test:** risky logic (a branch, a parser, money, security, data + writes) with no test that fails when it breaks. One good test, not coverage. +5. **Speed:** big slowdowns are problems. Small wins (work repeated in a hot + loop) are suggestions; some software counts every millisecond. +6. **Lean:** code that should not exist or should be smaller. + - delete: dead code, unused options, flags and config, speculative features + - reuse: two helpers doing the same thing (keep one, name the path) + - stdlib / native: the standard library or platform already does it; + a dependency doing what a few lines or the platform can do + - yagni: interface with one implementation, factory with one product, + wrapper that only passes calls through + - merge: near-copies that must change together + - split: one function or class doing several unrelated jobs, so it is + hard to read or test. Split by job, never by line count, and never into + helpers that exist only to make a function shorter. + +## 3. Check before you report + +- Every finding needs a concrete case: "this input or situation leads to this + wrong result". No case, no finding. +- Before calling code unused, grep the whole tree for it, including tests, + fixtures, config, and string or dynamic references. +- A shortcut marked with a `shortcut:` (or older `ponytail:`) comment that names its limit is a + decision, not a finding, unless the expected load already crosses it. +- Propose the smallest fix that works. Prefer fixes that delete code. Never + add layers, frameworks or config the problem does not need. +- No style taste, no "consider", no vague worries. + +## 4. Output + +Very simple English: short sentences, everyday words. Explain a technical +term the first time you use it. The reader may never have seen this code. + +Start with `What this repo does:` in two or three sentences, and the load +you assumed. + +Then the findings in three groups, most important first, skip empty groups: +- **Must fix:** bug, security, data loss, breaks at the expected load. +- **Should fix:** risky code without a test, real slowness, duplication, a + function that mixes jobs, code that should not exist. +- **Nice to have:** small speed-ups, shorter forms. + +Number findings across all groups, so the user can say "fix 2 and 5". At +most 20 findings; if you left smaller ones out, say how many. +Every finding has all four parts, each one or two short sentences: + +2. **Orders land on the wrong day** (`billing/close_day.py:L40-52`) + - **What this is:** At midnight this job closes the day and bills all orders of that day. + - **Problem:** It takes "today" from the server clock, which runs in UTC. An order placed + at 00:30 in Berlin is billed on the day before. + - **Fix:** Compute the day once in the shop's time zone: + `datetime.now(ZoneInfo("Europe/Berlin")).date()`. One line, nothing else changes. + - **If we skip it:** Late orders show the wrong date, and accounting fixes them by hand. + +End with: +- `Verdict:` one line: healthy, or what to fix first. +- `Lean: - lines, - dependencies possible.` when lean findings exist. +- `Not checked:` the parts you did not read or could not run. + +Nothing found: `What this repo does:`, then `Healthy. Nothing to fix.` and +one line on what you checked. + +One-shot report, changes no code. diff --git a/.claude/skills/ponytail-debt/SKILL.md b/.claude/skills/ponytail-debt/SKILL.md new file mode 100644 index 0000000..3124f52 --- /dev/null +++ b/.claude/skills/ponytail-debt/SKILL.md @@ -0,0 +1,44 @@ +--- +name: ponytail-debt +description: > + List every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, + changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the + shortcuts", /ponytail-debt. +--- + +Every deliberate ponytail shortcut is marked with a `shortcut:` comment naming +its ceiling and upgrade path (older code may say `ponytail:`). This collects them into one ledger so a deferral +can't quietly become permanent. + +## Scan + +Grep the repo for comment markers, skipping `.git` and everything the +`.gitignore` files ignore (dependencies, build output, caches, in any stack): + +`git grep --no-index --exclude-standard -nE '(#|//|/[*]) ?(shortcut|ponytail):'` (add other comment prefixes if your stack uses them) + +If the user names their own marker word (`/ponytail-debt TODO`), grep for that word instead. + +Each hit is one ledger row. The comment prefix keeps prose that merely mentions +the convention out of the ledger. Skip hits that are not a deferral, like a note +about a keyboard shortcut. + +## Output + +One row per marker, grouped by file: + +`:, . ceiling: . upgrade: .` + +The convention is `shortcut: , `, so pull the ceiling +and the trigger straight from the comment. Want an owner per row too? add +`git blame -L,`. + +Flag the rot risk: any marker comment that names no upgrade path or +trigger gets a `no-trigger` tag, those are the ones that silently rot. + +End with ` markers, with no trigger.` Nothing found: `No shortcut debt. Clean ledger.` + +## Boundaries + +Reads and reports only, changes nothing. To persist it, ask and it writes the +ledger to a file (e.g. `PONYTAIL-DEBT.md`). One-shot. diff --git a/.claude/skills/ponytail-gain/SKILL.md b/.claude/skills/ponytail-gain/SKILL.md new file mode 100644 index 0000000..1edff0e --- /dev/null +++ b/.claude/skills/ponytail-gain/SKILL.md @@ -0,0 +1,52 @@ +--- +name: ponytail-gain +description: > + Show ponytail's measured savings (code, cost, speed) from the benchmark. + One-shot display. Use for /ponytail-gain, "what does ponytail save", + "ponytail impact". +--- + +# Ponytail Gain + +Display this scoreboard when invoked. One-shot: do NOT change mode, write flag +files, or persist anything. + +The figures are the published agentic benchmark of Ponytail 5: headless Claude +Code (Opus 5.5, default effort) on 39 tasks (feature tickets in a real FastAPI + +React repo, bug fixes, security and privacy cases, small apps), 5 runs each, +against the same agent without the skill. 18 of the tasks have hidden checks +for correctness and safety. Each figure is the geometric mean of the per-task +medians. They are measured, not computed from the current repo. +Source: `benchmarks/results/2026-10-07-agentic.md` and the README. + +## Scoreboard + +Render plain ASCII bars. The bar length shows ponytail as a share of the +no-skill baseline; the label carries the exact figure: + +``` + ponytail gain benchmark · 39 tasks × 5 runs · Opus 5.5 + + no-skill ████████████████████ 100% + Lines of code █████████··········· 47% ▼ 53% + Output tokens ███████████········· 55% ▼ 45% + Cost ███████████████····· 74% ▼ 26% + Time ████████████········ 59% ▼ 41% + Hidden checks passed 97% (no-skill 96%) + Tests where the logic needs one 98% (no-skill 68%) + + This repo: /ponytail-debt (shortcuts you deferred) + /ponytail-audit (what's still cuttable) +``` + +## Honesty boundary + +These are benchmark averages, not this repo. NEVER print a per-repo savings +number ("you saved X lines/tokens here"): the unbuilt version was never +written, so there is no real baseline to subtract from in a live repo. The +only real per-repo figures come from `/ponytail-debt` (a counted ledger), and +this card points there instead of inventing one. + +## Boundaries + +One-shot display. Edits nothing, changes no mode. diff --git a/.claude/skills/ponytail-help/SKILL.md b/.claude/skills/ponytail-help/SKILL.md new file mode 100644 index 0000000..34fccb3 --- /dev/null +++ b/.claude/skills/ponytail-help/SKILL.md @@ -0,0 +1,76 @@ +--- +name: ponytail-help +description: > + Quick reference for ponytail levels, skills and commands. One-shot display. + Use for /ponytail-help, "ponytail help", "how do I use ponytail". +--- + +# Ponytail Help + +Display this reference card when invoked. One-shot, do NOT change mode, +write flag files, or persist anything. + +## Levels + +| Level | Trigger | What change | +|-------|---------|-------------| +| **Lite** | `/ponytail lite` | Build what was asked, name the smaller option in one line. | +| **Full** | `/ponytail` | The smallest complete change, a check where the logic needs one, and a reply that names what was skipped and any risk. Default. | +| **Ultra** | `/ponytail ultra` | Also questions the request and pushes back before building. | + +Level sticks until changed or session end. + +## Skills + +| Skill | Trigger | What it does | +|-------|---------|--------------| +| **ponytail** | `/ponytail` | Lazy mode itself: least new code, clear replies that name skipped work and risks. | +| **ponytail-review** | `/ponytail-review` | Quality review of a diff: bugs, security, load, missing tests, speed, what to cut. Each finding says what goes wrong and how to fix it. | +| **ponytail-audit** | `/ponytail-audit` | The same quality review for the whole repo, ranked. | +| **ponytail-debt** | `/ponytail-debt` | Harvest `shortcut:` comments into a tracked ledger. | +| **ponytail-gain** | `/ponytail-gain` | Measured-impact scoreboard: less code, less cost, more speed. | +| **ponytail-help** | `/ponytail-help` | This card. | + +In Codex CLI and the IDE extension, invoke skills with `$ponytail:ponytail`, +`$ponytail:ponytail-review`, or `$ponytail:ponytail-help`. Claude Code and OpenCode use the +slash-command forms above (OpenCode ships all six as slash commands). + +## Deactivate + +Say "stop ponytail" or "normal mode". Resume anytime with `/ponytail`. +`/ponytail off` also works. + +## Band (Claude Code) + +`/ponytail band` hides the band above the prompt, the same command brings it back. +`/ponytail band on` and `/ponytail band off` set it directly. The level stays. +`/ponytail band import` adds your past Claude Code sessions (cost, agent time, tokens) to the board. + +## Configure Default Mode + +Default mode = `full`, auto-active every session. Change it: + +**Environment variable** (highest priority): +```bash +export PONYTAIL_DEFAULT_MODE=ultra +``` + +**Config file** (`~/.config/ponytail/config.json`, Windows: `%APPDATA%\ponytail\config.json`): +```json +{ "defaultMode": "lite" } +``` + +Set `"off"` to disable auto-activation on session start, activate manually +with `/ponytail` when wanted. + +Resolution: env var > config file > `full`. + +## Update + +Enable auto-update once: open `/plugin`, go to Marketplaces, pick ponytail, Enable auto-update. Claude Code then pulls new versions at startup (run `/reload-plugins` when it prompts). Manual refresh: `/plugin marketplace update ponytail` then `/reload-plugins`. + +If `/plugin` is not recognized, your Claude Code is out of date. Update it (`npm install -g @anthropic-ai/claude-code@latest`, or `brew upgrade claude-code`) and restart. Other hosts use their own update flow. + +## More + +Full docs + examples: https://github.com/DietrichGebert/ponytail diff --git a/.claude/skills/ponytail-review/SKILL.md b/.claude/skills/ponytail-review/SKILL.md new file mode 100644 index 0000000..a50e3ac --- /dev/null +++ b/.claude/skills/ponytail-review/SKILL.md @@ -0,0 +1,101 @@ +--- +name: ponytail-review +description: > + Quality review of a change: is the logic right, is it safe, does it hold + under real load, is risky code tested, is it fast enough, and is every line + needed. Reads the connected code, not only the diff. Each finding is + explained in plain English. Use for "review this", "code review", "review + the last commit", "review my PR", "is this over-engineered", /ponytail-review. +--- + +Review a change like the senior developer who will be paged when it breaks. +Order of importance: correct, safe, holds under load, tested, fast, lean. +Lean still matters: every extra line must be read, tested and fixed later. +This is a report the user asked for, so give it in full. + +## 1. Understand first + +- Review what the user names: uncommitted or staged changes, a branch, a PR + link, or files. Nothing named: the uncommitted changes, or the last commit + if there are none. +- Read the diff, then the code it touches: callers of every changed function, + the functions it calls, the tests, the README. +- Trace the real flow: where data comes in, what is stored, what goes out. +- A change can break code it does not touch. When a signature, return value + or behavior changes, grep every caller. +- Find the expected load in the repo (README, deploy config): one person + running a script, or many users and processes at once. Judge scale against + that, and say which load you assumed. + +## 2. Look for + +1. **Bug:** wrong result, crash, missed edge case (empty, zero, last item, + rounding, time zones), a caller broken by the change, a fix applied in one + caller while the shared function stays broken. +2. **Risk:** security holes (injection, weak randomness, secrets, missing + checks on input from users), data loss (errors swallowed, writes in the + wrong order, no transaction). +3. **Scale:** fine for one user, wrong for many: check-then-write races, the + same work done by every process, memory or lists that only grow, a query + per item, O(n^2) on big input, per-process state that must be shared. +4. **Missing test:** risky new logic (a branch, a parser, money, security, + data writes, a bug fix) with no test that fails when it breaks. One good + test, not coverage. +5. **Speed:** big slowdowns are problems. Small wins (work repeated in a hot + loop) are suggestions; some software counts every millisecond. +6. **Lean:** code that should not exist or should be smaller. + - delete: dead code, unused options, speculative features + - reuse: the repo already has this helper (name the path) + - stdlib / native: the standard library or platform already does it; a + new dependency for a few lines + - yagni: abstraction with one implementation, config nobody sets + - merge: near-copies that must change together + - split: one function doing several unrelated jobs, so it is hard to read + or test. Split by job, never by line count, and never into helpers that + exist only to make a function shorter. + +## 3. Check before you report + +- Every finding needs a concrete case: "this input or situation leads to this + wrong result". No case, no finding. +- Re-read the lines and confirm: the caller exists, the value can really be + empty, the code really is unused. +- A shortcut marked with a `shortcut:` (or older `ponytail:`) comment that names its limit is a + decision, not a finding, unless the expected load already crosses it. +- Propose the smallest fix that works. Prefer fixes that delete code. Never + add layers, frameworks or config the problem does not need. +- No style taste, no "consider", no vague worries. + +## 4. Output + +Very simple English: short sentences, everyday words. Explain a technical +term the first time you use it. The reader may never have seen this code. + +Start with `What this change does:` in two or three sentences. + +Then the findings in three groups, skip empty groups: +- **Must fix:** bug, security, data loss, breaks at the expected load. +- **Should fix:** risky code without a test, real slowness, duplication, a + function that mixes jobs, code that should not exist. +- **Nice to have:** small speed-ups, shorter forms. + +Number findings across all groups, so the user can say "fix 2 and 5". +Every finding has all four parts, each one or two short sentences: + +2. **Orders land on the wrong day** (`billing/close_day.py:L40-52`) + - **What this is:** At midnight this job closes the day and bills all orders of that day. + - **Problem:** It takes "today" from the server clock, which runs in UTC. An order placed + at 00:30 in Berlin is billed on the day before. + - **Fix:** Compute the day once in the shop's time zone: + `datetime.now(ZoneInfo("Europe/Berlin")).date()`. One line, nothing else changes. + - **If we skip it:** Late orders show the wrong date, and accounting fixes them by hand. + +End with: +- `Verdict: Ship.` or `Verdict: fix 1 and 3 first.` +- `Lean: - lines possible.` when lean findings exist. +- `Not checked:` one line, if something mattered and you could not check it. + +Nothing found: `What this change does:`, then `Looks good. Ship.` and one line +on what you checked. + +Lists findings, changes no code. diff --git a/.claude/skills/ponytail/LICENSE b/.claude/skills/ponytail/LICENSE new file mode 100644 index 0000000..715d483 --- /dev/null +++ b/.claude/skills/ponytail/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 DietrichGebert + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/.claude/skills/ponytail/SKILL.md b/.claude/skills/ponytail/SKILL.md new file mode 100644 index 0000000..d64edd3 --- /dev/null +++ b/.claude/skills/ponytail/SKILL.md @@ -0,0 +1,52 @@ +--- +name: ponytail +description: > + Lazy senior dev mode: the smallest change that fully solves the task, and a + reply a busy human understands in one read. Use on any coding task (writing, + fixing, refactoring, reviewing, choosing dependencies) and when the user says + "ponytail", "be lazy", "simplest solution", "yagni", or complains about + over-engineering or bloat. Levels: lite, full (default), ultra. +argument-hint: "[lite|full|ultra|off]" +license: MIT +--- + +# Ponytail + +You are a lazy senior developer. The best code is the code never written. You solve the whole problem with the least new code. End your reply with one or two lines: what you skipped or did not check, and any risk the user must know. + +Active for the whole session until the user says "stop ponytail" or "normal mode". Switch level: `/ponytail lite|full|ultra`. + +## Before you write + +Read the task and the code it touches. List every place your change must reach: callers, tests, fixtures, config, exports. Check what your change could break for users: data it would destroy or expose, callers that stop working. That is scope. Extra features are not. + +## The smallest complete change + +Take the first option that fully works: + +1. Does it need to exist? Skip features, options and flexibility nobody asked for, and name them in one line. A vague request ("build me X") gets the smallest version that does the core job. +2. Already in this codebase (a helper, component, service, pattern)? Use it the way the surrounding code does. +3. Standard library or a platform feature? Use it, unless the project has its own. A house component beats a native widget. +4. An installed dependency? Use it. Never add a dependency for a few lines. +5. Can it be one line a reader gets at a glance? One line. +6. Otherwise: the minimum code that works. + +- Be lazy about the solution, never about the change itself: finish every part the task needs, including the callers, tests and fixtures your change breaks. +- No abstraction, wrapper, type conversion, option, config, boilerplate or "for later" code nobody asked for. Keep values in the form the platform already gives you. Deletion beats addition. Keep the structure the codebase already has: its layers, interfaces and conventions. +- The shortest working diff wins, once you know everything it must touch. A one-liner that needs decoding is not short. +- Comment only the why the code cannot show, in one line. +- Bug fix: before you edit, grep every caller of the function you touch, then fix the root cause once in the shared code. +- Code you move or merge keeps its error handling and validation. +- Between options of equal size, take the one that is correct on edge cases. +- Lazy code without its check is unfinished: new non-trivial logic (a branch, a loop, a parser, money or security, or a whole new script or app) leaves one small test or an assert-based self-check. Trivial changes need none. +- A shortcut with a known limit gets a code comment in this form: `shortcut: , `. + +Never cut: validation at trust boundaries, error handling that prevents data loss, security, accessibility, the calibration real hardware needs, anything the user asked for. + +## Levels + +| Level | Behavior | +|-------|----------| +| **lite** | Build what was asked. Name the smaller option in one line and let the user pick. | +| **full** | The rules above. Default. | +| **ultra** | Also question the request: before building, push back on any part the need does not justify. | diff --git a/.github/release-notes/browser.md b/.github/release-notes/browser.md index 98e7c1d..05c797b 100644 --- a/.github/release-notes/browser.md +++ b/.github/release-notes/browser.md @@ -1,4 +1,4 @@ -**Location Spoofer Browser Edition {VERSION}** — the edition that runs in your web browser, built on pymobiledevice3. Use it if you need iOS 17.0–17.3 support or the pymobiledevice3 command fallback; otherwise the native Windows app is recommended.{CHANNEL_NOTE} +**iDevBench Browser Edition {VERSION}** (formerly Location Spoofer) — the edition that runs in your web browser, built on pymobiledevice3. Use it if you need iOS 17.0–17.3 support or the pymobiledevice3 command fallback; otherwise the native Windows app is recommended.{CHANNEL_NOTE} ### Install 1. Install [**Apple Devices**](https://apps.microsoft.com/detail/9np83lwlpz9k) from the Microsoft Store (free, made by Apple; iTunes also works). diff --git a/.github/release-notes/standalone.md b/.github/release-notes/standalone.md index 0536fe1..2948ca8 100644 --- a/.github/release-notes/standalone.md +++ b/.github/release-notes/standalone.md @@ -1,4 +1,4 @@ -**Location Spoofer {VERSION}** — the recommended Windows app.{CHANNEL_NOTE} +**iDevBench {VERSION}** (formerly Location Spoofer) — the recommended Windows app.{CHANNEL_NOTE} ### Install 1. Install [**Apple Devices**](https://apps.microsoft.com/detail/9np83lwlpz9k) from the Microsoft Store (free, made by Apple; iTunes also works). diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2f79d7c..42e6ad2 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -150,8 +150,8 @@ jobs: BR_SHA=$(cut -d' ' -f1 dist/browser/LocationSpooferBrowser.exe.sha256) render browser "$BROWSER_VERSION$LABEL" "$BR_SHA" > notes-browser.md gh release create "browser-v$BROWSER_VERSION$SUFFIX" dist/browser/LocationSpooferBrowser.exe dist/browser/LocationSpooferBrowser.exe.sha256 \ - --title "Location Spoofer Browser Edition $BROWSER_VERSION$LABEL" --notes-file notes-browser.md --target "$GITHUB_SHA" $FLAGS_BR + --title "iDevBench Browser Edition $BROWSER_VERSION$LABEL" --notes-file notes-browser.md --target "$GITHUB_SHA" $FLAGS_BR SA_SHA=$(cut -d' ' -f1 dist/standalone/LocationSpooferStandalone.exe.sha256) render standalone "$STANDALONE_VERSION$LABEL" "$SA_SHA" > notes-standalone.md gh release create "standalone-v$STANDALONE_VERSION$SUFFIX" dist/standalone/LocationSpooferStandalone.exe dist/standalone/LocationSpooferStandalone.exe.sha256 \ - --title "Location Spoofer Standalone $STANDALONE_VERSION$LABEL" --notes-file notes-standalone.md --target "$GITHUB_SHA" $FLAGS_SA + --title "iDevBench $STANDALONE_VERSION$LABEL" --notes-file notes-standalone.md --target "$GITHUB_SHA" $FLAGS_SA diff --git a/CHANGELOG.md b/CHANGELOG.md index a37f150..06eb972 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,8 +7,17 @@ Test builds from the `dev` branch are marked as pre-releases. ## Unreleased (dev) +### Experimental (see [docs/testing/multiple-iphones-and-wifi.md](docs/testing/multiple-iphones-and-wifi.md)) +- Several iPhones at once: phones added under *Device › More iPhones* follow the main one (teleports, routes, GPX, joystick, Stop spoofing). Each gets positions from its own queue, so a slow or lost phone never holds up the others; a lost phone is marked until removed, and removing one sends it back to its real location. The Simulator has a second phone to try it. +- Wi-Fi connections: *Device tools › Connect over* (Automatic, USB cable only, Wi-Fi only) and *Allow Wi-Fi connection*, which turns on the phone's "Show this iPhone when on Wi-Fi" setting. The device list shows how each phone can be reached (USB, Wi-Fi, or both). In the browser version, a second iOS 17+ phone or an iOS 17+ phone over Wi-Fi needs the tunnel helper. Bluetooth isn't possible. + ### New -- **Website:** [iphone-spoofer.vercel.app](https://iphone-spoofer.vercel.app) shows what the app does, has the downloads, and lets you try a small version of it in your browser. The Terms of Use, Privacy Policy and licences now open there (setup guide and *Settings › About*). +- **Screen mirroring (iOS 27 and newer):** the iPhone's screen in its own *Mirroring* section (switch at the top of the side menu), over the USB cable. Click to tap, drag to swipe, scroll with the mouse wheel, Ctrl + wheel or a trackpad pinch to zoom, right-click for Home, and type from your keyboard (Ctrl works as ⌘). Buttons next to the screen press Home, Lock, Volume, Mute and Siri and do the app switcher, Control Centre, notifications and Back gestures. Over the screen the pointer is a small dot that dips when you click, and swipes leave a faint trail. The phone's name and iOS version are shown above it, and an iPhone home screen stands in until the picture arrives. The picture turns when the phone does (or with *Rotate*). The standalone app also plays the iPhone's sound. Save screenshots, or record the screen with its sound as a video, to Downloads or a folder chosen with *Browse* in *Settings › Mirroring*. *Stats* shows the stream's frame rate, data rate and delay, and the iPhone's CPU, memory, GPU, battery and temperature. A frozen picture restarts by itself after a few seconds, or at once with *Restart stream*. +- **Local API:** other programs on your computer can set the location, watch the screen, tap, swipe and type through the app while it is open (websites can't). See [docs/API.md](docs/API.md). +- **AI agents:** iDevBench is an MCP server, so Claude, Codex, Cursor and other AI apps can use the phone through it: see and control the screen, set the location, drive routes, play tracks and use the joystick. Setting it up is one prompt to paste into the agent (*Settings › AI agents*), or one button for Claude Desktop; there is also a Claude Code plugin. The agent gets a guide on how to use the phone, and only enters the passcode if you ask it to and give it the passcode. See [docs/API.md](docs/API.md#ai-agents-mcp). +- **iOS 27:** the standalone app now tries to mount the developer image itself instead of asking for Xcode first. +- **New name: iDevBench.** Location Spoofer is now called iDevBench, because it is growing into a toolkit for working with your iPhone from Windows, not only for its location. Nothing else changes: updating keeps your settings, favourites, routes and offline maps, and the download files keep their names so installed copies keep updating. +- **Website:** [idevbench.vercel.app](https://idevbench.vercel.app) shows what the app does, has the downloads, and lets you try a small version of it in your browser. The Terms of Use, Privacy Policy and licences now open there (setup guide and *Settings › About*). - **Offline maps:** *Settings › Offline maps* saves the area on screen (up to 3,000 map tiles, about a city, per download; as many areas as you like), so the map works without internet. Saved areas can be shown on the map or deleted. - **New map menu** (top right): picture previews of each map, the map theme (Dark, Light or Auto) and a shortcut to offline maps. - **Smooth trackpad zoom:** pinching or two-finger scrolling zooms smoothly to exactly where your fingers stop, instead of jumping in steps and flickering. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 03df65e..5737c41 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -4,7 +4,7 @@ Bug reports and ideas are welcome as [GitHub issues](https://github.com/YK3D/iPh ## Licence of contributions -Location Spoofer is source-available, not open source (see [LICENSE](LICENSE)). By opening a pull request you confirm that you have the right to submit the change, and you grant YK3D the licence described in section 4 of [LICENSE](LICENSE), so the change can be included and relicensed with the app. You keep the copyright in your contribution and are credited in the history. +iDevBench (formerly Location Spoofer) is source-available, not open source (see [LICENSE](LICENSE)). By opening a pull request you confirm that you have the right to submit the change, and you grant YK3D the licence described in section 4 of [LICENSE](LICENSE), so the change can be included and relicensed with the app. You keep the copyright in your contribution and are credited in the history. ## Feature tests @@ -48,6 +48,7 @@ Set `SPOOFER_DATA_DIR` to an empty folder first if you don't want the experiment | `standalone/` | Standalone app (Rust): local server, iPhone driver, routing, speed engine, native window | | `browser/` | Browser edition (Python, FastAPI) | | `ui/` | The interface both editions serve (HTML, CSS, JavaScript; no build step) | +| `plugins/idevbench/`, `.claude-plugin/marketplace.json` | The Claude Code plugin (MCP server at `http://127.0.0.1:8766/mcp` plus the guide as a skill). The MCP server itself is built into both editions (`/mcp`, `--mcp`); its tools are listed once in `ui/mcp-tools.json` as calls to the local API, and `ui/mcp-guide.md` is the guide (the plugin's `SKILL.md` must match it; a test checks). Check the plugin with `claude plugin validate ./plugins/idevbench --strict` | | `assets/icon/` | Icon artwork; `make_icons.py` regenerates every icon file from `source.jpg` | | `docs/screenshots/` | README screenshots; `capture.js` makes them, and `website/scripts/record-clips.cjs` makes the animation (`demo.webp`) with the website's clips | | `website/` | The showcase website with an in-browser demo (Vite + React, hosted on Vercel); see `website/README.md` | diff --git a/PRIVACY.md b/PRIVACY.md index 98d506c..9a3d7a0 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -1,8 +1,8 @@ # Privacy Policy -_Last updated: 5 November 2026_ +_Last updated: 25 November 2026_ -This policy covers both editions of Location Spoofer: the standalone app (`LocationSpooferStandalone.exe`) and the browser version (`LocationSpooferBrowser.exe` or run from source). Together they are called "the app". +This policy covers both editions of iDevBench, formerly called Location Spoofer: the standalone app (`LocationSpooferStandalone.exe`) and the browser version (`LocationSpooferBrowser.exe` or run from source). Together they are called "the app". ## The short version @@ -10,6 +10,8 @@ This policy covers both editions of Location Spoofer: the standalone app (`Locat * Everything you create — favourites, saved routes, settings, an optional Google API key — is stored **only on your computer**. * To show maps, find places and calculate routes, the app talks **directly from your computer to third-party online services** listed below. Those services receive the information needed to answer each request (for example map coordinates or a search term) and your IP address, under their own privacy policies. * The app talks to your iPhone **only over the USB cable or your local network**; nothing about the phone is sent to the internet by the app. +* **Screen mirroring** (the picture, the sound and your clicks and key presses) travels only between the phone and your computer. The app does not upload it, analyse it or keep a copy. Only screenshots and recordings that you save are written to disk, in your Downloads folder or the folder you choose in *Settings › Mirroring*. +* The **local API for other programs** works only while the app is open, only for programs on your computer (not websites or other computers). Programs that use it can receive the phone's screen and control the phone; what they do with it is covered by their own privacy policies. This includes the **AI agent connector** that comes with the app: if you connect an AI assistant (for example Claude Code or Cursor) to it, the screenshots it takes, what is visible on them and what you tell it (including a passcode, if you give it one to unlock the phone) are sent to that AI service, under its own privacy policy. *Add to Claude Desktop* only adds iDevBench to Claude Desktop's settings file on this computer. ## What is stored on your computer @@ -22,9 +24,12 @@ This policy covers both editions of Location Spoofer: the standalone app (`Locat | Offline maps: downloaded map areas, and the map styles and fonts | `offline` folder next to `data.json` | So the map works without internet. Delete areas in Settings › Offline maps | | Developer access only: the remembered developer password and downloaded feature-test builds | `feature-tests` folder next to `data.json` | Only if the developer unlocks feature tests and ticks "Remember" | | Downloaded updates | Next to the app's `.exe` until installed | Self-update | +| Screenshots and screen recordings (only the ones you save) | The folder you pick when saving (usually *Downloads*) | So you can keep them. The app does not keep its own copy | You can delete all of it at any time by deleting those folders. Uninstalling the app (deleting the `.exe`) does not delete `data.json`. +While screen mirroring is on, the most recent pictures and sound from the phone are held briefly in the computer's memory so they can be shown and played. They are gone when you stop mirroring or close the app. + ## Online services the app contacts The app sends requests **directly** to these services. No data passes through servers run by the app's authors. @@ -43,12 +48,16 @@ The app sends requests **directly** to these services. No data passes through se | GitHub (`api.github.com`, `github.com`, `release-assets.githubusercontent.com`) | Update checks (at start-up and every few hours) and update downloads; for the developer only, encrypted feature-test builds after unlocking *Developer access* | Your IP address and app version (in the request) | [GitHub Privacy Statement](https://docs.github.com/site-policy/privacy-policies/github-general-privacy-statement) | | GitHub raw content (`raw.githubusercontent.com/doronz88/DeveloperDiskImage`) | Only when the iPhone has no Developer Disk Image mounted | The requested file path, IP address | [GitHub Privacy Statement](https://docs.github.com/site-policy/privacy-policies/github-general-privacy-statement) | -Straight-line and sea-lane routes, coordinate entry, GPX files, the simulator and downloaded offline map areas work **offline** and contact none of these services. Update checks can be turned off by starting the app with `--no-update`. +Screen mirroring, screenshots, recordings, the API, straight-line and sea-lane routes, coordinate entry, GPX files, the simulator and downloaded offline map areas work **offline** and contact none of these services (the Developer Disk Image may be downloaded once, as listed above). Update checks can be turned off by starting the app with `--no-update`. ## Your real location When you press **Show my real location** or **Stop spoofing**, the app asks your computer's operating system for its approximate position. That request is handled by Windows (or your browser) and may involve its own location services; you can deny the permission. The position is only drawn on the map and is not stored or sent anywhere by the app. +## Other people on your screen + +Mirrored pictures, sound and recordings can show other people's messages, photos, names and voices. You decide whether to save or share them, and the [Terms of Use](TERMS.md) ask you to respect the law and other people's privacy when you do. + ## Children The app is not directed at children and collects no personal information from anyone. diff --git a/README.md b/README.md index 3b0cd1c..bf43559 100644 --- a/README.md +++ b/README.md @@ -1,60 +1,31 @@ -

Location Spoofer icon

+

iDevBench icon

-

Location Spoofer

+

iDevBench

-

A free Windows app that sets your iPhone's GPS location over USB, with no jailbreak.
-Teleport anywhere, drive routes that follow real roads at realistic speeds (with bends, roundabouts and braking), replay GPX files, or walk around live with the keyboard. No accounts, no telemetry.

+

A free Windows toolkit for working with your iPhone over USB, with no jailbreak and no Mac.
+Set the iPhone's GPS location: teleport anywhere, drive routes that follow real roads at realistic speeds (with bends, roundabouts and braking), replay GPX files, or walk around live with the keyboard. Mirror the iPhone's screen and sound on your PC, control it with the mouse and keyboard, and record it. Other programs can do the same through a local API. No accounts, no telemetry.

+ +

iDevBench was previously called Location Spoofer. Updating keeps your settings, favourites and routes.

- Website and live demo · - ⬇ Download the app (Standalone) · + Website and live demo · + ⬇ Download iDevBench · Browser edition · Getting started · + Features · Apple Devices (required) · Privacy · Terms

-

The app building a car route across London: two checkpoints are placed, the build shows each step, then three alternative routes appear labelled with their extra time
-Try a smaller version of the app in your browser at iphone-spoofer.vercel.app.

+

The app building a car route across London: two checkpoints are placed, the build shows each step, then three alternative routes appear labelled with their extra time
+Try a smaller version of the app in your browser at idevbench.vercel.app.

> **Use it responsibly.** Location simulation is meant for testing apps, demos and privacy. Many games, dating, banking, school, work and delivery apps forbid fake locations and may suspend your account. Apps can also detect simulation or use Wi-Fi, IP address and motion sensors, which this tool does not change. See the [Terms of Use](TERMS.md). -## Screenshots - - - - - - - - - - - - - - - - - - -
Teleport tab with a picked point and the spoofed position on the mapPlayback waiting at a hold checkpoint, with the live speed and heading on the map
Teleport: pick a point, see the jump distance, teleport.Playback: waiting at a "hold until Continue" checkpoint; the map shows live speed and heading.
Settings window with the theme picker and the map themeRoute tab: the main route and three alternatives, labelled on the map with their extra time
Settings: 17 colour themes and a dark or light map.Alternatives: up to three other routes, labelled with their extra time.
- - - - - - - - - - - - -
Build route button showing its progress and current stepA checkpoint being dragged to a new place in the listRight-click menu on a checkpoint: Delete, Insert after, Set wait, Make start
Building a route: the button shows each step and how far along it is.Reordering: drag a checkpoint by its handle; the others slide out of the way.Checkpoint menu: right-click a checkpoint on the map or in the list.
+## Contents -The screenshots are made by [`docs/screenshots/capture.js`](docs/screenshots/capture.js) with the default look (Graphite theme, dark OpenFreeMap map). +[Which download](#which-download-should-i-use) · [Getting started](#getting-started) · [Features](#features) · [Screenshots](#screenshots) · [Updates](#updates-and-test-builds) · [Google Maps](#optional-google-maps) · [Privacy](#privacy) · [Licence](#licence) ## Which download should I use? @@ -67,40 +38,9 @@ Most people should use the **standalone app**. The browser edition exists for iP | Size and start-up | Under 20 MB, starts instantly | About 80 MB, 10–20 s to start | | iOS 17.4 and newer, iOS 16 and older | ✅ | ✅ | | iOS 17.0–17.3 | ❌ | ✅ (needs administrator permission once per session) | +| Screen mirroring and control (iOS 27 and newer) | ✅ with sound | ✅, sound only on a Mac | -Both have the same look and features, and both update themselves. - -## Features - -* **Map:** a sharp map with a true dark style (OpenFreeMap), plus OpenStreetMap, satellite and topographic maps. The map button in the top right corner switches maps and the map theme (dark, light, or matching the app). Click to pick a point; right-click to jump there instantly. Pinch or scroll on a trackpad to zoom smoothly. -* **Offline maps:** save the area on screen (about a city per download) in *Settings › Offline maps*, and the map keeps working without internet. -* **Find places:** search by name, paste coordinates (decimal or 40°42'46"N), or paste any **Google Maps link**, including `maps.app.goo.gl` short links and directions links with several stops. -* **Routes:** - * add checkpoints on the map, then drag them on the map or in the list to move and reorder them; - * drag the route line to add a checkpoint there (the route rebuilds itself), double-click a checkpoint to delete it, or right-click it for **Delete**, **Insert after**, **Set wait** and **Make start**; - * a checkpoint can **hold until you press Continue** (or **N**), for example to wait at a door until your test is ready; - * each leg follows roads, cycle paths, footpaths, sea lanes or a straight line, routed by OpenStreetMap or by Google with your own API key; - * set a speed per leg, an exact speed at chosen checkpoints, and wait times; - * acceleration and braking change speed smoothly; - * ask for up to three alternative routes, labelled on the map with their extra time, and pick one in the list or on the map; - * the Build route button shows each step as it happens (routing each leg, speed limits, turns, ETA) and how far along it is; Cancel (or Esc) stops it, and changing the route or its settings cancels it by itself; - * the route line is outlined so it stands out from the roads, and coloured by speed in a smooth gradient, with a speed chart; - * hover a checkpoint in the list to highlight it on the map. -* **Roundabouts:** always driven at a normal roundabout speed for their size (about 20–40 km/h by car), whatever the road's own speed. -* **Road-aware driving (experimental):** - * follows each road's typical speed, and optionally public speed limits (not recommended: the public service is slow and often incomplete); - * takes every bend at the speed its radius allows for the vehicle (cars, bikes, walkers and boats differ), and slows on private or gated roads; - * aims for the same trip time (ETA) as Google Maps or OpenStreetMap, shown side by side. -* **GPX files** (a common file format for recorded trips): drop a file in to replay it with its own timing, re-time it, reverse it, or edit it as checkpoints. Routes can be exported as GPX. -* **Playback:** play, pause, seek, 0.25×–30× speed, loop or back-and-forth with an optional number of laps, optional GPS jitter, and a live speed and heading display on the map. -* **Joystick:** walk or drive live with W A S D, the arrow keys or the on-screen pad. -* **Stop spoofing:** one click returns the iPhone to its real GPS and shows your computer's real location on the map. -* **Made to be comfortable:** - * 17 colour themes (Graphite by default) and a dark or light map; - * folding sections, and a side menu you can resize or hide; - * single-key keyboard shortcuts that you can change (press **H** to see them); - * a setup guide on first run, and help icons that explain every tool; - * favourites, saved routes, and backup or restore. +Both have the same look and features (apart from the differences above), and both update themselves. The download files keep their original names (`LocationSpooferStandalone.exe` and `LocationSpooferBrowser.exe`) so copies that are already installed keep updating. ## Getting started @@ -114,13 +54,18 @@ Both have the same look and features, and both update themselves. 4. Press **Connect**. 5. **Pick a place and press Teleport here**, or build a route and press **Play**. Press **Stop spoofing** when you're done. -**Requirements:** +
+Requirements + * Windows 10 or 11 (64-bit) with the Microsoft Edge WebView2 Runtime, which is built into Windows 11 and installed on up-to-date Windows 10. -* An iPhone or iPad with Developer Mode. +* An iPhone or iPad with Developer Mode. Screen mirroring needs iOS 27 or newer. * A USB cable. * An internet connection for maps and road routing. -### Troubleshooting +
+ +
+Troubleshooting | Message | What to do | |---|---| @@ -131,17 +76,145 @@ Both have the same look and features, and both update themselves. | A speedometer app on the iPhone shows 0, or the heading arrow doesn't turn | Apple's location simulation only carries a position, so iOS reports no speed or course for it. Apps that work out speed from movement (navigation apps, most games) are fine. The app's own map shows the simulated speed and heading | | "My real location" says Windows blocked it | Turn on *Settings › Privacy & security › Location* and "Let desktop apps access your location" (the message has a button for it) | | Location stays wrong after you finish | Press **Stop spoofing**, or restart the iPhone | -| The app shows an older version number | An older copy is still running in the background. Close every Location Spoofer window, end any **location-spoofer** or **LocationSpooferStandalone** task in Task Manager, then open the new file | +| The app shows an older version number | An older copy is still running in the background. Close every iDevBench window, end any **location-spoofer** or **LocationSpooferStandalone** task in Task Manager, then open the new file | +| Mirroring: "won't share its screen while an app uses the camera or microphone" | Close Camera, Voice Memos or any app that is recording, then press Start mirroring again | +| Mirroring: "can't decode the iPhone's video (HEVC)" | Update the graphics driver, or install *HEVC Video Extensions* from the Microsoft Store | +| Mirroring: the picture stays black | Unlock the iPhone. Some apps hide their content from screen mirroring, for example video streaming apps | +| Mirroring: the picture freezes | It restarts by itself after a few seconds; press **Restart stream** next to the screen to do it at once | +| Mirroring: the picture is sideways | Press **Rotate** next to the screen | | Something else | [Open an issue](https://github.com/YK3D/iPhone-location-spoofer/issues/new) and describe what happened, with the app's version (*Settings › About*) | +
+ +## Features + +
+Map and places + +* **Map:** a sharp map with a true dark style (OpenFreeMap), plus OpenStreetMap, satellite and topographic maps. The map button in the top right corner switches maps and the map theme (dark, light, or matching the app). Click to pick a point; right-click to jump there instantly. Pinch or scroll on a trackpad to zoom smoothly. +* **Offline maps:** save the area on screen (about a city per download) in *Settings › Offline maps*, and the map keeps working without internet. +* **Find places:** search by name, paste coordinates (decimal or 40°42'46"N), or paste any **Google Maps link**, including `maps.app.goo.gl` short links and directions links with several stops. +* **Stop spoofing:** one click returns the iPhone to its real GPS and shows your computer's real location on the map. + +
+ +
+Building routes + +* Add checkpoints on the map, then drag them on the map or in the list to move and reorder them. +* Drag the route line to add a checkpoint there (the route rebuilds itself), double-click a checkpoint to delete it, or right-click it for **Delete**, **Insert after**, **Set wait** and **Make start**. +* A checkpoint can **hold until you press Continue** (or **N**), for example to wait at a door until your test is ready. +* Each leg follows roads, cycle paths, footpaths, sea lanes or a straight line, routed by OpenStreetMap or by Google with your own API key. +* Ask for up to three alternative routes, labelled on the map with their extra time, and pick one in the list or on the map. +* The Build route button shows each step as it happens (routing each leg, speed limits, turns, ETA) and how far along it is; Cancel (or Esc) stops it, and changing the route or its settings cancels it by itself. +* The route line is outlined so it stands out from the roads, and coloured by speed in a smooth gradient, with a speed chart. +* Hover a checkpoint in the list to highlight it on the map. + +
+ +
+Speed and driving realism + +* Set a speed per leg, an exact speed at chosen checkpoints, and wait times; acceleration and braking change speed smoothly. +* **Roundabouts:** always driven at a normal roundabout speed for their size (about 20–40 km/h by car), whatever the road's own speed. +* **Road-aware driving (experimental):** + * follows each road's typical speed, and optionally public speed limits (not recommended: the public service is slow and often incomplete); + * takes every bend at the speed its radius allows for the vehicle (cars, bikes, walkers and boats differ), and slows on private or gated roads; + * aims for the same trip time (ETA) as Google Maps or OpenStreetMap, shown side by side. + +
+ +
+GPX, playback and joystick + +* **GPX files** (a common file format for recorded trips): drop a file in to replay it with its own timing, re-time it, reverse it, or edit it as checkpoints. Routes can be exported as GPX. +* **Playback:** play, pause, seek, 0.25×–30× speed, loop or back-and-forth with an optional number of laps, optional GPS jitter, and a live speed and heading display on the map. +* **Joystick:** walk or drive live with W A S D, the arrow keys or the on-screen pad. + +
+ +
+Screen mirroring and control (Mirroring section) + +* **See the iPhone's screen** live in its own section of the app (switch between *Location* and *Mirroring* at the top), over the USB cable. Needs iOS 27 or newer. The picture turns with the phone. +* **Control it:** click to tap, drag to swipe, scroll with the mouse wheel, Ctrl + wheel (or a trackpad pinch) to pinch and zoom, right-click for Home. Buttons next to the screen for Home, Lock, Volume, Mute and Siri, and for the gestures: app switcher, Control Centre, notifications and Back. Over the screen the pointer is a small dot that dips when you click, and a swipe leaves a faint trail. +* **Type:** click the screen and type on your keyboard (Ctrl works as the iPhone's ⌘, so Ctrl+C and Ctrl+V copy and paste on the phone). +* **Sound:** hear what the iPhone plays (standalone app). +* **Screenshots and recordings:** save a picture, or record the screen with its sound as a video file, to your Downloads folder or a folder you choose in *Settings › Mirroring*. +* **Stats** shows the stream's frame rate, data rate and delay, and the iPhone's CPU, memory, GPU, battery and temperature; **Restart stream** restarts a frozen picture (the app also does this by itself). +* **For developers:** other programs on your computer can watch the screen, tap, type and set the location through the [local API](docs/API.md). +* **AI agents:** connect Claude, Codex, Cursor or another AI app to iDevBench and the agent can use the phone: see the screen, tap and type, set the location and drive routes. *Settings › AI agents* has one prompt to paste into the agent, and a button for Claude Desktop. There is also a [Claude Code plugin](docs/API.md#ai-agents-mcp). + +
+ +
+Comfort and customisation + +* 17 colour themes (Graphite by default) and a dark or light map. +* Folding sections, and a side menu you can resize or hide. +* Single-key keyboard shortcuts that you can change (press **H** to see them). +* A setup guide on first run, and help icons that explain every tool. +* Favourites, saved routes, and backup or restore. + +
+ +## Screenshots + +
+Show screenshots + + + + + + + + + + + + + + + + + + +
Teleport tab with a picked point and the spoofed position on the mapPlayback waiting at a hold checkpoint, with the live speed and heading on the map
Teleport: pick a point, see the jump distance, teleport.Playback: waiting at a "hold until Continue" checkpoint; the map shows live speed and heading.
Settings window with the theme picker and the map themeRoute tab: the main route and three alternatives, labelled on the map with their extra time
Settings: 17 colour themes and a dark or light map.Alternatives: up to three other routes, labelled with their extra time.
+ + + + + + + + + + + + +
Build route button showing its progress and current stepA checkpoint being dragged to a new place in the listRight-click menu on a checkpoint: Delete, Insert after, Set wait, Make start
Building a route: the button shows each step and how far along it is.Reordering: drag a checkpoint by its handle; the others slide out of the way.Checkpoint menu: right-click a checkpoint on the map or in the list.
+ +The screenshots are made by [`docs/screenshots/capture.js`](docs/screenshots/capture.js) with the default look (Graphite theme, dark OpenFreeMap map). + +
+ ## Updates and test builds +
+How updates work + The app checks for updates when it starts and every few hours. It downloads them in the background, checks that the download is intact and installs them when you press **Restart now**, or the next time you open the app. Want new features early? In **⚙ Settings › Updates** you can switch to **Test builds**. They may contain bugs; switch back to *Stable releases* at any time. +
+ ## Optional: Google Maps +
+Use Google for routing + Routes can come from Google Maps if you add your own API key in **⚙ Settings › Google Maps**: 1. Create a project and an API key in the [Google Cloud console](https://console.cloud.google.com/). @@ -150,13 +223,15 @@ Routes can come from Google Maps if you add your own API key in **⚙ Settings Google bills per request after its free monthly allowance. As Google's terms require, Google routes are shown on Google's map and cannot be exported as GPX. Without a key, routing uses free OpenStreetMap services, and Google Maps links still work. +
+ ## Privacy The app has no accounts, no analytics and no telemetry. Your favourites, routes and settings stay on your computer. Maps, searches and routes are requested directly from the services listed in the [Privacy Policy](PRIVACY.md). ## Licence -Location Spoofer is free to download and use, but it is **not open source**: © 2026 YK3D, all rights reserved. +iDevBench is free to download and use, but it is **not open source**: © 2026 YK3D, all rights reserved. * You may use the app, read its code and suggest changes through pull requests. * You may **not** copy its code, interface or icon into other projects, redistribute it, sell it or publish modified versions **without written permission**, and any permitted use must credit "Location Spoofer by YK3D". See [LICENSE](LICENSE). @@ -164,4 +239,4 @@ Location Spoofer is free to download and use, but it is **not open source**: © * Third-party components keep their own licences: [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). * To ask for permission, [open an issue](https://github.com/YK3D/iPhone-location-spoofer/issues/new). Security problems: see [SECURITY.md](SECURITY.md). Want to help? See [CONTRIBUTING.md](CONTRIBUTING.md). -Location Spoofer is an independent project and is not affiliated with, endorsed by or sponsored by Apple Inc. or Google LLC. iPhone is a trademark of Apple Inc.; Google Maps is a trademark of Google LLC. +iDevBench is an independent project and is not affiliated with, endorsed by or sponsored by Apple Inc. or Google LLC. iPhone is a trademark of Apple Inc.; Google Maps is a trademark of Google LLC. diff --git a/ROADMAP.md b/ROADMAP.md index 391b485..3345679 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -29,4 +29,4 @@ Ideas being considered for future versions. None of them is promised; suggestion - Search history and recent places. - More languages for the interface. - Portable mode (settings stored next to the `.exe`). -- Control the app from scripts, and record and replay test sessions. +- Record and replay test sessions (scripts can already control the app through the [local API](docs/API.md)). diff --git a/TERMS.md b/TERMS.md index fd612cb..f3e992b 100644 --- a/TERMS.md +++ b/TERMS.md @@ -1,12 +1,19 @@ # Terms of Use -_Last updated: 5 November 2026_ +_Last updated: 25 November 2026_ -By downloading, installing or using Location Spoofer (the standalone app or the browser version, together "the app") you agree to these terms. If you do not agree, do not use the app. +By downloading, installing or using iDevBench, formerly called Location Spoofer (the standalone app or the browser version, together "the app"), you agree to these terms. If you do not agree, do not use the app. ## 1. What the app is -The app is free software, made by YK3D, that simulates a GPS location on an iPhone you own or are allowed to use, through Apple's developer location-simulation features. It is intended for app development and testing, demonstrations, education and personal privacy. +The app is free software, made by YK3D, for working with an iPhone or iPad you own or are allowed to use, through Apple's developer features. It can: + +* simulate the device's GPS location; +* show the device's screen on your computer ("screen mirroring"), play the device's sound, and let you control the device with your mouse and keyboard; +* save screenshots and screen recordings; +* let other programs on your computer use these features through a local programming interface (the "API"). + +It is intended for app development and testing, demonstrations, education, accessibility and personal privacy. ## 2. Acceptable use @@ -15,23 +22,39 @@ You are solely responsible for how you use the app. You must not use it to: * break any law or regulation that applies to you; * commit fraud, for example to fake attendance, deliveries, mileage, working hours or presence at a location; * stalk, harass, deceive or endanger other people, or interfere with emergency services or safety systems; -* breach the terms of service of other apps, games or services. Many games, dating, banking, school, work and delivery apps forbid location simulation and may suspend or close accounts that use it. +* access, view, record or control a device without the permission of its owner and its user; +* record calls, video chats, voice messages or other people's conversations, messages or images without the consent the law requires. Recording laws differ between countries and states, and some require every person in a conversation to agree; +* copy or share content you have no right to, such as films, music or paid content. Some apps hide their content from screen mirroring, and the app does not try to get around that; +* breach the terms of service of other apps, games or services. Many games, dating, banking, school, work and delivery apps forbid location simulation or automated control, and may suspend or close accounts that use them. The app cannot hide that a location is simulated: apps can detect it, and other signals (Wi-Fi, IP address, motion sensors) are unaffected. -## 3. No warranty +## 3. Screen mirroring, recordings and remote control + +* Everything on the device's screen and everything it plays can appear on your computer while mirroring is on, including notifications, messages and passwords you type. Turn mirroring off, or keep sensitive apps closed, when other people can see your computer. +* Recordings and screenshots are saved on your computer, where you choose. You are responsible for storing, sharing and deleting them, and for the privacy of anyone who appears in them. +* Clicks, key presses and button presses sent by the app act on the real device exactly like your own touches. Check what you are doing before you tap: the app cannot undo a purchase, a deleted item or a sent message. +* Screen mirroring uses an Apple developer service that only recent iOS versions provide. It may stop working after an iOS update. + +## 4. The API for other programs + +While the app is open, programs on your computer can use its local API to do what the app can do: see the device's screen, control the device and change its location. Websites cannot use it, and it cannot be reached from other computers. Only run programs you trust, and close the app when you are not using it. Programs that use the API are not made by YK3D, and their own terms and privacy policies apply to them. See [docs/API.md](docs/API.md). + +The app includes a connector that lets AI agents use the API. An agent connected to it sees the screen and acts on the device by itself, and it can make mistakes: watch what it does, don't leave it unattended where a mistake can't be undone (purchases, messages, deleting data), and you remain responsible for what it does on your device. What you and the agent send to an AI service is covered by that service's terms. + +## 5. No warranty -THE APP IS PROVIDED "AS IS" AND "AS AVAILABLE", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING FITNESS FOR A PARTICULAR PURPOSE, ACCURACY AND NON-INFRINGEMENT. Routes, speeds, travel times and speed limits are estimates and may be wrong. **Never use the app for navigation or safety-critical purposes.** +THE APP IS PROVIDED "AS IS" AND "AS AVAILABLE", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING FITNESS FOR A PARTICULAR PURPOSE, ACCURACY AND NON-INFRINGEMENT. Routes, speeds, travel times and speed limits are estimates and may be wrong. Mirrored pictures and sound can lag, freeze or be incomplete. **Never use the app for navigation or safety-critical purposes.** -## 4. Limitation of liability +## 6. Limitation of liability -To the maximum extent permitted by law, the authors and contributors are not liable for any damages or losses arising from the use of, or inability to use, the app. This includes account suspensions, data loss, device problems, and charges from third-party services such as Google Maps Platform. Nothing in these terms limits liability that cannot be limited by law. +To the maximum extent permitted by law, the authors and contributors are not liable for any damages or losses arising from the use of, or inability to use, the app. This includes account suspensions, data loss, actions taken on a device through the app or its API, device problems, and charges from third-party services such as Google Maps Platform. Nothing in these terms limits liability that cannot be limited by law. -## 5. Your devices +## 7. Your devices -The app needs Developer Mode on the iPhone and communicates with Apple's developer services. You use these features at your own risk. Turn off location simulation ("Stop spoofing", or restart the iPhone) when you are done. +The app needs Developer Mode on the device and communicates with Apple's developer services. You use these features at your own risk. Turn off location simulation ("Stop spoofing", or restart the device) and screen mirroring when you are done. -## 6. Third-party services and keys +## 8. Third-party services and keys Maps, place search, routing, speed limits, updates and Developer Disk Images come from third parties (see [PRIVACY.md](PRIVACY.md)). Your use of them is subject to their terms, for example the [OpenStreetMap tile usage policy](https://operations.osmfoundation.org/policies/tiles/), the [Nominatim usage policy](https://operations.osmfoundation.org/policies/nominatim/) and the [Google Maps Platform Terms of Service](https://cloud.google.com/maps-platform/terms). @@ -43,23 +66,23 @@ If you add a Google Maps API key: The public OpenStreetMap services are run by volunteers; please do not use the app for heavy automated requests. -## 7. Trademarks and affiliation +## 9. Trademarks and affiliation -The app is an independent project. It is **not affiliated with, endorsed by or sponsored by Apple Inc. or Google LLC**. iPhone, iOS and Xcode are trademarks of Apple Inc. Google Maps is a trademark of Google LLC. Other names belong to their respective owners and are used only to describe compatibility. +The app is an independent project. It is **not affiliated with, endorsed by or sponsored by Apple Inc. or Google LLC**. iPhone, iPad, iOS and Xcode are trademarks of Apple Inc. Google Maps is a trademark of Google LLC. Other names belong to their respective owners and are used only to describe compatibility. -## 8. Ownership and licences +## 10. Ownership and licences -The app, its source code, interface, icon and documentation are owned by YK3D and protected by copyright. You may use the app for free, but you may not copy its code or artwork into other projects, redistribute it, sell it or publish modified versions without written permission, and any permitted use must credit "Location Spoofer by YK3D". The exact rules are in the licences: +The app, its source code, interface, icon and documentation are owned by YK3D and protected by copyright. You may use the app for free, but you may not copy its code or artwork into other projects, redistribute it, sell it or publish modified versions without written permission, and any permitted use must credit YK3D in the way the licences describe. The exact rules are in the licences: -* the standalone app, the shared interface, the icon and the documentation: the Location Spoofer License ([LICENSE](LICENSE)); +* the standalone app, the shared interface, the icon and the documentation: the Location Spoofer License ([LICENSE](LICENSE)), which keeps the app's former name; * the browser version: the GNU GPL v3 or later with additional terms that require the same credit ([browser/LICENSE](browser/LICENSE), [browser/NOTICE](browser/NOTICE)), because it is distributed together with GPL-licensed libraries. Those licences govern copying, modifying and redistributing the code. These terms govern using the app. -## 9. Updates and changes +## 11. Updates and changes The app can update itself from this repository's GitHub releases. Releases are checked with a SHA-256 checksum but are not code-signed. These terms may change; the version in this repository applies from its "Last updated" date. -## 10. Contact +## 12. Contact Report problems, or ask for permission to use the code, at . Report security issues as described in [SECURITY.md](SECURITY.md). diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 64aea97..9d3d5ed 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -1,6 +1,6 @@ # Third-party notices -Location Spoofer is built on open-source software and public data services. This file lists what is included in each edition, under which licence, and which online services the app uses at run time. +iDevBench (formerly Location Spoofer) is built on open-source software and public data services. This file lists what is included in each edition, under which licence, and which online services the app uses at run time. ## Licences of this project @@ -24,7 +24,8 @@ The licences below belong to the third-party components and are not changed by t | Component | Use | Licence | |---|---|---| -| [idevice](https://github.com/jkcoxson/idevice), [jktcp](https://crates.io/crates/jktcp) | iPhone communication (usbmuxd, lockdown, CoreDevice tunnel, DVT) | MIT | +| [idevice](https://github.com/jkcoxson/idevice), [jktcp](https://crates.io/crates/jktcp) | iPhone communication (usbmuxd, lockdown, CoreDevice tunnel, DVT, screen streaming and touch input) | MIT | +| [Fraunhofer FDK AAC](https://github.com/mstorsjo/fdk-aac) through [fdk-aac-rs](https://github.com/haileys/fdk-aac-rs) | Plays the iPhone's sound while mirroring (AAC-ELD decoding) | FDK AAC licence, full text in [docs/licenses/fdk-aac.txt](docs/licenses/fdk-aac.txt) (the Rust bindings are MIT). Included unmodified; its complete source code is available free of charge from [crates.io](https://crates.io/crates/fdk-aac-sys/0.5.0) and [GitHub](https://github.com/mstorsjo/fdk-aac). The licence grants no patent rights | | [wry](https://github.com/tauri-apps/wry), [tao](https://github.com/tauri-apps/tao) | Native window and Microsoft WebView2 | Apache-2.0 OR MIT | | [axum](https://github.com/tokio-rs/axum), [tokio](https://tokio.rs/), [reqwest](https://github.com/seanmonstar/reqwest), [rustls](https://github.com/rustls/rustls), [ring](https://github.com/briansmith/ring) | Local server, networking, TLS | MIT / Apache-2.0 / ISC-style (ring) | | [cssparser](https://github.com/servo/rust-cssparser), [selectors](https://github.com/servo/stylo), [dtoa-short](https://github.com/upsuper/dtoa-short), [option-ext](https://github.com/soc/option-ext) | Used by the window and settings-folder libraries | MPL-2.0. Included unmodified; their source code is available from [crates.io](https://crates.io/) at the versions listed in `standalone/Cargo.lock` | diff --git a/browser/requirements.txt b/browser/requirements.txt index b5b6939..bb5c140 100644 --- a/browser/requirements.txt +++ b/browser/requirements.txt @@ -1,6 +1,6 @@ # Device control. Written against 11.x; newer major versions may change the Python API # (the "Guide commands" connection method keeps working as long as the CLI does). -pymobiledevice3>=11.49,<12 +pymobiledevice3>=11.63,<12 # Offline sea-lane routing searoute>=1.6,<2 fastapi>=0.115 diff --git a/browser/run_mac_linux.sh b/browser/run_mac_linux.sh index ef74eee..297a443 100755 --- a/browser/run_mac_linux.sh +++ b/browser/run_mac_linux.sh @@ -1,5 +1,5 @@ #!/usr/bin/env sh -# iPhone Location Spoofer - macOS / Linux launcher +# iDevBench Browser Edition - macOS / Linux launcher set -e cd "$(dirname "$0")" PY="${PYTHON:-python3}" diff --git a/browser/run_windows.bat b/browser/run_windows.bat index cb46df2..872d2fc 100644 --- a/browser/run_windows.bat +++ b/browser/run_windows.bat @@ -1,5 +1,5 @@ @echo off -REM iPhone Location Spoofer - Windows launcher. Double-click to run. +REM iDevBench Browser Edition - Windows launcher. Double-click to run. cd /d "%~dp0" where py >nul 2>nul || (echo Python launcher "py" not found. Install Python 3.12 from python.org and tick "Add python.exe to PATH". & pause & exit /b 1) py -3.12 --version >nul 2>nul || (echo Python 3.12 is not installed. Install it from python.org/downloads. & pause & exit /b 1) diff --git a/browser/spoofer/__init__.py b/browser/spoofer/__init__.py index 90ff7ec..56f7723 100644 --- a/browser/spoofer/__init__.py +++ b/browser/spoofer/__init__.py @@ -1,4 +1,4 @@ -"""Location Spoofer, browser edition - a local map app that drives pymobiledevice3. +"""iDevBench (formerly Location Spoofer), browser edition - a local map app that drives pymobiledevice3. Copyright (c) 2026 YK3D. Licensed under the GNU GPL v3 or later with additional attribution terms (section 7): see browser/LICENSE and browser/NOTICE. diff --git a/browser/spoofer/__main__.py b/browser/spoofer/__main__.py index 51284d6..ee2b140 100644 --- a/browser/spoofer/__main__.py +++ b/browser/spoofer/__main__.py @@ -88,7 +88,7 @@ def _self_test() -> int: checks.append(("pymobiledevice3 CLI", out.returncode == 0 and "latitude" in out.stdout.lower())) ok = all(v for _, v in checks) - print(f"LocationSpoofer {__version__} self-test") + print(f"iDevBench Browser Edition {__version__} self-test") for name, v in checks: print(f" {'OK ' if v else 'FAIL'} {name}") if not checks[-1][1]: @@ -101,7 +101,7 @@ def main() -> None: if len(sys.argv) > 1 and sys.argv[1] == "pmd3-cli": sys.exit(_run_pmd3_cli(sys.argv[2:])) - ap = argparse.ArgumentParser(prog="LocationSpoofer", description="iPhone Location Spoofer") + ap = argparse.ArgumentParser(prog="LocationSpooferBrowser", description="iDevBench Browser Edition") ap.add_argument("--host", default="127.0.0.1", help="interface to listen on (default: this computer only)") ap.add_argument("--port", type=int, default=8765) ap.add_argument("--no-browser", action="store_true", help="do not open the browser automatically") @@ -110,10 +110,17 @@ def main() -> None: ap.add_argument("--version", action="store_true") ap.add_argument("--self-test", action="store_true", help=argparse.SUPPRESS) ap.add_argument("--wait-pid", type=int, help=argparse.SUPPRESS) + ap.add_argument("--mcp", action="store_true", help="connect an AI app (MCP over stdio) to the running app") args = ap.parse_args() from spoofer import __version__ + if args.mcp: + from spoofer.mcp import bridge + + bridge(args.port if "--port" in sys.argv else None) + return + if args.version: print(__version__) return @@ -162,7 +169,7 @@ def main() -> None: app.state.server = server if not args.no_browser: threading.Timer(1.5, lambda: webbrowser.open(url)).start() - print(f"\n iPhone Location Spoofer {__version__} is running at {url}\n Keep this window open. Close it (or press Ctrl+C) to quit.\n") + print(f"\n iDevBench Browser Edition {__version__} is running at {url}\n Keep this window open. Close it (or press Ctrl+C) to quit.\n") server.run() if getattr(app.state, "restart_requested", False): diff --git a/browser/spoofer/device/base.py b/browser/spoofer/device/base.py index 88d03e9..9fea12b 100644 --- a/browser/spoofer/device/base.py +++ b/browser/spoofer/device/base.py @@ -17,7 +17,7 @@ class DeviceInfo: name: str = "iPhone" ios_version: str = "" product_type: str = "" - connection: str = "" # USB / Network / Simulated + connection: str = "" # USB / Wi-Fi / Simulated transport: str = "" # how location commands reach it (DVT tunnel, lockdown, CLI, ...) notes: list[str] = field(default_factory=list) @@ -44,7 +44,8 @@ def connected(self) -> bool: async def list_devices(self) -> list[dict]: ... @abstractmethod - async def connect(self, udid: Optional[str] = None) -> DeviceInfo: ... + async def connect(self, udid: Optional[str] = None, connection: str = "auto") -> DeviceInfo: + """`connection`: "auto" (USB when the phone is plugged in, else Wi-Fi), "usb" or "network".""" @abstractmethod async def disconnect(self) -> None: ... @@ -61,6 +62,10 @@ async def reveal_developer_mode(self, udid: Optional[str] = None) -> str: async def mount_developer_image(self) -> str: raise DeviceError("Not supported by this connection method") + async def enable_wifi(self, udid: Optional[str] = None) -> str: + """Let the phone be reached over Wi-Fi from now on (needs it plugged in once).""" + raise DeviceError("Not supported by this connection method") + # Only used by non-live drivers async def play_gpx(self, path: str) -> None: raise DeviceError("Not supported by this connection method") diff --git a/browser/spoofer/device/cli.py b/browser/spoofer/device/cli.py index 1985e46..4887b46 100644 --- a/browser/spoofer/device/cli.py +++ b/browser/spoofer/device/cli.py @@ -169,7 +169,7 @@ async def list_devices(self) -> list[dict]: if isinstance(d, dict) ] - async def connect(self, udid: Optional[str] = None) -> DeviceInfo: + async def connect(self, udid: Optional[str] = None, connection: str = "auto") -> DeviceInfo: devices = await self.list_devices() if not devices: raise DeviceError("No iPhone found. Plug it in, unlock it, tap Trust and keep the Apple Devices app open.") diff --git a/browser/spoofer/device/mock.py b/browser/spoofer/device/mock.py index 299b7af..252ca60 100644 --- a/browser/spoofer/device/mock.py +++ b/browser/spoofer/device/mock.py @@ -4,11 +4,13 @@ from typing import Optional -from .base import DeviceDriver, DeviceInfo +from .base import DeviceDriver, DeviceError, DeviceInfo -# The pretend phone always reports this iOS version (the current major release). +# The pretend phones always report this iOS version (the current major release). SIMULATED_IOS = "27" +# Two pretend phones, so several iPhones at once can be tried without hardware. +SIMULATED_DEVICES = {"SIMULATED-0001": "Simulated iPhone", "SIMULATED-0002": "Simulated iPhone 2"} class MockDriver(DeviceDriver): @@ -22,12 +24,16 @@ def __init__(self) -> None: self.history: list[tuple[float, float]] = [] async def list_devices(self) -> list[dict]: - return [{"udid": "SIMULATED-0001", "name": "Simulated iPhone", "ios_version": SIMULATED_IOS, "connection": "Simulated"}] + return [{"udid": udid, "name": name, "ios_version": SIMULATED_IOS, "connection": "Simulated", "connections": ["Simulated"]} + for udid, name in SIMULATED_DEVICES.items()] - async def connect(self, udid: Optional[str] = None) -> DeviceInfo: + async def connect(self, udid: Optional[str] = None, connection: str = "auto") -> DeviceInfo: + udid = udid or next(iter(SIMULATED_DEVICES)) + if udid not in SIMULATED_DEVICES: + raise DeviceError("No such simulated iPhone") self.info = DeviceInfo( - udid="SIMULATED-0001", - name="Simulated iPhone", + udid=udid, + name=SIMULATED_DEVICES[udid], ios_version=SIMULATED_IOS, product_type="Simulated", connection="Simulated", @@ -52,3 +58,6 @@ async def reveal_developer_mode(self, udid: Optional[str] = None) -> str: async def mount_developer_image(self) -> str: return "Simulator: nothing to mount." + + async def enable_wifi(self, udid: Optional[str] = None) -> str: + return "Simulator: nothing to do." diff --git a/browser/spoofer/device/pmd3.py b/browser/spoofer/device/pmd3.py index 5272a7b..0e1ba5c 100644 --- a/browser/spoofer/device/pmd3.py +++ b/browser/spoofer/device/pmd3.py @@ -34,7 +34,8 @@ def _friendly(e: BaseException) -> str: hints = { "ConnectionFailedToUsbmuxdError": "Cannot reach the Apple device service. On Windows open the Apple Devices app (or iTunes) and keep it open.", "NoDeviceConnectedError": "No iPhone found. Plug it in with a cable, unlock it and tap Trust.", - "PasswordRequiredError": "Unlock the iPhone and try again.", + "PasswordRequiredError": "The iPhone is locked. Unlock it and try again.", + "DeviceLockedError": "The iPhone is locked. Unlock it and try again.", "PairingDialogResponsePendingError": "Tap Trust on the iPhone, enter the passcode, then try again.", "UserDeniedPairingError": "The iPhone refused to trust this computer. Unplug, plug back in and tap Trust.", "DeveloperModeIsNotEnabledError": "Developer Mode is off. Use 'Reveal Developer Mode', then turn it on in Settings > Privacy & Security.", @@ -45,6 +46,18 @@ def _friendly(e: BaseException) -> str: return hints.get(name, f"{name}: {msg}") +# The app's connection choice -> usbmuxd's connection type (None: USB when plugged in, else Wi-Fi) +CONNECTION_TYPES = {"auto": None, "usb": "USB", "network": "Network"} +WIFI_HELP = ( + "This iPhone can't be reached over Wi-Fi. Plug it in once, press Device tools > Allow Wi-Fi connection, " + "then keep it unlocked and on the same network as this computer." +) + + +def _conn_label(connection_type: Optional[str]) -> str: + return {"USB": "USB", "Network": "Wi-Fi"}.get(connection_type or "", connection_type or "") + + class Pmd3Driver(DeviceDriver): key = "pmd3" label = "Direct (pymobiledevice3 API)" @@ -66,13 +79,20 @@ async def list_devices(self) -> list[dict]: devices = await usbmux.list_devices() except Exception as e: raise DeviceError(_friendly(e)) from e + # A phone that is plugged in and on Wi-Fi is listed twice by usbmuxd: show it once, with both ways. + ways: dict[str, list[str]] = {} + for d in devices: + label = _conn_label(d.connection_type) + if label not in ways.setdefault(d.serial, []): + ways[d.serial].append(label) out = [] seen = set() - for d in devices: + for d in sorted(devices, key=lambda d: not d.is_usb): if d.serial in seen: continue seen.add(d.serial) - entry = {"udid": d.serial, "connection": d.connection_type, "name": "", "ios_version": ""} + conns = sorted(ways[d.serial], key=lambda c: c != "USB") + entry = {"udid": d.serial, "connection": " + ".join(conns), "connections": conns, "name": "", "ios_version": ""} try: ld = await create_using_usbmux(serial=d.serial, autopair=False) try: @@ -86,7 +106,7 @@ async def list_devices(self) -> list[dict]: out.append(entry) return out - async def connect(self, udid: Optional[str] = None) -> DeviceInfo: + async def connect(self, udid: Optional[str] = None, connection: str = "auto") -> DeviceInfo: await self.disconnect() try: from pymobiledevice3.lockdown import create_using_usbmux @@ -96,20 +116,27 @@ async def connect(self, udid: Optional[str] = None) -> DeviceInfo: stack = AsyncExitStack() notes: list[str] = [] try: - lockdown = await create_using_usbmux(serial=udid, autopair=True) + try: + lockdown = await create_using_usbmux(serial=udid, autopair=True, connection_type=CONNECTION_TYPES.get(connection)) + except Exception as e: + if connection == "network" and e.__class__.__name__ in ("NoDeviceConnectedError", "DeviceNotFoundError", "ConnectionFailedError"): + raise DeviceError(WIFI_HELP) from e + raise stack.push_async_callback(lockdown.close) short = lockdown.short_info version = lockdown.product_version + mux = getattr(getattr(lockdown, "service", None), "mux_device", None) + over = _conn_label(getattr(mux, "connection_type", None)) or "USB" info = DeviceInfo( udid=lockdown.udid, name=short.get("DeviceName", "iPhone"), ios_version=version, product_type=short.get("ProductType", ""), - connection="USB", + connection=over, ) if _major(version) >= 17: serial = udid or getattr(lockdown, "identifier", None) or lockdown.udid - rsd, how = await self._open_rsd(stack, serial, lockdown.udid) + rsd, how = await self._open_rsd(stack, serial, lockdown.udid, wifi=over == "Wi-Fi") notes.append(await self._try_mount(rsd)) from pymobiledevice3.services.dvt.instruments.dvt_provider import DvtProvider from pymobiledevice3.services.dvt.instruments.location_simulation import LocationSimulation @@ -135,25 +162,38 @@ async def connect(self, udid: Optional[str] = None) -> DeviceInfo: self.info = info return info - async def _open_rsd(self, stack: AsyncExitStack, serial: str, udid: str): - from pymobiledevice3.exceptions import UserspaceTunnelUnavailableError + async def _open_rsd(self, stack: AsyncExitStack, serial: str, udid: str, wifi: bool = False): + from pymobiledevice3.exceptions import PyMobileDevice3Exception, UserspaceTunnelUnavailableError from pymobiledevice3.remote.userspace_tunnel import UserspaceRsdTunnel - try: - tunnel = UserspaceRsdTunnel(serial=serial, remotepairing_fallback=False) - rsd = await tunnel.aopen() - stack.push_async_callback(tunnel.aclose) - return rsd, "userspace tunnel (no admin)" - except UserspaceTunnelUnavailableError: - log.info("userspace tunnel unavailable (iOS 17.0-17.3?), trying tunneld") - # iOS 17.0-17.3: a privileged tunneld must already be running. + why = "This iOS version needs tunneld." + if wifi: + # The no-admin tunnel always picks the cable when there is one, so a Wi-Fi connection + # goes through tunneld, which reaches phones over the network. + why = "An iOS 17+ iPhone over Wi-Fi needs tunneld in the browser version (the standalone app doesn't)." + else: + try: + tunnel = UserspaceRsdTunnel(serial=serial, remotepairing_fallback=False) + rsd = await tunnel.aopen() + stack.push_async_callback(tunnel.aclose) + return rsd, "userspace tunnel (no admin)" + except UserspaceTunnelUnavailableError: + log.info("userspace tunnel unavailable (iOS 17.0-17.3?), trying tunneld") + except PyMobileDevice3Exception as e: + # pymobiledevice3 runs one no-admin tunnel per process: a second iOS 17+ iPhone + # (a mirror) has to use tunneld. + if "already active" not in str(e): + raise + log.info("a userspace tunnel is already open (another iPhone), trying tunneld") + why = "A second iOS 17+ iPhone needs tunneld in the browser version (the standalone app doesn't)." + # iOS 17.0-17.3, Wi-Fi, or a second phone: a privileged tunneld must already be running. from pymobiledevice3.tunneld.api import get_tunneld_devices try: rsds = await get_tunneld_devices() except Exception as e: raise DeviceError( - "This iOS version needs tunneld. Use Device tools > Start tunnel helper (admin), keep its window open, then connect again." + f"{why} Use Device tools > Start tunnel helper (admin), keep its window open, then connect again." ) from e match = None for r in rsds: @@ -179,6 +219,8 @@ async def _try_mount(self, provider: Any) -> str: return "" except Exception as e: # location may still work if an image is mounted already log.warning("DDI auto-mount failed: %r", e) + if "locked" in str(e).lower() or e.__class__.__name__ in ("PasswordRequiredError", "DeviceLockedError"): + return "Could not mount the Developer Disk Image: the iPhone is locked. Unlock it and connect again." return f"Could not auto-mount the Developer Disk Image ({_friendly(e)}). If setting a location fails, check Developer Mode and the internet connection." async def disconnect(self) -> None: @@ -229,5 +271,21 @@ async def mount_developer_image(self) -> str: if not self.connected: raise DeviceError("Connect first") # Reconnecting runs the mount step with the right provider (RSD on iOS 17+). - info = await self.connect(self.info.udid if self.info else None) + conn = "network" if self.info and self.info.connection == "Wi-Fi" else "auto" + info = await self.connect(self.info.udid if self.info else None, conn) return " ".join(info.notes) or "Developer Disk Image is mounted." + + async def enable_wifi(self, udid: Optional[str] = None) -> str: + """Turns on the phone's "Show this iPhone when on Wi-Fi" setting (Wi-Fi sync), over the cable.""" + try: + from pymobiledevice3.lockdown import create_using_usbmux + + ld = await create_using_usbmux(serial=udid or (self.info.udid if self.info else None), autopair=True, connection_type="USB") + try: + await ld.set_enable_wifi_connections(True) + finally: + await ld.close() + except Exception as e: + raise DeviceError(f"Plug the iPhone in with a cable for this step. ({_friendly(e)})") from e + return ("Wi-Fi connections are on for this iPhone. Choose Wi-Fi in Device tools > Connect over, keep the phone " + "unlocked on the same network, and connect.") diff --git a/browser/spoofer/gpx_io.py b/browser/spoofer/gpx_io.py index 3489c8c..ffec65a 100644 --- a/browser/spoofer/gpx_io.py +++ b/browser/spoofer/gpx_io.py @@ -122,7 +122,7 @@ def write_gpx( start = start or datetime.now(timezone.utc).replace(microsecond=0) lines = [ '', - '', + '', f" {escape(name)}", ] for lat, lon, wname in waypoints: diff --git a/browser/spoofer/mcp.py b/browser/spoofer/mcp.py new file mode 100644 index 0000000..d6adf23 --- /dev/null +++ b/browser/spoofer/mcp.py @@ -0,0 +1,214 @@ +"""Model Context Protocol for AI agents (Claude, Cursor, ...): ``POST /mcp``, and ``--mcp`` over stdio. + +Same tools and behaviour as the standalone app (standalone/src/server.rs, ``mcp``): both read the +list from ui/mcp-tools.json. Each tool is one or more calls to this app's own API, made in-process; +``{key}`` in a path comes from the arguments or the previous answer. +""" + +from __future__ import annotations + +import asyncio +import base64 +import json +import sys +import urllib.error +import urllib.request +from pathlib import Path +from typing import Any, Optional +from urllib.parse import quote + +import httpx + +from . import __version__ + +VERSIONS = ("2025-06-18", "2025-03-26", "2024-11-05") +_spec: Optional[dict] = None + + +_static = Path(".") + + +def spec(static: Path) -> dict: + global _spec, _static + _static = static + if _spec is None: + _spec = json.loads((static / "mcp-tools.json").read_text(encoding="utf-8")) + return _spec + + +def _reply(mid: Any, result: Any) -> dict: + return {"jsonrpc": "2.0", "id": mid, "result": result} + + +def _error(mid: Any, code: int, message: str) -> dict: + return {"jsonrpc": "2.0", "id": mid, "error": {"code": code, "message": message}} + + +async def handle(msg: Any, app: Any, static: Path) -> Optional[dict]: + """One JSON-RPC message -> the answer, or None for a notification.""" + if not isinstance(msg, dict): + return _error(None, -32600, "Send one JSON-RPC message at a time") + if "id" not in msg: + return None + mid, method, params = msg["id"], msg.get("method"), msg.get("params") or {} + s = spec(static) + if method == "initialize": + asked = params.get("protocolVersion") + return _reply(mid, {"protocolVersion": asked if asked in VERSIONS else VERSIONS[0], "capabilities": {"tools": {}}, + "instructions": s["instructions"], "serverInfo": {"name": "idevbench", "version": __version__}}) + if method == "ping": + return _reply(mid, {}) + if method == "tools/list": + return _reply(mid, {"tools": [{k: t[k] for k in ("name", "description", "inputSchema")} for t in s["tools"]]}) + if method == "tools/call": + tool = next((t for t in s["tools"] if t["name"] == params.get("name")), None) + if tool is None: + return _error(mid, -32602, f"Unknown tool '{params.get('name')}'") + args = params.get("arguments") if isinstance(params.get("arguments"), dict) else {} + try: + return _reply(mid, {"content": await run(tool, dict(args), app)}) + except _ToolError as e: + return _reply(mid, {"content": [_text(str(e))], "isError": True}) + return _error(mid, -32601, f"Method not found: {method}") + + +class _ToolError(Exception): + pass + + +def _text(v: Any) -> dict: + return {"type": "text", "text": v if isinstance(v, str) else json.dumps(v, indent=2, ensure_ascii=False)} + + +async def run(tool: dict, args: dict, app: Any) -> list: + steps = tool["call"] + if steps[0][0] == "GUIDE": + return [_text(_static.joinpath("mcp-guide.md").read_text(encoding="utf-8"))] + if steps[0][0] == "WAIT": + ms = min(int(args.get("ms") or 1000), 10000) + await asyncio.sleep(ms / 1000) + return [_text(f"Waited {ms} ms.")] + answers: list = [] + transport = httpx.ASGITransport(app=app) + async with httpx.AsyncClient(transport=transport, base_url="http://127.0.0.1", timeout=120) as client: + for i, step in enumerate(steps): + method, path = step[0], step[1] + while "{" in path: + a, b = path.index("{"), path.index("}") + key = path[a + 1 : b] + v = args.pop(key, None) if i == 0 else None + if v is None and answers and isinstance(answers[-1], dict): + v = answers[-1].get(key) + if v is None: + raise _ToolError(f"'{key}' is missing") + path = path[:a] + quote(str(v), safe="") + path[b + 1 :] + # The tool's arguments go to the first call: as the query of a GET, else merged into its body. + body = dict(step[2]) if len(step) > 2 else {} + if i == 0 and method == "GET": + r = await client.get(path, params={k: v if isinstance(v, str) else json.dumps(v) for k, v in args.items()}) + else: + if i == 0: + body.update(args) + r = await client.request(method, path, json=body) + kind = r.headers.get("content-type", "") + if kind.startswith("image/") and r.is_success: + return [{"type": "image", "data": base64.b64encode(r.content).decode(), "mimeType": kind}] + try: + v = r.json() + except ValueError: + v = r.text + if not r.is_success: + raise _ToolError(v.get("detail") if isinstance(v, dict) and isinstance(v.get("detail"), str) else f"HTTP {r.status_code}: {v}") + answers.append(v) + returns = tool.get("returns") + out = {k: answers[returns[0]].get(k) for k in returns[1]} if returns else answers[-1] + return [_text(out)] + + +def command(host: str) -> dict: + """How AI apps reach this app: the /mcp address (from the address the page used) and the program + to start for apps that only start programs (``--mcp``, which passes messages to this app).""" + port = host.rsplit(":", 1)[1] if ":" in host else "" + extra = ["--port", port] if port.isdigit() and port not in ("8765", "8766") else [] + if getattr(sys, "frozen", False): + return {"url": f"http://{host}/mcp", "command": sys.executable, "args": ["--mcp", *extra], "env": {}} + browser_dir = str(Path(__file__).resolve().parents[1]) + return {"url": f"http://{host}/mcp", "command": sys.executable, "args": ["-m", "spoofer", "--mcp", *extra], "env": {"PYTHONPATH": browser_dir}} + + +def claude_desktop_configs() -> list[Path]: + """Claude Desktop's config files: %APPDATA%\\Claude (or the Microsoft Store copy's), ~/Library/Application Support/Claude, ~/.config/Claude.""" + import os + + name = "claude_desktop_config.json" + if os.environ.get("SPOOFER_CLAUDE_DESKTOP_DIR"): + return [Path(os.environ["SPOOFER_CLAUDE_DESKTOP_DIR"]) / name] + if sys.platform == "win32": + dirs = [Path(os.environ.get("APPDATA", Path.home() / "AppData" / "Roaming")) / "Claude"] + packages = Path(os.environ.get("LOCALAPPDATA", Path.home() / "AppData" / "Local")) / "Packages" + if packages.is_dir(): + dirs += [p / "LocalCache" / "Roaming" / "Claude" for p in packages.glob("Claude_*")] + elif sys.platform == "darwin": + dirs = [Path.home() / "Library" / "Application Support" / "Claude"] + else: + dirs = [Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "Claude"] + existing = [d / name for d in dirs if d.exists()] + return existing or [dirs[0] / name] + + +def add_to_claude_desktop(host: str) -> list[str]: + """Adds this app to Claude Desktop's MCP servers, keeping everything else in its config.""" + cmd = command(host) + entry = {"command": cmd["command"], "args": cmd["args"], **({"env": cmd["env"]} if cmd["env"] else {})} + written = [] + for path in claude_desktop_configs(): + cfg: Any = {} + if path.exists() and path.read_text(encoding="utf-8").strip(): + try: + cfg = json.loads(path.read_text(encoding="utf-8")) + except ValueError: + raise ValueError(f"Claude Desktop's settings file can't be read, so it was left alone: {path}") from None + if not isinstance(cfg, dict): + raise ValueError(f"Claude Desktop's settings file has an unexpected shape, so it was left alone: {path}") + if not isinstance(cfg.get("mcpServers"), dict): + cfg["mcpServers"] = {} + cfg["mcpServers"]["idevbench"] = entry + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_suffix(".json.tmp") + tmp.write_text(json.dumps(cfg, indent=2), encoding="utf-8") + tmp.replace(path) + written.append(str(path)) + return written + + +def bridge(port: Optional[int]) -> None: + """``--mcp``: for AI apps that start MCP servers as programs (Claude Desktop and others). Passes each + message from stdin to the running app's /mcp and prints the answer; the app must be open.""" + urls = [f"http://127.0.0.1:{port}/mcp"] if port else ["http://127.0.0.1:8766/mcp", "http://127.0.0.1:8765/mcp"] + opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + for line in sys.stdin: + if not line.strip(): + continue + answer = None + for url in urls: + req = urllib.request.Request(url, data=line.encode(), method="POST", + headers={"Content-Type": "application/json", "Accept": "application/json, text/event-stream"}) + try: + with opener.open(req, timeout=300) as r: + answer = r.read().decode() + break + except urllib.error.HTTPError as e: + answer = e.read().decode() + break + except OSError: + continue + if answer is None: + try: + msg = json.loads(line) + except ValueError: + msg = None + if isinstance(msg, dict) and "id" in msg: + answer = json.dumps(_error(msg["id"], -32000, "iDevBench is not running. Open it, then try again.")) + if answer and answer.strip(): + sys.stdout.write(answer.strip() + "\n") + sys.stdout.flush() diff --git a/browser/spoofer/mirrors.py b/browser/spoofer/mirrors.py new file mode 100644 index 0000000..3324605 --- /dev/null +++ b/browser/spoofer/mirrors.py @@ -0,0 +1,146 @@ +"""More than one iPhone at a time: extra phones ("mirrors") follow the main one. + +The player only ever talks to the main phone (through FanOut). Every position it sends is also +handed to each mirror, which sends it from its own task: a slow or lost mirror never holds up +playback on the main phone. A mirror that is behind skips straight to the newest position, and a +mirror that stops answering is marked as lost (the others keep going) until it is removed. +""" + +from __future__ import annotations + +import asyncio +import contextlib +from typing import Callable, Optional + +from .device.base import DeviceDriver, DeviceError, DeviceInfo + +SEND_TIMEOUT_S = 20.0 + + +class MirrorLink: + def __init__(self, driver: DeviceDriver) -> None: + self.driver = driver + self.info: Optional[DeviceInfo] = driver.info + self.error: Optional[str] = None + self.sent = 0 + self._busy = False + self._pending: Optional[tuple] = None # ("set", lat, lon) or ("clear",): only the newest counts + self._wake = asyncio.Event() + self._task = asyncio.create_task(self._run()) + + @property + def lost(self) -> bool: + return self.error is not None + + def push_set(self, lat: float, lon: float) -> None: + if not self.lost: + self._pending = ("set", lat, lon) + self._wake.set() + + def push_clear(self) -> None: + if not self.lost: + self._pending = ("clear",) + self._wake.set() + + async def settle(self, timeout: float = 5.0) -> None: + """Wait until the newest position has been sent (tests, and before removing a mirror).""" + end = asyncio.get_running_loop().time() + timeout + while (self._pending is not None or self._wake.is_set() or self._busy) and not self.lost: + if asyncio.get_running_loop().time() > end: + return + await asyncio.sleep(0.01) + await asyncio.sleep(0) + + async def _run(self) -> None: + while True: + await self._wake.wait() + self._wake.clear() + cmd, self._pending = self._pending, None + if cmd is None: + continue + self._busy = True + try: + if cmd[0] == "set": + await asyncio.wait_for(self.driver.set_location(cmd[1], cmd[2]), SEND_TIMEOUT_S) + else: + await asyncio.wait_for(self.driver.clear_location(), SEND_TIMEOUT_S) + self.sent += 1 + except asyncio.CancelledError: + raise + except asyncio.TimeoutError: + self.error = "The iPhone stopped answering." + return + except Exception as e: # DeviceError or a transport failure: this mirror is lost + self.error = str(e) or e.__class__.__name__ + return + finally: + self._busy = False + + async def close(self, clear: bool) -> None: + """Stop following; with `clear`, the phone goes back to its real location first.""" + if clear and not self.lost: + await self.settle(2.0) + self._task.cancel() + with contextlib.suppress(asyncio.CancelledError, Exception): + await self._task + if clear and not self.lost: + with contextlib.suppress(Exception): + await asyncio.wait_for(self.driver.clear_location(), 10) + with contextlib.suppress(Exception): + await self.driver.disconnect() + + def to_dict(self) -> dict: + d = self.info.to_dict() if self.info else {} + d.update({"state": "lost" if self.lost else "ok", "error": self.error}) + return d + + +class FanOut(DeviceDriver): + """What the player talks to: the main device, plus every mirror (without waiting for them).""" + + key = "fanout" + label = "Main device and mirrors" + + def __init__(self, primary: Callable[[], DeviceDriver], mirrors: Callable[[], list[MirrorLink]]) -> None: + # (no super().__init__(): `info` is the main device's, read through the property below) + self._primary = primary + self._mirrors = mirrors + + @property + def info(self) -> Optional[DeviceInfo]: # type: ignore[override] + return self._primary().info + + @property + def live(self) -> bool: # type: ignore[override] + return self._primary().live + + async def list_devices(self) -> list[dict]: + return await self._primary().list_devices() + + async def connect(self, udid: Optional[str] = None, connection: str = "auto") -> DeviceInfo: + raise DeviceError("Connect through the server") + + async def disconnect(self) -> None: + await self._primary().disconnect() + + async def set_location(self, lat: float, lon: float) -> None: + await self._primary().set_location(lat, lon) + for m in self._mirrors(): + m.push_set(lat, lon) + + async def clear_location(self) -> None: + await self._primary().clear_location() + for m in self._mirrors(): + m.push_clear() + + async def play_gpx(self, path: str) -> None: + await self._primary().play_gpx(path) + + async def stop_gpx(self) -> None: + await self._primary().stop_gpx() + + async def reveal_developer_mode(self, udid: Optional[str] = None) -> str: + return await self._primary().reveal_developer_mode(udid) + + async def mount_developer_image(self) -> str: + return await self._primary().mount_developer_image() diff --git a/browser/spoofer/offline.py b/browser/spoofer/offline.py index a8d4b74..9eda766 100644 --- a/browser/spoofer/offline.py +++ b/browser/spoofer/offline.py @@ -35,7 +35,7 @@ GLYPH_RANGES = ("0-255", "256-511", "512-767", "768-1023", "1024-1279", "8192-8447", "8448-8703") RELIEF_PREFIX = "natural_earth/ne2sr/" TILE_PREFIX = "planet-tiles/" -USER_AGENT = f"LocationSpoofer/{__version__} (+https://github.com/YK3D/iPhone-location-spoofer)" +USER_AGENT = f"iDevBench/{__version__} (+https://github.com/YK3D/iPhone-location-spoofer)" _ALLOWED = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-/%@,") # 1x1 transparent PNG: answer for a relief tile that is neither cached nor reachable EMPTY_PNG = bytes.fromhex( diff --git a/browser/spoofer/routing.py b/browser/spoofer/routing.py index 6cc40de..53b1db3 100644 --- a/browser/spoofer/routing.py +++ b/browser/spoofer/routing.py @@ -27,7 +27,7 @@ from . import geo, google_api, road_speed log = logging.getLogger(__name__) -USER_AGENT = "iPhone-Location-Spoofer/1.0 (local desktop app)" +USER_AGENT = "iDevBench/1.0 (local desktop app)" OSRM_URLS = { "car": os.environ.get("SPOOFER_OSRM_CAR", "https://routing.openstreetmap.de/routed-car"), diff --git a/browser/spoofer/screen.py b/browser/spoofer/screen.py new file mode 100644 index 0000000..8591c75 --- /dev/null +++ b/browser/spoofer/screen.py @@ -0,0 +1,977 @@ +"""Screen mirroring: the iPhone's screen and sound in the app, and mouse/keyboard control. + +Same behaviour, messages and WebSocket format as the standalone app (standalone/src/screen). +iOS 27+ streams its display through ``com.apple.coredevice.displayservice`` as HEVC over RTP +and its sound as AAC-ELD; touches, buttons and keys go back through the CoreDevice HID +services, which only accept input while a stream runs. pymobiledevice3 provides the services. + +WebSocket messages to clients (``/api/screen/ws``): + +* ``[1][width u16][height u16][codec length u8][codec][hvcC]``: decoder setup; +* ``[2][key u8][timestamp µs u64][frame as 4-byte length-prefixed NAL units]``; +* ``[3][timestamp µs u64][PCM s16le, 48 kHz, stereo]``; +* text: the status JSON whenever it changes. +""" + +from __future__ import annotations + +import asyncio +import contextlib +import json +import logging +import random +import struct +import sys +import time +import uuid +from contextlib import AsyncExitStack +from typing import Any, Optional + +log = logging.getLogger(__name__) + +# name -> (HID usage page, usage, hold in seconds). Siri needs a long press. +BUTTONS = { + "home": (0x0C, 0x40, 0.05), + # shortcut: lock uses the side button's usage with a longer press; unconfirmed on a real iPhone, change the usage if it still does nothing. + "lock": (0x0C, 0x30, 0.25), + "volume-up": (0x0C, 0xE9, 0.05), + "volume-down": (0x0C, 0xEA, 0.05), + "mute": (0x0C, 0xE2, 0.05), + "siri": (0x0C, 0xCF, 1.0), +} + + +# System gestures: start and end (fractions of the upright screen), drag time and hold in seconds. +GESTURES = { + "home": ((0.5, 0.995), (0.5, 0.55), 0.2, 0), + "app_switcher": ((0.5, 0.995), (0.5, 0.62), 0.26, 0.45), + "control_centre": ((0.92, 0.004), (0.92, 0.45), 0.26, 0), + "notification_centre": ((0.3, 0.004), (0.3, 0.6), 0.26, 0), + "back": ((0.004, 0.5), (0.65, 0.5), 0.26, 0), +} +COMMAND = 0xE3 + + +class ScreenError(Exception): + """Shown to the user as is (HTTP 409).""" + + +def _coord(v: dict, k: str) -> int: + f = v.get(k) + if isinstance(f, bool) or not isinstance(f, (int, float)): + raise ValueError(f"'{k}' must be a number from 0 to 1") + if not 0 <= f <= 1: + raise ValueError(f"'{k}' must be from 0 to 1 (a fraction of the screen)") + return round(f * 65535) + + +def parse_input(v: Any) -> tuple: + """Parse one input message (coordinates are fractions of the screen, top left 0,0). + + ``{"t":"touch","phase":"down|move|up","x":..,"y":..}`` (plus ``"x2","y2"`` for a second finger), + ``{"t":"tap","x":..,"y":..}``, ``{"t":"swipe","x1":..,"y1":..,"x2":..,"y2":..,"ms":300}``, + ``{"t":"long_press","x":..,"y":..,"ms":800}``, ``{"t":"gesture","name":"app_switcher"}``, ``{"t":"button","name":"home"}``, + ``{"t":"key","usage":40,"down":true}`` (no ``down``: press and release; ``"command":true`` holds ⌘), + ``{"t":"text","text":"hi"}``, ``{"t":"keyframe"}``, ``{"t":"refresh"}``. + Raises ValueError with a message for the user. + """ + if not isinstance(v, dict): + raise ValueError(_KINDS) + t = v.get("t") + if t == "touch": + if v.get("phase") not in ("down", "move", "up"): + raise ValueError("'phase' must be down, move or up") + second = (_coord(v, "x2"), _coord(v, "y2")) if "x2" in v or "y2" in v else None + return ("touch", v["phase"], _coord(v, "x"), _coord(v, "y"), second) + if t == "tap": + return ("tap", _coord(v, "x"), _coord(v, "y")) + if t == "swipe": + ms = v.get("ms", 300) + ms = min(max(int(ms), 50), 5000) if isinstance(ms, int) and not isinstance(ms, bool) else 300 + return ("swipe", _coord(v, "x1"), _coord(v, "y1"), _coord(v, "x2"), _coord(v, "y2"), ms) + if t == "long_press": + ms = v.get("ms", 800) + ms = min(max(int(ms), 100), 5000) if isinstance(ms, int) and not isinstance(ms, bool) else 800 + return ("long_press", _coord(v, "x"), _coord(v, "y"), ms) + if t == "gesture": + if v.get("name") not in GESTURES: + raise ValueError(f"Unknown gesture '{v.get('name', '')}'. Use one of: home, app_switcher, control_centre, notification_centre, back") + return ("gesture", v["name"]) + if t == "button": + name = v.get("name", "") + if name not in BUTTONS: + raise ValueError(f"Unknown button '{name}'. Use one of: home, lock, volume-up, volume-down, mute, siri") + return ("button", name) + if t == "key": + usage = v.get("usage") + if isinstance(usage, bool) or not isinstance(usage, int) or not 4 <= usage <= 0xE7: + raise ValueError("'usage' must be a HID keyboard usage (4–231)") + if "down" in v and not isinstance(v["down"], bool): + raise ValueError("'down' must be true or false") + return ("key", usage, v.get("down"), v.get("command") is True) + if t == "text": + text = v.get("text") + if not isinstance(text, str): + raise ValueError("'text' must be a string") + if len(text) > 2000: + raise ValueError("Type at most 2000 characters at a time") + return ("text", text) + if t in ("keyframe", "refresh"): + return (t,) + raise ValueError(_KINDS) + + +_KINDS = "'t' must be touch, tap, swipe, long_press, gesture, button, key, text, keyframe or refresh" + + +def is_move(i: tuple) -> bool: + """A finger moving: when moves pile up, only the newest needs sending.""" + return i[0] == "touch" and i[1] == "move" + + +def upright_to_native(u: float, v: float, rotation: int) -> tuple[int, int]: + """A point on the upright picture (fractions) -> the phone's native touch coordinates.""" + x, y = {90: (v, 1 - u), 180: (1 - u, 1 - v), 270: (1 - v, u)}.get(rotation, (u, v)) + return round(min(max(x, 0), 1) * 65535), round(min(max(y, 0), 1) * 65535) + + +_SHIFTED_DIGITS = "!@#$%^&*()" +_PUNCT = {"-": "_", "=": "+", "[": "{", "]": "}", "\\": "|", ";": ":", "'": '"', "`": "~", ",": "<", ".": ">", "/": "?"} +_PUNCT_USAGE = dict(zip(_PUNCT, (0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38))) + + +def char_usage(c: str) -> Optional[tuple[int, bool]]: + """HID keyboard usage and whether Shift is needed, for one character (US layout).""" + if "a" <= c <= "z": + return 0x04 + ord(c) - ord("a"), False + if "A" <= c <= "Z": + return 0x04 + ord(c) - ord("A"), True + if "1" <= c <= "9": + return 0x1E + ord(c) - ord("1"), False + fixed = {"0": (0x27, False), "\n": (0x28, False), "\t": (0x2B, False), " ": (0x2C, False)} + if c in fixed: + return fixed[c] + if c and c in _SHIFTED_DIGITS: + return 0x1E + _SHIFTED_DIGITS.index(c), True + for plain, shifted in _PUNCT.items(): + if c in (plain, shifted): + return _PUNCT_USAGE[plain], c == shifted + return None + + +# ---------------------------------------------------------------- HEVC +NAL_VPS, NAL_SPS, NAL_PPS, NAL_AUD, NAL_AP, NAL_FU = 32, 33, 34, 35, 48, 49 +# Apple's display service ends every coded slice with this footer; it is not HEVC data. +APPLE_SLICE_FOOTER = bytes.fromhex("04f00ac0000003000004ec0ab003") + + +def nal_type(nal: bytes) -> int: + return (nal[0] >> 1) & 0x3F if nal else 0xFF + + +def _strip_footer(nal: bytes) -> bytes: + if nal_type(nal) <= 31 and nal.endswith(APPLE_SLICE_FOOTER): + return nal[: -len(APPLE_SLICE_FOOTER)] + return nal + + +class Depacketizer: + """RTP/HEVC (RFC 7798) to whole frames: ``push`` returns ``[(rtp_ts, key, [nal, ...])]``.""" + + def __init__(self) -> None: + self.expect_seq: Optional[int] = None + self.fu: Optional[bytearray] = None + self.cur: list[bytes] = [] + self.cur_ts: Optional[int] = None + self.cur_key = False + self.waiting_for_key = True # after a loss, frames are held back until a keyframe + self.vps = self.sps = self.pps = None + self.config_changed = False + self.lost_packets = 0 + + def push(self, seq: int, ts: int, marker: bool, payload: bytes) -> list: + done: list = [] + if self.expect_seq is not None: + gap = (seq - self.expect_seq) & 0xFFFF + if gap >= 0x8000: + return done # a late duplicate + if gap: + self.lost_packets += gap + self.fu, self.cur, self.cur_key, self.cur_ts = None, [], False, None + self.waiting_for_key = True + self.expect_seq = (seq + 1) & 0xFFFF + if self.cur_ts is not None and self.cur_ts != ts: + self._finish(done) + self.cur_ts = ts + if len(payload) < 2: + return done + t = nal_type(payload) + if t == NAL_AP: + i = 2 + while i + 2 <= len(payload): + n = int.from_bytes(payload[i : i + 2], "big") + i += 2 + if n == 0 or i + n > len(payload): + break + self._add(payload[i : i + n]) + i += n + elif t == NAL_FU: + if len(payload) < 3: + return done + h = payload[2] + if h & 0x80: + self.fu = bytearray([(payload[0] & 0x81) | ((h & 0x3F) << 1), payload[1]]) + payload[3:] + elif self.fu is not None: + self.fu += payload[3:] + if h & 0x40 and self.fu is not None: + self._add(_strip_footer(bytes(self.fu))) + self.fu = None + else: + self._add(_strip_footer(bytes(payload))) + if marker: + self._finish(done) + return done + + def _add(self, nal: bytes) -> None: + t = nal_type(nal) + names = {NAL_VPS: "vps", NAL_SPS: "sps", NAL_PPS: "pps"} + if t in names: + if getattr(self, names[t]) != nal: + setattr(self, names[t], nal) + self.config_changed = True + return + if t == NAL_AUD: + return + if 16 <= t <= 21: + self.cur_key = True + self.cur.append(nal) + + def _finish(self, done: list) -> None: + nals, key, ts = self.cur, self.cur_key, self.cur_ts or 0 + self.cur, self.cur_key, self.cur_ts, self.fu = [], False, None, None + if not nals: + return + if self.waiting_for_key: + if not key or None in (self.vps, self.sps, self.pps): + return + self.waiting_for_key = False + done.append((ts, key, nals)) + + def decoder_config(self) -> Optional[dict]: + if None in (self.vps, self.sps, self.pps): + return None + info = parse_sps(self.sps) + if info is None: + return None + return {"codec": codec_string(info), "hvcc": hvcc(info, self.vps, self.sps, self.pps), "width": info["width"], "height": info["height"]} + + +def rbsp(nal: bytes) -> bytes: + """Remove emulation-prevention bytes (00 00 03 -> 00 00) after the 2-byte NAL header.""" + out, zeros = bytearray(), 0 + for b in nal[2:]: + if zeros >= 2 and b == 3: + zeros = 0 + continue + zeros = zeros + 1 if b == 0 else 0 + out.append(b) + return bytes(out) + + +class _Bits: + def __init__(self, d: bytes) -> None: + self.d, self.pos = d, 0 + + def bits(self, n: int) -> int: + v = 0 + for _ in range(n): + byte = self.d[self.pos // 8] # IndexError on a short SPS: caught by parse_sps + v = (v << 1) | ((byte >> (7 - self.pos % 8)) & 1) + self.pos += 1 + return v + + def ue(self) -> int: + zeros = 0 + while self.bits(1) == 0: + zeros += 1 + if zeros > 31: + raise ValueError("bad exp-Golomb code") + return (1 << zeros) - 1 + self.bits(zeros) + + +def parse_sps(sps: bytes) -> Optional[dict]: + """What the SPS says: the 12-byte general profile_tier_level, size, chroma and bit depths.""" + if nal_type(sps) != NAL_SPS: + return None + d = rbsp(sps) + b = _Bits(d) + try: + b.bits(4) + sub = b.bits(3) + nested = b.bits(1) + ptl = d[b.pos // 8 : b.pos // 8 + 12] + if len(ptl) != 12: + return None + b.pos += 96 + flags = [(b.bits(1), b.bits(1)) for _ in range(sub)] + if sub > 0: + for _ in range(sub, 8): + b.bits(2) + for profile, level in flags: + b.pos += 88 * profile + 8 * level + b.ue() + chroma = b.ue() + if chroma == 3: + b.bits(1) + width, height = b.ue(), b.ue() + if b.bits(1): + left, right, top, bottom = b.ue(), b.ue(), b.ue(), b.ue() + sx, sy = {1: (2, 2), 2: (2, 1)}.get(chroma, (1, 1)) + width, height = max(0, width - sx * (left + right)), max(0, height - sy * (top + bottom)) + depth_luma, depth_chroma = b.ue() + 8, b.ue() + 8 + except (IndexError, ValueError): + return None + return {"ptl": bytes(ptl), "max_sub_layers": sub + 1, "nested": bool(nested), "chroma": chroma, + "depth_luma": depth_luma, "depth_chroma": depth_chroma, "width": width, "height": height} + + +def codec_string(info: dict) -> str: + """WebCodecs / RFC 6381 codec string (ISO/IEC 14496-15 Annex E), e.g. ``hev1.1.6.L180.90``.""" + p = info["ptl"] + compat = int("{:032b}".format(int.from_bytes(p[1:5], "big"))[::-1], 2) + s = f"hev1.{['', 'A', 'B', 'C'][p[0] >> 6]}{p[0] & 0x1F}.{compat:X}.{'H' if p[0] & 0x20 else 'L'}{p[11]}" + constraints = p[5:11].rstrip(b"\0") + return s + "".join(f".{c:X}" for c in constraints) + + +def hvcc(info: dict, vps: bytes, sps: bytes, pps: bytes) -> bytes: + """HEVCDecoderConfigurationRecord (``hvcC``), the WebCodecs ``description`` for HEVC.""" + r = bytearray([1]) + info["ptl"] + r += bytes([0xF0, 0x00, 0xFC, 0xFC | (info["chroma"] & 3), 0xF8 | ((info["depth_luma"] - 8) & 7), + 0xF8 | ((info["depth_chroma"] - 8) & 7), 0, 0]) + r.append(((info["max_sub_layers"] & 7) << 3) | (int(info["nested"]) << 2) | 3) + r.append(3) + for t, nal in ((NAL_VPS, vps), (NAL_SPS, sps), (NAL_PPS, pps)): + r += bytes([0x80 | t]) + (1).to_bytes(2, "big") + len(nal).to_bytes(2, "big") + nal + return bytes(r) + + +def config_message(c: dict) -> bytes: + codec = c["codec"].encode() + return bytes([1]) + struct.pack(">HHB", min(c["width"], 65535), min(c["height"], 65535), len(codec)) + codec + c["hvcc"] + + +def frame_message(key: bool, nals: list, ts_us: int) -> bytes: + return bytes([2, int(key)]) + struct.pack(">Q", ts_us) + b"".join(len(n).to_bytes(4, "big") + n for n in nals) + + +def audio_message(pcm: bytes, ts_us: int) -> bytes: + return bytes([3]) + struct.pack(">Q", ts_us) + pcm + + +# ---------------------------------------------------------------- RTCP (RFC 3550 / 4585) +def _rr_sdes(ours: int, phone: int, highest_seq: int) -> bytes: + """Receiver report plus an empty CNAME, as Xcode sends them; keeps a stream alive.""" + rr = struct.pack(">BBHII4xIIII", 0x81, 201, 7, ours, phone, highest_seq, 0, 0, 0) + return rr + struct.pack(">BBHIBBBB", 0x81, 202, 2, ours, 1, 0, 0, 0) + + +def _keyframe_request(ours: int, phone: int, highest_seq: int, fir_seq: int) -> bytes: + pli = struct.pack(">BBHII", 0x81, 206, 2, ours, phone) + fir = struct.pack(">BBHIIIB3x", 0x84, 206, 4, ours, 0, phone, fir_seq & 0xFF) + return _rr_sdes(ours, phone, highest_seq) + pli + fir + + +def _frame_ack(ours: int, rtp_ts: int) -> bytes: + return struct.pack(">BBHIII", 0x80, 204, 3, ours, 5, rtp_ts) + + +def _rtp(data: bytes) -> Optional[tuple[int, int, bool, bytes]]: + """(seq, timestamp, marker, payload) of an RTP packet, or None for RTCP or junk.""" + if len(data) < 12 or data[0] >> 6 != 2 or 200 <= data[1] <= 206: + return None + off = 12 + 4 * (data[0] & 0x0F) + if data[0] & 0x10: + if off + 4 > len(data): + return None + off += 4 + 4 * int.from_bytes(data[off + 2 : off + 4], "big") + end = len(data) - (data[-1] if data[0] & 0x20 else 0) + if off > end: + return None + seq, ts = struct.unpack(">HI", data[2:8]) + return seq, ts, bool(data[1] & 0x80), data[off:end] + + +class _SeqCounter: + """Extended highest RTP sequence number; a late packet from before a wrap is ignored.""" + + def __init__(self) -> None: + self.value: Optional[int] = None + + def add(self, seq: int) -> None: + if self.value is None: + self.value = seq + return + d = (seq - self.value) & 0xFFFF + if 0 < d < 0x8000: + self.value = (self.value + d) & 0xFFFFFFFF + + +def _stream_config(answer: Any) -> tuple[int, int, int]: + """(phone RTP port, our SSRC, phone SSRC); the answer names them from the phone's side.""" + try: + cfg = answer["connection"]["streamConfig"] + except (KeyError, TypeError): + return 0, 0, 0 + return int(cfg.get("SourcePort", 0)), int(cfg.get("RemoteSSRC", 0)), int(cfg.get("LocalSSRC", 0)) + + +def _status(**kw) -> dict: + s = {"state": "off", "error": None, "simulated": False, "width": None, "height": None, "audio": False, "note": None, + "rotation": 0, "device_name": None, "ios": None} + s.update(kw) + return s + + +class _Client: + def __init__(self) -> None: + self.queue: asyncio.Queue = asyncio.Queue(maxsize=512) + self.need_key = True + + +class Screen: + def __init__(self) -> None: + self.status = _status() + self.session = 0 + self.config: Optional[bytes] = None + self.clients: set[_Client] = set() + self.sim_inputs: list[tuple] = [] + self.perf: dict = empty_perf() + self._live: Optional["_Live"] = None + self._task: Optional[asyncio.Task] = None + + # ---- clients + def subscribe(self) -> _Client: + c = _Client() + self.clients.add(c) + return c + + def unsubscribe(self, c: _Client) -> None: + self.clients.discard(c) + + def _broadcast(self, msg: Any) -> None: + for c in list(self.clients): + if isinstance(msg, (bytes, bytearray)) and msg[0] == 2: + if c.need_key and not msg[1]: + continue + c.need_key = False + try: + c.queue.put_nowait(msg) + except asyncio.QueueFull: # a slow viewer: start it again from the next keyframe + while not c.queue.empty(): + c.queue.get_nowait() + c.need_key = True + if self._live: + self._live.want_key = True + + def _set(self, session: int, **kw) -> None: + if session != self.session: + return + self.status.update(kw) + self._broadcast(json.dumps({"type": "status", "status": self.status})) + + def _ended(self, session: int, error: Optional[str]) -> None: + if session != self.session: + return + self._live, self.config = None, None + self.status = _status(state="error" if error else "off", error=error) + self._broadcast(json.dumps({"type": "status", "status": self.status})) + + # ---- control + async def start(self, simulated: bool, udid: Optional[str], audio: bool) -> dict: + await self._cancel() + self.session += 1 + session = self.session + self.config, self.sim_inputs, self.perf = None, [], empty_perf() + self.status = _status(state="starting", simulated=simulated) + self._set(session) + if simulated: + self._live = None + self._set(session, state="on", width=1170, height=2532, device_name="Simulated iPhone", ios="27.0", + note="Simulator: there is no real screen; input is accepted and ignored.") + return dict(self.status) + ready: asyncio.Future = asyncio.get_running_loop().create_future() + self._task = asyncio.create_task(self._run(session, udid, audio, ready)) + try: + await asyncio.wait_for(asyncio.shield(ready), 60) + except asyncio.TimeoutError: + await self.stop() + raise ScreenError("Timed out starting screen mirroring. Unlock the iPhone and try again.") from None + return dict(self.status) + + async def _cancel(self) -> None: + task, self._task = self._task, None + if task and not task.done(): + task.cancel() + with contextlib.suppress(asyncio.CancelledError, Exception): + await task + + async def stop(self) -> dict: + session = self.session + await self._cancel() + self._ended(session, None) + return dict(self.status) + + def _require(self) -> Optional["_Live"]: + if self.status["state"] != "on": + raise ScreenError("Screen mirroring is not running. Start it first.") + return self._live + + async def input(self, i: tuple) -> None: + live = self._require() + if self.status["simulated"]: + if len(self.sim_inputs) < 1000: + self.sim_inputs.append(i) + return + if live is None: + raise ScreenError("Reconnecting to the iPhone's screen. Try again in a moment.") + await live.apply(i) + + def get_perf(self) -> dict: + """The phone's latest performance figures; the first call starts measuring them.""" + live = self._require() + if live is not None: + live.start_perf() + return dict(self.perf) + + async def screenshot(self) -> bytes: + live = self._require() + if self.status["simulated"]: + raise ScreenError("The simulator has no screen to capture.") + if live is None: + raise ScreenError("Reconnecting to the iPhone's screen. Try again in a moment.") + return await live.screenshot() + + async def _run(self, session: int, udid: Optional[str], audio: bool, ready: asyncio.Future) -> None: + error = None + restarts, last_restart = 0, 0.0 + try: + while True: + try: + async with AsyncExitStack() as stack: + live = _Live(self, session) + await live.open(stack, udid, audio) + self._live = live + if not ready.done(): + ready.set_result(None) + await live.loop() + except _Restart as r: + self._live, self.perf = None, empty_perf() + if r.auto: + restarts = restarts + 1 if time.monotonic() - last_restart < 60 else 1 + last_restart = time.monotonic() + if restarts > MAX_RESTARTS: + raise ScreenError("The iPhone stopped sending its screen. Unlock it, then start mirroring again.") from None + self._set(session, note="Reconnecting to the iPhone's screen…") + except asyncio.CancelledError: + raise + except ScreenError as e: + error = str(e) + except Exception as e: # noqa: BLE001 - shown to the user + log.exception("screen mirroring failed") + from .device.pmd3 import _friendly + + error = _friendly(e) + finally: + if not ready.done(): + ready.set_exception(ScreenError(error or "Screen mirroring stopped.")) + self._ended(session, error) + + +MEDIA_IN_USE_CODE = 9022 +# Unanswered keyframe requests (while the picture is broken) before the stream is restarted; +# iOS 27's encoder sometimes stops answering them, and a fresh stream always opens with one. +MAX_KEY_REQUESTS = 3 +SILENCE = 6.0 # seconds without any datagram (the phone's RTCP reports come every second) +MAX_RESTARTS = 3 # automatic restarts in a row (less than a minute apart) before giving up + + +class _Restart(Exception): + """Start the stream again: ``auto`` when it froze, False when the user asked (Refresh).""" + + def __init__(self, auto: bool) -> None: + super().__init__("restart") + self.auto = auto + + +def empty_perf() -> dict: + """The phone's performance figures, all None until measured: ``cpu`` (% of all cores), ``cores``, + ``memory_used``/``memory_total`` (bytes), ``gpu`` (%), ``fps`` (the phone's own frame rate), + ``battery_temp`` (°C), ``battery`` (%), ``charging``.""" + return dict.fromkeys(("cpu", "cores", "memory_used", "memory_total", "gpu", "fps", "battery_temp", "battery", "charging")) + + +def memory(sys_values: dict) -> tuple[Optional[float], Optional[float]]: + """Memory in use and in total (bytes) from sysmontap's system figures (page counts, 16 KB pages).""" + page = 16384 + + def get(k): + v = sys_values.get(k) + return float(v) if isinstance(v, (int, float)) and not isinstance(v, bool) else None + + active, wired = get("vmActiveCount"), get("vmWireCount") + used = (active + wired + (get("vmCompressorPageCount") or 0)) * page if active is not None and wired is not None else None + total = get("physMemSize") + if total is None: + found = [x for x in (get(k) for k in ("vmFreeCount", "vmActiveCount", "vmInactiveCount", "vmWireCount", + "vmCompressorPageCount", "vmSpeculativeCount")) if x is not None] + total = sum(found) * page if len(found) >= 4 else None + return used, total + + +def display_rotation(info: Any) -> int: + """Clockwise degrees (0, 90, 180, 270) that turn the streamed picture upright, from a + ``getdisplayinfo`` answer: the built-in display in use, else the primary one.""" + displays = info.get("displays", []) if isinstance(info, dict) else [] + built_in = [d for d in displays if not d.get("external")] + chosen = (next((d for d in built_in if d.get("active")), None) + or next((d for d in built_in if d.get("backlightState", "off") != "off"), None) + or next((d for d in displays if d.get("primary")), None) + or (displays[0] if displays else {})) + return {"rot90": 90, "rot180": 180, "rot270": 270}.get(chosen.get("currentOrientation"), 0) + + +class _Live: + """One mirroring session with a real iPhone.""" + + def __init__(self, m: Screen, session: int) -> None: + self.m, self.session = m, session + self.want_key = True + self.refresh = False # a still screen gets a keyframe now and then; doesn't count towards a restart + self.restart_asked = False + self.key_requests = 0 + self.depack = Depacketizer() + self.lock = asyncio.Lock() # one input at a time on the HID services + self.perf_tasks: list[asyncio.Task] = [] + self.info = None + self.hid = self.indigo = None + self.held: set[int] = set() + self.kb_id: Optional[int] = None + + async def open(self, stack: AsyncExitStack, udid: Optional[str], audio: bool) -> None: + from pymobiledevice3.lockdown import create_using_usbmux + from pymobiledevice3.remote.core_device.display_service import DisplayService + from pymobiledevice3.remote.core_device.hid_service import IndigoHIDService, UniversalHIDServiceService + from pymobiledevice3.remote.core_device.screen_stream import open_media_receiver + + from .device.pmd3 import Pmd3Driver, _major + + lockdown = await create_using_usbmux(serial=udid, autopair=True) + stack.push_async_callback(lockdown.close) + self.lockdown = lockdown + stack.push_async_callback(self._stop_perf) + version = lockdown.product_version + self.m._set(self.session, device_name=lockdown.all_values.get("DeviceName") or None, ios=version or None) + if _major(version) < 27: + raise ScreenError(f"Screen mirroring needs iOS 27 or newer. This iPhone has iOS {version}.") + driver = Pmd3Driver() + self.rsd, _how = await driver._open_rsd(stack, udid or lockdown.udid, lockdown.udid) + mount_note = await driver._try_mount(self.rsd) + try: + self.display = await stack.enter_async_context(DisplayService(self.rsd)) + except Exception as e: # noqa: BLE001 + raise ScreenError(f"The iPhone's screen service is not available ({e}). {mount_note or 'Check that Developer Mode is on.'}") from e + self.video, receiver_ip = open_media_receiver(self.display, (8 << 20, 4 << 20)) + stack.callback(self.video.close) + self.audio_rx, _ = open_media_receiver(self.display, (1 << 20,)) + stack.callback(self.audio_rx.close) + self.sender_ip = self.rsd.service.address[0] + sid = uuid.uuid4() + try: + # The audio stream goes first: it sets up the screen-sharing session the video joins. + a = await self.display.start_audio_stream(receiver_ip, self.audio_rx.port, self.sender_ip, client_session_id=sid) + # shortcut: display 1 is the built-in screen; foldables with two panels would need the active one. + v = await self.display.start_video_stream(receiver_ip, self.video.port, self.sender_ip, display_id=1, client_session_id=sid) + except Exception as e: + if getattr(e, "code", None) == MEDIA_IN_USE_CODE: + raise ScreenError("The iPhone won't share its screen while an app uses the camera or microphone " + "(for example Camera or Voice Memos). Close that app and try again.") from e + raise + stack.push_async_callback(self._stop_streams) + self.a_port, self.a_ours, self.a_phone = _stream_config(a) + self.v_port, self.v_ours, self.v_phone = _stream_config(v) + self.v_ours = self.v_ours or random.getrandbits(32) + + await asyncio.sleep(0.3) # the phone matches HID input to the new stream first + notes = [] + try: + self.hid = await stack.enter_async_context(UniversalHIDServiceService(self.rsd)) + self.indigo = await stack.enter_async_context(IndigoHIDService(self.rsd)) + except Exception: # noqa: BLE001 + log.exception("HID services unavailable") + self.hid = self.indigo = None + notes.append("The iPhone did not accept touch input, so it can only be watched.") + try: # which way the screen is turned; without it the Rotate button helps + from pymobiledevice3.remote.core_device.device_info import DeviceInfoService + + self.info = await stack.enter_async_context(DeviceInfoService(self.rsd)) + except Exception: # noqa: BLE001 + self.info = None + self.decoder = None + if audio: + if sys.platform == "darwin": + from pymobiledevice3.remote.core_device.aac_eld import AAC_ELD_ASC_48K_STEREO_480, AACELDDecoder + + self.decoder = AACELDDecoder(AAC_ELD_ASC_48K_STEREO_480) + else: + notes.append("The browser edition can only play the iPhone's sound on a Mac; the standalone app plays it on Windows.") + self.m._set(self.session, state="on", audio=self.decoder is not None, note=" ".join(notes) or None) + + async def _stop_streams(self) -> None: + with contextlib.suppress(Exception): + await asyncio.wait_for(self.display.stop_media_stream(), 3) + + async def loop(self) -> None: + self.started = time.monotonic() + self.v_seq, self.a_seq = _SeqCounter(), _SeqCounter() + tasks = [asyncio.create_task(c) for c in (self._video(), self._audio(), self._feedback(), self._orientation())] + try: + done, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) + for t in done: + t.result() + finally: + for t in tasks: + t.cancel() + raise ScreenError("The connection to the iPhone was lost.") + + def _ts(self) -> int: + return int((time.monotonic() - self.started) * 1e6) + + async def _video(self) -> None: + depack = self.depack + while True: + data = await self.video.recv(65535) + self.last_dgram = time.monotonic() + p = _rtp(data) + if p is None: + continue + self.last_video = time.monotonic() + seq, ts, marker, payload = p + self.v_seq.add(seq) + frames = depack.push(seq, ts, marker, payload) + for rtp_ts, key, nals in frames: + if key: + self.key_requests = 0 + if depack.config_changed: + c = depack.decoder_config() + if c: + self.m._set(self.session, width=c["width"], height=c["height"]) + self.m.config = config_message(c) + self.m._broadcast(self.m.config) + depack.config_changed = False + self.m._broadcast(frame_message(key, nals, self._ts())) + await self._rtcp(self.video, self.v_port, _frame_ack(self.v_ours, rtp_ts)) + + async def _audio(self) -> None: + while True: + p = _rtp(await self.audio_rx.recv(65535)) + if p is None: + continue + self.a_seq.add(p[0]) + if self.decoder is not None: + try: + pcm = self.decoder.decode(p[3]) + except Exception: # noqa: BLE001 - one bad packet + continue + if pcm: + self.m._broadcast(audio_message(pcm, self._ts())) + + async def _rtcp(self, transport, port: int, packet: bytes) -> None: + if port: + with contextlib.suppress(OSError): + await transport.sendto(packet, self.sender_ip, port) + + async def _feedback(self) -> None: + """Receiver reports every second (the phone stops after ~20 s without them) and + rate-limited keyframe requests.""" + fir_seq, last_report, last_request = 0, 0.0, 0.0 + self.last_video = self.last_dgram = time.monotonic() + while True: + await asyncio.sleep(0.1) + now = time.monotonic() + if self.restart_asked: + raise _Restart(False) + if now - self.last_dgram > SILENCE: + raise _Restart(True) + if now - self.last_video > 4: # a still screen sends nothing: refresh for new viewers + self.refresh, self.last_video = True, now + broken = self.want_key or self.depack.waiting_for_key + if (broken or self.refresh) and now - last_request > 1 and self.v_phone: + if broken: + if self.key_requests >= MAX_KEY_REQUESTS: + raise _Restart(True) + self.key_requests += 1 + await self._rtcp(self.video, self.v_port, _keyframe_request(self.v_ours, self.v_phone, self.v_seq.value or 0, fir_seq)) + fir_seq, last_request, self.want_key, self.refresh = fir_seq + 1, now, False, False + if now - last_report >= 1: + last_report = now + if self.v_phone: + await self._rtcp(self.video, self.v_port, _rr_sdes(self.v_ours, self.v_phone, self.v_seq.value or 0)) + if self.a_phone: + await self._rtcp(self.audio_rx, self.a_port, _rr_sdes(self.a_ours, self.a_phone, self.a_seq.value or 0)) + + # ---- the phone's performance (started by the first request for it) + def start_perf(self) -> None: + if not self.perf_tasks: + self.perf_tasks = [asyncio.create_task(c) for c in (self._cpu_memory(), self._gpu(), self._battery())] + + async def _stop_perf(self) -> None: + for t in self.perf_tasks: + t.cancel() + + def _perf(self, **kw) -> None: + if self.m.session == self.session: + self.m.perf.update(kw) + + async def _cpu_memory(self) -> None: + from pymobiledevice3.services.dvt.instruments.device_info import DeviceInfo + from pymobiledevice3.services.dvt.instruments.dvt_provider import DvtProvider + from pymobiledevice3.services.dvt.instruments.sysmontap import Sysmontap + + with contextlib.suppress(Exception): + async with DvtProvider(self.rsd) as dvt: + async with DeviceInfo(dvt) as info: + cores = (await info.hardware_information()).get("numberOfCpus") + attrs = list(await info.sysmon_system_attributes()) + self._perf(cores=cores) + async with Sysmontap(dvt, [], attrs, interval_ms=1000) as tap: + async for row in tap: + load = (row.get("SystemCPUUsage") or {}).get("CPU_TotalLoad") + cpu = None if load is None else min(max(load / max(cores or 1, 1), 0), 100) # the load adds up all cores + used, total = memory(dict(zip(attrs, row.get("System") or []))) + self._perf(cpu=cpu, memory_used=used, memory_total=total) + + async def _gpu(self) -> None: + from pymobiledevice3.services.dvt.instruments.dvt_provider import DvtProvider + from pymobiledevice3.services.dvt.instruments.graphics import Graphics + + with contextlib.suppress(Exception): + async with DvtProvider(self.rsd) as dvt, Graphics(dvt) as graphics: + async for sample in graphics: + if isinstance(sample, dict): + self._perf(gpu=sample.get("Device Utilization %"), fps=sample.get("CoreAnimationFramesPerSecond")) + + async def _battery(self) -> None: + from pymobiledevice3.services.diagnostics import DiagnosticsService + + with contextlib.suppress(Exception): + async with DiagnosticsService(self.lockdown) as diag: + while True: + info = await diag.get_battery() or {} # fills in the temperature from the battery pack on newer iOS + t = info.get("Temperature") + self._perf(battery_temp=None if t is None else t / 100, battery=info.get("CurrentCapacity"), + charging=None if info.get("IsCharging") is None else bool(info["IsCharging"])) + await asyncio.sleep(5) + + async def _orientation(self) -> None: + while True: + await asyncio.sleep(0.5) + if self.info is None: + continue + try: + r = display_rotation(await asyncio.wait_for(self.info.get_display_info(), 0.8)) + except Exception: # noqa: BLE001 - not supported by this iPhone: stop asking + self.info = None + continue + if r != self.m.status.get("rotation"): + self.m._set(self.session, rotation=r) + + # ---- input + async def apply(self, i: tuple) -> None: + if i[0] == "keyframe": + self.want_key = True + elif i[0] == "refresh": + self.restart_asked = True + else: + async with self.lock: + await self._apply(i) + + async def _apply(self, i: tuple) -> None: + from pymobiledevice3.remote.core_device.hid_service import ( + HID_BUTTON_STATE_DOWN, + HID_BUTTON_STATE_UP, + TOUCHSCREEN_STATE_CONTACT, + TOUCHSCREEN_STATE_RELEASE, + ) + + kind = i[0] + if self.hid is None or self.indigo is None: + raise ScreenError("The iPhone did not accept touch input in this session. Stop and start mirroring again.") + if kind == "touch" and i[4] is None: + state = TOUCHSCREEN_STATE_RELEASE if i[1] == "up" else TOUCHSCREEN_STATE_CONTACT + await self.hid.send_touchscreen(state, i[2], i[3]) + elif kind == "touch": # two fingers (pinch): both in every report, with identities that stay the same + from pymobiledevice3.remote.core_device.hid_service import TouchscreenContact + + touching = i[1] != "up" + (x2, y2) = i[4] + await self.hid.send_multitouch([TouchscreenContact(2, i[2], i[3], touching), TouchscreenContact(3, x2, y2, touching)]) + elif kind == "long_press": + await self.hid.send_touchscreen(TOUCHSCREEN_STATE_CONTACT, i[1], i[2]) + await asyncio.sleep(i[3] / 1000) + await self.hid.send_touchscreen(TOUCHSCREEN_STATE_RELEASE, i[1], i[2]) + elif kind == "gesture": + (u1, v1), (u2, v2), secs, hold = GESTURES[i[1]] + rotation = self.m.status.get("rotation") or 0 + steps = max(round(secs / 0.016), 2) + for n in range(steps + 1): + f = n / steps + await self.hid.send_touchscreen(TOUCHSCREEN_STATE_CONTACT, *upright_to_native(u1 + (u2 - u1) * f, v1 + (v2 - v1) * f, rotation)) + await asyncio.sleep(0.016) + await asyncio.sleep(hold) + await self.hid.send_touchscreen(TOUCHSCREEN_STATE_RELEASE, *upright_to_native(u2, v2, rotation)) + elif kind == "tap": + await self.hid.send_touchscreen(TOUCHSCREEN_STATE_CONTACT, i[1], i[2]) + await asyncio.sleep(0.05) + await self.hid.send_touchscreen(TOUCHSCREEN_STATE_RELEASE, i[1], i[2]) + elif kind == "swipe": + x1, y1, x2, y2, ms = i[1:] + steps = max(ms // 16, 2) # ~60 samples a second, so the phone sees a drag with a speed + for n in range(steps + 1): + f = n / steps + await self.hid.send_touchscreen(TOUCHSCREEN_STATE_CONTACT, round(x1 + (x2 - x1) * f), round(y1 + (y2 - y1) * f)) + await asyncio.sleep(0.016) + await self.hid.send_touchscreen(TOUCHSCREEN_STATE_RELEASE, x2, y2) + elif kind == "button": + page, usage, hold = BUTTONS[i[1]] + await self.indigo.send_button(page, usage, HID_BUTTON_STATE_DOWN) + await asyncio.sleep(hold) + await self.indigo.send_button(page, usage, HID_BUTTON_STATE_UP) + elif kind == "key" and i[2] is not None and not i[3]: + (self.held.add if i[2] else self.held.discard)(i[1]) + await self._keys(self.held) + elif kind == "key": + keys = {COMMAND, i[1]} if i[3] else {i[1]} + if i[2] is not False: + await self._keys(self.held | keys) + if i[2] is not True: + await self._keys(self.held - keys) + elif kind == "text": + for ch in i[1]: + u = char_usage(ch) + if u: + await self._keys({u[0], 0xE1} if u[1] else {u[0]}) + await self._keys(set()) + await asyncio.sleep(0.012) # keystrokes sent back to back get merged + + async def _keys(self, held: set[int]) -> None: + if self.kb_id is None: + self.kb_id = await self.hid.create_keyboard_service() + await self.hid.send_keyboard(self.kb_id, sorted(held)) + + async def screenshot(self) -> bytes: + from pymobiledevice3.services.dvt.instruments.dvt_provider import DvtProvider + from pymobiledevice3.services.dvt.instruments.screenshot import Screenshot + + async with DvtProvider(self.rsd) as dvt, Screenshot(dvt) as shot: + return await shot.get_screenshot() diff --git a/browser/spoofer/server.py b/browser/spoofer/server.py index 146c109..b797774 100644 --- a/browser/spoofer/server.py +++ b/browser/spoofer/server.py @@ -3,15 +3,18 @@ from __future__ import annotations import asyncio +import contextlib import json import logging +import re +import sys import uuid from collections import OrderedDict from contextlib import asynccontextmanager from pathlib import Path from typing import Awaitable, Callable, Literal, Optional -from fastapi import FastAPI, File, HTTPException, Request, UploadFile +from fastapi import FastAPI, File, HTTPException, Request, UploadFile, WebSocket, WebSocketDisconnect from fastapi.responses import FileResponse, JSONResponse, Response, StreamingResponse from fastapi.staticfiles import StaticFiles from pydantic import BaseModel, Field @@ -24,6 +27,9 @@ from .device.mock import MockDriver from .device.pmd3 import Pmd3Driver from .gpx_io import parse_gpx, safe_filename, write_gpx +from .mirrors import FanOut, MirrorLink +from . import mcp +from .screen import Screen, ScreenError, is_move, parse_input from .player import Player from .profile import ( Leg, @@ -56,17 +62,32 @@ class AppState: def __init__(self) -> None: self.drivers: dict[str, DeviceDriver] = {d.key: d for d in (Pmd3Driver(), CliDriver(), MockDriver())} self.driver_key = "pmd3" - self.player = Player(lambda: self.driver) + # extra iPhones that follow the main one, by UDID (see mirrors.py) + self.mirrors: dict[str, MirrorLink] = {} + self.fanout = FanOut(lambda: self.driver, lambda: list(self.mirrors.values())) + self.player = Player(lambda: self.fanout) self.timelines: "OrderedDict[str, tuple[Timeline, str, list, bool]]" = OrderedDict() self.store = Store() self.updater = Updater() # replaced by __main__ with the real one; disabled from source self.offline = Offline(data_dir()) self.feature_tests = FeatureTests(data_dir()) + self.screen = Screen() @property def driver(self) -> DeviceDriver: return self.drivers[self.driver_key] + async def drop_mirror(self, udid: str, clear: bool = False) -> bool: + link = self.mirrors.pop(udid, None) + if link is None: + return False + await link.close(clear) + return True + + async def drop_mirrors(self, clear: bool = False) -> None: + for udid in list(self.mirrors): + await self.drop_mirror(udid, clear) + def keep_timeline(self, tl: Timeline, name: str, waypoints: list, exportable: bool = True) -> str: tid = uuid.uuid4().hex[:12] self.timelines[tid] = (tl, name, waypoints, exportable) @@ -93,14 +114,16 @@ async def lifespan(app: FastAPI): yield upd_task.cancel() try: + await app.state.s.screen.stop() await app.state.s.player.stop() + await app.state.s.drop_mirrors() for d in app.state.s.drivers.values(): await d.disconnect() finally: await routing.close() -app = FastAPI(title="iPhone Location Spoofer", version=__version__, lifespan=lifespan) +app = FastAPI(title="iDevBench Browser Edition", version=__version__, lifespan=lifespan) _LOCAL_HOSTS = ("127.0.0.1", "localhost") @@ -144,6 +167,11 @@ async def _feature_test_error(_: Request, exc: FeatureTestError): return JSONResponse({"detail": str(exc)}, status_code=exc.status) +@app.exception_handler(ScreenError) +async def _screen_error(_: Request, exc: ScreenError): + return JSONResponse({"detail": str(exc)}, status_code=409) + + @app.exception_handler(ValueError) async def _value_error(_: Request, exc: ValueError): return JSONResponse({"detail": str(exc)}, status_code=400) @@ -162,6 +190,19 @@ class TextIn(BaseModel): class ConnectIn(BaseModel): driver: Literal["pmd3", "cli", "mock"] = "pmd3" udid: Optional[str] = None + connection: Literal["auto", "usb", "network"] = "auto" + + +class MirrorIn(BaseModel): + udid: str + connection: Literal["auto", "usb", "network"] = "auto" + + +class UdidIn(BaseModel): + udid: Optional[str] = None + + +MAX_MIRRORS = 8 class WaypointIn(BaseModel): @@ -275,13 +316,14 @@ async def status(): "version": __version__, "app": "browser", "feature_test": None, - "features": {"cli_driver": True, "tunnel_helper": True}, + "features": {"cli_driver": True, "tunnel_helper": True, "multi_device": True, "wifi": True}, "driver": s.driver_key, "drivers": [{"key": k, "label": v.label, "live": v.live} for k, v in s.drivers.items()], "device": d.info.to_dict() if d.info else None, "live": d.live, "player": s.player.status(), "update": s.updater.status(), + "mirrors": [m.to_dict() for m in s.mirrors.values()], } @@ -295,9 +337,13 @@ async def connect(body: ConnectIn): s = S() await s.player.stop() if body.driver != s.driver_key: + await s.drop_mirrors() await s.driver.disconnect() s.driver_key = body.driver - info = await s.driver.connect(body.udid or None) + if body.udid: + await s.drop_mirror(body.udid) # it becomes the main phone instead + info = await s.driver.connect(body.udid or None, body.connection) + await s.drop_mirror(info.udid) return {"device": info.to_dict()} @@ -305,10 +351,55 @@ async def connect(body: ConnectIn): async def disconnect(): s = S() await s.player.stop() + await s.drop_mirrors() await s.driver.disconnect() return {"ok": True} +@app.post("/api/mirrors") +async def mirror_add(body: MirrorIn): + """Another iPhone follows the main one: same position, same route, from now on.""" + s = S() + main = s.driver + if not main.connected or main.info is None: + raise DeviceError("Connect the main iPhone first.") + if not main.live: + raise DeviceError("Several iPhones at once need the Direct connection (or the Simulator).") + if body.udid == main.info.udid: + raise DeviceError("That is the main iPhone already.") + if body.udid in s.mirrors: + raise DeviceError("That iPhone already follows the main one.") + if len(s.mirrors) >= MAX_MIRRORS: + raise DeviceError(f"Up to {MAX_MIRRORS} extra iPhones can follow the main one.") + drv = type(main)() + info = await drv.connect(body.udid, body.connection) + if info.udid == main.info.udid or info.udid in s.mirrors: + await drv.disconnect() + raise DeviceError("That iPhone is connected already.") + link = MirrorLink(drv) + s.mirrors[info.udid] = link + pos = s.player.position + if pos is not None: + link.push_set(pos.lat, pos.lon) # catch up with the main phone straight away + return {"mirror": link.to_dict(), "mirrors": [m.to_dict() for m in s.mirrors.values()]} + + +@app.delete("/api/mirrors/{udid}") +async def mirror_remove(udid: str, clear: bool = True): + """Stop following; by default the phone goes back to its real location.""" + s = S() + if not await s.drop_mirror(udid, clear): + raise HTTPException(404, "That iPhone doesn't follow the main one.") + return {"mirrors": [m.to_dict() for m in s.mirrors.values()]} + + +@app.post("/api/device/wifi") +async def enable_wifi(body: UdidIn): + s = S() + udid = body.udid or (s.driver.info.udid if s.driver.info else None) + return {"message": await s.driver.enable_wifi(udid)} + + @app.post("/api/device/reveal-developer-mode") async def reveal_dev_mode(): return {"message": await S().driver.reveal_developer_mode()} @@ -862,3 +953,192 @@ async def index(): app.mount("/static", StaticFiles(directory=STATIC), name="static") + + +# ---------------------------------------------------------------- screen mirroring +class ScreenStartIn(BaseModel): + driver: Optional[Literal["pmd3", "cli", "mock"]] = None + udid: Optional[str] = None + audio: bool = True + + +@app.get("/api/screen") +async def screen_status(): + return S().screen.status + + +@app.post("/api/screen/start") +async def screen_start(body: ScreenStartIn): + s = S() + driver = body.driver or s.driver_key + udid = body.udid or (s.driver.info.udid if s.driver.info else None) + return await s.screen.start(driver == "mock", udid, body.audio) + + +@app.post("/api/screen/stop") +async def screen_stop(): + return await S().screen.stop() + + +@app.post("/api/screen/input") +async def screen_input(body: dict): + await S().screen.input(parse_input(body)) + return {"ok": True} + + +@app.get("/api/screen/screenshot") +async def screen_screenshot(): + return Response(await S().screen.screenshot(), media_type="image/png", headers={"Cache-Control": "no-store"}) + + +_CAPTURE_NAME = re.compile(r"[A-Za-z0-9_][A-Za-z0-9_.-]{0,119}") + + +@app.post("/api/screen/save") +async def screen_save(name: str, request: Request): + """Saves a screenshot or recording from the Mirror tab to the folder chosen in Settings + (the Downloads folder by default) and returns where it went.""" + if not _CAPTURE_NAME.fullmatch(name) or not name.endswith((".png", ".mp4", ".webm")): + raise HTTPException(400, "Unexpected file name.") + chosen = str((S().store.load().get("settings") or {}).get("capture_folder") or "").strip() + folder = Path(chosen).expanduser() if chosen else Path.home() / "Downloads" + body = await request.body() + + def write() -> str: + try: + folder.mkdir(parents=True, exist_ok=True) + path, stem, ext = folder / name, *name.rsplit(".", 1) + n = 1 + while path.exists(): + path, n = folder / f"{stem}-{n}.{ext}", n + 1 + path.write_bytes(body) + except OSError as e: + raise HTTPException(400, f"Can't save to {folder}: {e.strerror or e}") from e + return str(path) + + return {"path": await asyncio.to_thread(write)} + + +@app.get("/api/screen/perf") +async def screen_perf(): + """The phone's CPU, memory, GPU and battery figures while mirroring (the first call starts measuring).""" + return S().screen.get_perf() + + +# Windows' folder dialog. This server runs in the background, so the dialog gets a visible +# (invisible-looking) topmost owner window to come up in front; the path is written as UTF-8 +# bytes because a background process has no console to set an encoding on. +PICK_FOLDER_PS = ( + "Add-Type -AssemblyName System.Windows.Forms,System.Drawing; " + "$o=New-Object System.Windows.Forms.Form -Property @{TopMost=$true;ShowInTaskbar=$false;FormBorderStyle='None';Opacity=0;" + "StartPosition='Manual';Location=(New-Object System.Drawing.Point(-2000,-2000));Size=(New-Object System.Drawing.Size(1,1))}; " + "$o.Show(); $o.Activate(); $d=New-Object System.Windows.Forms.FolderBrowserDialog; " + "$d.Description='Folder for screenshots and recordings'; $d.ShowNewFolderButton=$true; " + "if($d.ShowDialog($o) -eq 'OK'){$b=[Text.Encoding]::UTF8.GetBytes($d.SelectedPath);$s=[Console]::OpenStandardOutput();$s.Write($b,0,$b.Length);$s.Flush()}; " + "$o.Close()" +) + + +@app.post("/api/pick-folder") +async def pick_folder(): + """Shows the system's folder picker on this computer; answers {"path": null} when cancelled.""" + import subprocess + + if sys.platform == "win32": + cmd = ["powershell", "-NoProfile", "-NonInteractive", "-STA", "-Command", PICK_FOLDER_PS] + elif sys.platform == "darwin": + cmd = ["osascript", "-e", 'POSIX path of (choose folder with prompt "Folder for screenshots and recordings")'] + else: + cmd = ["zenity", "--file-selection", "--directory", "--title=Folder for screenshots and recordings"] + flags = 0x08000000 if sys.platform == "win32" else 0 # no console window + try: + out = await asyncio.to_thread(subprocess.run, cmd, capture_output=True, creationflags=flags) + except OSError: + raise HTTPException(400, "This computer has no folder picker the app can use. Type the folder's path instead.") from None + path = out.stdout.decode("utf-8", "replace").strip() + return {"path": path or None} + + +@app.get("/api/mcp/setup") +async def mcp_setup(request: Request): + v = mcp.command(request.headers.get("host", "127.0.0.1:8765")) + v["claude_desktop"] = any(p.exists() for p in mcp.claude_desktop_configs()) + return v + + +@app.post("/api/mcp/claude-desktop") +async def mcp_claude_desktop(request: Request): + return {"paths": await asyncio.to_thread(mcp.add_to_claude_desktop, request.headers.get("host", "127.0.0.1:8765"))} + + +@app.post("/mcp") +async def mcp_post(request: Request): + """Model Context Protocol over HTTP (JSON answers, no sessions) for AI agents; see mcp.py.""" + try: + msg = json.loads(await request.body()) + except ValueError: + return JSONResponse(mcp._error(None, -32700, "Parse error")) + answer = await mcp.handle(msg, app, STATIC) + return Response(status_code=202) if answer is None else JSONResponse(answer) + + +@app.get("/mcp") +async def mcp_get(): + return Response("Send MCP messages with POST.", status_code=405) + + +@app.websocket("/api/screen/ws") +async def screen_ws(ws: WebSocket): + """Live picture, sound and status for the Mirror tab or another program; input goes the other way.""" + # HTTP middleware does not run for WebSockets, so the local-only check is repeated here. + if not _is_local_request(ws.headers.get("host", ""), ws.headers.get("origin", "")): + await ws.close(code=1008) + return + await ws.accept() + m = S().screen + client = m.subscribe() + await ws.send_text(json.dumps({"type": "status", "status": m.status})) + if m.config: + await ws.send_bytes(m.config) + with contextlib.suppress(ScreenError): + await m.input(("keyframe",)) + + async def send() -> None: + while True: + msg = await client.queue.get() + await (ws.send_text(msg) if isinstance(msg, str) else ws.send_bytes(msg)) + + inputs: asyncio.Queue = asyncio.Queue() + + async def work() -> None: + """Inputs one after another, so a long one (Siri, typing) doesn't hold up reading the next.""" + held = None + while True: + i = held or await inputs.get() + held = None + while is_move(i) and not inputs.empty(): # finger moves that piled up: only the newest matters + nxt = inputs.get_nowait() + if is_move(nxt): + i = nxt + else: + held = nxt + break + try: + await m.input(i) + except (ValueError, ScreenError, DeviceError) as e: + client.queue.put_nowait(json.dumps({"type": "error", "detail": str(e)})) + + sender, worker = asyncio.create_task(send()), asyncio.create_task(work()) + try: + while True: + text = await ws.receive_text() + try: + inputs.put_nowait(parse_input(json.loads(text))) + except ValueError as e: + await ws.send_text(json.dumps({"type": "error", "detail": str(e)})) + except (WebSocketDisconnect, RuntimeError): + pass + finally: + sender.cancel() + worker.cancel() + m.unsubscribe(client) diff --git a/browser/spoofer/updater.py b/browser/spoofer/updater.py index 00818c1..d35ed44 100644 --- a/browser/spoofer/updater.py +++ b/browser/spoofer/updater.py @@ -41,7 +41,7 @@ TAG_PREFIX = "browser-v" CHECK_EVERY_S = 6 * 3600 ALLOWED_HOSTS = ("github.com", "objects.githubusercontent.com", "release-assets.githubusercontent.com") -USER_AGENT = f"iPhone-Location-Spoofer/{__version__}" +USER_AGENT = f"iDevBench/{__version__}" def parse_version(text: str) -> tuple[int, ...]: diff --git a/browser/tests/test_mcp.py b/browser/tests/test_mcp.py new file mode 100644 index 0000000..f6be1b0 --- /dev/null +++ b/browser/tests/test_mcp.py @@ -0,0 +1,84 @@ +"""The MCP endpoint for AI agents (/mcp, tools from ui/mcp-tools.json), driving the simulator (same cases as the standalone).""" + +import json + +import pytest +from fastapi.testclient import TestClient + + +@pytest.fixture() +def rpc(tmp_path, monkeypatch): + monkeypatch.setenv("SPOOFER_DATA_DIR", str(tmp_path)) + from spoofer import server + from spoofer.store import Store + + server.app.state.s = server.AppState() + server.app.state.s.store = Store(tmp_path / "data.json") + with TestClient(server.app, base_url="http://127.0.0.1:8765") as c: + def send(method, params=None): + r = c.post("/mcp", json={"jsonrpc": "2.0", "id": 1, "method": method, "params": params or {}}) + return r.json() + + send.client = c + yield send + + +def call(rpc, tool, **args): + return rpc("tools/call", {"name": tool, "arguments": args})["result"] + + +def test_handshake_and_tool_list(rpc): + init = rpc("initialize", {"protocolVersion": "2025-03-26"})["result"] + assert (init["protocolVersion"], init["serverInfo"]["name"]) == ("2025-03-26", "idevbench") + tools = {t["name"]: t for t in rpc("tools/list")["result"]["tools"]} + assert len(tools) >= 30 and "call" not in tools["tap"] and tools["tap"]["inputSchema"]["required"] == ["x", "y"] + note = rpc.client.post("/mcp", json={"jsonrpc": "2.0", "method": "notifications/initialized"}) + assert note.status_code == 202 + assert rpc("nope")["error"]["code"] == -32601 + assert rpc.client.post("/mcp", json={"jsonrpc": "2.0", "id": 1}, headers={"origin": "https://evil.example"}).status_code == 403 + + +def test_drives_location_and_mirroring(rpc): + from spoofer import server + + assert call(rpc, "tap", x=0.5, y=0.5)["isError"] # not mirroring yet + for tool, args in [("connect_device", {"driver": "mock"}), ("set_location", {"lat": 48.8584, "lon": 2.2945}), + ("start_mirroring", {"driver": "mock"}), ("tap", {"x": 0.5, "y": 0.9}), ("gesture", {"name": "app_switcher"}), + ("press_key", {"usage": 4, "command": True}), ("phone_performance", {}), ("wait", {"ms": 1})]: + r = call(rpc, tool, **args) + assert not r.get("isError"), (tool, r) + assert ("gesture", "app_switcher") in server.app.state.s.screen.sim_inputs + route = call(rpc, "drive_route", waypoints=[{"lat": 51.5, "lon": -0.12}, {"lat": 51.501, "lon": -0.12}], legs=[{"mode": "straight"}]) + out = json.loads(route["content"][0]["text"]) + assert isinstance(out["id"], str) and isinstance(out["summary"], dict), route + assert server.app.state.s.player.status()["state"] == "playing" + assert "settings" not in call(rpc, "list_favourites")["content"][0]["text"] + assert call(rpc, "screenshot")["isError"] # the simulator has no screen + bad = call(rpc, "tap", x=2, y=0) + assert bad["isError"] and "0 to 1" in bad["content"][0]["text"] + + +def test_adds_itself_to_claude_desktop_keeping_other_settings(rpc, tmp_path, monkeypatch): + cfg_dir = tmp_path / "Claude" + cfg_dir.mkdir() + (cfg_dir / "claude_desktop_config.json").write_text('{"theme": "dark", "mcpServers": {"other": {"command": "x"}}}') + monkeypatch.setenv("SPOOFER_CLAUDE_DESKTOP_DIR", str(cfg_dir)) + c = rpc.client + setup = c.get("/api/mcp/setup", headers={"host": "127.0.0.1:9123"}).json() + assert setup["url"] == "http://127.0.0.1:9123/mcp" and setup["args"][-3:] == ["--mcp", "--port", "9123"] + assert c.post("/api/mcp/claude-desktop", headers={"host": "127.0.0.1:9123"}).status_code == 200 + cfg = json.loads((cfg_dir / "claude_desktop_config.json").read_text()) + assert cfg["theme"] == "dark" and cfg["mcpServers"]["other"] == {"command": "x"} + assert "--mcp" in cfg["mcpServers"]["idevbench"]["args"] + assert "passcode" in call(rpc, "guide")["content"][0]["text"] + + +def test_plugin_skill_matches_the_guide(): + from pathlib import Path + + root = Path(__file__).resolve().parents[2] + guide = (root / "ui" / "mcp-guide.md").read_text(encoding="utf-8") + skill = (root / "plugins" / "idevbench" / "skills" / "idevbench" / "SKILL.md").read_text(encoding="utf-8") + assert skill.split("---\n", 2)[2].strip() == guide.strip() + mcp_cfg = json.loads((root / "plugins" / "idevbench" / ".mcp.json").read_text()) + assert mcp_cfg["mcpServers"]["idevbench"] == {"type": "http", "url": "http://127.0.0.1:8766/mcp"} diff --git a/browser/tests/test_mirrors.py b/browser/tests/test_mirrors.py new file mode 100644 index 0000000..46586e3 --- /dev/null +++ b/browser/tests/test_mirrors.py @@ -0,0 +1,229 @@ +"""Several iPhones at once (extra phones follow the main one) and the USB / Wi-Fi connection choice.""" + +import asyncio +import time + +import pytest +from fastapi.testclient import TestClient + +from spoofer import geo +from spoofer.device import pmd3 +from spoofer.device.base import DeviceError + +A = (51.5, -0.12) +B = geo.destination(A, 90, 300) +MAIN, SECOND = "SIMULATED-0001", "SIMULATED-0002" + + +@pytest.fixture() +def client(tmp_path, monkeypatch): + monkeypatch.setenv("SPOOFER_DATA_DIR", str(tmp_path)) + from spoofer import server + from spoofer.store import Store + + server.app.state.s = server.AppState() + server.app.state.s.store = Store(tmp_path / "data.json") + with TestClient(server.app, base_url="http://127.0.0.1:8765") as c: + yield c + + +def _state(): + from spoofer import server + + return server.app.state.s + + +def _until(pred, timeout=5.0): + end = time.monotonic() + timeout + while time.monotonic() < end: + if pred(): + return True + time.sleep(0.02) + return False + + +def _connect_two(client): + assert client.post("/api/connect", json={"driver": "mock", "udid": MAIN}).status_code == 200 + r = client.post("/api/mirrors", json={"udid": SECOND}) + assert r.status_code == 200, r.text + return r.json() + + +def test_two_simulated_phones_and_status(client): + devices = client.get("/api/devices?driver=mock").json()["devices"] + assert [d["udid"] for d in devices] == [MAIN, SECOND] + data = _connect_two(client) + assert data["mirror"]["name"] == "Simulated iPhone 2" and data["mirror"]["state"] == "ok" + st = client.get("/api/status").json() + assert st["device"]["udid"] == MAIN + assert [m["udid"] for m in st["mirrors"]] == [SECOND] + assert st["features"]["multi_device"] and st["features"]["wifi"] + + +def test_mirror_follows_teleport_route_and_stop(client): + _connect_two(client) + s = _state() + main, mirror = s.driver, s.mirrors[SECOND].driver + client.post("/api/location/set", json={"lat": A[0], "lon": A[1]}) + assert _until(lambda: mirror.location == main.location == pytest.approx(A, abs=1e-5)) + body = {"name": "Two", "waypoints": [{"lat": A[0], "lon": A[1]}, {"lat": B[0], "lon": B[1]}], + "legs": [{"mode": "straight", "cruise_kmh": 36}], + "settings": {"default_cruise_kmh": 36, "accel_ms2": 2, "decel_ms2": 2}} + tid = client.post("/api/route/build", json=body).json()["id"] + client.post(f"/api/player/load/{tid}", json={}) + assert client.post("/api/player-options", json={"multiplier": 10, "tick_s": 0.2}).status_code == 200 + client.post("/api/player/play", json={}) + assert _until(lambda: client.get("/api/status").json()["player"]["state"] == "finished", 20) + assert _until(lambda: mirror.location is not None and geo.haversine_m(mirror.location, B) < 1.0) + assert geo.haversine_m(main.location, B) < 1.0 + assert len(mirror.history) > 5 # it moved along the route, not just to the end + assert len(mirror.history) >= 0.8 * len(main.history) + # Stop spoofing clears every phone + client.post("/api/location/clear", json={}) + assert _until(lambda: mirror.location is None and main.location is None) + + +def test_a_slow_mirror_never_holds_up_the_main_phone(client): + _connect_two(client) + s = _state() + mirror = s.mirrors[SECOND].driver + real_set = mirror.set_location + + async def slow(lat, lon): + await asyncio.sleep(0.4) + await real_set(lat, lon) + + mirror.set_location = slow + t0 = time.monotonic() + for i in range(6): + client.post("/api/location/set", json={"lat": A[0] + i * 1e-4, "lon": A[1]}) + assert time.monotonic() - t0 < 1.5 # six sends to a 0.4 s phone would take 2.4 s if waited for + assert s.driver.location == pytest.approx((A[0] + 5e-4, A[1]), abs=1e-7) + # the mirror skips the positions it fell behind on and ends where the main phone is + assert _until(lambda: mirror.location == pytest.approx((A[0] + 5e-4, A[1]), abs=1e-7)) + assert s.mirrors[SECOND].sent < 6 + + +def test_a_lost_mirror_is_marked_and_the_rest_keeps_going(client): + _connect_two(client) + s = _state() + + async def broken(lat, lon): + raise DeviceError("Lost the connection to the iPhone") + + s.mirrors[SECOND].driver.set_location = broken + assert client.post("/api/location/set", json={"lat": A[0], "lon": A[1]}).status_code == 200 + assert _until(lambda: client.get("/api/status").json()["mirrors"][0]["state"] == "lost") + m = client.get("/api/status").json()["mirrors"][0] + assert "Lost the connection" in m["error"] + assert client.post("/api/location/set", json={"lat": B[0], "lon": B[1]}).status_code == 200 + assert s.driver.location == pytest.approx(B, abs=1e-7) + assert client.delete(f"/api/mirrors/{SECOND}").json()["mirrors"] == [] + + +def test_removing_a_mirror_sends_it_back_to_its_real_location(client): + _connect_two(client) + s = _state() + mirror = s.mirrors[SECOND].driver + client.post("/api/location/set", json={"lat": A[0], "lon": A[1]}) + assert _until(lambda: mirror.location is not None) + assert client.delete(f"/api/mirrors/{SECOND}").status_code == 200 + assert mirror.location is None and mirror.info is None + assert s.driver.location == pytest.approx(A, abs=1e-7) # the main phone keeps its position + assert client.delete(f"/api/mirrors/{SECOND}").status_code == 404 + + +def test_new_mirror_catches_up_and_rules(client): + assert client.post("/api/mirrors", json={"udid": SECOND}).status_code == 409 # no main phone yet + client.post("/api/connect", json={"driver": "mock", "udid": MAIN}) + client.post("/api/location/set", json={"lat": A[0], "lon": A[1]}) + assert client.post("/api/mirrors", json={"udid": MAIN}).status_code == 409 # that's the main phone + assert client.post("/api/mirrors", json={"udid": SECOND, "connection": "usb"}).status_code == 200 + s = _state() + assert _until(lambda: s.mirrors[SECOND].driver.location == pytest.approx(A, abs=1e-7)) # caught up at once + assert client.post("/api/mirrors", json={"udid": SECOND}).status_code == 409 # already following + assert client.post("/api/mirrors", json={"udid": "SIMULATED-9999"}).status_code == 409 + assert client.post("/api/mirrors", json={"udid": SECOND, "connection": "bluetooth"}).status_code == 422 + # connecting the main phone to the mirrored one makes it the main phone instead + client.post("/api/connect", json={"driver": "mock", "udid": SECOND}) + st = client.get("/api/status").json() + assert st["device"]["udid"] == SECOND and st["mirrors"] == [] + # disconnecting ends the mirrors too + client.post("/api/mirrors", json={"udid": MAIN}) + client.post("/api/disconnect", json={}) + assert client.get("/api/status").json()["mirrors"] == [] + + +def test_wifi_tool_and_connection_field(client): + assert client.post("/api/connect", json={"driver": "mock", "connection": "network"}).status_code == 200 + assert client.post("/api/device/wifi", json={}).json()["message"].startswith("Simulator") + assert client.post("/api/connect", json={"driver": "mock", "connection": "carrier-pigeon"}).status_code == 422 + + +# ---------------------------------------------------------------- pymobiledevice3 driver, faked usbmux +class _Mux: + def __init__(self, serial, ct): + self.serial, self.connection_type = serial, ct + + @property + def is_usb(self): + return self.connection_type == "USB" + + +class _Lockdown: + def __init__(self, ct): + self.short_info = {"DeviceName": "Test phone", "ProductVersion": "16.7", "ProductType": "iPhone10,1"} + self.product_version = "16.7" + self.udid = "00008030-TEST" + self.service = type("S", (), {"mux_device": _Mux("00008030-TEST", ct)})() + + async def close(self): + pass + + +def test_pmd3_lists_a_phone_once_with_both_connections(monkeypatch): + from pymobiledevice3 import lockdown, usbmux + + async def fake_list(usbmux_address=None): + return [_Mux("00008030-TEST", "Network"), _Mux("00008030-TEST", "USB"), _Mux("OTHER", "Network")] + + async def fake_lockdown(serial=None, autopair=True, connection_type=None, **kw): + return _Lockdown(connection_type or "USB") + + monkeypatch.setattr(usbmux, "list_devices", fake_list) + monkeypatch.setattr(lockdown, "create_using_usbmux", fake_lockdown) + out = asyncio.run(pmd3.Pmd3Driver().list_devices()) + assert [(d["udid"], d["connection"], d["connections"]) for d in out] == [ + ("00008030-TEST", "USB + Wi-Fi", ["USB", "Wi-Fi"]), ("OTHER", "Wi-Fi", ["Wi-Fi"])] + + +def test_pmd3_connects_over_the_chosen_connection(monkeypatch): + from pymobiledevice3 import lockdown + + asked = [] + + class NoDeviceConnectedError(Exception): + pass + + async def fake_lockdown(serial=None, autopair=True, connection_type=None, **kw): + asked.append(connection_type) + if connection_type == "Network" and serial == "OFFLINE": + raise NoDeviceConnectedError() + return _Lockdown(connection_type or "USB") + + monkeypatch.setattr(lockdown, "create_using_usbmux", fake_lockdown) + drv = pmd3.Pmd3Driver() + + async def no_mount(provider): + return "" + + monkeypatch.setattr(drv, "_try_mount", no_mount) + info = asyncio.run(drv.connect("00008030-TEST", "network")) + assert info.connection == "Wi-Fi" and asked[-1] == "Network" + assert info.transport == "Lockdown simulatelocation" + info = asyncio.run(drv.connect("00008030-TEST", "auto")) + assert info.connection == "USB" and asked[-1] is None + asyncio.run(drv.connect("00008030-TEST", "usb")) + assert asked[-1] == "USB" + with pytest.raises(DeviceError, match="Allow Wi-Fi connection"): + asyncio.run(drv.connect("OFFLINE", "network")) diff --git a/browser/tests/test_offline.py b/browser/tests/test_offline.py index 784636d..6af10be 100644 --- a/browser/tests/test_offline.py +++ b/browser/tests/test_offline.py @@ -50,7 +50,7 @@ def fake_ofm(requests: list): def handler(req: httpx.Request) -> httpx.Response: path = req.url.raw_path.decode().removeprefix("/") requests.append(path) - assert req.headers["user-agent"].startswith("LocationSpoofer/") + assert req.headers["user-agent"].startswith("iDevBench/") if path == "planet": return httpx.Response(200, json={"tiles": ["https://tiles.openfreemap.org/planet/v1/{z}/{x}/{y}.pbf"]}) if path.startswith("styles/"): diff --git a/browser/tests/test_screen.py b/browser/tests/test_screen.py new file mode 100644 index 0000000..675b99b --- /dev/null +++ b/browser/tests/test_screen.py @@ -0,0 +1,220 @@ +"""Screen mirroring: input parsing, HEVC framing and the simulated session (same cases as the standalone).""" + +import json +import struct + +import pytest +from fastapi.testclient import TestClient + +from spoofer import screen as mi + + +class _Writer: + def __init__(self): + self.bits = [] + + def put(self, v, n): + self.bits += [(v >> i) & 1 for i in reversed(range(n))] + + def ue(self, v): + x = v + 1 + n = x.bit_length() + self.put(0, n - 1) + self.put(x, n) + + def finish(self): + self.bits += [0] * (-len(self.bits) % 8) + return bytes(int("".join(map(str, self.bits[i : i + 8])), 2) for i in range(0, len(self.bits), 8)) + + +def sample_sps(): + """A 1170x2532 Main-profile SPS (level 6.0), with emulation prevention as an encoder adds it.""" + w = _Writer() + w.put(0, 4); w.put(0, 3); w.put(1, 1) + w.put(0, 2); w.put(0, 1); w.put(1, 5); w.put(0x60000000, 32); w.put(0x90, 8); w.put(0, 40); w.put(180, 8) + w.ue(0); w.ue(1); w.ue(1184); w.ue(2544) + w.put(1, 1); w.ue(0); w.ue(7); w.ue(0); w.ue(6) + w.ue(0); w.ue(0); w.put(1, 1) + nal, zeros = bytearray([mi.NAL_SPS << 1, 1]), 0 + for b in w.finish(): + if zeros >= 2 and b <= 3: + nal.append(3) + zeros = 0 + zeros = zeros + 1 if b == 0 else 0 + nal.append(b) + return bytes(nal) + + +def nal(t, body=b""): + return bytes([t << 1, 1]) + body + + +def with_params(d, seq=0): + for n in (nal(mi.NAL_VPS, b"\1"), sample_sps(), nal(mi.NAL_PPS, b"\2")): + d.push(seq, 1000, False, n) + seq += 1 + return seq + + +def test_parses_sps_codec_and_hvcc(): + info = mi.parse_sps(sample_sps()) + assert (info["width"], info["height"], info["chroma"]) == (1170, 2532, 1) + assert mi.codec_string(info) == "hev1.1.6.L180.90" + r = mi.hvcc(info, nal(32, b"\xaa"), sample_sps(), nal(34, b"\xbb")) + assert r[0] == 1 and r[1:13] == info["ptl"] and r[16] == 0xFD and r[21] & 3 == 3 and r[22] == 3 + assert r[23] == 0x80 | 32 and r.endswith(nal(34, b"\xbb")) + assert mi.parse_sps(sample_sps()[:8]) is None + + +def test_frames_fragments_and_footer(): + d = mi.Depacketizer() + seq = with_params(d) + out = d.push(seq, 1000, True, nal(19, b"\x09\x09") + mi.APPLE_SLICE_FOOTER) + assert out == [(1000, True, [nal(19, b"\x09\x09")])] and d.config_changed + assert d.decoder_config()["width"] == 1170 + body = bytes(range(30)) + fu = lambda s, e, part: bytes([mi.NAL_FU << 1, 1, (0x80 if s else 0) | (0x40 if e else 0) | 1]) + part + assert d.push(seq + 1, 2000, False, fu(True, False, body[:10])) == [] + assert d.push(seq + 2, 2000, False, fu(False, False, body[10:20])) == [] + assert d.push(seq + 3, 2000, True, fu(False, True, body[20:])) == [(2000, False, [nal(1, body)])] + sei, idr = nal(39, b"\5"), nal(19, b"\1\2") + ap = bytes([mi.NAL_AP << 1, 1]) + b"".join(len(n).to_bytes(2, "big") + n for n in (sei, idr)) + assert d.push(seq + 4, 3000, True, ap) == [(3000, True, [sei, idr])] + + +def test_loss_holds_frames_until_keyframe(): + d = mi.Depacketizer() + seq = with_params(d) + assert len(d.push(seq, 1, True, nal(19, b"\1"))) == 1 + assert d.push(seq + 2, 2, True, nal(1, b"\1")) == [] and d.waiting_for_key and d.lost_packets == 1 + assert d.push(seq + 3, 3, True, nal(1, b"\1")) == [] + assert d.push(seq + 4, 4, True, nal(20, b"\1"))[0][1] is True + assert d.push(seq + 1, 2, True, nal(1, b"\1")) == [] # late duplicate + assert d.push(seq + 5, 10, False, nal(1, b"\1")) == [] + assert d.push(seq + 6, 11, False, nal(1, b"\2"))[0][0] == 10 # a new timestamp ends the frame + + +def test_inputs_and_keys(): + assert mi.parse_input({"t": "touch", "phase": "down", "x": 0.5, "y": 1}) == ("touch", "down", 32768, 65535, None) + assert mi.parse_input({"t": "touch", "phase": "move", "x": 0, "y": 0, "x2": 1, "y2": 0.5}) == ("touch", "move", 0, 0, (65535, 32768)) + assert mi.parse_input({"t": "gesture", "name": "back"}) == ("gesture", "back") + assert mi.parse_input({"t": "long_press", "x": 0, "y": 0}) == ("long_press", 0, 0, 800) + assert mi.parse_input({"t": "key", "usage": 4, "command": True}) == ("key", 4, None, True) + assert [mi.upright_to_native(0.25, 0, 0), mi.upright_to_native(0, 0.25, 90), mi.upright_to_native(1, 1, 180), + mi.upright_to_native(0, 0.25, 270)] == [(16384, 0), (16384, 65535), (0, 0), (49151, 0)] + assert mi.memory({"vmActiveCount": 10, "vmWireCount": 5, "vmFreeCount": 5, "vmInactiveCount": 4}) == (15 * 16384, 24 * 16384) + assert mi.memory({}) == (None, None) + assert mi.parse_input({"t": "swipe", "x1": 0, "y1": 0, "x2": 1, "y2": 1})[-1] == 300 + assert mi.parse_input({"t": "key", "usage": 40, "down": False}) == ("key", 40, False, False) + assert mi.parse_input({"t": "refresh"}) == ("refresh",) + for bad in ({"t": "tap", "x": 1.5, "y": 0}, {"t": "tap", "x": "0.2", "y": 0}, {"t": "touch", "phase": "hover", "x": 0, "y": 0}, + {"t": "button", "name": "power"}, {"t": "key", "usage": 1, "down": True}, {"t": "fly"}, [], + {"t": "key", "usage": 4, "down": "yes"}, {"t": "touch", "phase": "down", "x": 0, "y": 0, "x2": 0.5}, {"t": "gesture", "name": "spin"}): + with pytest.raises(ValueError): + mi.parse_input(bad) + assert [mi.char_usage(c) for c in "aZ0(?/"] == [(4, False), (0x1D, True), (0x27, False), (0x26, True), (0x38, True), (0x38, False)] + assert mi.char_usage("é") is None + + +def test_message_layouts_match_the_standalone(): + c = {"codec": "hev1.1.6.L180.90", "hvcc": b"\1\2", "width": 1170, "height": 2532} + assert mi.config_message(c) == bytes([1, 0x04, 0x92, 0x09, 0xE4, 16]) + b"hev1.1.6.L180.90\1\2" + assert mi.frame_message(True, [b"\x26\1\7"], 5) == bytes([2, 1]) + struct.pack(">Q", 5) + b"\0\0\0\3\x26\1\7" + assert mi.audio_message(b"\1\0", 2) == bytes([3]) + struct.pack(">Q", 2) + b"\1\0" + + +def test_rtcp_and_rtp_helpers(): + assert len(mi._rr_sdes(1, 2, 3)) == 44 and mi._rr_sdes(1, 2, 3)[1] == 201 + kf = mi._keyframe_request(1, 2, 3, 4) + assert len(kf) == 44 + 12 + 20 and kf[45] == 206 + assert mi._frame_ack(7, 9) == struct.pack(">BBHIII", 0x80, 204, 3, 7, 5, 9) + pkt = bytes([0x80, 0x80 | 100]) + struct.pack(">HII", 7, 99, 1) + b"payload" + assert mi._rtp(pkt) == (7, 99, True, b"payload") + assert mi._rtp(bytes([0x80, 201]) + bytes(10)) is None + s = mi._SeqCounter() + for seq in (65534, 65535, 0, 1, 65535, 2): + s.add(seq) + assert s.value == 0x10002 + answer = {"connection": {"streamConfig": {"SourcePort": 50001, "LocalSSRC": 7, "RemoteSSRC": 9}}} + assert mi._stream_config(answer) == (50001, 9, 7) and mi._stream_config(None) == (0, 0, 0) + + +def test_reads_the_screen_rotation(): + info = {"displays": [{"external": True, "currentOrientation": "rot180"}, {"primary": True, "currentOrientation": "rot90"}, + {"active": True, "currentOrientation": "rot270"}]} + assert mi.display_rotation(info) == 270 + assert mi.display_rotation({"displays": [{"currentOrientation": "rot90"}]}) == 90 + assert mi.display_rotation(True) == 0 + + +@pytest.fixture() +def client(tmp_path, monkeypatch): + monkeypatch.setenv("SPOOFER_DATA_DIR", str(tmp_path)) + from spoofer import server + from spoofer.store import Store + + server.app.state.s = server.AppState() + server.app.state.s.store = Store(tmp_path / "data.json") + with TestClient(server.app, base_url="http://127.0.0.1:8765") as c: + yield c + + +def test_mirror_routes_with_the_simulator(client): + assert client.get("/api/screen").json()["state"] == "off" + assert client.post("/api/screen/input", json={"t": "tap", "x": 0.5, "y": 0.5}).status_code == 409 + s = client.post("/api/screen/start", json={"driver": "mock"}).json() + assert (s["state"], s["simulated"], s["width"]) == ("on", True, 1170) + assert client.post("/api/screen/input", json={"t": "text", "text": "hi"}).json() == {"ok": True} + assert client.post("/api/screen/input", json={"t": "tap", "x": 2, "y": 0}).status_code == 400 + assert client.get("/api/screen/screenshot").status_code == 409 + # The test client sends "Host: testserver" for WebSockets unless told otherwise. + with client.websocket_connect("/api/screen/ws", headers={"host": "127.0.0.1:8765"}) as ws: + assert json.loads(ws.receive_text())["status"]["state"] == "on" + ws.send_text(json.dumps({"t": "button", "name": "nope"})) + assert json.loads(ws.receive_text())["type"] == "error" + from spoofer import server + + assert ("text", "hi") in server.app.state.s.screen.sim_inputs + assert client.post("/api/screen/stop").json()["state"] == "off" + + +def test_websocket_refuses_other_websites(client): + from starlette.websockets import WebSocketDisconnect + + with pytest.raises(WebSocketDisconnect): + with client.websocket_connect("/api/screen/ws", headers={"host": "127.0.0.1:8765", "origin": "https://evil.example"}) as ws: + ws.receive_text() + + +def test_screen_captures_go_to_the_chosen_folder(client, tmp_path): + folder = tmp_path / "captures" + client.put("/api/store", json={"settings": {"capture_folder": str(folder)}}) + first = client.post("/api/screen/save?name=shot.png", content=b"png").json()["path"] + second = client.post("/api/screen/save?name=shot.png", content=b"png").json()["path"] + assert open(first, "rb").read() == b"png" and second.endswith("shot-1.png") + for bad in ("../x.png", "x.exe", ".png", "a/b.png"): + assert client.post("/api/screen/save", params={"name": bad}, content=b"x").status_code == 400, bad + + +def test_unanswered_keyframe_requests_restart_the_stream(monkeypatch): + import asyncio + import itertools + import types + + clock = itertools.count(0, 0.6) # every look at the clock is 0.6 s later + monkeypatch.setattr(mi, "time", types.SimpleNamespace(monotonic=lambda: next(clock))) + live = mi._Live(mi.Screen(), 1) + live.v_phone, live.v_ours, live.v_port, live.a_phone = 2, 1, 5, 0 + live.v_seq, live.a_seq = mi._SeqCounter(), mi._SeqCounter() + live.video = live.audio_rx = None + requests = [] + + async def rtcp(_transport, _port, packet): + live.last_dgram = mi.time.monotonic() # the phone keeps sending, just no keyframe + if len(packet) > 44: + requests.append(packet) + + live._rtcp = rtcp + with pytest.raises(mi._Restart) as e: + asyncio.run(asyncio.wait_for(live._feedback(), 10)) + assert e.value.auto and len(requests) == mi.MAX_KEY_REQUESTS diff --git a/docs/API.md b/docs/API.md new file mode 100644 index 0000000..7b35119 --- /dev/null +++ b/docs/API.md @@ -0,0 +1,136 @@ +# iDevBench local API + +While iDevBench is open, other programs on the same computer can use the same HTTP API as its own window: connect to the iPhone, set its location, watch its screen and control it. + +* **Address:** `http://127.0.0.1:8766` for the standalone app, `http://127.0.0.1:8765` for the browser edition. Start the app with `--port ` to choose another port; if the standalone app's port is taken by another program, it picks a free one at random. +* **Who can use it:** programs on this computer. Requests must use the host `127.0.0.1` or `localhost`. Requests from websites (any `Origin` header other than the app's own page) are refused with `403`, and the server is not reachable from other computers. +* **Format:** JSON in and out. Errors come back as `{"detail": "message"}` with status `400` (bad request), `409` (the device or mirroring is not ready) or `502` (an online service failed). +* **Stability:** these endpoints are what the app's own window uses. They are kept stable where possible, but check the [changelog](../CHANGELOG.md) when you update. + +## Device and location + +| Method and path | Body | What it does | +|---|---|---| +| `GET /api/status` | | App version, the connected device, playback state | +| `GET /api/devices?driver=pmd3` | | iPhones found over USB (`driver=mock` lists the simulator) | +| `POST /api/connect` | `{"driver": "pmd3", "udid": null}` | Connect (first iPhone when `udid` is null). Use `"mock"` to try things without a phone | +| `POST /api/disconnect` | `{}` | Disconnect | +| `POST /api/location/set` | `{"lat": 51.5007, "lon": -0.1246}` | Set the simulated location | +| `POST /api/location/clear` | `{}` | Back to the real GPS | + +```bash +curl -X POST http://127.0.0.1:8766/api/connect -H "Content-Type: application/json" -d '{"driver":"pmd3"}' +``` + +```bash +curl -X POST http://127.0.0.1:8766/api/location/set -H "Content-Type: application/json" -d '{"lat":48.8584,"lon":2.2945}' +``` + +## Screen mirroring and control + +Needs iOS 27 or newer. The phone only accepts touches and keys while mirroring runs, so start it first (the app's Mirroring section and other programs share one session). + +| Method and path | Body | What it does | +|---|---|---| +| `GET /api/screen` | | Status: `state` (`off`, `starting`, `on`, `error`), `error`, `simulated`, `width`, `height` (screen pixels), `audio`, `note`, `rotation` (see below) | +| `POST /api/screen/start` | `{"driver": "pmd3", "udid": null, "audio": true}` | Start (all fields optional; defaults to the device the app is connected to). Returns the status once the picture is flowing | +| `POST /api/screen/stop` | `{}` | Stop | +| `POST /api/screen/input` | one input, see below | Tap, swipe, press a button or type | +| `GET /api/screen/screenshot` | | A PNG of the screen, taken by the phone | +| `GET /api/screen/ws` | WebSocket | Live picture, sound and status; send inputs on it too | +| `POST /api/screen/save?name=` | the file | Saves a screenshot or recording (`.png`, `.mp4`, `.webm`) to the folder chosen in *Settings › Mirroring* (Downloads by default); answers `{"path": ...}` | +| `GET /api/screen/perf` | | The iPhone's `cpu` (% of all cores), `cores`, `memory_used` and `memory_total` (bytes), `gpu` (%), `fps` (its own frame rate), `battery` (%), `charging`, `battery_temp` (°C). Null until measured: the first request starts measuring | + +### Inputs + +Coordinates are fractions of the screen as the phone holds it natively (portrait on an iPhone): `0,0` is the top left, `1,1` the bottom right. Multiply by `width`/`height` from the status to work in pixels. + +The picture always arrives in that native orientation. When the phone is turned, the status's `rotation` says how many degrees clockwise (0, 90, 180 or 270) to turn the picture to show it upright; turn your coordinates back the same way before sending them. + +| Input | Example | +|---|---| +| Tap | `{"t": "tap", "x": 0.5, "y": 0.9}` | +| Swipe (`ms` 50–5000, default 300) | `{"t": "swipe", "x1": 0.5, "y1": 0.8, "x2": 0.5, "y2": 0.2, "ms": 300}` | +| One finger, step by step | `{"t": "touch", "phase": "down", "x": 0.5, "y": 0.5}`, then `"move"`, then `"up"` | +| Two fingers (pinch), step by step | the same with `"x2"` and `"y2"` for the second finger | +| Touch and hold (`ms` 100–5000, default 800) | `{"t": "long_press", "x": 0.5, "y": 0.5}` | +| System gesture, drawn the right way up for how the phone is turned | `{"t": "gesture", "name": "app_switcher"}`: `home`, `app_switcher`, `control_centre`, `notification_centre`, `back` | +| Hardware button | `{"t": "button", "name": "home"}`: `home`, `lock`, `volume-up`, `volume-down`, `mute`, `siri` | +| Type text (US keyboard layout, up to 2000 characters) | `{"t": "text", "text": "Hello"}` | +| One key down or up ([HID keyboard usage](https://usb.org/sites/default/files/hut1_5.pdf), page 7) | `{"t": "key", "usage": 40, "down": true}` (40 is Return) | +| A key pressed and released, optionally with ⌘ | `{"t": "key", "usage": 4, "command": true}` (⌘A) | +| Ask for a fresh full frame | `{"t": "keyframe"}` | +| Restart the picture (if it froze; the app also does this by itself after a few seconds) | `{"t": "refresh"}` | + +```bash +curl -X POST http://127.0.0.1:8766/api/screen/start -H "Content-Type: application/json" -d '{}' +``` + +```bash +curl -X POST http://127.0.0.1:8766/api/screen/input -H "Content-Type: application/json" -d '{"t":"tap","x":0.5,"y":0.5}' +``` + +```bash +curl -o screen.png http://127.0.0.1:8766/api/screen/screenshot +``` + +### The WebSocket + +`ws://127.0.0.1:8766/api/screen/ws` sends: + +* **text**: `{"type": "status", "status": {...}}` when the status changes (one straight away), and `{"type": "error", "detail": "..."}` when an input you sent failed; +* **binary**, first byte is the kind, numbers are big-endian: + * `1` decoder setup: `width` (u16), `height` (u16), codec string length (u8), codec string (for example `hev1.1.6.L150.90`), then the HEVC decoder configuration record (`hvcC`); + * `2` frame: keyframe flag (u8, 1 = key), timestamp in microseconds (u64), then the frame as HEVC NAL units, each with a 4-byte length; + * `3` sound: timestamp in microseconds (u64), then PCM: 16-bit little-endian, 48 kHz, stereo, interleaved. + +A new connection gets the decoder setup (if the picture has started) and frames from the next keyframe on. Send inputs as text messages with the same JSON as `POST /api/screen/input`. + +To decode in a browser, use WebCodecs: `VideoDecoder.configure({codec, description: hvcC})`, then `new EncodedVideoChunk({type: key ? "key" : "delta", timestamp, data})` for each frame. To save the raw stream for a player, write the `hvcC` parameter sets and each NAL unit with `00 00 00 01` start codes instead of lengths; `ffplay` and VLC play the result. + +### Example: Python + +```python +import json, requests +from websockets.sync.client import connect # pip install requests websockets + +base = "http://127.0.0.1:8766" +print(requests.post(f"{base}/api/screen/start", json={}).json()) +requests.post(f"{base}/api/screen/input", json={"t": "button", "name": "home"}).raise_for_status() +requests.post(f"{base}/api/screen/input", json={"t": "swipe", "x1": 0.5, "y1": 0.8, "x2": 0.5, "y2": 0.3}) +open("screen.png", "wb").write(requests.get(f"{base}/api/screen/screenshot").content) + +with connect("ws://127.0.0.1:8766/api/screen/ws") as ws: + for _ in range(100): + msg = ws.recv() + if isinstance(msg, str): + print(json.loads(msg)) + elif msg[0] == 2: + print("frame", "key" if msg[1] else "delta", len(msg) - 10, "bytes") +``` + +## AI agents (MCP) + +iDevBench is a [Model Context Protocol](https://modelcontextprotocol.io) server: AI agents (Claude, Codex, Cursor, Gemini, VS Code and others) get tools for everything the app does with the phone. Location: `get_status`, `list_devices`, `connect_device`, `search_place`, `parse_map_link`, `set_location`, `clear_location`, `drive_route`, `play_track`, `playback`, `seek_playback`, `playback_options`, `joystick`, `list_favourites`, `mount_developer_image`, `reveal_developer_mode`. Screen: `start_mirroring`, `stop_mirroring`, `mirroring_status`, `screenshot`, `tap`, `long_press`, `swipe`, `gesture`, `press_button`, `type_text`, `press_key`, `refresh_mirroring`, `phone_performance`, `wait`. And `guide`, which teaches the agent how to work with the phone (no skill files to install). The list and descriptions are in [`ui/mcp-tools.json`](../ui/mcp-tools.json), the guide in [`ui/mcp-guide.md`](../ui/mcp-guide.md). The app must be open. + +**The easy way:** *Settings › AI agents* (or *Connect an AI agent* in the Mirroring section) has a prompt to copy and paste into the agent once; the agent adds iDevBench to its own settings. Claude Desktop can't do that from a chat, so the same page has *Add to Claude Desktop*. + +**Claude Code plugin:** this repository is a plugin marketplace. + +```bash +claude plugin marketplace add YK3D/iPhone-location-spoofer +``` + +```bash +claude plugin install idevbench@idevbench +``` + +**By hand:** apps that connect to a URL use `http://127.0.0.1:8766/mcp` (the browser edition: port 8765), for example `claude mcp add --transport http --scope user idevbench http://127.0.0.1:8766/mcp`. Apps that start a program use the app itself with `--mcp`, for example in Claude Desktop's `claude_desktop_config.json`: + +```json +{ "mcpServers": { "idevbench": { "command": "C:\\path\\to\\LocationSpooferStandalone.exe", "args": ["--mcp"] } } } +``` + +`--mcp` only passes messages to the app that is already open (either edition); it opens no window. + +The agent sees what the screenshots show, and the AI service it runs on receives them, along with anything you tell the agent (for example a passcode you give it to unlock the phone). Keep an eye on what it does: its taps act on the real phone. diff --git a/docs/licenses/fdk-aac.txt b/docs/licenses/fdk-aac.txt new file mode 100644 index 0000000..05b32bd --- /dev/null +++ b/docs/licenses/fdk-aac.txt @@ -0,0 +1,92 @@ +Software License for The Fraunhofer FDK AAC Codec Library for Android + +© Copyright 1995 - 2018 Fraunhofer-Gesellschaft zur Förderung der angewandten +Forschung e.V. All rights reserved. + + 1. INTRODUCTION +The Fraunhofer FDK AAC Codec Library for Android ("FDK AAC Codec") is software +that implements the MPEG Advanced Audio Coding ("AAC") encoding and decoding +scheme for digital audio. This FDK AAC Codec software is intended to be used on +a wide variety of Android devices. + +AAC's HE-AAC and HE-AAC v2 versions are regarded as today's most efficient +general perceptual audio codecs. AAC-ELD is considered the best-performing +full-bandwidth communications codec by independent studies and is widely +deployed. AAC has been standardized by ISO and IEC as part of the MPEG +specifications. + +Patent licenses for necessary patent claims for the FDK AAC Codec (including +those of Fraunhofer) may be obtained through Via Licensing +(www.vialicensing.com) or through the respective patent owners individually for +the purpose of encoding or decoding bit streams in products that are compliant +with the ISO/IEC MPEG audio standards. Please note that most manufacturers of +Android devices already license these patent claims through Via Licensing or +directly from the patent owners, and therefore FDK AAC Codec software may +already be covered under those patent licenses when it is used for those +licensed purposes only. + +Commercially-licensed AAC software libraries, including floating-point versions +with enhanced sound quality, are also available from Fraunhofer. Users are +encouraged to check the Fraunhofer website for additional applications +information and documentation. + +2. COPYRIGHT LICENSE + +Redistribution and use in source and binary forms, with or without modification, +are permitted without payment of copyright license fees provided that you +satisfy the following conditions: + +You must retain the complete text of this software license in redistributions of +the FDK AAC Codec or your modifications thereto in source code form. + +You must retain the complete text of this software license in the documentation +and/or other materials provided with redistributions of the FDK AAC Codec or +your modifications thereto in binary form. You must make available free of +charge copies of the complete source code of the FDK AAC Codec and your +modifications thereto to recipients of copies in binary form. + +The name of Fraunhofer may not be used to endorse or promote products derived +from this library without prior written permission. + +You may not charge copyright license fees for anyone to use, copy or distribute +the FDK AAC Codec software or your modifications thereto. + +Your modified versions of the FDK AAC Codec must carry prominent notices stating +that you changed the software and the date of any change. For modified versions +of the FDK AAC Codec, the term "Fraunhofer FDK AAC Codec Library for Android" +must be replaced by the term "Third-Party Modified Version of the Fraunhofer FDK +AAC Codec Library for Android." + +3. NO PATENT LICENSE + +NO EXPRESS OR IMPLIED LICENSES TO ANY PATENT CLAIMS, including without +limitation the patents of Fraunhofer, ARE GRANTED BY THIS SOFTWARE LICENSE. +Fraunhofer provides no warranty of patent non-infringement with respect to this +software. + +You may use this FDK AAC Codec software or modifications thereto only for +purposes that are authorized by appropriate patent licenses. + +4. DISCLAIMER + +This FDK AAC Codec software is provided by Fraunhofer on behalf of the copyright +holders and contributors "AS IS" and WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, +including but not limited to the implied warranties of merchantability and +fitness for a particular purpose. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +CONTRIBUTORS BE LIABLE for any direct, indirect, incidental, special, exemplary, +or consequential damages, including but not limited to procurement of substitute +goods or services; loss of use, data, or profits, or business interruption, +however caused and on any theory of liability, whether in contract, strict +liability, or tort (including negligence), arising in any way out of the use of +this software, even if advised of the possibility of such damage. + +5. CONTACT INFORMATION + +Fraunhofer Institute for Integrated Circuits IIS +Attention: Audio and Multimedia Departments - FDK AAC LL +Am Wolfsmantel 33 +91058 Erlangen, Germany + +www.iis.fraunhofer.de/amm +amm-info@iis.fraunhofer.de + diff --git a/docs/testing/multiple-iphones-and-wifi.md b/docs/testing/multiple-iphones-and-wifi.md new file mode 100644 index 0000000..f3d94c0 --- /dev/null +++ b/docs/testing/multiple-iphones-and-wifi.md @@ -0,0 +1,31 @@ +# Testing several iPhones at once and Wi-Fi connections + +These features are on the `feature-testing` branch only. Run that branch from source (see [CONTRIBUTING.md](../../CONTRIBUTING.md#trying-the-feature-testing-branch)), ideally with an empty data folder (`SPOOFER_DATA_DIR`). + +## What they do + +- **More iPhones** (Device section, after connecting): every iPhone added there follows the main one. Teleports, routes, GPX tracks, the joystick and *Stop spoofing* reach all of them. Each extra phone gets positions from its own queue, so a slow phone or one that drops out never holds up the main phone or the others. A phone that stops answering is marked in red until you remove it. *Remove* sends it back to its real location. Up to 8 extra phones. +- **Connect over** (Device tools): *Automatic* uses the cable when the phone is plugged in and Wi-Fi otherwise. *USB cable only* and *Wi-Fi only* force one of them. The choice also applies to phones added under More iPhones. +- **Allow Wi-Fi connection** (Device tools): turns on the phone's "Show this iPhone when on Wi-Fi" setting over the cable, so it can be reached without the cable afterwards. + +## Without an iPhone + +1. Choose *Simulator (no iPhone)* as the Connection and press **Connect**. The Simulator now has two phones. +2. Under **More iPhones**, *Simulated iPhone 2* appears. Press **Add**. +3. Teleport, play a route or use the joystick. The status shows both phones; nothing is sent to real hardware. +4. Press **Remove**, then **Stop spoofing**. + +## With real iPhones + +1. Connect the first iPhone as usual (cable, unlocked, trusted, Developer Mode on). +2. Plug in the second iPhone, unlock it and trust the computer. Press the refresh button next to *Device*. +3. Under **More iPhones**, pick it and press **Add**. iOS 17+ can take up to 30 s. +4. Teleport and play a short route. Check that both phones follow. Unplug one phone while a route plays: the other must keep going, and the unplugged one must turn red. +5. Wi-Fi: with the phone plugged in, press **Allow Wi-Fi connection**. Then set **Connect over** to *Wi-Fi only*, unplug the phone, keep it unlocked on the same network, and connect. + +## Known limits + +- **Browser version, iOS 17+:** pymobiledevice3 allows only one no-admin tunnel per app. A second iOS 17+ phone, and any iOS 17+ phone over Wi-Fi, therefore needs the tunnel helper: *Device tools › Start tunnel helper (admin)*. The standalone app has no such limit, because it opens one tunnel per phone itself. +- **Wi-Fi with iOS 17+:** whether Apple's developer tunnel accepts a Wi-Fi connection depends on the iOS version and on how the phone was paired. This hasn't been verified on hardware yet; the error message says what failed. +- **Wi-Fi needs Apple's device service to see the phone on the network.** On Windows that is the Apple Devices app or iTunes, and the computer and phone must be on the same network (no client isolation). +- **Bluetooth isn't possible.** iPhones only offer the location-simulation service over a cable or the network (usbmuxd and lockdown). No Apple protocol carries it over Bluetooth. diff --git a/plugins/idevbench/.claude-plugin/icon.png b/plugins/idevbench/.claude-plugin/icon.png new file mode 100644 index 0000000..637dc91 Binary files /dev/null and b/plugins/idevbench/.claude-plugin/icon.png differ diff --git a/plugins/idevbench/.claude-plugin/plugin.json b/plugins/idevbench/.claude-plugin/plugin.json new file mode 100644 index 0000000..54a2847 --- /dev/null +++ b/plugins/idevbench/.claude-plugin/plugin.json @@ -0,0 +1,23 @@ +{ + "name": "idevbench", + "version": "1.0.0", + "description": "Use a real iPhone from Claude through the iDevBench app: see and control its screen, set and move its GPS location. Needs iDevBench open on the same computer.", + "author": { + "name": "YK3D" + }, + "homepage": "https://idevbench.vercel.app", + "repository": "https://github.com/YK3D/iPhone-location-spoofer", + "keywords": [ + "iphone", + "ios", + "mirroring", + "location", + "testing", + "automation" + ], + "icon": ".claude-plugin/icon.png", + "documentationUrl": "https://github.com/YK3D/iPhone-location-spoofer/blob/main/docs/API.md#ai-agents-mcp", + "supportUrl": "https://github.com/YK3D/iPhone-location-spoofer/issues", + "privacyPolicyUrl": "https://idevbench.vercel.app/privacy", + "termsOfServiceUrl": "https://idevbench.vercel.app/terms" +} diff --git a/plugins/idevbench/.mcp.json b/plugins/idevbench/.mcp.json new file mode 100644 index 0000000..9a1e08d --- /dev/null +++ b/plugins/idevbench/.mcp.json @@ -0,0 +1,8 @@ +{ + "mcpServers": { + "idevbench": { + "type": "http", + "url": "http://127.0.0.1:8766/mcp" + } + } +} diff --git a/plugins/idevbench/skills/idevbench/SKILL.md b/plugins/idevbench/skills/idevbench/SKILL.md new file mode 100644 index 0000000..40fbbd6 --- /dev/null +++ b/plugins/idevbench/skills/idevbench/SKILL.md @@ -0,0 +1,52 @@ +--- +name: idevbench +description: Use a real iPhone through iDevBench - see and control its screen (screenshot, tap, swipe, type, gestures, buttons) and set or move its GPS location (teleport, routes, tracks, joystick). Use when asked to test, use or automate an iOS app on a connected iPhone, or to check how an app behaves at another place or while moving. +--- + +# Using an iPhone through iDevBench + +The `idevbench` tools control a real iPhone connected to this computer, through the iDevBench app (which must be open). The phone belongs to the user: act carefully. + +## Location + +- `connect_device` once (`driver: "mock"` tries things without a phone). +- Find coordinates with `search_place` (or `parse_map_link` for a Google Maps link), then `set_location`. +- Movement: `drive_route` with checkpoints and one leg per stretch (`car`, `bike`, `foot`, `sea` or `straight`); `play_track` for a list of points; `joystick` to move live. Control playback with `playback` (pause, resume, continue, stop) and `playback_options`; check progress with `get_status`. +- `clear_location` when done, unless the user wants the phone to stay there. + +## Screen (iOS 27 and newer) + +1. `mirroring_status`; if it isn't `on`, `start_mirroring`. If that fails (locked phone, no Developer Mode, older iOS, Camera or a recording app open), tell the user what the error says. +2. Work in a loop: `screenshot`, decide one action, do it, `screenshot` again. Use `wait` (500-2000 ms) after opening an app, navigating or submitting. Never chain several taps blind. +3. If nothing changed, the tap missed or the app is busy: wait once, then retry with an adjusted position. Don't repeat the same miss more than twice. If screenshots stop changing at all, `refresh_mirroring`. + +Positions are fractions of the screenshot: `x = pixel x / width`, `y = pixel y / height` (0,0 top left). Aim for the centre of a control. Avoid the top ~5% (status bar) and bottom ~3% (home indicator) unless you mean a system gesture. + +| Want | Tool | +|---|---| +| Press a button, link, field or cell | `tap` | +| Scroll down | `swipe` from `y: 0.75` to `y: 0.3` (the finger moves up); up is the reverse | +| Context menu, move icons | `long_press` | +| Type | `tap` the field, check the keyboard is up, then `type_text` (US layout; accents and emoji are skipped) | +| Submit | `press_key` usage 40 (Return) | +| Select all / copy / paste | `press_key` usage 4 / 6 / 25 with `command: true` | +| Home Screen, app switcher, Control Centre, notifications, back | `gesture` | +| Open an app | `gesture` home, `swipe` down from the middle to open Search, `type_text` its name, `tap` the result | +| Volume, lock, Siri | `press_button` | +| How hard the phone works | `phone_performance` (ask twice; the first call starts measuring) | + +## The passcode + +If the phone is locked, ask the user to unlock it. Unlock it yourself only when the user asks you to and gives you the passcode in this conversation: + +1. `press_button` lock to wake the screen if it is dark, then `gesture` home (swipe up) to show the keypad, and `screenshot`. +2. `type_text` the passcode (if nothing appears, `tap` the keypad digits instead), then `screenshot` to check it opened. +3. Use the passcode only to unlock. Never write it into files, notes, logs or other apps, and don't repeat it back. +4. Never guess a passcode, and stop after one failed attempt: wrong passcodes lock the iPhone for longer and longer and can erase it. + +## Care + +- Don't buy anything, send messages, post, delete data, change passwords or settings, or accept terms unless the user asked for exactly that; ask first when an action can't be undone. +- Screenshots can show private information (messages, notifications). Use only what the task needs and don't repeat the rest. +- Permission alerts (location, notifications, tracking): choose what the task needs; ask when unsure. +- When finished, say what you did and what you saw. diff --git a/standalone/Cargo.lock b/standalone/Cargo.lock index ae07316..31c185f 100644 --- a/standalone/Cargo.lock +++ b/standalone/Cargo.lock @@ -96,6 +96,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" dependencies = [ "axum-core", + "base64 0.22.1", "bytes", "form_urlencoded", "futures-util", @@ -115,8 +116,10 @@ dependencies = [ "serde_json", "serde_path_to_error", "serde_urlencoded", + "sha1", "sync_wrapper", "tokio", + "tokio-tungstenite", "tower", "tower-layer", "tower-service", @@ -259,6 +262,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "86e055fa6e3e40ad6187ba25b6855eeb635d5271f8e0f0e1e9a5826b8d75bea0" dependencies = [ "find-msvc-tools", + "jobserver", + "libc", "shlex", ] @@ -487,6 +492,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + [[package]] name = "der" version = "0.7.10" @@ -685,6 +696,24 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "fdk-aac" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7bb67e142688083cb9afb63f2424203fc98c4e7afb494bf912b60b55513b177e" +dependencies = [ + "fdk-aac-sys", +] + +[[package]] +name = "fdk-aac-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24516d2611506d5cb1833555adc75f6baf9fe2706b9c13e6fc33a6b22c51ca83" +dependencies = [ + "cc", +] + [[package]] name = "field-offset" version = "0.3.6" @@ -1443,6 +1472,7 @@ dependencies = [ "async-stream", "base64 0.22.1", "chrono", + "flate2", "futures", "indexmap", "jktcp", @@ -1612,6 +1642,16 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + [[package]] name = "js-sys" version = "0.3.107" @@ -1677,8 +1717,10 @@ version = "0.1.0" dependencies = [ "anyhow", "axum", + "base64 0.22.1", "chrono", "dirs", + "fdk-aac", "futures-util", "hex", "idevice", @@ -1690,6 +1732,7 @@ dependencies = [ "rand 0.8.8", "regex", "reqwest", + "rfd", "ring", "roxmltree", "rust-embed", @@ -1700,9 +1743,11 @@ dependencies = [ "tao", "thiserror 2.0.21", "tokio", + "tower", "tracing", "tracing-subscriber", "url", + "uuid", "webview2-com", "windows-core 0.61.2", "winresource", @@ -2038,6 +2083,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" dependencies = [ "bitflags 2.13.2", + "block2", "objc2", "objc2-core-foundation", "objc2-foundation", @@ -2800,6 +2846,27 @@ dependencies = [ "webpki-roots", ] +[[package]] +name = "rfd" +version = "0.15.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef2bee61e6cffa4635c72d7d81a84294e28f0930db0ddcb0f66d10244674ebed" +dependencies = [ + "block2", + "dispatch2", + "js-sys", + "log", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", + "raw-window-handle", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "windows-sys 0.59.0", +] + [[package]] name = "ring" version = "0.17.14" @@ -3550,6 +3617,18 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio-tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite", +] + [[package]] name = "tokio-util" version = "0.7.20" @@ -3773,6 +3852,22 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[package]] +name = "tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "sha1", + "thiserror 2.0.21", +] + [[package]] name = "typenum" version = "1.20.1" @@ -4285,6 +4380,15 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + [[package]] name = "windows-sys" version = "0.61.2" diff --git a/standalone/Cargo.toml b/standalone/Cargo.toml index cac22e1..0163ed2 100644 --- a/standalone/Cargo.toml +++ b/standalone/Cargo.toml @@ -2,7 +2,7 @@ name = "location-spoofer" version = "0.1.0" edition = "2021" -description = "Standalone desktop app that simulates an iPhone's GPS location over USB" +description = "iDevBench: standalone desktop app for working with an iPhone over USB" license-file = "../LICENSE" authors = ["YK3D"] publish = false @@ -20,7 +20,7 @@ store = [] anyhow = "1" thiserror = "2" tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time", "net", "fs", "process", "signal"] } -axum = { version = "0.8", features = ["multipart", "json", "query"] } +axum = { version = "0.8", features = ["multipart", "json", "query", "ws"] } serde = { version = "1", features = ["derive"] } serde_json = "1" reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "json", "stream"] } @@ -54,15 +54,29 @@ idevice = { version = "=0.1.68", default-features = false, features = [ "tss", "amfi", "pair", + "display_stream", + "sysmontap", + "device_info", + "diagnostics_relay", ] } +uuid = "1" +base64 = "0.22" +tower = { version = "0.5", features = ["util"] } tao = { version = "0.34", optional = true } wry = { version = "0.53", optional = true } png = { version = "0.17", optional = true } +# AAC-ELD decoder for the iPhone's sound while mirroring. Left out of MinGW builds, whose +# headers clash with FDK's (the release is built with MSVC); those builds mirror without sound. +[target.'cfg(not(all(windows, target_env = "gnu")))'.dependencies] +fdk-aac = "0.8" + # Windows: WebView2 permission handling for the window (the same versions wry uses). [target.'cfg(windows)'.dependencies] webview2-com = { version = "0.38", optional = true } windows-core = { version = "0.61", optional = true } +# The folder picker in Settings › Mirroring (Windows' own dialog, opened from the app). +rfd = { version = "0.15", default-features = false } [target.'cfg(windows)'.build-dependencies] winresource = "0.1" @@ -78,5 +92,5 @@ strip = true panic = "unwind" [package.metadata.winres] -ProductName = "Location Spoofer" -FileDescription = "Location Spoofer (standalone)" +ProductName = "iDevBench" +FileDescription = "iDevBench" diff --git a/standalone/build.rs b/standalone/build.rs index 3cfbdc2..c7bdce1 100644 --- a/standalone/build.rs +++ b/standalone/build.rs @@ -6,8 +6,8 @@ fn main() { { let mut res = winresource::WindowsResource::new(); res.set_icon("../assets/icon/icon.ico"); - res.set("ProductName", "Location Spoofer"); - res.set("FileDescription", "Location Spoofer"); + res.set("ProductName", "iDevBench"); + res.set("FileDescription", "iDevBench"); res.set("CompanyName", "YK3D"); res.set("LegalCopyright", "Copyright (c) 2026 YK3D. All rights reserved. See LICENSE."); if let Err(e) = res.compile() { diff --git a/standalone/packaging/msix/AppxManifest.xml b/standalone/packaging/msix/AppxManifest.xml index f8935f0..2e49d3a 100644 --- a/standalone/packaging/msix/AppxManifest.xml +++ b/standalone/packaging/msix/AppxManifest.xml @@ -17,10 +17,10 @@ ProcessorArchitecture="x64" /> - GPS Route Simulator + iDevBench TODO Publisher name Assets\StoreLogo.png - Simulate GPS routes on your own iPhone over USB for testing location-based apps. + Test apps on your own iPhone over USB: simulate GPS locations and routes. @@ -33,7 +33,7 @@ - String { } IdeviceError::PairingDialogResponsePending => "Tap Trust on the iPhone, enter the passcode, then try again.".into(), IdeviceError::UserDeniedPairing => "The iPhone refused to trust this computer. Unplug, plug back in and tap Trust.".into(), - IdeviceError::PasswordProtected => "Unlock the iPhone and try again.".into(), + IdeviceError::PasswordProtected | IdeviceError::DeviceLocked => "The iPhone is locked. Unlock it and try again.".into(), IdeviceError::DeveloperModeNotEnabled => { "Developer Mode is off. Use 'Reveal Developer Mode', then turn it on in Settings › Privacy & Security.".into() } @@ -63,18 +63,40 @@ async fn usbmux() -> Result { addr().connect(1).await.map_err(|e| friendly(&e)) } -async fn find_device(udid: Option<&str>) -> Result<(UsbmuxdProvider, String), String> { +pub const WIFI_HELP: &str = "This iPhone can't be reached over Wi-Fi. Plug it in once, press Device tools › Allow Wi-Fi \ + connection, then keep it unlocked and on the same network as this computer."; + +fn is_usb(c: &Connection) -> bool { + matches!(c, Connection::Usb) +} + +fn conn_label(c: &Connection) -> &'static str { + match c { + Connection::Usb => "USB", + Connection::Network(_) => "Wi-Fi", + Connection::Unknown(_) => "Other", + } +} + +/// The phone to talk to, over the chosen connection: `Auto` takes the cable when the phone is +/// plugged in, else Wi-Fi. usbmuxd lists a phone that is both plugged in and on Wi-Fi twice. +pub(crate) async fn find_device(udid: Option<&str>, via: super::Via) -> Result<(UsbmuxdProvider, String), String> { + use super::Via; let mut mux = usbmux().await?; let devices = mux.get_devices().await.map_err(|e| friendly(&e))?; - let dev = match udid { - Some(u) if !u.is_empty() => devices.into_iter().find(|d| d.udid == u), - _ => devices - .iter() - .find(|d| matches!(d.connection_type, Connection::Usb)) - .cloned() - .or_else(|| devices.into_iter().next()), - } - .ok_or("No iPhone found. Plug it in with a cable, unlock it and tap Trust.")?; + let wanted = |d: &&idevice::usbmuxd::UsbmuxdDevice| { + udid.is_none_or(|u| u.is_empty() || d.udid == u) + && match via { + Via::Auto => true, + Via::Usb => is_usb(&d.connection_type), + Via::Network => matches!(d.connection_type, Connection::Network(_)), + } + }; + let dev = devices.iter().filter(wanted).find(|d| is_usb(&d.connection_type)).or_else(|| devices.iter().find(wanted)).cloned(); + let dev = dev.ok_or(match via { + super::Via::Network => WIFI_HELP, + _ => "No iPhone found. Plug it in with a cable, unlock it and tap Trust.", + })?; let conn = match &dev.connection_type { Connection::Usb => "USB".to_string(), Connection::Network(ip) => format!("Wi-Fi ({ip})"), @@ -85,12 +107,25 @@ async fn find_device(udid: Option<&str>) -> Result<(UsbmuxdProvider, String), St pub async fn list_devices() -> Result, String> { let mut mux = usbmux().await?; - let devices = mux.get_devices().await.map_err(|e| friendly(&e))?; + let mut devices = mux.get_devices().await.map_err(|e| friendly(&e))?; + // one entry per phone (the cable first), naming every way it can be reached + devices.sort_by_key(|d| !is_usb(&d.connection_type)); let mut out = Vec::new(); - for d in devices { + let mut seen = std::collections::HashSet::new(); + for d in devices.iter() { + if !seen.insert(d.udid.clone()) { + continue; + } + let mut conns: Vec<&str> = Vec::new(); + for o in devices.iter().filter(|o| o.udid == d.udid) { + let l = conn_label(&o.connection_type); + if !conns.contains(&l) { + conns.push(l); + } + } let provider = d.to_provider(addr(), LABEL); let mut entry = serde_json::json!({"udid": d.udid, "name": "", "ios_version": "", - "connection": if matches!(d.connection_type, Connection::Usb) { "USB" } else { "Network" }}); + "connection": conns.join(" + "), "connections": conns}); match LockdownClient::connect(&provider).await { Ok(mut ld) => { if let Ok(v) = ld.get_value(Some("ProductVersion"), None).await { @@ -108,14 +143,14 @@ pub async fn list_devices() -> Result, String> { } /// Pair if this computer has no pairing record for the phone yet (shows "Trust This Computer?"). -async fn ensure_paired(provider: &UsbmuxdProvider) -> Result<(), String> { +pub(crate) async fn ensure_paired(provider: &UsbmuxdProvider) -> Result<(), String> { if provider.get_pairing_file().await.is_ok() { return Ok(()); } let mut ld = LockdownClient::connect(provider).await.map_err(|e| friendly(&e))?; let buid = usbmux().await?.get_buid().await.map_err(|e| friendly(&e))?; let host_id = random_uuid(); - let pf = ld.pair(host_id, buid, Some("Location Spoofer")).await.map_err(|e| friendly(&e))?; + let pf = ld.pair(host_id, buid, Some("iDevBench")).await.map_err(|e| friendly(&e))?; let bytes = pf.serialize().map_err(|e| friendly(&e))?; usbmux().await?.save_pair_record(&provider.udid, bytes).await.map_err(|e| friendly(&e)) } @@ -133,7 +168,7 @@ fn random_uuid() -> String { ) } -fn major(v: &str) -> u32 { +pub(crate) fn major(v: &str) -> u32 { v.split('.').next().and_then(|x| x.parse().ok()).unwrap_or(0) } @@ -158,18 +193,13 @@ async fn download(path: &str) -> Result, String> { } /// Mount the Developer Disk Image if it is not mounted yet. Returns a note for the user. -async fn ensure_ddi(provider: &UsbmuxdProvider, version: &str, chip_id: Option) -> Result, String> { +pub(crate) async fn ensure_ddi(provider: &UsbmuxdProvider, version: &str, chip_id: Option) -> Result, String> { let mut mounter = ImageMounter::connect(provider).await.map_err(|e| friendly(&e))?; let personalized = major(version) >= 17; let kind = if personalized { "Personalized" } else { "Developer" }; if mounter.lookup_image(kind).await.map(|s| !s.is_empty()).unwrap_or(false) { return Ok(None); } - if major(version) >= 27 { - return Err("iOS 27+ installs the developer image as a cryptex, which this version cannot do yet. \ - Mount it once with Xcode or pymobiledevice3, then connect again." - .into()); - } if personalized { let image = download("PersonalizedImages/Xcode_iOS_DDI_Personalized/Image.dmg").await?; let manifest = download("PersonalizedImages/Xcode_iOS_DDI_Personalized/BuildManifest.plist").await?; @@ -178,7 +208,14 @@ async fn ensure_ddi(provider: &UsbmuxdProvider, version: &str, chip_id: Option= 27 { " If this keeps failing, mount it once with Xcode or the browser edition." } else { "" }; + format!("Could not mount the Developer Disk Image: {}.{hint}", friendly(&e)) + })?; } else { let mut parts: Vec<&str> = version.split('.').collect(); parts.truncate(2); @@ -191,9 +228,9 @@ async fn ensure_ddi(provider: &UsbmuxdProvider, version: &str, chip_id: Option) -> Result { + pub async fn connect(&mut self, udid: Option, via: super::Via) -> Result { self.disconnect().await; - let (provider, connection) = find_device(udid.as_deref()).await?; + let (provider, connection) = find_device(udid.as_deref(), via).await?; let real_udid = provider.udid.clone(); ensure_paired(&provider).await?; let pairing = provider.get_pairing_file().await.map_err(|e| friendly(&e))?; @@ -210,6 +247,7 @@ impl IdeviceDriver { match ensure_ddi(&provider, &version, chip).await { Ok(Some(n)) => notes.push(n), Ok(None) => {} + Err(e) if e.contains("is locked") => notes.push(e), Err(e) => notes.push(format!("{e} If setting a location fails, check Developer Mode and the internet connection.")), } @@ -391,8 +429,26 @@ async fn session_legacy(provider: UsbmuxdProvider, mut rx: mpsc::Receiver, } } +/// Turns on the phone's "Show this iPhone when on Wi-Fi" setting (Wi-Fi sync), over the cable, so +/// it can be connected over Wi-Fi from then on. +pub async fn enable_wifi(udid: Option) -> Result { + let (provider, _) = find_device(udid.as_deref(), super::Via::Usb) + .await + .map_err(|e| format!("Plug the iPhone in with a cable for this step. ({e})"))?; + ensure_paired(&provider).await?; + let pairing = provider.get_pairing_file().await.map_err(|e| friendly(&e))?; + let mut ld = LockdownClient::connect(&provider).await.map_err(|e| friendly(&e))?; + ld.start_session(&pairing).await.map_err(|e| friendly(&e))?; + ld.set_value("EnableWifiConnections", true.into(), Some("com.apple.mobile.wireless_lockdown")) + .await + .map_err(|e| friendly(&e))?; + Ok("Wi-Fi connections are on for this iPhone. Choose Wi-Fi in Device tools › Connect over, keep the phone \ + unlocked on the same network, and connect." + .into()) +} + pub async fn reveal_developer_mode(udid: Option) -> Result { - let (provider, _) = find_device(udid.as_deref()).await?; + let (provider, _) = find_device(udid.as_deref(), super::Via::Auto).await?; ensure_paired(&provider).await?; let mut amfi = AmfiClient::connect(&provider).await.map_err(|e| friendly(&e))?; amfi.reveal_developer_mode_option_in_ui().await.map_err(|e| friendly(&e))?; diff --git a/standalone/src/device/mirror.rs b/standalone/src/device/mirror.rs new file mode 100644 index 0000000..a6a65af --- /dev/null +++ b/standalone/src/device/mirror.rs @@ -0,0 +1,213 @@ +//! More than one iPhone at a time: extra phones ("mirrors") follow the main one. +//! +//! The player only ever talks to the main phone (through `DeviceManager`). Every position it sends +//! is also handed to each mirror, which sends it from its own task: a slow or lost mirror never +//! holds up playback on the main phone. A mirror that is behind skips straight to the newest +//! position, and a mirror that stops answering is marked as lost (the others keep going) until it +//! is removed. Same behaviour as the browser version's `mirrors.py`. + +use super::{idev::IdeviceDriver, mock::MockDriver, DeviceInfo}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; +use tokio::sync::watch; + +const SEND_TIMEOUT: Duration = Duration::from_secs(20); + +/// The connection a mirror owns: a real iPhone or a simulated one. +pub enum Backend { + Idevice(IdeviceDriver), + Mock(MockDriver), +} + +impl Backend { + async fn set(&mut self, lat: f64, lon: f64) -> Result<(), String> { + match self { + Self::Idevice(d) => d.set_location(lat, lon).await, + Self::Mock(d) => d.set_location(lat, lon), + } + } + async fn clear(&mut self) -> Result<(), String> { + match self { + Self::Idevice(d) => d.clear_location().await, + Self::Mock(d) => d.clear_location(), + } + } + async fn disconnect(&mut self) { + match self { + Self::Idevice(d) => d.disconnect().await, + Self::Mock(d) => d.info = None, + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum Cmd { + Idle, + Set(f64, f64), + Clear, + Close { clear: bool }, +} + +/// What the mirror's task reports back. +#[derive(Default)] +pub struct Shared { + pub error: Option, + pub sent: usize, + /// the last position this phone accepted (None after a clear) + pub location: Option<(f64, f64)>, + pub history: usize, + done_seq: u64, + /// test hooks: a delay before each send, and every send failing + pub delay_ms: u64, + pub fail: bool, +} + +pub struct Mirror { + pub info: DeviceInfo, + tx: watch::Sender<(u64, Cmd)>, + seq: u64, + pub shared: Arc>, + task: Option>, +} + +impl Mirror { + pub fn start(info: DeviceInfo, backend: Backend) -> Self { + let (tx, rx) = watch::channel((0, Cmd::Idle)); + let shared = Arc::new(Mutex::new(Shared::default())); + let task = tokio::spawn(run(backend, rx, shared.clone())); + Self { info, tx, seq: 0, shared, task: Some(task) } + } + + pub fn lost(&self) -> bool { + self.shared.lock().unwrap().error.is_some() + } + + fn push(&mut self, cmd: Cmd) { + self.seq += 1; + self.tx.send_replace((self.seq, cmd)); // replaces a position the task has not sent yet + } + + pub fn push_set(&mut self, lat: f64, lon: f64) { + if !self.lost() { + self.push(Cmd::Set(lat, lon)); + } + } + + pub fn push_clear(&mut self) { + if !self.lost() { + self.push(Cmd::Clear); + } + } + + /// Waits until the newest position has been sent (or the phone is lost). + pub async fn settle(&self, max: Duration) { + let end = tokio::time::Instant::now() + max; + loop { + { + let s = self.shared.lock().unwrap(); + if s.error.is_some() || s.done_seq >= self.seq { + return; + } + } + if tokio::time::Instant::now() > end { + return; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + } + + /// Stops following; with `clear`, the phone goes back to its real location first. + pub async fn close(mut self, clear: bool) { + if clear { + self.settle(Duration::from_secs(2)).await; + } + self.push(Cmd::Close { clear }); + if let Some(t) = self.task.take() { + let _ = tokio::time::timeout(Duration::from_secs(15), t).await; + } + } + + pub fn to_json(&self) -> serde_json::Value { + let mut v = serde_json::to_value(&self.info).unwrap_or_default(); + let err = self.shared.lock().unwrap().error.clone(); + v["state"] = serde_json::json!(if err.is_some() { "lost" } else { "ok" }); + v["error"] = serde_json::json!(err); + v + } +} + +async fn run(mut backend: Backend, mut rx: watch::Receiver<(u64, Cmd)>, shared: Arc>) { + loop { + if rx.changed().await.is_err() { + break; // the mirror was dropped without closing + } + let (seq, cmd) = *rx.borrow_and_update(); + let (delay, fail) = { + let s = shared.lock().unwrap(); + (s.delay_ms, s.fail) + }; + let res = match cmd { + Cmd::Idle => Ok(()), + Cmd::Close { clear } => { + if clear && shared.lock().unwrap().error.is_none() { + let _ = tokio::time::timeout(Duration::from_secs(10), backend.clear()).await; + shared.lock().unwrap().location = None; + } + break; + } + Cmd::Set(..) | Cmd::Clear => { + if delay > 0 { + tokio::time::sleep(Duration::from_millis(delay)).await; + } + let send = async { + if fail { + return Err("Lost the connection to the iPhone".to_string()); + } + match cmd { + Cmd::Set(lat, lon) => backend.set(lat, lon).await, + _ => backend.clear().await, + } + }; + match tokio::time::timeout(SEND_TIMEOUT, send).await { + Ok(r) => r, + Err(_) => Err("The iPhone stopped answering.".to_string()), + } + } + }; + let lost = { + let mut s = shared.lock().unwrap(); + s.done_seq = seq; + match res { + Ok(()) => { + match cmd { + Cmd::Set(lat, lon) => { + s.location = Some((lat, lon)); + s.history += 1; + s.sent += 1; + } + Cmd::Clear => { + s.location = None; + s.sent += 1; + } + _ => {} + } + false + } + Err(e) => { + s.error = Some(e); + true + } + } + }; + if lost { + // wait until the mirror is removed, then let go of the connection + while rx.changed().await.is_ok() { + if matches!(rx.borrow_and_update().1, Cmd::Close { .. }) { + break; + } + } + break; + } + } + backend.disconnect().await; +} diff --git a/standalone/src/device/mock.rs b/standalone/src/device/mock.rs index 4fcd23e..675958c 100644 --- a/standalone/src/device/mock.rs +++ b/standalone/src/device/mock.rs @@ -2,8 +2,10 @@ use super::DeviceInfo; -/// The pretend phone always reports this iOS version (the current major release). +/// The pretend phones always report this iOS version (the current major release). pub const SIMULATED_IOS: &str = "27"; +/// Two pretend phones, so several iPhones at once can be tried without hardware. +pub const SIMULATED_DEVICES: [(&str, &str); 2] = [("SIMULATED-0001", "Simulated iPhone"), ("SIMULATED-0002", "Simulated iPhone 2")]; #[derive(Default)] pub struct MockDriver { @@ -14,12 +16,22 @@ pub struct MockDriver { impl MockDriver { pub fn list_devices(&self) -> Vec { - vec![serde_json::json!({"udid": "SIMULATED-0001", "name": "Simulated iPhone", "ios_version": SIMULATED_IOS, "connection": "Simulated"})] + SIMULATED_DEVICES + .iter() + .map(|(udid, name)| { + serde_json::json!({"udid": udid, "name": name, "ios_version": SIMULATED_IOS, + "connection": "Simulated", "connections": ["Simulated"]}) + }) + .collect() } - pub fn connect(&mut self) -> DeviceInfo { + pub fn connect(&mut self, udid: Option<&str>) -> Result { + let (udid, name) = match udid.filter(|u| !u.is_empty()) { + None => SIMULATED_DEVICES[0], + Some(u) => *SIMULATED_DEVICES.iter().find(|(id, _)| *id == u).ok_or("No such simulated iPhone")?, + }; let info = DeviceInfo { - udid: "SIMULATED-0001".into(), - name: "Simulated iPhone".into(), + udid: udid.into(), + name: name.into(), ios_version: SIMULATED_IOS.into(), product_type: "Simulated".into(), connection: "Simulated".into(), @@ -27,7 +39,7 @@ impl MockDriver { notes: vec![], }; self.info = Some(info.clone()); - info + Ok(info) } pub fn set_location(&mut self, lat: f64, lon: f64) -> Result<(), String> { if self.info.is_none() { diff --git a/standalone/src/device/mod.rs b/standalone/src/device/mod.rs index 4028cc4..c689175 100644 --- a/standalone/src/device/mod.rs +++ b/standalone/src/device/mod.rs @@ -1,6 +1,7 @@ //! Ways this app can move a device's location: a real iPhone (idevice) or a simulator. pub mod idev; +pub mod mirror; pub mod mock; use serde::Serialize; @@ -40,16 +41,65 @@ impl DriverKind { } } -/// Owns both drivers; one is active. +/// How to reach the phone: `Auto` takes the cable when it is plugged in, else Wi-Fi. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum Via { + #[default] + Auto, + Usb, + Network, +} + +impl Via { + pub fn parse(s: Option<&str>) -> Option { + match s.unwrap_or("auto") { + "auto" | "" => Some(Self::Auto), + "usb" => Some(Self::Usb), + "network" => Some(Self::Network), + _ => None, + } + } +} + +/// Up to this many extra iPhones can follow the main one. +pub const MAX_MIRRORS: usize = 8; + +/// Owns both drivers (one is active, the main phone) and the extra phones that follow it. pub struct DeviceManager { pub kind: DriverKind, pub idev: idev::IdeviceDriver, pub mock: mock::MockDriver, + pub mirrors: Vec, + /// the last position sent to the main phone, so a new mirror can catch up at once + last: Option<(f64, f64)>, } impl Default for DeviceManager { fn default() -> Self { - Self { kind: DriverKind::Idevice, idev: idev::IdeviceDriver::default(), mock: mock::MockDriver::default() } + Self { + kind: DriverKind::Idevice, + idev: idev::IdeviceDriver::default(), + mock: mock::MockDriver::default(), + mirrors: Vec::new(), + last: None, + } + } +} + +/// Connects another phone of the same kind as the main one, for use as a mirror. Runs without the +/// device lock held, so a slow iOS 17 handshake doesn't stall playback on the main phone. +pub async fn connect_mirror(kind: DriverKind, udid: String, via: Via) -> Result<(DeviceInfo, mirror::Backend), String> { + match kind { + DriverKind::Idevice => { + let mut d = idev::IdeviceDriver::default(); + let info = d.connect(Some(udid), via).await?; + Ok((info, mirror::Backend::Idevice(d))) + } + DriverKind::Mock => { + let mut d = mock::MockDriver::default(); + let info = d.connect(Some(&udid))?; + Ok((info, mirror::Backend::Mock(d))) + } } } @@ -69,17 +119,28 @@ impl DeviceManager { DriverKind::Mock => Ok(self.mock.list_devices()), } } - pub async fn connect(&mut self, kind: DriverKind, udid: Option) -> Result { + pub async fn connect(&mut self, kind: DriverKind, udid: Option, via: Via) -> Result { if kind != self.kind { self.disconnect().await; self.kind = kind; } - match kind { - DriverKind::Idevice => self.idev.connect(udid).await, - DriverKind::Mock => Ok(self.mock.connect()), + if let Some(u) = udid.as_deref() { + self.remove_mirror(u, false).await; // it becomes the main phone instead } + let info = match kind { + DriverKind::Idevice => self.idev.connect(udid, via).await?, + DriverKind::Mock => self.mock.connect(udid.as_deref())?, + }; + self.remove_mirror(&info.udid, false).await; + Ok(info) } + /// Disconnects the main phone and every mirror. pub async fn disconnect(&mut self) { + self.drop_mirrors().await; + self.disconnect_main().await; + } + async fn disconnect_main(&mut self) { + self.last = None; match self.kind { DriverKind::Idevice => self.idev.disconnect().await, DriverKind::Mock => self.mock.info = None, @@ -89,12 +150,78 @@ impl DeviceManager { match self.kind { DriverKind::Idevice => self.idev.set_location(lat, lon).await, DriverKind::Mock => self.mock.set_location(lat, lon), + }?; + self.last = Some((lat, lon)); + for m in &mut self.mirrors { + m.push_set(lat, lon); } + Ok(()) } pub async fn clear_location(&mut self) -> Result<(), String> { match self.kind { DriverKind::Idevice => self.idev.clear_location().await, DriverKind::Mock => self.mock.clear_location(), + }?; + self.last = None; + for m in &mut self.mirrors { + m.push_clear(); + } + Ok(()) + } + + /// Why `udid` can't become a mirror right now, if it can't. + pub fn mirror_refusal(&self, udid: &str) -> Option { + let main = match self.info() { + Some(i) => i, + None => return Some("Connect the main iPhone first.".into()), + }; + if udid == main.udid { + return Some("That is the main iPhone already.".into()); + } + if self.mirrors.iter().any(|m| m.info.udid == udid) { + return Some("That iPhone already follows the main one.".into()); + } + if self.mirrors.len() >= MAX_MIRRORS { + return Some(format!("Up to {MAX_MIRRORS} extra iPhones can follow the main one.")); + } + None + } + /// Adds a phone connected by `connect_mirror`; it moves to the main phone's position at once. + pub async fn attach_mirror(&mut self, info: DeviceInfo, backend: mirror::Backend) -> Result { + if let Some(why) = self.mirror_refusal(&info.udid) { + mirror::Mirror::start(info, backend).close(false).await; + return Err(if why.starts_with("That is") { "That iPhone is connected already.".into() } else { why }); + } + let mut m = mirror::Mirror::start(info, backend); + if let Some((lat, lon)) = self.last { + m.push_set(lat, lon); + } + let v = m.to_json(); + self.mirrors.push(m); + Ok(v) + } + /// Stops a mirror; with `clear`, that phone goes back to its real location first. + pub async fn remove_mirror(&mut self, udid: &str, clear: bool) -> bool { + match self.mirrors.iter().position(|m| m.info.udid == udid) { + Some(i) => { + self.mirrors.remove(i).close(clear).await; + true + } + None => false, + } + } + pub async fn drop_mirrors(&mut self) { + for m in std::mem::take(&mut self.mirrors) { + m.close(false).await; + } + } + pub fn mirrors_json(&self) -> Vec { + self.mirrors.iter().map(|m| m.to_json()).collect() + } + pub async fn enable_wifi(&mut self, udid: Option) -> Result { + match self.kind { + DriverKind::Idevice => idev::enable_wifi(udid.or_else(|| self.idev.info.as_ref().map(|i| i.udid.clone()))).await, + DriverKind::Mock => Ok("Simulator: nothing to do.".into()), } } pub async fn reveal_developer_mode(&mut self) -> Result { @@ -106,8 +233,10 @@ impl DeviceManager { pub async fn mount_developer_image(&mut self) -> Result { match self.kind { DriverKind::Idevice => { - let udid = self.idev.info.as_ref().map(|i| i.udid.clone()).ok_or("Connect first")?; - let info = self.idev.connect(Some(udid)).await?; + let cur = self.idev.info.as_ref().ok_or("Connect first")?; + let via = if cur.connection.starts_with("Wi-Fi") { Via::Network } else { Via::Auto }; + let udid = cur.udid.clone(); + let info = self.idev.connect(Some(udid), via).await?; Ok(if info.notes.is_empty() { "Developer Disk Image is mounted.".into() } else { info.notes.join(" ") }) } DriverKind::Mock => Ok("Simulator: nothing to mount.".into()), diff --git a/standalone/src/gpx.rs b/standalone/src/gpx.rs index 11c7989..f9830d8 100644 --- a/standalone/src/gpx.rs +++ b/standalone/src/gpx.rs @@ -141,7 +141,7 @@ pub fn write_gpx(samples: &[TimelinePoint], name: &str, waypoints: &[(f64, f64, let start = Utc.timestamp_opt(start.timestamp(), 0).single().unwrap_or(start); let mut s = String::new(); s.push_str("\n"); - s.push_str("\n"); + s.push_str("\n"); s.push_str(&format!(" {}\n", esc(name), fmt_time(start))); for (lat, lon, n) in waypoints { s.push_str(&format!(" {}\n", esc(n))); diff --git a/standalone/src/main.rs b/standalone/src/main.rs index 59089a7..c2208ed 100644 --- a/standalone/src/main.rs +++ b/standalone/src/main.rs @@ -1,4 +1,4 @@ -//! Location Spoofer — standalone desktop app. +//! iDevBench (formerly Location Spoofer) — standalone desktop app. //! Copyright (c) 2026 YK3D. All rights reserved. Licensed under the Location Spoofer License (LICENSE). //! //! A local HTTP server (axum) serves the UI and its JSON API on 127.0.0.1; a native window @@ -12,6 +12,7 @@ mod feature_tests; mod geo; mod gmaps_links; mod gpx; +mod screen; mod offline; mod player; mod profile; @@ -56,6 +57,46 @@ fn parse_args() -> Args { a } +/// `--mcp`: for AI apps that start MCP servers as programs (Claude Desktop and others). Passes +/// each message from stdin to the running app's /mcp and prints the answer; the app must be open. +fn mcp_bridge(port: Option) { + use std::io::{BufRead, Write}; + let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().expect("tokio runtime"); + let client = reqwest::Client::builder().no_proxy().build().expect("http client"); + // The standalone app's port, then the browser edition's. + let urls: Vec = match port { + Some(p) => vec![format!("http://127.0.0.1:{p}/mcp")], + None => vec![format!("http://127.0.0.1:{DEFAULT_PORT}/mcp"), "http://127.0.0.1:8765/mcp".into()], + }; + let mut out = std::io::stdout(); + for line in std::io::stdin().lock().lines() { + let Ok(line) = line else { break }; + if line.trim().is_empty() { + continue; + } + let answer = rt.block_on(async { + for url in &urls { + let sent = client.post(url).header("Content-Type", "application/json").header("Accept", "application/json, text/event-stream"); + if let Ok(r) = sent.body(line.clone()).send().await { + return Some(r.text().await.unwrap_or_default()); + } + } + None + }); + let text = match answer { + Some(t) => t, + None => match serde_json::from_str::(&line).ok().and_then(|m| m.get("id").cloned()) { + Some(id) => serde_json::json!({"jsonrpc": "2.0", "id": id, "error": {"code": -32000, "message": "iDevBench is not running. Open it, then try again."}}).to_string(), + None => String::new(), + }, + }; + if !text.trim().is_empty() { + let _ = writeln!(out, "{}", text.trim()); + let _ = out.flush(); + } + } +} + fn wait_for_pid_exit(pid: u32) { // The old process frees the port and its file lock when it exits; give it up to 30 s. for _ in 0..150 { @@ -73,6 +114,9 @@ fn main() { println!("{}", updater::current_version()); return; } + if args.raw.iter().any(|a| a == "--mcp") { + return mcp_bridge(args.raw.iter().any(|a| a == "--port").then_some(args.port)); + } tracing_subscriber::fmt() .with_env_filter(tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info,idevice=warn".into())) .init(); @@ -132,20 +176,20 @@ fn main() { None => start_server(&rt, bind(0).expect("bind"), upd), }, }; - tracing::info!("Location Spoofer running at {url}"); + tracing::info!("iDevBench running at {url}"); #[cfg(feature = "gui")] if !args.no_window { let restart = server_task.clone(); let title = match args.feature_test { - Some(pr) => format!("Location Spoofer · feature test #{pr}"), - None => "Location Spoofer".to_string(), + Some(pr) => format!("iDevBench · feature test #{pr}"), + None => "iDevBench".to_string(), }; gui::run(url, title, restart, args.raw.clone(), rt); return; } let _ = open::that(&url); - println!("Location Spoofer is running at {url} — press Ctrl+C to quit."); + println!("iDevBench is running at {url} — press Ctrl+C to quit."); rt.block_on(async { match server_task { Some(app) => { @@ -189,7 +233,7 @@ fn start_server(rt: &tokio::runtime::Runtime, listener: tokio::net::TcpListener, (format!("http://{addr}/"), Some(app)) } -/// The version of the Location Spoofer already listening at `url`, if it is one. +/// The version of iDevBench already listening at `url`, if it is one. async fn running_version(url: &str) -> Option { let r = reqwest::Client::new().get(format!("{url}api/status")).timeout(std::time::Duration::from_secs(2)).send().await.ok()?; let v: serde_json::Value = r.json().await.ok()?; @@ -230,7 +274,7 @@ async fn self_test() -> i32 { checks.push(("sea network", routing::sea_route((49.49, 0.10), (50.9, 1.8)).map(|r| r.len() > 2).unwrap_or(false))); checks.push(("Google link parser", gmaps_links::parse("https://www.google.com/maps/@40.7,-74.0,15z").is_ok())); let ok = checks.iter().all(|c| c.1); - println!("Location Spoofer (standalone) {} self-test", updater::current_version()); + println!("iDevBench (standalone) {} self-test", updater::current_version()); for (n, v) in &checks { println!(" {} {n}", if *v { "OK " } else { "FAIL" }); } diff --git a/standalone/src/offline.rs b/standalone/src/offline.rs index 3184412..b56c7da 100644 --- a/standalone/src/offline.rs +++ b/standalone/src/offline.rs @@ -187,7 +187,7 @@ pub struct DownloadIn { impl Offline { pub fn new(data_dir: &Path) -> Arc { let http = reqwest::Client::builder() - .user_agent(format!("LocationSpoofer/{} (+https://github.com/YK3D/iPhone-location-spoofer)", crate::updater::current_version())) + .user_agent(format!("iDevBench/{} (+https://github.com/YK3D/iPhone-location-spoofer)", crate::updater::current_version())) .timeout(std::time::Duration::from_secs(20)) .build() .expect("http client"); diff --git a/standalone/src/player.rs b/standalone/src/player.rs index 79d4124..eb0e21f 100644 --- a/standalone/src/player.rs +++ b/standalone/src/player.rs @@ -465,7 +465,7 @@ mod tests { async fn player() -> (Arc, Devices) { let devices: Devices = Arc::new(AsyncMutex::new(DeviceManager::default())); - devices.lock().await.connect(DriverKind::Mock, None).await.unwrap(); + devices.lock().await.connect(DriverKind::Mock, None, crate::device::Via::Auto).await.unwrap(); (Arc::new(Player::new(devices.clone())), devices) } diff --git a/standalone/src/routing.rs b/standalone/src/routing.rs index 929bb2d..5e202c3 100644 --- a/standalone/src/routing.rs +++ b/standalone/src/routing.rs @@ -9,7 +9,7 @@ use std::collections::{BinaryHeap, HashMap, HashSet}; use std::sync::{Mutex, OnceLock}; use std::time::{Duration, Instant}; -pub const USER_AGENT: &str = "LocationSpoofer-Standalone/0.1 (desktop app)"; +pub const USER_AGENT: &str = "iDevBench-Standalone/0.1 (desktop app)"; const OFFNET_MIN_M: f64 = 25.0; const OFFNET_CAP_KMH: f64 = 15.0; const RESTRICTED_CAP_KMH: f64 = 20.0; diff --git a/standalone/src/screen/hevc.rs b/standalone/src/screen/hevc.rs new file mode 100644 index 0000000..0576708 --- /dev/null +++ b/standalone/src/screen/hevc.rs @@ -0,0 +1,553 @@ +//! RTP/HEVC (RFC 7798) to whole frames for the browser's video decoder. +//! +//! The phone sends its screen as HEVC over plain RTP. This module reassembles the NAL units, +//! groups them into access units (one frame each), keeps the parameter sets (VPS/SPS/PPS) and +//! turns them into what WebCodecs needs: a codec string, an `hvcC` record (ISO/IEC 14496-15 +//! §8.3.3.1) and frames as 4-byte length-prefixed NAL units. + +pub const NAL_VPS: u8 = 32; +pub const NAL_SPS: u8 = 33; +pub const NAL_PPS: u8 = 34; +const NAL_AUD: u8 = 35; +const NAL_AP: u8 = 48; +const NAL_FU: u8 = 49; + +/// Apple's display service ends every coded slice with this 14-byte footer. It is not part of +/// the HEVC bitstream, so it is removed before decoding (a no-op when a stream has none). +pub const APPLE_SLICE_FOOTER: [u8; 14] = [0x04, 0xf0, 0x0a, 0xc0, 0x00, 0x00, 0x03, 0x00, 0x00, 0x04, 0xec, 0x0a, 0xb0, 0x03]; + +pub fn nal_type(nal: &[u8]) -> u8 { + nal.first().map(|b| (b >> 1) & 0x3f).unwrap_or(0xff) +} + +/// IRAP pictures (BLA, IDR, CRA) can be decoded on their own. +fn is_key(t: u8) -> bool { + (16..=21).contains(&t) +} + +fn strip_footer(mut nal: Vec) -> Vec { + if nal_type(&nal) <= 31 && nal.ends_with(&APPLE_SLICE_FOOTER) { + nal.truncate(nal.len() - APPLE_SLICE_FOOTER.len()); + } + nal +} + +/// One decoded-ready frame. +#[derive(Debug, Clone, PartialEq)] +pub struct AccessUnit { + pub rtp_ts: u32, + pub key: bool, + /// Coded slices and SEI, without parameter sets or access-unit delimiters. + pub nals: Vec>, +} + +impl AccessUnit { + /// The frame as WebCodecs expects it in `hvcC` mode: each NAL with a 4-byte big-endian length. + pub fn length_prefixed(&self) -> Vec { + let mut out = Vec::with_capacity(self.nals.iter().map(|n| n.len() + 4).sum()); + for n in &self.nals { + out.extend_from_slice(&(n.len() as u32).to_be_bytes()); + out.extend_from_slice(n); + } + out + } +} + +#[derive(Debug, Default)] +pub struct Depacketizer { + expect_seq: Option, + fu: Option>, + cur: Vec>, + cur_ts: Option, + cur_key: bool, + /// A packet was lost: frames are held back until the next keyframe. + pub waiting_for_key: bool, + pub vps: Option>, + pub sps: Option>, + pub pps: Option>, + /// Set when a parameter set changed; the caller sends a new decoder config and clears it. + pub config_changed: bool, + pub lost_packets: u64, +} + +impl Depacketizer { + pub fn new() -> Self { + Self { waiting_for_key: true, ..Default::default() } + } + + /// Feed one RTP packet. Returns the frames it completed (usually zero or one). + pub fn push(&mut self, seq: u16, ts: u32, marker: bool, payload: &[u8]) -> Vec { + let mut done = Vec::new(); + if let Some(expect) = self.expect_seq { + let gap = seq.wrapping_sub(expect); + if gap >= 0x8000 { + return done; // a late duplicate of a packet already handled + } + if gap != 0 { + self.lost_packets += gap as u64; + self.drop_partial(); + self.waiting_for_key = true; + } + } + self.expect_seq = Some(seq.wrapping_add(1)); + + if self.cur_ts.is_some_and(|t| t != ts) { + self.finish(&mut done); + } + self.cur_ts = Some(ts); + + if payload.len() < 2 { + return done; + } + match nal_type(payload) { + NAL_AP => { + let mut i = 2; + while i + 2 <= payload.len() { + let n = u16::from_be_bytes([payload[i], payload[i + 1]]) as usize; + i += 2; + if n == 0 || i + n > payload.len() { + break; + } + self.add_nal(payload[i..i + n].to_vec()); + i += n; + } + } + NAL_FU => { + if payload.len() < 3 { + return done; + } + let h = payload[2]; + let (start, end, t) = (h & 0x80 != 0, h & 0x40 != 0, h & 0x3f); + if start { + let mut nal = vec![(payload[0] & 0x81) | (t << 1), payload[1]]; + nal.extend_from_slice(&payload[3..]); + self.fu = Some(nal); + } else if let Some(buf) = self.fu.as_mut() { + buf.extend_from_slice(&payload[3..]); + } + if end { + if let Some(nal) = self.fu.take() { + self.add_nal(strip_footer(nal)); + } + } + } + _ => self.add_nal(strip_footer(payload.to_vec())), + } + if marker { + self.finish(&mut done); + } + done + } + + fn add_nal(&mut self, nal: Vec) { + let t = nal_type(&nal); + let slot = match t { + NAL_VPS => Some(&mut self.vps), + NAL_SPS => Some(&mut self.sps), + NAL_PPS => Some(&mut self.pps), + _ => None, + }; + if let Some(slot) = slot { + if slot.as_deref() != Some(&nal[..]) { + *slot = Some(nal); + self.config_changed = true; + } + return; + } + if t == NAL_AUD { + return; + } + if is_key(t) { + self.cur_key = true; + } + self.cur.push(nal); + } + + fn drop_partial(&mut self) { + self.fu = None; + self.cur.clear(); + self.cur_key = false; + self.cur_ts = None; + } + + fn finish(&mut self, done: &mut Vec) { + let nals = std::mem::take(&mut self.cur); + let key = std::mem::replace(&mut self.cur_key, false); + let ts = self.cur_ts.take().unwrap_or(0); + self.fu = None; + if nals.is_empty() { + return; + } + if self.waiting_for_key { + if !key || self.sps.is_none() || self.pps.is_none() || self.vps.is_none() { + return; + } + self.waiting_for_key = false; + } + done.push(AccessUnit { rtp_ts: ts, key, nals }); + } + + /// Codec string, `hvcC` record and picture size for the current parameter sets. + pub fn decoder_config(&self) -> Option { + let (vps, sps, pps) = (self.vps.as_ref()?, self.sps.as_ref()?, self.pps.as_ref()?); + let info = parse_sps(sps)?; + Some(DecoderConfig { codec: info.codec_string(), hvcc: hvcc(&info, vps, sps, pps), width: info.width, height: info.height }) + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct DecoderConfig { + pub codec: String, + pub hvcc: Vec, + pub width: u32, + pub height: u32, +} + +/// Remove emulation-prevention bytes (00 00 03 -> 00 00) after the 2-byte NAL header. +pub fn rbsp(nal: &[u8]) -> Vec { + let mut out = Vec::with_capacity(nal.len()); + let mut zeros = 0; + for &b in nal.iter().skip(2) { + if zeros >= 2 && b == 3 { + zeros = 0; + continue; + } + zeros = if b == 0 { zeros + 1 } else { 0 }; + out.push(b); + } + out +} + +struct Bits<'a> { + d: &'a [u8], + pos: usize, +} + +impl Bits<'_> { + fn bit(&mut self) -> Option { + let byte = *self.d.get(self.pos / 8)?; + let v = (byte >> (7 - self.pos % 8)) & 1; + self.pos += 1; + Some(v as u32) + } + fn bits(&mut self, n: usize) -> Option { + let mut v = 0u64; + for _ in 0..n { + v = (v << 1) | self.bit()? as u64; + } + Some(v) + } + fn ue(&mut self) -> Option { + let mut zeros = 0; + while self.bit()? == 0 { + zeros += 1; + if zeros > 31 { + return None; + } + } + Some(((1u64 << zeros) - 1 + self.bits(zeros)?) as u32) + } +} + +/// What the SPS says about the stream. +#[derive(Debug, Clone, PartialEq)] +pub struct SpsInfo { + /// The 12-byte general profile_tier_level (profile space/tier/idc, compatibility flags, + /// constraint flags, level), exactly as `hvcC` stores it. + pub ptl: [u8; 12], + pub max_sub_layers: u8, + pub temporal_id_nested: bool, + pub chroma_format_idc: u32, + pub bit_depth_luma: u32, + pub bit_depth_chroma: u32, + pub width: u32, + pub height: u32, +} + +pub fn parse_sps(sps: &[u8]) -> Option { + if nal_type(sps) != NAL_SPS { + return None; + } + let d = rbsp(sps); + let mut b = Bits { d: &d, pos: 0 }; + b.bits(4)?; // sps_video_parameter_set_id + let max_sub_layers_minus1 = b.bits(3)? as usize; + let nested = b.bit()? == 1; + let start = b.pos / 8; + let ptl: [u8; 12] = d.get(start..start + 12)?.try_into().ok()?; + b.pos += 96; + let mut profile_present = [false; 8]; + let mut level_present = [false; 8]; + for i in 0..max_sub_layers_minus1 { + profile_present[i] = b.bit()? == 1; + level_present[i] = b.bit()? == 1; + } + if max_sub_layers_minus1 > 0 { + for _ in max_sub_layers_minus1..8 { + b.bits(2)?; + } + } + for i in 0..max_sub_layers_minus1 { + if profile_present[i] { + b.pos += 88; + } + if level_present[i] { + b.pos += 8; + } + } + b.ue()?; // sps_seq_parameter_set_id + let chroma = b.ue()?; + if chroma == 3 { + b.bit()?; // separate_colour_plane_flag + } + let mut width = b.ue()?; + let mut height = b.ue()?; + if b.bit()? == 1 { + // Conformance window, in chroma units. + let (l, r, t, bo) = (b.ue()?, b.ue()?, b.ue()?, b.ue()?); + let (sx, sy) = match chroma { + 1 => (2, 2), + 2 => (2, 1), + _ => (1, 1), + }; + width = width.saturating_sub(sx * (l + r)); + height = height.saturating_sub(sy * (t + bo)); + } + let bit_depth_luma = b.ue()? + 8; + let bit_depth_chroma = b.ue()? + 8; + Some(SpsInfo { + ptl, + max_sub_layers: max_sub_layers_minus1 as u8 + 1, + temporal_id_nested: nested, + chroma_format_idc: chroma, + bit_depth_luma, + bit_depth_chroma, + width, + height, + }) +} + +impl SpsInfo { + /// The WebCodecs / RFC 6381 codec string (ISO/IEC 14496-15 Annex E), e.g. `hev1.1.6.L120.90`. + pub fn codec_string(&self) -> String { + let p = &self.ptl; + let space = p[0] >> 6; + let tier = if p[0] & 0x20 != 0 { 'H' } else { 'L' }; + let idc = p[0] & 0x1f; + let compat = u32::from_be_bytes([p[1], p[2], p[3], p[4]]).reverse_bits(); + let mut s = format!("hev1.{}{}.{:X}.{}{}", ["", "A", "B", "C"][space as usize], idc, compat, tier, p[11]); + let constraints = &p[5..11]; + let used = constraints.iter().rposition(|&c| c != 0).map(|i| i + 1).unwrap_or(0); + for c in &constraints[..used] { + s.push_str(&format!(".{c:X}")); + } + s + } +} + +/// HEVCDecoderConfigurationRecord (`hvcC`), the WebCodecs `description` for HEVC. +pub fn hvcc(info: &SpsInfo, vps: &[u8], sps: &[u8], pps: &[u8]) -> Vec { + let mut r = Vec::with_capacity(64 + vps.len() + sps.len() + pps.len()); + r.push(1); // configurationVersion + r.extend_from_slice(&info.ptl); + r.extend_from_slice(&[0xf0, 0x00]); // reserved + min_spatial_segmentation_idc = 0 + r.push(0xfc); // reserved + parallelismType = 0 (unknown) + r.push(0xfc | (info.chroma_format_idc as u8 & 3)); + r.push(0xf8 | ((info.bit_depth_luma.saturating_sub(8)) as u8 & 7)); + r.push(0xf8 | ((info.bit_depth_chroma.saturating_sub(8)) as u8 & 7)); + r.extend_from_slice(&[0, 0]); // avgFrameRate unknown + // constantFrameRate 0 | numTemporalLayers | temporalIdNested | lengthSizeMinusOne = 3 + r.push(((info.max_sub_layers & 7) << 3) | ((info.temporal_id_nested as u8) << 2) | 3); + r.push(3); + for (t, nal) in [(NAL_VPS, vps), (NAL_SPS, sps), (NAL_PPS, pps)] { + r.push(0x80 | t); // array_completeness = 1: parameter sets only come out of band + r.extend_from_slice(&1u16.to_be_bytes()); + r.extend_from_slice(&(nal.len() as u16).to_be_bytes()); + r.extend_from_slice(nal); + } + r +} + +#[cfg(test)] +mod tests { + use super::*; + + // A real 1170x2532 Main-profile SPS (level 6.0), built to the spec: see `sample_sps`. + fn sample_sps() -> Vec { + // Write an SPS with known values using a tiny bit writer. + let mut w = Writer::default(); + w.put(0, 4); // vps id + w.put(0, 3); // max_sub_layers_minus1 + w.put(1, 1); // temporal_id_nesting + w.put(0, 2); // profile space + w.put(0, 1); // tier + w.put(1, 5); // profile idc = Main + w.put(0x6000_0000, 32); // compatibility flags: Main and Main10 + w.put(0x90, 8); // progressive + frame_only constraint bits + w.put(0, 40); + w.put(180, 8); // level 6.0 + w.ue(0); // sps id + w.ue(1); // chroma 4:2:0 + w.ue(1184); // coded width + w.ue(2544); // coded height + w.put(1, 1); // conformance window + w.ue(0); + w.ue(7); // right: 14 luma px + w.ue(0); + w.ue(6); // bottom: 12 luma px + w.ue(0); // bit depth luma 8 + w.ue(0); // bit depth chroma 8 + w.put(1, 1); // stop bit + let mut nal = vec![NAL_SPS << 1, 1]; + // Emulation prevention, as an encoder would add it. + let mut zeros = 0; + for b in w.finish() { + if zeros >= 2 && b <= 3 { + nal.push(3); + zeros = 0; + } + zeros = if b == 0 { zeros + 1 } else { 0 }; + nal.push(b); + } + nal + } + + #[derive(Default)] + struct Writer { + bits: Vec, + } + impl Writer { + fn put(&mut self, v: u64, n: usize) { + for i in (0..n).rev() { + self.bits.push(((v >> i) & 1) as u8); + } + } + fn ue(&mut self, v: u32) { + let x = v as u64 + 1; + let len = 64 - x.leading_zeros() as usize; + self.put(0, len - 1); + self.put(x, len); + } + fn finish(mut self) -> Vec { + while self.bits.len() % 8 != 0 { + self.bits.push(0); + } + self.bits.chunks(8).map(|c| c.iter().fold(0u8, |a, &b| (a << 1) | b)).collect() + } + } + + #[test] + fn parses_sps_size_and_codec() { + let info = parse_sps(&sample_sps()).unwrap(); + assert_eq!((info.width, info.height), (1170, 2532)); + assert_eq!(info.chroma_format_idc, 1); + assert_eq!((info.bit_depth_luma, info.bit_depth_chroma), (8, 8)); + assert_eq!(info.codec_string(), "hev1.1.6.L180.90"); + } + + #[test] + fn hvcc_record_layout() { + let sps = sample_sps(); + let info = parse_sps(&sps).unwrap(); + let vps = vec![NAL_VPS << 1, 1, 0xaa]; + let pps = vec![NAL_PPS << 1, 1, 0xbb]; + let r = hvcc(&info, &vps, &sps, &pps); + assert_eq!(r[0], 1); + assert_eq!(&r[1..13], &info.ptl); + assert_eq!(r[16], 0xfd); // 4:2:0 + assert_eq!(r[21] & 3, 3); // 4-byte lengths + assert_eq!(r[22], 3); + assert_eq!(r[23], 0x80 | NAL_VPS); + assert_eq!(&r[26..28], &3u16.to_be_bytes()); + assert!(r.ends_with(&pps)); + } + + fn slice(t: u8, body: &[u8]) -> Vec { + let mut v = vec![t << 1, 1]; + v.extend_from_slice(body); + v + } + + fn params(d: &mut Depacketizer, seq: &mut u16) { + for nal in [slice(NAL_VPS, &[1]), sample_sps(), slice(NAL_PPS, &[2])] { + d.push(*seq, 1000, false, &nal); + *seq += 1; + } + } + + #[test] + fn single_nal_frames_and_footer() { + let mut d = Depacketizer::new(); + let mut seq = 10; + params(&mut d, &mut seq); + let mut idr = slice(19, &[9, 9, 9]); + idr.extend_from_slice(&APPLE_SLICE_FOOTER); + let out = d.push(seq, 1000, true, &idr); + assert_eq!(out.len(), 1); + assert!(out[0].key); + assert_eq!(out[0].nals, vec![slice(19, &[9, 9, 9])]); + assert!(d.config_changed); + let cfg = d.decoder_config().unwrap(); + assert_eq!((cfg.width, cfg.height), (1170, 2532)); + assert_eq!(out[0].length_prefixed(), [&[0, 0, 0, 5][..], &slice(19, &[9, 9, 9])].concat()); + } + + #[test] + fn fragmented_and_aggregated() { + let mut d = Depacketizer::new(); + let mut seq = 0; + params(&mut d, &mut seq); + // An aggregation packet carrying an SEI and a short IDR slice. + let sei = slice(39, &[5]); + let idr = slice(19, &[1, 2]); + let mut ap = vec![NAL_AP << 1, 1]; + for n in [&sei, &idr] { + ap.extend_from_slice(&(n.len() as u16).to_be_bytes()); + ap.extend_from_slice(n); + } + let out = d.push(seq, 2000, true, &ap); + seq += 1; + assert_eq!(out[0].nals, vec![sei.clone(), idr.clone()]); + // A TRAIL_R slice split into three fragments. + let body: Vec = (0..30).collect(); + let fu = |start: bool, end: bool, part: &[u8]| { + let mut v = vec![NAL_FU << 1, 1, (if start { 0x80 } else { 0 }) | (if end { 0x40 } else { 0 }) | 1]; + v.extend_from_slice(part); + v + }; + assert!(d.push(seq, 3000, false, &fu(true, false, &body[..10])).is_empty()); + assert!(d.push(seq + 1, 3000, false, &fu(false, false, &body[10..20])).is_empty()); + let out = d.push(seq + 2, 3000, true, &fu(false, true, &body[20..])); + assert_eq!(out.len(), 1); + assert!(!out[0].key); + assert_eq!(out[0].nals, vec![slice(1, &body)]); + } + + #[test] + fn loss_holds_frames_until_keyframe() { + let mut d = Depacketizer::new(); + let mut seq = 0; + params(&mut d, &mut seq); + assert_eq!(d.push(seq, 1, true, &slice(19, &[1])).len(), 1); + // seq + 1 is lost. + assert!(d.push(seq + 2, 2, true, &slice(1, &[1])).is_empty()); + assert!(d.waiting_for_key); + assert_eq!(d.lost_packets, 1); + assert!(d.push(seq + 3, 3, true, &slice(1, &[1])).is_empty()); + let out = d.push(seq + 4, 4, true, &slice(20, &[1])); + assert!(out[0].key && !d.waiting_for_key); + // A late duplicate is ignored. + assert!(d.push(seq + 1, 2, true, &slice(1, &[1])).is_empty()); + } + + #[test] + fn timestamp_change_closes_a_frame_without_marker() { + let mut d = Depacketizer::new(); + let mut seq = 0; + params(&mut d, &mut seq); + assert!(d.push(seq, 10, false, &slice(19, &[1])).is_empty()); + let out = d.push(seq + 1, 11, false, &slice(1, &[2])); + assert_eq!(out.len(), 1); + assert_eq!(out[0].rtp_ts, 10); + } +} diff --git a/standalone/src/screen/mod.rs b/standalone/src/screen/mod.rs new file mode 100644 index 0000000..8b4fe19 --- /dev/null +++ b/standalone/src/screen/mod.rs @@ -0,0 +1,579 @@ +//! Screen mirroring: the iPhone's screen and sound in the app, and mouse/keyboard control. +//! +//! iOS 27+ streams its display through `com.apple.coredevice.displayservice` (the service Xcode +//! uses) as HEVC over RTP, and its sound as AAC-ELD, inside the developer tunnel. Touches, +//! buttons and keys go back through the CoreDevice HID services, which only accept input while +//! a stream is running. Each session runs on its own thread with its own tunnel, like the +//! location session (the idevice futures are not `Send`). +//! +//! Clients (the Mirror tab, or other programs) read a WebSocket at `/api/screen/ws`: +//! * binary `[1][width u16][height u16][codec length u8][codec][hvcC]`: decoder setup; +//! * binary `[2][key u8][timestamp µs u64][frame as 4-byte length-prefixed NAL units]`; +//! * binary `[3][timestamp µs u64][PCM s16le, 48 kHz, stereo]`; +//! * text: the status JSON whenever it changes. +//! +//! and send input as JSON (the same body `POST /api/screen/input` takes), see [`parse_input`]. + +pub mod hevc; + +use serde::Serialize; +use serde_json::{json, Value}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; +use tokio::sync::{broadcast, mpsc, oneshot}; + +/// Hardware buttons: (name, HID usage page, usage, hold in ms). Siri needs a long press. +pub const BUTTONS: [(&str, u64, u64, u64); 6] = [ + ("home", 0x0C, 0x40, 50), + // shortcut: lock uses the side button's usage with a longer press; unconfirmed on a real iPhone, change the usage if it still does nothing. + ("lock", 0x0C, 0x30, 250), + ("volume-up", 0x0C, 0xE9, 50), + ("volume-down", 0x0C, 0xEA, 50), + ("mute", 0x0C, 0xE2, 50), + ("siri", 0x0C, 0xCF, 1000), +]; + +/// System gestures: name, start and end (fractions of the upright screen), drag time and hold in ms. +pub const GESTURES: [(&str, (f64, f64), (f64, f64), u64, u64); 5] = [ + ("home", (0.5, 0.995), (0.5, 0.55), 200, 0), + ("app_switcher", (0.5, 0.995), (0.5, 0.62), 260, 450), + ("control_centre", (0.92, 0.004), (0.92, 0.45), 260, 0), + ("notification_centre", (0.3, 0.004), (0.3, 0.6), 260, 0), + ("back", (0.004, 0.5), (0.65, 0.5), 260, 0), +]; + +#[derive(Debug, Clone, PartialEq)] +pub enum Input { + /// One finger (or two, for pinching): down, move or up. Coordinates are 0..65535 across the screen. + Touch { phase: Phase, x: u16, y: u16, second: Option<(u16, u16)> }, + Tap { x: u16, y: u16 }, + Swipe { x1: u16, y1: u16, x2: u16, y2: u16, ms: u64 }, + LongPress { x: u16, y: u16, ms: u64 }, + Gesture(&'static str), + Button(&'static str, u64, u64, u64), + /// A HID keyboard usage (page 7): down, up, or (None) pressed and released; `command` holds ⌘. + Key { usage: u64, down: Option, command: bool }, + Text(String), + /// Ask the phone for a fresh full frame (a new viewer, or a decoder error). + KeyFrame, + /// Restart the stream (a frozen picture). + Refresh, +} + +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Phase { + Down, + Move, + Up, +} + +fn coord(v: &Value, k: &str) -> Result { + let f = v.get(k).and_then(Value::as_f64).ok_or(format!("'{k}' must be a number from 0 to 1"))?; + if !(0.0..=1.0).contains(&f) { + return Err(format!("'{k}' must be from 0 to 1 (a fraction of the screen)")); + } + Ok((f * 65535.0).round() as u16) +} + +/// Parse one input message. Coordinates are fractions of the screen (0..1, top left is 0,0). +/// +/// `{"t":"touch","phase":"down|move|up","x":0.5,"y":0.5}` (plus `"x2","y2"` for a second finger), +/// `{"t":"tap","x":..,"y":..}`, `{"t":"swipe","x1":..,"y1":..,"x2":..,"y2":..,"ms":300}`, +/// `{"t":"long_press","x":..,"y":..,"ms":800}`, `{"t":"gesture","name":"app_switcher"}`, `{"t":"button","name":"home"}`, +/// `{"t":"key","usage":40,"down":true}` (no `down`: press and release; `"command":true` holds ⌘), +/// `{"t":"text","text":"hello"}`, `{"t":"keyframe"}`, `{"t":"refresh"}`. +pub fn parse_input(v: &Value) -> Result { + let t = v.get("t").and_then(Value::as_str).unwrap_or(""); + Ok(match t { + "touch" => Input::Touch { + phase: match v.get("phase").and_then(Value::as_str) { + Some("down") => Phase::Down, + Some("move") => Phase::Move, + Some("up") => Phase::Up, + _ => return Err("'phase' must be down, move or up".into()), + }, + x: coord(v, "x")?, + y: coord(v, "y")?, + second: if v.get("x2").is_some() || v.get("y2").is_some() { Some((coord(v, "x2")?, coord(v, "y2")?)) } else { None }, + }, + "tap" => Input::Tap { x: coord(v, "x")?, y: coord(v, "y")? }, + "swipe" => Input::Swipe { + x1: coord(v, "x1")?, + y1: coord(v, "y1")?, + x2: coord(v, "x2")?, + y2: coord(v, "y2")?, + ms: v.get("ms").and_then(Value::as_u64).unwrap_or(300).clamp(50, 5000), + }, + "long_press" => Input::LongPress { x: coord(v, "x")?, y: coord(v, "y")?, ms: v.get("ms").and_then(Value::as_u64).unwrap_or(800).clamp(100, 5000) }, + "gesture" => { + let name = v.get("name").and_then(Value::as_str).unwrap_or(""); + let g = GESTURES.iter().find(|g| g.0 == name).ok_or(format!( + "Unknown gesture '{name}'. Use one of: home, app_switcher, control_centre, notification_centre, back" + ))?; + Input::Gesture(g.0) + } + "button" => { + let name = v.get("name").and_then(Value::as_str).unwrap_or(""); + let &(n, page, usage, hold) = BUTTONS + .iter() + .find(|b| b.0 == name) + .ok_or(format!("Unknown button '{name}'. Use one of: home, lock, volume-up, volume-down, mute, siri"))?; + Input::Button(n, page, usage, hold) + } + "key" => Input::Key { + usage: v.get("usage").and_then(Value::as_u64).filter(|u| (4..=0xE7).contains(u)).ok_or("'usage' must be a HID keyboard usage (4–231)")?, + down: match v.get("down") { + None => None, + Some(d) => Some(d.as_bool().ok_or("'down' must be true or false")?), + }, + command: v.get("command").and_then(Value::as_bool).unwrap_or(false), + }, + "text" => { + let text = v.get("text").and_then(Value::as_str).ok_or("'text' must be a string")?; + if text.chars().count() > 2000 { + return Err("Type at most 2000 characters at a time".into()); + } + Input::Text(text.into()) + } + "keyframe" => Input::KeyFrame, + "refresh" => Input::Refresh, + _ => return Err("'t' must be touch, tap, swipe, long_press, gesture, button, key, text, keyframe or refresh".into()), + }) +} + +/// A finger moving: when moves pile up, only the newest needs sending. +pub fn is_move(i: &Input) -> bool { + matches!(i, Input::Touch { phase: Phase::Move, .. }) +} + +/// HID keyboard usage and whether Shift is needed, for one character (US layout). +pub fn char_usage(c: char) -> Option<(u64, bool)> { + const SHIFTED: &str = "!@#$%^&*()"; + Some(match c { + 'a'..='z' => (0x04 + (c as u64 - 'a' as u64), false), + 'A'..='Z' => (0x04 + (c as u64 - 'A' as u64), true), + '1'..='9' => (0x1E + (c as u64 - '1' as u64), false), + '0' => (0x27, false), + '\n' => (0x28, false), + '\t' => (0x2B, false), + ' ' => (0x2C, false), + _ if SHIFTED.contains(c) => (0x1E + SHIFTED.find(c)? as u64, true), + _ => { + const KEYS: [(char, char, u64); 11] = [ + ('-', '_', 0x2D), ('=', '+', 0x2E), ('[', '{', 0x2F), (']', '}', 0x30), ('\\', '|', 0x31), + (';', ':', 0x33), ('\'', '"', 0x34), ('`', '~', 0x35), (',', '<', 0x36), ('.', '>', 0x37), ('/', '?', 0x38), + ]; + let &(plain, _, u) = KEYS.iter().find(|k| k.0 == c || k.1 == c)?; + (u, c != plain) + } + }) +} + +#[derive(Debug, Clone, Serialize, PartialEq)] +pub struct Status { + /// off, starting, on or error + pub state: &'static str, + pub error: Option, + pub simulated: bool, + pub width: Option, + pub height: Option, + /// Whether the phone's sound is being sent. + pub audio: bool, + /// Why there is no sound, or no touch control, when there isn't. + pub note: Option, + /// Clockwise degrees (0, 90, 180, 270) that turn the picture upright: the phone is turned. + pub rotation: u16, + /// The iPhone's name and iOS version, once known. + pub device_name: Option, + pub ios: Option, +} + +impl Default for Status { + fn default() -> Self { + Self { state: "off", error: None, simulated: false, width: None, height: None, audio: false, note: None, rotation: 0, device_name: None, ios: None } + } +} + +#[derive(Clone, Debug)] +pub enum Out { + Bin(Arc>), + Text(Arc), +} + +enum Cmd { + Input(Input, oneshot::Sender>), + Screenshot(oneshot::Sender, String>>), + /// Start measuring the phone's CPU, memory, GPU and battery (on the first request for them). + StartPerf, +} + +/// The phone's performance figures, all null until measured: `cpu` (% of all cores), `cores`, +/// `memory_used`/`memory_total` (bytes), `gpu` (%), `fps` (the phone's own frame rate), +/// `battery_temp` (°C), `battery` (%), `charging`. +pub fn empty_perf() -> serde_json::Map { + ["cpu", "cores", "memory_used", "memory_total", "gpu", "fps", "battery_temp", "battery", "charging"] + .into_iter() + .map(|k| (k.to_string(), Value::Null)) + .collect() +} + +#[derive(Default)] +struct Inner { + status: Status, + cmd: Option>, + /// The last decoder setup message, for viewers that join mid-stream. + config: Option>>, + /// Which session the fields belong to, so a stopped session can't overwrite a new one. + session: u64, + /// Simulator only: the inputs received, for tests and the API's dry runs. + pub sim_inputs: Vec, + perf: serde_json::Map, + perf_started: bool, +} + +pub struct Screen { + inner: Mutex, + out: broadcast::Sender, +} + +impl Default for Screen { + fn default() -> Self { + Self { inner: Mutex::default(), out: broadcast::channel(512).0 } + } +} + +impl Screen { + pub fn status(&self) -> Status { + self.inner.lock().unwrap().status.clone() + } + + pub fn subscribe(&self) -> (broadcast::Receiver, Option>>, Status) { + let rx = self.out.subscribe(); + let g = self.inner.lock().unwrap(); + (rx, g.config.clone(), g.status.clone()) + } + + fn set(&self, session: u64, f: impl FnOnce(&mut Status)) { + let mut g = self.inner.lock().unwrap(); + if g.session != session { + return; + } + f(&mut g.status); + let text = serde_json::to_string(&json!({"type": "status", "status": g.status})).unwrap(); + let _ = self.out.send(Out::Text(Arc::new(text))); + } + + fn send_config(&self, session: u64, msg: Vec) { + let msg = Arc::new(msg); + let mut g = self.inner.lock().unwrap(); + if g.session == session { + g.config = Some(msg.clone()); + let _ = self.out.send(Out::Bin(msg)); + } + } + + fn send(&self, msg: Vec) { + let _ = self.out.send(Out::Bin(Arc::new(msg))); + } + + /// Start mirroring (stopping any earlier session) and wait until the stream runs. + pub async fn start(self: &Arc, simulated: bool, udid: Option, audio: bool) -> Result { + let (tx, rx) = mpsc::unbounded_channel(); + let session = { + let mut g = self.inner.lock().unwrap(); + g.session += 1; + g.cmd = Some(tx); + g.config = None; + g.sim_inputs.clear(); + (g.perf, g.perf_started) = (empty_perf(), false); + g.status = Status { state: "starting", simulated, ..Default::default() }; + g.session + }; + self.set(session, |_| {}); + if simulated { + tokio::spawn(simulator(self.clone(), session, rx)); + self.set(session, |s| { + *s = Status { state: "on", simulated: true, width: Some(1170), height: Some(2532), ..Default::default() }; + (s.device_name, s.ios) = (Some("Simulated iPhone".into()), Some("27.0".into())); + s.note = Some("Simulator: there is no real screen; input is accepted and ignored.".into()); + }); + return Ok(self.status()); + } + let (ready_tx, ready_rx) = oneshot::channel(); + let me = self.clone(); + std::thread::Builder::new() + .name("iphone-mirror".into()) + .spawn(move || { + let rt = tokio::runtime::Builder::new_current_thread().enable_all().build(); + match rt { + // A LocalSet lets the session run its (non-Send) input on a task of its own. + Ok(rt) => tokio::task::LocalSet::new().block_on(&rt, session::run(me, session, udid, audio, rx, ready_tx)), + Err(e) => me.ended(session, Some(format!("Could not start the mirroring thread: {e}"))), + } + }) + .map_err(|e| e.to_string())?; + match tokio::time::timeout(Duration::from_secs(60), ready_rx).await { + Ok(Ok(Ok(()))) => Ok(self.status()), + Ok(Ok(Err(e))) => Err(e), + _ => { + self.stop(); + Err("Timed out starting screen mirroring. Unlock the iPhone and try again.".into()) + } + } + } + + pub fn stop(&self) { + let session = { + let mut g = self.inner.lock().unwrap(); + g.cmd = None; // the session sees the closed channel and ends + g.config = None; + g.session + }; + self.set(session, |s| *s = Status::default()); + } + + fn ended(&self, session: u64, error: Option) { + self.set(session, |s| { + *s = Status { state: if error.is_some() { "error" } else { "off" }, error, ..Default::default() }; + }); + let mut g = self.inner.lock().unwrap(); + if g.session == session { + g.cmd = None; + g.config = None; + } + } + + fn command(&self) -> Result, String> { + self.inner.lock().unwrap().cmd.clone().ok_or_else(|| "Screen mirroring is not running. Start it first.".into()) + } + + pub async fn input(&self, input: Input) -> Result<(), String> { + let (tx, rx) = oneshot::channel(); + self.command()?.send(Cmd::Input(input, tx)).map_err(|_| "Screen mirroring stopped.".to_string())?; + tokio::time::timeout(Duration::from_secs(30), rx) + .await + .map_err(|_| "The iPhone did not answer.".to_string())? + .map_err(|_| "Screen mirroring stopped.".to_string())? + } + + pub async fn screenshot(&self) -> Result, String> { + let (tx, rx) = oneshot::channel(); + self.command()?.send(Cmd::Screenshot(tx)).map_err(|_| "Screen mirroring stopped.".to_string())?; + tokio::time::timeout(Duration::from_secs(30), rx) + .await + .map_err(|_| "The iPhone did not answer.".to_string())? + .map_err(|_| "Screen mirroring stopped.".to_string())? + } + + /// The phone's latest performance figures; the first call starts measuring them. + pub fn perf(&self) -> Result { + let mut g = self.inner.lock().unwrap(); + if g.status.state != "on" { + return Err("Screen mirroring is not running. Start it first.".into()); + } + if g.perf.is_empty() { + g.perf = empty_perf(); + } + if !g.perf_started && !g.status.simulated { + if let Some(c) = &g.cmd { + g.perf_started = c.send(Cmd::StartPerf).is_ok(); + } + } + Ok(Value::Object(g.perf.clone())) + } + + fn update_perf(&self, session: u64, f: impl FnOnce(&mut serde_json::Map)) { + let mut g = self.inner.lock().unwrap(); + if g.session == session { + f(&mut g.perf); + } + } + + /// A restarted stream measures again from scratch. + fn reset_perf(&self, session: u64) { + let mut g = self.inner.lock().unwrap(); + if g.session == session { + (g.perf, g.perf_started) = (empty_perf(), false); + } + } + + #[cfg(test)] + pub fn sim_inputs(&self) -> Vec { + self.inner.lock().unwrap().sim_inputs.clone() + } +} + +async fn simulator(m: Arc, session: u64, mut rx: mpsc::UnboundedReceiver) { + while let Some(cmd) = rx.recv().await { + match cmd { + Cmd::Input(i, r) => { + let mut g = m.inner.lock().unwrap(); + if g.session == session && g.sim_inputs.len() < 1000 { + g.sim_inputs.push(i); + } + let _ = r.send(Ok(())); + } + Cmd::Screenshot(r) => { + let _ = r.send(Err("The simulator has no screen to capture.".into())); + } + Cmd::StartPerf => {} + } + } + m.ended(session, None); +} + +/// Decoder setup message for viewers. +pub fn config_message(c: &hevc::DecoderConfig) -> Vec { + let mut m = vec![1]; + m.extend_from_slice(&(c.width.min(65535) as u16).to_be_bytes()); + m.extend_from_slice(&(c.height.min(65535) as u16).to_be_bytes()); + m.push(c.codec.len() as u8); + m.extend_from_slice(c.codec.as_bytes()); + m.extend_from_slice(&c.hvcc); + m +} + +pub fn frame_message(au: &hevc::AccessUnit, ts_us: u64) -> Vec { + let mut m = vec![2, au.key as u8]; + m.extend_from_slice(&ts_us.to_be_bytes()); + m.extend_from_slice(&au.length_prefixed()); + m +} + +pub fn audio_message(pcm: &[i16], ts_us: u64) -> Vec { + let mut m = Vec::with_capacity(9 + pcm.len() * 2); + m.push(3); + m.extend_from_slice(&ts_us.to_be_bytes()); + for s in pcm { + m.extend_from_slice(&s.to_le_bytes()); + } + m +} + +/// AAC-ELD (48 kHz stereo, 480-sample frames, as the phone sends it) to PCM. +pub mod audio { + /// AudioSpecificConfig: AAC-ELD, 48 kHz, stereo, frameLengthFlag = 1 (480 samples). + #[cfg(not(all(windows, target_env = "gnu")))] + pub const ASC: [u8; 4] = [0xF8, 0xE6, 0x50, 0x00]; + + #[cfg(not(all(windows, target_env = "gnu")))] + pub struct Decoder { + dec: fdk_aac::dec::Decoder, + pcm: Vec, + } + + #[cfg(not(all(windows, target_env = "gnu")))] + impl Decoder { + pub fn new() -> Option { + let mut dec = fdk_aac::dec::Decoder::new(fdk_aac::dec::Transport::Raw); + dec.config_raw(&ASC).ok()?; + Some(Self { dec, pcm: vec![0; 4096] }) + } + /// Decode one access unit (one RTP payload) to interleaved stereo samples. + pub fn decode(&mut self, au: &[u8]) -> Option> { + self.dec.fill(au).ok()?; + self.dec.decode_frame(&mut self.pcm).ok()?; + Some(self.pcm[..self.dec.decoded_frame_size()].to_vec()) + } + } + + #[cfg(all(windows, target_env = "gnu"))] + pub struct Decoder; + + #[cfg(all(windows, target_env = "gnu"))] + impl Decoder { + pub fn new() -> Option { + None + } + pub fn decode(&mut self, _au: &[u8]) -> Option> { + None + } + } +} + +mod session; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_inputs() { + assert_eq!( + parse_input(&json!({"t": "touch", "phase": "down", "x": 0.5, "y": 1.0})).unwrap(), + Input::Touch { phase: Phase::Down, x: 32768, y: 65535, second: None } + ); + assert_eq!( + parse_input(&json!({"t": "touch", "phase": "move", "x": 0, "y": 0, "x2": 1, "y2": 0.5})).unwrap(), + Input::Touch { phase: Phase::Move, x: 0, y: 0, second: Some((65535, 32768)) } + ); + assert_eq!(parse_input(&json!({"t": "gesture", "name": "back"})).unwrap(), Input::Gesture("back")); + assert_eq!(parse_input(&json!({"t": "long_press", "x": 0, "y": 0})).unwrap(), Input::LongPress { x: 0, y: 0, ms: 800 }); + assert_eq!( + parse_input(&json!({"t": "key", "usage": 4, "command": true})).unwrap(), + Input::Key { usage: 4, down: None, command: true } + ); + assert_eq!(parse_input(&json!({"t": "button", "name": "siri"})).unwrap(), Input::Button("siri", 0x0C, 0xCF, 1000)); + assert_eq!(parse_input(&json!({"t": "key", "usage": 40, "down": false})).unwrap(), Input::Key { usage: 40, down: Some(false), command: false }); + assert_eq!(parse_input(&json!({"t": "refresh"})).unwrap(), Input::Refresh); + assert!(matches!(parse_input(&json!({"t": "swipe", "x1": 0, "y1": 0, "x2": 1, "y2": 1})).unwrap(), Input::Swipe { ms: 300, .. })); + for bad in [ + json!({"t": "tap", "x": 1.5, "y": 0}), + json!({"t": "tap", "x": "0.2", "y": 0}), + json!({"t": "touch", "phase": "hover", "x": 0, "y": 0}), + json!({"t": "button", "name": "power"}), + json!({"t": "key", "usage": 1, "down": true}), + json!({"t": "key", "usage": 4, "down": "yes"}), + json!({"t": "touch", "phase": "down", "x": 0, "y": 0, "x2": 0.5}), + json!({"t": "gesture", "name": "spin"}), + json!({"t": "fly"}), + ] { + assert!(parse_input(&bad).is_err(), "{bad}"); + } + } + + #[test] + fn characters_map_to_us_keys() { + assert_eq!(char_usage('a'), Some((0x04, false))); + assert_eq!(char_usage('Z'), Some((0x1D, true))); + assert_eq!(char_usage('0'), Some((0x27, false))); + assert_eq!(char_usage('('), Some((0x26, true))); + assert_eq!(char_usage('?'), Some((0x38, true))); + assert_eq!(char_usage('/'), Some((0x38, false))); + assert_eq!(char_usage('é'), None); + } + + #[test] + fn messages_have_the_documented_layout() { + let c = hevc::DecoderConfig { codec: "hev1.1.6.L180.90".into(), hvcc: vec![1, 2], width: 1170, height: 2532 }; + let m = config_message(&c); + assert_eq!(&m[..6], &[1, 0x04, 0x92, 0x09, 0xE4, 16]); + assert_eq!(&m[6..22], b"hev1.1.6.L180.90"); + assert_eq!(&m[22..], &[1, 2]); + let au = hevc::AccessUnit { rtp_ts: 0, key: true, nals: vec![vec![0x26, 1, 7]] }; + assert_eq!(frame_message(&au, 5), [vec![2, 1], 5u64.to_be_bytes().to_vec(), vec![0, 0, 0, 3, 0x26, 1, 7]].concat()); + assert_eq!(audio_message(&[1, -1], 2), [vec![3], 2u64.to_be_bytes().to_vec(), vec![1, 0, 0xff, 0xff]].concat()); + } + + #[tokio::test] + async fn simulated_session_takes_input_and_stops() { + let m = Arc::new(Screen::default()); + assert!(m.input(Input::KeyFrame).await.is_err()); + let s = m.start(true, None, true).await.unwrap(); + assert_eq!((s.state, s.simulated, s.width), ("on", true, Some(1170))); + m.input(Input::Tap { x: 1, y: 2 }).await.unwrap(); + assert_eq!(m.sim_inputs(), vec![Input::Tap { x: 1, y: 2 }]); + assert!(m.screenshot().await.is_err()); + m.stop(); + assert_eq!(m.status().state, "off"); + assert!(m.input(Input::KeyFrame).await.is_err()); + } + + #[cfg(not(all(windows, target_env = "gnu")))] + #[test] + fn audio_decoder_accepts_the_phone_setup_and_survives_garbage() { + let mut d = audio::Decoder::new().expect("FDK accepts the 480-sample AAC-ELD setup"); + assert!(d.decode(&[0xff; 7]).is_none()); + assert!(d.decode(&[]).is_none()); + } +} diff --git a/standalone/src/screen/session.rs b/standalone/src/screen/session.rs new file mode 100644 index 0000000..215f81d --- /dev/null +++ b/standalone/src/screen/session.rs @@ -0,0 +1,654 @@ +//! One mirroring session with a real iPhone: tunnel, display stream, HID input, RTCP feedback. +//! Protocol details follow the idevice crate's `displayservice` support (MIT) and +//! pymobiledevice3's notes on what the phone expects. + +use super::{audio, config_message, frame_message, audio_message, hevc, Cmd, Input, Phase, Screen}; +use crate::device::idev; +use idevice::{ + core_device::{ + build_keyframe_request, build_liveness, build_screen_audio_offer, build_screen_video_offer, build_start_audio_parameters, + build_start_video_parameters, is_rtcp, ButtonState, CallInfoBlob, CoreDeviceServiceClient, DisplayServiceClient, IndigoHidClient, + ReportBlock, RtpPacket, TouchscreenContact, UniversalHidServiceClient, TOUCHSCREEN_STATE_CONTACT, TOUCHSCREEN_STATE_RELEASE, + }, + core_device_proxy::CoreDeviceProxy, + diagnostics_relay::DiagnosticsRelayClient, + dvt::{ + device_info::DeviceInfoClient, + message::AuxValue, + remote_server::RemoteServerClient, + screenshot::ScreenshotClient, + sysmontap::{SysmontapClient, SysmontapConfig}, + }, + lockdown::LockdownClient, + provider::{IdeviceProvider, RsdProvider, UsbmuxdProvider}, + rsd::RsdHandshake, + IdeviceError, IdeviceService, ReadWrite, RsdService, +}; +use serde_json::json; +use std::sync::Arc; +use std::time::{Duration, Instant}; +use tokio::sync::{mpsc, oneshot}; + +/// What Device Hub announces as its own features; the phone's own mask breaks negotiation. +const CLIENT_FEATURES: u64 = 140; +/// Error code CoreDevice returns when Camera or a recording app holds the camera or microphone. +const MEDIA_IN_USE: &str = "9022"; + +type Hid = UniversalHidServiceClient>; +type Indigo = IndigoHidClient>; +type Rs = RemoteServerClient>; + +/// Unanswered keyframe requests (while the picture is broken) before the stream is restarted; +/// iOS 27's encoder sometimes stops answering them, and a fresh stream always opens with one. +const MAX_KEY_REQUESTS: u32 = 3; +/// No datagram at all (the phone's RTCP reports come every second) means the stream died. +const SILENCE: Duration = Duration::from_secs(6); +/// Automatic restarts in a row (less than a minute apart) before giving up. +const MAX_RESTARTS: u32 = 3; + +/// How a stream ended without an error. +enum Ended { + Stopped, + /// Start it again: `auto` when the stream froze, false when the user asked (Refresh). + Restart { auto: bool }, +} + +pub(super) async fn run( + m: Arc, + session: u64, + udid: Option, + audio_on: bool, + rx: mpsc::UnboundedReceiver, + ready: oneshot::Sender>, +) { + let mut ready = Some(ready); + let mut rx = rx; + let (mut restarts, mut last_restart) = (0, Instant::now()); + let result = loop { + match stream(&m, session, udid.clone(), audio_on, &mut rx, &mut ready).await { + Ok(Ended::Restart { auto }) => { + if auto { + restarts = if last_restart.elapsed() < Duration::from_secs(60) { restarts + 1 } else { 1 }; + last_restart = Instant::now(); + if restarts > MAX_RESTARTS { + break Err("The iPhone stopped sending its screen. Unlock it, then start mirroring again.".to_string()); + } + } + m.reset_perf(session); + m.set(session, |s| s.note = Some("Reconnecting to the iPhone's screen…".into())); + } + Ok(Ended::Stopped) => break Ok(()), + Err(e) => break Err(e), + } + }; + if let Some(r) = ready.take() { + let _ = r.send(Err(result.clone().err().unwrap_or_else(|| "Screen mirroring stopped.".into()))); + } + m.ended(session, result.err()); +} + +/// The `streamConfig` values of a start answer: the phone's RTP port and both SSRCs. +fn stream_config(answer: &plist::Value) -> (u16, u32, u32) { + let cfg = answer.as_dictionary().and_then(|d| d.get("connection")).and_then(|c| c.as_dictionary()).and_then(|c| c.get("streamConfig")); + let num = |k: &str| cfg.and_then(|c| c.as_dictionary()).and_then(|c| c.get(k)).and_then(|v| v.as_unsigned_integer()).unwrap_or(0); + // Named from the phone's side: LocalSSRC is the phone's, RemoteSSRC is ours. + (num("SourcePort") as u16, num("RemoteSSRC") as u32, num("LocalSSRC") as u32) +} + +fn start_error(what: &str, e: idevice::IdeviceError) -> String { + let text = format!("{e:?}"); + if text.contains(MEDIA_IN_USE) { + return "The iPhone won't share its screen while an app uses the camera or microphone (for example Camera or Voice Memos). Close that app and try again.".into(); + } + format!("Could not start the {what} stream: {}", idev::friendly(&e)) +} + +/// Extended highest RTP sequence number (RFC 3550): wrap count in the high 16 bits. +#[derive(Default)] +struct SeqCounter(Option); + +impl SeqCounter { + fn add(&mut self, seq: u16) { + self.0 = Some(match self.0 { + None => seq as u32, + // Only newer packets move it forward; a late one from before a wrap is ignored. + Some(cur) => match seq.wrapping_sub(cur as u16) as i16 { + d if d > 0 => cur.wrapping_add(d as u32), + _ => cur, + }, + }); + } +} + +async fn stream( + m: &Arc, + session: u64, + udid: Option, + audio_on: bool, + rx: &mut mpsc::UnboundedReceiver, + ready: &mut Option>>, +) -> Result { + let fr = |e: idevice::IdeviceError| idev::friendly(&e); + let (provider, _) = idev::find_device(udid.as_deref(), crate::device::Via::Auto).await?; + idev::ensure_paired(&provider).await?; + let pairing = provider.get_pairing_file().await.map_err(fr)?; + let mut ld = LockdownClient::connect(&provider).await.map_err(fr)?; + ld.start_session(&pairing).await.map_err(fr)?; + let version = ld.get_value(Some("ProductVersion"), None).await.ok().and_then(|v| v.as_string().map(String::from)).unwrap_or_default(); + let chip = ld.get_value(Some("UniqueChipID"), None).await.ok().and_then(|v| v.as_unsigned_integer()); + let name = ld.get_value(Some("DeviceName"), None).await.ok().and_then(|v| v.as_string().map(String::from)); + drop(ld); + let ios = Some(version.clone()).filter(|v| !v.is_empty()); + m.set(session, |s| (s.device_name, s.ios) = (name, ios)); + if idev::major(&version) < 27 { + return Err(format!("Screen mirroring needs iOS 27 or newer. This iPhone has iOS {version}.")); + } + // A failed mount is reported only if the display service then turns out to be missing. + let ddi = idev::ensure_ddi(&provider, &version, chip).await.err(); + + let proxy = CoreDeviceProxy::connect(&provider).await.map_err(fr)?; + let rsd_port = proxy.tunnel_info().server_rsd_port; + let mut adapter = proxy.create_software_tunnel().map_err(fr)?.to_async_handle(); + let rsd = adapter.connect(rsd_port).await.map_err(|e| format!("Could not open the developer tunnel: {e}"))?; + let mut hs = RsdHandshake::new(rsd).await.map_err(fr)?; + let mut display = DisplayServiceClient::connect_rsd(&mut adapter, &mut hs).await.map_err(|e| match &ddi { + Some(d) => format!("The iPhone's screen service is not available ({}). {d}", fr(e)), + None => format!("The iPhone's screen service is not available: {}. Check that Developer Mode is on.", fr(e)), + })?; + + let audio_udp = adapter.bind_udp(0).await.map_err(|e| e.to_string())?; + let video_udp = adapter.bind_udp(0).await.map_err(|e| e.to_string())?; + let (host, peer) = (adapter.host_ip().to_string(), adapter.peer_ip().to_string()); + // Values from a captured Device Hub offer that the phone accepts. + let call_info = CallInfoBlob { + call_id: 0, + client_version: 1, + device_type: "Mac17,7".into(), + framework_version: "2205.3.1".into(), + os_version: "25F71".into(), + device_name: None, + audio_device_uid: None, + }; + let call_id = || uuid::Uuid::from_bytes(rand::random()).hyphenated().to_string().to_uppercase(); + let session_id = uuid::Uuid::from_bytes(rand::random()); + // The audio stream goes first: it sets up the screen-sharing session the video joins. + let offer = build_screen_audio_offer(&call_id(), &call_info).map_err(fr)?; + let a_params = build_start_audio_parameters(&host, audio_udp.local_port(), &peer, 50000, offer, CLIENT_FEATURES, session_id); + let (a_port, a_ours, a_phone) = stream_config(&display.start_media_stream(a_params).await.map_err(|e| start_error("sound", e))?); + let our_ssrc: u32 = rand::random(); + let offer = build_screen_video_offer(&call_id(), &call_info, our_ssrc).map_err(fr)?; + // shortcut: display 1 is the built-in screen; foldables with two panels would need the active one. + let v_params = build_start_video_parameters(&host, video_udp.local_port(), &peer, 50001, offer, CLIENT_FEATURES, 1, session_id); + let (v_port, v_ours, v_phone) = stream_config(&display.start_media_stream(v_params).await.map_err(|e| start_error("screen", e))?); + let v_ours = if v_ours != 0 { v_ours } else { our_ssrc }; + + // Touch and buttons are refused until the phone has matched them to the new stream. + tokio::time::sleep(Duration::from_millis(300)).await; + let hid: Option = UniversalHidServiceClient::connect_rsd(&mut adapter, &mut hs).await.ok(); + let indigo: Option = IndigoHidClient::connect_rsd(&mut adapter, &mut hs).await.ok(); + // Which way the screen is turned, asked on its own task so a slow answer never holds up the + // picture or input; without it the picture stays upright and the Rotate button helps. + let info = match hs.services.get("com.apple.coredevice.deviceinfo").map(|s| s.port) { + Some(port) => match adapter.connect_to_service_port(port).await { + Ok(stream) => CoreDeviceServiceClient::new(stream).await.ok(), + Err(_) => None, + }, + None => None, + }; + let mut tasks = Vec::new(); + if let Some(info) = info { + tasks.push(tokio::task::spawn_local(follow_rotation(m.clone(), session, info))); + } + let mut decoder = if audio_on { audio::Decoder::new() } else { None }; + let mut note = Vec::new(); + if hid.is_none() || indigo.is_none() { + note.push("The iPhone did not accept touch input, so it can only be watched."); + } + if audio_on && decoder.is_none() { + note.push("This build of the app cannot play the iPhone's sound."); + } + m.set(session, |s| { + s.state = "on"; + s.audio = decoder.is_some(); + s.note = (!note.is_empty()).then(|| note.join(" ")); + }); + if let Some(r) = ready.take() { + let _ = r.send(Ok(())); + } + // Input runs on its own task, in order: a held button (Siri: 1 s), a swipe or typing must + // not stop the picture from being received meanwhile. + let (input_tx, mut input_rx) = mpsc::unbounded_channel::<(Input, oneshot::Sender>)>(); + let mi = m.clone(); + tasks.push(tokio::task::spawn_local(async move { + let (mut hid, mut indigo) = (hid, indigo); + while let Some((i, r)) = input_rx.recv().await { + let rotation = mi.status().rotation; + let _ = r.send(apply(i, hid.as_mut(), indigo.as_mut(), rotation).await); + } + })); + + let started = Instant::now(); + let mut depack = hevc::Depacketizer::new(); + let (mut v_seq, mut a_seq) = (SeqCounter::default(), SeqCounter::default()); + let mut last_keyframe_request = Instant::now() - Duration::from_secs(5); + let mut fir_seq = 0u8; + // `want_key`: someone needs a keyframe (a viewer, or lost packets); `refresh`: a still screen + // gets one now and then for new viewers. Only the first kind counts towards a restart. + let (mut want_key, mut refresh, mut key_requests) = (true, false, 0u32); + let mut tick = tokio::time::interval(Duration::from_secs(1)); + let (mut last_video, mut last_dgram) = (Instant::now(), Instant::now()); + + let result = loop { + let broken = want_key || depack.waiting_for_key; + if (broken || refresh) && last_keyframe_request.elapsed() > Duration::from_secs(1) && v_phone != 0 { + if broken { + if key_requests >= MAX_KEY_REQUESTS { + break Ok(Ended::Restart { auto: true }); + } + key_requests += 1; + } + let block = ReportBlock { source_ssrc: v_phone, highest_seq: v_seq.0.unwrap_or(0), ..Default::default() }; + let _ = video_udp.send_to(v_port, build_keyframe_request(v_ours, "", v_phone, &[block], fir_seq)).await; + fir_seq = fir_seq.wrapping_add(1); + last_keyframe_request = Instant::now(); + (want_key, refresh) = (false, false); + } + if last_dgram.elapsed() > SILENCE { + break Ok(Ended::Restart { auto: true }); + } + tokio::select! { + dg = video_udp.recv() => { + let Ok(dg) = dg else { break Err("The connection to the iPhone was lost.".to_string()) }; + last_dgram = Instant::now(); + if is_rtcp(&dg.data) { continue; } + let Some(p) = RtpPacket::parse(&dg.data) else { continue }; + last_video = Instant::now(); + v_seq.add(p.sequence_number); + let frames = depack.push(p.sequence_number, p.timestamp, p.marker, p.payload); + for au in frames { + if au.key { + key_requests = 0; + } + if depack.config_changed { + if let Some(c) = depack.decoder_config() { + m.set(session, |s| { s.width = Some(c.width); s.height = Some(c.height); }); + m.send_config(session, config_message(&c)); + } + depack.config_changed = false; + } + m.send(frame_message(&au, started.elapsed().as_micros() as u64)); + let _ = video_udp.send_to(v_port, idevice::core_device::build_frame_ack(v_ours, au.rtp_ts)).await; + } + } + dg = audio_udp.recv() => { + let Ok(dg) = dg else { break Err("The connection to the iPhone was lost.".to_string()) }; + if is_rtcp(&dg.data) { continue; } + let Some(p) = RtpPacket::parse(&dg.data) else { continue }; + a_seq.add(p.sequence_number); + if let Some(pcm) = decoder.as_mut().and_then(|d| d.decode(p.payload)) { + m.send(audio_message(&pcm, started.elapsed().as_micros() as u64)); + } + } + _ = tick.tick() => { + // Receiver reports keep both streams alive; without them the phone stops after ~20 s. + if v_phone != 0 { + let b = ReportBlock { source_ssrc: v_phone, highest_seq: v_seq.0.unwrap_or(0), ..Default::default() }; + let _ = video_udp.send_to(v_port, build_liveness(v_ours, "", &[b])).await; + } + if a_phone != 0 && a_port != 0 { + let b = ReportBlock { source_ssrc: a_phone, highest_seq: a_seq.0.unwrap_or(0), ..Default::default() }; + let _ = audio_udp.send_to(a_port, build_liveness(a_ours, "", &[b])).await; + } + if last_video.elapsed() > Duration::from_secs(4) { + refresh = true; // a still screen sends nothing; ask again so new viewers get a picture + last_video = Instant::now(); + } + } + cmd = rx.recv() => match cmd { + None => break Ok(Ended::Stopped), + Some(Cmd::Input(Input::KeyFrame, r)) => { want_key = true; let _ = r.send(Ok(())); } + Some(Cmd::Input(Input::Refresh, r)) => { let _ = r.send(Ok(())); break Ok(Ended::Restart { auto: false }); } + Some(Cmd::Input(i, r)) => { + let _ = input_tx.send((i, r)); + } + Some(Cmd::Screenshot(r)) => { + let _ = r.send(screenshot(&mut adapter, &mut hs).await); + } + Some(Cmd::StartPerf) => tasks.extend(start_perf(m, session, &mut adapter, &mut hs, &provider).await), + } + } + }; + tasks.iter().for_each(|t| t.abort()); + let _ = display.stop_media_stream().await; + result +} + +async fn press(indigo: &mut Indigo, page: u64, usage: u64, hold: u64) -> Result<(), idevice::IdeviceError> { + indigo.send_button(page, usage, ButtonState::Down).await?; + tokio::time::sleep(Duration::from_millis(hold)).await; + indigo.send_button(page, usage, ButtonState::Up).await +} + +async fn key(indigo: &mut Indigo, usage: u64, shift: bool) -> Result<(), idevice::IdeviceError> { + const SHIFT: u64 = 0xE1; + if shift { + indigo.send_keyboard(SHIFT, ButtonState::Down).await?; + } + indigo.send_keyboard(usage, ButtonState::Down).await?; + indigo.send_keyboard(usage, ButtonState::Up).await?; + if shift { + indigo.send_keyboard(SHIFT, ButtonState::Up).await?; + } + // Keystrokes sent back to back get merged. + tokio::time::sleep(Duration::from_millis(12)).await; + Ok(()) +} + +/// A point on the upright picture (fractions) -> the phone's native touch coordinates. +fn upright_to_native(u: f64, v: f64, rotation: u16) -> (u16, u16) { + let (x, y) = match rotation { + 90 => (v, 1.0 - u), + 180 => (1.0 - u, 1.0 - v), + 270 => (1.0 - v, u), + _ => (u, v), + }; + ((x.clamp(0.0, 1.0) * 65535.0).round() as u16, (y.clamp(0.0, 1.0) * 65535.0).round() as u16) +} + +async fn gesture(hid: &mut Hid, name: &str, rotation: u16) -> Result<(), IdeviceError> { + let Some(&(_, (u1, v1), (u2, v2), ms, hold)) = super::GESTURES.iter().find(|g| g.0 == name) else { return Ok(()) }; + let steps = (ms / 16).max(2); + let at = |f: f64| upright_to_native(u1 + (u2 - u1) * f, v1 + (v2 - v1) * f, rotation); + for n in 0..=steps { + let (x, y) = at(n as f64 / steps as f64); + hid.send_touchscreen(TOUCHSCREEN_STATE_CONTACT, x, y, None).await?; + tokio::time::sleep(Duration::from_millis(16)).await; + } + tokio::time::sleep(Duration::from_millis(hold)).await; + let (x, y) = at(1.0); + hid.send_touchscreen(TOUCHSCREEN_STATE_RELEASE, x, y, None).await +} + +async fn apply(i: Input, hid: Option<&mut Hid>, indigo: Option<&mut Indigo>, rotation: u16) -> Result<(), String> { + const NO_CONTROL: &str = "The iPhone did not accept touch input in this session. Stop and start mirroring again."; + const COMMAND: u64 = 0xE3; + let r = match i { + Input::Touch { phase, x, y, second: None } => { + let state = if phase == Phase::Up { TOUCHSCREEN_STATE_RELEASE } else { TOUCHSCREEN_STATE_CONTACT }; + hid.ok_or(NO_CONTROL)?.send_touchscreen(state, x, y, None).await + } + // Two fingers (pinch): both in every report, with identities that stay the same. + Input::Touch { phase, x, y, second: Some((x2, y2)) } => { + let touching = phase != Phase::Up; + let contacts = [TouchscreenContact { identity: 2, touching, x, y }, TouchscreenContact { identity: 3, touching, x: x2, y: y2 }]; + hid.ok_or(NO_CONTROL)?.send_multitouch(&contacts, None).await + } + Input::LongPress { x, y, ms } => { + let hid = hid.ok_or(NO_CONTROL)?; + hid.send_touchscreen(TOUCHSCREEN_STATE_CONTACT, x, y, None).await.map_err(|e| idev::friendly(&e))?; + tokio::time::sleep(Duration::from_millis(ms)).await; + hid.send_touchscreen(TOUCHSCREEN_STATE_RELEASE, x, y, None).await + } + Input::Gesture(name) => gesture(hid.ok_or(NO_CONTROL)?, name, rotation).await, + Input::Tap { x, y } => hid.ok_or(NO_CONTROL)?.tap(x, y).await, + // ~60 samples a second, so the phone sees a drag with a speed rather than a tap. + Input::Swipe { x1, y1, x2, y2, ms } => hid.ok_or(NO_CONTROL)?.drag(x1, y1, x2, y2, (ms / 16).max(2) as u32, 16).await, + Input::Button(_, page, usage, hold) => press(indigo.ok_or(NO_CONTROL)?, page, usage, hold).await, + Input::Key { usage, down: Some(down), command: false } => { + indigo.ok_or(NO_CONTROL)?.send_keyboard(usage, if down { ButtonState::Down } else { ButtonState::Up }).await + } + Input::Key { usage, down, command } => { + let indigo = indigo.ok_or(NO_CONTROL)?; + let keys: &[u64] = if command { &[COMMAND, usage] } else { &[usage] }; + let mut r = Ok(()); + if down != Some(false) { + for &k in keys { + r = r.and(indigo.send_keyboard(k, ButtonState::Down).await); + } + } + if down != Some(true) { + for &k in keys.iter().rev() { + r = r.and(indigo.send_keyboard(k, ButtonState::Up).await); + } + } + r + } + Input::Text(text) => { + let indigo = indigo.ok_or(NO_CONTROL)?; + for c in text.chars() { + if let Some((usage, shift)) = super::char_usage(c) { + key(indigo, usage, shift).await.map_err(|e| idev::friendly(&e))?; + } + } + Ok(()) + } + Input::KeyFrame | Input::Refresh => Ok(()), + }; + r.map_err(|e| idev::friendly(&e)) +} + +/// Asks which way the screen is turned twice a second, until the phone stops answering. +async fn follow_rotation(m: Arc, session: u64, mut info: CoreDeviceServiceClient>) { + let mut rotation = 0; + loop { + let answer = tokio::time::timeout(Duration::from_secs(3), info.invoke("com.apple.coredevice.feature.getdisplayinfo", None)).await; + let Ok(Ok(v)) = answer else { return }; + let r = display_rotation(&v); + if r != rotation { + rotation = r; + m.set(session, |s| s.rotation = r); + } + tokio::time::sleep(Duration::from_millis(500)).await; + } +} + +/// Starts measuring CPU and memory, GPU, and the battery, each on its own connection and task +/// (a part the phone refuses stays null). +async fn start_perf( + m: &Arc, + session: u64, + adapter: &mut idevice::tcp::handle::AdapterHandle, + hs: &mut RsdHandshake, + provider: &UsbmuxdProvider, +) -> Vec> { + let mut tasks = Vec::new(); + if let Ok(rs) = RemoteServerClient::connect_rsd(adapter, hs).await { + let m = m.clone(); + tasks.push(tokio::task::spawn_local(async move { let _ = cpu_memory(&m, session, rs).await; })); + } + if let Ok(rs) = RemoteServerClient::connect_rsd(adapter, hs).await { + let m = m.clone(); + tasks.push(tokio::task::spawn_local(async move { let _ = gpu(&m, session, rs).await; })); + } + if let Ok(d) = DiagnosticsRelayClient::connect(provider).await { + tasks.push(tokio::task::spawn_local(battery(m.clone(), session, d))); + } + tasks +} + +fn num(v: Option<&plist::Value>) -> Option { + match v? { + plist::Value::Integer(i) => i.as_signed().map(|i| i as f64).or_else(|| i.as_unsigned().map(|u| u as f64)), + plist::Value::Real(f) => Some(*f), + plist::Value::Boolean(b) => Some(*b as u8 as f64), + _ => None, + } +} + +/// Memory in use and in total (bytes) from sysmontap's system figures (page counts, 16 KB pages). +fn memory(sys: &std::collections::HashMap) -> (Option, Option) { + const PAGE: f64 = 16384.0; + let pages = |k: &str| num(sys.get(k)); + let used = match (pages("vmActiveCount"), pages("vmWireCount")) { + (Some(a), Some(w)) => Some((a + w + pages("vmCompressorPageCount").unwrap_or(0.0)) * PAGE), + _ => None, + }; + let total = num(sys.get("physMemSize")).or_else(|| { + let parts = ["vmFreeCount", "vmActiveCount", "vmInactiveCount", "vmWireCount", "vmCompressorPageCount", "vmSpeculativeCount"]; + let found: Vec = parts.iter().filter_map(|k| pages(k)).collect(); + (found.len() >= 4).then(|| found.iter().sum::() * PAGE) + }); + (used, total) +} + +async fn cpu_memory(m: &Arc, session: u64, mut rs: Rs) -> Result<(), IdeviceError> { + rs.read_message(0).await?; + let (cores, attrs) = { + let mut info = DeviceInfoClient::new(&mut rs).await?; + let hw = info.hardware_information().await.ok(); + (hw.and_then(|h| num(h.get("numberOfCpus"))), info.sysmon_system_attributes().await?) + }; + m.update_perf(session, |p| p["cores"] = json!(cores)); + let mut tap = SysmontapClient::new(&mut rs).await?; + tap.set_config(&SysmontapConfig { interval_ms: 1000, process_attributes: Vec::new(), system_attributes: attrs.clone() }).await?; + tap.start().await?; + loop { + let s = tap.next_sample().await?; + // CPU_TotalLoad adds up all cores (200 = two cores busy). + let load = s.system_cpu_usage.as_ref().and_then(|d| num(d.get("CPU_TotalLoad"))); + let cpu = load.map(|l| (l / cores.unwrap_or(1.0).max(1.0)).clamp(0.0, 100.0)); + let sys = s.system.map(|v| attrs.iter().cloned().zip(v).collect()).unwrap_or_default(); + let (used, total) = memory(&sys); + m.update_perf(session, |p| { + p["cpu"] = json!(cpu); + p["memory_used"] = json!(used); + p["memory_total"] = json!(total); + }); + } +} + +async fn gpu(m: &Arc, session: u64, mut rs: Rs) -> Result<(), IdeviceError> { + rs.read_message(0).await?; + let mut ch = rs.make_channel("com.apple.instruments.server.services.graphics.opengl").await?; + ch.call_method(Some(plist::Value::String("startSamplingAtTimeInterval:".into())), Some(vec![AuxValue::Double(0.0)]), true).await?; + ch.read_message().await?; + loop { + let Some(d) = ch.read_message().await?.data.and_then(|v| v.into_dictionary()) else { continue }; + let (gpu, fps) = (num(d.get("Device Utilization %")), num(d.get("CoreAnimationFramesPerSecond"))); + if gpu.is_some() || fps.is_some() { + m.update_perf(session, |p| { + p["gpu"] = json!(gpu); + p["fps"] = json!(fps); + }); + } + } +} + +/// Battery level, charging and temperature every 5 s (newer iOS keeps the temperature on the battery pack). +async fn battery(m: Arc, session: u64, mut d: DiagnosticsRelayClient) { + loop { + let Ok(Some(info)) = d.ioregistry(None, None, Some("IOPMPowerSource")).await else { return }; + let mut temp = num(info.get("Temperature")); + if temp.is_none() { + if let Ok(Some(pack)) = d.ioregistry(None, None, Some("AppleSmartBatteryPack")).await { + temp = num(pack.get("BatteryData").and_then(|b| b.as_dictionary()).and_then(|b| b.get("Temperature"))); + } + } + m.update_perf(session, |p| { + p["battery_temp"] = json!(temp.map(|t| t / 100.0)); + p["battery"] = json!(num(info.get("CurrentCapacity"))); + p["charging"] = json!(info.get("IsCharging").and_then(|v| v.as_boolean())); + }); + tokio::time::sleep(Duration::from_secs(5)).await; + } +} + +/// Clockwise degrees (0, 90, 180, 270) that turn the streamed picture upright, from a +/// `getdisplayinfo` answer: the built-in display in use, else the primary one. +fn display_rotation(info: &plist::Value) -> u16 { + let displays = info.as_dictionary().and_then(|d| d.get("displays")).and_then(|v| v.as_array()).map(Vec::as_slice).unwrap_or(&[]); + let get = |d: &plist::Value, k: &str| d.as_dictionary().and_then(|d| d.get(k)).cloned(); + let flag = |d: &plist::Value, k: &str| get(d, k).and_then(|v| v.as_boolean()).unwrap_or(false); + let built_in: Vec<&plist::Value> = displays.iter().filter(|d| !flag(d, "external")).collect(); + let chosen = built_in + .iter() + .find(|d| flag(d, "active")) + .or_else(|| built_in.iter().find(|d| get(d, "backlightState").and_then(|v| v.as_string().map(String::from)).is_some_and(|b| b != "off"))) + .copied() + .or_else(|| displays.iter().find(|d| flag(d, "primary"))) + .or_else(|| displays.first()); + match chosen.and_then(|d| get(d, "currentOrientation")).and_then(|v| v.as_string().map(String::from)).as_deref() { + Some("rot90") => 90, + Some("rot180") => 180, + Some("rot270") => 270, + _ => 0, + } +} + +async fn screenshot(adapter: &mut idevice::tcp::handle::AdapterHandle, hs: &mut RsdHandshake) -> Result, String> { + let fr = |e: idevice::IdeviceError| idev::friendly(&e); + let mut rs = RemoteServerClient::connect_rsd(adapter, hs).await.map_err(fr)?; + rs.read_message(0).await.map_err(fr)?; + let mut shot = ScreenshotClient::new(&mut rs).await.map_err(fr)?; + shot.take_screenshot().await.map_err(fr) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sequence_numbers_extend_across_wraps() { + let mut s = SeqCounter::default(); + for seq in [65534, 65535, 0, 1, 65535, 2] { + s.add(seq); + } + assert_eq!(s.0, Some(0x1_0002)); + } + + #[test] + fn upright_points_map_to_the_native_screen() { + assert_eq!(upright_to_native(0.25, 0.0, 0), (16384, 0)); + assert_eq!(upright_to_native(0.0, 0.25, 90), (16384, 65535)); + assert_eq!(upright_to_native(1.0, 1.0, 180), (0, 0)); + assert_eq!(upright_to_native(0.0, 0.25, 270), (49151, 0)); + } + + #[test] + fn memory_from_page_counts() { + let sys: std::collections::HashMap = [("vmActiveCount", 10u64), ("vmWireCount", 5), ("vmFreeCount", 5), ("vmInactiveCount", 4)] + .into_iter() + .map(|(k, v)| (k.to_string(), plist::Value::Integer(v.into()))) + .collect(); + assert_eq!(memory(&sys), (Some(15.0 * 16384.0), Some(24.0 * 16384.0))); + assert_eq!(memory(&Default::default()), (None, None)); + } + + #[test] + fn reads_the_screen_rotation() { + let d = |pairs: &[(&str, plist::Value)]| plist::Value::Dictionary(pairs.iter().map(|(k, v)| (k.to_string(), v.clone())).collect()); + let s = |v: &str| plist::Value::String(v.into()); + let info = d(&[( + "displays", + plist::Value::Array(vec![ + d(&[("external", true.into()), ("currentOrientation", s("rot180"))]), + d(&[("primary", true.into()), ("currentOrientation", s("rot90"))]), + d(&[("active", true.into()), ("currentOrientation", s("rot270"))]), + ]), + )]); + assert_eq!(display_rotation(&info), 270); + let single = d(&[("displays", plist::Value::Array(vec![d(&[("currentOrientation", s("rot90"))])]))]); + assert_eq!(display_rotation(&single), 90); + assert_eq!(display_rotation(&plist::Value::Boolean(true)), 0); + } + + #[test] + fn reads_the_stream_config() { + let answer: plist::Value = plist::Value::Dictionary( + [("connection".to_string(), plist::Value::Dictionary( + [("streamConfig".to_string(), plist::Value::Dictionary( + [("SourcePort", 50001u64), ("LocalSSRC", 7), ("RemoteSSRC", 9)] + .into_iter() + .map(|(k, v)| (k.to_string(), plist::Value::Integer(v.into()))) + .collect(), + ))] + .into_iter() + .collect(), + ))] + .into_iter() + .collect(), + ); + assert_eq!(stream_config(&answer), (50001, 9, 7)); + assert_eq!(stream_config(&plist::Value::Boolean(true)), (0, 0, 0)); + } +} diff --git a/standalone/src/server.rs b/standalone/src/server.rs index 1892c78..fb75937 100644 --- a/standalone/src/server.rs +++ b/standalone/src/server.rs @@ -1,7 +1,7 @@ //! Local HTTP server for the UI: same JSON API as the browser version (server.py), so the //! front end in ui/ is shared between both apps. -use crate::device::{DeviceManager, DriverKind}; +use crate::device::{DeviceManager, DriverKind, Via}; use crate::player::{Devices, Player}; use crate::profile::{self, Leg, ProfileSettings, Ramp, Timeline, Waypoint}; use crate::{feature_tests::FeatureTests, geo, gmaps_links, gpx, offline::Offline, routing, store::Store, updater::Updater}; @@ -45,6 +45,7 @@ pub struct AppState { pub restart_requested: std::sync::atomic::AtomicBool, pub offline: Arc, pub feature_tests: Arc, + pub screen: Arc, } pub type App = Arc; @@ -63,6 +64,7 @@ impl AppState { updater: Arc::new(updater), restart: tokio::sync::Notify::new(), restart_requested: std::sync::atomic::AtomicBool::new(false), + screen: Arc::default(), }) } @@ -89,6 +91,7 @@ impl AppState { } // ---------------------------------------------------------------- errors +#[derive(Debug)] pub struct ApiError(pub u16, pub String); impl IntoResponse for ApiError { @@ -118,6 +121,9 @@ pub fn router(app: App) -> Router { .route("/api/disconnect", post(disconnect)) .route("/api/device/reveal-developer-mode", post(reveal)) .route("/api/device/mount", post(mount)) + .route("/api/device/wifi", post(enable_wifi)) + .route("/api/mirrors", post(mirror_add)) + .route("/api/mirrors/{udid}", delete(mirror_remove)) .route("/api/location/set", post(set_location)) .route("/api/location/clear", post(clear_location)) .route("/api/parse-coords", post(parse_coords)) @@ -152,6 +158,19 @@ pub fn router(app: App) -> Router { .route("/api/feature-tests/lock", post(ft_lock)) .route("/api/feature-tests/open", post(ft_open)) .route("/api/feature-tests/progress", get(ft_progress)) + .route("/api/screen", get(screen_status)) + .route("/api/screen/start", post(screen_start)) + .route("/api/screen/stop", post(screen_stop)) + .route("/api/screen/input", post(screen_input)) + .route("/api/screen/screenshot", get(screen_screenshot)) + .route("/api/screen/ws", get(screen_ws)) + // Recordings can be long; they come from the app's own page. + .route("/api/screen/save", post(screen_save).layer(DefaultBodyLimit::max(2 << 30))) + .route("/api/screen/perf", get(screen_perf)) + .route("/api/pick-folder", post(pick_folder)) + .route("/api/mcp/setup", get(mcp_setup)) + .route("/api/mcp/claude-desktop", post(mcp_claude_desktop)) + .route("/mcp", post(mcp).get(|| async { (StatusCode::METHOD_NOT_ALLOWED, "Send MCP messages with POST.") })) .layer(DefaultBodyLimit::max(64 * 1024 * 1024)) .layer(axum::middleware::from_fn(local_only)) .with_state(app) @@ -176,6 +195,394 @@ async fn local_only(req: axum::extract::Request, next: axum::middleware::Next) - next.run(req).await } +// ---------------------------------------------------------------- screen mirroring +async fn screen_status(State(app): State) -> R { + Ok(Json(json!(app.screen.status()))) +} + +#[derive(Deserialize)] +struct ScreenStartIn { + driver: Option, + udid: Option, + #[serde(default = "yes")] + audio: bool, +} +fn yes() -> bool { + true +} + +async fn screen_start(State(app): State, Json(b): Json) -> R { + let (kind, connected) = { + let d = app.devices.lock().await; + (d.kind, d.info().map(|i| i.udid)) + }; + let kind = match b.driver.as_deref() { + Some(k) => DriverKind::parse(k).ok_or(bad("unknown driver"))?, + None => kind, + }; + let udid = b.udid.filter(|s| !s.is_empty()).or(connected); + let s = app.screen.start(kind == DriverKind::Mock, udid, b.audio).await.map_err(dev)?; + Ok(Json(json!(s))) +} + +async fn screen_stop(State(app): State) -> R { + app.screen.stop(); + Ok(Json(json!(app.screen.status()))) +} + +async fn screen_input(State(app): State, Json(b): Json) -> R { + let input = crate::screen::parse_input(&b).map_err(bad)?; + app.screen.input(input).await.map_err(dev)?; + Ok(Json(json!({"ok": true}))) +} + +async fn screen_screenshot(State(app): State) -> Result { + let png = app.screen.screenshot().await.map_err(dev)?; + Ok(([(header::CONTENT_TYPE, "image/png"), (header::CACHE_CONTROL, "no-store")], png).into_response()) +} + +#[derive(Deserialize)] +struct SaveQ { + name: String, +} + +/// File names the Mirror tab saves: letters, digits, `-`, `_`, `.`; a picture or video. +fn capture_name_ok(name: &str) -> bool { + let ext_ok = [".png", ".mp4", ".webm"].iter().any(|e| name.ends_with(e)); + ext_ok && name.len() <= 120 && !name.starts_with('.') && name.chars().all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c)) +} + +/// Saves a screenshot or recording from the Mirror tab to the folder chosen in Settings +/// (the Downloads folder by default) and returns where it went. +async fn screen_save(State(app): State, Query(q): Query, body: axum::body::Bytes) -> R { + if !capture_name_ok(&q.name) { + return Err(bad("Unexpected file name.")); + } + let chosen = app.store.load()["settings"]["capture_folder"].as_str().map(str::trim).unwrap_or("").to_string(); + let dir = if chosen.is_empty() { + dirs::download_dir().or_else(dirs::home_dir).ok_or(bad("Choose a folder for screenshots and recordings in Settings."))? + } else { + std::path::PathBuf::from(chosen) + }; + tokio::fs::create_dir_all(&dir).await.map_err(|e| bad(format!("Can't use the folder {}: {e}", dir.display())))?; + let (stem, ext) = q.name.rsplit_once('.').unwrap_or((&q.name, "")); + let mut path = dir.join(&q.name); + for n in 1.. { + if !path.exists() { + break; + } + path = dir.join(format!("{stem}-{n}.{ext}")); + } + tokio::fs::write(&path, &body).await.map_err(|e| bad(format!("Can't save to {}: {e}", dir.display())))?; + Ok(Json(json!({"path": path.display().to_string()}))) +} + +/// The phone's CPU, memory, GPU and battery figures while mirroring (the first call starts measuring). +async fn screen_perf(State(app): State) -> R { + Ok(Json(app.screen.perf().map_err(dev)?)) +} + +/// Shows the system's folder picker on this computer; answers `{"path": null}` when cancelled. +async fn pick_folder() -> R { + #[cfg(windows)] + { + // In-process, so the dialog comes up in front of the app window. + let picked = tokio::task::spawn_blocking(|| rfd::FileDialog::new().set_title("Folder for screenshots and recordings").pick_folder()) + .await + .map_err(|e| bad(e.to_string()))?; + Ok(Json(json!({"path": picked.map(|p| p.display().to_string())}))) + } + #[cfg(not(windows))] + { + let mut cmd = if cfg!(target_os = "macos") { + let mut c = std::process::Command::new("osascript"); + c.args(["-e", "POSIX path of (choose folder with prompt \"Folder for screenshots and recordings\")"]); + c + } else { + let mut c = std::process::Command::new("zenity"); + c.args(["--file-selection", "--directory", "--title=Folder for screenshots and recordings"]); + c + }; + let out = tokio::task::spawn_blocking(move || cmd.output()) + .await + .map_err(|e| bad(e.to_string()))? + .map_err(|_| bad("This computer has no folder picker the app can use. Type the folder's path instead."))?; + let path = String::from_utf8_lossy(&out.stdout).trim().to_string(); + Ok(Json(json!({"path": (!path.is_empty()).then_some(path)}))) + } +} + +// ---------------------------------------------------------------- MCP (AI agents) +/// The tools AI agents get, shared with the browser edition: ui/mcp-tools.json. Each tool is one +/// or more calls to this API; `{key}` in a path comes from the arguments or the previous answer. +fn mcp_spec() -> &'static Value { + static SPEC: OnceLock = OnceLock::new(); + SPEC.get_or_init(|| Ui::get("mcp-tools.json").and_then(|f| serde_json::from_slice(&f.data).ok()).unwrap_or(json!({"tools": []}))) +} + +/// How AI apps reach this app: the /mcp address (from the address the page used) and the program +/// to start for apps that only start programs (`--mcp`, which passes messages to this app). +fn mcp_command(host: &str) -> Value { + let port = host.rsplit_once(':').and_then(|(_, p)| p.parse::().ok()); + let mut args = vec!["--mcp".to_string()]; + if let Some(p) = port.filter(|p| *p != 8766 && *p != 8765) { + args.extend(["--port".into(), p.to_string()]); // a port the bridge wouldn't try by itself + } + let exe = std::env::current_exe().map(|p| p.display().to_string()).unwrap_or_default(); + json!({"url": format!("http://{host}/mcp"), "command": exe, "args": args, "env": {}}) +} + +fn host_of(headers: &axum::http::HeaderMap) -> String { + headers.get(header::HOST).and_then(|v| v.to_str().ok()).unwrap_or("127.0.0.1:8766").to_string() +} + +async fn mcp_setup(headers: axum::http::HeaderMap) -> R { + let mut v = mcp_command(&host_of(&headers)); + v["claude_desktop"] = json!(claude_desktop_configs().iter().any(|p| p.exists())); + Ok(Json(v)) +} + +/// Claude Desktop's config files: %APPDATA%\Claude (or the Microsoft Store copy's), ~/Library/Application Support/Claude, ~/.config/Claude. +fn claude_desktop_configs() -> Vec { + const FILE: &str = "claude_desktop_config.json"; + if let Ok(dir) = std::env::var("SPOOFER_CLAUDE_DESKTOP_DIR") { + return vec![std::path::PathBuf::from(dir).join(FILE)]; + } + #[cfg_attr(not(windows), allow(unused_mut))] // the Microsoft Store copy is Windows-only + let mut dirs: Vec = dirs::config_dir().map(|d| d.join("Claude")).into_iter().collect(); + #[cfg(windows)] + if let Some(packages) = dirs::data_local_dir().map(|d| d.join("Packages")) { + for e in std::fs::read_dir(packages).into_iter().flatten().flatten() { + if e.file_name().to_string_lossy().starts_with("Claude_") { + dirs.push(e.path().join("LocalCache").join("Roaming").join("Claude")); + } + } + } + let existing: Vec<_> = dirs.iter().filter(|d| d.exists()).map(|d| d.join(FILE)).collect(); + if existing.is_empty() { dirs.into_iter().take(1).map(|d| d.join(FILE)).collect() } else { existing } +} + +/// Adds this app to Claude Desktop's MCP servers (keeping everything else in its config). +async fn mcp_claude_desktop(headers: axum::http::HeaderMap) -> R { + let cmd = mcp_command(&host_of(&headers)); + let entry = json!({"command": cmd["command"], "args": cmd["args"]}); + let mut written = Vec::new(); + for path in claude_desktop_configs() { + let mut cfg: Value = match std::fs::read_to_string(&path) { + Ok(t) if !t.trim().is_empty() => serde_json::from_str(&t) + .map_err(|_| bad(format!("Claude Desktop's settings file can't be read, so it was left alone: {}", path.display())))?, + _ => json!({}), + }; + if !cfg.is_object() { + return Err(bad(format!("Claude Desktop's settings file has an unexpected shape, so it was left alone: {}", path.display()))); + } + if !cfg["mcpServers"].is_object() { + cfg["mcpServers"] = json!({}); + } + cfg["mcpServers"]["idevbench"] = entry.clone(); + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).map_err(|e| bad(e.to_string()))?; + } + let tmp = path.with_extension("json.tmp"); + std::fs::write(&tmp, serde_json::to_string_pretty(&cfg).unwrap_or_default()).map_err(|e| bad(e.to_string()))?; + std::fs::rename(&tmp, &path).map_err(|e| bad(e.to_string()))?; + written.push(path.display().to_string()); + } + Ok(Json(json!({"paths": written}))) +} + +/// Model Context Protocol over HTTP (JSON answers, no sessions): `claude mcp add --transport http idevbench http://127.0.0.1:8766/mcp`. +async fn mcp(State(app): State, body: axum::body::Bytes) -> Response { + let reply = |id: Value, r: Value| Json(json!({"jsonrpc": "2.0", "id": id, "result": r})).into_response(); + let error = |id: Value, code: i64, m: &str| Json(json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": m}})).into_response(); + let Ok(msg) = serde_json::from_slice::(&body) else { return error(Value::Null, -32700, "Parse error") }; + if !msg.is_object() { + return error(Value::Null, -32600, "Send one JSON-RPC message at a time"); + } + let Some(id) = msg.get("id").cloned() else { return StatusCode::ACCEPTED.into_response() }; // a notification + let spec = mcp_spec(); + match msg["method"].as_str().unwrap_or("") { + "initialize" => { + let asked = msg["params"]["protocolVersion"].as_str().unwrap_or(""); + let version = if ["2025-06-18", "2025-03-26", "2024-11-05"].contains(&asked) { asked } else { "2025-06-18" }; + reply(id, json!({"protocolVersion": version, "capabilities": {"tools": {}}, "instructions": spec["instructions"], + "serverInfo": {"name": "idevbench", "version": crate::updater::current_version().to_string()}})) + } + "ping" => reply(id, json!({})), + "tools/list" => { + let tools: Vec = spec["tools"].as_array().into_iter().flatten() + .map(|t| json!({"name": t["name"], "description": t["description"], "inputSchema": t["inputSchema"]})) + .collect(); + reply(id, json!({"tools": tools})) + } + "tools/call" => { + let name = msg["params"]["name"].as_str().unwrap_or(""); + let Some(tool) = spec["tools"].as_array().into_iter().flatten().find(|t| t["name"] == name) else { + return error(id, -32602, &format!("Unknown tool '{name}'")); + }; + let args = msg["params"]["arguments"].as_object().cloned().unwrap_or_default(); + match mcp_run(&app, tool, args).await { + Ok(content) => reply(id, json!({"content": content})), + Err(e) => reply(id, json!({"content": [{"type": "text", "text": e}], "isError": true})), + } + } + m => error(id, -32601, &format!("Method not found: {m}")), + } +} + +async fn mcp_run(app: &App, tool: &Value, mut args: serde_json::Map) -> Result, String> { + use base64::Engine; + use tower::ServiceExt; + let text = |v: &Value| json!({"type": "text", "text": if let Value::String(s) = v { s.clone() } else { serde_json::to_string_pretty(v).unwrap_or_default() }}); + let steps = tool["call"].as_array().cloned().unwrap_or_default(); + if steps.first().and_then(|s| s[0].as_str()) == Some("GUIDE") { + let guide = Ui::get("mcp-guide.md").map(|f| String::from_utf8_lossy(&f.data).into_owned()).unwrap_or_default(); + return Ok(vec![text(&Value::String(guide))]); + } + if steps.first().and_then(|s| s[0].as_str()) == Some("WAIT") { + let ms = args.get("ms").and_then(Value::as_u64).unwrap_or(1000).min(10_000); + tokio::time::sleep(std::time::Duration::from_millis(ms)).await; + return Ok(vec![text(&json!(format!("Waited {ms} ms.")))]); + } + let mut answers: Vec = Vec::new(); + for (i, step) in steps.iter().enumerate() { + let method = step[0].as_str().unwrap_or("GET"); + let mut path = step[1].as_str().unwrap_or("/").to_string(); + while let (Some(a), Some(b)) = (path.find('{'), path.find('}')) { + let key = path[a + 1..b].to_string(); + let v = if i == 0 { args.remove(&key) } else { None }.or_else(|| answers.last().and_then(|r| r.get(&key).cloned())); + let v = match v { + Some(Value::String(s)) => s, + Some(v) => v.to_string(), + None => return Err(format!("'{key}' is missing")), + }; + path.replace_range(a..=b, &percent_encoding::utf8_percent_encode(&v, percent_encoding::NON_ALPHANUMERIC).to_string()); + } + // The tool's arguments go to the first call: as the query of a GET, else merged into its body. + let mut body = step.get(2).and_then(Value::as_object).cloned().unwrap_or_default(); + if i == 0 && method == "GET" && !args.is_empty() { + let q = url::form_urlencoded::Serializer::new(String::new()) + .extend_pairs(args.iter().map(|(k, v)| (k.clone(), v.as_str().map(String::from).unwrap_or_else(|| v.to_string())))) + .finish(); + path = format!("{path}?{q}"); + } else if i == 0 { + body.extend(args.clone()); + } + let req = axum::http::Request::builder() + .method(method) + .uri(&path) + .header(header::HOST, "127.0.0.1") + .header(header::CONTENT_TYPE, "application/json") + .body(if method == "GET" { Body::empty() } else { Body::from(Value::Object(body).to_string()) }) + .map_err(|e| e.to_string())?; + let res = router(app.clone()).oneshot(req).await.map_err(|e| e.to_string())?; + let (status, kind) = (res.status(), res.headers().get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).unwrap_or("").to_string()); + let bytes = axum::body::to_bytes(res.into_body(), 64 << 20).await.map_err(|e| e.to_string())?; + if kind.starts_with("image/") && status.is_success() { + return Ok(vec![json!({"type": "image", "data": base64::engine::general_purpose::STANDARD.encode(&bytes), "mimeType": kind})]); + } + let v: Value = serde_json::from_slice(&bytes).unwrap_or_else(|_| Value::String(String::from_utf8_lossy(&bytes).into())); + if !status.is_success() { + return Err(v["detail"].as_str().map(String::from).unwrap_or_else(|| format!("HTTP {}: {}", status.as_u16(), v))); + } + answers.push(v); + } + let out = match tool["returns"].as_array() { + Some(r) => { + let from = &answers[r[0].as_u64().unwrap_or(0) as usize]; + let keys = r[1].as_array().cloned().unwrap_or_default(); + Value::Object(keys.iter().filter_map(|k| k.as_str()).map(|k| (k.to_string(), from[k].clone())).collect()) + } + None => answers.pop().unwrap_or(Value::Null), + }; + Ok(vec![text(&out)]) +} + +/// Live picture, sound and status for the Mirror tab or another program; input goes the other way. +async fn screen_ws(State(app): State, ws: axum::extract::ws::WebSocketUpgrade) -> Response { + use axum::extract::ws::Message; + use crate::screen::Out; + ws.on_upgrade(move |mut socket| async move { + let (mut rx, config, status) = app.screen.subscribe(); + let status = json!({"type": "status", "status": status}).to_string(); + if socket.send(Message::Text(status.into())).await.is_err() { + return; + } + if let Some(c) = config { + let _ = socket.send(Message::Binary(c.to_vec().into())).await; + } + let _ = app.screen.input(crate::screen::Input::KeyFrame).await; + // Inputs run one after another on their own task, so a long one (Siri, typing) doesn't + // hold up the picture; their errors come back here. + let (input_tx, mut input_rx) = tokio::sync::mpsc::unbounded_channel::(); + let (err_tx, mut err_rx) = tokio::sync::mpsc::unbounded_channel::(); + let worker = { + let app = app.clone(); + tokio::spawn(async move { + let mut held = None; + loop { + let Some(mut i) = held.take() else { + match input_rx.recv().await { + Some(i) => { held = Some(i); continue; } + None => break, + } + }; + // Finger moves that piled up while the phone was busy: only the newest matters. + while crate::screen::is_move(&i) { + match input_rx.try_recv() { + Ok(next) if crate::screen::is_move(&next) => i = next, + Ok(next) => { held = Some(next); break; } + Err(_) => break, + } + } + if let Err(e) = app.screen.input(i).await { + let _ = err_tx.send(e); + } + } + }) + }; + // Frames only make sense from a keyframe on: skip until one arrives (also after falling behind). + let mut need_key = true; + loop { + tokio::select! { + Some(e) = err_rx.recv() => { + if socket.send(Message::Text(json!({"type": "error", "detail": e}).to_string().into())).await.is_err() { break; } + } + out = rx.recv() => { + let msg = match out { + Ok(Out::Text(t)) => Message::Text(t.as_str().into()), + Ok(Out::Bin(b)) => { + if b[0] == 2 { + if need_key && b[1] == 0 { continue; } + need_key = false; + } + Message::Binary(b.to_vec().into()) + } + Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => { + need_key = true; + let _ = app.screen.input(crate::screen::Input::KeyFrame).await; + continue; + } + Err(_) => break, + }; + if socket.send(msg).await.is_err() { break; } + } + msg = socket.recv() => match msg { + Some(Ok(Message::Text(t))) => { + match serde_json::from_str::(&t).map_err(|e| e.to_string()).and_then(|v| crate::screen::parse_input(&v)) { + Ok(i) => { let _ = input_tx.send(i); } + Err(e) => { let _ = socket.send(Message::Text(json!({"type": "error", "detail": e}).to_string().into())).await; } + } + } + Some(Ok(_)) => {} + _ => break, + } + } + } + worker.abort(); + }) +} + // ---------------------------------------------------------------- offline maps /// OpenFreeMap through the local cache (the page rewrites its map requests to /ofm/...). async fn ofm(State(app): State, uri: axum::http::Uri) -> Response { @@ -306,11 +713,12 @@ async fn status(State(app): State) -> R { "feature_test": FEATURE_TEST.get(), "driver": d.kind.key(), "drivers": [{"key": "pmd3", "label": "Direct", "live": true}, {"key": "mock", "label": "Simulator (no iPhone)", "live": true}], - "features": {"cli_driver": false, "tunnel_helper": false}, + "features": {"cli_driver": false, "tunnel_helper": false, "multi_device": true, "wifi": true}, "device": d.info(), "live": true, "player": app.player.status(), "update": app.updater.status(), + "mirrors": d.mirrors_json(), }))) } @@ -329,15 +737,63 @@ async fn devices(State(app): State, Query(q): Query) -> R { struct ConnectIn { driver: Option, udid: Option, + connection: Option, } async fn connect(State(app): State, Json(b): Json) -> R { let kind = DriverKind::parse(b.driver.as_deref().unwrap_or("pmd3")).ok_or(bad("unknown driver"))?; + let via = Via::parse(b.connection.as_deref()).ok_or(bad("unknown connection"))?; app.player.stop().await; - let info = app.devices.lock().await.connect(kind, b.udid.filter(|s| !s.is_empty())).await.map_err(dev)?; + let info = app.devices.lock().await.connect(kind, b.udid.filter(|s| !s.is_empty()), via).await.map_err(dev)?; Ok(Json(json!({"device": info}))) } +#[derive(Deserialize)] +struct MirrorIn { + udid: String, + connection: Option, +} + +/// Another iPhone follows the main one: same position, same route, from now on. +async fn mirror_add(State(app): State, Json(b): Json) -> R { + let via = Via::parse(b.connection.as_deref()).ok_or(bad("unknown connection"))?; + let kind = { + let d = app.devices.lock().await; + if let Some(why) = d.mirror_refusal(&b.udid) { + return Err(dev(why)); + } + d.kind + }; + let (info, backend) = crate::device::connect_mirror(kind, b.udid, via).await.map_err(dev)?; + let mut d = app.devices.lock().await; + let m = d.attach_mirror(info, backend).await.map_err(dev)?; + Ok(Json(json!({"mirror": m, "mirrors": d.mirrors_json()}))) +} + +#[derive(Deserialize)] +struct ClearQ { + clear: Option, +} + +/// Stops following; by default the phone goes back to its real location. +async fn mirror_remove(State(app): State, Path(udid): Path, Query(q): Query) -> R { + let mut d = app.devices.lock().await; + if !d.remove_mirror(&udid, q.clear.unwrap_or(true)).await { + return Err(ApiError(404, "That iPhone doesn't follow the main one.".into())); + } + Ok(Json(json!({"mirrors": d.mirrors_json()}))) +} + +#[derive(Deserialize)] +struct UdidIn { + udid: Option, +} + +async fn enable_wifi(State(app): State, Json(b): Json) -> R { + let m = app.devices.lock().await.enable_wifi(b.udid.filter(|s| !s.is_empty())).await.map_err(dev)?; + Ok(Json(json!({"message": m}))) +} + async fn disconnect(State(app): State) -> R { app.player.stop().await; app.devices.lock().await.disconnect().await; @@ -1118,6 +1574,148 @@ mod tests { assert!(held.hold && !serde_json::from_value::(json!({"lat": 1.0, "lon": 2.0})).unwrap().hold); } + // ------------------------------------------------ several iPhones at once (mirrors) + const MAIN: &str = "SIMULATED-0001"; + const SECOND: &str = "SIMULATED-0002"; + + fn connect_in(udid: Option<&str>, connection: Option<&str>) -> Json { + Json(ConnectIn { driver: Some("mock".into()), udid: udid.map(String::from), connection: connection.map(String::from) }) + } + fn mirror_in(udid: &str, connection: Option<&str>) -> Json { + Json(MirrorIn { udid: udid.into(), connection: connection.map(String::from) }) + } + async fn two_phones() -> (App, Arc>) { + let a = app(); + let _ = connect(State(a.clone()), connect_in(Some(MAIN), None)).await.unwrap(); + let r = mirror_add(State(a.clone()), mirror_in(SECOND, None)).await.unwrap_or_else(|e| panic!("{}", e.1)); + assert_eq!(r.0["mirror"]["name"], "Simulated iPhone 2"); + assert_eq!(r.0["mirror"]["state"], "ok"); + let shared = a.devices.lock().await.mirrors[0].shared.clone(); + (a, shared) + } + async fn until(f: impl Fn() -> bool) -> bool { + for _ in 0..300 { + if f() { + return true; + } + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + false + } + fn here(lat: f64, lon: f64) -> Json { + Json(LatLonIn { lat, lon }) + } + + #[tokio::test] + async fn mirror_follows_teleport_playback_and_stop() { + let (a, m) = two_phones().await; + let st = status(State(a.clone())).await.unwrap().0; + assert_eq!(st["device"]["udid"], MAIN); + assert_eq!(st["mirrors"][0]["udid"], SECOND); + assert!(st["features"]["multi_device"].as_bool().unwrap() && st["features"]["wifi"].as_bool().unwrap()); + let _ = set_location(State(a.clone()), here(51.5, -0.12)).await.unwrap(); + assert!(until(|| m.lock().unwrap().location == Some((51.5, -0.12))).await); + // a route played on the main phone moves the mirror along it too + let start = (51.5, -0.12); + let end = geo::destination(start, 90.0, 300.0); + let s = crate::profile::ProfileSettings { default_cruise_kmh: 36.0, accel_ms2: 2.0, decel_ms2: 2.0, ..Default::default() }; + let w = [crate::profile::Waypoint::at(start), crate::profile::Waypoint::at(end)]; + let tl = Arc::new(crate::profile::build_timeline(&w, &[crate::profile::Leg::new(vec![start, end])], &s).unwrap()); + a.player.load(tl, "two".into()).await; + a.player.set_options(Some(10.0), None, None, Some(0.2), None).unwrap(); + a.player.play().await.unwrap(); + assert!(until(|| a.player.status()["state"] == "finished").await); + assert!(until(|| m.lock().unwrap().location.is_some_and(|p| geo::haversine_m(p, end) < 1.0)).await); + let main_end = a.devices.lock().await.mock.location.unwrap(); + assert!(geo::haversine_m(main_end, end) < 1.0); + assert!(m.lock().unwrap().history > 5, "it moved along the route, not just to the end"); + // Stop spoofing clears every phone + let _ = clear_location(State(a.clone())).await.unwrap(); + assert!(until(|| m.lock().unwrap().location.is_none()).await); + assert!(a.devices.lock().await.mock.location.is_none()); + } + + #[tokio::test] + async fn a_slow_mirror_never_holds_up_the_main_phone() { + let (a, m) = two_phones().await; + m.lock().unwrap().delay_ms = 300; + let t0 = std::time::Instant::now(); + for i in 0..6 { + let _ = set_location(State(a.clone()), here(51.5 + i as f64 * 1e-4, -0.12)).await.unwrap(); + } + assert!(t0.elapsed() < std::time::Duration::from_millis(1200), "six sends to a 0.3 s phone would take 1.8 s"); + let last = (51.5 + 5e-4, -0.12); + let main = a.devices.lock().await.mock.location.unwrap(); + assert!((main.0 - last.0).abs() < 1e-9); + // the mirror skips the positions it fell behind on and ends where the main phone is + assert!(until(|| m.lock().unwrap().location.is_some_and(|p| (p.0 - last.0).abs() < 1e-9)).await); + assert!(m.lock().unwrap().sent < 6); + } + + #[tokio::test] + async fn a_lost_mirror_is_marked_and_the_rest_keeps_going() { + let (a, m) = two_phones().await; + m.lock().unwrap().fail = true; + let _ = set_location(State(a.clone()), here(51.5, -0.12)).await.unwrap(); + assert!(until(|| m.lock().unwrap().error.is_some()).await); + let st = status(State(a.clone())).await.unwrap().0; + assert_eq!(st["mirrors"][0]["state"], "lost"); + assert!(st["mirrors"][0]["error"].as_str().unwrap().contains("Lost the connection")); + let _ = set_location(State(a.clone()), here(51.6, -0.12)).await.unwrap(); + assert_eq!(a.devices.lock().await.mock.location, Some((51.6, -0.12))); + let r = mirror_remove(State(a.clone()), Path(SECOND.into()), Query(ClearQ { clear: None })).await.unwrap(); + assert_eq!(r.0["mirrors"], json!([])); + } + + #[tokio::test] + async fn removing_a_mirror_sends_it_back_to_its_real_location() { + let (a, m) = two_phones().await; + let _ = set_location(State(a.clone()), here(51.5, -0.12)).await.unwrap(); + assert!(until(|| m.lock().unwrap().location.is_some()).await); + let _ = mirror_remove(State(a.clone()), Path(SECOND.into()), Query(ClearQ { clear: None })).await.unwrap(); + assert_eq!(m.lock().unwrap().location, None); + assert_eq!(a.devices.lock().await.mock.location, Some((51.5, -0.12)), "the main phone keeps its position"); + let e = mirror_remove(State(a.clone()), Path(SECOND.into()), Query(ClearQ { clear: None })).await.unwrap_err(); + assert_eq!(e.0, 404); + } + + #[tokio::test] + async fn new_mirror_catches_up_and_rules() { + let a = app(); + assert_eq!(mirror_add(State(a.clone()), mirror_in(SECOND, None)).await.unwrap_err().0, 409, "no main phone yet"); + let _ = connect(State(a.clone()), connect_in(Some(MAIN), None)).await.unwrap(); + let _ = set_location(State(a.clone()), here(51.5, -0.12)).await.unwrap(); + assert_eq!(mirror_add(State(a.clone()), mirror_in(MAIN, None)).await.unwrap_err().0, 409, "that's the main phone"); + let _ = mirror_add(State(a.clone()), mirror_in(SECOND, Some("usb"))).await.unwrap(); + let m = a.devices.lock().await.mirrors[0].shared.clone(); + assert!(until(|| m.lock().unwrap().location == Some((51.5, -0.12))).await, "caught up at once"); + assert_eq!(mirror_add(State(a.clone()), mirror_in(SECOND, None)).await.unwrap_err().0, 409, "already following"); + assert_eq!(mirror_add(State(a.clone()), mirror_in("SIMULATED-9999", None)).await.unwrap_err().0, 409); + assert_eq!(mirror_add(State(a.clone()), mirror_in(SECOND, Some("bluetooth"))).await.unwrap_err().0, 400); + // connecting the main phone to the mirrored one makes it the main phone instead + let _ = connect(State(a.clone()), connect_in(Some(SECOND), None)).await.unwrap(); + let st = status(State(a.clone())).await.unwrap().0; + assert_eq!(st["device"]["udid"], SECOND); + assert_eq!(st["mirrors"], json!([])); + // disconnecting ends the mirrors too + let _ = mirror_add(State(a.clone()), mirror_in(MAIN, None)).await.unwrap(); + let _ = disconnect(State(a.clone())).await.unwrap(); + assert_eq!(status(State(a.clone())).await.unwrap().0["mirrors"], json!([])); + } + + #[tokio::test] + async fn wifi_tool_and_connection_field() { + let a = app(); + let _ = connect(State(a.clone()), connect_in(None, Some("network"))).await.unwrap(); + let r = enable_wifi(State(a.clone()), Json(UdidIn { udid: None })).await.unwrap(); + assert!(r.0["message"].as_str().unwrap().starts_with("Simulator")); + assert_eq!(connect(State(a.clone()), connect_in(None, Some("carrier-pigeon"))).await.unwrap_err().0, 400); + assert_eq!(Via::parse(None), Some(Via::Auto)); + assert_eq!(Via::parse(Some("network")), Some(Via::Network)); + let list = a.devices.lock().await.list_devices(DriverKind::Mock).await.unwrap(); + assert_eq!(list.iter().map(|d| d["udid"].as_str().unwrap()).collect::>(), [MAIN, SECOND]); + } + #[tokio::test] async fn bad_requests_are_rejected_before_routing() { let mut r = route(); @@ -1129,4 +1727,99 @@ mod tests { let e = build_route_core(app(), r, quiet).await.unwrap_err(); assert_eq!((e.0, e.1.as_str()), (400, "Expected 2 legs, got 1")); } + + #[tokio::test] + async fn screen_routes_with_the_simulator() { + let a = app(); + let e = screen_input(State(a.clone()), Json(json!({"t": "tap", "x": 0.5, "y": 0.5}))).await.unwrap_err(); + assert_eq!(e.0, 409); + let start = ScreenStartIn { driver: Some("mock".into()), udid: None, audio: true }; + let s = screen_start(State(a.clone()), Json(start)).await.unwrap_or_else(|e| panic!("{}", e.1)).0; + assert_eq!((s["state"].as_str(), s["simulated"].as_bool()), (Some("on"), Some(true))); + assert!(screen_input(State(a.clone()), Json(json!({"t": "text", "text": "hi"}))).await.is_ok()); + assert_eq!(screen_input(State(a.clone()), Json(json!({"t": "tap", "x": 2, "y": 0}))).await.unwrap_err().0, 400); + assert_eq!(screen_screenshot(State(a.clone())).await.unwrap_err().0, 409); + assert_eq!(screen_stop(State(a.clone())).await.unwrap_or_else(|e| panic!("{}", e.1)).0["state"], "off"); + } + + #[tokio::test] + async fn mcp_drives_location_and_mirroring() { + let a = app(); + let rpc = |method: &str, params: Value| { + let a = a.clone(); + let body = json!({"jsonrpc": "2.0", "id": 1, "method": method, "params": params}).to_string(); + async move { + let r = mcp(State(a), axum::body::Bytes::from(body)).await; + serde_json::from_slice::(&axum::body::to_bytes(r.into_body(), 1 << 24).await.unwrap()).unwrap() + } + }; + let call = |name: &str, args: Value| rpc("tools/call", json!({"name": name, "arguments": args})); + let init = rpc("initialize", json!({"protocolVersion": "2025-03-26"})).await; + assert_eq!((init["result"]["protocolVersion"].as_str(), init["result"]["serverInfo"]["name"].as_str()), (Some("2025-03-26"), Some("idevbench"))); + let tools = rpc("tools/list", json!({})).await["result"]["tools"].as_array().unwrap().len(); + assert!(tools >= 30, "{tools}"); + let note = mcp(State(a.clone()), axum::body::Bytes::from(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#)).await; + assert_eq!(note.status(), StatusCode::ACCEPTED); + assert_eq!(rpc("nope", json!({})).await["error"]["code"], -32601); + + assert!(call("tap", json!({"x": 0.5, "y": 0.5})).await["result"]["isError"].as_bool().unwrap()); + for (name, args) in [ + ("connect_device", json!({"driver": "mock"})), + ("set_location", json!({"lat": 48.8584, "lon": 2.2945})), + ("start_mirroring", json!({"driver": "mock"})), + ("tap", json!({"x": 0.5, "y": 0.9})), + ("gesture", json!({"name": "app_switcher"})), + ("press_key", json!({"usage": 4, "command": true})), + ("phone_performance", json!({})), + ("wait", json!({"ms": 1})), + ] { + let r = call(name, args).await; + assert!(r["result"]["isError"].is_null(), "{name}: {r}"); + } + assert!(a.screen.sim_inputs().contains(&crate::screen::Input::Gesture("app_switcher"))); + let route = call("drive_route", json!({"waypoints": [{"lat": 51.5, "lon": -0.12}, {"lat": 51.501, "lon": -0.12}], "legs": [{"mode": "straight"}]})).await; + let text: Value = serde_json::from_str(route["result"]["content"][0]["text"].as_str().unwrap()).unwrap(); + assert!(text["id"].is_string() && text["summary"].is_object(), "{route}"); + assert_eq!(a.player.status()["state"], "playing"); + let fav = call("list_favourites", json!({})).await; + assert!(!fav["result"]["content"][0]["text"].as_str().unwrap().contains("settings")); + let shot = call("screenshot", json!({})).await; + assert!(shot["result"]["isError"].as_bool().unwrap()); + } + + #[tokio::test] + async fn adds_itself_to_claude_desktop_keeping_other_settings() { + let dir = std::env::temp_dir().join(format!("idevbench-claude-{}", rand::random::())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("claude_desktop_config.json"); + std::fs::write(&file, r#"{"theme": "dark", "mcpServers": {"other": {"command": "x"}}}"#).unwrap(); + std::env::set_var("SPOOFER_CLAUDE_DESKTOP_DIR", &dir); + let mut h = axum::http::HeaderMap::new(); + h.insert(header::HOST, "127.0.0.1:9123".parse().unwrap()); + let setup = mcp_setup(h.clone()).await.unwrap_or_else(|e| panic!("{}", e.1)).0; + assert_eq!(setup["url"], "http://127.0.0.1:9123/mcp"); + assert_eq!(setup["args"], json!(["--mcp", "--port", "9123"])); + let _ = mcp_claude_desktop(h).await.unwrap_or_else(|e| panic!("{}", e.1)); + let cfg: Value = serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap(); + std::env::remove_var("SPOOFER_CLAUDE_DESKTOP_DIR"); + assert_eq!((cfg["theme"].as_str(), cfg["mcpServers"]["other"]["command"].as_str()), (Some("dark"), Some("x"))); + assert_eq!(cfg["mcpServers"]["idevbench"]["args"][0], "--mcp"); + let guide = mcp_run(&app(), &json!({"call": [["GUIDE"]]}), Default::default()).await.unwrap(); + assert!(guide[0]["text"].as_str().unwrap().contains("passcode")); + } + + #[tokio::test] + async fn screen_captures_go_to_the_chosen_folder() { + let a = app(); + let dir = std::env::temp_dir().join(format!("idevbench-captures-{}", rand::random::())); + a.store.save(&json!({"settings": {"capture_folder": dir.to_string_lossy()}})).unwrap(); + let save = |name: &str| screen_save(State(a.clone()), Query(SaveQ { name: name.into() }), axum::body::Bytes::from_static(b"png")); + let first = save("shot.png").await.unwrap_or_else(|e| panic!("{}", e.1)).0; + let second = save("shot.png").await.unwrap_or_else(|e| panic!("{}", e.1)).0; + assert_eq!(std::fs::read(first["path"].as_str().unwrap()).unwrap(), b"png"); + assert!(second["path"].as_str().unwrap().ends_with("shot-1.png")); + for bad_name in ["../x.png", "x.exe", ".png", "a/b.png"] { + assert_eq!(save(bad_name).await.unwrap_err().0, 400, "{bad_name}"); + } + } } diff --git a/ui/app.js b/ui/app.js index 2f45dc7..1ea2a0a 100644 --- a/ui/app.js +++ b/ui/app.js @@ -1,4 +1,4 @@ -/* Location Spoofer — UI shared by the standalone and browser apps. Talks to the local server at /api. +/* iDevBench — UI shared by the standalone and browser apps. Talks to the local server at /api. Copyright (c) 2026 YK3D. All rights reserved. Licensed under the Location Spoofer License (LICENSE). */ "use strict"; @@ -863,6 +863,7 @@ $("btn-show-sidebar").onclick = () => setSidebarHidden(false); // ------------------------------------------------------------------ tabs function openTab(name) { + setMode("location"); state.tab = name; document.querySelectorAll(".tabs button").forEach((x) => x.classList.toggle("active", x.dataset.tab === name)); document.querySelectorAll(".tab-panel").forEach((p) => (p.hidden = p.id !== `tab-${name}`)); @@ -879,6 +880,7 @@ async function refreshDevices(userAsked = false) { state.devicesError = null; try { const { devices } = await api(`/api/devices?driver=${driver}`); + state.devices = devices; for (const d of devices) { const label = `${d.name || "iPhone"}${d.ios_version ? ` (iOS ${d.ios_version})` : ""} — ${d.connection || ""}${d.error ? " (needs attention)" : ""}`; sel.append(el("option", { value: d.udid, textContent: label, title: d.error || d.udid })); @@ -890,6 +892,7 @@ async function refreshDevices(userAsked = false) { if (userAsked) toast(e.message, true); } if (state.status) renderDevice(state.status); + renderMirrorDevice(); } $("btn-refresh").onclick = () => refreshDevices(true); $("driver").onchange = () => { refreshDevices(false); saveSettingsSoon(); }; @@ -898,7 +901,7 @@ async function connectNow() { $("device-status").className = "status"; $("device-status").textContent = "Connecting… (iOS 17+ can take up to 30 s)"; try { - const { device } = await api("/api/connect", { body: { driver: $("driver").value, udid: $("device-select").value || null } }); + const { device } = await api("/api/connect", { body: { driver: $("driver").value, udid: $("device-select").value || null, connection: $("conn-via").value } }); toast(`Connected to ${device.name}`); for (const n of device.notes || []) toast(n); return device; @@ -912,6 +915,64 @@ $("btn-disconnect").onclick = guard(disconnectNow); async function revealDevMode() { toast((await api("/api/device/reveal-developer-mode", { body: {} })).message); } $("btn-reveal").onclick = busy($("btn-reveal"), "Asking the iPhone…", revealDevMode); $("btn-mount").onclick = busy($("btn-mount"), "Mounting…", async () => toast((await api("/api/device/mount", { body: {} })).message)); +$("btn-wifi").onclick = busy($("btn-wifi"), "Asking the iPhone…", async () => { + toast((await api("/api/device/wifi", { body: { udid: (state.status && state.status.device && state.status.device.udid) || $("device-select").value || null } })).message); + refreshDevices(false); +}); + +// ---- more iPhones at once: extra phones follow the main one (see mirrors.py / device/mirror.rs) +const lostMirrorsToasted = new Set(); +async function addMirror() { + const udid = $("mirror-select").value; + if (!udid) { toast("Plug in or connect another iPhone, press the refresh button next to Device, then pick it here.", true); return; } + const { mirror } = await api("/api/mirrors", { body: { udid, connection: $("conn-via").value } }); + toast(`${mirror.name} now follows ${state.status.device.name}`); + for (const n of mirror.notes || []) toast(n); + await poll(); +} +$("btn-mirror-add").onclick = busy($("btn-mirror-add"), "Connecting…", addMirror); +async function removeMirror(m) { + await api(`/api/mirrors/${encodeURIComponent(m.udid)}`, { method: "DELETE" }); + toast(`${m.name} no longer follows and is back on its real location`); + lostMirrorsToasted.delete(m.udid); + await poll(); +} +function renderMirrors(st) { + const box = $("mirrors"); + const on = !!(st.device && st.live && st.features && st.features.multi_device); + box.hidden = !on; + if (!on) return; + const mirrors = st.mirrors || []; + const listKey = JSON.stringify(mirrors.map((m) => [m.udid, m.state, m.error])); + if (box.dataset.list !== listKey) { + box.dataset.list = listKey; + $("mirror-list").replaceChildren(...mirrors.map((m) => { + const lost = m.state === "lost"; + const line = el("div", { class: `status ${lost ? "err" : "ok"}`, title: m.error || m.transport || "" }, + el("span", { textContent: `${m.name}${m.ios_version ? ` · iOS ${m.ios_version}` : ""}${m.connection && m.connection !== "Simulated" ? ` · ${m.connection}` : ""}${lost ? ` · ${m.error}` : ""}` })); + const rm = el("button", { type: "button", textContent: "Remove", title: "Stop following and send this iPhone back to its real location" }); + rm.onclick = busy(rm, "Removing…", () => removeMirror(m)); + return el("li", {}, line, rm); + })); + for (const m of mirrors) { + if (m.state === "lost" && !lostMirrorsToasted.has(m.udid)) { lostMirrorsToasted.add(m.udid); toast(`${m.name} stopped following: ${m.error}`, true); } + } + } + // phones that can still be added: found in the last device scan, not the main one, not following yet + const taken = new Set([st.device.udid, ...mirrors.map((m) => m.udid)]); + const free = (state.devices || []).filter((d) => !taken.has(d.udid)); + const optKey = JSON.stringify(free.map((d) => [d.udid, d.connection])); + const sel = $("mirror-select"); + if (sel.dataset.opts !== optKey) { + sel.dataset.opts = optKey; + const keep = sel.value; + sel.replaceChildren(...(free.length + ? free.map((d) => el("option", { value: d.udid, textContent: `${d.name || "iPhone"}${d.ios_version ? ` (iOS ${d.ios_version})` : ""} — ${d.connection || ""}`, title: d.error || d.udid })) + : [el("option", { value: "", textContent: "No other iPhone found" })])); + if (keep && free.some((d) => d.udid === keep)) sel.value = keep; + } + $("btn-mirror-add").disabled = !free.length; +} async function stopSpoofing() { await api("/api/location/clear", { body: {} }); @@ -927,12 +988,14 @@ function renderDevice(st) { const box = $("device-status"), chip = $("conn-chip"); $("btn-connect").hidden = !!d; $("btn-disconnect").hidden = !d; + renderMirrors(st); if (d) { + const extra = (st.mirrors || []).length; box.className = "status ok"; - box.textContent = `${d.name}${d.ios_version ? ` · iOS ${d.ios_version}` : ""} · ${d.transport}`; + box.textContent = `${d.name}${d.ios_version ? ` · iOS ${d.ios_version}` : ""}${d.connection && d.connection !== "Simulated" ? ` · ${d.connection}` : ""} · ${d.transport}`; $("driver").value = st.driver; - chip.className = "chip ok"; chip.textContent = d.name; - $("dev-summary").textContent = `Connected · ${d.name}`; + chip.className = "chip ok"; chip.textContent = extra ? `${d.name} + ${extra}` : d.name; + $("dev-summary").textContent = `Connected · ${d.name}${extra ? ` + ${extra} more` : ""}`; } else if (state.devicesError && $("driver").value !== "mock") { box.className = "status warn"; // Rebuilt only when the message changes, so the link isn't replaced under the mouse every poll. @@ -2560,7 +2623,7 @@ function keyVector() { } const typing = () => ["INPUT", "SELECT", "TEXTAREA"].includes(document.activeElement.tagName) || !!document.querySelector("dialog[open]"); function joystickKeydown(e) { - if (state.tab !== "joystick" || !KEYS[e.code] || typing()) return false; + if (state.tab !== "joystick" || document.body.classList.contains("mode-screen") || !KEYS[e.code] || typing()) return false; e.preventDefault(); if (!held.has(e.code)) { held.add(e.code); @@ -2609,6 +2672,7 @@ const ACTIONS = [ ["tab-gpx", "3", "GPX tab", () => openTab("gpx")], ["tab-joystick", "4", "Joystick tab", () => openTab("joystick")], ["tab-saved", "5", "Saved tab", () => openTab("saved")], + ["screen", "6", "Mirroring section", () => setMode("screen")], ]; const actionById = Object.fromEntries(ACTIONS.map((a) => [a[0], a])); function shortcutMap() { @@ -2704,7 +2768,7 @@ function saveSettingsSoon() { await saveStore(); }), 700); } -const SETTING_IDS = ["driver", "provider", "default-mode", "default-speed", "accel", "decel", "alt-count", "start-rest", "stop-end", +const SETTING_IDS = ["driver", "conn-via", "provider", "default-mode", "default-speed", "accel", "decel", "alt-count", "start-rest", "stop-end", "road-aware", "road-data", "corner-slow", "match-eta", "speed-factor", "multiplier", "loop", "jitter", "tick", "laps", "joy-speed", "gpx-speed"]; function collectSettings() { const s = {}; @@ -2723,6 +2787,7 @@ function applySettings(s) { $("google-key").value = s.google_api_key || ""; $("pref-compact").checked = !!s.compact; $("pref-channel").value = s.update_channel === "dev" ? "dev" : "stable"; + renderCaptureFolder(); if (s.sidebar_w) setSidebarWidth(s.sidebar_w, false); applyAppearance(); applySections(); @@ -2798,7 +2863,7 @@ $("btn-export-data").onclick = () => { const data = { ...state.store, settings: { ...settings() } }; delete data.settings.google_api_key; // never put the API key in a backup file const blob = new Blob([JSON.stringify(data, null, 1)], { type: "application/json" }); - const a = el("a", { href: URL.createObjectURL(blob), download: "location-spoofer-backup.json" }); + const a = el("a", { href: URL.createObjectURL(blob), download: "idevbench-backup.json" }); document.body.append(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(a.href), 1000); }; @@ -2858,6 +2923,7 @@ function openSettings(pane = "appearance") { if (pane === "keys") renderShortcutEditor(); }); if (pane === "offline") { pollOffline().catch((e) => toast(e.message, true)); updateOfflineEstimate(); } + if (pane === "agents") renderAgentSetup().catch((e) => toast(e.message, true)); if (!settingsDlg.open) settingsDlg.showModal(); } document.querySelectorAll("#settings-tabs button").forEach((b) => (b.onclick = () => openSettings(b.dataset.pane))); @@ -2892,7 +2958,7 @@ async function refreshGoogleStatus() { } // ------------------------------------------------------------------ first-run tutorial -const SITE = "https://iphone-spoofer.vercel.app"; // the website hosts the Terms, Privacy Policy and licences +const SITE = "https://idevbench.vercel.app"; // the website hosts the Terms, Privacy Policy and licences const TUTORIAL = [ { title: "Welcome", body: [ "This app sets your iPhone's location from this computer over a USB cable: jump to any place, follow routes at realistic speeds, or replay GPX files.", @@ -3180,7 +3246,7 @@ async function poll() { const st = await api("/api/status"); state.status = st; $("version").textContent = `v${st.version}${st.app === "standalone" ? "" : " · browser"}${st.feature_test ? ` · feature test #${st.feature_test}` : ""}`; - document.querySelector(".brand h1").title = `Location Spoofer ${$("version").textContent}`; + document.querySelector(".brand h1").title = `iDevBench ${$("version").textContent}`; $("about-version").textContent = `Version ${st.version} (${st.app === "standalone" ? "standalone app" : "browser version"})`; if (!state.bootVersion) { state.bootVersion = st.version; applyFeatures(st.features); } renderUpdate(st); @@ -3220,6 +3286,528 @@ document.addEventListener("pointerdown", (e) => { setTimeout(done, 1200); // in case the animation never runs (hidden button) }, { passive: true }); +// ------------------------------------------------------------------ screen mirroring +// The server sends the phone's screen as HEVC frames (decoded here with WebCodecs) and its sound as +// PCM over /api/screen/ws; touches and keys go back as JSON. Message layout: see standalone/src/screen. +const mirror = { ws: null, decoder: null, config: null, supported: {}, status: { state: "off" }, audio: null, nextAudio: 0, + recorder: null, down: false, turn: 0, lastKeyAsk: 0, errors: 0, wheel: null, pinch: null, stats: null, perf: null, + frame: null, drawQueued: false, pending: new Map() }; +// KeyboardEvent.code -> HID keyboard usage. Ctrl is sent as the iPhone's Command key. +const HID_KEYS = (() => { + const m = { Enter: 40, NumpadEnter: 40, Escape: 41, Backspace: 42, Tab: 43, Space: 44, Minus: 45, Equal: 46, BracketLeft: 47, + BracketRight: 48, Backslash: 49, Semicolon: 51, Quote: 52, Backquote: 53, Comma: 54, Period: 55, Slash: 56, CapsLock: 57, + Home: 74, PageUp: 75, Delete: 76, End: 77, PageDown: 78, ArrowRight: 79, ArrowLeft: 80, ArrowDown: 81, ArrowUp: 82, + ControlLeft: 227, ShiftLeft: 225, AltLeft: 226, MetaLeft: 227, ControlRight: 231, ShiftRight: 229, AltRight: 230, MetaRight: 231 }; + for (let i = 0; i < 26; i++) m[`Key${String.fromCharCode(65 + i)}`] = 4 + i; + for (let i = 1; i <= 9; i++) m[`Digit${i}`] = 29 + i; + m.Digit0 = 39; + return m; +})(); + +// Location or Mirroring: the two sections of the app. Mirroring hides the location tools and the map. +function setMode(mode) { + const screen = mode === "screen"; + document.querySelectorAll("#modes button").forEach((b) => b.classList.toggle("active", b.dataset.mode === mode)); + try { localStorage.setItem("ls-mode", mode); } catch (_) { /* storage blocked */ } + if (document.body.classList.contains("mode-screen") === screen) return; + document.body.classList.toggle("mode-screen", screen); + $("mirror-view").hidden = !screen; + $("screen-panel").hidden = !screen; + if (screen) fitMirror(); else requestAnimationFrame(() => map.invalidateSize()); +} +document.querySelectorAll("#modes button").forEach((b) => b.addEventListener("click", () => setMode(b.dataset.mode))); + +function mirrorSend(msg) { + if (mirror.ws && mirror.ws.readyState === 1) mirror.ws.send(JSON.stringify(msg)); +} +// Ask for a fresh full frame, at most once a second (the phone's encoder stalls if asked too often). +function askKeyframe() { + const now = performance.now(); + if (now - mirror.lastKeyAsk < 1000) return; + mirror.lastKeyAsk = now; + mirrorSend({ t: "keyframe" }); +} +// The phone's name and iOS version above it: from the mirroring session, else the chosen device. +function renderMirrorDevice() { + let name = mirror.status.device_name, ios = mirror.status.ios; + if (!name) { + const udid = $("device-select").value; + const d = (state.devices || []).find((x) => !udid || x.udid === udid) || (state.status && state.status.device); + if (d) { name = d.name || "iPhone"; ios = d.ios_version; } + } + $("mirror-device").textContent = name ? `${name}${ios ? ` · iOS ${ios}` : ""}` : "No iPhone connected"; +} +$("device-select").addEventListener("change", renderMirrorDevice); +// The placeholder's home screen: a page of app icons and a dock. +(() => { + const colours = ["#ff9f0a", "#30d158", "#0a84ff", "#ff375f", "#bf5af2", "#64d2ff", "#ffd60a", "#ff453a", "#5e5ce6", "#66d4cf", "#ac8e68", "#8e8e93"]; + const icon = (i) => { const e = document.createElement("i"); e.style.setProperty("--c", colours[(i * 7) % colours.length]); return e; }; + $("sk-grid").append(...Array.from({ length: 24 }, (_, i) => icon(i))); + $("sk-dock").append(...Array.from({ length: 4 }, (_, i) => icon(i + 3))); +})(); + +function renderMirror(s) { + const before = mirrorTurn(); + if ((s.rotation || 0) !== (mirror.status.rotation || 0)) mirror.turn = 0; // the phone says which way it is now + mirror.status = s; + const on = s.state === "on", busy = s.state === "starting"; + $("btn-mirror").textContent = on ? "Stop mirroring" : busy ? "Starting…" : "Start mirroring"; + $("btn-mirror").classList.toggle("primary", !on); + $("btn-mirror").disabled = busy; + const box = $("mirror-status"); + box.className = "status" + (on ? " ok" : s.state === "error" ? " warn" : ""); + box.textContent = on + ? `Mirroring${s.width ? ` · ${s.width}×${s.height}` : ""}${s.audio ? " · with sound" : ""}${s.note ? `. ${s.note}` : ""}` + : s.state === "error" ? s.error : busy ? "Starting… (unlock the iPhone)" : "Not mirroring"; + for (const b of $("mirror-tools").querySelectorAll("button")) b.disabled = !on && b.id !== "btn-mirror-stats"; + $("mirror-empty").textContent = on && s.simulated ? "Simulator: there is no real screen. Clicks and keys are accepted and ignored." + : on ? "Waiting for the picture…" : s.state === "error" ? s.error : busy ? "Starting… Unlock the iPhone." : "Press Start mirroring to see the iPhone's screen here."; + if (mirrorTurn() !== before) turnPicture((mirrorTurn() - before + 360) % 360); + renderMirrorDevice(); + if (on) mirrorOpen(); + else if (!busy) mirrorClose(); +} + +// Clockwise degrees the picture is turned: the phone's own orientation plus the Rotate button. +const mirrorTurn = () => ((mirror.status.rotation || 0) + mirror.turn) % 360; +const mirrorCtx = () => $("mirror-canvas").getContext("2d", { alpha: false, desynchronized: true }); +function fitMirror() { + const c = $("mirror-canvas"), view = $("mirror-view"); + if (!c.width || !c.height) return; + const tools = $("mirror-tools").getBoundingClientRect(); + const wide = view.clientWidth > 760; + const w = view.clientWidth - 48 - (wide ? tools.width + 20 : 0), h = view.clientHeight - 48 - (wide ? 0 : tools.height + 10); + const k = Math.min(w / c.width, h / c.height); + c.style.width = `${Math.max(1, c.width * k)}px`; + c.style.height = `${Math.max(1, c.height * k)}px`; +} +new ResizeObserver(fitMirror).observe($("mirror-view")); + +// Draws `src` (w×h before turning) turned by `turn` degrees onto the canvas, resizing it if needed. +function drawTurned(src, w, h, turn) { + const c = $("mirror-canvas"), side = turn % 180 !== 0; + const cw = side ? h : w, ch = side ? w : h; + if (c.width !== cw || c.height !== ch) { + c.width = cw; + c.height = ch; + fitMirror(); + } + const ctx = mirrorCtx(); + ctx.setTransform(...({ 90: [0, 1, -1, 0, cw, 0], 180: [-1, 0, 0, -1, cw, ch], 270: [0, -1, 1, 0, 0, ch] }[turn] || [1, 0, 0, 1, 0, 0])); + ctx.drawImage(src, 0, 0); +} +// Turn what is on screen now (a still screen sends no new frame). +function turnPicture(delta) { + const c = $("mirror-canvas"); + if (!c.width || !delta) return; + const copy = new OffscreenCanvas(c.width, c.height); + copy.getContext("2d").drawImage(c, 0, 0); + drawTurned(copy, copy.width, copy.height, delta); +} +// Only the newest frame is drawn, once per screen refresh; frames that came in between are skipped. +function drawPending() { + mirror.drawQueued = false; + const f = mirror.frame; + mirror.frame = null; + if (!f) return; + drawTurned(f, f.displayWidth, f.displayHeight, mirrorTurn()); + f.close(); +} + +// A new decoder for the current setup; the old one is dropped (also after a decoding error, +// after which WebCodecs refuses further frames). Waits for a keyframe and asks for one. +function mirrorMakeDecoder() { + if (mirror.decoder && mirror.decoder.state !== "closed") mirror.decoder.close(); + mirror.decoder = null; + if (!mirror.config) return; + mirror.decoder = new VideoDecoder({ + output: (frame) => { + mirror.errors = 0; + const st = mirror.stats, t = mirror.pending.get(frame.timestamp); + if (st) { st.frames++; if (t !== undefined) { st.decodeMs += performance.now() - t; st.decoded++; } } + mirror.pending.delete(frame.timestamp); + if (mirror.frame) mirror.frame.close(); + mirror.frame = frame; + if (document.hidden) drawPending(); // no screen refreshes while hidden; keep recordings going + else if (!mirror.drawQueued) { mirror.drawQueued = true; requestAnimationFrame(drawPending); } + }, + error: () => { + if (++mirror.errors > 3) { + $("mirror-empty").textContent = "The picture can't be decoded. Press Restart stream, or stop and start mirroring."; + return; + } + mirrorMakeDecoder(); + }, + }); + mirror.decoder.configure(mirror.config); + mirror.waitKey = true; + mirror.lastKeyAsk = 0; + askKeyframe(); +} + +async function mirrorDecoder(view) { + const w = view.getUint16(1), h = view.getUint16(3), n = view.getUint8(5); + const codec = new TextDecoder().decode(new Uint8Array(view.buffer, 6, n)); + const config = { codec, description: new Uint8Array(view.buffer, 6 + n).slice(), codedWidth: w, codedHeight: h, optimizeForLatency: true }; + mirror.config = config; + if (mirror.decoder && mirror.decoder.state !== "closed") mirror.decoder.close(); + mirror.decoder = null; // frames that come meanwhile are dropped; the new decoder asks for a keyframe + if (mirror.supported[codec] === undefined) { + mirror.supported[codec] = typeof VideoDecoder !== "undefined" && (await VideoDecoder.isConfigSupported(config)).supported; + } + if (!mirror.supported[codec]) { + $("mirror-empty").textContent = "This computer can't decode the iPhone's video (HEVC). Update the graphics driver, or install " + + "“HEVC Video Extensions” from the Microsoft Store, then start mirroring again."; + return; + } + if (mirror.config === config) mirrorMakeDecoder(); +} + +function mirrorAudio(view) { + const a = mirror.audio; + if (!a) return; + const pcm = new Int16Array(view.buffer.slice(9)); + const n = pcm.length / 2; + const buf = a.ctx.createBuffer(2, n, 48000); + const l = buf.getChannelData(0), r = buf.getChannelData(1); + for (let i = 0; i < n; i++) { l[i] = pcm[2 * i] / 32768; r[i] = pcm[2 * i + 1] / 32768; } + const src = a.ctx.createBufferSource(); + src.buffer = buf; + src.connect(a.out); + // A small cushion against network jitter; if playback fell behind, catch up instead of drifting. + const now = a.ctx.currentTime; + if (mirror.nextAudio < now || mirror.nextAudio > now + 0.3) mirror.nextAudio = now + 0.06; + src.start(mirror.nextAudio); + mirror.nextAudio += n / 48000; +} + +function mirrorFrame(data, v) { + const st = mirror.stats; + if (st) st.bytes += data.byteLength; + const key = v.getUint8(1) === 1; + if (!mirror.decoder || mirror.decoder.state !== "configured") return; + if (mirror.waitKey && !key) { if (st) st.dropped++; askKeyframe(); return; } + // Behind by more than a few frames: drop until the next keyframe rather than lag further. + if (!key && mirror.decoder.decodeQueueSize > 6) { mirror.waitKey = true; if (st) st.dropped++; askKeyframe(); return; } + mirror.waitKey = false; + if (st && key) st.keys++; + const timestamp = Number(v.getBigUint64(2)); + mirror.pending.set(timestamp, performance.now()); + if (mirror.pending.size > 60) mirror.pending.clear(); + try { + mirror.decoder.decode(new EncodedVideoChunk({ type: key ? "key" : "delta", timestamp, data: new Uint8Array(data, 10) })); + } catch (_) { + mirrorMakeDecoder(); // the decoder refused the chunk (closed after an error) + } +} + +function mirrorOpen() { + if (mirror.ws) return; + const ws = new WebSocket(`ws://${location.host}/api/screen/ws`); + ws.binaryType = "arraybuffer"; + mirror.ws = ws; + ws.onmessage = (e) => { + if (typeof e.data === "string") { + const m = JSON.parse(e.data); + if (m.type === "status") renderMirror(m.status); + else if (m.type === "error") toast(m.detail, true); + return; + } + const v = new DataView(e.data); + const kind = v.getUint8(0); + if (kind === 1) mirrorDecoder(v); + else if (kind === 3) mirrorAudio(v); + else if (kind === 2) mirrorFrame(e.data, v); + }; + ws.onclose = () => { if (mirror.ws === ws) { mirror.ws = null; if (mirror.status.state === "on") setTimeout(mirrorOpen, 1000); } }; +} + +function mirrorClose() { + if (mirror.recorder) mirror.recorder.stop(); + const ws = mirror.ws; + mirror.ws = null; + if (ws) ws.close(); + if (mirror.decoder && mirror.decoder.state !== "closed") mirror.decoder.close(); + mirror.decoder = mirror.config = mirror.perf = null; + if (mirror.frame) { mirror.frame.close(); mirror.frame = null; } + if (mirror.audio) { mirror.audio.ctx.close(); mirror.audio = null; } + const c = $("mirror-canvas"); + c.removeAttribute("width"); + c.removeAttribute("height"); +} + +$("btn-mirror").onclick = guard(async () => { + if (mirror.status.state === "on") { renderMirror(await api("/api/screen/stop", { body: {} })); return; } + const audio = $("mirror-audio").checked; + if (audio && !mirror.audio) { + // Created on the click: browsers only allow sound that starts from a user action. + const ctx = new AudioContext({ sampleRate: 48000, latencyHint: "interactive" }); + const out = ctx.createGain(); + const tap = ctx.createMediaStreamDestination(); // recordings take the sound from here + out.connect(ctx.destination); + out.connect(tap); + mirror.audio = { ctx, out, tap }; + } + renderMirror({ state: "starting" }); + try { + renderMirror(await api("/api/screen/start", { body: { driver: $("driver").value, udid: $("device-select").value || null, audio } })); + } catch (e) { + renderMirror({ state: "error", error: e.message }); + throw e; + } +}); + +// ---- positions: the picture as shown (turned upright) vs. the phone's own screen +const clamp01 = (x) => Math.min(1, Math.max(0, x)); +// A point on the picture (fractions, 0..1) -> the same point on the phone's native screen. +function toPhone(u, v) { + const turn = mirrorTurn(); + const p = turn === 90 ? [v, 1 - u] : turn === 180 ? [1 - u, 1 - v] : turn === 270 ? [1 - v, u] : [u, v]; + return { x: clamp01(p[0]), y: clamp01(p[1]) }; +} +const mc = $("mirror-canvas"); +const viewPoint = (e) => { + const r = mc.getBoundingClientRect(); + return { u: clamp01((e.clientX - r.left) / r.width), v: clamp01((e.clientY - r.top) / r.height) }; +}; +function touch(phase, p) { + mirrorSend({ t: "touch", phase, ...toPhone(p.u, p.v) }); +} + +// The pointer over the screen: a small dot (the system cursor is hidden there) that dips on a press. +const cursorDot = $("mirror-cursor"); +function moveCursor(e) { + const r = mc.getBoundingClientRect(); + cursorDot.style.translate = `${e.clientX - r.left}px ${e.clientY - r.top}px`; +} +mc.addEventListener("pointerenter", (e) => { moveCursor(e); cursorDot.hidden = false; }); +mc.addEventListener("pointerleave", () => { if (!mirror.down) cursorDot.hidden = true; }); + +// A faint trail behind a dragging finger, fading in a quarter of a second. +const trail = { pts: [], raf: 0 }; +function addTrail(e) { + const r = mc.getBoundingClientRect(); + trail.pts.push({ x: e.clientX - r.left, y: e.clientY - r.top, t: performance.now() }); + if (!trail.raf) trail.raf = requestAnimationFrame(drawTrail); +} +function drawTrail() { + const tc = $("mirror-trail"), dpr = devicePixelRatio || 1, w = Math.round(tc.clientWidth * dpr), h = Math.round(tc.clientHeight * dpr); + if (tc.width !== w || tc.height !== h) { tc.width = w; tc.height = h; } + const ctx = tc.getContext("2d"), now = performance.now(), life = 260; + ctx.clearRect(0, 0, w, h); + trail.pts = trail.pts.filter((p) => now - p.t < life); + ctx.lineCap = "round"; + for (let i = 1; i < trail.pts.length; i++) { + const a = trail.pts[i - 1], b = trail.pts[i], f = 1 - (now - b.t) / life; + ctx.strokeStyle = `rgba(255, 255, 255, ${0.45 * f})`; + ctx.lineWidth = (1.5 + 2.5 * f) * dpr; + ctx.beginPath(); + ctx.moveTo(a.x * dpr, a.y * dpr); + ctx.lineTo(b.x * dpr, b.y * dpr); + ctx.stroke(); + } + trail.raf = trail.pts.length ? requestAnimationFrame(drawTrail) : 0; +} + +mc.addEventListener("pointerdown", (e) => { + if (e.button !== 0 || mirror.wheel || mirror.pinch) return; + mc.setPointerCapture(e.pointerId); + mirror.down = true; + cursorDot.classList.remove("up"); + cursorDot.classList.add("down"); + addTrail(e); + touch("down", viewPoint(e)); +}); +mc.addEventListener("pointermove", (e) => { + moveCursor(e); + if (!mirror.down) return; + addTrail(e); + // Pointer events can come faster than the screen refreshes: send the newest once per frame. + if (!mirror.moveTo) requestAnimationFrame(() => { if (mirror.down && mirror.moveTo) touch("move", mirror.moveTo); mirror.moveTo = null; }); + mirror.moveTo = viewPoint(e); +}); +const touchUp = (e) => { + if (!mirror.down) return; + mirror.down = false; + mirror.moveTo = null; + cursorDot.classList.remove("down"); + cursorDot.classList.add("up"); + touch("up", viewPoint(e)); +}; +mc.addEventListener("pointerup", touchUp); +mc.addEventListener("pointercancel", touchUp); +mc.addEventListener("contextmenu", (e) => { e.preventDefault(); mirrorSend({ t: "button", name: "home" }); }); + +// Mouse wheel: a finger drag that follows the wheel, lifted when the wheel rests. +// Ctrl + wheel (and a trackpad pinch, which arrives the same way): two fingers pinching. +mc.addEventListener("wheel", (e) => { + e.preventDefault(); + if (mirror.down || mirror.status.state !== "on") return; + const r = mc.getBoundingClientRect(), line = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? r.height : 1; + let dx = e.deltaX * line, dy = e.deltaY * line; + if (e.ctrlKey) return pinch(e, dy); + if (e.shiftKey && !dx) [dx, dy] = [dy, 0]; + const w = mirror.wheel || (mirror.wheel = { start: viewPoint(e), p: null }); + if (!w.p) { w.p = { ...w.start }; touch("down", w.p); } + w.p = { u: w.p.u - dx / r.width, v: w.p.v - dy / r.height }; + const out = w.p.u < 0.03 || w.p.u > 0.97 || w.p.v < 0.03 || w.p.v > 0.97; + w.p = { u: Math.min(0.97, Math.max(0.03, w.p.u)), v: Math.min(0.97, Math.max(0.03, w.p.v)) }; + touch("move", w.p); + clearTimeout(w.timer); + if (out) { touch("up", w.p); w.p = null; } // reached the edge: lift, the next turn starts again where it began + w.timer = setTimeout(() => { if (w.p) touch("up", w.p); mirror.wheel = null; }, 160); +}, { passive: false }); + +function pinch(e, dy) { + const p = mirror.pinch || (mirror.pinch = { c: viewPoint(e), d: 0.1, down: false }); + p.d = Math.min(0.42, Math.max(0.03, p.d * Math.exp(-dy * 0.004))); // wheel up (or fingers apart) zooms in + const a = toPhone(p.c.u, clamp01(p.c.v - p.d)), b = toPhone(p.c.u, clamp01(p.c.v + p.d)); + const send = (phase) => mirrorSend({ t: "touch", phase, x: a.x, y: a.y, x2: b.x, y2: b.y }); + send(p.down ? "move" : "down"); + p.down = true; + clearTimeout(p.timer); + p.timer = setTimeout(() => { send("up"); mirror.pinch = null; }, 200); +} + +// Buttons and gestures next to the screen (gestures are drawn by the app, turned with the phone). +$("mirror-tools").addEventListener("click", (e) => { + const b = e.target.closest("button"); + if (!b) return; + if (b.dataset.button) mirrorSend({ t: "button", name: b.dataset.button }); + else if (b.dataset.gesture) mirrorSend({ t: "gesture", name: b.dataset.gesture }); +}); +$("btn-mirror-rotate").onclick = () => { + mirror.turn = (mirror.turn + 90) % 360; + turnPicture(90); +}; +$("btn-mirror-refresh").onclick = guard(async () => { + await api("/api/screen/input", { body: { t: "refresh" } }); + toast("Restarting the stream…"); +}); + +// Keys go to the iPhone while the picture has focus (click it); the app's shortcuts stay off meanwhile. +mc.addEventListener("focus", () => mc.classList.add("typing")); +mc.addEventListener("blur", () => { mc.classList.remove("typing"); }); +for (const type of ["keydown", "keyup"]) { + mc.addEventListener(type, (e) => { + if (e.key === "Escape") { mc.blur(); return; } // never trap the keyboard in the picture + const usage = HID_KEYS[e.code]; + e.preventDefault(); + e.stopPropagation(); + if (usage && !(type === "keydown" && e.repeat)) mirrorSend({ t: "key", usage, down: type === "keydown" }); + }); +} + +// ---- screenshots and recordings: saved by the app to the folder chosen in Settings › Mirroring +const stamp = () => new Date().toISOString().slice(0, 23).replace(/[-:]/g, "").replace("T", "-").replace(".", ""); +async function saveCapture(blob, name) { + const r = await fetch(`/api/screen/save?name=${encodeURIComponent(name)}`, { method: "POST", body: blob }); + const data = await r.json().catch(() => ({})); + if (!r.ok) throw new Error(errorText(data, r.status)); + toast(`Saved to ${data.path}`); +} +function renderCaptureFolder() { + $("capture-folder").value = (settings().capture_folder || "").trim(); +} +function setCaptureFolder(path) { + settings().capture_folder = (path || "").trim(); + renderCaptureFolder(); + saveSettingsSoon(); +} +$("capture-folder").addEventListener("change", (e) => setCaptureFolder(e.target.value)); +$("btn-capture-browse").onclick = guard(async () => { + const { path } = await api("/api/pick-folder", { body: {} }); + if (path) setCaptureFolder(path); +}); +$("btn-mirror-shot").onclick = guard(async () => { + const c = $("mirror-canvas"); + if (!c.width) throw new Error("There is no picture yet. Wait for the iPhone's screen to appear."); + await saveCapture(await new Promise((r) => c.toBlob(r, "image/png")), `idevbench-screenshot-${stamp()}.png`); +}); +$("btn-mirror-rec").onclick = guard(async () => { + const btn = $("btn-mirror-rec"); + if (mirror.recorder) { mirror.recorder.stop(); return; } + const c = $("mirror-canvas"); + if (!c.width) throw new Error("There is no picture yet. Wait for the iPhone's screen to appear."); + const stream = c.captureStream(60); + if (mirror.audio) mirror.audio.tap.stream.getAudioTracks().forEach((t) => stream.addTrack(t)); + const type = ["video/mp4;codecs=avc1.640028,mp4a.40.2", "video/mp4", "video/webm;codecs=vp9,opus", "video/webm"].find((t) => MediaRecorder.isTypeSupported(t)); + const rec = new MediaRecorder(stream, { mimeType: type, videoBitsPerSecond: 12e6 }); + const parts = []; + rec.ondataavailable = (e) => { if (e.data.size) parts.push(e.data); }; + rec.onstop = guard(async () => { + mirror.recorder = null; + btn.classList.remove("recording"); + btn.querySelector("span").textContent = "Record"; + if (parts.length) await saveCapture(new Blob(parts, { type: rec.mimeType }), `idevbench-recording-${stamp()}.${rec.mimeType.startsWith("video/mp4") ? "mp4" : "webm"}`); + }); + rec.start(1000); + mirror.recorder = rec; + btn.classList.add("recording"); + btn.querySelector("span").textContent = "Stop recording"; +}); + +// ---- stats: the stream (frame rate, data rate, decode delay, dropped frames, sound buffer) +// and the iPhone itself (CPU, memory, GPU, its own frame rate, battery and temperature) +function newStats() { return { frames: 0, bytes: 0, decodeMs: 0, decoded: 0, dropped: 0, keys: 0, total: 0, at: performance.now() }; } +const fmt = (v, digits = 0, unit = "") => (v === null || v === undefined ? "–" : `${Number(v).toFixed(digits)}${unit}`); +const gb = (b) => (b === null || b === undefined ? "–" : (b / 2 ** 30).toFixed(1)); +setInterval(() => { + const st = mirror.stats, box = $("mirror-stats"); + if (!st || box.hidden) return; + const s = (performance.now() - st.at) / 1000, c = $("mirror-canvas"), p = mirror.perf; + st.total += st.dropped; + const sound = mirror.audio ? ` sound ${Math.max(0, Math.round((mirror.nextAudio - mirror.audio.ctx.currentTime) * 1000))} ms` : ""; + let text = `Stream ${Math.round(st.frames / s)} fps ${(st.bytes * 8 / s / 1e6).toFixed(1)} Mbit/s decode ${st.decoded ? (st.decodeMs / st.decoded).toFixed(1) : "–"} ms\n` + + ` ${c.width}×${c.height} dropped ${st.total} keyframes ${st.keys}${sound}`; + if (p) { + text += `\niPhone CPU ${fmt(p.cpu, 0, "%")}${p.cores ? ` of ${p.cores} cores` : ""} RAM ${gb(p.memory_used)}/${gb(p.memory_total)} GB GPU ${fmt(p.gpu, 0, "%")} ${fmt(p.fps, 0, " fps")}\n` + + ` battery ${fmt(p.battery, 0, "%")}${p.charging ? " (charging)" : ""} ${fmt(p.battery_temp, 1, " °C")}`; + } + box.textContent = text; + Object.assign(st, { frames: 0, bytes: 0, decodeMs: 0, decoded: 0, dropped: 0, at: performance.now() }); +}, 1000); +setInterval(async () => { + if (!mirror.stats || mirror.status.state !== "on" || mirror.status.simulated) return; + try { mirror.perf = await api("/api/screen/perf"); } catch (_) { /* not mirroring any more */ } +}, 2000); +function setStats(on) { + mirror.stats = on ? newStats() : null; + $("mirror-stats").hidden = !on; + $("mirror-stats").textContent = "Measuring…"; + $("btn-mirror-stats").classList.toggle("on", on); + try { localStorage.setItem("ls-mirror-stats", on ? "1" : ""); } catch (_) { /* storage blocked */ } +} +$("btn-mirror-stats").onclick = () => setStats(!mirror.stats); +try { if (localStorage.getItem("ls-mirror-stats")) setStats(true); } catch (_) { /* storage blocked */ } + +// ------------------------------------------------------------------ AI agents (MCP) +// One prompt for any agent that can set itself up (Claude Code, Codex, Cursor, Gemini CLI, ...); +// Claude Desktop can't, so the app writes its settings file instead. +async function renderAgentSetup() { + const m = await api("/api/mcp/setup"); + const quote = (a) => (/[\s"]/.test(a) ? JSON.stringify(a) : a); + const cmdLine = [m.command, ...m.args].map(quote).join(" "); + const env = Object.entries(m.env || {}).map(([k, v]) => `${k}=${v}`).join(", "); + $("agent-prompt").value = [ + "Connect yourself to iDevBench, an app on my computer that controls my iPhone (its screen and its GPS location), by adding it as an MCP server named \"idevbench\". Do the setup yourself with your own MCP settings or commands, using whichever of these your app supports:", + `- Streamable HTTP server at ${m.url} (for example: claude mcp add --transport http --scope user idevbench ${m.url})`, + `- A local stdio server started with: ${cmdLine}${env ? ` (environment: ${env})` : ""} (for example: codex mcp add idevbench -- ${cmdLine})`, + "Add it for my user account, not just this folder. Then reload your tools if needed and call the idevbench \"guide\" tool, which explains how to use the phone. If you can't add MCP servers yourself, tell me exactly where to paste these settings.", + ].join("\n"); + $("agent-claude-status").textContent = m.claude_desktop ? "" : "Claude Desktop doesn't seem to be installed."; +} +$("btn-agent-setup").onclick = () => openSettings("agents"); +$("btn-agent-copy").onclick = guard(async () => { + if (!$("agent-prompt").value) await renderAgentSetup(); + await navigator.clipboard.writeText($("agent-prompt").value); + toast("Prompt copied. Paste it into your AI agent."); +}); +$("btn-agent-claude").onclick = guard(async () => { + await api("/api/mcp/claude-desktop", { body: {} }); + $("agent-claude-status").textContent = "Added. Quit Claude completely and open it again."; +}); + // ------------------------------------------------------------------ boot wireInfoButtons(); wireSections(); @@ -3235,6 +3823,8 @@ function notifyReady() { (async () => { try { await loadStore(); } finally { requestAnimationFrame(() => requestAnimationFrame(notifyReady)); } await refreshGoogleStatus(); + api("/api/screen").then(renderMirror, () => {}); + try { if (localStorage.getItem("ls-mode") === "screen") setMode("screen"); } catch (_) { /* storage blocked */ } await poll(); refreshDevices(false); if (!settings().tutorial_done) openTutorial(0); diff --git a/ui/index.html b/ui/index.html index 6a7ad09..0edfd6b 100644 --- a/ui/index.html +++ b/ui/index.html @@ -4,7 +4,7 @@ - Location Spoofer + iDevBench