From 257d3bdb695f67a1fa3edf78ff5534082409e5c9 Mon Sep 17 00:00:00 2001 From: Evan Bacon Date: Mon, 9 Nov 2026 19:00:45 -0800 Subject: [PATCH 1/3] fix(serve-sim): launch the Duo guest helper when re-signed with the hardened runtime (#193) Apps that bundle serve-sim and notarize it (e.g. Electron) re-sign serve-sim-duo-hid with the hardened runtime. dyld then drops the DYLD_ROOT_PATH that `simctl spawn` supplies, so the helper aborts with "DYLD_ROOT_PATH not set for simulator program" and Duo fold/HID and the hinge reader fail. duoHidHelperPath() now checks the helper's signature once per process; a hardened helper without allow-dyld-environment-variables is copied to a per-user cache (keyed by size+mtime) and ad-hoc re-signed without the runtime flag. Any failure falls back to the bundled path. The fold rejection message and the native bridge now point at the guest helper failing to start. --- .../Sources/SimNative/DuoHIDBridge.swift | 8 +- packages/serve-sim/package.json | 1 + .../src/__tests__/launchable-helper.test.ts | 129 ++++++++++++++++++ packages/serve-sim/src/index.ts | 2 +- packages/serve-sim/src/launchable-helper.ts | 62 +++++++++ packages/serve-sim/src/native.ts | 9 +- 6 files changed, 206 insertions(+), 5 deletions(-) create mode 100644 packages/serve-sim/src/__tests__/launchable-helper.test.ts create mode 100644 packages/serve-sim/src/launchable-helper.ts diff --git a/packages/serve-sim/Sources/SimNative/DuoHIDBridge.swift b/packages/serve-sim/Sources/SimNative/DuoHIDBridge.swift index d4fa3c78b..2f6c19c64 100644 --- a/packages/serve-sim/Sources/SimNative/DuoHIDBridge.swift +++ b/packages/serve-sim/Sources/SimNative/DuoHIDBridge.swift @@ -51,8 +51,12 @@ final class DuoHIDBridge { while Date() < deadline && reply.count < 64 { var descriptor = pollfd(fd: output.fileDescriptor, events: Int16(POLLIN), revents: 0) let remaining = max(1, Int32(deadline.timeIntervalSinceNow * 1000)) - guard poll(&descriptor, 1, remaining) > 0, - let byte = try output.read(upToCount: 1), !byte.isEmpty else { break } + guard poll(&descriptor, 1, remaining) > 0 else { break } + guard let byte = try output.read(upToCount: 1), !byte.isEmpty else { + // Its own stderr (inherited above) says why, e.g. dyld refusing to start it. + fputs("[hid] Duo guest helper exited without replying to \"\(command)\": \(executable)\n", stderr) + break + } if byte[0] == 10 { return String(data: reply, encoding: .utf8) == "OK" } reply.append(byte) } diff --git a/packages/serve-sim/package.json b/packages/serve-sim/package.json index ee91ab082..c69dea144 100644 --- a/packages/serve-sim/package.json +++ b/packages/serve-sim/package.json @@ -54,6 +54,7 @@ "src/max-bitrate.ts", "src/keyboard-modifiers.ts", "src/key-sequencer.ts", + "src/launchable-helper.ts", "src/metro-reload.ts", "src/middleware.ts", "src/native.ts", diff --git a/packages/serve-sim/src/__tests__/launchable-helper.test.ts b/packages/serve-sim/src/__tests__/launchable-helper.test.ts new file mode 100644 index 000000000..e8a39a2dc --- /dev/null +++ b/packages/serve-sim/src/__tests__/launchable-helper.test.ts @@ -0,0 +1,129 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { spawnSync, type execFile, type spawn } from "child_process"; +import { EventEmitter } from "events"; +import { copyFileSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "fs"; +import { tmpdir } from "os"; +import { join } from "path"; +import { PassThrough } from "stream"; +import { DuoStateMonitor } from "../duo-state"; +import { launchableHelper } from "../launchable-helper"; + +// Issue #193: a helper re-signed with the hardened runtime (Electron/notarized +// bundles) aborts under `simctl spawn` with "DYLD_ROOT_PATH not set". +const HARDENED = "CodeDirectory v=20500 size=342 flags=0x10002(adhoc,runtime) hashes=4+2 location=embedded"; +const LINKER_SIGNED = "CodeDirectory v=20400 size=342 flags=0x20002(adhoc,linker-signed) hashes=8+0 location=embedded"; +const ENTITLED = `${HARDENED}\n[Dict]\n\t[Key] com.apple.security.cs.allow-dyld-environment-variables\n\t[Value]\n\t\t[Bool] true`; + +const scratchDirs: string[] = []; +afterEach(() => { + for (const dir of scratchDirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +function scratch(): string { + const dir = mkdtempSync(join(tmpdir(), "serve-sim-launchable-")); + scratchDirs.push(dir); + return dir; +} + +/** A helper on disk plus a fake codesign that reports `probe` and records calls. */ +function fixture(probe: { status: number | null; output: string }, signStatus = 0) { + const dir = scratch(); + const helper = join(dir, "serve-sim-duo-hid"); + writeFileSync(helper, "helper-bytes", { mode: 0o755 }); + const calls: string[][] = []; + const codesign = (args: string[]) => { + calls.push(args); + return args[0] === "-d" ? probe : { status: signStatus, output: "" }; + }; + return { helper, calls, codesign, cacheDir: join(dir, "cache") }; +} + +describe("launchableHelper", () => { + test("re-signs a hardened helper's cached copy without the runtime flag", () => { + const { helper, calls, codesign, cacheDir } = fixture({ status: 0, output: HARDENED }); + const resolved = launchableHelper(helper, { codesign, cacheDir }); + + expect(resolved).not.toBe(helper); + expect(resolved.startsWith(cacheDir)).toBe(true); + expect(resolved.endsWith("/serve-sim-duo-hid")).toBe(true); + expect(readFileSync(resolved, "utf8")).toBe("helper-bytes"); + const sign = calls.find((args) => args[0] === "-f")!; + expect(sign.slice(0, 3)).toEqual(["-f", "-s", "-"]); + expect(sign).not.toContain("--options"); + + // A second process reuses the copy instead of signing again. + calls.length = 0; + expect(launchableHelper(helper, { codesign, cacheDir })).toBe(resolved); + expect(calls.some((args) => args[0] === "-f")).toBe(false); + }); + + test("a changed helper gets a fresh copy", () => { + const { helper, codesign, cacheDir } = fixture({ status: 0, output: HARDENED }); + const first = launchableHelper(helper, { codesign, cacheDir }); + writeFileSync(helper, "updated-helper-bytes"); + const second = launchableHelper(helper, { codesign, cacheDir }); + expect(second).not.toBe(first); + expect(readFileSync(second, "utf8")).toBe("updated-helper-bytes"); + }); + + test("keeps the bundled helper when it already launches", () => { + // npm's linker-signed helper, and a hardened one entitled to keep DYLD_* variables. + for (const output of [LINKER_SIGNED, ENTITLED, "CodeDirectory flags=0x2(adhoc) runtime-version"]) { + const { helper, calls, codesign, cacheDir } = fixture({ status: 0, output }); + expect(launchableHelper(helper, { codesign, cacheDir })).toBe(helper); + expect(calls).toHaveLength(1); + } + }); + + test("falls back to the bundled helper when codesign fails", () => { + const unsigned = fixture({ status: 1, output: "code object is not signed at all" }); + expect(launchableHelper(unsigned.helper, unsigned)).toBe(unsigned.helper); + + const missing = fixture({ status: null, output: "" }); // codesign not installed + expect(launchableHelper(missing.helper, missing)).toBe(missing.helper); + + const signFails = fixture({ status: 0, output: HARDENED }, 1); + expect(launchableHelper(signFails.helper, signFails)).toBe(signFails.helper); + + const throws = fixture({ status: 0, output: HARDENED }); + expect(launchableHelper(throws.helper, { codesign: () => { throw new Error("boom"); }, cacheDir: throws.cacheDir })).toBe(throws.helper); + }); + + test("the Duo hinge reader spawns the resolved copy inside the simulator", () => { + const { helper, codesign, cacheDir } = fixture({ status: 0, output: HARDENED }); + const resolved = launchableHelper(helper, { codesign, cacheDir }); + const spawned: string[][] = []; + const fakeChild = () => Object.assign(new EventEmitter(), { + stdin: new PassThrough(), stdout: new PassThrough(), stderr: new PassThrough(), kill: () => true, + }); + const monitor = new DuoStateMonitor("UDID", () => {}, { + duoHelper: () => resolved, + spawn: ((_command: string, args: string[]) => { spawned.push(args); return fakeChild(); }) as unknown as typeof spawn, + execFile: (() => fakeChild()) as unknown as typeof execFile, + }); + monitor.close(); + expect(spawned).toContainEqual(["simctl", "spawn", "UDID", resolved, "watch-angle"]); + }); +}); + +// Real codesign: sign a copy the way Electron packaging does, then resolve it. +const BUILT_HELPER = join(import.meta.dir, "../../dist/simduo/serve-sim-duo-hid"); +const hasCodesign = process.platform === "darwin" && existsSync("/usr/bin/codesign"); + +describe.skipIf(!hasCodesign)("launchableHelper (codesign)", () => { + const flags = (path: string) => spawnSync("/usr/bin/codesign", ["-d", "--verbose=2", path], { encoding: "utf8" }).stderr; + + test("a hardened-runtime helper resolves to a copy without the runtime flag", () => { + const dir = scratch(); + const helper = join(dir, "serve-sim-duo-hid"); + copyFileSync(existsSync(BUILT_HELPER) ? BUILT_HELPER : "/usr/bin/true", helper); + expect(spawnSync("/usr/bin/codesign", ["-f", "-s", "-", "--options", "runtime", helper]).status).toBe(0); + expect(flags(helper)).toMatch(/flags=0x[0-9a-f]+\([^)]*runtime/); + + const resolved = launchableHelper(helper, { cacheDir: join(dir, "cache") }); + expect(resolved).not.toBe(helper); + expect(flags(resolved)).toMatch(/flags=0x[0-9a-f]+\(adhoc/); + expect(flags(resolved)).not.toMatch(/flags=0x[0-9a-f]+\([^)]*runtime/); + expect(spawnSync("/usr/bin/codesign", ["--verify", resolved]).status).toBe(0); + }); +}); diff --git a/packages/serve-sim/src/index.ts b/packages/serve-sim/src/index.ts index 10e5d0079..0d620a6ea 100755 --- a/packages/serve-sim/src/index.ts +++ b/packages/serve-sim/src/index.ts @@ -1270,7 +1270,7 @@ async function fold(hinge: number, deviceArg?: string) { if (frame[0] !== FOLD_TAG) return; try { const reply = JSON.parse(frame.subarray(1).toString()); - finish(reply.ok === true ? undefined : new Error("Simulator rejected the fold. An iPhone Duo with guest HID support is required.")); + finish(reply.ok === true ? undefined : new Error("Simulator rejected the fold. An iPhone Duo with guest HID support is required. If this is an iPhone Duo, the guest helper (serve-sim-duo-hid) failed to start or reply; the serve-sim server log shows why.")); } catch (error) { finish(error instanceof Error ? error : new Error(String(error))); } }; ws.onclose = () => finish(new Error("Connection closed before the simulator acknowledged the fold.")); diff --git a/packages/serve-sim/src/launchable-helper.ts b/packages/serve-sim/src/launchable-helper.ts new file mode 100644 index 000000000..8a77b19ec --- /dev/null +++ b/packages/serve-sim/src/launchable-helper.ts @@ -0,0 +1,62 @@ +/** + * Guest helpers run under `simctl spawn`, which points dyld at the simulator + * runtime through DYLD_ROOT_PATH. A helper re-signed with the hardened runtime + * (as Electron/notarization packaging does) has dyld drop DYLD_* variables, so + * it aborts with "DYLD_ROOT_PATH not set for simulator program". Such a helper + * is copied to a per-user cache and ad-hoc re-signed without the runtime flag. + */ +import { spawnSync } from "child_process"; +import { copyFileSync, existsSync, mkdirSync, mkdtempSync, renameSync, rmSync, statSync } from "fs"; +import { tmpdir } from "os"; +import { basename, join } from "path"; + +const DYLD_ENV_ENTITLEMENT = "com.apple.security.cs.allow-dyld-environment-variables"; + +export interface LaunchableHelperDeps { + /** Runs `codesign` with `args`; `output` is stdout and stderr combined. */ + codesign?: (args: string[]) => { status: number | null; output: string }; + /** Where re-signed copies live. */ + cacheDir?: string; +} + +function runCodesign(args: string[]) { + const result = spawnSync("/usr/bin/codesign", args, { encoding: "utf8", timeout: 10_000 }); + return { status: result.status, output: `${result.stdout ?? ""}${result.stderr ?? ""}` }; +} + +/** True when dyld would strip the DYLD_* variables `simctl spawn` supplies. */ +function dropsDyldEnvironment(codesignOutput: string): boolean { + const flags = /flags=0x[0-9a-f]+\(([^)]*)\)/i.exec(codesignOutput)?.[1]?.split(",") ?? []; + return flags.includes("runtime") && !codesignOutput.includes(DYLD_ENV_ENTITLEMENT); +} + +/** `helper`, or a re-signed copy of it that `simctl spawn` can launch. Never throws. */ +export function launchableHelper(helper: string, deps: LaunchableHelperDeps = {}): string { + const codesign = deps.codesign ?? runCodesign; + try { + const probe = codesign(["-d", "--verbose=2", "--entitlements", "-", helper]); + if (probe.status !== 0 || !dropsDyldEnvironment(probe.output)) return helper; + + const { size, mtimeMs } = statSync(helper); + const uid = process.getuid?.() ?? "user"; + const dir = join(deps.cacheDir ?? join(tmpdir(), `serve-sim-${uid}`, "helpers"), `${size}-${Math.trunc(mtimeMs)}`); + const copy = join(dir, basename(helper)); + if (existsSync(copy)) return copy; + + mkdirSync(dir, { recursive: true, mode: 0o700 }); + // Sign in a private scratch dir and rename into place, so a concurrent + // process never launches a half-written copy. + const scratch = mkdtempSync(join(dir, ".tmp-")); + try { + const staged = join(scratch, basename(helper)); + copyFileSync(helper, staged); + if (codesign(["-f", "-s", "-", staged]).status !== 0) return helper; + renameSync(staged, copy); + } finally { + rmSync(scratch, { recursive: true, force: true }); + } + return copy; + } catch { + return helper; + } +} diff --git a/packages/serve-sim/src/native.ts b/packages/serve-sim/src/native.ts index f0382fe17..07d4cc510 100644 --- a/packages/serve-sim/src/native.ts +++ b/packages/serve-sim/src/native.ts @@ -12,6 +12,7 @@ import { dirname, join } from "path"; import { existsSync } from "fs"; import { fileURLToPath } from "url"; import { KeySequencer, type KeyType } from "./key-sequencer"; +import { launchableHelper } from "./launchable-helper"; import { maxBitrateFromEnv } from "./max-bitrate"; import { resolveDeviceSet } from "./simctl"; @@ -164,9 +165,13 @@ function resolveAddon(): string { ); } -/** The guest-side Duo helper (`simctl spawn`): HID commands and the hinge reader. */ +let duoHidHelper: string | undefined; +/** + * The guest-side Duo helper (`simctl spawn`): HID commands and the hinge reader. + * A hardened-runtime re-signed bundle resolves to a copy dyld can launch. + */ export function duoHidHelperPath(): string { - return join(dirname(resolveAddon()), "..", "simduo", "serve-sim-duo-hid"); + return duoHidHelper ??= launchableHelper(join(dirname(resolveAddon()), "..", "simduo", "serve-sim-duo-hid")); } let addon: NativeAddon | undefined; From 429c2629001f143f99b241b520d2aef6dbeab4d1 Mon Sep 17 00:00:00 2001 From: Evan Bacon Date: Mon, 9 Nov 2026 19:13:04 -0800 Subject: [PATCH 2/3] fix(serve-sim): resolve the Duo guest helper only for an iPhone Duo (#193) NativeHid resolved the launchable Duo helper in its constructor, so every HID session ran a blocking codesign probe even on non-Duo devices. SimHID now starts with the bundled path; once native setup reports a Duo, JS resolves the launchable copy and hands it over with setDuoHelper. Commands the Duo routes through its guest helper (button, buttonHid, orientation, pose, hinge) wait for that hand-off. DeviceSession passes the resolver to the Duo state monitor uncalled, as before. The allow-dyld-environment-variables entitlement now counts only when its value is true; a hardened helper with it set to false is re-signed. --- .../Sources/SimNative/DuoHIDBridge.swift | 4 +- .../Sources/SimNative/HIDInjector.swift | 2 + .../Sources/SimNative/sim-module.swift | 6 ++ .../device-session-lifecycle.test.ts | 20 ++++++ .../src/__tests__/launchable-helper.test.ts | 32 +++++++++- .../__tests__/native-hid-duo-helper.test.ts | 63 +++++++++++++++++++ packages/serve-sim/src/device-session.ts | 7 ++- packages/serve-sim/src/launchable-helper.ts | 14 ++++- packages/serve-sim/src/native.ts | 46 +++++++++++--- 9 files changed, 179 insertions(+), 15 deletions(-) create mode 100644 packages/serve-sim/src/__tests__/native-hid-duo-helper.test.ts diff --git a/packages/serve-sim/Sources/SimNative/DuoHIDBridge.swift b/packages/serve-sim/Sources/SimNative/DuoHIDBridge.swift index 2f6c19c64..e76ba09b4 100644 --- a/packages/serve-sim/Sources/SimNative/DuoHIDBridge.swift +++ b/packages/serve-sim/Sources/SimNative/DuoHIDBridge.swift @@ -6,7 +6,9 @@ import SimNativeSupport /// replies acknowledge dispatch, so a failed command never switches capture. final class DuoHIDBridge { private let udid: String - private let executable: String + /// Settable so JS can swap in a launchable copy once the device is known + /// to be a Duo (resolving it costs a `codesign` probe). + var executable: String private var process: Process? private var input: FileHandle? private var output: FileHandle? diff --git a/packages/serve-sim/Sources/SimNative/HIDInjector.swift b/packages/serve-sim/Sources/SimNative/HIDInjector.swift index 947c6b788..752f884ce 100644 --- a/packages/serve-sim/Sources/SimNative/HIDInjector.swift +++ b/packages/serve-sim/Sources/SimNative/HIDInjector.swift @@ -543,6 +543,8 @@ actor HIDInjector { func isFoldable() -> Bool { duoBridge != nil } + func setDuoHelper(_ path: String) { duoBridge?.executable = path } + func close() { duoBridge = nil } private func updateTouchTarget(width: Int, height: Int) { diff --git a/packages/serve-sim/Sources/SimNative/sim-module.swift b/packages/serve-sim/Sources/SimNative/sim-module.swift index 28a656fdb..8d494d3aa 100644 --- a/packages/serve-sim/Sources/SimNative/sim-module.swift +++ b/packages/serve-sim/Sources/SimNative/sim-module.swift @@ -91,6 +91,12 @@ private func u32(_ v: Int) -> UInt32 { return await injector.isFoldable() } + /// Replace the guest helper the Duo bridge launches. No-op for other devices. + @NodeMethod func setDuoHelper(_ path: String) async throws { + try await setupTask.value + await injector.setDuoHelper(path) + } + @NodeMethod func close() async { _ = try? await setupTask.value await injector.close() diff --git a/packages/serve-sim/src/__tests__/device-session-lifecycle.test.ts b/packages/serve-sim/src/__tests__/device-session-lifecycle.test.ts index 778fb209f..38b198bb4 100644 --- a/packages/serve-sim/src/__tests__/device-session-lifecycle.test.ts +++ b/packages/serve-sim/src/__tests__/device-session-lifecycle.test.ts @@ -8,6 +8,7 @@ import { DeviceSession, type DeviceSessionDependencies, } from "../device-session"; +import { duoHidHelperPath } from "../native"; const servers: Server[] = []; @@ -520,6 +521,25 @@ describe("DeviceSession fold pose HID", () => { }); }); +test("only a Duo's state monitor gets the launchable-helper resolver (#193)", async () => { + const monitors: Array<() => string> = []; + const createDuoMonitor: DeviceSessionDependencies["createDuoMonitor"] = (_udid, _onState, duoHelper) => { + monitors.push(duoHelper); + return { close() {}, refreshOrientation() {} }; + }; + for (const foldable of [false, true]) { + const session = new DeviceSession("TEST-UDID", { + ...dependencies(), + hid: { ...dependencies().hid, isFoldable: async () => foldable }, + createDuoMonitor, + }); + await session.start(); + session.close(); + } + // Passed uncalled: resolving runs `codesign`, which the monitor defers to the hinge reader. + expect(monitors).toEqual([duoHidHelperPath]); +}); + test("3D attach and hinge updates render cached frames; stale worker failures cannot close a replacement", async () => { const frames: Array<(frame: { data: Uint8Array; width: number; height: number }) => Promise> = []; let update!: (state: import("../duo-state").DuoState) => void; diff --git a/packages/serve-sim/src/__tests__/launchable-helper.test.ts b/packages/serve-sim/src/__tests__/launchable-helper.test.ts index e8a39a2dc..9a68782ba 100644 --- a/packages/serve-sim/src/__tests__/launchable-helper.test.ts +++ b/packages/serve-sim/src/__tests__/launchable-helper.test.ts @@ -12,7 +12,11 @@ import { launchableHelper } from "../launchable-helper"; // bundles) aborts under `simctl spawn` with "DYLD_ROOT_PATH not set". const HARDENED = "CodeDirectory v=20500 size=342 flags=0x10002(adhoc,runtime) hashes=4+2 location=embedded"; const LINKER_SIGNED = "CodeDirectory v=20400 size=342 flags=0x20002(adhoc,linker-signed) hashes=8+0 location=embedded"; -const ENTITLED = `${HARDENED}\n[Dict]\n\t[Key] com.apple.security.cs.allow-dyld-environment-variables\n\t[Value]\n\t\t[Bool] true`; +const entitlements = (allowDyld: boolean) => + `${HARDENED}\n[Dict]\n\t[Key] com.apple.security.cs.allow-dyld-environment-variables\n\t[Value]\n\t\t[Bool] ${allowDyld}` + + "\n\t[Key] com.apple.security.cs.disable-library-validation\n\t[Value]\n\t\t[Bool] true"; +const ENTITLED = entitlements(true); +const XML_ENTITLED = `${HARDENED}\ncom.apple.security.cs.allow-dyld-environment-variables`; const scratchDirs: string[] = []; afterEach(() => { @@ -68,13 +72,23 @@ describe("launchableHelper", () => { test("keeps the bundled helper when it already launches", () => { // npm's linker-signed helper, and a hardened one entitled to keep DYLD_* variables. - for (const output of [LINKER_SIGNED, ENTITLED, "CodeDirectory flags=0x2(adhoc) runtime-version"]) { + for (const output of [LINKER_SIGNED, ENTITLED, XML_ENTITLED, "CodeDirectory flags=0x2(adhoc) runtime-version"]) { const { helper, calls, codesign, cacheDir } = fixture({ status: 0, output }); expect(launchableHelper(helper, { codesign, cacheDir })).toBe(helper); expect(calls).toHaveLength(1); } }); + test("an allow-dyld-environment-variables entitlement set to false still gets re-signed", () => { + for (const output of [ + entitlements(false), + `${HARDENED}\ncom.apple.security.cs.allow-dyld-environment-variablesother`, + ]) { + const { helper, codesign, cacheDir } = fixture({ status: 0, output }); + expect(launchableHelper(helper, { codesign, cacheDir })).not.toBe(helper); + } + }); + test("falls back to the bundled helper when codesign fails", () => { const unsigned = fixture({ status: 1, output: "code object is not signed at all" }); expect(launchableHelper(unsigned.helper, unsigned)).toBe(unsigned.helper); @@ -126,4 +140,18 @@ describe.skipIf(!hasCodesign)("launchableHelper (codesign)", () => { expect(flags(resolved)).not.toMatch(/flags=0x[0-9a-f]+\([^)]*runtime/); expect(spawnSync("/usr/bin/codesign", ["--verify", resolved]).status).toBe(0); }); + + test("allow-dyld-environment-variables keeps the helper only when true", () => { + for (const allowDyld of [true, false]) { + const dir = scratch(); + const helper = join(dir, "serve-sim-duo-hid"); + copyFileSync(existsSync(BUILT_HELPER) ? BUILT_HELPER : "/usr/bin/true", helper); + const plist = join(dir, "entitlements.plist"); + writeFileSync(plist, `com.apple.security.cs.allow-dyld-environment-variables<${allowDyld}/>com.apple.security.cs.disable-library-validation`); + expect(spawnSync("/usr/bin/codesign", ["-f", "-s", "-", "--options", "runtime", "--entitlements", plist, helper]).status).toBe(0); + const resolved = launchableHelper(helper, { cacheDir: join(dir, "cache") }); + if (allowDyld) expect(resolved).toBe(helper); + else expect(flags(resolved)).not.toMatch(/flags=0x[0-9a-f]+\([^)]*runtime/); + } + }); }); diff --git a/packages/serve-sim/src/__tests__/native-hid-duo-helper.test.ts b/packages/serve-sim/src/__tests__/native-hid-duo-helper.test.ts new file mode 100644 index 000000000..56773f395 --- /dev/null +++ b/packages/serve-sim/src/__tests__/native-hid-duo-helper.test.ts @@ -0,0 +1,63 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, rmSync, writeFileSync } from "fs"; +import { tmpdir } from "os"; +import { join } from "path"; +import { launchableHelper } from "../launchable-helper"; +import { NativeHid, type NativeHidDeps } from "../native"; + +// Issue #193 follow-up: resolving the launchable Duo helper runs `codesign`, +// so only an iPhone Duo's HID session may pay for it. +const HARDENED = "CodeDirectory v=20500 size=342 flags=0x10002(adhoc,runtime) hashes=4+2 location=embedded"; + +const scratchDirs: string[] = []; +afterEach(() => { + for (const dir of scratchDirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +function setup(foldable: boolean) { + const dir = mkdtempSync(join(tmpdir(), "serve-sim-native-hid-")); + scratchDirs.push(dir); + const bundled = join(dir, "serve-sim-duo-hid"); + writeFileSync(bundled, "helper-bytes", { mode: 0o755 }); + const codesignCalls: string[][] = []; + const codesign = (args: string[]) => { + codesignCalls.push(args); + return args[0] === "-d" ? { status: 0, output: HARDENED } : { status: 0, output: "" }; + }; + const native: string[] = []; + class FakeSimHID { + constructor(_udid: string, duoHelper: string) { native.push(`new ${duoHelper}`); } + isFoldable = async () => foldable; + setDuoHelper = async (path: string) => { native.push(`setDuoHelper ${path}`); }; + pose = async () => { native.push("pose"); return true; }; + orientation = async () => { native.push("orientation"); return true; }; + } + const deps: NativeHidDeps = { + SimHID: FakeSimHID as unknown as NativeHidDeps["SimHID"], + bundledDuoHelper: () => bundled, + duoHelper: () => launchableHelper(bundled, { codesign, cacheDir: join(dir, "cache") }), + }; + return { bundled, codesignCalls, native, deps }; +} + +describe("NativeHid Duo helper", () => { + test("a non-Duo device never runs codesign", async () => { + const { bundled, codesignCalls, native, deps } = setup(false); + const hid = new NativeHid("UDID", deps); + expect(await hid.orientation(1)).toBe(true); + expect(codesignCalls).toEqual([]); + expect(native).toEqual([`new ${bundled}`, "orientation"]); + }); + + test("a Duo points the bridge at the launchable copy before its first guest command", async () => { + const { bundled, codesignCalls, native, deps } = setup(true); + const hid = new NativeHid("UDID", deps); + expect(native).toEqual([`new ${bundled}`]); + expect(await hid.pose("book", 0)).toBe(true); + expect(codesignCalls[0]?.[0]).toBe("-d"); + const resolved = native[1]!.replace("setDuoHelper ", ""); + expect(resolved).not.toBe(bundled); + expect(resolved.endsWith("/serve-sim-duo-hid")).toBe(true); + expect(native).toEqual([`new ${bundled}`, `setDuoHelper ${resolved}`, "pose"]); + }); +}); diff --git a/packages/serve-sim/src/device-session.ts b/packages/serve-sim/src/device-session.ts index 87277261c..2ee6ab7a0 100644 --- a/packages/serve-sim/src/device-session.ts +++ b/packages/serve-sim/src/device-session.ts @@ -197,7 +197,8 @@ export interface DeviceSessionDependencies { capture: CaptureTransport; hid: HidTransport; createDuoRenderer?: (onFailure: (error: DuoRendererError) => void) => Pick; - createDuoMonitor?: (udid: string, onState: (state: DuoState) => void) => Pick; + /** `duoHelper` resolves the launchable guest helper (may run `codesign`); call it lazily. */ + createDuoMonitor?: (udid: string, onState: (state: DuoState) => void, duoHelper: () => string) => Pick; /** Server-side recording cap; defaults to `MAX_RECORDING_MS`. */ maxRecordingMs?: number; /** How long a capped file is held for its owner; defaults to `RECORDING_HOLD_MS`. */ @@ -312,12 +313,12 @@ export class DeviceSession { if (!this.dependencies?.createDuoMonitor) { void warnDeviceHubInput(this.udid).then((shadowed) => { this.deviceHubShadowed = shadowed; }); } - const createMonitor = this.dependencies?.createDuoMonitor ?? ((udid, onState) => new DuoStateMonitor(udid, onState, { duoHelper: duoHidHelperPath })); + const createMonitor = this.dependencies?.createDuoMonitor ?? ((udid, onState, duoHelper) => new DuoStateMonitor(udid, onState, { duoHelper })); this.duoMonitor = createMonitor(this.udid, (state) => { void this.followDuoState(state).catch((error) => { console.error("[duo] State update failed:", error); }); - }); + }, duoHidHelperPath); } })().catch((error) => { // Failed DeviceSession instances are evicted by the registry below. Keep diff --git a/packages/serve-sim/src/launchable-helper.ts b/packages/serve-sim/src/launchable-helper.ts index 8a77b19ec..106f4c1c7 100644 --- a/packages/serve-sim/src/launchable-helper.ts +++ b/packages/serve-sim/src/launchable-helper.ts @@ -24,10 +24,22 @@ function runCodesign(args: string[]) { return { status: result.status, output: `${result.stdout ?? ""}${result.stderr ?? ""}` }; } +/** + * True when the entitlements grant DYLD_* variables. `codesign` prints them as + * `[Key] ` / `[Value]` / `[Bool] true`, or as XML `` / ``. + */ +function allowsDyldEnvironment(codesignOutput: string): boolean { + const at = codesignOutput.indexOf(DYLD_ENV_ENTITLEMENT); + if (at < 0) return false; + // Only the value directly after the key counts, never a later key's. + const value = /^\s*(?:\[Value\]\s*\[Bool\]\s*(\w+)|<\/key>\s*<(\w+)\s*\/>)/.exec(codesignOutput.slice(at + DYLD_ENV_ENTITLEMENT.length)); + return (value?.[1] ?? value?.[2]) === "true"; +} + /** True when dyld would strip the DYLD_* variables `simctl spawn` supplies. */ function dropsDyldEnvironment(codesignOutput: string): boolean { const flags = /flags=0x[0-9a-f]+\(([^)]*)\)/i.exec(codesignOutput)?.[1]?.split(",") ?? []; - return flags.includes("runtime") && !codesignOutput.includes(DYLD_ENV_ENTITLEMENT); + return flags.includes("runtime") && !allowsDyldEnvironment(codesignOutput); } /** `helper`, or a re-signed copy of it that `simctl spawn` can launch. Never throws. */ diff --git a/packages/serve-sim/src/native.ts b/packages/serve-sim/src/native.ts index 07d4cc510..c0a924748 100644 --- a/packages/serve-sim/src/native.ts +++ b/packages/serve-sim/src/native.ts @@ -37,6 +37,8 @@ interface SimHIDHandle { softwareKeyboard(): Promise; caDebug(name: string, enabled: boolean): Promise; isFoldable(): Promise; + /** Swap the helper the Duo bridge launches; a no-op on other devices. */ + setDuoHelper(path: string): Promise; close(): Promise; pose(name: string, fromDegrees: number): Promise; hinge(degrees: number): Promise; @@ -165,13 +167,19 @@ function resolveAddon(): string { ); } +/** The guest-side Duo helper as bundled, without checking that it launches. */ +function bundledDuoHidHelperPath(): string { + return join(dirname(resolveAddon()), "..", "simduo", "serve-sim-duo-hid"); +} + let duoHidHelper: string | undefined; /** * The guest-side Duo helper (`simctl spawn`): HID commands and the hinge reader. * A hardened-runtime re-signed bundle resolves to a copy dyld can launch. + * Resolving runs a blocking `codesign` probe, so only call it for an iPhone Duo. */ export function duoHidHelperPath(): string { - return duoHidHelper ??= launchableHelper(join(dirname(resolveAddon()), "..", "simduo", "serve-sim-duo-hid")); + return duoHidHelper ??= launchableHelper(bundledDuoHidHelperPath()); } let addon: NativeAddon | undefined; @@ -189,13 +197,35 @@ function load(): NativeAddon { * In-process HID injector for one simulator. Mirrors the WebSocket HID protocol * the spawned helper used to handle, but as direct native calls. */ +export interface NativeHidDeps { + SimHID?: NativeAddon["SimHID"]; + /** The helper as bundled; must be cheap. */ + bundledDuoHelper?: () => string; + /** The launchable helper; may run `codesign`, so it is only called for a Duo. */ + duoHelper?: () => string; +} + export class NativeHid { private readonly handle: SimHIDHandle; private readonly keys: KeySequencer; + /** Settles once a Duo's bridge points at the launchable helper. */ + private readonly duoHelperReady: Promise; - constructor(udid: string) { - this.handle = new (load().SimHID)(udid, duoHidHelperPath()); + constructor(udid: string, deps: NativeHidDeps = {}) { + const bundled = (deps.bundledDuoHelper ?? bundledDuoHidHelperPath)(); + this.handle = new (deps.SimHID ?? load().SimHID)(udid, bundled); this.keys = new KeySequencer(this.handle); + const resolve = deps.duoHelper ?? duoHidHelperPath; + this.duoHelperReady = this.handle.isFoldable().then(async (foldable) => { + if (!foldable) return; + const helper = resolve(); + if (helper !== bundled) await this.handle.setDuoHelper(helper); + }).catch(() => {}); + } + + /** Commands a Duo routes through its guest helper wait for it to be resolved. */ + private viaDuoHelper(fn: () => PromiseLike): () => Promise { + return () => this.duoHelperReady.then(fn); } // The N-API bindings throw synchronously when a JS value can't be coerced to @@ -223,11 +253,11 @@ export class NativeHid { } button(button: string): Promise { - return this.guard("button", () => this.handle.button(button), undefined); + return this.guard("button", this.viaDuoHelper(() => this.handle.button(button)), undefined); } buttonHid(page: number, usage: number, phase: ButtonPhase = "press"): Promise { - return this.guard("buttonHid", () => this.handle.buttonHid(page, usage, phase), undefined); + return this.guard("buttonHid", this.viaDuoHelper(() => this.handle.buttonHid(page, usage, phase)), undefined); } key(type: KeyType, usage: number): Promise { @@ -244,7 +274,7 @@ export class NativeHid { } orientation(orientation: number): Promise { - return this.guard("orientation", () => this.handle.orientation(orientation), false); + return this.guard("orientation", this.viaDuoHelper(() => this.handle.orientation(orientation)), false); } memoryWarning(): Promise { @@ -268,11 +298,11 @@ export class NativeHid { } pose(name: string, fromDegrees: number): Promise { - return this.guard("pose", () => this.handle.pose(name, fromDegrees), false); + return this.guard("pose", this.viaDuoHelper(() => this.handle.pose(name, fromDegrees)), false); } hinge(degrees: number): Promise { - return this.guard("hinge", () => this.handle.hinge(degrees), false); + return this.guard("hinge", this.viaDuoHelper(() => this.handle.hinge(degrees)), false); } } From d27aba11201dce9826aa3f927449c6d2b09801ed Mon Sep 17 00:00:00 2001 From: Evan Bacon Date: Mon, 9 Nov 2026 19:24:19 -0800 Subject: [PATCH 3/3] fix(serve-sim): only run a private, content-keyed Duo helper copy (#193) The re-signed Duo helper cache lives under tmpdir(), which is the shared /tmp when TMPDIR is unset, and was keyed only by size and mtime. A copy already present was executed without checking who owned it. - Key the cache by a SHA-256 of the bundled helper, not by size and mtime. - Require every cache directory and the cached copy to be owned by the current uid, not symlinks, and not group- or world-writable; otherwise fall back to the bundled helper. - Pin the staged copy to 0755 so a loose source mode doesn't make it fail the check on the next run. - Once Duo helper setup settles, run wrapped HID commands right away so they keep their order with touches sent in the same tick. --- .../src/__tests__/launchable-helper.test.ts | 56 ++++++++++++++++++- .../__tests__/native-hid-duo-helper.test.ts | 12 ++++ packages/serve-sim/src/launchable-helper.ts | 50 +++++++++++++++-- packages/serve-sim/src/native.ts | 13 +++-- 4 files changed, 119 insertions(+), 12 deletions(-) diff --git a/packages/serve-sim/src/__tests__/launchable-helper.test.ts b/packages/serve-sim/src/__tests__/launchable-helper.test.ts index 9a68782ba..2218207fd 100644 --- a/packages/serve-sim/src/__tests__/launchable-helper.test.ts +++ b/packages/serve-sim/src/__tests__/launchable-helper.test.ts @@ -1,9 +1,9 @@ import { afterEach, describe, expect, test } from "bun:test"; import { spawnSync, type execFile, type spawn } from "child_process"; import { EventEmitter } from "events"; -import { copyFileSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "fs"; +import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, utimesSync, writeFileSync } from "fs"; import { tmpdir } from "os"; -import { join } from "path"; +import { dirname, join } from "path"; import { PassThrough } from "stream"; import { DuoStateMonitor } from "../duo-state"; import { launchableHelper } from "../launchable-helper"; @@ -70,6 +70,58 @@ describe("launchableHelper", () => { expect(readFileSync(second, "utf8")).toBe("updated-helper-bytes"); }); + test("a different helper with the same size and mtime gets its own copy", () => { + const { helper, codesign, cacheDir } = fixture({ status: 0, output: HARDENED }); + const { mtime } = statSync(helper); + const first = launchableHelper(helper, { codesign, cacheDir }); + writeFileSync(helper, "HELPER-BYTES"); // same length as "helper-bytes" + utimesSync(helper, mtime, mtime); + const second = launchableHelper(helper, { codesign, cacheDir }); + expect(second).not.toBe(first); + expect(readFileSync(second, "utf8")).toBe("HELPER-BYTES"); + }); + + test("never runs a cached copy that others could have planted", () => { + // A cache dir, version dir or copy that is group/world-writable, or a + // symlinked cache root, falls back to the bundled helper instead. + const cases: Array<(copy: string, cacheDir: string) => void> = [ + (_copy, cacheDir) => chmodSync(cacheDir, 0o777), + (copy) => chmodSync(dirname(copy), 0o777), + (copy) => chmodSync(copy, 0o777), + (copy) => { + rmSync(copy); + symlinkSync("/usr/bin/true", copy); + }, + ]; + for (const plant of cases) { + const { helper, codesign, cacheDir } = fixture({ status: 0, output: HARDENED }); + const copy = launchableHelper(helper, { codesign, cacheDir }); + expect(copy).not.toBe(helper); + writeFileSync(copy, "planted"); + plant(copy, cacheDir); + expect(launchableHelper(helper, { codesign, cacheDir })).toBe(helper); + } + + // A group-writable bundled helper still yields a reusable private copy. + const loose = fixture({ status: 0, output: HARDENED }); + chmodSync(loose.helper, 0o775); + const looseCopy = launchableHelper(loose.helper, loose); + expect(looseCopy).not.toBe(loose.helper); + expect(launchableHelper(loose.helper, loose)).toBe(looseCopy); + + const { helper, codesign } = fixture({ status: 0, output: HARDENED }); + const real = scratch(); + const linked = join(scratch(), "cache"); + symlinkSync(real, linked); + expect(launchableHelper(helper, { codesign, cacheDir: linked })).toBe(helper); + + // A pre-existing world-writable cache dir is not used, even when empty. + const shared = fixture({ status: 0, output: HARDENED }); + mkdirSync(shared.cacheDir, { mode: 0o777 }); + chmodSync(shared.cacheDir, 0o777); + expect(launchableHelper(shared.helper, shared)).toBe(shared.helper); + }); + test("keeps the bundled helper when it already launches", () => { // npm's linker-signed helper, and a hardened one entitled to keep DYLD_* variables. for (const output of [LINKER_SIGNED, ENTITLED, XML_ENTITLED, "CodeDirectory flags=0x2(adhoc) runtime-version"]) { diff --git a/packages/serve-sim/src/__tests__/native-hid-duo-helper.test.ts b/packages/serve-sim/src/__tests__/native-hid-duo-helper.test.ts index 56773f395..cb3a8362a 100644 --- a/packages/serve-sim/src/__tests__/native-hid-duo-helper.test.ts +++ b/packages/serve-sim/src/__tests__/native-hid-duo-helper.test.ts @@ -31,6 +31,7 @@ function setup(foldable: boolean) { setDuoHelper = async (path: string) => { native.push(`setDuoHelper ${path}`); }; pose = async () => { native.push("pose"); return true; }; orientation = async () => { native.push("orientation"); return true; }; + touch = async () => { native.push("touch"); }; } const deps: NativeHidDeps = { SimHID: FakeSimHID as unknown as NativeHidDeps["SimHID"], @@ -60,4 +61,15 @@ describe("NativeHid Duo helper", () => { expect(resolved.endsWith("/serve-sim-duo-hid")).toBe(true); expect(native).toEqual([`new ${bundled}`, `setDuoHelper ${resolved}`, "pose"]); }); + + test("once resolved, guest commands keep their order with touches sent in the same tick", async () => { + for (const foldable of [false, true]) { + const { native, deps } = setup(foldable); + const hid = new NativeHid("UDID", deps); + await hid.orientation(1); + native.length = 0; + await Promise.all([hid.orientation(2), hid.touch("begin", 0.5, 0.5, 100, 100)]); + expect(native).toEqual(["orientation", "touch"]); + } + }); }); diff --git a/packages/serve-sim/src/launchable-helper.ts b/packages/serve-sim/src/launchable-helper.ts index 106f4c1c7..ebd9857f0 100644 --- a/packages/serve-sim/src/launchable-helper.ts +++ b/packages/serve-sim/src/launchable-helper.ts @@ -4,9 +4,14 @@ * (as Electron/notarization packaging does) has dyld drop DYLD_* variables, so * it aborts with "DYLD_ROOT_PATH not set for simulator program". Such a helper * is copied to a per-user cache and ad-hoc re-signed without the runtime flag. + * + * The cache may sit in a shared `/tmp` (when TMPDIR is unset), and its copy is + * executed, so every directory on the way and the copy itself must be owned by + * this user and writable by nobody else; otherwise the bundled helper is used. */ import { spawnSync } from "child_process"; -import { copyFileSync, existsSync, mkdirSync, mkdtempSync, renameSync, rmSync, statSync } from "fs"; +import { createHash } from "crypto"; +import { chmodSync, copyFileSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, type Stats } from "fs"; import { tmpdir } from "os"; import { basename, join } from "path"; @@ -42,6 +47,35 @@ function dropsDyldEnvironment(codesignOutput: string): boolean { return flags.includes("runtime") && !allowsDyldEnvironment(codesignOutput); } +/** True when only this user could have written the entry at `stats`. */ +function privateTo(stats: Stats, isType: (s: Stats) => boolean): boolean { + const uid = process.getuid?.(); + return isType(stats) && (uid === undefined || stats.uid === uid) && (stats.mode & 0o022) === 0; +} + +/** Creates `dir` if missing; throws unless it is a private, non-symlinked directory. */ +function ensurePrivateDir(dir: string): void { + try { + mkdirSync(dir, { mode: 0o700 }); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; + } + if (!privateTo(lstatSync(dir), (s) => s.isDirectory())) throw new Error(`Refusing to use ${dir}`); +} + +/** The private cached copy at `copy`, `undefined` when absent; throws when not private. */ +function existingCopy(copy: string): string | undefined { + let stats: Stats; + try { + stats = lstatSync(copy); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined; + throw error; + } + if (!privateTo(stats, (s) => s.isFile())) throw new Error(`Refusing to run ${copy}`); + return copy; +} + /** `helper`, or a re-signed copy of it that `simctl spawn` can launch. Never throws. */ export function launchableHelper(helper: string, deps: LaunchableHelperDeps = {}): string { const codesign = deps.codesign ?? runCodesign; @@ -49,19 +83,23 @@ export function launchableHelper(helper: string, deps: LaunchableHelperDeps = {} const probe = codesign(["-d", "--verbose=2", "--entitlements", "-", helper]); if (probe.status !== 0 || !dropsDyldEnvironment(probe.output)) return helper; - const { size, mtimeMs } = statSync(helper); - const uid = process.getuid?.() ?? "user"; - const dir = join(deps.cacheDir ?? join(tmpdir(), `serve-sim-${uid}`, "helpers"), `${size}-${Math.trunc(mtimeMs)}`); + // Keyed by content, so a different build never reuses another's copy. + const digest = createHash("sha256").update(readFileSync(helper)).digest("hex").slice(0, 32); + const userRoot = join(tmpdir(), `serve-sim-${process.getuid?.() ?? "user"}`); + const dirs = deps.cacheDir ? [deps.cacheDir] : [userRoot, join(userRoot, "helpers")]; + const dir = join(dirs[dirs.length - 1]!, digest); + for (const d of [...dirs, dir]) ensurePrivateDir(d); const copy = join(dir, basename(helper)); - if (existsSync(copy)) return copy; + const cached = existingCopy(copy); + if (cached) return cached; - mkdirSync(dir, { recursive: true, mode: 0o700 }); // Sign in a private scratch dir and rename into place, so a concurrent // process never launches a half-written copy. const scratch = mkdtempSync(join(dir, ".tmp-")); try { const staged = join(scratch, basename(helper)); copyFileSync(helper, staged); + chmodSync(staged, 0o755); // the source's mode may be group-writable if (codesign(["-f", "-s", "-", staged]).status !== 0) return helper; renameSync(staged, copy); } finally { diff --git a/packages/serve-sim/src/native.ts b/packages/serve-sim/src/native.ts index c0a924748..a6eef7717 100644 --- a/packages/serve-sim/src/native.ts +++ b/packages/serve-sim/src/native.ts @@ -210,6 +210,7 @@ export class NativeHid { private readonly keys: KeySequencer; /** Settles once a Duo's bridge points at the launchable helper. */ private readonly duoHelperReady: Promise; + private duoHelperSettled = false; constructor(udid: string, deps: NativeHidDeps = {}) { const bundled = (deps.bundledDuoHelper ?? bundledDuoHidHelperPath)(); @@ -220,12 +221,16 @@ export class NativeHid { if (!foldable) return; const helper = resolve(); if (helper !== bundled) await this.handle.setDuoHelper(helper); - }).catch(() => {}); + }).catch(() => {}).finally(() => { this.duoHelperSettled = true; }); } - /** Commands a Duo routes through its guest helper wait for it to be resolved. */ - private viaDuoHelper(fn: () => PromiseLike): () => Promise { - return () => this.duoHelperReady.then(fn); + /** + * Commands a Duo routes through its guest helper wait for it to be resolved. + * Once it has been, they run immediately so they keep their order relative + * to touches and keys sent in the same tick. + */ + private viaDuoHelper(fn: () => PromiseLike): () => PromiseLike { + return () => (this.duoHelperSettled ? fn() : this.duoHelperReady.then(fn)); } // The N-API bindings throw synchronously when a JS value can't be coerced to