1+ import * as crypto from "crypto";
12import * as path from "path";
23import { ApplicationManagerBase } from "../../application-manager-base";
34import { hook, sleep } from "../../../helpers";
@@ -11,6 +12,10 @@ import {
1112 IPlistParser,
1213} from "../../../declarations";
1314import { IOptions } from "../../../../declarations";
15+ import { ITempService } from "../../../../definitions/temp-service";
16+
17+ const LSREGISTER_PATH =
18+ "/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister";
1419
1520interface IIOSMacApplicationHost extends Mobile.IiOSDevice {
1621 readonly wrapperPath: string;
@@ -25,6 +30,7 @@ export class IOSMacApplicationManager extends ApplicationManagerBase {
2530 private $fs: IFileSystem,
2631 private $options: IOptions,
2732 private $plistParser: IPlistParser,
33+ private $tempService: ITempService,
2834 protected $deviceLogProvider: Mobile.IDeviceLogProvider,
2935 $logger: ILogger,
3036 $hooksService: IHooksService,
@@ -76,14 +82,16 @@ export class IOSMacApplicationManager extends ApplicationManagerBase {
7682 appData: Mobile.IStartApplicationData,
7783 ): Promise<void> {
7884 await this.setDeviceLogData(appData);
85+ await this.restoreCodeSignature();
86+ await this.registerWithLaunchServices();
7987
8088 const args = ["-n", this.device.wrapperPath];
8189 if (appData.waitForDebugger) {
8290 args.push("--args", "--nativescript-debug-brk");
8391 }
8492 await this.$childProcess.spawnFromEvent("open", args, "close");
8593
86- const [pid] = await this.getRunningPids();
94+ const [pid] = await this.getRunningPids(appData.appId );
8795 if (pid) {
8896 this.$deviceLogProvider.setApplicationPidForDevice(
8997 this.device.deviceInfo.identifier,
@@ -98,7 +106,7 @@ export class IOSMacApplicationManager extends ApplicationManagerBase {
98106 await this.device.destroyDebugSocket(appData.appId);
99107
100108 for (const signal of ["TERM", "KILL"]) {
101- const pids = await this.getRunningPids();
109+ const pids = await this.getRunningPids(appData.appId );
102110 if (!pids.length) {
103111 return;
104112 }
@@ -109,7 +117,7 @@ export class IOSMacApplicationManager extends ApplicationManagerBase {
109117
110118 // `open -n` while the old instance is still exiting starts a second copy.
111119 for (let attempt = 0; attempt < 40; attempt++) {
112- if (!(await this.getRunningPids()).length) {
120+ if (!(await this.getRunningPids(appData.appId )).length) {
113121 return;
114122 }
115123 await sleep(50);
@@ -129,25 +137,133 @@ export class IOSMacApplicationManager extends ApplicationManagerBase {
129137 return null;
130138 }
131139
140+ /**
141+ * Syncing writes into the signed bundle and breaks its seal, and macOS won't
142+ * launch a bundle whose seal is broken. The signature embedded in the
143+ * executable survives the sync, so its leaf certificate names the identity
144+ * to re-sign with.
145+ */
146+ private async restoreCodeSignature(): Promise<void> {
147+ const bundlePath = this.device.applicationBundlePath;
148+ const verify = await this.$childProcess.spawnFromEvent(
149+ "codesign",
150+ ["--verify", "--strict", bundlePath],
151+ "close",
152+ {},
153+ { throwError: false },
154+ );
155+ if (verify.exitCode === 0) {
156+ return;
157+ }
158+
159+ try {
160+ const certificatesPrefix = path.join(
161+ await this.$tempService.mkdirSync("ios-mac-codesign"),
162+ "certificate",
163+ );
164+ await this.$childProcess.spawnFromEvent(
165+ "codesign",
166+ ["-d", `--extract-certificates=${certificatesPrefix}`, bundlePath],
167+ "close",
168+ );
169+ const leafCertificatePath = `${certificatesPrefix}0`;
170+ if (!this.$fs.exists(leafCertificatePath)) {
171+ this.$logger.warn(
172+ `${bundlePath} has no signing certificate to re-sign it with. Rebuild the app if macOS refuses to launch it.`,
173+ );
174+ return;
175+ }
176+
177+ const identity = crypto
178+ .createHash("sha1")
179+ .update(this.$fs.readFile(leafCertificatePath))
180+ .digest("hex");
181+ await this.$childProcess.spawnFromEvent(
182+ "codesign",
183+ [
184+ "--force",
185+ "--sign",
186+ identity,
187+ "--preserve-metadata=identifier,entitlements,flags,runtime",
188+ bundlePath,
189+ ],
190+ "close",
191+ );
192+ } catch (err) {
193+ this.$logger.warn(
194+ `Unable to re-sign ${bundlePath}: ${err.message}. Rebuild the app if macOS refuses to launch it.`,
195+ );
196+ }
197+ }
198+
199+ /**
200+ * macOS only launches an iOS app whose code matches the CDHashes
201+ * LaunchServices recorded for it. Once the bundle changes, the launch can
202+ * race LaunchServices' own re-registration, use the stale record and fail
203+ * with "Launch Constraint Violation", so register it before every launch.
204+ */
205+ private async registerWithLaunchServices(): Promise<void> {
206+ const result = await this.$childProcess.spawnFromEvent(
207+ LSREGISTER_PATH,
208+ ["-f", this.device.wrapperPath],
209+ "close",
210+ {},
211+ { throwError: false },
212+ );
213+ if (result.exitCode !== 0) {
214+ this.$logger.trace(
215+ `Unable to register ${this.device.wrapperPath} with LaunchServices: ${result.stderr}`,
216+ );
217+ }
218+ }
219+
132220 /**
133221 * macOS runs the app from a copy of the wrapper under /private/var/folders,
134222 * so match the bundle layout rather than the path the CLI installed to.
223+ * Other iPad apps can share the executable name, so each match's
224+ * Info.plist must also name this app.
135225 */
136- private async getRunningPids(): Promise<string[]> {
226+ private async getRunningPids(appId: string ): Promise<string[]> {
137227 const name = this.device.executableName.replace(
138228 /[.*+?^${}()|[\]\\]/g,
139229 "\\$&",
140230 );
231+ const processPattern = `/Wrapper/${name}\\.app/${name}( |$)`;
232+ const result = await this.$childProcess.spawnFromEvent(
233+ "pgrep",
234+ ["-lf", processPattern],
235+ "close",
236+ {},
237+ // pgrep exits with 1 when nothing matches.
238+ { throwError: false },
239+ );
240+
241+ const bundlePattern = new RegExp(
242+ `^(\\d+) (.*/Wrapper/${name}\\.app)/${name}(?: |$)`,
243+ );
244+ const pids: string[] = [];
245+ for (const line of (result.stdout || "").split("\n")) {
246+ const match = bundlePattern.exec(line);
247+ if (match && (await this.isBundleOf(match[2], appId))) {
248+ pids.push(match[1]);
249+ }
250+ }
251+
252+ return pids;
253+ }
254+
255+ private async isBundleOf(
256+ bundlePath: string,
257+ appId: string,
258+ ): Promise<boolean> {
141259 try {
142- const result = await this.$childProcess.spawnFromEvent(
143- "pgrep",
144- ["-f", `/Wrapper/${name}\\.app/${name}( |$)`],
145- "close",
260+ const infoPlist = await this.$plistParser.parseFile(
261+ path.join(bundlePath, "Info.plist"),
146262 );
147- return result.stdout.split(/\s+/).filter(Boolean) ;
263+ return infoPlist?.CFBundleIdentifier === appId ;
148264 } catch (err) {
149- // pgrep exits with 1 when nothing matches.
150- return [] ;
265+ this.$logger.trace(`Unable to read the Info.plist of ${bundlePath}`, err);
266+ return false ;
151267 }
152268 }
153269
0 commit comments