From 9ab16e80b1e03b84568043b210bb57f55543d0f6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 14:46:27 +0000 Subject: [PATCH 01/11] Several iPhones at once and Wi-Fi connections (experimental, both editions) - More iPhones: extra phones follow the main one. The player still talks to one device; every position is also handed to each mirror, which sends it from its own coalescing queue (Python: mirrors.py MirrorLink/FanOut, Rust: device/mirror.rs), so a slow or lost phone never holds up playback. Lost phones are marked until removed; removing one clears its location. API: POST /api/mirrors, DELETE /api/mirrors/{udid}, status "mirrors". In Rust a mirror connects without the device lock held. - Connection choice (auto / usb / network) for connect and mirrors, a device list that shows USB, Wi-Fi or both, and "Allow Wi-Fi connection" (lockdown EnableWifiConnections). Browser edition: a second iOS 17+ phone or an iOS 17+ phone over Wi-Fi falls back to tunneld, because pymobiledevice3 allows one userspace tunnel per process. - The Simulator has two phones. Tests in both editions; test notes in docs/testing/multiple-iphones-and-wifi.md. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GWYAdn8QS1XrFZScnrMdvK --- CHANGELOG.md | 4 + browser/spoofer/device/base.py | 9 +- browser/spoofer/device/cli.py | 2 +- browser/spoofer/device/mock.py | 21 +- browser/spoofer/device/pmd3.py | 91 +++++++-- browser/spoofer/mirrors.py | 146 ++++++++++++++ browser/spoofer/server.py | 85 +++++++- browser/tests/test_mirrors.py | 229 ++++++++++++++++++++++ docs/testing/multiple-iphones-and-wifi.md | 31 +++ standalone/src/device/idev.rs | 85 ++++++-- standalone/src/device/mirror.rs | 213 ++++++++++++++++++++ standalone/src/device/mock.rs | 24 ++- standalone/src/device/mod.rs | 145 +++++++++++++- standalone/src/player.rs | 2 +- standalone/src/server.rs | 203 ++++++++++++++++++- ui/app.js | 71 ++++++- ui/index.html | 24 +++ ui/style.css | 11 ++ 18 files changed, 1326 insertions(+), 70 deletions(-) create mode 100644 browser/spoofer/mirrors.py create mode 100644 browser/tests/test_mirrors.py create mode 100644 docs/testing/multiple-iphones-and-wifi.md create mode 100644 standalone/src/device/mirror.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c4a27e..d75d2fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ Test builds from the `dev` branch are marked as pre-releases. ## Unreleased (dev) +### Experimental (`feature-testing` only; 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 - A real dark map: the default map is now OpenFreeMap, drawn from vector data, so it is sharp at every zoom and has a true dark style (with colours tuned so water, parks, the road hierarchy and labels stand out) and a light style. Free, no account or key. Choose the map in *Settings › Appearance › Map* (OpenFreeMap, OpenStreetMap, Topographic, Satellite) or with the map's layer button; the choice is remembered. Without WebGL, or if OpenFreeMap can't be reached, the app says so and shows OpenStreetMap. - The tutorial has an animated drawing for each step (the route being drawn, the cable and Trust prompt, the Developer Mode switch, a position moving along a route), and each step slides in. 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..94e22db 100644 --- a/browser/spoofer/device/pmd3.py +++ b/browser/spoofer/device/pmd3.py @@ -45,6 +45,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 +78,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 +105,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 +115,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 +161,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: @@ -229,5 +268,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/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/server.py b/browser/spoofer/server.py index ace3b86..9b5ef8c 100644 --- a/browser/spoofer/server.py +++ b/browser/spoofer/server.py @@ -22,6 +22,7 @@ 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 .player import Player from .profile import ( Leg, @@ -54,7 +55,10 @@ 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 @@ -63,6 +67,17 @@ def __init__(self) -> None: 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) @@ -90,6 +105,7 @@ async def lifespan(app: FastAPI): upd_task.cancel() try: await app.state.s.player.stop() + await app.state.s.drop_mirrors() for d in app.state.s.drivers.values(): await d.disconnect() finally: @@ -153,6 +169,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): @@ -265,13 +294,14 @@ async def status(): return { "version": __version__, "app": "browser", - "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()], } @@ -285,9 +315,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()} @@ -295,10 +329,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()} 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/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/standalone/src/device/idev.rs b/standalone/src/device/idev.rs index 8115bdc..c64ec5c 100644 --- a/standalone/src/device/idev.rs +++ b/standalone/src/device/idev.rs @@ -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. +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 { @@ -191,9 +226,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))?; @@ -391,8 +426,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/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/server.rs b/standalone/src/server.rs index ded621a..b3231cc 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::{geo, gmaps_links, gpx, routing, store::Store, updater::Updater}; @@ -10,7 +10,7 @@ use axum::{ extract::{DefaultBodyLimit, Multipart, Path, Query, State}, http::{header, StatusCode}, response::{IntoResponse, Response}, - routing::{get, post}, + routing::{delete, get, post}, Json, Router, }; use rust_embed::RustEmbed; @@ -81,6 +81,7 @@ impl AppState { } // ---------------------------------------------------------------- errors +#[derive(Debug)] pub struct ApiError(pub u16, pub String); impl IntoResponse for ApiError { @@ -110,6 +111,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)) @@ -196,11 +200,12 @@ async fn status(State(app): State) -> R { "app": "standalone", "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(), }))) } @@ -219,15 +224,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; @@ -1008,6 +1061,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(); diff --git a/ui/app.js b/ui/app.js index 6d5e0ba..366a1cd 100644 --- a/ui/app.js +++ b/ui/app.js @@ -735,6 +735,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 })); @@ -754,7 +755,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; @@ -768,6 +769,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: {} }); @@ -783,12 +842,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"; box.textContent = state.devicesError; chip.className = "chip warn"; chip.textContent = "Not ready"; @@ -2552,7 +2613,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 = {}; diff --git a/ui/index.html b/ui/index.html index 2dd25d8..b41f544 100644 --- a/ui/index.html +++ b/ui/index.html @@ -111,9 +111,33 @@

