Repository navigation
Expand file tree
/
Copy pathios-mac-application-manager.ts
More file actions
291 lines (264 loc) · 8.12 KB
/
Copy pathios-mac-application-manager.ts
File metadata and controls
291 lines (264 loc) · 8.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
import * as crypto from "crypto";
import * as path from "path";
import { ApplicationManagerBase } from "../../application-manager-base";
import { hook, sleep } from "../../../helpers";
import { cache } from "../../../decorators";
import { IOS_LOG_PREDICATE } from "../../../constants";
import {
IChildProcess,
IDictionary,
IFileSystem,
IHooksService,
IPlistParser,
} from "../../../declarations";
import { IOptions } from "../../../../declarations";
import { ITempService } from "../../../../definitions/temp-service";
const LSREGISTER_PATH =
"/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister";
interface IIOSMacApplicationHost extends Mobile.IiOSDevice {
readonly wrapperPath: string;
readonly applicationBundlePath: string;
readonly executableName: string;
}
export class IOSMacApplicationManager extends ApplicationManagerBase {
constructor(
private device: IIOSMacApplicationHost,
private $childProcess: IChildProcess,
private $fs: IFileSystem,
private $options: IOptions,
private $plistParser: IPlistParser,
private $tempService: ITempService,
protected $deviceLogProvider: Mobile.IDeviceLogProvider,
$logger: ILogger,
$hooksService: IHooksService,
) {
super($logger, $hooksService, $deviceLogProvider);
}
public async getInstalledApplications(): Promise<string[]> {
const infoPlistPath = path.join(
this.device.applicationBundlePath,
"Info.plist",
);
if (!this.$fs.exists(infoPlistPath)) {
return [];
}
const infoPlist = await this.$plistParser.parseFile(infoPlistPath);
return infoPlist?.CFBundleIdentifier ? [infoPlist.CFBundleIdentifier] : [];
}
@hook("install")
public async installApplication(packageFilePath: string): Promise<void> {
const wrapperPath = this.device.wrapperPath;
this.$fs.deleteDirectory(wrapperPath);
this.$fs.ensureDirectoryExists(path.join(wrapperPath, "Wrapper"));
// ditto keeps the bundle's symlinks and extended attributes, which its
// code signature covers.
await this.$childProcess.spawnFromEvent(
"ditto",
[packageFilePath, this.device.applicationBundlePath],
"close",
);
this.$fs.symlink(
path.join("Wrapper", path.basename(this.device.applicationBundlePath)),
path.join(wrapperPath, "WrappedBundle"),
);
}
public async uninstallApplication(appIdentifier: string): Promise<void> {
await this.stopApplication({
appId: appIdentifier,
projectName: null,
projectDir: null,
});
this.$fs.deleteDirectory(this.device.wrapperPath);
}
public async startApplication(
appData: Mobile.IStartApplicationData,
): Promise<void> {
await this.setDeviceLogData(appData);
await this.restoreCodeSignature();
await this.registerWithLaunchServices();
const args = ["-n", this.device.wrapperPath];
if (appData.waitForDebugger) {
args.push("--args", "--nativescript-debug-brk");
}
await this.$childProcess.spawnFromEvent("open", args, "close");
const [pid] = await this.getRunningPids(appData.appId);
if (pid) {
this.$deviceLogProvider.setApplicationPidForDevice(
this.device.deviceInfo.identifier,
pid,
);
}
}
public async stopApplication(
appData: Mobile.IApplicationData,
): Promise<void> {
await this.device.destroyDebugSocket(appData.appId);
for (const signal of ["TERM", "KILL"]) {
const pids = await this.getRunningPids(appData.appId);
if (!pids.length) {
return;
}
await this.$childProcess
.spawnFromEvent("kill", [`-${signal}`, ...pids], "close")
.catch((err) => this.$logger.trace(err));
// `open -n` while the old instance is still exiting starts a second copy.
for (let attempt = 0; attempt < 40; attempt++) {
if (!(await this.getRunningPids(appData.appId)).length) {
return;
}
await sleep(50);
}
}
}
public async getDebuggableApps(): Promise<
Mobile.IDeviceApplicationInformation[]
> {
return [];
}
public async getDebuggableAppViews(
appIdentifiers: string[],
): Promise<IDictionary<Mobile.IDebugWebViewInfo[]>> {
return null;
}
/**
* Syncing writes into the signed bundle and breaks its seal, and macOS won't
* launch a bundle whose seal is broken. The signature embedded in the
* executable survives the sync, so its leaf certificate names the identity
* to re-sign with.
*/
private async restoreCodeSignature(): Promise<void> {
const bundlePath = this.device.applicationBundlePath;
const verify = await this.$childProcess.spawnFromEvent(
"codesign",
["--verify", "--strict", bundlePath],
"close",
{},
{ throwError: false },
);
if (verify.exitCode === 0) {
return;
}
try {
const certificatesPrefix = path.join(
await this.$tempService.mkdirSync("ios-mac-codesign"),
"certificate",
);
await this.$childProcess.spawnFromEvent(
"codesign",
["-d", `--extract-certificates=${certificatesPrefix}`, bundlePath],
"close",
);
const leafCertificatePath = `${certificatesPrefix}0`;
if (!this.$fs.exists(leafCertificatePath)) {
this.$logger.warn(
`${bundlePath} has no signing certificate to re-sign it with. Rebuild the app if macOS refuses to launch it.`,
);
return;
}
const identity = crypto
.createHash("sha1")
.update(this.$fs.readFile(leafCertificatePath))
.digest("hex");
await this.$childProcess.spawnFromEvent(
"codesign",
[
"--force",
"--sign",
identity,
"--preserve-metadata=identifier,entitlements,flags,runtime",
bundlePath,
],
"close",
);
} catch (err) {
this.$logger.warn(
`Unable to re-sign ${bundlePath}: ${err.message}. Rebuild the app if macOS refuses to launch it.`,
);
}
}
/**
* macOS only launches an iOS app whose code matches the CDHashes
* LaunchServices recorded for it. Once the bundle changes, the launch can
* race LaunchServices' own re-registration, use the stale record and fail
* with "Launch Constraint Violation", so register it before every launch.
*/
private async registerWithLaunchServices(): Promise<void> {
const result = await this.$childProcess.spawnFromEvent(
LSREGISTER_PATH,
["-f", this.device.wrapperPath],
"close",
{},
{ throwError: false },
);
if (result.exitCode !== 0) {
this.$logger.trace(
`Unable to register ${this.device.wrapperPath} with LaunchServices: ${result.stderr}`,
);
}
}
/**
* macOS runs the app from a copy of the wrapper under /private/var/folders,
* so match the bundle layout rather than the path the CLI installed to.
* Other iPad apps can share the executable name, so each match's
* Info.plist must also name this app.
*/
private async getRunningPids(appId: string): Promise<string[]> {
const name = this.device.executableName.replace(
/[.*+?^${}()|[\]\\]/g,
"\\$&",
);
const processPattern = `/Wrapper/${name}\\.app/${name}( |$)`;
const result = await this.$childProcess.spawnFromEvent(
"pgrep",
["-lf", processPattern],
"close",
{},
// pgrep exits with 1 when nothing matches.
{ throwError: false },
);
const bundlePattern = new RegExp(
`^(\\d+) (.*/Wrapper/${name}\\.app)/${name}(?: |$)`,
);
const pids: string[] = [];
for (const line of (result.stdout || "").split("\n")) {
const match = bundlePattern.exec(line);
if (match && (await this.isBundleOf(match[2], appId))) {
pids.push(match[1]);
}
}
return pids;
}
private async isBundleOf(
bundlePath: string,
appId: string,
): Promise<boolean> {
try {
const infoPlist = await this.$plistParser.parseFile(
path.join(bundlePath, "Info.plist"),
);
return infoPlist?.CFBundleIdentifier === appId;
} catch (err) {
this.$logger.trace(`Unable to read the Info.plist of ${bundlePath}`, err);
return false;
}
}
private async setDeviceLogData(
appData: Mobile.IApplicationData,
): Promise<void> {
this.$deviceLogProvider.setProjectNameForDevice(
this.device.deviceInfo.identifier,
appData.projectName,
);
this.$deviceLogProvider.setProjectDirForDevice(
this.device.deviceInfo.identifier,
appData.projectDir,
);
if (!this.$options.justlaunch) {
await this.startDeviceLog();
}
}
@cache()
private startDeviceLog(): Promise<void> {
return this.device.openDeviceLogStream({ predicate: IOS_LOG_PREDICATE });
}
}