simcast-host 0.0.0-stage → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +72 -2
- package/bin/simcast-host.js +11 -0
- package/package.json +28 -4
- package/proto/idb.proto +1816 -0
- package/src/agent/admin.js +87 -0
- package/src/agent/awake.js +136 -0
- package/src/agent/bonjour.js +172 -0
- package/src/agent/build.js +24 -0
- package/src/agent/checks.js +612 -0
- package/src/agent/clean.js +419 -0
- package/src/agent/cli.js +617 -0
- package/src/agent/clients.js +475 -0
- package/src/agent/exec.js +163 -0
- package/src/agent/live.js +709 -0
- package/src/agent/macinfo.js +61 -0
- package/src/agent/pairing.js +123 -0
- package/src/agent/paths.js +23 -0
- package/src/agent/recipes/expo.js +119 -0
- package/src/agent/recipes/index.js +66 -0
- package/src/agent/recipes/kit.js +124 -0
- package/src/agent/record.js +133 -0
- package/src/agent/runtime.js +166 -0
- package/src/agent/screen.js +285 -0
- package/src/agent/server.js +568 -0
- package/src/agent/service.js +119 -0
- package/src/agent/setup.js +283 -0
- package/src/agent/sim.js +124 -0
- package/src/agent/stalls.js +32 -0
- package/src/agent/state.js +121 -0
- package/src/agent/tunnel.js +464 -0
- package/src/common.js +119 -0
|
@@ -0,0 +1,568 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import http from 'node:http';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import * as tar from 'tar';
|
|
6
|
+
import { WebSocketServer } from 'ws';
|
|
7
|
+
import { MIN_CLIENT_PROTOCOL, PROTOCOL, PROTOCOL_HEADER, VERSION, color, heartbeat, isSafeRelPath, isValidProjectId, negotiateProtocol, sha1File } from '../common.js';
|
|
8
|
+
import * as admin from './admin.js';
|
|
9
|
+
import * as awake from './awake.js';
|
|
10
|
+
import * as bonjour from './bonjour.js';
|
|
11
|
+
import * as build from './build.js';
|
|
12
|
+
import { publicResult, runChecks } from './checks.js';
|
|
13
|
+
import * as clients from './clients.js';
|
|
14
|
+
import { HttpError } from './clients.js';
|
|
15
|
+
import { spawnTool } from './exec.js';
|
|
16
|
+
import * as live from './live.js';
|
|
17
|
+
import { developerDir as findDeveloperDir, freeDiskGB, macosVersion, probe, wakeInfo, xcodeVersion } from './macinfo.js';
|
|
18
|
+
import * as pairing from './pairing.js';
|
|
19
|
+
import { pickRecipe } from './recipes/index.js';
|
|
20
|
+
import * as kit from './recipes/kit.js';
|
|
21
|
+
import * as record from './record.js';
|
|
22
|
+
import { agentHealth, isAgentHealth, writeStatus } from './runtime.js';
|
|
23
|
+
import * as screen from './screen.js';
|
|
24
|
+
import * as sim from './sim.js';
|
|
25
|
+
import { watchStalls } from './stalls.js';
|
|
26
|
+
import * as tunnel from './tunnel.js';
|
|
27
|
+
import { agentHome, loadAgentConfig, loadState, macName, macNameNow, projectPaths, saveState } from './state.js';
|
|
28
|
+
|
|
29
|
+
let busy = null; // one sync or build at a time; the Mac mini has enough to do
|
|
30
|
+
let runStep = null; // the run's current step, for the stall log
|
|
31
|
+
|
|
32
|
+
function sendJson(res, status, body) {
|
|
33
|
+
res.writeHead(status, { 'content-type': 'application/json' });
|
|
34
|
+
res.end(JSON.stringify(body));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function readJson(req, limit = 64 * 1024 * 1024) {
|
|
38
|
+
const chunks = [];
|
|
39
|
+
let size = 0;
|
|
40
|
+
for await (const chunk of req) {
|
|
41
|
+
size += chunk.length;
|
|
42
|
+
if (size > limit) throw new HttpError(413, 'Request body too large');
|
|
43
|
+
chunks.push(chunk);
|
|
44
|
+
}
|
|
45
|
+
try {
|
|
46
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
|
|
47
|
+
} catch {
|
|
48
|
+
throw new HttpError(400, 'Invalid JSON body');
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function requireProject(id) {
|
|
53
|
+
if (!isValidProjectId(id)) throw new HttpError(400, 'Invalid project id');
|
|
54
|
+
return projectPaths(id);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Marks the Mac busy and keeps it awake until the returned release() is called
|
|
58
|
+
// (calling it again does nothing).
|
|
59
|
+
function claim(label) {
|
|
60
|
+
if (busy) throw new HttpError(409, `The Mac is busy (${busy}). Try again when it finishes.`);
|
|
61
|
+
busy = label;
|
|
62
|
+
writeStatus({ busy }, { now: true }); // not debounced: `clean` checks it before deleting builds
|
|
63
|
+
const unhold = awake.hold(label);
|
|
64
|
+
let released = false;
|
|
65
|
+
return () => {
|
|
66
|
+
if (released) return;
|
|
67
|
+
released = true;
|
|
68
|
+
busy = null;
|
|
69
|
+
writeStatus({ busy });
|
|
70
|
+
unhold();
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// GET /info. `req` and `client` give the M3 fields that depend on the caller.
|
|
75
|
+
async function info(req, client, cfg) {
|
|
76
|
+
const developerDir = await findDeveloperDir();
|
|
77
|
+
const local = String(req.socket.localAddress || '').replace(/^::ffff:/, '');
|
|
78
|
+
let wake = null;
|
|
79
|
+
try { wake = wakeInfo(local) || null; } catch { /* unknown interface */ }
|
|
80
|
+
return {
|
|
81
|
+
version: VERSION,
|
|
82
|
+
macos: await macosVersion(),
|
|
83
|
+
xcode: await xcodeVersion(),
|
|
84
|
+
developerDir,
|
|
85
|
+
deviceHub: developerDir ? fs.existsSync(path.join(developerDir, '..', 'Applications', 'DeviceHub.app')) : false,
|
|
86
|
+
cocoapods: (await probe('pod', ['--version']))?.split('\n').pop() || null,
|
|
87
|
+
idbCompanion: (await live.findCompanion()) || null,
|
|
88
|
+
hostApp: await live.hostAppRunning(),
|
|
89
|
+
live: live.liveStatus(),
|
|
90
|
+
pairedWith: clients.pairedClient()?.name || null,
|
|
91
|
+
node: process.version,
|
|
92
|
+
arch: process.arch,
|
|
93
|
+
memoryGB: Math.round(os.totalmem() / 1e9),
|
|
94
|
+
freeMemoryGB: Number((os.freemem() / 1e9).toFixed(1)),
|
|
95
|
+
freeDiskGB: await freeDiskGB(),
|
|
96
|
+
awake: awake.awakeStatus(),
|
|
97
|
+
agentId: cfg.agentId,
|
|
98
|
+
macName: macNameNow(),
|
|
99
|
+
pcs: clients.list().length,
|
|
100
|
+
wake,
|
|
101
|
+
tunnel: tunnel.portsFor(client.id),
|
|
102
|
+
bonjour: bonjour.status(),
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// ---- sync ----------------------------------------------------------------
|
|
107
|
+
|
|
108
|
+
async function syncManifest(body) {
|
|
109
|
+
const { project, files } = body;
|
|
110
|
+
const p = requireProject(project);
|
|
111
|
+
if (!files || typeof files !== 'object') throw new HttpError(400, 'Missing files');
|
|
112
|
+
const release = claim('sync');
|
|
113
|
+
try {
|
|
114
|
+
fs.mkdirSync(p.src, { recursive: true });
|
|
115
|
+
const state = loadState(project);
|
|
116
|
+
const need = [];
|
|
117
|
+
for (const [rel, hash] of Object.entries(files)) {
|
|
118
|
+
if (!isSafeRelPath(rel)) throw new HttpError(400, `Unsafe path: ${rel}`);
|
|
119
|
+
const prev = state.manifest[rel];
|
|
120
|
+
if (!prev || prev.sha1 !== hash) {
|
|
121
|
+
need.push(rel);
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
// Re-send if something on the Mac (like prebuild) touched the file.
|
|
125
|
+
try {
|
|
126
|
+
const st = fs.statSync(path.join(p.src, rel));
|
|
127
|
+
if (st.mtimeMs !== prev.mtimeMs || st.size !== prev.size) need.push(rel);
|
|
128
|
+
} catch {
|
|
129
|
+
need.push(rel);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
let deleted = 0;
|
|
133
|
+
for (const rel of Object.keys(state.manifest)) {
|
|
134
|
+
if (rel in files) continue;
|
|
135
|
+
fs.rmSync(path.join(p.src, rel), { force: true });
|
|
136
|
+
delete state.manifest[rel];
|
|
137
|
+
deleted++;
|
|
138
|
+
}
|
|
139
|
+
state.pending = need;
|
|
140
|
+
saveState(project, state);
|
|
141
|
+
return { need, deleted };
|
|
142
|
+
} finally {
|
|
143
|
+
release();
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async function syncUpload(req, project) {
|
|
148
|
+
const p = requireProject(project);
|
|
149
|
+
const release = claim('sync');
|
|
150
|
+
try {
|
|
151
|
+
fs.mkdirSync(p.src, { recursive: true });
|
|
152
|
+
await new Promise((resolve, reject) => {
|
|
153
|
+
const extract = tar.x({ cwd: p.src, strict: true });
|
|
154
|
+
extract.on('error', reject);
|
|
155
|
+
extract.on('close', resolve);
|
|
156
|
+
req.on('error', reject);
|
|
157
|
+
req.pipe(extract);
|
|
158
|
+
});
|
|
159
|
+
const state = loadState(project);
|
|
160
|
+
for (const rel of state.pending || []) {
|
|
161
|
+
const abs = path.join(p.src, rel);
|
|
162
|
+
if (!fs.existsSync(abs)) continue;
|
|
163
|
+
const st = fs.statSync(abs);
|
|
164
|
+
state.manifest[rel] = { sha1: await sha1File(abs), mtimeMs: st.mtimeMs, size: st.size };
|
|
165
|
+
}
|
|
166
|
+
const count = (state.pending || []).length;
|
|
167
|
+
state.pending = [];
|
|
168
|
+
saveState(project, state);
|
|
169
|
+
return { ok: true, files: count };
|
|
170
|
+
} finally {
|
|
171
|
+
release();
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// ---- run -----------------------------------------------------------------
|
|
176
|
+
|
|
177
|
+
async function runIos(req, res, body) {
|
|
178
|
+
const { project, device, rebuild = false, clean = false, cng = true, showUI = false, devServerUrl } = body;
|
|
179
|
+
const p = requireProject(project);
|
|
180
|
+
if (!fs.existsSync(p.src)) throw new HttpError(400, 'Project has not been synced yet');
|
|
181
|
+
let recipe;
|
|
182
|
+
try {
|
|
183
|
+
recipe = pickRecipe(p.src, body.recipe);
|
|
184
|
+
} catch (err) {
|
|
185
|
+
throw new HttpError(400, err.message);
|
|
186
|
+
}
|
|
187
|
+
const release = claim('build');
|
|
188
|
+
try {
|
|
189
|
+
await runClaimed(res, { project, device, rebuild, clean, cng, showUI, devServerUrl, p, recipe });
|
|
190
|
+
} finally {
|
|
191
|
+
release();
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// The run itself, while claim('build') is held.
|
|
196
|
+
async function runClaimed(res, { project, device, rebuild, clean, cng, showUI, devServerUrl, p, recipe }) {
|
|
197
|
+
res.writeHead(200, { 'content-type': 'application/x-ndjson', 'cache-control': 'no-cache' });
|
|
198
|
+
const emit = (event) => {
|
|
199
|
+
if (!res.destroyed) res.write(`${JSON.stringify(event)}\n`);
|
|
200
|
+
};
|
|
201
|
+
fs.mkdirSync(p.logs, { recursive: true });
|
|
202
|
+
const logFile = path.join(p.logs, `run-${new Date().toISOString().replace(/[:.]/g, '-')}.log`);
|
|
203
|
+
const logStream = fs.createWriteStream(logFile);
|
|
204
|
+
const onLine = (line, stream) => {
|
|
205
|
+
logStream.write(`${line}\n`);
|
|
206
|
+
emit({ t: 'log', line, stream });
|
|
207
|
+
};
|
|
208
|
+
const step = (msg) => {
|
|
209
|
+
runStep = msg;
|
|
210
|
+
logStream.write(`\n=== ${msg} (${new Date().toISOString()})\n`);
|
|
211
|
+
emit({ t: 'step', msg });
|
|
212
|
+
};
|
|
213
|
+
const started = Date.now();
|
|
214
|
+
const state = loadState(project);
|
|
215
|
+
|
|
216
|
+
const ctx = {
|
|
217
|
+
src: p.src,
|
|
218
|
+
derived: p.derived,
|
|
219
|
+
state,
|
|
220
|
+
options: { cng, clean, devServerUrl },
|
|
221
|
+
sim,
|
|
222
|
+
tunnel: { listening: (port) => tunnel.listening(port) },
|
|
223
|
+
onLine,
|
|
224
|
+
step,
|
|
225
|
+
info: (msg) => emit({ t: 'info', msg }),
|
|
226
|
+
warn: (msg) => emit({ t: 'warn', msg }),
|
|
227
|
+
};
|
|
228
|
+
|
|
229
|
+
try {
|
|
230
|
+
step('Preparing simulator');
|
|
231
|
+
const dev = await sim.resolveDevice(device);
|
|
232
|
+
emit({ t: 'info', msg: `${dev.name} (${dev.runtime})` });
|
|
233
|
+
if (dev.state !== 'Booted') await sim.boot(dev.udid);
|
|
234
|
+
if (showUI) await sim.showUI();
|
|
235
|
+
ctx.info(`${recipe.name} project`);
|
|
236
|
+
|
|
237
|
+
if (recipe.deps) {
|
|
238
|
+
step('Checking JS dependencies');
|
|
239
|
+
const installed = await recipe.deps(ctx);
|
|
240
|
+
saveState(project, state);
|
|
241
|
+
emit({ t: 'info', msg: installed ? 'Dependencies installed' : 'Dependencies unchanged' });
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
step('Fingerprinting native code');
|
|
245
|
+
const fp = await recipe.fingerprint(ctx);
|
|
246
|
+
emit({ t: 'info', msg: `${fp.hash.slice(0, 12)} via ${fp.source}` });
|
|
247
|
+
|
|
248
|
+
let appPath = build.cachedApp(p.builds, fp.hash);
|
|
249
|
+
if (!appPath || rebuild || clean) {
|
|
250
|
+
step('Building native iOS app (the slow part, only when native code changes)');
|
|
251
|
+
const built = await recipe.build(ctx);
|
|
252
|
+
appPath = build.cacheApp(built, p.builds, fp.hash);
|
|
253
|
+
} else {
|
|
254
|
+
emit({ t: 'info', msg: 'Native code unchanged, reusing the cached build' });
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
step('Installing app');
|
|
258
|
+
const meta = await kit.readAppMeta(appPath);
|
|
259
|
+
await sim.terminate(dev.udid, meta.bundleId);
|
|
260
|
+
await sim.install(dev.udid, appPath);
|
|
261
|
+
|
|
262
|
+
step('Launching');
|
|
263
|
+
await recipe.launch(ctx, { udid: dev.udid, appPath, meta });
|
|
264
|
+
|
|
265
|
+
state.lastRun = { udid: dev.udid, bundleId: meta.bundleId, executable: meta.executable, at: Date.now() };
|
|
266
|
+
saveState(project, state);
|
|
267
|
+
emit({ t: 'done', ok: true, ms: Date.now() - started, logFile });
|
|
268
|
+
} catch (err) {
|
|
269
|
+
logStream.write(`\nFAILED: ${err.message}\n`);
|
|
270
|
+
emit({ t: 'done', ok: false, error: err.message, tail: err.tail || [], ms: Date.now() - started, logFile });
|
|
271
|
+
} finally {
|
|
272
|
+
runStep = null;
|
|
273
|
+
logStream.end();
|
|
274
|
+
res.end();
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// ---- simulator actions ---------------------------------------------------
|
|
279
|
+
|
|
280
|
+
async function simAction(body) {
|
|
281
|
+
const { action, device, value, project } = body;
|
|
282
|
+
const dev = await sim.resolveDevice(device);
|
|
283
|
+
const lastBundle = isValidProjectId(project) ? loadState(project).lastRun?.bundleId : null;
|
|
284
|
+
switch (action) {
|
|
285
|
+
case 'boot': await sim.boot(dev.udid); break;
|
|
286
|
+
case 'shutdown': await sim.shutdown(dev.udid); break;
|
|
287
|
+
case 'erase': await sim.erase(dev.udid); break;
|
|
288
|
+
case 'show': await sim.showUI(); break;
|
|
289
|
+
case 'dark':
|
|
290
|
+
case 'light': await sim.appearance(dev.udid, action); break;
|
|
291
|
+
case 'rotate-left':
|
|
292
|
+
case 'rotate-right': return { ok: true, device: dev, rotation: await live.rotate(dev.udid, action.slice('rotate-'.length)) };
|
|
293
|
+
case 'url':
|
|
294
|
+
if (!value) throw new HttpError(400, 'Missing URL');
|
|
295
|
+
await sim.openUrl(dev.udid, value);
|
|
296
|
+
break;
|
|
297
|
+
case 'location':
|
|
298
|
+
if (value === 'clear') await sim.clearLocation(dev.udid);
|
|
299
|
+
else if (/^-?\d+(\.\d+)?,-?\d+(\.\d+)?$/.test(value || '')) await sim.setLocation(dev.udid, value);
|
|
300
|
+
else throw new HttpError(400, 'Location must be "lat,lon" or "clear"');
|
|
301
|
+
break;
|
|
302
|
+
case 'push': {
|
|
303
|
+
const bundleId = body.bundleId || lastBundle;
|
|
304
|
+
if (!bundleId) throw new HttpError(400, 'No bundle id. Run the app once first, or pass --bundle.');
|
|
305
|
+
await sim.push(dev.udid, bundleId, value || { aps: { alert: 'Hello from simcast' } });
|
|
306
|
+
break;
|
|
307
|
+
}
|
|
308
|
+
default: throw new HttpError(400, `Unknown action "${action}"`);
|
|
309
|
+
}
|
|
310
|
+
return { ok: true, device: dev };
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
async function streamLogs(req, res, query) {
|
|
314
|
+
const project = query.get('project');
|
|
315
|
+
const state = isValidProjectId(project) ? loadState(project) : {};
|
|
316
|
+
const udid = query.get('device') ? (await sim.resolveDevice(query.get('device'))).udid : state.lastRun?.udid;
|
|
317
|
+
if (!udid) throw new HttpError(400, 'No device. Run the app once first, or pass --device.');
|
|
318
|
+
const args = ['simctl', 'spawn', udid, 'log', 'stream', '--style', 'compact'];
|
|
319
|
+
if (!query.get('all') && state.lastRun?.executable) args.push('--predicate', `process == "${state.lastRun.executable.replace(/"/g, '')}"`);
|
|
320
|
+
res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' });
|
|
321
|
+
const child = spawnTool('xcrun', args);
|
|
322
|
+
child.stdout.pipe(res);
|
|
323
|
+
child.stderr.pipe(res);
|
|
324
|
+
child.on('error', () => res.end());
|
|
325
|
+
child.on('close', () => res.end());
|
|
326
|
+
req.on('close', () => child.kill());
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// ---- live screen ---------------------------------------------------------
|
|
330
|
+
|
|
331
|
+
async function streamScreen(req, res, query) {
|
|
332
|
+
const dev = await sim.resolveDevice(query.get('device'));
|
|
333
|
+
if (dev.state !== 'Booted') await sim.boot(dev.udid);
|
|
334
|
+
const fps = Math.min(30, Math.max(1, Number(query.get('fps')) || 30));
|
|
335
|
+
const boundary = 'simcastframe';
|
|
336
|
+
res.writeHead(200, {
|
|
337
|
+
'content-type': `multipart/x-mixed-replace; boundary=${boundary}`,
|
|
338
|
+
'cache-control': 'no-cache, no-store',
|
|
339
|
+
connection: 'keep-alive',
|
|
340
|
+
'x-device-udid': dev.udid,
|
|
341
|
+
});
|
|
342
|
+
req.socket.setNoDelay(true);
|
|
343
|
+
let waiting = false; // drop frames for slow viewers instead of lagging
|
|
344
|
+
let pending = null;
|
|
345
|
+
const write = (frame) => {
|
|
346
|
+
if (res.destroyed) return;
|
|
347
|
+
if (waiting) { pending = frame; return; }
|
|
348
|
+
res.write(`--${boundary}\r\nContent-Type: image/jpeg\r\nContent-Length: ${frame.length}\r\n\r\n`);
|
|
349
|
+
const ok = res.write(frame);
|
|
350
|
+
res.write('\r\n');
|
|
351
|
+
if (!ok) {
|
|
352
|
+
waiting = true;
|
|
353
|
+
res.once('drain', () => {
|
|
354
|
+
waiting = false;
|
|
355
|
+
if (pending) { const f = pending; pending = null; write(f); }
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
};
|
|
359
|
+
console.log(`[${new Date().toISOString()}] viewer connected to ${dev.name} (${dev.udid})`);
|
|
360
|
+
const unsubscribe = await screen.subscribe(dev.udid, fps, write);
|
|
361
|
+
res.on('close', () => {
|
|
362
|
+
console.log(`[${new Date().toISOString()}] viewer left ${dev.name}`);
|
|
363
|
+
unsubscribe();
|
|
364
|
+
});
|
|
365
|
+
// Send headers right away so the window knows the Mac answered.
|
|
366
|
+
res.flushHeaders();
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
async function screenStatus(query) {
|
|
370
|
+
const dev = await sim.resolveDevice(query.get('device'));
|
|
371
|
+
let points = null;
|
|
372
|
+
try { points = screen.screenPoints(dev.udid); } catch { /* no frame yet */ }
|
|
373
|
+
return { device: dev, points, stream: screen.hubInfo(dev.udid) };
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// ---- server --------------------------------------------------------------
|
|
377
|
+
|
|
378
|
+
// The protocol this request's client and the agent agree on (plan 2.1).
|
|
379
|
+
const protocolOf = (req) => negotiateProtocol(req.headers[PROTOCOL_HEADER]);
|
|
380
|
+
|
|
381
|
+
export function startAgent({ port } = {}) {
|
|
382
|
+
const cfg = loadAgentConfig();
|
|
383
|
+
clients.startServing();
|
|
384
|
+
macName(); // asked once at start, so /health soon has it
|
|
385
|
+
const listenPort = Number(port || process.env.SIMCAST_PORT || cfg.port);
|
|
386
|
+
|
|
387
|
+
const server = http.createServer(async (req, res) => {
|
|
388
|
+
const url = new URL(req.url, 'http://agent');
|
|
389
|
+
const route = `${req.method} ${url.pathname}`;
|
|
390
|
+
try {
|
|
391
|
+
// The order of checks: docs/protocol.md, "Order of checks".
|
|
392
|
+
// 1. /health: no checks.
|
|
393
|
+
if (route === 'GET /health') {
|
|
394
|
+
return sendJson(res, 200, {
|
|
395
|
+
ok: true, name: 'simcast-host', version: VERSION, protocol: protocolOf(req),
|
|
396
|
+
protocolMin: MIN_CLIENT_PROTOCOL, protocolMax: PROTOCOL, agentId: cfg.agentId, macName: macNameNow(),
|
|
397
|
+
pairing: pairing.status().open, platform: process.platform, features: ['doctor'],
|
|
398
|
+
});
|
|
399
|
+
}
|
|
400
|
+
// 2. The Mac-local admin API (loopback and the admin token).
|
|
401
|
+
if (url.pathname === '/admin' || url.pathname.startsWith('/admin/')) {
|
|
402
|
+
return await admin.handle(req, res, { url, adminToken: cfg.adminToken });
|
|
403
|
+
}
|
|
404
|
+
// 3. Pairing with a code: no bearer token, a valid client id.
|
|
405
|
+
if (route === 'POST /pair/code') {
|
|
406
|
+
const client = clients.clientOf(req);
|
|
407
|
+
if (!client) throw new HttpError(400, 'This PC runs an older simcast. Update simcast on this PC and run "simcast pair" again.');
|
|
408
|
+
const body = await readJson(req, 64 * 1024);
|
|
409
|
+
const paired = pairing.tryCode(client, body.code, body.force === true);
|
|
410
|
+
return sendJson(res, 200, {
|
|
411
|
+
ok: true, token: paired.token, agentId: cfg.agentId, macName: macNameNow(),
|
|
412
|
+
previous: paired.previous, active: true,
|
|
413
|
+
});
|
|
414
|
+
}
|
|
415
|
+
// 4-6. The bearer token and the client id.
|
|
416
|
+
const { client, via } = clients.authenticate(req);
|
|
417
|
+
// 7. The pairing routes.
|
|
418
|
+
if (route === 'POST /pair') {
|
|
419
|
+
const body = await readJson(req, 64 * 1024);
|
|
420
|
+
return sendJson(res, 200, { ok: true, ...clients.claim(client, { force: body.force === true }) });
|
|
421
|
+
}
|
|
422
|
+
if (route === 'DELETE /pair') {
|
|
423
|
+
clients.unpair(client.id, 'unpaired itself');
|
|
424
|
+
return sendJson(res, 200, { ok: true });
|
|
425
|
+
}
|
|
426
|
+
if (route === 'POST /token/rotate') {
|
|
427
|
+
const { token, issuedAt } = clients.rotate(client);
|
|
428
|
+
return sendJson(res, 200, { token, agentId: cfg.agentId, macName: macNameNow(), issuedAt });
|
|
429
|
+
}
|
|
430
|
+
// 8. Admission: the active PC, or a switch to this one.
|
|
431
|
+
clients.admit(client);
|
|
432
|
+
// 9. The route; the socket is remembered so it can be cut.
|
|
433
|
+
clients.track(req.socket, client.id, via);
|
|
434
|
+
|
|
435
|
+
switch (route) {
|
|
436
|
+
case 'GET /info': return sendJson(res, 200, await info(req, client, cfg));
|
|
437
|
+
case 'GET /doctor': return sendJson(res, 200, { checks: (await runChecks({ scope: 'doctor' })).map(publicResult) });
|
|
438
|
+
case 'GET /devices': return sendJson(res, 200, { devices: await sim.listDevices({ all: url.searchParams.has('all') }) });
|
|
439
|
+
case 'GET /probe': {
|
|
440
|
+
const target = url.searchParams.get('url') || '';
|
|
441
|
+
if (!/^https?:\/\//.test(target)) throw new HttpError(400, 'Only http(s) URLs can be probed');
|
|
442
|
+
return sendJson(res, 200, await kit.probe(target));
|
|
443
|
+
}
|
|
444
|
+
case 'POST /sync/manifest': return sendJson(res, 200, await syncManifest(await readJson(req)));
|
|
445
|
+
case 'POST /sync/upload': return sendJson(res, 200, await syncUpload(req, url.searchParams.get('project')));
|
|
446
|
+
case 'POST /run': return await runIos(req, res, await readJson(req));
|
|
447
|
+
case 'POST /sim': return sendJson(res, 200, await simAction(await readJson(req)));
|
|
448
|
+
case 'GET /screenshot': {
|
|
449
|
+
const dev = await sim.resolveDevice(url.searchParams.get('device'));
|
|
450
|
+
const png = await sim.screenshot(dev.udid);
|
|
451
|
+
res.writeHead(200, { 'content-type': 'image/png' });
|
|
452
|
+
return res.end(png);
|
|
453
|
+
}
|
|
454
|
+
case 'GET /pasteboard': {
|
|
455
|
+
const dev = await sim.resolveDevice(url.searchParams.get('device'));
|
|
456
|
+
return sendJson(res, 200, { text: await sim.pasteboard(dev.udid) });
|
|
457
|
+
}
|
|
458
|
+
case 'POST /pasteboard': {
|
|
459
|
+
const body = await readJson(req, 1024 * 1024);
|
|
460
|
+
if (typeof body.text !== 'string') throw new HttpError(400, 'Missing text');
|
|
461
|
+
const dev = await sim.resolveDevice(body.device);
|
|
462
|
+
await sim.setPasteboard(dev.udid, body.text);
|
|
463
|
+
return sendJson(res, 200, { ok: true });
|
|
464
|
+
}
|
|
465
|
+
case 'POST /record': {
|
|
466
|
+
const body = await readJson(req);
|
|
467
|
+
const dev = await sim.resolveDevice(body.device);
|
|
468
|
+
if (body.action === 'start') {
|
|
469
|
+
await record.startRecording(dev.udid);
|
|
470
|
+
return sendJson(res, 200, { ok: true });
|
|
471
|
+
}
|
|
472
|
+
if (body.action !== 'stop') throw new HttpError(400, 'action must be "start" or "stop"');
|
|
473
|
+
const mp4 = await record.stopRecording(dev.udid);
|
|
474
|
+
res.writeHead(200, { 'content-type': 'video/mp4' });
|
|
475
|
+
return res.end(mp4);
|
|
476
|
+
}
|
|
477
|
+
case 'GET /logs': return await streamLogs(req, res, url.searchParams);
|
|
478
|
+
case 'GET /stream': return await streamScreen(req, res, url.searchParams);
|
|
479
|
+
case 'GET /screen': return sendJson(res, 200, await screenStatus(url.searchParams));
|
|
480
|
+
case 'GET /tunnel/ports': return sendJson(res, 200, tunnel.portsFor(client.id));
|
|
481
|
+
case 'POST /input': {
|
|
482
|
+
const ev = await readJson(req, 64 * 1024);
|
|
483
|
+
try { screen.checkInput(ev); } catch (err) { throw new HttpError(400, err.message); }
|
|
484
|
+
const dev = await sim.resolveDevice(ev.device);
|
|
485
|
+
await screen.sendInput(dev.udid, ev);
|
|
486
|
+
return sendJson(res, 200, { ok: true });
|
|
487
|
+
}
|
|
488
|
+
default: return sendJson(res, 404, { error: `No route ${route}` });
|
|
489
|
+
}
|
|
490
|
+
} catch (err) {
|
|
491
|
+
if (res.headersSent) return res.end();
|
|
492
|
+
sendJson(res, err.status || 500, { error: err.message, ...(err.body || {}), tail: err.tail });
|
|
493
|
+
}
|
|
494
|
+
});
|
|
495
|
+
|
|
496
|
+
server.requestTimeout = 0; // builds can take a long time
|
|
497
|
+
for (const sig of ['SIGTERM', 'SIGINT', 'SIGHUP']) {
|
|
498
|
+
process.on(sig, () => {
|
|
499
|
+
clients.stopAll();
|
|
500
|
+
tunnel.stopAll();
|
|
501
|
+
bonjour.stop();
|
|
502
|
+
screen.stopAll();
|
|
503
|
+
live.stopAllCompanions();
|
|
504
|
+
process.exit(0);
|
|
505
|
+
});
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
// WebSockets: /session is the PC's control connection (heartbeats, so either side
|
|
509
|
+
// notices a lost connection within seconds); /live carries H.264 frames out and input in;
|
|
510
|
+
// /tunnel is the PC's tunnel control connection. /tunnel/data is a raw TCP
|
|
511
|
+
// stream (Upgrade: simcast-tcp) and never goes through the WebSocket server.
|
|
512
|
+
const wss = new WebSocketServer({ noServer: true, perMessageDeflate: false, maxPayload: 1024 * 1024 });
|
|
513
|
+
server.on('upgrade', (req, socket, head) => {
|
|
514
|
+
const url = new URL(req.url, 'http://agent');
|
|
515
|
+
const refuse = (status, msg) => {
|
|
516
|
+
socket.write(`HTTP/1.1 ${status}\r\nx-simcast-error: ${encodeURIComponent(msg)}\r\nConnection: close\r\n\r\n`);
|
|
517
|
+
socket.destroy();
|
|
518
|
+
};
|
|
519
|
+
if (!['/live', '/session', '/tunnel', '/tunnel/data'].includes(url.pathname)) return refuse('404 Not Found', `No route ${url.pathname}`);
|
|
520
|
+
// The same checks as for requests (steps 4-8), refused as bare responses.
|
|
521
|
+
let client;
|
|
522
|
+
let via;
|
|
523
|
+
try {
|
|
524
|
+
({ client, via } = clients.authenticate(req));
|
|
525
|
+
clients.admit(client);
|
|
526
|
+
} catch (err) {
|
|
527
|
+
const status = err.status || 500;
|
|
528
|
+
return refuse(`${status} ${http.STATUS_CODES[status] || 'Error'}`, err.message);
|
|
529
|
+
}
|
|
530
|
+
clients.track(socket, client.id, via);
|
|
531
|
+
socket.setNoDelay(true);
|
|
532
|
+
if (url.pathname === '/tunnel/data') return tunnel.handleData(req, socket, head, client);
|
|
533
|
+
const protocol = protocolOf(req);
|
|
534
|
+
wss.handleUpgrade(req, socket, head, (ws) => {
|
|
535
|
+
if (url.pathname === '/session') return clients.addSession(ws, client, { protocol, via });
|
|
536
|
+
if (url.pathname === '/tunnel') return tunnel.attachControl(ws, client, { protocol });
|
|
537
|
+
heartbeat(ws); // a silent drop closes the viewer, which lifts a finger still held down
|
|
538
|
+
live.attachViewer(ws, { device: url.searchParams.get('device'), quality: url.searchParams.get('quality') })
|
|
539
|
+
.catch((err) => { try { ws.close(1011, err.message.slice(0, 120)); } catch { /* ignore */ } });
|
|
540
|
+
});
|
|
541
|
+
});
|
|
542
|
+
server.on('error', async (err) => {
|
|
543
|
+
if (err.code !== 'EADDRINUSE') {
|
|
544
|
+
console.error(color.red(`The agent could not listen on port ${listenPort}: ${err.message}`));
|
|
545
|
+
process.exit(1);
|
|
546
|
+
}
|
|
547
|
+
// Only one agent at a time: a second one (the LaunchAgent plus a manual
|
|
548
|
+
// `serve`, say) leaves quietly; anything else on the port is an error.
|
|
549
|
+
if (isAgentHealth(await agentHealth(listenPort, 2000))) {
|
|
550
|
+
console.log(`Another simcast-host is already running on port ${listenPort}.`);
|
|
551
|
+
console.log(' Use the running one, or stop it first: simcast-host uninstall. If another program uses the port, give the host another with --port.');
|
|
552
|
+
process.exit(0);
|
|
553
|
+
}
|
|
554
|
+
console.error(color.red(`Port ${listenPort} is used by another program. Stop it, or start the agent with --port.`));
|
|
555
|
+
process.exit(1);
|
|
556
|
+
});
|
|
557
|
+
server.listen(listenPort, '0.0.0.0', () => {
|
|
558
|
+
const boundPort = server.address().port; // differs from listenPort when 0 was asked for
|
|
559
|
+
console.log(color.bold(`simcast agent ${VERSION} listening on port ${boundPort}`));
|
|
560
|
+
console.log(`Data folder: ${agentHome}`);
|
|
561
|
+
if (process.platform !== 'darwin') console.log(color.yellow('Warning: not running on macOS, so builds and simulators will fail.'));
|
|
562
|
+
console.log(`\nPair a PC: run ${color.cyan('simcast-host pair')} on this Mac, then ${color.cyan('simcast pair')} on the PC.`);
|
|
563
|
+
macName().then((name) => bonjour.start({ port: boundPort, agentId: cfg.agentId, macName: name }));
|
|
564
|
+
});
|
|
565
|
+
const stopWatching = watchStalls({ during: () => (runStep ? `run step "${runStep}"` : '') });
|
|
566
|
+
server.on('close', stopWatching);
|
|
567
|
+
return server;
|
|
568
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// How the agent keeps running: a LaunchAgent (com.simcast.host) in your
|
|
2
|
+
// logged-in session, not a system daemon. The simulator and code signing both
|
|
3
|
+
// need that session.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { parseArgs } from 'node:util';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
import { color } from '../common.js';
|
|
9
|
+
import { run, spawnTool } from './exec.js';
|
|
10
|
+
import { AGENT_LABEL, LAUNCH_AGENTS_DIR, LOG_FILE, uid } from './paths.js';
|
|
11
|
+
|
|
12
|
+
const BIN = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'bin', 'simcast-host.js');
|
|
13
|
+
|
|
14
|
+
// Settings a user may have exported when running `install`; the service should
|
|
15
|
+
// see the same ones, since launchd starts it with an almost empty environment.
|
|
16
|
+
const CARRIED_ENV = ['SIMCAST_EXTRA_PATH', 'SIMCAST_HOME', 'SIMCAST_LOG_FILE', 'SIMCAST_TUNNEL_PORT_OFFSET'];
|
|
17
|
+
|
|
18
|
+
// The CARRIED_ENV values an existing plist has, so running setup again (after
|
|
19
|
+
// an upgrade, say) keeps them unless the shell sets them anew.
|
|
20
|
+
const unxml = (s) => s.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, '&');
|
|
21
|
+
export function plistEnv(text) {
|
|
22
|
+
const env = {};
|
|
23
|
+
for (const [, k, v] of text.matchAll(/<key>([A-Z_]+)<\/key><string>([^<]*)<\/string>/g)) {
|
|
24
|
+
if (CARRIED_ENV.includes(k)) env[k] = unxml(v);
|
|
25
|
+
}
|
|
26
|
+
return env;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// A Homebrew Cellar path names one version (…/Cellar/node/25.1.0/…), gone after
|
|
30
|
+
// `brew upgrade`; its opt link (…/opt/node/…) follows upgrades.
|
|
31
|
+
export const stablePath = (p) => p.replace(/\/Cellar\/([^/]+)\/[^/]+\//, '/opt/$1/');
|
|
32
|
+
|
|
33
|
+
export const plistPath = (label) => path.join(LAUNCH_AGENTS_DIR, `${label}.plist`);
|
|
34
|
+
const domain = () => `gui/${uid()}`;
|
|
35
|
+
|
|
36
|
+
const xml = (s) => String(s)
|
|
37
|
+
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
|
38
|
+
.replace(/"/g, '"').replace(/'/g, ''');
|
|
39
|
+
|
|
40
|
+
export function renderPlist({ label = AGENT_LABEL, programArguments, env = {}, logFile = LOG_FILE }) {
|
|
41
|
+
const strings = (items, indent) => items.map((s) => `${indent}<string>${xml(s)}</string>`).join('\n');
|
|
42
|
+
const envLines = Object.entries(env).map(([k, v]) => ` <key>${xml(k)}</key><string>${xml(v)}</string>`).join('\n');
|
|
43
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
44
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
45
|
+
<plist version="1.0">
|
|
46
|
+
<dict>
|
|
47
|
+
<key>Label</key><string>${xml(label)}</string>
|
|
48
|
+
<key>ProgramArguments</key>
|
|
49
|
+
<array>
|
|
50
|
+
${strings(programArguments, ' ')}
|
|
51
|
+
</array>
|
|
52
|
+
<key>RunAtLoad</key><true/>
|
|
53
|
+
<key>KeepAlive</key><true/>
|
|
54
|
+
<key>ProcessType</key><string>Interactive</string>
|
|
55
|
+
<key>StandardOutPath</key><string>${xml(logFile)}</string>
|
|
56
|
+
<key>StandardErrorPath</key><string>${xml(logFile)}</string>
|
|
57
|
+
<key>EnvironmentVariables</key>
|
|
58
|
+
<dict>
|
|
59
|
+
${envLines}
|
|
60
|
+
</dict>
|
|
61
|
+
</dict>
|
|
62
|
+
</plist>
|
|
63
|
+
`;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Unloads a job; "not loaded" (3, or 113 "could not find service") is fine.
|
|
67
|
+
async function bootout(label) {
|
|
68
|
+
const res = await run('launchctl', ['bootout', `${domain()}/${label}`]);
|
|
69
|
+
if (res.code !== 0 && res.code !== 3 && res.code !== 113) {
|
|
70
|
+
throw new Error(`launchctl bootout ${label} failed (exit ${res.code}): ${res.tail.join(' ')}`);
|
|
71
|
+
}
|
|
72
|
+
return res.code === 0;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export async function installCmd(args = []) {
|
|
76
|
+
const { values } = parseArgs({ args, options: { port: { type: 'string' }, json: { type: 'boolean' } } });
|
|
77
|
+
if (values.port !== undefined && !/^\d+$/.test(values.port)) {
|
|
78
|
+
console.error(`--port must be a number, not "${values.port}".`);
|
|
79
|
+
return 64;
|
|
80
|
+
}
|
|
81
|
+
const file = plistPath(AGENT_LABEL);
|
|
82
|
+
let kept = {};
|
|
83
|
+
try { kept = plistEnv(fs.readFileSync(file, 'utf8')); } catch { /* no plist yet */ }
|
|
84
|
+
const env = { LANG: 'en_US.UTF-8', ...kept };
|
|
85
|
+
for (const key of CARRIED_ENV) if (process.env[key]) env[key] = process.env[key];
|
|
86
|
+
const programArguments = [stablePath(process.execPath), stablePath(BIN), 'serve', ...(values.port ? ['--port', values.port] : [])];
|
|
87
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
88
|
+
fs.mkdirSync(path.dirname(LOG_FILE), { recursive: true });
|
|
89
|
+
fs.writeFileSync(file, renderPlist({ programArguments, env }));
|
|
90
|
+
|
|
91
|
+
// bootstrap refuses a job that is already loaded, so unload the old one first.
|
|
92
|
+
await bootout(AGENT_LABEL);
|
|
93
|
+
const res = await run('launchctl', ['bootstrap', domain(), file]);
|
|
94
|
+
if (res.code !== 0) {
|
|
95
|
+
console.error(color.red(`launchctl bootstrap failed (exit ${res.code}): ${res.tail.join(' ')}`));
|
|
96
|
+
console.error(`The LaunchAgent is at ${file}. Check the log: ${LOG_FILE}`);
|
|
97
|
+
return 1;
|
|
98
|
+
}
|
|
99
|
+
console.log(color.green('Agent installed and started. It starts again when you log in.'));
|
|
100
|
+
console.log(` LaunchAgent: ${file}`);
|
|
101
|
+
console.log(` Log: ${LOG_FILE}`);
|
|
102
|
+
console.log(`\nNext, connect your computer: ${color.cyan('simcast-host pair')}`);
|
|
103
|
+
return 0;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export async function uninstallCmd(args = []) {
|
|
107
|
+
parseArgs({ args, options: { port: { type: 'string' }, json: { type: 'boolean' } } });
|
|
108
|
+
const file = plistPath(AGENT_LABEL);
|
|
109
|
+
const wasLoaded = await bootout(AGENT_LABEL);
|
|
110
|
+
const hadFile = fs.existsSync(file);
|
|
111
|
+
fs.rmSync(file, { force: true });
|
|
112
|
+
if (!wasLoaded && !hadFile) {
|
|
113
|
+
console.log(`No simcast LaunchAgent was installed (${file}).`);
|
|
114
|
+
} else {
|
|
115
|
+
console.log(color.green('Agent stopped and removed.'));
|
|
116
|
+
if (hadFile) console.log(` Removed ${file}`);
|
|
117
|
+
}
|
|
118
|
+
return 0;
|
|
119
|
+
}
|