Location Spoofer

Not connected
+ +
Device tools
+
+ + +
+
+
diff --git a/ui/style.css b/ui/style.css index 48add8c..d4f1561 100644 --- a/ui/style.css +++ b/ui/style.css @@ -339,6 +339,17 @@ button.info:hover, button.info:focus-visible { color: var(--accent); opacity: 1; color: var(--text); background: var(--panel); border: 1px solid var(--border-strong); border-radius: var(--radius); box-shadow: var(--shadow-pop); } .tool-list { display: flex; flex-direction: column; gap: 4px; } +/* more iPhones (mirrors) */ +.mirrors { display: flex; flex-direction: column; gap: 6px; padding: 8px 10px; border-radius: var(--radius); background: var(--well); } +.mirrors-head { display: flex; align-items: center; gap: 8px; } +.mirrors-title { font-size: 12px; font-weight: 600; } +.mirrors-head .info { margin-left: auto; } +.mirror-list { display: flex; flex-direction: column; gap: 4px; margin: 0; padding: 0; list-style: none; } +.mirror-list:empty { display: none; } +.mirror-list li { display: flex; align-items: center; gap: 8px; min-height: 26px; animation: panel-in .2s var(--ease-out); } +.mirror-list li .status { flex: 1; min-width: 0; } +.mirror-list li .status span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.mirror-list li button { height: 24px; min-height: 24px; } .tool { display: flex; align-items: center; gap: 6px; } .tool > button:first-child { flex: 1; justify-content: flex-start; } .exp label.check button.info { margin-left: auto; } From 2d2285448849c50e22faeed0531e2608783fefae Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 08:52:37 +0000 Subject: [PATCH 02/11] Make README sections collapsible and group features Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01GWYAdpc1fQ215D2g8Kru2B --- README.md | 189 ++++++++++++++++++++++++++++++++++-------------------- 1 file changed, 121 insertions(+), 68 deletions(-) diff --git a/README.md b/README.md index 3b0cd1c..053a56f 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ Teleport anywhere, drive routes that follow real roads at realistic speeds (with ⬇ Download the app (Standalone) · Browser edition · Getting started · + Features · Apple Devices (required) · Privacy · Terms @@ -20,41 +21,9 @@ Teleport anywhere, drive routes that follow real roads at realistic speeds (with > **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? @@ -70,38 +39,6 @@ Most people should use the **standalone app**. The browser edition exists for iP 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. - ## Getting started 1. **Install Apple's iPhone software.** Get [**Apple Devices** from the Microsoft Store](https://apps.microsoft.com/detail/9np83lwlpz9k) (free, made by Apple; iTunes also works). It lets Windows talk to an iPhone. You don't need to keep its window open. @@ -114,13 +51,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. * A USB cable. * An internet connection for maps and road routing. -### Troubleshooting +
+ +
+Troubleshooting | Message | What to do | |---|---| @@ -134,14 +76,123 @@ Both have the same look and features, and both update themselves. | 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 | | 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. + +
+ +
+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,6 +201,8 @@ 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). From ddc2bddda62facf63aa667ab5ab2b991fe4982a2 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 15:52:51 +0000 Subject: [PATCH 03/11] Add ponytail skills and enable the midstream plugin for this repo Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01GWYAdnU1u7fGQpQgUmyrcZ --- .claude/settings.json | 10 +++ .claude/skills/ponytail-audit/SKILL.md | 103 ++++++++++++++++++++++++ .claude/skills/ponytail-debt/SKILL.md | 44 ++++++++++ .claude/skills/ponytail-gain/SKILL.md | 52 ++++++++++++ .claude/skills/ponytail-help/SKILL.md | 76 +++++++++++++++++ .claude/skills/ponytail-review/SKILL.md | 101 +++++++++++++++++++++++ .claude/skills/ponytail/LICENSE | 21 +++++ .claude/skills/ponytail/SKILL.md | 52 ++++++++++++ 8 files changed, 459 insertions(+) create mode 100644 .claude/settings.json create mode 100644 .claude/skills/ponytail-audit/SKILL.md create mode 100644 .claude/skills/ponytail-debt/SKILL.md create mode 100644 .claude/skills/ponytail-gain/SKILL.md create mode 100644 .claude/skills/ponytail-help/SKILL.md create mode 100644 .claude/skills/ponytail-review/SKILL.md create mode 100644 .claude/skills/ponytail/LICENSE create mode 100644 .claude/skills/ponytail/SKILL.md 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. | From e8ba3eca8bcad5d75f7c62c044d06a4312d7a94e Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 16:17:14 +0000 Subject: [PATCH 04/11] Rename the app to Sideport; Terms and Privacy cover mirroring and the API MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Location Spoofer becomes Sideport, a toolkit for working with an iPhone from Windows. Every name people see changes: the window and page title, the side menu, Settings › About, release titles and notes, the README, CONTRIBUTING, the changelog, GPX "creator", user agents, the backup file name and the executable's version info. Kept on purpose, so nothing breaks for people who already use the app: - release file names (LocationSpooferStandalone.exe, LocationSpooferBrowser.exe), which installed copies look for when they update themselves; - data folders, so settings, favourites, routes and offline maps carry over; - the repository URLs, which GitHub redirects after a rename; - LICENSE and browser/NOTICE, whose terms name Location Spoofer. Terms of Use and Privacy Policy now describe screen mirroring, device sound, remote control, screenshots and recordings, and the opt-in API for other programs (key kept in api.json, never in backups). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GWYAdk7FBJL1zvtWFNTApV --- .github/release-notes/browser.md | 2 +- .github/release-notes/standalone.md | 2 +- .github/workflows/release.yml | 4 +- CHANGELOG.md | 1 + CONTRIBUTING.md | 2 +- PRIVACY.md | 16 ++++-- README.md | 20 ++++---- TERMS.md | 57 +++++++++++++++------- THIRD_PARTY_NOTICES.md | 2 +- browser/run_mac_linux.sh | 2 +- browser/run_windows.bat | 2 +- browser/spoofer/__init__.py | 2 +- browser/spoofer/__main__.py | 6 +-- browser/spoofer/gpx_io.py | 2 +- browser/spoofer/offline.py | 2 +- browser/spoofer/routing.py | 2 +- browser/spoofer/server.py | 2 +- browser/spoofer/updater.py | 2 +- browser/tests/test_offline.py | 2 +- standalone/Cargo.toml | 6 +-- standalone/build.rs | 4 +- standalone/packaging/msix/AppxManifest.xml | 6 +-- standalone/src/device/idev.rs | 2 +- standalone/src/gpx.rs | 2 +- standalone/src/main.rs | 14 +++--- standalone/src/offline.rs | 2 +- standalone/src/routing.rs | 2 +- ui/app.js | 6 +-- ui/index.html | 8 +-- ui/style.css | 2 +- 30 files changed, 109 insertions(+), 75 deletions(-) diff --git a/.github/release-notes/browser.md b/.github/release-notes/browser.md index 98e7c1d..92afc26 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} +**Sideport 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..6001c60 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} +**Sideport {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..47dc1f8 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 "Sideport 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 "Sideport $STANDALONE_VERSION$LABEL" --notes-file notes-standalone.md --target "$GITHUB_SHA" $FLAGS_SA diff --git a/CHANGELOG.md b/CHANGELOG.md index a37f150..5906107 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ Test builds from the `dev` branch are marked as pre-releases. ## Unreleased (dev) ### New +- **New name: Sideport.** Location Spoofer is now called Sideport, 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:** [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*). - **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. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 03df65e..ab47f60 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. +Sideport (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 diff --git a/PRIVACY.md b/PRIVACY.md index 98d506c..e0742d5 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 Sideport, 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, where you choose. +* The **API for other programs** is off by default. If you turn it on, programs on your computer that have the API key can receive the phone's screen and sound and control the phone. What they do with it is covered by their own privacy policies. ## What is stored on your computer @@ -22,9 +24,13 @@ 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 | +| API key and the API on/off setting (only if you turn the API on) | `api.json` next to `data.json` | So programs you trust can use the API. It is never included in backup exports | 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 +49,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 053a56f..22c13d8 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,15 @@ -

Location Spoofer icon

+

Sideport icon

-

Location Spoofer

+

Sideport

-

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. No accounts, no telemetry.

+ +

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

Website and live demo · - ⬇ Download the app (Standalone) · + ⬇ Download Sideport · Browser edition · Getting started · Features · @@ -37,7 +39,7 @@ Most people should use the **standalone app**. The browser edition exists for iP | iOS 17.4 and newer, iOS 16 and older | ✅ | ✅ | | iOS 17.0–17.3 | ❌ | ✅ (needs administrator permission once per session) | -Both have the same look and features, and both update themselves. +Both have the same look and features, 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 @@ -73,7 +75,7 @@ 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 Sideport window, end any **location-spoofer** or **LocationSpooferStandalone** task in Task Manager, then open the new file | | 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*) |

