diff --git a/AGENTS.md b/AGENTS.md index 4e094d15..485563b2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -22,7 +22,7 @@ ipaforge/ ├── packages/ │ ├── kernel/ # IPAForgeError/ErrorCode, ports (Logger, HttpClient, SecretStore, FileSource), bytes and text utils, plist │ ├── signer/ # Mach-O code signing (CodeDirectory, CodeResources, entitlements, CMS, fat, bundles, IPA) -│ ├── device/ # usbmux, lockdown, pairing (classic and iOS 17.4+ remote), AFC, house_arrest, installation_proxy +│ ├── device/ # usbmux, lockdown, pairing (classic and iOS 17.4+ remote), AFC, house_arrest, installation_proxy, Wi-Fi without usbmuxd (mDNS) │ ├── apple/ # GSA auth + 2FA, anisette provider chain, developer services API │ ├── catalog/ # release sources (GitHub API), downloads, cache, AltStore-format app sources │ ├── installer/ # pipelines/flows, diagnostics, Engine facade @@ -47,7 +47,7 @@ ipaforge/ | `fixtures/signer/generate.sh` | Regenerates the Apple `codesign` golden fixtures (macOS) | | `packages/signer/scripts/compare-real-cert.ts` | Maintainer check against a real Apple Development `.p12` | | `packages/device/src/index.ts` | Public device API (`createDeviceManager`: pairing, install, profiles, app files, checks) | -| `apps/desktop/src/main/adapters/` | Node adapters: usbmuxd transport, pinned TLS, file source | +| `apps/desktop/src/main/adapters/` | Node adapters: usbmuxd transport, pinned TLS, file source, and for Wi-Fi without usbmuxd direct TCP and the mDNS socket (`network/`) | | `apps/desktop/scripts/device-probe.ts` | Maintainer CLI against a real device | | `packages/apple/src/index.ts` | Public Apple API (`createAppleAccounts`: anisette, sign-in + 2FA, app tokens, saved accounts) | | `apps/desktop/scripts/apple-probe.ts` | Maintainer CLI: sign in with real Apple IDs | diff --git a/apps/desktop/build/mac-locales/ar.lproj/InfoPlist.strings b/apps/desktop/build/mac-locales/ar.lproj/InfoPlist.strings new file mode 100644 index 00000000..e8704200 --- /dev/null +++ b/apps/desktop/build/mac-locales/ar.lproj/InfoPlist.strings @@ -0,0 +1,2 @@ +/* macOS shows this when IPAForge first looks for devices on the local network. */ +"NSLocalNetworkUsageDescription" = "يبحث IPAForge عن جهاز iPhone وiPad في الشبكة المحلية، ليتمكن من تثبيت التطبيقات عبر Wi-Fi دون كابل."; diff --git a/apps/desktop/build/mac-locales/de.lproj/InfoPlist.strings b/apps/desktop/build/mac-locales/de.lproj/InfoPlist.strings new file mode 100644 index 00000000..82d262b6 --- /dev/null +++ b/apps/desktop/build/mac-locales/de.lproj/InfoPlist.strings @@ -0,0 +1,2 @@ +/* macOS shows this when IPAForge first looks for devices on the local network. */ +"NSLocalNetworkUsageDescription" = "IPAForge sucht dein iPhone und iPad im lokalen Netzwerk, damit es Apps ohne Kabel über WLAN installieren kann."; diff --git a/apps/desktop/build/mac-locales/en.lproj/InfoPlist.strings b/apps/desktop/build/mac-locales/en.lproj/InfoPlist.strings new file mode 100644 index 00000000..5736ee7e --- /dev/null +++ b/apps/desktop/build/mac-locales/en.lproj/InfoPlist.strings @@ -0,0 +1,2 @@ +/* macOS shows this when IPAForge first looks for devices on the local network. */ +"NSLocalNetworkUsageDescription" = "IPAForge looks for your iPhone and iPad on the local network, so it can install apps over Wi-Fi without a cable."; diff --git a/apps/desktop/build/mac-locales/ja.lproj/InfoPlist.strings b/apps/desktop/build/mac-locales/ja.lproj/InfoPlist.strings new file mode 100644 index 00000000..cbe76106 --- /dev/null +++ b/apps/desktop/build/mac-locales/ja.lproj/InfoPlist.strings @@ -0,0 +1,2 @@ +/* macOS shows this when IPAForge first looks for devices on the local network. */ +"NSLocalNetworkUsageDescription" = "IPAForge はローカルネットワーク上の iPhone と iPad を探し、ケーブルなしで Wi-Fi 経由でアプリをインストールします。"; diff --git a/apps/desktop/build/mac-locales/ro.lproj/InfoPlist.strings b/apps/desktop/build/mac-locales/ro.lproj/InfoPlist.strings new file mode 100644 index 00000000..d42f2ec2 --- /dev/null +++ b/apps/desktop/build/mac-locales/ro.lproj/InfoPlist.strings @@ -0,0 +1,2 @@ +/* macOS shows this when IPAForge first looks for devices on the local network. */ +"NSLocalNetworkUsageDescription" = "IPAForge caută iPhone-ul și iPad-ul tău în rețeaua locală, ca să poată instala aplicații prin Wi-Fi, fără cablu."; diff --git a/apps/desktop/build/mac-locales/ru.lproj/InfoPlist.strings b/apps/desktop/build/mac-locales/ru.lproj/InfoPlist.strings new file mode 100644 index 00000000..81066537 --- /dev/null +++ b/apps/desktop/build/mac-locales/ru.lproj/InfoPlist.strings @@ -0,0 +1,2 @@ +/* macOS shows this when IPAForge first looks for devices on the local network. */ +"NSLocalNetworkUsageDescription" = "IPAForge ищет ваш iPhone и iPad в локальной сети, чтобы устанавливать приложения по Wi-Fi без кабеля."; diff --git a/apps/desktop/electron-builder.yml b/apps/desktop/electron-builder.yml index 1d5e79f7..b70b35dd 100644 --- a/apps/desktop/electron-builder.yml +++ b/apps/desktop/electron-builder.yml @@ -38,6 +38,17 @@ mac: identity: '-' hardenedRuntime: false notarize: false + # Finding iPhones on Wi-Fi: macOS asks before an app looks on the local network, with this reason (translated in + # build/mac-locales), and only for the Bonjour types listed. + extendInfo: + NSLocalNetworkUsageDescription: IPAForge looks for your iPhone and iPad on the local network, so it can install apps over Wi-Fi without a cable. + NSBonjourServices: + - _apple-mobdev2._tcp + - _remotepairing._tcp + extraResources: + - from: build/mac-locales + to: . + filter: ['**/*'] dmg: title: ${productName} ${version} diff --git a/apps/desktop/scripts/device-probe.ts b/apps/desktop/scripts/device-probe.ts index 0a117eaf..ca3ad6c2 100644 --- a/apps/desktop/scripts/device-probe.ts +++ b/apps/desktop/scripts/device-probe.ts @@ -13,6 +13,10 @@ // pnpm --filter @ipaforge/desktop device-probe afc-speed [--mb 32] (times AFC writes with each chunk size) // pnpm --filter @ipaforge/desktop device-probe reveal-devmode // pnpm --filter @ipaforge/desktop device-probe rp-pair (iOS 17.4+: makes a remote pairing, then verifies it) +// pnpm --filter @ipaforge/desktop device-probe wifi-list [--udid ] (finds known devices on Wi-Fi, no usbmuxd) +// +// --direct (any device command): reach the device straight over Wi-Fi only, skipping the cable and usbmuxd. The +// devices to look for are usbmuxd's and --udid; their pair records come from usbmuxd. // // `pair` (and any command on a device without a pair record) waits for the OS to pair: unlock the device and tap // Trust, and the OS stores its record in usbmuxd. If none appears within the timeout, or with --own, IPAForge pairs diff --git a/apps/desktop/src/main/adapters/network/local-network-error.ts b/apps/desktop/src/main/adapters/network/local-network-error.ts new file mode 100644 index 00000000..41d2823d --- /dev/null +++ b/apps/desktop/src/main/adapters/network/local-network-error.ts @@ -0,0 +1,20 @@ +// What a refused local network send looks like: macOS answers with "no route to host" (or "operation not +// permitted") when the user hasn't allowed IPAForge to find devices on the local network. +import { ErrorCode, IPAForgeError } from '@ipaforge/kernel' + +const DENIED_CODES = new Set(['EHOSTUNREACH', 'EPERM', 'EACCES']) + +/** The error to throw for a failed local network send: `device.local_network_denied` when the OS refused it. */ +export const localNetworkError = ( + cause: unknown, + platform: NodeJS.Platform = process.platform +): IPAForgeError => { + const code = (cause as { code?: unknown } | undefined)?.code + const isDenied = + platform === 'darwin' && typeof code === 'string' && DENIED_CODES.has(code) + + return new IPAForgeError( + isDenied ? ErrorCode.LocalNetworkDenied : ErrorCode.DeviceDisconnected, + { cause, data: { code } } + ) +} diff --git a/apps/desktop/src/main/adapters/network/multicast-socket.ts b/apps/desktop/src/main/adapters/network/multicast-socket.ts new file mode 100644 index 00000000..1af4f8e8 --- /dev/null +++ b/apps/desktop/src/main/adapters/network/multicast-socket.ts @@ -0,0 +1,84 @@ +// Node `openMulticast`: a UDP socket on a port of its own (never 5353, so it never competes with Bonjour or +// avahi), sending each mDNS query out of every IPv4 interface, and hearing the answers sent straight back to it. +import { createSocket, type Socket } from 'node:dgram' +import { networkInterfaces } from 'node:os' + +import { localNetworkError } from '@desktop/main/adapters/network/local-network-error.ts' +import { + type Datagram, + MDNS_GROUP, + MDNS_PORT, + type MulticastSocket +} from '@ipaforge/device' + +const MULTICAST_TTL = 255 + +/** The computer's IPv4 addresses on real networks (not loopback). */ +const lanAddresses = (): string[] => + Object.values(networkInterfaces()) + .flatMap((addresses) => addresses ?? []) + .filter((address) => address.family === 'IPv4' && !address.internal) + .map((address) => address.address) + +const bind = (socket: Socket): Promise => + new Promise((resolve, reject) => { + socket.once('error', reject) + socket.bind(0, () => { + socket.off('error', reject) + resolve() + }) + }) + +const sendOn = ( + socket: Socket, + bytes: Uint8Array, + from: string +): Promise => + new Promise((resolve, reject) => { + try { + socket.setMulticastInterface(from) + } catch (error) { + reject(error) + return + } + socket.send(bytes, MDNS_PORT, MDNS_GROUP, (error) => + error ? reject(error) : resolve() + ) + }) + +export const openMulticast = async (): Promise => { + const socket = createSocket({ type: 'udp4' }) + await bind(socket) + socket.setMulticastTTL(MULTICAST_TTL) + const listeners = new Set<(datagram: Datagram) => void>() + socket.on('message', (bytes, from) => { + const datagram = { bytes: new Uint8Array(bytes), from: from.address } + for (const listener of [...listeners]) listener(datagram) + }) + socket.on('error', () => undefined) + + return { + send: async (bytes) => { + const addresses = lanAddresses() + const results = await Promise.allSettled( + addresses.map((address) => sendOn(socket, bytes, address)) + ) + const failure = results.find( + (result): result is PromiseRejectedResult => + result.status === 'rejected' + ) + // Sent on at least one network: fine. On none (or no network at all): say why. + if (results.some((result) => result.status === 'fulfilled')) return + throw localNetworkError(failure?.reason) + }, + onMessage: (listener) => { + listeners.add(listener) + return () => listeners.delete(listener) + }, + close: () => + new Promise((resolve) => { + listeners.clear() + socket.close(() => resolve()) + }) + } +} diff --git a/apps/desktop/src/main/adapters/network/network.test.ts b/apps/desktop/src/main/adapters/network/network.test.ts new file mode 100644 index 00000000..c1164fb5 --- /dev/null +++ b/apps/desktop/src/main/adapters/network/network.test.ts @@ -0,0 +1,64 @@ +import { createServer, type Server } from 'node:net' + +import { afterEach, describe, expect, it } from 'vitest' + +import { localNetworkError } from '@desktop/main/adapters/network/local-network-error.ts' +import { connectTcp } from '@desktop/main/adapters/network/tcp-connection.ts' +import { ErrorCode } from '@ipaforge/kernel' + +const errno = (code: string) => Object.assign(new Error(code), { code }) + +describe('localNetworkError', () => { + it('reads a refused send on macOS as local network access denied', () => { + expect(localNetworkError(errno('EHOSTUNREACH'), 'darwin').code).toBe( + ErrorCode.LocalNetworkDenied + ) + }) + + it('reads anything else, or elsewhere, as a lost connection', () => { + expect(localNetworkError(errno('ENETUNREACH'), 'darwin').code).toBe( + ErrorCode.DeviceDisconnected + ) + expect(localNetworkError(errno('EHOSTUNREACH'), 'win32').code).toBe( + ErrorCode.DeviceDisconnected + ) + }) +}) + +describe('connectTcp', () => { + let server: Server | undefined + afterEach(() => server?.close()) + + it('connects straight to an address and port, as a device Connection', async () => { + server = createServer((socket) => + socket.on('data', (bytes) => socket.write(bytes)) + ) + await new Promise((resolve) => + server?.listen(0, '127.0.0.1', resolve) + ) + const address = server.address() + const port = typeof address === 'object' && address ? address.port : 0 + + const connection = await connectTcp('127.0.0.1', port) + await connection.write(new TextEncoder().encode('lockdown')) + expect( + new TextDecoder().decode((await connection.read()) ?? new Uint8Array()) + ).toBe('lockdown') + await connection.close() + }) + + it('fails with a device error when nothing listens there', async () => { + server = createServer() + await new Promise((resolve) => + server?.listen(0, '127.0.0.1', resolve) + ) + const address = server.address() + const port = typeof address === 'object' && address ? address.port : 0 + await new Promise((resolve) => server?.close(() => resolve())) + server = undefined + + await expect(connectTcp('127.0.0.1', port)).rejects.toMatchObject({ + code: ErrorCode.DeviceDisconnected + }) + }) +}) diff --git a/apps/desktop/src/main/adapters/network/tcp-connection.ts b/apps/desktop/src/main/adapters/network/tcp-connection.ts new file mode 100644 index 00000000..27025764 --- /dev/null +++ b/apps/desktop/src/main/adapters/network/tcp-connection.ts @@ -0,0 +1,36 @@ +// Node `connectTcp`: a TCP connection straight to a device's Wi-Fi address (lockdown on 62078, then each service's +// port), as the device `Connection` port, so lockdown's TLS and every service run on it unchanged. +import { connect, type Socket } from 'node:net' + +import { localNetworkError } from '@desktop/main/adapters/network/local-network-error.ts' +import { createNodeConnection } from '@desktop/main/adapters/node-connection.ts' +import type { Connection } from '@ipaforge/device' + +const CONNECT_TIMEOUT_MS = 5000 +const KEEP_ALIVE_MS = 10_000 + +const open = (host: string, port: number): Promise => + new Promise((resolve, reject) => { + const socket = connect({ host, port, noDelay: true }) + const timer = setTimeout( + () => + socket.destroy(new Error(`timed out connecting to ${host}:${port}`)), + CONNECT_TIMEOUT_MS + ) + const onError = (error: Error) => { + clearTimeout(timer) + reject(localNetworkError(error)) + } + socket.once('connect', () => { + clearTimeout(timer) + socket.off('error', onError) + socket.setKeepAlive(true, KEEP_ALIVE_MS) + resolve(socket) + }) + socket.once('error', onError) + }) + +export const connectTcp = async ( + host: string, + port: number +): Promise => createNodeConnection(await open(host, port)) diff --git a/apps/desktop/src/main/adapters/usbmux-transport.ts b/apps/desktop/src/main/adapters/usbmux-transport.ts index 15ccca53..55ff4d3c 100644 --- a/apps/desktop/src/main/adapters/usbmux-transport.ts +++ b/apps/desktop/src/main/adapters/usbmux-transport.ts @@ -1,6 +1,9 @@ -// Node DeviceTransport: connects to the system usbmuxd (Unix socket on macOS/Linux, TCP 27015 on Windows). +// Node DeviceTransport: connects to the system usbmuxd (Unix socket on macOS/Linux, TCP 27015 on Windows), and +// straight to devices on the local network (TCP to their Wi-Fi address, and the UDP socket that finds them). import { connect, type Socket } from 'node:net' +import { openMulticast } from '@desktop/main/adapters/network/multicast-socket.ts' +import { connectTcp } from '@desktop/main/adapters/network/tcp-connection.ts' import { createNodeConnection } from '@desktop/main/adapters/node-connection.ts' import { describeEndpoint, @@ -46,5 +49,7 @@ const open = (endpoint: UsbmuxdEndpoint): Promise => export const createNodeUsbmuxTransport = ( endpoint: UsbmuxdEndpoint = resolveUsbmuxdEndpoint() ): DeviceTransport => ({ - connectUsbmux: async () => createNodeConnection(await open(endpoint)) + connectUsbmux: async () => createNodeConnection(await open(endpoint)), + connectTcp, + openMulticast }) diff --git a/apps/desktop/src/main/constants.ts b/apps/desktop/src/main/constants.ts index c8f322c9..a30cb3d3 100644 --- a/apps/desktop/src/main/constants.ts +++ b/apps/desktop/src/main/constants.ts @@ -12,6 +12,11 @@ export const allowedExternalLinks = [ { origin: 'https://apps.microsoft.com', path: '/detail/9np83lwlpz9k' } ] as const +/** System settings pages the UI may open, by their exact URL: macOS Privacy & Security › Local Network. */ +export const allowedSettingsLinks: ReadonlySet = new Set([ + 'x-apple.systempreferences:com.apple.preference.security?Privacy_LocalNetwork' +]) + /** * The only permission the UI gets: writing text to the clipboard (Copy diagnostics, copying an Apple link). * Camera, microphone, notifications and every other request are refused. diff --git a/apps/desktop/src/main/external-links.test.ts b/apps/desktop/src/main/external-links.test.ts index 1a464d1f..3b8aea86 100644 --- a/apps/desktop/src/main/external-links.test.ts +++ b/apps/desktop/src/main/external-links.test.ts @@ -29,4 +29,17 @@ describe('isAllowedExternalLink', () => { ]) expect(isAllowedExternalLink(url), url).toBe(false) }) + + it("allows macOS's Local Network settings, by its exact URL only", () => { + expect( + isAllowedExternalLink( + 'x-apple.systempreferences:com.apple.preference.security?Privacy_LocalNetwork' + ) + ).toBe(true) + expect( + isAllowedExternalLink( + 'x-apple.systempreferences:com.apple.preference.security?Privacy_Camera' + ) + ).toBe(false) + }) }) diff --git a/apps/desktop/src/main/external-links.ts b/apps/desktop/src/main/external-links.ts index e9c160c2..43a20d9c 100644 --- a/apps/desktop/src/main/external-links.ts +++ b/apps/desktop/src/main/external-links.ts @@ -1,11 +1,18 @@ -import { allowedExternalLinks } from '@desktop/main/constants.ts' +import { + allowedExternalLinks, + allowedSettingsLinks +} from '@desktop/main/constants.ts' /** The page is the allowed path or below it ("/" allows the whole origin). */ const isUnder = (pathname: string, path: string): boolean => path === '/' || pathname === path || pathname.startsWith(`${path}/`) -/** Whether the UI may open `url` in the browser: HTTPS, an allowed origin, no credentials, under an allowed path. */ +/** + * Whether the UI may open `url`: an allowed system settings page exactly, or HTTPS on an allowed origin, no + * credentials, under an allowed path. + */ export const isAllowedExternalLink = (url: string): boolean => { + if (allowedSettingsLinks.has(url)) return true if (!URL.canParse(url)) return false const { origin, pathname, username, password } = new URL(url) if (username || password) return false diff --git a/apps/desktop/src/probes/device/commands/device.ts b/apps/desktop/src/probes/device/commands/device.ts index 5dab70e8..3f5134b8 100644 --- a/apps/desktop/src/probes/device/commands/device.ts +++ b/apps/desktop/src/probes/device/commands/device.ts @@ -17,6 +17,18 @@ export const listCommand = } } +/** wifi-list: searches the network for known devices (usbmuxd's and --udid) and lists where each was found. */ +export const wifiListCommand = + ({ discoverDirect, show }: DeviceProbe) => + async (): Promise => { + const started = Date.now() + const found = await discoverDirect() + console.log(`searched the network for ${Date.now() - started} ms`) + if (found.length === 0) console.log('no known devices on Wi-Fi') + for (const device of found) + console.log(`${show(device.udid)} wifi ${device.address ?? '?'}`) + } + export const infoCommand = ({ withDevice, show }: DeviceProbe) => (): Promise => diff --git a/apps/desktop/src/probes/device/commands/index.ts b/apps/desktop/src/probes/device/commands/index.ts index 083fab4d..03116182 100644 --- a/apps/desktop/src/probes/device/commands/index.ts +++ b/apps/desktop/src/probes/device/commands/index.ts @@ -6,7 +6,8 @@ import { listCommand, pairCommand, profilesCommand, - revealDevModeCommand + revealDevModeCommand, + wifiListCommand } from '@desktop/probes/device/commands/device.ts' import { installCommand } from '@desktop/probes/device/commands/install.ts' import { @@ -31,5 +32,6 @@ export const deviceCommands = (probe: DeviceProbe): ProbeCommands => ({ 'afc-speed': afcSpeedCommand(probe), place: placeCommand(probe), 'reveal-devmode': revealDevModeCommand(probe), - 'rp-pair': remotePairCommand(probe) + 'rp-pair': remotePairCommand(probe), + 'wifi-list': wifiListCommand(probe) }) diff --git a/apps/desktop/src/probes/device/context.ts b/apps/desktop/src/probes/device/context.ts index 65375c2d..5e2b7778 100644 --- a/apps/desktop/src/probes/device/context.ts +++ b/apps/desktop/src/probes/device/context.ts @@ -9,8 +9,10 @@ import { type DeviceHandle, type DeviceManager, type PairingProgress, + serializeKnownDevices, shortUdid, - type UsbmuxDevice + type UsbmuxDevice, + WIFI_DEVICES_KEY } from '@ipaforge/device' export type DeviceProbe = { @@ -18,8 +20,10 @@ export type DeviceProbe = { readonly args: DeviceProbeArgs /** A UDID as printed: shortened unless --show-udid is given. */ readonly show: (udid: string) => string - /** The device named by --udid, or the first one connected. */ + /** The device named by --udid, or the first one connected (with --direct: found on Wi-Fi). */ readonly pickDevice: () => Promise + /** With --direct: searches the network for usbmuxd's devices and --udid, and returns those found. */ + readonly discoverDirect: () => Promise /** Opens the picked device (pairing if needed), runs `use`, then closes it. */ readonly withDevice: ( use: (handle: DeviceHandle) => Promise @@ -38,15 +42,36 @@ export const printPairingProgress = (event: PairingProgress): void => console.log(`pairing: ${describePairingProgress(event)}`) export const createDeviceProbe = (args: DeviceProbeArgs): DeviceProbe => { + const secrets = createMemorySecretStore() const manager = createDeviceManager({ transport: createNodeUsbmuxTransport(), - secrets: createMemorySecretStore(), + secrets, logger: createProbeLogger() }) const showUdid = args.flag('show-udid') + const isDirect = args.flag('direct') + + /** + * --direct: the device straight over Wi-Fi only. This run's secrets live in memory, so the devices to look for + * are told first: usbmuxd's (on a cable or its own Wi-Fi link) and --udid (its pair record comes from usbmuxd). + */ + const discoverDirect = async (): Promise => { + const listed = await manager.listDevices().catch(() => []) + const udids = new Set([ + ...listed.map((device) => device.udid), + ...(args.option('udid') ? [args.option('udid') as string] : []) + ]) + await secrets.set( + WIFI_DEVICES_KEY, + serializeKnownDevices([...udids].map((udid) => ({ udid }))) + ) + return manager.discoverNetwork() + } const pickDevice = async (): Promise => { - const devices = await manager.listDevices() + const devices = isDirect + ? await discoverDirect() + : await manager.listDevices() const wanted = args.option('udid') const device = wanted ? devices.find((d) => d.udid === wanted) : devices[0] if (!device) @@ -61,8 +86,10 @@ export const createDeviceProbe = (args: DeviceProbeArgs): DeviceProbe => { ): Promise => { const device = await pickDevice() const handle = await manager.open(device.udid, { - onProgress: printPairingProgress + onProgress: printPairingProgress, + ...(isDirect ? { route: 'wifi' as const } : {}) }) + if (isDirect) console.log(`over Wi-Fi at ${device.address ?? '?'}`) try { await use(handle) } finally { @@ -75,6 +102,7 @@ export const createDeviceProbe = (args: DeviceProbeArgs): DeviceProbe => { args, show: (udid) => (showUdid ? udid : shortUdid(udid)), pickDevice, + discoverDirect, withDevice } } diff --git a/docs/design/architecture.md b/docs/design/architecture.md index a7a6b344..016891e3 100644 --- a/docs/design/architecture.md +++ b/docs/design/architecture.md @@ -46,7 +46,8 @@ ipaforge/ │ ├── device/ # CONTEXT: talking to iOS devices │ │ └── src/ │ │ ├── domain/ # UsbmuxDevice, DeviceInfo, PairRecord (+PEM), profiles, install errors, pairing apps -│ │ │ # (data), config, constants; ports: DeviceTransport → Connection (with startTls) +│ │ │ # (data), config, constants; ports: DeviceTransport → Connection (with startTls), +│ │ │ # and, for Wi-Fi without usbmuxd, connectTcp and openMulticast (MulticastSocket) │ │ ├── infrastructure/ # framing, usbmux, lockdown, pairing certificates (pkijs), afc, house-arrest, │ │ │ # installation-proxy, misagent, amfi │ │ └── application/ # DeviceManager facade: pair, sessions, installIpa, profiles, app files, checks @@ -168,6 +169,9 @@ export type Connection = { export type DeviceTransport = { connectUsbmux(): Promise + // Optional: a host that can reach devices on the local network without usbmuxd. + connectTcp?(host: string, port: number): Promise + openMulticast?(): Promise } ``` diff --git a/docs/design/failure-catalogue.md b/docs/design/failure-catalogue.md index 23aad832..95951249 100644 --- a/docs/design/failure-catalogue.md +++ b/docs/design/failure-catalogue.md @@ -82,6 +82,8 @@ | TLS handshake with lockdownd fails | `device.protocol_error` with the TLS error code and reason; not a pairing problem, never re-paired | | `MissingValue` on `EnableWifiDebugging` | `device.passcode_required` | | usbmuxd unreachable | `device.usbmuxd_unavailable` | +| macOS refuses an mDNS send or a LAN connection (`EHOSTUNREACH`/`EPERM`: Local Network privacy) | `device.local_network_denied`; Wi-Fi devices can't be found, a cable still works | +| Private Wi-Fi Address: the advert's MAC differs from the device's on each network | not an error: the advert is matched by its `authTag` (iOS 26.4+) against the pair record's HostID | ## 3. Two-factor authentication requirements (Phase 3) - Trusted-device push; SMS with a number picker; resend; switch method. diff --git a/docs/design/roadmap.md b/docs/design/roadmap.md index adfda2da..cf2228eb 100644 --- a/docs/design/roadmap.md +++ b/docs/design/roadmap.md @@ -128,6 +128,10 @@ Every feature below maps to the phases that deliver it. "Automatic" means the us - already in: installing over Wi-Fi to a device usbmuxd sees on the network (compressed, 1 MiB AFC writes), and a device seen over both USB and Wi-Fi listed once - **11.1** remote pairing for SideStore (iOS 17.4 and later): made over USB through the lockdown service `com.apple.dt.remotepairingdeviced.lockdown` (JSON framed with `RPPairing` and a 2-byte big-endian length, no tunnel): pair-setup (SRP-6a, 3072-bit group, SHA-512, the fixed USB PIN; Ed25519 identities under ChaCha20-Poly1305, the device's signature checked) and pair-verify before a saved one is reused. One identity per device, kept encrypted. SideStore gets it as its own file, `PairingFile_RemoteRP.plist` (`public_key`, `private_key`, `identifier`, `alt_irk`), next to the classic `PairingFile_Lockdown.plist`: a file with both key sets is ambiguous to SideStore. Repair SideStore checks it. Also: anisette server tests ask once, without retries (#82) - **11.2** installing through the iOS 17+ device tunnel (RSD/CoreDevice), over USB and Wi-Fi, without depending on the system's usbmuxd for Wi-Fi, and finding devices on the network + - [x] **11.2a** Wi-Fi without usbmuxd: a known device found on the network (mDNS `_apple-mobdev2._tcp` from a port of IPAForge's own, matched by the iOS 26.4+ `authTag` against the pair record's HostID, or by its MAC address) and reached straight at its address (lockdown on 62078, same pairing and TLS), also on Linux without usbmuxd; its Wi-Fi connections turned on whenever a session opens; USB first, then straight over Wi-Fi (16–18 MiB/s), then usbmuxd's Wi-Fi (6.4 MiB/s); macOS Local Network permission (translated reason) and a Devices page notice when it's refused (#97) + - [ ] **11.2b** the tunnel over USB: CoreDeviceProxy and CDTunnel, an IPv6 and TCP client in TypeScript (one packet per TLS record, packets under 8 KB), HTTP/2 and XPC, RSD, the shims + - [ ] **11.2c** the tunnel over Wi-Fi: the 11.1 remote pairing on `_remotepairing._tcp`, encrypted `createListener`, our own TLS 1.2 PSK (iOS refuses the SHA-1 suites Electron's BoringSSL has) + - [ ] **11.2d** connection states in the UI, recovery and docs - **11.3** Apple TV and Vision Pro as targets: found on the network, paired with the PIN on screen, installs through the 11.2 tunnel - not planned: Apple Watch as a target (Watch apps install with their iPhone app; installing to the Watch directly isn't documented) - [ ] **12. Release 1.0**: docs site, an upstream SideStore "preload manifest" proposal, translations, a security review (secrets, Electron hardening, CSP), a licence audit, and a tagged multi-platform release pipeline diff --git a/docs/device.md b/docs/device.md index 4dc0ff64..b99e227a 100644 --- a/docs/device.md +++ b/docs/device.md @@ -2,7 +2,7 @@ # Talking to the Device -`@ipaforge/device` installs apps, manages provisioning profiles and places pairing files on an iPhone or iPad. It never drives USB itself: it talks to the operating system's **usbmuxd**, which already owns the device, so it works next to Finder, Apple Devices and iTunes. +`@ipaforge/device` installs apps, manages provisioning profiles and places pairing files on an iPhone or iPad. It never drives USB itself: it talks to the operating system's **usbmuxd**, which already owns the device, so it works next to Finder, Apple Devices and iTunes. On Wi-Fi it can also reach a device it knows directly, without usbmuxd (see [Wi-Fi without usbmuxd](#wi-fi-without-usbmuxd)). | OS | How IPAForge reaches the device | If it's missing | |---|---|---| @@ -23,6 +23,19 @@ IPAForge uses the pairing the operating system already made. When the user taps - If the device rejects the OS's record (for example after **Reset Location & Privacy** or **Clear Trusted Computers**), IPAForge does not pair over it. It fails with `device.invalid_pair_record`: unplug the device, plug it back in, unlock it and tap Trust, so the OS pairs again. If the device rejects a record IPAForge made itself, IPAForge pairs again once. - Every session is TLS-encrypted. The device is authenticated by **pinning**: it must present exactly the device certificate from the pair record. A failed TLS handshake is reported as `device.protocol_error` with the TLS details; it does not mean the pairing is wrong, so it never triggers pairing. The certificates in a pair record are SHA-1 with empty subject and issuer names, which OpenSSL refuses at its default security level, so device connections (and only those) run at `@SECLEVEL=0`; the pinning is what authenticates the device. +## Wi-Fi without usbmuxd + +A device this computer has opened before can be reached on the same Wi-Fi network without usbmuxd. This works on Linux without usbmuxd installed, and where Apple's own Wi-Fi discovery doesn't list the device. + +- **Wi-Fi is turned on by itself.** Whenever a session opens, by cable or over Wi-Fi, IPAForge reads the device's `EnableWifiConnections` (lockdown domain `com.apple.mobile.wireless_lockdown`, the same setting as Finder's *Show this iPhone when on Wi-Fi*) and turns it on if it is off. It logs when it does. Hosts can turn this off with `enableWifiConnections: false`. A failure here never fails the session. +- **The device is remembered:** its UDID and its real Wi-Fi MAC address (lockdown `WiFiAddress`), in the secret store under `wifi-devices`. +- **Finding it:** IPAForge asks for `_apple-mobdev2._tcp.local` (mDNS) every 10 seconds, from a UDP port of its own, so devices answer straight back to it (RFC 6762 §6.7). It never binds 5353, so it doesn't compete with Bonjour or avahi. Each query goes out of every IPv4 interface. One answer carries the advert's name (`@-supportsRP-NN`), its TXT values and the device's IPv4 address. +- **Telling devices apart:** with Private Wi-Fi Address, the MAC in the advert changes on every network. So on iOS 26.4 and later IPAForge checks the advert's `authTag` against each known device's pair record: it must equal the first 8 bytes of HMAC-SHA256(key, `identifier`), the key being HKDF-SHA512 of the pair record's HostID (no salt, no info, 32 bytes), checked against a real iPhone on iOS 26.6.1. Otherwise (an advert without tags) it compares the MAC in the advert's name with the remembered one; a signed advert with no tag of ours is never matched by its MAC. Adverts of devices this computer isn't paired with are ignored. A tag must be exactly 8 bytes (compared in constant time, at most 4 per advert), so a short forged one can't match. Matching only decides where to connect: the device is authenticated as on USB, by the TLS pin to the pair record's device certificate, so an advert that lies leads to a failed session, never to an install. +- **Connecting:** lockdown on TCP port 62078 straight at the device's address, with the same pair record and TLS, then every service on the port lockdown starts. Without usbmuxd, IPAForge's own pair record is used (a device paired by the OS needs its usbmuxd record, so it needs usbmuxd). +- **Which link is used:** USB first, then straight over Wi-Fi, then usbmuxd's own Wi-Fi link. Straight over Wi-Fi measured 16–18 MiB/s against 6.4 MiB/s for usbmuxd's link, and ~37 MiB/s over USB. +- A device is gone after a goodbye from it, or when it hasn't answered for three rounds. +- **macOS asks first.** The first search shows "find devices on your local network" (the reason is in the app's Info.plist, translated). If it's refused, sends fail with "no route to host", which IPAForge reports as `device.local_network_denied`, and the Devices page explains how to allow it. Devices on a cable still work. + ## What it can do | Capability | Service | @@ -79,6 +92,7 @@ iOS 17.4 added a second kind of pairing, remote pairing, which newer SideStore b | `device.identity_invalid` (`0xe8008018`) | The signing certificate was revoked or is no longer valid | Sign again with a valid certificate; check the computer's clock | | `device.profile_not_found` (`0xe8008015`) | A bundle has no matching profile, or the device registration is still pending | Retry later; re-provision | | `device.install_failed` | Any other installd error; its name is in the details | See the details | +| `device.local_network_denied` | macOS refused IPAForge local network access, so devices on Wi-Fi can't be found | System Settings › Privacy & Security › Local Network › IPAForge; or use a cable | ## For contributors @@ -90,10 +104,12 @@ pnpm --filter @ipaforge/desktop device-probe apps | profiles # read-only pnpm --filter @ipaforge/desktop device-probe pairing-status # classic and remote pairing files (read-only) pnpm --filter @ipaforge/desktop device-probe rp-pair # iOS 17.4+: makes a remote pairing, then verifies it (kept in memory only) pnpm --filter @ipaforge/desktop device-probe afc-speed [--mb 32] # times AFC writes per chunk size (written, then deleted) +pnpm --filter @ipaforge/desktop device-probe wifi-list [--udid ] # finds known devices on Wi-Fi, without usbmuxd +pnpm --filter @ipaforge/desktop device-probe info --direct [--udid ] # any device command, straight over Wi-Fi only IPAFORGE_DEVICE=1 pnpm vitest run apps/desktop/src/main/adapters/device.hardware.test.ts ``` -Unit tests run against an in-memory fake device (`packages/device/src/__tests__/fake-device/`), which simulates usbmuxd, lockdownd and every service, so CI needs no hardware. +Unit tests run against an in-memory fake device (`packages/device/src/__tests__/fake-device/`), which simulates usbmuxd, lockdownd and every service, and a fake Wi-Fi (direct TCP and mDNS answers), so CI needs no hardware. ## See Also diff --git a/docs/installing.md b/docs/installing.md index 617fbf24..a81775f4 100644 --- a/docs/installing.md +++ b/docs/installing.md @@ -79,6 +79,8 @@ From 0.1.0-alpha.4 on, IPAForge updates itself: see [Updating and uninstalling]( | **macOS** | Nothing extra | | **Linux** | `usbmuxd`, e.g. `sudo apt install usbmuxd` / `sudo dnf install usbmuxd`; it starts when a device is plugged in | +**Wi-Fi:** once a device has been connected by cable, IPAForge can install to it over Wi-Fi on the same network, also without usbmuxd running. On macOS, allow **IPAForge** to find devices on your local network when asked (System Settings › Privacy & Security › Local Network). On Windows, allow IPAForge through the firewall if asked. + ## Install ### Windows diff --git a/docs/roadmap.md b/docs/roadmap.md index 402a6221..f963a2ed 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -17,7 +17,7 @@ The detailed roadmap, with each phase's scope, is [design/roadmap.md](design/roa | 8 | Install & preload UX ✓ | One-click SideStore ✓, live run view ✓, recovery screens ✓, Apple ID switch ✓, preload picker ✓ (#59), app sources ✓ (#66), detailed install progress ✓ (#67), the Apps section ✓ (#68), Repair SideStore ✓ (#70), SideStore QR codes ✓ (#71), on-device checklist ✓ (#72), the smaller notes ✓ (#73), anisette servers in Settings ✓ (#80), days left as SideStore counts them and SideStore refreshed with its own date ✓ (#81), installs that never hang on a locked device and Cancel refresh ✓ (#93) | | 9 | Desktop app ✓ (#61, #62, #63, #64, #65, #69, #74, #75, #77) | Electron packages for Windows, macOS, Linux ✓; the macOS app signed with IPAForge's own certificate ✓; auto-update and What's new ✓ (#74); Windows signing and notarisation moved to 1.0 | | 10 | Management tools ✓ | Developer Portal page (#86), pairing files per app (#87), saving signed IPAs (#90), `.p12` import and export (#93) | -| 11 | Wireless & remote pairing | 11.1 the iOS 17.4+ remote pairing file for SideStore ✓ (#82); 11.2 installing through the iOS 17+ device tunnel over USB and Wi-Fi, and finding devices on the network; 11.3 Apple TV and Vision Pro (installing over Wi-Fi to a paired device works already) | +| 11 | Wireless & remote pairing | 11.1 the iOS 17.4+ remote pairing file for SideStore ✓ (#82); 11.2a Wi-Fi without usbmuxd, devices found on the network ✓ (#97); 11.2b–d installing through the iOS 17+ device tunnel over USB and Wi-Fi; 11.3 Apple TV and Vision Pro (installing over Wi-Fi to a paired device works already) | | 12 | Release 1.0 | Docs site, translations, security review, Windows code signing and Apple notarisation, reusable packages on npm | ## See Also diff --git a/docs/rpc.md b/docs/rpc.md index d2fb1c95..2068c02d 100644 --- a/docs/rpc.md +++ b/docs/rpc.md @@ -90,7 +90,7 @@ Engine to UI: ## Live feeds -`client.watchDevices(listener)` subscribes to connected devices under an id the client picks and returns the function that unsubscribes. The listener gets `{ type: 'devices', devices }` first, then `attached` / `detached` events, each followed by the new list. Events are validated with zod on both sides, like every other message; an event for a subscription the client no longer has is dropped. Subscribing twice under one id is `rpc.invalid_message`; unsubscribing twice is harmless. +`client.watchDevices(listener)` subscribes to connected devices under an id the client picks and returns the function that unsubscribes. The listener gets `{ type: 'devices', devices }` first, then `attached` / `detached` events, each followed by the new list. Devices found on Wi-Fi by IPAForge itself come the same way (negative device ids). `{ type: 'network', denied }` says when the OS refuses local network access (macOS Local Network), and is sent again to a listener that subscribes later. Events are validated with zod on both sides, like every other message; an event for a subscription the client no longer has is dropped. Subscribing twice under one id is `rpc.invalid_message`; unsubscribing twice is harmless. `client.logs` is the log viewer's side: `page(query)` returns `{ entries, hasMore, counts }` (the newest matching entries, oldest first, and the count per level ignoring `minLevel`); `watch(listener)` gets every new entry; `level()` and `setLevel(level)` read and change the level; `write(record)` sends one of the UI's records, fire and forget. The host passes its buffer and level to `createRpcServer({ logs })`; without them the viewer gets empty pages. None of this traffic is logged, and a log entry that fails to send is dropped silently: logging the failure would make the next entry to send. diff --git a/docs/ui.md b/docs/ui.md index 7dff1959..74fec519 100644 --- a/docs/ui.md +++ b/docs/ui.md @@ -124,7 +124,7 @@ To add a palette, add its id to `paletteIds`, add its tokens to `palettes.ts` an Nothing about devices is polled. The list comes from the Engine's device feed (usbmuxd `Listen`). A device's status (lock, Developer Mode, trust) is read when it connects, when the Device menu or the Devices page opens, on **Check again**, and by the install run itself; the computer isn't told when a device is unlocked, so the next read shows it. A device coming or going shows a small note (`features/devices/components/device-notes.tsx`, a HeroUI toast), never an error screen. - The **Devices** page (Manage → Devices) has a card per device: state, model, iOS, connection and UDID, **Use this device**, **Save pairing file…** (a ready device: this computer's pairing file as `.mobiledevicepairing`, for another tool), and for a device that isn't ready what to do: unlock it, the Developer Mode steps, or **Ask again** for Trust (`engine.pairDevice`, which shows the Trust prompt on the device and waits for the tap). The **Install** page shows the same notice for the device in use, a notice when no device is connected, and one when Apple blocked the Apple ID in use on that device, with a button to use another saved Apple ID. + The **Devices** page (Manage → Devices) lists devices on a cable and on Wi-Fi (found by IPAForge itself, without usbmuxd: their connection reads Wi-Fi). When macOS refuses the search on Wi-Fi, a notice at the top says so, with **Open Local Network settings** (the device feed's `network` event, `useLocalNetworkDenied`; fake Engine scenario `local-network-denied`). It has a card per device: state, model, iOS, connection and UDID, **Use this device**, **Save pairing file…** (a ready device: this computer's pairing file as `.mobiledevicepairing`, for another tool), and for a device that isn't ready what to do: unlock it, the Developer Mode steps, or **Ask again** for Trust (`engine.pairDevice`, which shows the Trust prompt on the device and waits for the tap). The **Install** page shows the same notice for the device in use, a notice when no device is connected, and one when Apple blocked the Apple ID in use on that device, with a button to use another saved Apple ID. Under each card, the **on-device checklist** (`features/devices/checklist/`) says what the device needs for its iOS version, in three groups: - **Before installing:** connected, unlocked and trusting this computer (ticked from the device's status, with **Ask again**), a passcode (yours to tick), and Developer Mode on iOS 16 and later (with **Show the option**, `engine.revealDeveloperMode`, which makes its switch appear in Settings). diff --git a/packages/device/src/__tests__/fake-device/fake-device.ts b/packages/device/src/__tests__/fake-device/fake-device.ts index f947efb1..e31cae0f 100644 --- a/packages/device/src/__tests__/fake-device/fake-device.ts +++ b/packages/device/src/__tests__/fake-device/fake-device.ts @@ -8,6 +8,7 @@ import { serveAfc } from '@device/__tests__/fake-device/fake-afc.ts' import { createPipe } from '@device/__tests__/fake-device/pipe.ts' +import { lockdownAdvert } from '@device/__tests__/mdns-answer.ts' import { DEFAULT_DEVICE_CONFIG } from '@device/domain/config.ts' import { LOCKDOWN_PORT, @@ -17,6 +18,7 @@ import { import { serializePairRecord } from '@device/domain/pairing/pair-record.ts' import { encodePem } from '@device/domain/pairing/pem.ts' import type { + Datagram, DeviceTransport, TlsCredentials } from '@device/domain/ports/types.ts' @@ -125,6 +127,12 @@ export type FakeUsbmuxd = { osPairsAfterMisses: number | undefined /** usbmuxd is not running: every connection fails. */ unavailable: boolean + /** Devices on the fake Wi-Fi, by address: they answer mDNS queries and take TCP connections. */ + readonly onWifi: Map + /** Extra TXT entries a device's Wi-Fi advert carries (identifier, authTag), by UDID. */ + readonly wifiTxt: Map + /** The OS refuses local network access (macOS): every mDNS send fails. */ + localNetworkDenied: boolean attach(device: FakeDevice): void detach(udid: string): void } @@ -258,13 +266,16 @@ type LockdownRequest = { type LockdownHandler = (request: LockdownRequest) => Promise /** What lockdownd reports for `domain`/`key`; `undefined` when it has no value. */ +/** Every fake device's Wi-Fi MAC address, as lockdown reports it and its Wi-Fi advert's name starts. */ +export const WIFI_MAC = 'aa:bb:cc:dd:ee:ff' + const lockdownValue = ( device: FakeDevice, domain: string | undefined, key: string | undefined ): PlistValue | undefined => { if (key === 'DevicePublicKey') return device.devicePublicKeyPem - if (key === 'WiFiAddress') return 'aa:bb:cc:dd:ee:ff' + if (key === 'WiFiAddress') return WIFI_MAC if (domain === AMFI_DOMAIN && key === 'DeveloperModeStatus') return device.developerMode if (!key) return deviceValues(device) @@ -676,6 +687,9 @@ export const createFakeUsbmuxd = ( requests: [], osPairsAfterMisses: options.osPairsAfterMisses, unavailable: false, + onWifi: new Map(), + wifiTxt: new Map(), + localNetworkDenied: false, attach: (device) => { devices.push(device) for (const listener of listeners) listener(attachedPacket(device)) @@ -699,6 +713,46 @@ export const createFakeUsbmuxd = ( const pipe = createPipe() void serve(createLink(pipe.server), pipe.onTls) return pipe.client + }, + connectTcp: async (host, port) => { + const device = fake.onWifi.get(host) + const service = + port === LOCKDOWN_PORT + ? 'lockdown' + : device && portsOf(device).get(port) + if (!device || !service) + throw new IPAForgeError(ErrorCode.DeviceDisconnected, { + data: { host, port } + }) + fake.requests.push(`tcp:${host}:${port}`) + const pipe = createPipe() + void handOver(createLink(pipe.server), pipe.onTls, { device, service }) + return pipe.client + }, + openMulticast: async () => { + const listeners = new Set<(datagram: Datagram) => void>() + + return { + send: async () => { + if (fake.localNetworkDenied) + throw new IPAForgeError(ErrorCode.LocalNetworkDenied) + for (const [address, device] of fake.onWifi) { + const bytes = lockdownAdvert({ + mac: WIFI_MAC, + host: `${device.udid.slice(-4)}.local`, + address, + txt: fake.wifiTxt.get(device.udid) ?? [] + }) + for (const listener of [...listeners]) + listener({ bytes, from: address }) + } + }, + onMessage: (listener) => { + listeners.add(listener) + return () => listeners.delete(listener) + }, + close: async () => listeners.clear() + } } } } diff --git a/packages/device/src/__tests__/mdns-answer.ts b/packages/device/src/__tests__/mdns-answer.ts new file mode 100644 index 00000000..866bf50e --- /dev/null +++ b/packages/device/src/__tests__/mdns-answer.ts @@ -0,0 +1,103 @@ +// Test-only: an mDNS answer in wire format (no name compression), as a device sends one for a lockdown-over-Wi-Fi +// query, so the codec and the search can be tested without a network. +import { + CLASS_IN, + RecordType, + WIFI_LOCKDOWN_SERVICE +} from '@device/infrastructure/mdns/constants.ts' +import { ByteWriter, utf8Encode } from '@ipaforge/kernel' + +type RecordSpec = { + readonly name: string + readonly type: number + readonly ttl?: number + readonly data: Uint8Array +} + +const nameBytes = (name: string): Uint8Array => { + const writer = new ByteWriter() + for (const label of name.split('.').filter(Boolean)) { + const bytes = utf8Encode(label) + writer.u8(bytes.length).bytes(bytes) + } + return writer.u8(0).toBytes() +} + +export const mdnsMessage = ( + records: readonly RecordSpec[], + id = 0 +): Uint8Array => { + const writer = new ByteWriter() + writer + .u16be(id) + .u16be(0x84_00) + .u16be(0) + .u16be(records.length) + .u16be(0) + .u16be(0) + for (const record of records) + writer + .bytes(nameBytes(record.name)) + .u16be(record.type) + .u16be(CLASS_IN | 0x80_00) + .u32be(record.ttl ?? 120) + .u16be(record.data.length) + .bytes(record.data) + return writer.toBytes() +} + +export const ptrData = (target: string) => nameBytes(target) + +export const srvData = (port: number, target: string) => + new ByteWriter() + .u16be(0) + .u16be(0) + .u16be(port) + .bytes(nameBytes(target)) + .toBytes() + +export const txtData = (entries: readonly string[]) => { + const writer = new ByteWriter() + for (const entry of entries) { + const bytes = utf8Encode(entry) + writer.u8(bytes.length).bytes(bytes) + } + return writer.toBytes() +} + +export const aData = (address: string) => + new Uint8Array(address.split('.').map(Number)) + +export type FakeAdvert = { + readonly mac: string + readonly host: string + readonly address: string + readonly txt?: readonly string[] + readonly ttl?: number +} + +/** A device's whole advert in one answer, as iOS sends it: PTR, SRV, TXT and A. */ +export const lockdownAdvert = ( + { mac, host, address, txt = [], ttl }: FakeAdvert, + id = 0 +) => { + const instance = `${mac}@fe80::1-supportsRP-24.${WIFI_LOCKDOWN_SERVICE}` + const at = (record: Omit) => ({ + ...record, + ...(ttl === undefined ? {} : { ttl }) + }) + + return mdnsMessage( + [ + at({ + name: WIFI_LOCKDOWN_SERVICE, + type: RecordType.PTR, + data: ptrData(instance) + }), + at({ name: instance, type: RecordType.SRV, data: srvData(32498, host) }), + at({ name: instance, type: RecordType.TXT, data: txtData(txt) }), + at({ name: host, type: RecordType.A, data: aData(address) }) + ], + id + ) +} diff --git a/packages/device/src/__tests__/setup.ts b/packages/device/src/__tests__/setup.ts index 4b3c2a6a..282492f7 100644 --- a/packages/device/src/__tests__/setup.ts +++ b/packages/device/src/__tests__/setup.ts @@ -1,4 +1,4 @@ -// Test-only: a DeviceManager wired to a fake usbmuxd with a fake clock and instant sleeps. +// Test-only: a DeviceManager wired to a fake usbmuxd (and a fake Wi-Fi) with a fake clock and instant sleeps. import { createFakeDevice, @@ -45,6 +45,8 @@ export const createRig = async ( sleep: async (ms) => { sleeps.push(ms) now += ms + // Instant, but a real turn of the event loop, so work that isn't a microtask (WebCrypto) still runs. + await new Promise((resolve) => setTimeout(resolve, 0)) }, config }) diff --git a/packages/device/src/application/context.ts b/packages/device/src/application/context.ts index 047351ed..855a81aa 100644 --- a/packages/device/src/application/context.ts +++ b/packages/device/src/application/context.ts @@ -1,3 +1,4 @@ +import type { UsbmuxDevice } from '@device/domain/types.ts' import type { FrameLimits } from '@device/infrastructure/framing/plist-frames.ts' import { createUsbmuxClient } from '@device/infrastructure/usbmux/client.ts' import type { UsbmuxClient } from '@device/infrastructure/usbmux/types.ts' @@ -8,6 +9,10 @@ export type DeviceContext = { readonly deps: DeviceDeps readonly usbmux: UsbmuxClient readonly limits: FrameLimits + /** Devices found on the network while a search runs, by UDID: reached straight at their Wi-Fi address. */ + readonly network: Map + /** Each network device's negative device id, kept so it stays the same while the manager lives. */ + readonly networkIds: Map } export const createDeviceContext = (deps: DeviceDeps): DeviceContext => { @@ -19,6 +24,8 @@ export const createDeviceContext = (deps: DeviceDeps): DeviceContext => { return { deps, limits, + network: new Map(), + networkIds: new Map(), usbmux: createUsbmuxClient({ transport: deps.transport, logger: deps.logger, diff --git a/packages/device/src/application/device-link.ts b/packages/device/src/application/device-link.ts new file mode 100644 index 00000000..6dc035e5 --- /dev/null +++ b/packages/device/src/application/device-link.ts @@ -0,0 +1,28 @@ +// The one place a connection to a port on the device is opened: through usbmuxd, or straight to its Wi-Fi +// address when it was found on the network. Everything above (lockdown, its TLS, every service) is the same. +import type { DeviceContext } from '@device/application/context.ts' +import { shortUdid } from '@device/domain/device.ts' +import type { UsbmuxDevice } from '@device/domain/types.ts' +import { createLink, type Link } from '@device/infrastructure/framing/link.ts' +import { ErrorCode, IPAForgeError } from '@ipaforge/kernel' + +export const connectToDevice = async ( + ctx: DeviceContext, + device: UsbmuxDevice, + port: number +): Promise => { + if (device.address === undefined) + return ctx.usbmux.connect(device.deviceId, port) + const { connectTcp } = ctx.deps.transport + if (!connectTcp) + throw new IPAForgeError(ErrorCode.DeviceNotFound, { + message: 'this host cannot connect to devices on the network', + data: { device: shortUdid(device.udid) } + }) + ctx.deps.logger.debug('connecting over Wi-Fi', { + device: shortUdid(device.udid), + port + }) + + return createLink(await connectTcp(device.address, port)) +} diff --git a/packages/device/src/application/lockdown.ts b/packages/device/src/application/lockdown.ts index 95737db2..a9264197 100644 --- a/packages/device/src/application/lockdown.ts +++ b/packages/device/src/application/lockdown.ts @@ -1,5 +1,7 @@ -// Connections to lockdownd: plain (for pairing) and with a session started (for everything else). +// Connections to lockdownd: plain (for pairing) and with a session started (for everything else), through +// usbmuxd or straight to the device on Wi-Fi. import type { DeviceContext } from '@device/application/context.ts' +import { connectToDevice } from '@device/application/device-link.ts' import { LOCKDOWN_PORT } from '@device/domain/constants.ts' import { tlsCredentials } from '@device/domain/pairing/pair-record.ts' import type { PairRecord } from '@device/domain/pairing/types.ts' @@ -18,7 +20,7 @@ export const openLockdown = async ( ctx: DeviceContext, device: UsbmuxDevice ): Promise => { - const link = await ctx.usbmux.connect(device.deviceId, LOCKDOWN_PORT) + const link = await connectToDevice(ctx, device, LOCKDOWN_PORT) const lockdown = createLockdownClient(link, { label: ctx.deps.config.label, limits: ctx.limits, diff --git a/packages/device/src/application/manager.test.ts b/packages/device/src/application/manager.test.ts index 57f4d8ef..715786ad 100644 --- a/packages/device/src/application/manager.test.ts +++ b/packages/device/src/application/manager.test.ts @@ -30,6 +30,10 @@ const codeOf = async ( return undefined } +/** The pair records IPAForge saved of its own (the secret store also remembers devices' Wi-Fi addresses). */ +const ownPairRecords = (rig: { secrets: { values: Map } }) => + [...rig.secrets.values.keys()].filter((key) => key.startsWith('pair-record/')) + describe('devices', () => { it('lists devices and prefers USB over Wi-Fi for the same device', async () => { const rig = await createRig() @@ -120,7 +124,7 @@ describe('pairing and sessions', () => { ]) expect(rig.sleeps).toEqual([1000, 1000]) expect(pairRequests(rig)).toBe(0) - expect(rig.secrets.values.size).toBe(0) + expect(ownPairRecords(rig)).toEqual([]) expectUsbmuxdUntouched(rig) const record = parsePairRecord( @@ -251,7 +255,7 @@ describe('pairing and sessions', () => { expect(error.message).toContain('tap Trust') expect(pairRequests(rig)).toBe(0) expect(rig.fake.pairRecords.get(rig.device.udid)).toBe(osRecord) - expect(rig.secrets.values.size).toBe(0) + expect(ownPairRecords(rig)).toEqual([]) expectUsbmuxdUntouched(rig) }) diff --git a/packages/device/src/application/manager.ts b/packages/device/src/application/manager.ts index afbb4c03..e7263c11 100644 --- a/packages/device/src/application/manager.ts +++ b/packages/device/src/application/manager.ts @@ -1,4 +1,5 @@ -// The device facade: finding devices, pairing, and opening a session handle. +// The device facade: finding devices (through usbmuxd and on the local network), pairing, and opening a session +// handle. import { createDeviceContext, type DeviceContext @@ -7,6 +8,10 @@ import { createDeviceHandle, type DeviceHandle } from '@device/application/handle.ts' +import { + discoverNetworkDevices, + watchNetworkDevices +} from '@device/application/network-devices.ts' import { pairDevice } from '@device/application/pair.ts' import { exportPairRecord, @@ -33,6 +38,17 @@ export type DeviceManager = { onEvent: (event: DeviceEvent) => void, signal: AbortSignal ): Promise + /** + * Searches the local network for known devices until `signal` aborts, streaming them as attach/detach events + * (each with its Wi-Fi `address`). Ends at once when the host can't search; throws `device.local_network_denied` + * when the OS refuses local network access. + */ + watchNetwork( + onEvent: (event: DeviceEvent) => void, + signal: AbortSignal + ): Promise + /** Searches the network for a few seconds and returns the known devices found there. */ + discoverNetwork(): Promise pair(udid: string, options?: PairOptions): Promise isPaired(udid: string): Promise exportPairRecord(udid: string): Promise @@ -40,17 +56,62 @@ export type DeviceManager = { open(udid: string, options?: OpenSessionOptions): Promise } -const findDevice = async ( +const isUsbmuxdMissing = (error: unknown): boolean => + error instanceof IPAForgeError && error.code === ErrorCode.UsbmuxdUnavailable + +/** usbmuxd's devices, or none when there is no usbmuxd (devices on Wi-Fi can still be reached directly). */ +const usbmuxDevices = async (ctx: DeviceContext): Promise => { + try { + return await ctx.usbmux.listDevices() + } catch (error) { + if (isUsbmuxdMissing(error)) return [] + throw error + } +} + +/** + * The way to reach `udid`: by cable first, then straight over Wi-Fi (faster than usbmuxd's own Wi-Fi link, measured + * 16–18 against 6.4 MiB/s), then usbmuxd over Wi-Fi. When none is known, a short search of the network looks for it. + */ +const notFound = (udid: string) => + new IPAForgeError(ErrorCode.DeviceNotFound, { + data: { device: shortUdid(udid) } + }) + +/** `udid` straight over Wi-Fi: as found by the running search, or by a short one. */ +const findOnWifi = async ( ctx: DeviceContext, udid: string ): Promise => { - const device = (await ctx.usbmux.listDevices()).find( + const device = + ctx.network.get(udid) ?? + (await discoverNetworkDevices(ctx)).find( + (candidate) => candidate.udid === udid + ) + if (!device) throw notFound(udid) + return device +} + +const findDevice = async ( + ctx: DeviceContext, + udid: string, + route: OpenSessionOptions['route'] = 'best' +): Promise => { + if (route === 'wifi') return findOnWifi(ctx, udid) + const listed = (await usbmuxDevices(ctx)).filter( (candidate) => candidate.udid === udid ) - if (!device) - throw new IPAForgeError(ErrorCode.DeviceNotFound, { - data: { device: shortUdid(udid) } - }) + const usb = listed.find((candidate) => candidate.connectionType === 'usb') + if (usb) return usb + const direct = + ctx.network.get(udid) ?? + (listed.length === 0 + ? (await discoverNetworkDevices(ctx)).find( + (candidate) => candidate.udid === udid + ) + : undefined) + const device = direct ?? listed[0] + if (!device) throw notFound(udid) return device } @@ -58,8 +119,20 @@ export const createDeviceManager = (input: DeviceDepsInput): DeviceManager => { const ctx = createDeviceContext(resolveDeviceDeps(input)) return { - listDevices: () => ctx.usbmux.listDevices(), + listDevices: async () => { + const network = [...ctx.network.values()] + try { + return [...(await ctx.usbmux.listDevices()), ...network] + } catch (error) { + // Without usbmuxd, devices on Wi-Fi are still reachable: only none at all is an error. + if (isUsbmuxdMissing(error) && network.length > 0) return network + throw error + } + }, watch: (onEvent, signal) => ctx.usbmux.listen(onEvent, signal), + watchNetwork: (onEvent, signal) => + watchNetworkDevices(ctx, onEvent, signal), + discoverNetwork: () => discoverNetworkDevices(ctx), pair: async (udid, options) => (await pairDevice(ctx, await findDevice(ctx, udid), options)).record, isPaired: async (udid) => (await getPairRecord(ctx, udid)) !== undefined, @@ -71,7 +144,11 @@ export const createDeviceManager = (input: DeviceDepsInput): DeviceManager => { open: async (udid, options) => createDeviceHandle( ctx, - await openSession(ctx, await findDevice(ctx, udid), options) + await openSession( + ctx, + await findDevice(ctx, udid, options?.route), + options + ) ) } } diff --git a/packages/device/src/application/network-devices.ts b/packages/device/src/application/network-devices.ts new file mode 100644 index 00000000..638614da --- /dev/null +++ b/packages/device/src/application/network-devices.ts @@ -0,0 +1,167 @@ +// Devices on the local network, reached without usbmuxd: the adverts a search finds, matched to devices this +// computer knows (the authTag against each pair record's HostID on iOS 26.4 and later, else the MAC address in the +// advert's name), as attached and detached events. Each gets a negative device id, the same for as long as it stays. +import type { DeviceContext } from '@device/application/context.ts' +import { getPairRecord } from '@device/application/pair-records.ts' +import { knownWifiDevices } from '@device/application/wifi.ts' +import { shortUdid } from '@device/domain/device.ts' +import type { DeviceEvent, UsbmuxDevice } from '@device/domain/types.ts' +import { authTagMatches } from '@device/infrastructure/mdns/auth-tag.ts' +import { browseWifiDevices } from '@device/infrastructure/mdns/browser.ts' +import type { WifiAdvert } from '@device/infrastructure/mdns/types.ts' +import { toIPAForgeError } from '@ipaforge/kernel' + +/** An advert carries one tag per paired computer; more than this is not a real device's. */ +const MAX_AUTH_TAGS = 4 + +/** A stable negative id per device, so it never collides with usbmuxd's. */ +const networkIdFor = (ctx: DeviceContext, udid: string): number => { + const known = ctx.networkIds.get(udid) + if (known !== undefined) return known + const id = -(ctx.networkIds.size + 1) + ctx.networkIds.set(udid, id) + return id +} + +const hostIdFor = async ( + ctx: DeviceContext, + udid: string +): Promise => { + try { + return (await getPairRecord(ctx, udid))?.record.hostId + } catch (error) { + ctx.deps.logger.debug('no pair record for a Wi-Fi match', { + device: shortUdid(udid), + code: toIPAForgeError(error).code + }) + return undefined + } +} + +/** + * The known device this advert is from, or `undefined` when it is someone else's (or not paired with us). A signed + * advert (iOS 26.4+) is matched by its tags only; the MAC address is for adverts without them. + */ +const matchAdvert = async ( + ctx: DeviceContext, + advert: WifiAdvert +): Promise => { + const known = await knownWifiDevices(ctx) + if (advert.identifier && advert.authTags.length > 0) { + for (const { udid } of known) { + const hostId = await hostIdFor(ctx, udid) + if (!hostId) continue + for (const tag of advert.authTags.slice(0, MAX_AUTH_TAGS)) + if (await authTagMatches(hostId, advert.identifier, tag)) return udid + } + // A device that signs its advert signs it for every computer it's paired with: no tag of ours, not ours. + return undefined + } + return known.find( + (device) => device.mac !== undefined && device.mac === advert.mac + )?.udid +} + +/** + * Searches the network until `signal` aborts, keeping `ctx.network` current and reporting each device as it comes + * and goes. Ends at once when the host can't search the network; throws `device.local_network_denied` when the OS + * refuses it. + */ +export const watchNetworkDevices = async ( + ctx: DeviceContext, + onEvent: (event: DeviceEvent) => void, + signal: AbortSignal +): Promise => { + const { transport, logger, clock, sleep, config } = ctx.deps + if (!transport.openMulticast || !transport.connectTcp) return + const socket = await transport.openMulticast() + const byInstance = new Map() + // Matching an advert reads pair records; a search that stops waits for the matches still running. + const matching = new Set>() + + const found = async (advert: WifiAdvert) => { + const udid = await matchAdvert(ctx, advert) + if (!udid) { + logger.debug( + 'a device on the network that this computer is not paired with', + { + instance: advert.instance + } + ) + return + } + byInstance.set(advert.instance, udid) + const device: UsbmuxDevice = { + udid, + deviceId: networkIdFor(ctx, udid), + connectionType: 'network', + address: advert.address + } + ctx.network.set(udid, device) + logger.info('found on Wi-Fi', { device: shortUdid(udid) }) + onEvent({ kind: 'attached', device }) + } + + const lost = (instance: string) => { + const udid = byInstance.get(instance) + if (!udid) return + byInstance.delete(instance) + ctx.network.delete(udid) + logger.info('gone from Wi-Fi', { device: shortUdid(udid) }) + onEvent({ kind: 'detached', deviceId: networkIdFor(ctx, udid), udid }) + } + + try { + await browseWifiDevices( + socket, + { + sleep, + now: () => clock.now().getTime(), + intervalMs: config.networkQueryIntervalMs, + logger + }, + (event) => { + if (event.kind === 'lost') { + lost(event.instance) + return + } + const match = found(event.advert).catch((error: unknown) => + logger.warn('a device on the network could not be matched', { + code: toIPAForgeError(error).code + }) + ) + matching.add(match) + void match.finally(() => matching.delete(match)) + }, + signal + ) + } finally { + await Promise.all(matching) + for (const udid of byInstance.values()) ctx.network.delete(udid) + await socket.close() + } +} + +/** Searches the network for `ctx.deps.config.networkBrowseMs` and returns what it found. */ +export const discoverNetworkDevices = async ( + ctx: DeviceContext +): Promise => { + const controller = new AbortController() + const found: UsbmuxDevice[] = [] + const search = watchNetworkDevices( + ctx, + (event) => { + if (event.kind === 'attached') found.push(event.device) + }, + controller.signal + ) + await Promise.race([ + search, + ctx.deps + .sleep(ctx.deps.config.networkBrowseMs) + .then(() => controller.abort()) + ]) + await search.catch(() => undefined) + + return found +} diff --git a/packages/device/src/application/pair-records.ts b/packages/device/src/application/pair-records.ts index 766fe671..0aa30c81 100644 --- a/packages/device/src/application/pair-records.ts +++ b/packages/device/src/application/pair-records.ts @@ -18,12 +18,24 @@ export const notPairedError = (udid: string): IPAForgeError => data: { device: shortUdid(udid) } }) -/** The record the OS keeps in usbmuxd once the user has tapped Trust; `undefined` while there is none. */ +const isUsbmuxdMissing = (error: unknown): boolean => + error instanceof IPAForgeError && error.code === ErrorCode.UsbmuxdUnavailable + +/** + * The record the OS keeps in usbmuxd once the user has tapped Trust; `undefined` while there is none, and when + * there is no usbmuxd at all (a device reached on Wi-Fi then uses IPAForge's own record). + */ export const readOsPairRecord = async ( ctx: DeviceContext, udid: string ): Promise => { - const bytes = await ctx.usbmux.readPairRecord(udid) + let bytes: Uint8Array | undefined + try { + bytes = await ctx.usbmux.readPairRecord(udid) + } catch (error) { + if (!isUsbmuxdMissing(error)) throw error + return undefined + } return bytes ? parsePairRecord(bytes, ctx.deps.config.plist) : undefined } diff --git a/packages/device/src/application/session.ts b/packages/device/src/application/session.ts index 8139c770..a57ae4fe 100644 --- a/packages/device/src/application/session.ts +++ b/packages/device/src/application/session.ts @@ -1,4 +1,5 @@ import type { DeviceContext } from '@device/application/context.ts' +import { connectToDevice } from '@device/application/device-link.ts' import { type LockdownSession, openLockdownSession @@ -15,6 +16,7 @@ import type { StartServiceOptions, StoredPairRecord } from '@device/application/types.ts' +import { prepareWifi } from '@device/application/wifi.ts' import { LockdownDomain } from '@device/domain/constants.ts' import { shortUdid } from '@device/domain/device.ts' import { tlsCredentials } from '@device/domain/pairing/pair-record.ts' @@ -112,7 +114,7 @@ const sessionFor = ( ) return closeOnError( - await ctx.usbmux.connect(device.deviceId, port), + await connectToDevice(ctx, device, port), async (link) => { if (enableServiceSsl) await link.startTls(credentials) return link @@ -177,5 +179,6 @@ export const openSession = async ( options.autoPair ?? true ) ctx.deps.logger.info('session opened', { device: shortUdid(device.udid) }) + await prepareWifi(ctx, device, started.lockdown) return sessionFor(ctx, device, pairRecord, started) } diff --git a/packages/device/src/application/types.ts b/packages/device/src/application/types.ts index ade5ec5c..3234115a 100644 --- a/packages/device/src/application/types.ts +++ b/packages/device/src/application/types.ts @@ -121,6 +121,8 @@ export type PlacedPairing = { export type OpenSessionOptions = PairOptions & { /** Pair automatically (trust prompt) when there is no usable pair record. Default true. */ readonly autoPair?: boolean + /** `wifi`: only straight over Wi-Fi, skipping the cable and usbmuxd (maintainer probes). Default: the best link. */ + readonly route?: 'best' | 'wifi' } export type StartServiceOptions = { diff --git a/packages/device/src/application/wifi.test.ts b/packages/device/src/application/wifi.test.ts new file mode 100644 index 00000000..89df94de --- /dev/null +++ b/packages/device/src/application/wifi.test.ts @@ -0,0 +1,184 @@ +// Wi-Fi without usbmuxd: what a session sets up, and finding and opening a known device on the network. +import { describe, expect, it } from 'vitest' + +import { WIFI_MAC } from '@device/__tests__/fake-device/fake-device.ts' +import { createRig, type TestRig } from '@device/__tests__/setup.ts' +import { + LockdownDomain, + WIFI_CONNECTIONS_KEY +} from '@device/domain/constants.ts' +import { parsePairRecord } from '@device/domain/pairing/pair-record.ts' +import type { DeviceEvent } from '@device/domain/types.ts' +import { + parseKnownDevices, + serializeKnownDevices, + WIFI_DEVICES_KEY +} from '@device/domain/wifi.ts' +import { + DEFAULT_PLIST_LIMITS, + ErrorCode, + toBase64, + utf8Encode +} from '@ipaforge/kernel' + +const WIFI_KEY = `${LockdownDomain.WirelessLockdown}/${WIFI_CONNECTIONS_KEY}` +const ADDRESS = '192.0.2.10' + +const openAndClose = async (rig: TestRig) => { + const handle = await rig.manager.open(rig.device.udid) + await handle.close() +} + +/** The device leaves the cable and usbmuxd, and is on the fake Wi-Fi instead. */ +const moveToWifi = (rig: TestRig) => { + rig.fake.detach(rig.device.udid) + rig.fake.onWifi.set(ADDRESS, rig.device) +} + +/** The authTag a device sends for `hostId` (the same scheme as the code under test; the vector test pins it). */ +const bytes = (text: string): Uint8Array => + new Uint8Array(utf8Encode(text)) + +const authTagFor = async (hostId: string, identifier: string) => { + const subtle = globalThis.crypto.subtle + const ikm = await subtle.importKey('raw', bytes(hostId), 'HKDF', false, [ + 'deriveBits' + ]) + const bits = await subtle.deriveBits( + { + name: 'HKDF', + hash: 'SHA-512', + salt: new Uint8Array(0), + info: new Uint8Array(0) + }, + ikm, + 256 + ) + const key = await subtle.importKey( + 'raw', + bits, + { name: 'HMAC', hash: 'SHA-256' }, + false, + ['sign'] + ) + const tag = new Uint8Array(await subtle.sign('HMAC', key, bytes(identifier))) + + return toBase64(tag.subarray(0, 8)) +} + +const watchUntil = async (rig: TestRig, count: number) => { + const events: DeviceEvent[] = [] + const controller = new AbortController() + await rig.manager.watchNetwork((event) => { + events.push(event) + if (events.length >= count) controller.abort() + }, controller.signal) + return events +} + +describe('Wi-Fi without usbmuxd', () => { + it("turns on the device's Wi-Fi connections when a session opens, and remembers the device", async () => { + const rig = await createRig() + await openAndClose(rig) + + expect(rig.device.values.get(WIFI_KEY)).toBe(true) + expect(parseKnownDevices(await rig.secrets.get(WIFI_DEVICES_KEY))).toEqual([ + { udid: rig.device.udid, mac: WIFI_MAC } + ]) + }) + + it('leaves Wi-Fi connections alone when they are on already, or when the host says not to', async () => { + const on = await createRig() + on.device.values.set(WIFI_KEY, true) + await openAndClose(on) + expect(on.device.requests).not.toContain('lockdown:SetValue') + + const off = await createRig({}, { enableWifiConnections: false }) + await openAndClose(off) + expect(off.device.values.has(WIFI_KEY)).toBe(false) + }) + + it('finds a known device on Wi-Fi and opens it straight at its address', async () => { + const rig = await createRig() + await openAndClose(rig) + moveToWifi(rig) + + const handle = await rig.manager.open(rig.device.udid) + expect(handle.device).toMatchObject({ + udid: rig.device.udid, + connectionType: 'network', + address: ADDRESS + }) + expect(rig.fake.requests).toContain(`tcp:${ADDRESS}:62078`) + await handle.close() + }) + + it("matches a device by its authTag when its advert's MAC is a private one", async () => { + const rig = await createRig() + await rig.secrets.set( + WIFI_DEVICES_KEY, + serializeKnownDevices([ + { udid: rig.device.udid, mac: '02:00:00:00:00:99' } + ]) + ) + const record = parsePairRecord( + await rig.manager.exportPairRecord(rig.device.udid), + DEFAULT_PLIST_LIMITS + ) + const identifier = '0A1B2C3D-4E5F-4A6B-8C7D-9E0F1A2B3C4D' + rig.fake.wifiTxt.set(rig.device.udid, [ + `identifier=${identifier}`, + `authTag=${await authTagFor(record.hostId, identifier)}` + ]) + moveToWifi(rig) + + const [event] = await watchUntil(rig, 1) + expect(event).toMatchObject({ + kind: 'attached', + device: { udid: rig.device.udid, address: ADDRESS } + }) + }) + + it('ignores a device on the network that this computer does not know', async () => { + const rig = await createRig() + moveToWifi(rig) + expect(await rig.manager.discoverNetwork()).toEqual([]) + }) + + it('lists Wi-Fi devices while a search runs, also without usbmuxd', async () => { + const rig = await createRig() + await openAndClose(rig) + moveToWifi(rig) + rig.fake.unavailable = true + const controller = new AbortController() + let listed: unknown + await rig.manager.watchNetwork(async () => { + listed = await rig.manager.listDevices() + controller.abort() + }, controller.signal) + + expect(listed).toEqual([ + expect.objectContaining({ udid: rig.device.udid, address: ADDRESS }) + ]) + }) + + it('says when the OS refuses local network access', async () => { + const rig = await createRig() + rig.fake.localNetworkDenied = true + await expect( + rig.manager.watchNetwork(() => {}, new AbortController().signal) + ).rejects.toMatchObject({ code: ErrorCode.LocalNetworkDenied }) + }) + + it("doesn't match a signed advert by its MAC when none of its tags is this computer's", async () => { + const rig = await createRig() + await openAndClose(rig) + rig.fake.wifiTxt.set(rig.device.udid, [ + 'identifier=0A1B2C3D-4E5F-4A6B-8C7D-9E0F1A2B3C4D', + 'authTag=AAAAAAAAAAA=' + ]) + moveToWifi(rig) + + expect(await rig.manager.discoverNetwork()).toEqual([]) + }) +}) diff --git a/packages/device/src/application/wifi.ts b/packages/device/src/application/wifi.ts new file mode 100644 index 00000000..77d5f165 --- /dev/null +++ b/packages/device/src/application/wifi.ts @@ -0,0 +1,78 @@ +// Wi-Fi without the cable: when a session opens, the device's Wi-Fi connections are turned on (they're off on a +// new device), and the device is remembered with its Wi-Fi MAC address, so it can be told apart when it is found +// on the network. Both are best-effort: neither ever fails the session. +import type { DeviceContext } from '@device/application/context.ts' +import { + LockdownDomain, + WIFI_ADDRESS_KEY, + WIFI_CONNECTIONS_KEY +} from '@device/domain/constants.ts' +import { shortUdid } from '@device/domain/device.ts' +import type { KnownWifiDevice, UsbmuxDevice } from '@device/domain/types.ts' +import { + normalizeMac, + parseKnownDevices, + serializeKnownDevices, + WIFI_DEVICES_KEY +} from '@device/domain/wifi.ts' +import type { LockdownClient } from '@device/infrastructure/lockdown/types.ts' +import { toIPAForgeError } from '@ipaforge/kernel' + +const turnOnWifiConnections = async ( + ctx: DeviceContext, + device: UsbmuxDevice, + lockdown: LockdownClient +): Promise => { + const domain = LockdownDomain.WirelessLockdown + if ((await lockdown.getValue(WIFI_CONNECTIONS_KEY, domain)) === true) return + await lockdown.setValue(domain, WIFI_CONNECTIONS_KEY, true) + ctx.deps.logger.info('turned on Wi-Fi connections', { + device: shortUdid(device.udid) + }) +} + +/** The devices this computer has opened before, so one found on Wi-Fi can be matched to its pair record. */ +export const knownWifiDevices = async ( + ctx: DeviceContext +): Promise => + parseKnownDevices(await ctx.deps.secrets.get(WIFI_DEVICES_KEY)) + +const rememberDevice = async ( + ctx: DeviceContext, + device: UsbmuxDevice, + lockdown: LockdownClient +): Promise => { + const value = await lockdown.getValue(WIFI_ADDRESS_KEY) + const mac = typeof value === 'string' ? normalizeMac(value) : undefined + const known = await knownWifiDevices(ctx) + const current = known.find((entry) => entry.udid === device.udid) + if (current && current.mac === mac) return + const others = known.filter((entry) => entry.udid !== device.udid) + await ctx.deps.secrets.set( + WIFI_DEVICES_KEY, + serializeKnownDevices([...others, { udid: device.udid, mac }]) + ) +} + +/** Prepares an opened session's device for Wi-Fi: its connections on, its MAC address remembered. */ +export const prepareWifi = async ( + ctx: DeviceContext, + device: UsbmuxDevice, + lockdown: LockdownClient +): Promise => { + const steps = [ + ...(ctx.deps.config.enableWifiConnections ? [turnOnWifiConnections] : []), + rememberDevice + ] + for (const step of steps) { + try { + await step(ctx, device, lockdown) + } catch (error) { + ctx.deps.logger.warn('Wi-Fi setup skipped', { + device: shortUdid(device.udid), + step: step.name, + code: toIPAForgeError(error).code + }) + } + } +} diff --git a/packages/device/src/domain/config.ts b/packages/device/src/domain/config.ts index ecbf67f7..9beffca8 100644 --- a/packages/device/src/domain/config.ts +++ b/packages/device/src/domain/config.ts @@ -17,6 +17,12 @@ export type DeviceConfig = { readonly afcWriteChunkBytes: number /** Bytes requested per AFC read packet. */ readonly afcReadChunkBytes: number + /** Turn on the device's Wi-Fi connections whenever a session opens, so it can be reached without the cable. */ + readonly enableWifiConnections: boolean + /** How long a search for devices on the network listens for answers. */ + readonly networkBrowseMs: number + /** How often a running search asks again; a device not heard from for three rounds is gone. */ + readonly networkQueryIntervalMs: number } export const DEFAULT_DEVICE_CONFIG: DeviceConfig = { @@ -28,7 +34,10 @@ export const DEFAULT_DEVICE_CONFIG: DeviceConfig = { pairingTimeoutMs: 120_000, // Measured on an iPhone over Wi-Fi (device-probe afc-speed): 64 KiB 2.7 MiB/s, 256 KiB 4.7, 1 MiB 6.4, 4 MiB 6.7. afcWriteChunkBytes: 1024 * 1024, - afcReadChunkBytes: 1024 * 1024 + afcReadChunkBytes: 1024 * 1024, + enableWifiConnections: true, + networkBrowseMs: 3000, + networkQueryIntervalMs: 10_000 } export const resolveDeviceConfig = ( diff --git a/packages/device/src/domain/constants.ts b/packages/device/src/domain/constants.ts index f22a01ba..b9c1feb7 100644 --- a/packages/device/src/domain/constants.ts +++ b/packages/device/src/domain/constants.ts @@ -35,6 +35,12 @@ export const Service = { Amfi: 'com.apple.amfi.lockdown' } as const +/** The wireless lockdown key that lets the device take connections over Wi-Fi (Finder's "Show this iPhone when on Wi-Fi"). */ +export const WIFI_CONNECTIONS_KEY = 'EnableWifiConnections' + +/** The lockdown value holding the device's Wi-Fi MAC address. */ +export const WIFI_ADDRESS_KEY = 'WiFiAddress' + export const LockdownDomain = { Amfi: 'com.apple.security.mac.amfi', WirelessLockdown: 'com.apple.mobile.wireless_lockdown' diff --git a/packages/device/src/domain/ports/types.ts b/packages/device/src/domain/ports/types.ts index 157e11af..616a3246 100644 --- a/packages/device/src/domain/ports/types.ts +++ b/packages/device/src/domain/ports/types.ts @@ -24,7 +24,30 @@ export type Connection = { close(): Promise } -/** Opens connections to the system usbmuxd (macOS/Linux socket, Windows Apple Mobile Device Service). */ +/** A datagram the network sent back, and the address it came from. */ +export type Datagram = { + readonly bytes: Uint8Array + readonly from: string +} + +/** + * A UDP socket for finding devices on the local network (mDNS): it sends to the mDNS multicast group and hears + * the answers sent back to it. It uses a port of its own, never 5353, so it never competes with the system's + * Bonjour or avahi. `send` throws `device.local_network_denied` when the OS refuses local network access. + */ +export type MulticastSocket = { + send(bytes: Uint8Array): Promise + /** Calls `listener` with every datagram that arrives; the returned function stops it. */ + onMessage(listener: (datagram: Datagram) => void): () => void + close(): Promise +} + +/** + * Opens connections to the system usbmuxd (macOS/Linux socket, Windows Apple Mobile Device Service) and, when the + * host can, straight to a device on the local network: TCP to its Wi-Fi address, and the socket that finds it. + */ export type DeviceTransport = { connectUsbmux(): Promise + connectTcp?(host: string, port: number): Promise + openMulticast?(): Promise } diff --git a/packages/device/src/domain/types.ts b/packages/device/src/domain/types.ts index 4e054c71..90e25695 100644 --- a/packages/device/src/domain/types.ts +++ b/packages/device/src/domain/types.ts @@ -1,12 +1,14 @@ export type ConnectionType = 'usb' | 'network' -/** A device as usbmuxd reports it. */ +/** A device as usbmuxd reports it, or as found on the local network (then with its `address`). */ export type UsbmuxDevice = { readonly udid: string - /** usbmuxd's handle for this attachment (changes on every reconnect). */ + /** usbmuxd's handle for this attachment (changes on every reconnect); negative for one found on Wi-Fi. */ readonly deviceId: number readonly connectionType: ConnectionType readonly productId?: number + /** Its Wi-Fi address when found on the network: reached directly over TCP, without usbmuxd. */ + readonly address?: string } export type DeviceEvent = @@ -78,3 +80,9 @@ export type RemoveStaleOptions = { /** Also remove this team's profiles whose app is no longer installed. */ readonly teamId?: string } + +/** A device seen before, so it can be recognised on the network: its UDID and its real Wi-Fi MAC address. */ +export type KnownWifiDevice = { + readonly udid: string + readonly mac?: string | undefined +} diff --git a/packages/device/src/domain/wifi.ts b/packages/device/src/domain/wifi.ts new file mode 100644 index 00000000..acea1ba5 --- /dev/null +++ b/packages/device/src/domain/wifi.ts @@ -0,0 +1,46 @@ +// The devices IPAForge knows, so one found on the network can be told apart: each one's UDID and, when known, +// its real Wi-Fi MAC address. Kept in the secret store under one key, as a small JSON list. +import type { KnownWifiDevice } from '@device/domain/types.ts' +import { utf8Decode, utf8Encode } from '@ipaforge/kernel' + +const MAC = /^[0-9a-f]{2}(:[0-9a-f]{2}){5}$/ + +/** Key under which the known devices are kept. */ +export const WIFI_DEVICES_KEY = 'wifi-devices' + +/** A MAC address in lower case with colons, or `undefined` when it isn't one. */ +export const normalizeMac = (value: string): string | undefined => { + const mac = value.trim().toLowerCase().replaceAll('-', ':') + + return MAC.test(mac) ? mac : undefined +} + +/** The MAC address an advert's instance name starts with (`@
…`): the real one, or a private one. */ +export const macOfInstance = (instance: string): string | undefined => { + const [prefix] = instance.split('@') + + return prefix === undefined ? undefined : normalizeMac(prefix) +} + +const isKnownDevice = (value: unknown): value is KnownWifiDevice => + typeof value === 'object' && + value !== null && + typeof (value as { udid?: unknown }).udid === 'string' && + ['string', 'undefined'].includes(typeof (value as { mac?: unknown }).mac) + +export const parseKnownDevices = ( + bytes: Uint8Array | undefined +): KnownWifiDevice[] => { + if (!bytes) return [] + try { + const parsed: unknown = JSON.parse(utf8Decode(bytes)) + + return Array.isArray(parsed) ? parsed.filter(isKnownDevice) : [] + } catch { + return [] + } +} + +export const serializeKnownDevices = ( + devices: readonly KnownWifiDevice[] +): Uint8Array => utf8Encode(JSON.stringify(devices)) diff --git a/packages/device/src/index.ts b/packages/device/src/index.ts index 492f80fe..38fb662b 100644 --- a/packages/device/src/index.ts +++ b/packages/device/src/index.ts @@ -62,7 +62,9 @@ export { } from '@device/domain/pairing-apps.ts' export type { Connection, + Datagram, DeviceTransport, + MulticastSocket, TlsCredentials } from '@device/domain/ports/types.ts' export { @@ -86,6 +88,10 @@ export type { RemoveStaleOptions, UsbmuxDevice } from '@device/domain/types.ts' +export { + serializeKnownDevices, + WIFI_DEVICES_KEY +} from '@device/domain/wifi.ts' export type { AfcClient, AfcStat } from '@device/infrastructure/afc/types.ts' export type { ContainerMode } from '@device/infrastructure/house-arrest/client.ts' export type { InstalledApp } from '@device/infrastructure/installation-proxy/apps.ts' @@ -93,5 +99,9 @@ export type { ApplicationType, InstallProgress } from '@device/infrastructure/installation-proxy/types.ts' +export { + MDNS_GROUP, + MDNS_PORT +} from '@device/infrastructure/mdns/constants.ts' export { createPairRecord } from '@device/infrastructure/pairing/certificates.ts' export type { DeviceDeps, DeviceDepsInput, Sleep } from '@device/types.ts' diff --git a/packages/device/src/infrastructure/mdns/auth-tag.ts b/packages/device/src/infrastructure/mdns/auth-tag.ts new file mode 100644 index 00000000..d3bce927 --- /dev/null +++ b/packages/device/src/infrastructure/mdns/auth-tag.ts @@ -0,0 +1,70 @@ +// iOS 26.4 and later sign their Wi-Fi advert for each paired computer: the `authTag` TXT value is the start of +// HMAC-SHA256(key, identifier), the key being HKDF-SHA512 of that computer's HostID (no salt, no info, 32 bytes). +// It survives Private Wi-Fi Address, which changes the MAC address on every network. Verified on iOS 26.6.1. +import { fromBase64, utf8Encode } from '@ipaforge/kernel' + +const KEY_BYTES = 32 + +/** iOS sends the first 8 bytes of the HMAC; any other length is refused, so a short forged tag can't match. */ +export const AUTH_TAG_BYTES = 8 + +/** WebCrypto wants bytes backed by a plain ArrayBuffer. */ +const buffer = (bytes: Uint8Array): Uint8Array => + new Uint8Array(bytes) + +const keyFor = async (hostId: string): Promise => { + const subtle = globalThis.crypto.subtle + const ikm = await subtle.importKey( + 'raw', + buffer(utf8Encode(hostId)), + 'HKDF', + false, + ['deriveBits'] + ) + const bits = await subtle.deriveBits( + { + name: 'HKDF', + hash: 'SHA-512', + salt: new Uint8Array(0), + info: new Uint8Array(0) + }, + ikm, + KEY_BYTES * 8 + ) + + return subtle.importKey( + 'raw', + bits, + { name: 'HMAC', hash: 'SHA-256' }, + false, + ['sign'] + ) +} + +/** Whether `tag` (base64) is what a device paired with this HostID sends for `identifier`. */ +export const authTagMatches = async ( + hostId: string, + identifier: string, + tag: string +): Promise => { + let wanted: Uint8Array + try { + wanted = fromBase64(tag) + } catch { + return false + } + if (wanted.length !== AUTH_TAG_BYTES) return false + const mac = new Uint8Array( + await globalThis.crypto.subtle.sign( + 'HMAC', + await keyFor(hostId), + buffer(utf8Encode(identifier)) + ) + ) + // Every byte is compared, whatever differs first. + let difference = 0 + for (let index = 0; index < AUTH_TAG_BYTES; index++) + difference |= (wanted[index] ?? 0) ^ (mac[index] ?? 0) + + return difference === 0 +} diff --git a/packages/device/src/infrastructure/mdns/browser.ts b/packages/device/src/infrastructure/mdns/browser.ts new file mode 100644 index 00000000..df8b4fde --- /dev/null +++ b/packages/device/src/infrastructure/mdns/browser.ts @@ -0,0 +1,145 @@ +// Finding devices on the local network: asks for `_apple-mobdev2._tcp` (lockdown over Wi-Fi) now and every +// interval, from a port of its own so answers come straight back to it (RFC 6762 §6.7), and turns the records into +// adverts: the instance, the IPv4 address, the MAC address in its name, and the identifier and authTags of its TXT. +// An advert withdrawn (a goodbye) or not heard from for three rounds is lost. +import type { MulticastSocket } from '@device/domain/ports/types.ts' +import { macOfInstance } from '@device/domain/wifi.ts' +import { + RecordType, + WIFI_LOCKDOWN_SERVICE +} from '@device/infrastructure/mdns/constants.ts' +import { + decodeMessage, + encodeQuery +} from '@device/infrastructure/mdns/message.ts' +import type { + BrowseEvent, + BrowseOptions, + PendingAdvert, + ResourceRecord, + WifiAdvert +} from '@device/infrastructure/mdns/types.ts' +import { ErrorCode, IPAForgeError, toIPAForgeError } from '@ipaforge/kernel' + +const ROUNDS_BEFORE_LOST = 3 + +const txtValues = (entries: readonly string[], key: string): string[] => + entries + .filter((entry) => entry.startsWith(`${key}=`)) + .map((entry) => entry.slice(key.length + 1)) + +const sameAdvert = (a: WifiAdvert, b: WifiAdvert): boolean => + a.address === b.address && + a.identifier === b.identifier && + a.authTags.join() === b.authTags.join() + +export const browseWifiDevices = async ( + socket: MulticastSocket, + { sleep, now, intervalMs, logger }: BrowseOptions, + onEvent: (event: BrowseEvent) => void, + signal: AbortSignal +): Promise => { + const partials = new Map() + const hosts = new Map() + const adverts = new Map() + let queryId = globalThis.crypto.getRandomValues(new Uint16Array(1))[0] ?? 0 + + const send = async (questions: Parameters[0]) => { + queryId = (queryId + 1) & 0xff_ff + try { + await socket.send(encodeQuery(questions, queryId)) + } catch (error) { + // Refused local network access is the caller's to report; anything else is retried next round. + if ( + error instanceof IPAForgeError && + error.code === ErrorCode.LocalNetworkDenied + ) + throw error + logger.debug('mDNS query not sent', { code: toIPAForgeError(error).code }) + } + } + + const lose = (instance: string) => { + partials.delete(instance) + if (adverts.delete(instance)) onEvent({ kind: 'lost', instance }) + } + + const settle = (instance: string, partial: PendingAdvert) => { + const address = partial.host ? hosts.get(partial.host) : undefined + if (!address) return false + const advert: WifiAdvert = { + instance, + address, + mac: macOfInstance(instance), + identifier: partial.identifier, + authTags: partial.authTags + } + const known = adverts.get(instance) + adverts.set(instance, { advert, seenAt: now() }) + if (!known || !sameAdvert(known.advert, advert)) + onEvent({ kind: 'found', advert }) + return true + } + + const take = (record: ResourceRecord) => { + if ( + record.type === RecordType.PTR && + record.name === WIFI_LOCKDOWN_SERVICE + ) { + if (record.ttl === 0) lose(record.target) + else if (!partials.has(record.target)) + partials.set(record.target, { authTags: [] }) + return + } + if (record.type === RecordType.A) { + if (record.ttl > 0) hosts.set(record.name, record.address) + return + } + const partial = partials.get(record.name) + if (!partial) return + if (record.type === RecordType.SRV) partial.host = record.target + if (record.type === RecordType.TXT) { + partial.identifier = txtValues(record.entries, 'identifier')[0] + partial.authTags = txtValues(record.entries, 'authTag') + } + } + + const onMessage = (bytes: Uint8Array) => { + let records: readonly ResourceRecord[] + try { + const message = decodeMessage(bytes) + if (!message.isResponse) return + records = message.records + } catch (error) { + logger.debug('mDNS answer skipped', { code: toIPAForgeError(error).code }) + return + } + for (const record of records) take(record) + for (const [instance, partial] of partials) { + if (settle(instance, partial)) continue + // The answer named the device but not where it is: ask for that next. + void send([ + { name: instance, type: RecordType.SRV }, + { name: instance, type: RecordType.TXT }, + ...(partial.host ? [{ name: partial.host, type: RecordType.A }] : []) + ]).catch(() => undefined) + } + } + + const stop = socket.onMessage(({ bytes }) => onMessage(bytes)) + try { + while (!signal.aborted) { + await send([{ name: WIFI_LOCKDOWN_SERVICE, type: RecordType.PTR }]) + try { + await sleep(intervalMs, signal) + } catch { + return + } + const cutoff = now() - ROUNDS_BEFORE_LOST * intervalMs + for (const [instance, { seenAt }] of adverts) + if (seenAt < cutoff) lose(instance) + } + } finally { + stop() + } +} diff --git a/packages/device/src/infrastructure/mdns/constants.ts b/packages/device/src/infrastructure/mdns/constants.ts new file mode 100644 index 00000000..bddfd853 --- /dev/null +++ b/packages/device/src/infrastructure/mdns/constants.ts @@ -0,0 +1,23 @@ +/** The mDNS IPv4 multicast group and port every query goes to (RFC 6762: fixed by the protocol). */ +// eslint-disable-next-line sonarjs/no-hardcoded-ip -- the mDNS group is part of the protocol, never configurable +export const MDNS_GROUP = '224.0.0.251' +export const MDNS_PORT = 5353 + +/** The DNS record types device adverts use. */ +export const RecordType = { + A: 1, + PTR: 12, + TXT: 16, + AAAA: 28, + SRV: 33 +} as const + +/** Class IN; mDNS uses the top bit of a record's class for "cache flush", which is masked off here. */ +export const CLASS_IN = 1 +export const CLASS_MASK = 0x7f_ff + +/** The service a device advertises while it takes lockdown connections over Wi-Fi. */ +export const WIFI_LOCKDOWN_SERVICE = '_apple-mobdev2._tcp.local' + +/** Most compression pointers a name may follow before it counts as a loop. */ +export const MAX_NAME_JUMPS = 32 diff --git a/packages/device/src/infrastructure/mdns/mdns.test.ts b/packages/device/src/infrastructure/mdns/mdns.test.ts new file mode 100644 index 00000000..fb5e457c --- /dev/null +++ b/packages/device/src/infrastructure/mdns/mdns.test.ts @@ -0,0 +1,207 @@ +import { describe, expect, it } from 'vitest' + +import { lockdownAdvert, ptrData } from '@device/__tests__/mdns-answer.ts' +import type { Datagram, MulticastSocket } from '@device/domain/ports/types.ts' +import { authTagMatches } from '@device/infrastructure/mdns/auth-tag.ts' +import { browseWifiDevices } from '@device/infrastructure/mdns/browser.ts' +import { + RecordType, + WIFI_LOCKDOWN_SERVICE +} from '@device/infrastructure/mdns/constants.ts' +import { + decodeMessage, + encodeQuery +} from '@device/infrastructure/mdns/message.ts' +import type { BrowseEvent } from '@device/infrastructure/mdns/types.ts' +import { ErrorCode, IPAForgeError, silentLogger } from '@ipaforge/kernel' + +const ADVERT = { + mac: '02:00:00:00:00:01', + host: 'iPhone.local', + address: '192.0.2.10', + txt: [ + 'identifier=0A1B2C3D-4E5F-4A6B-8C7D-9E0F1A2B3C4D', + 'authTag=dr5/vaK9kIw=' + ] +} + +describe('mDNS messages', () => { + it('encodes a query for the lockdown-over-Wi-Fi service', () => { + const query = encodeQuery( + [{ name: WIFI_LOCKDOWN_SERVICE, type: RecordType.PTR }], + 0x12_34 + ) + expect([...query.subarray(0, 12)]).toEqual([ + 0x12, 0x34, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 + ]) + expect(new TextDecoder().decode(query.subarray(12, 27))).toBe( + '\u000e_apple-mobdev2' + ) + expect([...query.subarray(-4)]).toEqual([0, RecordType.PTR, 0, 1]) + }) + + it("reads a device's whole advert: PTR, SRV, TXT and A", () => { + const message = decodeMessage(lockdownAdvert(ADVERT, 7)) + expect(message.id).toBe(7) + expect(message.isResponse).toBe(true) + expect(message.records.map((record) => record.type)).toEqual([ + RecordType.PTR, + RecordType.SRV, + RecordType.TXT, + RecordType.A + ]) + expect(message.records[1]).toMatchObject({ + port: 32498, + target: 'iPhone.local' + }) + expect(message.records[2]).toMatchObject({ entries: ADVERT.txt }) + expect(message.records[3]).toMatchObject({ address: '192.0.2.10' }) + }) + + it('follows name compression, and refuses a pointer loop', () => { + // One question, then one answer whose name is a pointer (0xc00c) back to the question's name. + const query = encodeQuery( + [{ name: WIFI_LOCKDOWN_SERVICE, type: RecordType.PTR }], + 0 + ) + const target = ptrData('a.b') + const pointed = new Uint8Array([ + ...[0, 0, 0x84, 0, 0, 1, 0, 1, 0, 0, 0, 0], + ...query.subarray(12), + ...[0xc0, 12, 0, RecordType.PTR, 0, 1, 0, 0, 0, 120, 0, target.length], + ...target + ]) + expect(decodeMessage(pointed).records).toEqual([ + { + name: WIFI_LOCKDOWN_SERVICE, + ttl: 120, + type: RecordType.PTR, + target: 'a.b' + } + ]) + + const loop = new Uint8Array([ + 0, 0, 0x84, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0xc0, 12 + ]) + expect(() => decodeMessage(loop)).toThrow(IPAForgeError) + }) +}) + +describe('authTag', () => { + // The vector was computed with Python's hmac and hashlib, independently of this code. + const HOST_ID = '5F0B6C2A-1D3E-4F5A-8B9C-0D1E2F3A4B5C' + const IDENTIFIER = '0A1B2C3D-4E5F-4A6B-8C7D-9E0F1A2B3C4D' + + it("matches the tag a device sends for this computer's HostID", async () => { + expect(await authTagMatches(HOST_ID, IDENTIFIER, 'dr5/vaK9kIw=')).toBe(true) + }) + + it("refuses another computer's tag, another identifier and a broken tag", async () => { + expect(await authTagMatches('another', IDENTIFIER, 'dr5/vaK9kIw=')).toBe( + false + ) + expect(await authTagMatches(HOST_ID, 'another', 'dr5/vaK9kIw=')).toBe(false) + expect(await authTagMatches(HOST_ID, IDENTIFIER, '***')).toBe(false) + }) + + it('refuses a tag of any length but 8 bytes, even one that starts the right way', async () => { + // The first byte of the real tag, alone: it would match a check that compared only what it was given. + expect(await authTagMatches(HOST_ID, IDENTIFIER, 'dg==')).toBe(false) + expect(await authTagMatches(HOST_ID, IDENTIFIER, 'dr5/vaK9kIwA')).toBe( + false + ) + }) +}) + +/** A socket on a fake network: each query is answered at once with `answers()`. */ +const fakeSocket = (answers: () => Uint8Array[], deny = false) => { + const listeners = new Set<(datagram: Datagram) => void>() + let sent = 0 + const socket: MulticastSocket = { + send: async () => { + if (deny) throw new IPAForgeError(ErrorCode.LocalNetworkDenied) + sent++ + for (const bytes of answers()) + for (const listener of [...listeners]) + listener({ bytes, from: '192.0.2.10' }) + }, + onMessage: (listener) => { + listeners.add(listener) + return () => listeners.delete(listener) + }, + close: async () => listeners.clear() + } + + return { socket, sent: () => sent } +} + +const browse = async ( + socket: MulticastSocket, + rounds: number, + onRound: (round: number) => void = () => {} +) => { + const events: BrowseEvent[] = [] + const controller = new AbortController() + let now = 0 + let round = 0 + await browseWifiDevices( + socket, + { + logger: silentLogger, + intervalMs: 1000, + now: () => now, + sleep: async () => { + now += 1000 + round++ + onRound(round) + if (round >= rounds) controller.abort() + } + }, + (event) => events.push(event), + controller.signal + ) + return events +} + +describe('searching the network', () => { + it('finds a device once, with its address, MAC and TXT values', async () => { + const { socket, sent } = fakeSocket(() => [lockdownAdvert(ADVERT)]) + const events = await browse(socket, 2) + expect(events).toEqual([ + { + kind: 'found', + advert: { + instance: `${ADVERT.mac}@fe80::1-supportsRP-24.${WIFI_LOCKDOWN_SERVICE}`, + address: '192.0.2.10', + mac: ADVERT.mac, + identifier: '0A1B2C3D-4E5F-4A6B-8C7D-9E0F1A2B3C4D', + authTags: ['dr5/vaK9kIw='] + } + } + ]) + expect(sent()).toBe(2) + }) + + it('loses a device on its goodbye, or after three silent rounds', async () => { + let answer = lockdownAdvert(ADVERT) + const goodbye = fakeSocket(() => [answer]) + const said = await browse(goodbye.socket, 2, () => { + answer = lockdownAdvert({ ...ADVERT, ttl: 0 }) + }) + expect(said.map((event) => event.kind)).toEqual(['found', 'lost']) + + let isThere = true + const silent = fakeSocket(() => (isThere ? [lockdownAdvert(ADVERT)] : [])) + const quiet = await browse(silent.socket, 6, () => { + isThere = false + }) + expect(quiet.map((event) => event.kind)).toEqual(['found', 'lost']) + }) + + it('stops with local_network_denied when the OS refuses the search', async () => { + const { socket } = fakeSocket(() => [], true) + await expect(browse(socket, 1)).rejects.toMatchObject({ + code: ErrorCode.LocalNetworkDenied + }) + }) +}) diff --git a/packages/device/src/infrastructure/mdns/message.ts b/packages/device/src/infrastructure/mdns/message.ts new file mode 100644 index 00000000..ee1c1011 --- /dev/null +++ b/packages/device/src/infrastructure/mdns/message.ts @@ -0,0 +1,173 @@ +// DNS messages as mDNS uses them (RFC 1035, RFC 6762): building a query and reading the records of an answer, +// name compression included. Records of types the device adverts don't use are skipped. +import { + CLASS_IN, + CLASS_MASK, + MAX_NAME_JUMPS, + RecordType +} from '@device/infrastructure/mdns/constants.ts' +import type { + DnsMessage, + DnsQuestion, + ResourceRecord +} from '@device/infrastructure/mdns/types.ts' +import { + ByteReader, + ByteWriter, + ErrorCode, + IPAForgeError, + utf8Decode, + utf8Encode +} from '@ipaforge/kernel' + +const HEADER_BYTES = 12 +const RESPONSE_FLAG = 0x80_00 +const POINTER = 0xc0 + +const malformed = (message: string) => + new IPAForgeError(ErrorCode.DeviceProtocolError, { + message: `mDNS: ${message}` + }) + +const writeName = (writer: ByteWriter, name: string): void => { + for (const label of name.split('.').filter(Boolean)) { + const bytes = utf8Encode(label) + if (bytes.length > 63) throw malformed(`label too long in ${name}`) + writer.u8(bytes.length).bytes(bytes) + } + writer.u8(0) +} + +/** A query for `questions`, with `id` (an answer sent back to our own port echoes it). */ +export const encodeQuery = ( + questions: readonly DnsQuestion[], + id: number +): Uint8Array => { + const writer = new ByteWriter() + writer.u16be(id).u16be(0).u16be(questions.length).u16be(0).u16be(0).u16be(0) + for (const question of questions) { + writeName(writer, question.name) + writer.u16be(question.type).u16be(CLASS_IN) + } + + return writer.toBytes() +} + +/** Reads the name at `offset`, following compression pointers; returns it and where the name ended. */ +const readName = ( + bytes: Uint8Array, + offset: number +): { readonly name: string; readonly end: number } => { + const labels: string[] = [] + let position = offset + let end: number | undefined + for (let jumps = 0; jumps <= MAX_NAME_JUMPS; ) { + const length = bytes[position] + if (length === undefined) throw malformed('name runs past the message') + if (length === 0) + return { name: labels.join('.'), end: end ?? position + 1 } + if ((length & POINTER) === POINTER) { + const low = bytes[position + 1] + if (low === undefined) throw malformed('pointer runs past the message') + end ??= position + 2 + position = ((length & ~POINTER) << 8) | low + jumps++ + continue + } + labels.push(utf8Decode(bytes.subarray(position + 1, position + 1 + length))) + position += 1 + length + } + throw malformed('name compression loops') +} + +const ipv4 = (data: Uint8Array): string => [...data].join('.') + +const ipv6 = (data: Uint8Array): string => { + const groups: string[] = [] + for (let index = 0; index < 16; index += 2) + groups.push( + (((data[index] ?? 0) << 8) | (data[index + 1] ?? 0)).toString(16) + ) + return groups.join(':') +} + +const txtEntries = (data: Uint8Array): string[] => { + const entries: string[] = [] + for (let position = 0; position < data.length; ) { + const length = data[position] ?? 0 + if (length > 0) + entries.push( + utf8Decode(data.subarray(position + 1, position + 1 + length)) + ) + position += 1 + length + } + return entries +} + +const readRecord = ( + bytes: Uint8Array, + offset: number +): { readonly record: ResourceRecord | undefined; readonly end: number } => { + const { name, end: nameEnd } = readName(bytes, offset) + const reader = new ByteReader(bytes, nameEnd) + if (reader.remaining < 10) + throw malformed('record header runs past the message') + const type = reader.u16be() + const recordClass = reader.u16be() & CLASS_MASK + const ttl = reader.u32be() + const length = reader.u16be() + if (reader.remaining < length) + throw malformed('record data runs past the message') + const dataStart = reader.position + const data = reader.bytes(length) + const end = dataStart + length + if (recordClass !== CLASS_IN) return { record: undefined, end } + const base = { name, ttl } + if (type === RecordType.PTR) + return { + record: { ...base, type, target: readName(bytes, dataStart).name }, + end + } + if (type === RecordType.SRV) { + const port = ((data[4] ?? 0) << 8) | (data[5] ?? 0) + + return { + record: { + ...base, + type, + port, + target: readName(bytes, dataStart + 6).name + }, + end + } + } + if (type === RecordType.TXT) + return { record: { ...base, type, entries: txtEntries(data) }, end } + if (type === RecordType.A && length === 4) + return { record: { ...base, type, address: ipv4(data) }, end } + if (type === RecordType.AAAA && length === 16) + return { record: { ...base, type, address: ipv6(data) }, end } + return { record: undefined, end } +} + +/** Every record an mDNS message carries (answers, authority, additional); questions are skipped. */ +export const decodeMessage = (bytes: Uint8Array): DnsMessage => { + if (bytes.length < HEADER_BYTES) + throw malformed('message shorter than its header') + const header = new ByteReader(bytes) + const id = header.u16be() + const flags = header.u16be() + const questions = header.u16be() + const recordCount = header.u16be() + header.u16be() + header.u16be() + let position = HEADER_BYTES + for (let index = 0; index < questions; index++) + position = readName(bytes, position).end + 4 + const records: ResourceRecord[] = [] + for (let index = 0; index < recordCount; index++) { + const { record, end } = readRecord(bytes, position) + if (record) records.push(record) + position = end + } + + return { id, isResponse: (flags & RESPONSE_FLAG) !== 0, records } +} diff --git a/packages/device/src/infrastructure/mdns/types.ts b/packages/device/src/infrastructure/mdns/types.ts new file mode 100644 index 00000000..6fdbf268 --- /dev/null +++ b/packages/device/src/infrastructure/mdns/types.ts @@ -0,0 +1,76 @@ +import type { RecordType } from '@device/infrastructure/mdns/constants.ts' +import type { Sleep } from '@device/types.ts' +import type { Logger } from '@ipaforge/kernel' + +type RecordBase = { + readonly name: string + /** Seconds; 0 is a goodbye (the record is withdrawn). */ + readonly ttl: number +} + +export type ResourceRecord = + | (RecordBase & { + readonly type: typeof RecordType.PTR + readonly target: string + }) + | (RecordBase & { + readonly type: typeof RecordType.SRV + readonly port: number + readonly target: string + }) + | (RecordBase & { + readonly type: typeof RecordType.TXT + readonly entries: readonly string[] + }) + | (RecordBase & { + readonly type: typeof RecordType.A + readonly address: string + }) + | (RecordBase & { + readonly type: typeof RecordType.AAAA + readonly address: string + }) + +export type DnsQuestion = { + readonly name: string + readonly type: number +} + +export type DnsMessage = { + readonly id: number + readonly isResponse: boolean + /** Answers, then authority and additional records: every record the message carries, in order. */ + readonly records: readonly ResourceRecord[] +} + +/** A device advertising lockdown over Wi-Fi, as one search found it. */ +export type WifiAdvert = { + /** The service instance name (`@
-supportsRP-NN…`), the advert's identity on this network. */ + readonly instance: string + /** Its IPv4 address. */ + readonly address: string + /** The MAC address in the instance name: the device's real one, or a private one for this network. */ + readonly mac?: string | undefined + /** TXT `identifier` and `authTag` values (iOS 26.4 and later), checked against the pair records. */ + readonly identifier?: string | undefined + readonly authTags: readonly string[] +} + +export type BrowseEvent = + | { readonly kind: 'found'; readonly advert: WifiAdvert } + | { readonly kind: 'lost'; readonly instance: string } + +export type BrowseOptions = { + readonly sleep: Sleep + /** Milliseconds since some fixed point, to time rounds. */ + readonly now: () => number + readonly intervalMs: number + readonly logger: Logger +} + +/** What one search knows of an instance before its address is in: where it is, and its TXT values. */ +export type PendingAdvert = { + host?: string + identifier?: string | undefined + authTags: string[] +} diff --git a/packages/installer/src/application/device-watch.test.ts b/packages/installer/src/application/device-watch.test.ts index e0bc7908..05691f81 100644 --- a/packages/installer/src/application/device-watch.test.ts +++ b/packages/installer/src/application/device-watch.test.ts @@ -19,20 +19,33 @@ type Session = { readonly signal: AbortSignal } -/** A DeviceManager whose `Listen` sessions the test drives: each `watch` call is a session that stays open. */ -const fakeUsbmux = (listed: () => UsbmuxDevice[]) => { - const sessions: Session[] = [] - const listDevices = vi.fn(async () => listed()) - const watch = vi.fn( +/** A session the test drives: it stays open until aborted or dropped. */ +const sessionsOf = (sessions: Session[]) => + vi.fn( (onEvent: (event: DeviceEvent) => void, signal: AbortSignal) => new Promise((resolve, reject) => { sessions.push({ emit: onEvent, drop: reject, signal }) signal.addEventListener('abort', () => resolve(), { once: true }) }) ) - const devices = { listDevices, watch } as unknown as DeviceManager - return { devices, listDevices, watch, sessions } +/** + * A DeviceManager whose `Listen` sessions and network searches the test drives: each `watch` and `watchNetwork` + * call is a session that stays open. + */ +const fakeUsbmux = (listed: () => UsbmuxDevice[]) => { + const sessions: Session[] = [] + const searches: Session[] = [] + const listDevices = vi.fn(async () => listed()) + const watch = sessionsOf(sessions) + const watchNetwork = sessionsOf(searches) + const devices = { + listDevices, + watch, + watchNetwork + } as unknown as DeviceManager + + return { devices, listDevices, watch, sessions, searches } } const config = { @@ -181,4 +194,48 @@ describe('createDeviceWatch', () => { watch.subscribe(() => {}) await vi.waitFor(() => expect(sessions).toHaveLength(2)) }) + + it('adds devices found on Wi-Fi, each with its best link: USB, then straight over Wi-Fi, then usbmuxd', async () => { + const usbmuxWifi: UsbmuxDevice = { + udid: 'IPAD', + deviceId: 2, + connectionType: 'network' + } + const { watch, sessions, searches } = setup(() => [IPHONE, usbmuxWifi]) + const { events, listener } = record() + watch.subscribe(listener) + await vi.waitFor(() => expect(sessions).toHaveLength(1)) + await vi.waitFor(() => expect(searches).toHaveLength(1)) + const [search] = searches + const direct = (udid: string, deviceId: number): UsbmuxDevice => ({ + udid, + deviceId, + connectionType: 'network', + address: '192.0.2.10' + }) + search?.emit({ kind: 'attached', device: direct('IPHONE', -1) }) + search?.emit({ kind: 'attached', device: direct('IPAD', -2) }) + search?.emit({ kind: 'attached', device: direct('IPOD', -3) }) + + const last = events.filter((event) => event.type === 'devices').at(-1) + expect(last).toEqual({ + type: 'devices', + devices: [IPHONE, direct('IPAD', -2), direct('IPOD', -3)] + }) + }) + + it('says when the OS refuses local network access, also to a listener that comes later', async () => { + const { watch, searches } = setup() + const first = record() + watch.subscribe(first.listener) + await vi.waitFor(() => expect(searches).toHaveLength(1)) + searches[0]?.drop(new IPAForgeError(ErrorCode.LocalNetworkDenied)) + await vi.waitFor(() => + expect(first.events).toContainEqual({ type: 'network', denied: true }) + ) + + const late = record() + watch.subscribe(late.listener) + expect(late.events).toContainEqual({ type: 'network', denied: true }) + }) }) diff --git a/packages/installer/src/application/device-watch.ts b/packages/installer/src/application/device-watch.ts index ba88d4a5..732ecb7d 100644 --- a/packages/installer/src/application/device-watch.ts +++ b/packages/installer/src/application/device-watch.ts @@ -1,6 +1,8 @@ // Connected devices as a live feed, from usbmuxd's `Listen` instead of polling. One connection serves every // listener. When it drops (the usbmuxd service restarted, the computer slept), it reconnects with backoff and sends // one full list again; only when usbmuxd refuses `Listen` outright does it fall back to reading the list slowly. +// Beside it, a search of the local network finds known devices on Wi-Fi without usbmuxd (it keeps going when +// usbmuxd is missing), and says when the OS refuses local network access. import type { DeviceWatch, @@ -28,17 +30,26 @@ const abortableSleep = (ms: number, signal: AbortSignal): Promise => ) }) -/** One entry per device: a device on USB and Wi-Fi is listed with its USB link. */ +/** How good a link is: USB, then straight over Wi-Fi (faster than usbmuxd's), then usbmuxd over Wi-Fi. */ +const linkRank = (device: UsbmuxDevice): number => { + if (device.connectionType === 'usb') return 0 + return device.address === undefined ? 2 : 1 +} + +/** One entry per device, with its best link. */ const byDevice = (attached: ReadonlyMap) => { const devices = new Map() for (const device of attached.values()) { const known = devices.get(device.udid) - if (!known || device.connectionType === 'usb') + if (!known || linkRank(device) < linkRank(known)) devices.set(device.udid, device) } return [...devices.values()] } +const isLocalNetworkDenied = (error: unknown): boolean => + error instanceof IPAForgeError && error.code === ErrorCode.LocalNetworkDenied + /** usbmuxd answered `Listen` with an error before sending anything: it will not stream on this machine. */ const isListenRefused = (error: unknown, received: boolean): boolean => !received && @@ -56,6 +67,7 @@ export const createDeviceWatch = ({ let attached = new Map() let current: readonly UsbmuxDevice[] | undefined let controller: AbortController | undefined + let networkDenied = false const emit = (event: DeviceWatchEvent) => { for (const listener of [...listeners]) listener(event) @@ -126,6 +138,35 @@ export const createDeviceWatch = ({ }) } + const setNetworkDenied = (denied: boolean) => { + if (denied === networkDenied) return + networkDenied = denied + emit({ type: 'network', denied }) + } + + /** Searches the network until aborted; retries with backoff, and ends when the host can't search at all. */ + const searchNetwork = async (signal: AbortSignal) => { + let failures = 0 + while (!signal.aborted) { + try { + await devices.watchNetwork((event) => { + setNetworkDenied(false) + apply(event) + }, signal) + return + } catch (error) { + if (signal.aborted) return + setNetworkDenied(isLocalNetworkDenied(error)) + failures += 1 + log.warn('network search failed; retrying', { + code: toIPAForgeError(error).code, + attempt: failures + }) + await sleep(backoff(failures), signal) + } + } + } + const run = async (signal: AbortSignal) => { let failures = 0 while (!signal.aborted) { @@ -155,6 +196,9 @@ export const createDeviceWatch = ({ run(own.signal).catch(() => { // Only an abort ends the loop with an error; it is how the watch stops. }) + searchNetwork(own.signal).catch(() => { + // As above: only an abort. + }) } const stop = () => { @@ -162,6 +206,7 @@ export const createDeviceWatch = ({ controller = undefined attached = new Map() current = undefined + networkDenied = false log.info('stopped watching devices') } @@ -170,7 +215,10 @@ export const createDeviceWatch = ({ if (signal?.aborted) return () => {} listeners.add(listener) if (!controller) start() - else if (current) listener({ type: 'devices', devices: current }) + else if (current) { + listener({ type: 'devices', devices: current }) + if (networkDenied) listener({ type: 'network', denied: true }) + } const unsubscribe = () => { signal?.removeEventListener('abort', unsubscribe) if (!listeners.delete(listener)) return diff --git a/packages/installer/src/application/types.ts b/packages/installer/src/application/types.ts index 08b9a59c..d9954b69 100644 --- a/packages/installer/src/application/types.ts +++ b/packages/installer/src/application/types.ts @@ -35,6 +35,8 @@ export type DeviceWatchEvent = readonly deviceId: number readonly udid?: string } + /** Whether the OS refuses IPAForge local network access (macOS Local Network), so Wi-Fi devices can't be found. */ + | { readonly type: 'network'; readonly denied: boolean } export type DeviceWatchListener = (event: DeviceWatchEvent) => void diff --git a/packages/installer/src/diagnostics/catalogue.ts b/packages/installer/src/diagnostics/catalogue.ts index 5dc103c7..6533e0d3 100644 --- a/packages/installer/src/diagnostics/catalogue.ts +++ b/packages/installer/src/diagnostics/catalogue.ts @@ -33,6 +33,8 @@ export const RECOVERY_CATALOGUE = { ], 'device.profile_not_found': [R.Retry, R.ReinstallApp], 'device.pairing_path_invalid': [R.Retry], + // A cable still works while Wi-Fi is refused. + 'device.local_network_denied': [R.AllowLocalNetwork, R.ReconnectDevice], // apple 'apple.anisette_unavailable': [ diff --git a/packages/installer/src/diagnostics/recovery.ts b/packages/installer/src/diagnostics/recovery.ts index 24f88138..5dd130d4 100644 --- a/packages/installer/src/diagnostics/recovery.ts +++ b/packages/installer/src/diagnostics/recovery.ts @@ -26,6 +26,8 @@ export const RecoveryAction = { PairAgain: 'pair-again', SetPasscode: 'set-passcode', InstallDeviceSupport: 'install-device-support', + /** macOS: allow IPAForge to find devices on the local network (Privacy & Security › Local Network). */ + AllowLocalNetwork: 'allow-local-network', ReinstallApp: 'reinstall-app', ChooseAnotherIpa: 'choose-another-ipa', ChooseAnotherChannel: 'choose-another-channel', diff --git a/packages/kernel/src/errors/codes.ts b/packages/kernel/src/errors/codes.ts index 7adf9f1c..99759ad0 100644 --- a/packages/kernel/src/errors/codes.ts +++ b/packages/kernel/src/errors/codes.ts @@ -26,6 +26,7 @@ export const ErrorCode = { SigningIdentityInvalid: 'device.identity_invalid', ProfileNotFound: 'device.profile_not_found', PairingPathInvalid: 'device.pairing_path_invalid', + LocalNetworkDenied: 'device.local_network_denied', // apple AnisetteUnavailable: 'apple.anisette_unavailable', diff --git a/packages/rpc/src/domain/protocol/subscriptions.ts b/packages/rpc/src/domain/protocol/subscriptions.ts index a3761564..6e83a061 100644 --- a/packages/rpc/src/domain/protocol/subscriptions.ts +++ b/packages/rpc/src/domain/protocol/subscriptions.ts @@ -21,5 +21,6 @@ export const deviceWatchEventSchema = z.discriminatedUnion('type', [ type: z.literal('detached'), deviceId: z.number().int(), udid: z.string().optional() - }) + }), + z.object({ type: z.literal('network'), denied: z.boolean() }) ]) diff --git a/packages/ui/src/__tests__/screen-table.ts b/packages/ui/src/__tests__/screen-table.ts index bc9924ad..1e70bc41 100644 --- a/packages/ui/src/__tests__/screen-table.ts +++ b/packages/ui/src/__tests__/screen-table.ts @@ -5,6 +5,7 @@ import { checklistShown, developerShown, fillPreload, + localNetworkNoticeShown, logsShown, openAddAllToSideStore, openPairingFiles, @@ -76,6 +77,13 @@ export const screens = { await renderScreen('/devices', { ...options, scenario: 'checklist-todo' }) await checklistShown() }, + 'devices-local-network': async (options: ScreenOptions) => { + await renderScreen('/devices', { + ...options, + scenario: 'local-network-denied' + }) + await localNetworkNoticeShown() + }, apps: async (options: ScreenOptions) => { await renderScreen('/apps', options) await appsShown() diff --git a/packages/ui/src/__tests__/screens.ts b/packages/ui/src/__tests__/screens.ts index e7838e1e..25a513c3 100644 --- a/packages/ui/src/__tests__/screens.ts +++ b/packages/ui/src/__tests__/screens.ts @@ -168,6 +168,12 @@ export const renderChangelog = async ({ export const anisetteShown = () => waitFor(() => expect(all('main ul li').length).toBeGreaterThanOrEqual(4)) +/** Devices with macOS's Local Network refusal noted (its button opens the settings). */ +export const localNetworkNoticeShown = () => + waitFor(() => + expect(all('main [role="status"] button').length).toBeGreaterThanOrEqual(1) + ) + /** The Install page has the Engine's plan (App IDs, free apps, certificate, team). */ export const planShown = () => waitFor(() => expect(all('main dl dd').length).toBeGreaterThanOrEqual(4)) diff --git a/packages/ui/src/features/devices/components/local-network-notice.test.tsx b/packages/ui/src/features/devices/components/local-network-notice.test.tsx new file mode 100644 index 00000000..f8ff5235 --- /dev/null +++ b/packages/ui/src/features/devices/components/local-network-notice.test.tsx @@ -0,0 +1,37 @@ +import { screen, within } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { describe, expect, it } from 'vitest' + +import { t } from '@ui/__tests__/test-i18n.ts' +import { renderApp } from '@ui/__tests__/test-services.tsx' +import { LOCAL_NETWORK_SETTINGS_URL } from '@ui/features/devices/constants.ts' + +describe('Local network notice', () => { + it('says on the Devices page when macOS refuses the search on Wi-Fi, and opens its settings', async () => { + const user = userEvent.setup() + const { links } = await renderApp('/devices', { + scenario: 'local-network-denied' + }) + const notice = ( + await screen.findByText(t('errors.device.local_network_denied.title')) + ).closest('[role="status"]') as HTMLElement + expect(notice.textContent).toContain( + t('recovery.fix.allowLocalNetwork.how') + ) + + await user.click( + within(notice).getByRole('button', { + name: t('devices.localNetwork.open') + }) + ) + expect(links.opened).toEqual([LOCAL_NETWORK_SETTINGS_URL]) + }) + + it('stays away while the search is allowed', async () => { + await renderApp('/devices') + await screen.findByRole('heading', { level: 1, name: t('nav.devices') }) + expect( + screen.queryByText(t('errors.device.local_network_denied.title')) + ).toBeNull() + }) +}) diff --git a/packages/ui/src/features/devices/components/local-network-notice.tsx b/packages/ui/src/features/devices/components/local-network-notice.tsx new file mode 100644 index 00000000..d06a665c --- /dev/null +++ b/packages/ui/src/features/devices/components/local-network-notice.tsx @@ -0,0 +1,34 @@ +import { Button } from '@heroui/react' +import { useTranslation } from 'react-i18next' + +import { NoticeBox } from '@ui/features/devices/components/notice-box.tsx' +import { LOCAL_NETWORK_SETTINGS_URL } from '@ui/features/devices/constants.ts' +import { useLocalNetworkDenied } from '@ui/hooks/queries/use-local-network-denied.ts' +import { useUiServices } from '@ui/hooks/use-ui-services.ts' + +/** macOS refused IPAForge local network access: devices on Wi-Fi can't be found until it is allowed. */ +export const LocalNetworkNotice = () => { + const { t } = useTranslation() + const { links } = useUiServices() + const isDenied = useLocalNetworkDenied() + if (!isDenied) return null + const onOpen = () => links.open(LOCAL_NETWORK_SETTINGS_URL) + + return ( + +

{t('errors.device.local_network_denied.body')}

+

{t('recovery.fix.allowLocalNetwork.how')}

+ + } + action={ + + } + /> + ) +} diff --git a/packages/ui/src/features/devices/constants.ts b/packages/ui/src/features/devices/constants.ts index 08564f68..29edf4d3 100644 --- a/packages/ui/src/features/devices/constants.ts +++ b/packages/ui/src/features/devices/constants.ts @@ -139,3 +139,7 @@ export const modelNames: Readonly> = { 'iPad16,5': 'iPad Pro 13-inch (M4)', 'iPad16,6': 'iPad Pro 13-inch (M4)' } + +/** macOS System Settings › Privacy & Security › Local Network. */ +export const LOCAL_NETWORK_SETTINGS_URL = + 'x-apple.systempreferences:com.apple.preference.security?Privacy_LocalNetwork' diff --git a/packages/ui/src/features/devices/devices-page.tsx b/packages/ui/src/features/devices/devices-page.tsx index 5ca93cae..340541c4 100644 --- a/packages/ui/src/features/devices/devices-page.tsx +++ b/packages/ui/src/features/devices/devices-page.tsx @@ -6,13 +6,15 @@ import { PageHeader } from '@ui/components/page-header.tsx' import { DeviceChecklist } from '@ui/features/devices/checklist/components/device-checklist.tsx' import { DeviceCard } from '@ui/features/devices/components/device-card.tsx' import { EngineStatus } from '@ui/features/devices/components/engine-status.tsx' +import { LocalNetworkNotice } from '@ui/features/devices/components/local-network-notice.tsx' import { useRefreshDeviceStatus } from '@ui/hooks/queries/use-device-status.ts' import { useDevices } from '@ui/hooks/queries/use-devices.ts' import { useDeviceInUse, useSelection } from '@ui/hooks/use-selection.ts' /** - * Manage → Devices: every connected device (and the picked one while it is unplugged) with its state and what to - * do about it. Opening the page reads every device's status again. + * Manage → Devices: every connected device, by cable or on Wi-Fi (and the picked one while it is unplugged), with + * its state and what to do about it, and a note when macOS refuses the search on Wi-Fi. Opening the page reads every + * device's status again. */ export const DevicesPage = () => { const { t } = useTranslation() @@ -29,6 +31,7 @@ export const DevicesPage = () => {
+ {devices.map((device) => (
export const queryKeys = { devices: ['devices'] as const, + /** Whether the OS refuses local network access (macOS), so devices on Wi-Fi can't be found: from the feed. */ + localNetworkDenied: ['local-network-denied'] as const, deviceStatus: (udid: string | undefined) => ['devices', udid ?? null, 'status'] as const, accounts: ['accounts'] as const, diff --git a/packages/ui/src/hooks/queries/use-device-feed.ts b/packages/ui/src/hooks/queries/use-device-feed.ts index 585003c1..7bb83e53 100644 --- a/packages/ui/src/hooks/queries/use-device-feed.ts +++ b/packages/ui/src/hooks/queries/use-device-feed.ts @@ -7,8 +7,9 @@ import { uniqueDevices } from '@ui/hooks/queries/use-devices.ts' import { useEngine } from '@ui/hooks/use-engine.ts' /** - * Keeps the device queries in step with the Engine's device feed (usbmuxd `Listen`): every new list replaces the - * cached one, and a device that comes or goes has its status read again. Mounted once, by `App`. + * Keeps the device queries in step with the Engine's device feed (usbmuxd `Listen` and the search of the local + * network): every new list replaces the cached one, a device that comes or goes has its status read again, and a + * refused local network access is kept for the Devices page. Mounted once, by `App`. */ export const useDeviceFeed = (): void => { const engine = useEngine() @@ -23,6 +24,10 @@ export const useDeviceFeed = (): void => { ) return } + if (event.type === 'network') { + queryClient.setQueryData(queryKeys.localNetworkDenied, event.denied) + return + } const udid = event.type === 'attached' ? event.device.udid : event.udid if (udid) void queryClient.invalidateQueries({ diff --git a/packages/ui/src/hooks/queries/use-local-network-denied.ts b/packages/ui/src/hooks/queries/use-local-network-denied.ts new file mode 100644 index 00000000..dd599845 --- /dev/null +++ b/packages/ui/src/hooks/queries/use-local-network-denied.ts @@ -0,0 +1,17 @@ +import { skipToken, useQuery } from '@tanstack/react-query' + +import { queryKeys } from '@ui/hooks/queries/query-keys.ts' + +/** + * Whether the OS refuses IPAForge local network access (macOS), as the device feed last said: false until it does. + * Never fetched: only the feed writes it, so nothing can overwrite what the feed said. + */ +export const useLocalNetworkDenied = (): boolean => { + const { data } = useQuery({ + queryKey: queryKeys.localNetworkDenied, + queryFn: skipToken, + staleTime: Number.POSITIVE_INFINITY + }) + + return data ?? false +} diff --git a/packages/ui/src/locales/ar.json b/packages/ui/src/locales/ar.json index 460ebd05..5dcebfe6 100644 --- a/packages/ui/src/locales/ar.json +++ b/packages/ui/src/locales/ar.json @@ -443,6 +443,10 @@ "pairing_path_invalid": { "title": "لا يمكن وضع ملف اقتران في هذا المسار", "body": "استخدم مسارًا في Documents أو Library الخاصة بالتطبيق ينتهي بـ ‎.plist أو ‎.mobiledevicepairing." + }, + "local_network_denied": { + "title": "لا يستطيع IPAForge البحث عن الأجهزة في شبكتك", + "body": "لم يسمح macOS لـ IPAForge بالعثور على الأجهزة في شبكتك المحلية، لذا لا يمكنه الوصول إلى أجهزة iPhone عبر Wi-Fi. الأجهزة الموصولة بالكابل تعمل كالمعتاد." } }, "apple": { @@ -877,9 +881,13 @@ "changeAnisetteServer": { "how": "افتح الإعدادات، واختبر خوادم anisette، واختر خادمًا يعمل، أو عُد إلى الوضع التلقائي.", "button": "فتح خوادم anisette" + }, + "allowLocalNetwork": { + "how": "افتح إعدادات النظام › الخصوصية والأمن › الشبكة المحلية، وفعّل IPAForge، ثم حاول مرة أخرى. أو وصّل الجهاز بالكابل." } }, - "reportHint": "يفتح بلاغًا جديدًا على GitHub مع ملء التشخيص. لا يُرسل شيء حتى ترسله بنفسك." + "reportHint": "يفتح بلاغًا جديدًا على GitHub مع ملء التشخيص. لا يُرسل شيء حتى ترسله بنفسك.", + "allow-local-network": "السماح بالوصول إلى الشبكة المحلية" }, "devices": { "engine": { @@ -958,7 +966,10 @@ "disconnected": "تم فصل {name}", "aDevice": "جهاز" }, - "savePairing": "حفظ ملف الاقتران…" + "savePairing": "حفظ ملف الاقتران…", + "localNetwork": { + "open": "افتح إعدادات الشبكة المحلية" + } }, "prompts": { "cancel": "إلغاء", diff --git a/packages/ui/src/locales/de.json b/packages/ui/src/locales/de.json index 27a2157a..615f0fdd 100644 --- a/packages/ui/src/locales/de.json +++ b/packages/ui/src/locales/de.json @@ -443,6 +443,10 @@ "pairing_path_invalid": { "title": "Dieser Pfad kann keine Kopplungsdatei aufnehmen", "body": "Nutze einen Pfad in Documents oder Library der App, der auf .plist oder .mobiledevicepairing endet." + }, + "local_network_denied": { + "title": "IPAForge kann im Netzwerk nicht nach Geräten suchen", + "body": "macOS hat IPAForge nicht erlaubt, Geräte im lokalen Netzwerk zu finden, daher erreicht es iPhones nicht über WLAN. Geräte am Kabel funktionieren weiterhin." } }, "apple": { @@ -877,9 +881,13 @@ "changeAnisetteServer": { "how": "Öffne die Einstellungen, teste die Anisette-Server und wähle einen, der funktioniert, oder wechsle zurück zu Automatisch.", "button": "Anisette-Server öffnen" + }, + "allowLocalNetwork": { + "how": "Öffne Systemeinstellungen › Datenschutz & Sicherheit › Lokales Netzwerk, aktiviere IPAForge und versuche es erneut. Oder schließe das Gerät per Kabel an." } }, - "reportHint": "Öffnet ein neues GitHub-Issue mit der Diagnose. Nichts wird gesendet, bevor du es abschickst." + "reportHint": "Öffnet ein neues GitHub-Issue mit der Diagnose. Nichts wird gesendet, bevor du es abschickst.", + "allow-local-network": "Zugriff auf das lokale Netzwerk erlauben" }, "devices": { "engine": { @@ -958,7 +966,10 @@ "disconnected": "{name} getrennt", "aDevice": "Ein Gerät" }, - "savePairing": "Kopplungsdatei sichern…" + "savePairing": "Kopplungsdatei sichern…", + "localNetwork": { + "open": "Einstellungen für lokales Netzwerk öffnen" + } }, "prompts": { "cancel": "Abbrechen", diff --git a/packages/ui/src/locales/en.json b/packages/ui/src/locales/en.json index 3948e0fe..bc574a50 100644 --- a/packages/ui/src/locales/en.json +++ b/packages/ui/src/locales/en.json @@ -443,6 +443,10 @@ "pairing_path_invalid": { "title": "That path can’t hold a pairing file", "body": "Use a path in the app’s Documents or Library that ends in .plist or .mobiledevicepairing." + }, + "local_network_denied": { + "title": "IPAForge can't look for devices on your network", + "body": "macOS hasn't allowed IPAForge to find devices on your local network, so it can't reach iPhones over Wi-Fi. Devices on a cable still work." } }, "apple": { @@ -877,9 +881,13 @@ "changeAnisetteServer": { "how": "Open Settings, test the anisette servers, and choose one that works, or go back to Automatic.", "button": "Open anisette servers" + }, + "allowLocalNetwork": { + "how": "Open System Settings › Privacy & Security › Local Network, turn on IPAForge, then try again. Or connect the device with a cable." } }, - "reportHint": "Opens a new GitHub issue with the diagnostics filled in. Nothing is sent until you submit it." + "reportHint": "Opens a new GitHub issue with the diagnostics filled in. Nothing is sent until you submit it.", + "allow-local-network": "Allow local network access" }, "devices": { "engine": { @@ -958,7 +966,10 @@ "disconnected": "{name} disconnected", "aDevice": "A device" }, - "savePairing": "Save pairing file…" + "savePairing": "Save pairing file…", + "localNetwork": { + "open": "Open Local Network settings" + } }, "prompts": { "cancel": "Cancel", diff --git a/packages/ui/src/locales/ja.json b/packages/ui/src/locales/ja.json index b21adf9a..6e8aa215 100644 --- a/packages/ui/src/locales/ja.json +++ b/packages/ui/src/locales/ja.json @@ -443,6 +443,10 @@ "pairing_path_invalid": { "title": "このパスにはペアリングファイルを置けません", "body": "アプリのDocumentsまたはLibrary内で、.plistまたは.mobiledevicepairingで終わるパスを使ってください。" + }, + "local_network_denied": { + "title": "IPAForge がネットワーク上のデバイスを探せません", + "body": "macOS が IPAForge にローカルネットワーク上のデバイスを探すことを許可していないため、Wi-Fi で iPhone に接続できません。ケーブル接続のデバイスは引き続き使えます。" } }, "apple": { @@ -877,9 +881,13 @@ "changeAnisetteServer": { "how": "設定を開いて anisette サーバーをテストし、動作するものを選ぶか、自動に戻してください。", "button": "anisette サーバーを開く" + }, + "allowLocalNetwork": { + "how": "システム設定 › プライバシーとセキュリティ › ローカルネットワーク で IPAForge をオンにしてから、もう一度お試しください。またはケーブルで接続してください。" } }, - "reportHint": "診断情報を記入した新しいGitHub Issueを開きます。送信するまで何も送られません。" + "reportHint": "診断情報を記入した新しいGitHub Issueを開きます。送信するまで何も送られません。", + "allow-local-network": "ローカルネットワークへのアクセスを許可" }, "devices": { "engine": { @@ -958,7 +966,10 @@ "disconnected": "{name}が切断されました", "aDevice": "デバイス" }, - "savePairing": "ペアリングファイルを保存…" + "savePairing": "ペアリングファイルを保存…", + "localNetwork": { + "open": "ローカルネットワークの設定を開く" + } }, "prompts": { "cancel": "キャンセル", diff --git a/packages/ui/src/locales/ro.json b/packages/ui/src/locales/ro.json index f3b39e63..183f5751 100644 --- a/packages/ui/src/locales/ro.json +++ b/packages/ui/src/locales/ro.json @@ -443,6 +443,10 @@ "pairing_path_invalid": { "title": "Calea nu poate ține un fișier de asociere", "body": "Folosește o cale în Documents sau Library a aplicației care se termină în .plist sau .mobiledevicepairing." + }, + "local_network_denied": { + "title": "IPAForge nu poate căuta dispozitive în rețea", + "body": "macOS nu i-a permis lui IPAForge să găsească dispozitive în rețeaua locală, așa că nu poate ajunge la iPhone-uri prin Wi-Fi. Dispozitivele conectate prin cablu funcționează în continuare." } }, "apple": { @@ -877,9 +881,13 @@ "changeAnisetteServer": { "how": "Deschide Setările, testează serverele anisette și alege unul care funcționează, sau revino la Automat.", "button": "Deschide serverele anisette" + }, + "allowLocalNetwork": { + "how": "Deschide Configurări sistem › Confidențialitate și securitate › Rețea locală, activează IPAForge, apoi încearcă din nou. Sau conectează dispozitivul prin cablu." } }, - "reportHint": "Deschide un tichet nou pe GitHub, cu diagnosticul completat. Nu se trimite nimic până nu îl publici tu." + "reportHint": "Deschide un tichet nou pe GitHub, cu diagnosticul completat. Nu se trimite nimic până nu îl publici tu.", + "allow-local-network": "Permite accesul la rețeaua locală" }, "devices": { "engine": { @@ -958,7 +966,10 @@ "disconnected": "{name} s-a deconectat", "aDevice": "Un dispozitiv" }, - "savePairing": "Salvează fișierul de asociere…" + "savePairing": "Salvează fișierul de asociere…", + "localNetwork": { + "open": "Deschide setările Rețea locală" + } }, "prompts": { "cancel": "Anulează", diff --git a/packages/ui/src/locales/ru.json b/packages/ui/src/locales/ru.json index 5d16b987..dc02b38c 100644 --- a/packages/ui/src/locales/ru.json +++ b/packages/ui/src/locales/ru.json @@ -443,6 +443,10 @@ "pairing_path_invalid": { "title": "По этому пути нельзя разместить файл сопряжения", "body": "Укажите путь в Documents или Library приложения, оканчивающийся на .plist или .mobiledevicepairing." + }, + "local_network_denied": { + "title": "IPAForge не может искать устройства в сети", + "body": "macOS не разрешила IPAForge находить устройства в локальной сети, поэтому он не может подключиться к iPhone по Wi-Fi. Устройства по кабелю по-прежнему работают." } }, "apple": { @@ -877,9 +881,13 @@ "changeAnisetteServer": { "how": "Откройте настройки, проверьте серверы anisette и выберите работающий или вернитесь к «Автоматически».", "button": "Открыть серверы anisette" + }, + "allowLocalNetwork": { + "how": "Откройте Системные настройки › Конфиденциальность и безопасность › Локальная сеть, включите IPAForge и повторите попытку. Или подключите устройство кабелем." } }, - "reportHint": "Открывает новый issue на GitHub с заполненной диагностикой. Ничего не отправляется, пока вы его не отправите." + "reportHint": "Открывает новый issue на GitHub с заполненной диагностикой. Ничего не отправляется, пока вы его не отправите.", + "allow-local-network": "Разрешить доступ к локальной сети" }, "devices": { "engine": { @@ -958,7 +966,10 @@ "disconnected": "{name}: отключено", "aDevice": "Устройство" }, - "savePairing": "Сохранить файл сопряжения…" + "savePairing": "Сохранить файл сопряжения…", + "localNetwork": { + "open": "Открыть настройки локальной сети" + } }, "prompts": { "cancel": "Отменить", diff --git a/packages/ui/src/services/engine/fake/fake-devices.ts b/packages/ui/src/services/engine/fake/fake-devices.ts index 24a31d6d..55ea9b2b 100644 --- a/packages/ui/src/services/engine/fake/fake-devices.ts +++ b/packages/ui/src/services/engine/fake/fake-devices.ts @@ -1,6 +1,6 @@ // The fake Engine's connected devices and their live feed, like the Engine's `watchDevices`: the list first, then // each attach and detach with the list after it. Tests plug devices in and out; the `hot-plug` scenario does it on -// a timer so the dev host shows the feed. +// a timer so the dev host shows the feed, and `local-network-denied` says macOS refused the search on Wi-Fi. import type { DeviceWatchEvent } from '@ipaforge/rpc' import { FAKE_IPAD, fakeDevices } from '@ui/services/engine/fake/fake-data.ts' import type { @@ -14,7 +14,8 @@ const HOT_PLUG_INTERVAL_MS = 5000 export const createFakeDeviceFeed = ( hotPlug: boolean, - initial: readonly Device[] = fakeDevices + initial: readonly Device[] = fakeDevices, + isLocalNetworkDenied = false ): FakeDeviceFeed => { let devices = [...initial] const listeners = new Set() @@ -56,6 +57,7 @@ export const createFakeDeviceFeed = ( watch: (listener, signal) => { listeners.add(listener) listener({ type: 'devices', devices }) + if (isLocalNetworkDenied) listener({ type: 'network', denied: true }) if (hotPlug && !timer) timer = setInterval(toggleIpad, HOT_PLUG_INTERVAL_MS) const unsubscribe = () => { diff --git a/packages/ui/src/services/engine/fake/fake-engine.ts b/packages/ui/src/services/engine/fake/fake-engine.ts index 46523b4b..63eb9aa9 100644 --- a/packages/ui/src/services/engine/fake/fake-engine.ts +++ b/packages/ui/src/services/engine/fake/fake-engine.ts @@ -193,7 +193,8 @@ export const createFakeEngine = ({ new Promise((resolve) => setTimeout(resolve, appleDelayMs)), devices = createFakeDeviceFeed( scenario === 'hot-plug', - scenario === 'devices' ? showcaseDevices : undefined + scenario === 'devices' ? showcaseDevices : undefined, + scenario === 'local-network-denied' ) }: FakeEngineOptions = {}): Engine => { const world = createFakeWorld(scenario, delayMs, appleAnswer) diff --git a/packages/ui/src/services/engine/fake/fake-scenarios.ts b/packages/ui/src/services/engine/fake/fake-scenarios.ts index a8d451e2..c0677c59 100644 --- a/packages/ui/src/services/engine/fake/fake-scenarios.ts +++ b/packages/ui/src/services/engine/fake/fake-scenarios.ts @@ -10,6 +10,7 @@ export const fakeScenarioIds = [ 'happy', 'computer-not-ready', 'hot-plug', + 'local-network-denied', 'devices', 'accounts', 'code-needed',