Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 |
Expand Down
2 changes: 2 additions & 0 deletions apps/desktop/build/mac-locales/ar.lproj/InfoPlist.strings
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/* macOS shows this when IPAForge first looks for devices on the local network. */
"NSLocalNetworkUsageDescription" = "يبحث IPAForge عن جهاز iPhone وiPad في الشبكة المحلية، ليتمكن من تثبيت التطبيقات عبر Wi-Fi دون كابل.";
2 changes: 2 additions & 0 deletions apps/desktop/build/mac-locales/de.lproj/InfoPlist.strings
Original file line number Diff line number Diff line change
@@ -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.";
2 changes: 2 additions & 0 deletions apps/desktop/build/mac-locales/en.lproj/InfoPlist.strings
Original file line number Diff line number Diff line change
@@ -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.";
2 changes: 2 additions & 0 deletions apps/desktop/build/mac-locales/ja.lproj/InfoPlist.strings
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/* macOS shows this when IPAForge first looks for devices on the local network. */
"NSLocalNetworkUsageDescription" = "IPAForge はローカルネットワーク上の iPhone と iPad を探し、ケーブルなしで Wi-Fi 経由でアプリをインストールします。";
2 changes: 2 additions & 0 deletions apps/desktop/build/mac-locales/ro.lproj/InfoPlist.strings
Original file line number Diff line number Diff line change
@@ -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.";
2 changes: 2 additions & 0 deletions apps/desktop/build/mac-locales/ru.lproj/InfoPlist.strings
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/* macOS shows this when IPAForge first looks for devices on the local network. */
"NSLocalNetworkUsageDescription" = "IPAForge ищет ваш iPhone и iPad в локальной сети, чтобы устанавливать приложения по Wi-Fi без кабеля.";
11 changes: 11 additions & 0 deletions apps/desktop/electron-builder.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down
4 changes: 4 additions & 0 deletions apps/desktop/scripts/device-probe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <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
Expand Down
20 changes: 20 additions & 0 deletions apps/desktop/src/main/adapters/network/local-network-error.ts
Original file line number Diff line number Diff line change
@@ -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 } }
)
}
84 changes: 84 additions & 0 deletions apps/desktop/src/main/adapters/network/multicast-socket.ts
Original file line number Diff line number Diff line change
@@ -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<void> =>
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<void> =>
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<MulticastSocket> => {
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())
})
}
}
64 changes: 64 additions & 0 deletions apps/desktop/src/main/adapters/network/network.test.ts
Original file line number Diff line number Diff line change
@@ -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<void>((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<void>((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<void>((resolve) => server?.close(() => resolve()))
server = undefined

await expect(connectTcp('127.0.0.1', port)).rejects.toMatchObject({
code: ErrorCode.DeviceDisconnected
})
})
})
36 changes: 36 additions & 0 deletions apps/desktop/src/main/adapters/network/tcp-connection.ts
Original file line number Diff line number Diff line change
@@ -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<Socket> =>
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<Connection> => createNodeConnection(await open(host, port))
9 changes: 7 additions & 2 deletions apps/desktop/src/main/adapters/usbmux-transport.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -46,5 +49,7 @@ const open = (endpoint: UsbmuxdEndpoint): Promise<Socket> =>
export const createNodeUsbmuxTransport = (
endpoint: UsbmuxdEndpoint = resolveUsbmuxdEndpoint()
): DeviceTransport => ({
connectUsbmux: async () => createNodeConnection(await open(endpoint))
connectUsbmux: async () => createNodeConnection(await open(endpoint)),
connectTcp,
openMulticast
})
5 changes: 5 additions & 0 deletions apps/desktop/src/main/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> = 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.
Expand Down
13 changes: 13 additions & 0 deletions apps/desktop/src/main/external-links.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
})
11 changes: 9 additions & 2 deletions apps/desktop/src/main/external-links.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down
12 changes: 12 additions & 0 deletions apps/desktop/src/probes/device/commands/device.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> => {
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<void> =>
Expand Down
6 changes: 4 additions & 2 deletions apps/desktop/src/probes/device/commands/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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)
})
Loading
Loading