|
| 1 | +import * as crypto from "crypto"; |
| 2 | +import * as path from "path"; |
| 3 | +import { ApplicationManagerBase } from "../../application-manager-base"; |
| 4 | +import { hook, sleep } from "../../../helpers"; |
| 5 | +import { cache } from "../../../decorators"; |
| 6 | +import { IOS_LOG_PREDICATE } from "../../../constants"; |
| 7 | +import { |
| 8 | + IChildProcess, |
| 9 | + IDictionary, |
| 10 | + IFileSystem, |
| 11 | + IHooksService, |
| 12 | + IPlistParser, |
| 13 | +} from "../../../declarations"; |
| 14 | +import { 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"; |
| 19 | + |
| 20 | +interface IIOSMacApplicationHost extends Mobile.IiOSDevice { |
| 21 | + readonly wrapperPath: string; |
| 22 | + readonly applicationBundlePath: string; |
| 23 | + readonly executableName: string; |
| 24 | +} |
| 25 | + |
| 26 | +export class IOSMacApplicationManager extends ApplicationManagerBase { |
| 27 | + constructor( |
| 28 | + private device: IIOSMacApplicationHost, |
| 29 | + private $childProcess: IChildProcess, |
| 30 | + private $fs: IFileSystem, |
| 31 | + private $options: IOptions, |
| 32 | + private $plistParser: IPlistParser, |
| 33 | + private $tempService: ITempService, |
| 34 | + protected $deviceLogProvider: Mobile.IDeviceLogProvider, |
| 35 | + $logger: ILogger, |
| 36 | + $hooksService: IHooksService, |
| 37 | + ) { |
| 38 | + super($logger, $hooksService, $deviceLogProvider); |
| 39 | + } |
| 40 | + |
| 41 | + public async getInstalledApplications(): Promise<string[]> { |
| 42 | + const infoPlistPath = path.join( |
| 43 | + this.device.applicationBundlePath, |
| 44 | + "Info.plist", |
| 45 | + ); |
| 46 | + if (!this.$fs.exists(infoPlistPath)) { |
| 47 | + return []; |
| 48 | + } |
| 49 | + |
| 50 | + const infoPlist = await this.$plistParser.parseFile(infoPlistPath); |
| 51 | + return infoPlist?.CFBundleIdentifier ? [infoPlist.CFBundleIdentifier] : []; |
| 52 | + } |
| 53 | + |
| 54 | + @hook("install") |
| 55 | + public async installApplication(packageFilePath: string): Promise<void> { |
| 56 | + const wrapperPath = this.device.wrapperPath; |
| 57 | + this.$fs.deleteDirectory(wrapperPath); |
| 58 | + this.$fs.ensureDirectoryExists(path.join(wrapperPath, "Wrapper")); |
| 59 | + // ditto keeps the bundle's symlinks and extended attributes, which its |
| 60 | + // code signature covers. |
| 61 | + await this.$childProcess.spawnFromEvent( |
| 62 | + "ditto", |
| 63 | + [packageFilePath, this.device.applicationBundlePath], |
| 64 | + "close", |
| 65 | + ); |
| 66 | + this.$fs.symlink( |
| 67 | + path.join("Wrapper", path.basename(this.device.applicationBundlePath)), |
| 68 | + path.join(wrapperPath, "WrappedBundle"), |
| 69 | + ); |
| 70 | + } |
| 71 | + |
| 72 | + public async uninstallApplication(appIdentifier: string): Promise<void> { |
| 73 | + await this.stopApplication({ |
| 74 | + appId: appIdentifier, |
| 75 | + projectName: null, |
| 76 | + projectDir: null, |
| 77 | + }); |
| 78 | + this.$fs.deleteDirectory(this.device.wrapperPath); |
| 79 | + } |
| 80 | + |
| 81 | + public async startApplication( |
| 82 | + appData: Mobile.IStartApplicationData, |
| 83 | + ): Promise<void> { |
| 84 | + await this.setDeviceLogData(appData); |
| 85 | + await this.restoreCodeSignature(); |
| 86 | + await this.registerWithLaunchServices(); |
| 87 | + |
| 88 | + const args = ["-n", this.device.wrapperPath]; |
| 89 | + if (appData.waitForDebugger) { |
| 90 | + args.push("--args", "--nativescript-debug-brk"); |
| 91 | + } |
| 92 | + await this.$childProcess.spawnFromEvent("open", args, "close"); |
| 93 | + |
| 94 | + const [pid] = await this.getRunningPids(appData.appId); |
| 95 | + if (pid) { |
| 96 | + this.$deviceLogProvider.setApplicationPidForDevice( |
| 97 | + this.device.deviceInfo.identifier, |
| 98 | + pid, |
| 99 | + ); |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + public async stopApplication( |
| 104 | + appData: Mobile.IApplicationData, |
| 105 | + ): Promise<void> { |
| 106 | + await this.device.destroyDebugSocket(appData.appId); |
| 107 | + |
| 108 | + for (const signal of ["TERM", "KILL"]) { |
| 109 | + const pids = await this.getRunningPids(appData.appId); |
| 110 | + if (!pids.length) { |
| 111 | + return; |
| 112 | + } |
| 113 | + |
| 114 | + await this.$childProcess |
| 115 | + .spawnFromEvent("kill", [`-${signal}`, ...pids], "close") |
| 116 | + .catch((err) => this.$logger.trace(err)); |
| 117 | + |
| 118 | + // `open -n` while the old instance is still exiting starts a second copy. |
| 119 | + for (let attempt = 0; attempt < 40; attempt++) { |
| 120 | + if (!(await this.getRunningPids(appData.appId)).length) { |
| 121 | + return; |
| 122 | + } |
| 123 | + await sleep(50); |
| 124 | + } |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + public async getDebuggableApps(): Promise< |
| 129 | + Mobile.IDeviceApplicationInformation[] |
| 130 | + > { |
| 131 | + return []; |
| 132 | + } |
| 133 | + |
| 134 | + public async getDebuggableAppViews( |
| 135 | + appIdentifiers: string[], |
| 136 | + ): Promise<IDictionary<Mobile.IDebugWebViewInfo[]>> { |
| 137 | + return null; |
| 138 | + } |
| 139 | + |
| 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 | + |
| 220 | + /** |
| 221 | + * macOS runs the app from a copy of the wrapper under /private/var/folders, |
| 222 | + * 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. |
| 225 | + */ |
| 226 | + private async getRunningPids(appId: string): Promise<string[]> { |
| 227 | + const name = this.device.executableName.replace( |
| 228 | + /[.*+?^${}()|[\]\\]/g, |
| 229 | + "\\$&", |
| 230 | + ); |
| 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> { |
| 259 | + try { |
| 260 | + const infoPlist = await this.$plistParser.parseFile( |
| 261 | + path.join(bundlePath, "Info.plist"), |
| 262 | + ); |
| 263 | + return infoPlist?.CFBundleIdentifier === appId; |
| 264 | + } catch (err) { |
| 265 | + this.$logger.trace(`Unable to read the Info.plist of ${bundlePath}`, err); |
| 266 | + return false; |
| 267 | + } |
| 268 | + } |
| 269 | + |
| 270 | + private async setDeviceLogData( |
| 271 | + appData: Mobile.IApplicationData, |
| 272 | + ): Promise<void> { |
| 273 | + this.$deviceLogProvider.setProjectNameForDevice( |
| 274 | + this.device.deviceInfo.identifier, |
| 275 | + appData.projectName, |
| 276 | + ); |
| 277 | + this.$deviceLogProvider.setProjectDirForDevice( |
| 278 | + this.device.deviceInfo.identifier, |
| 279 | + appData.projectDir, |
| 280 | + ); |
| 281 | + |
| 282 | + if (!this.$options.justlaunch) { |
| 283 | + await this.startDeviceLog(); |
| 284 | + } |
| 285 | + } |
| 286 | + |
| 287 | + @cache() |
| 288 | + private startDeviceLog(): Promise<void> { |
| 289 | + return this.device.openDeviceLogStream({ predicate: IOS_LOG_PREDICATE }); |
| 290 | + } |
| 291 | +} |
0 commit comments