@@ -209,7 +211,7 @@ The app has no accounts, no analytics and no telemetry. Your favourites, routes ## Licence -Location Spoofer is free to download and use, but it is **not open source**: © 2026 YK3D, all rights reserved. +Sideport 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). @@ -217,4 +219,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. +Sideport 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/TERMS.md b/TERMS.md index fd612cb..8251b60 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 Sideport, 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"), if you turn it on. + +It is intended for app development and testing, demonstrations, education, accessibility and personal privacy. ## 2. Acceptable use @@ -15,23 +22,37 @@ 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 + +The API is off until you turn it on in *Settings › Developer API*. When it is on, any program on your computer that has the API key can do what the app can do: read the device's screen, control the device and change its location. Only give the key to programs you trust, and create a new key (which stops the old one working) if you no longer trust one. Programs that use the API are not made by YK3D, and their own terms and privacy policies apply to them. + +## 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 +64,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..34a1ce6 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. +Sideport (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 diff --git a/browser/run_mac_linux.sh b/browser/run_mac_linux.sh index ef74eee..f01bbda 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 +# Sideport 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..8d238d3 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 Sideport 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..a3ffe6d 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. +"""Sideport (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..5769162 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"Sideport 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="Sideport 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") @@ -162,7 +162,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 Sideport 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/gpx_io.py b/browser/spoofer/gpx_io.py index 3489c8c..a529e30 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/offline.py b/browser/spoofer/offline.py index a8d4b74..bc32aac 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"Sideport/{__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..91cdf78 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 = "Sideport/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/server.py b/browser/spoofer/server.py index 146c109..6ab1f69 100644 --- a/browser/spoofer/server.py +++ b/browser/spoofer/server.py @@ -100,7 +100,7 @@ async def lifespan(app: FastAPI): await routing.close() -app = FastAPI(title="iPhone Location Spoofer", version=__version__, lifespan=lifespan) +app = FastAPI(title="Sideport Browser Edition", version=__version__, lifespan=lifespan) _LOCAL_HOSTS = ("127.0.0.1", "localhost") diff --git a/browser/spoofer/updater.py b/browser/spoofer/updater.py index 00818c1..fd0471b 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"Sideport/{__version__}" def parse_version(text: str) -> tuple[int, ...]: diff --git a/browser/tests/test_offline.py b/browser/tests/test_offline.py index 784636d..a454bac 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("Sideport/") 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/standalone/Cargo.toml b/standalone/Cargo.toml index cac22e1..5183cdf 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 = "Sideport: standalone desktop app for working with an iPhone over USB" license-file = "../LICENSE" authors = ["YK3D"] publish = false @@ -78,5 +78,5 @@ strip = true panic = "unwind" [package.metadata.winres] -ProductName = "Location Spoofer" -FileDescription = "Location Spoofer (standalone)" +ProductName = "Sideport" +FileDescription = "Sideport" diff --git a/standalone/build.rs b/standalone/build.rs index 3cfbdc2..dca653d 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", "Sideport"); + res.set("FileDescription", "Sideport"); 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..be1ec20 100644 --- a/standalone/packaging/msix/AppxManifest.xml +++ b/standalone/packaging/msix/AppxManifest.xml @@ -17,10 +17,10 @@ ProcessorArchitecture="x64" /> - GPS Route Simulator + Sideport 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 @@ - Result<(), String> { 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("Sideport")).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)) } diff --git a/standalone/src/gpx.rs b/standalone/src/gpx.rs index 11c7989..f998aea 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..8067d64 100644 --- a/standalone/src/main.rs +++ b/standalone/src/main.rs @@ -1,4 +1,4 @@ -//! Location Spoofer — standalone desktop app. +//! Sideport (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 @@ -132,20 +132,20 @@ fn main() { None => start_server(&rt, bind(0).expect("bind"), upd), }, }; - tracing::info!("Location Spoofer running at {url}"); + tracing::info!("Sideport 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!("Sideport · feature test #{pr}"), + None => "Sideport".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!("Sideport is running at {url} — press Ctrl+C to quit."); rt.block_on(async { match server_task { Some(app) => { @@ -189,7 +189,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 Sideport 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 +230,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!("Sideport (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..91906f5 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!("Sideport/{} (+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/routing.rs b/standalone/src/routing.rs index 929bb2d..15b4fa2 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 = "Sideport-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/ui/app.js b/ui/app.js index 2f45dc7..541ecea 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. +/* Sideport — 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"; @@ -2798,7 +2798,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: "sideport-backup.json" }); document.body.append(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(a.href), 1000); }; @@ -3180,7 +3180,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 = `Sideport ${$("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); diff --git a/ui/index.html b/ui/index.html index 6a7ad09..4c8a04e 100644 --- a/ui/index.html +++ b/ui/index.html @@ -4,7 +4,7 @@ - Location Spoofer + Sideport