simcast-host 0.0.0-stage → 0.9.1
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 +618 -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 +75 -0
- package/src/agent/pairing.js +123 -0
- package/src/agent/paths.js +23 -0
- package/src/agent/recipes/expo.js +134 -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 +577 -0
- package/src/agent/service.js +119 -0
- package/src/agent/setup.js +283 -0
- package/src/agent/sim.js +129 -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,475 @@
|
|
|
1
|
+
// The PCs this Mac knows (docs/protocol.md, "Authentication and the paired PC").
|
|
2
|
+
//
|
|
3
|
+
// ~/.simcast/clients.json (0600):
|
|
4
|
+
// { version: 1, active: "<clientId>" | null,
|
|
5
|
+
// pcs: [ { id, name, via: "code", tokenHash, prevTokenHash, prevValidUntil,
|
|
6
|
+
// tokenIssuedAt, pairedAt, lastSeenAt } ] }
|
|
7
|
+
// - Up to 16 PCs. Only SHA-256 hashes (base64url) of their tokens are stored.
|
|
8
|
+
// - The Mac works with one PC at a time, the active one. Another paired PC
|
|
9
|
+
// becomes the active one by itself when the active PC isn't connected;
|
|
10
|
+
// otherwise it gets 403 in-use (or takes over with POST /pair { force }).
|
|
11
|
+
//
|
|
12
|
+
// "Connected": a PC is connected while it has a /session open (tracked here)
|
|
13
|
+
// or a /tunnel control connection up. For the tunnel this module asks
|
|
14
|
+
// tunnel.portsFor(id).connected, so tunnel.js needs no hook into this module;
|
|
15
|
+
// it only calls track(socket, id) for its sockets. tunnel.js may call
|
|
16
|
+
// reportConnected() when its control connection comes or goes, to refresh the
|
|
17
|
+
// status file's `connected` at once (otherwise it is refreshed on the next
|
|
18
|
+
// session change).
|
|
19
|
+
import crypto from 'node:crypto';
|
|
20
|
+
import fs from 'node:fs';
|
|
21
|
+
import path from 'node:path';
|
|
22
|
+
import { HEARTBEAT_TIMEOUT_MS, PROTOCOL, VERSION, heartbeat } from '../common.js';
|
|
23
|
+
import * as awake from './awake.js';
|
|
24
|
+
import { writeStatus } from './runtime.js';
|
|
25
|
+
import { agentHome, newToken } from './state.js';
|
|
26
|
+
import * as tunnel from './tunnel.js';
|
|
27
|
+
|
|
28
|
+
export const MAX_PCS = 16;
|
|
29
|
+
export const GRACE_MS = 7 * 24 * 60 * 60 * 1000; // a rotated token stays valid this long
|
|
30
|
+
export const TOUCH_MS = 60 * 1000; // lastSeenAt and name changes are written at most this often
|
|
31
|
+
|
|
32
|
+
const FILE = path.join(agentHome, 'clients.json');
|
|
33
|
+
const log = (msg) => console.log(`[${new Date().toISOString()}] clients: ${msg}`);
|
|
34
|
+
|
|
35
|
+
export const UNPAIRED_REASON = 'This PC was unpaired on the Mac. Pair again: simcast pair';
|
|
36
|
+
const NOT_PAIRED = 'This PC isn\'t paired with this Mac. Pair again: simcast pair';
|
|
37
|
+
const OTHER_PCS_TOKEN = 'This token belongs to another PC. Pair again: simcast pair';
|
|
38
|
+
const OLD_PC = 'This PC runs an older simcast. Update simcast on this PC and run "simcast pair" again.';
|
|
39
|
+
|
|
40
|
+
// An error with an HTTP status, and extra JSON fields for the body (`code`, ...).
|
|
41
|
+
// The server sends { error: message, ...body }; upgrades send the message in
|
|
42
|
+
// x-simcast-error.
|
|
43
|
+
export class HttpError extends Error {
|
|
44
|
+
constructor(status, message, body = {}) {
|
|
45
|
+
super(message);
|
|
46
|
+
this.status = status;
|
|
47
|
+
this.body = body;
|
|
48
|
+
if (body.code) this.code = body.code;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// ---- time (a seam for the rotation grace in tests) ---------------------------
|
|
53
|
+
|
|
54
|
+
let clock = () => Date.now();
|
|
55
|
+
export function setClock(fn) { clock = fn || (() => Date.now()); }
|
|
56
|
+
const now = () => clock();
|
|
57
|
+
const iso = (ms = now()) => new Date(ms).toISOString();
|
|
58
|
+
|
|
59
|
+
// ---- storage -----------------------------------------------------------------
|
|
60
|
+
|
|
61
|
+
export const hashToken = (token) => crypto.createHash('sha256').update(String(token)).digest('base64url');
|
|
62
|
+
|
|
63
|
+
function readJson(file) {
|
|
64
|
+
try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function cleanRecord(pc) {
|
|
68
|
+
return {
|
|
69
|
+
id: String(pc.id),
|
|
70
|
+
name: String(pc.name || 'another PC'),
|
|
71
|
+
via: 'code', // ponytail: the only way to pair since 0.8
|
|
72
|
+
tokenHash: pc.tokenHash || null,
|
|
73
|
+
prevTokenHash: pc.prevTokenHash || null,
|
|
74
|
+
prevValidUntil: pc.prevValidUntil || null,
|
|
75
|
+
tokenIssuedAt: pc.tokenIssuedAt || null,
|
|
76
|
+
pairedAt: pc.pairedAt || null,
|
|
77
|
+
lastSeenAt: pc.lastSeenAt || null,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// clients.json as it is on disk: { db }, `db` being { version, active, pcs }.
|
|
82
|
+
export function readDb() {
|
|
83
|
+
const raw = readJson(FILE);
|
|
84
|
+
if (raw && Array.isArray(raw.pcs)) {
|
|
85
|
+
const pcs = raw.pcs.filter((pc) => pc && typeof pc.id === 'string').map(cleanRecord).slice(0, MAX_PCS);
|
|
86
|
+
const active = pcs.some((pc) => pc.id === raw.active) ? raw.active : null;
|
|
87
|
+
return { db: { version: 1, active, pcs } };
|
|
88
|
+
}
|
|
89
|
+
return { db: { version: 1, active: null, pcs: [] } };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function writeFileAtomic(file, text) {
|
|
93
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
94
|
+
fs.writeFileSync(tmp, text, { mode: 0o600 });
|
|
95
|
+
try { fs.chmodSync(tmp, 0o600); } catch { /* not on Windows */ }
|
|
96
|
+
fs.renameSync(tmp, file);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function writeDb(d) {
|
|
100
|
+
fs.mkdirSync(agentHome, { recursive: true });
|
|
101
|
+
writeFileAtomic(FILE, JSON.stringify(d, null, 2));
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
let { db } = readDb();
|
|
105
|
+
|
|
106
|
+
let dirty = false;
|
|
107
|
+
let lastWrite = 0;
|
|
108
|
+
let touchTimer = null;
|
|
109
|
+
|
|
110
|
+
// A failed write (Windows refuses the rename while another process has the file
|
|
111
|
+
// open) is retried, so a pairing or a new token is never lost on disk; the error
|
|
112
|
+
// is logged once it has failed SAVE_RETRIES times in a row.
|
|
113
|
+
const SAVE_RETRIES = 20;
|
|
114
|
+
const SAVE_RETRY_MS = 50;
|
|
115
|
+
let saveFailures = 0;
|
|
116
|
+
let retryTimer = null;
|
|
117
|
+
function save() {
|
|
118
|
+
dirty = false;
|
|
119
|
+
lastWrite = now();
|
|
120
|
+
if (touchTimer) { clearTimeout(touchTimer); touchTimer = null; }
|
|
121
|
+
if (retryTimer) { clearTimeout(retryTimer); retryTimer = null; }
|
|
122
|
+
try {
|
|
123
|
+
writeDb(db);
|
|
124
|
+
saveFailures = 0;
|
|
125
|
+
} catch (err) {
|
|
126
|
+
saveFailures += 1;
|
|
127
|
+
if (saveFailures === SAVE_RETRIES) console.error(`Could not write ${FILE}: ${err.message}`);
|
|
128
|
+
dirty = true; // the exit hook tries once more
|
|
129
|
+
if (saveFailures < SAVE_RETRIES * 10) {
|
|
130
|
+
retryTimer = setTimeout(() => { retryTimer = null; save(); }, SAVE_RETRY_MS);
|
|
131
|
+
retryTimer.unref();
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// lastSeenAt and name changes: kept in memory, written at most once a minute.
|
|
137
|
+
function saveSoon() {
|
|
138
|
+
dirty = true;
|
|
139
|
+
if (touchTimer) return;
|
|
140
|
+
const wait = Math.max(0, lastWrite + TOUCH_MS - now());
|
|
141
|
+
if (wait === 0) return save();
|
|
142
|
+
touchTimer = setTimeout(() => { touchTimer = null; if (dirty) save(); }, wait);
|
|
143
|
+
touchTimer.unref();
|
|
144
|
+
}
|
|
145
|
+
process.once('exit', () => { if (dirty) save(); });
|
|
146
|
+
|
|
147
|
+
const find = (id) => db.pcs.find((pc) => pc.id === id) || null;
|
|
148
|
+
const activeRecord = () => find(db.active);
|
|
149
|
+
|
|
150
|
+
// Set by the server at start: only the agent writes the status file (a
|
|
151
|
+
// simcast-host command that edits clients.json must not).
|
|
152
|
+
let serving = false;
|
|
153
|
+
export function startServing() {
|
|
154
|
+
serving = true;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// ---- connections, per PC -----------------------------------------------------
|
|
158
|
+
|
|
159
|
+
// id -> { sessions: Set<{ ws, hb, release, via }>, sockets: Map<socket, via> }
|
|
160
|
+
const conns = new Map();
|
|
161
|
+
function connsOf(id) {
|
|
162
|
+
let c = conns.get(id);
|
|
163
|
+
if (!c) conns.set(id, c = { sessions: new Set(), sockets: new Map() });
|
|
164
|
+
return c;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// Whether a PC (the active one when `id` is left out) is connected: a /session
|
|
168
|
+
// open here, or its /tunnel control connection up (tunnel.portsFor).
|
|
169
|
+
export function isConnected(id = db.active) {
|
|
170
|
+
if (!id) return false;
|
|
171
|
+
if (conns.get(id)?.sessions.size) return true;
|
|
172
|
+
try { return Boolean(tunnel.portsFor(id)?.connected); } catch { return false; }
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// The status file's `connected`: the active PC's name while it is connected.
|
|
176
|
+
export function reportConnected() {
|
|
177
|
+
if (!serving) return;
|
|
178
|
+
writeStatus({ connected: isConnected() ? activeRecord()?.name || null : null });
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// Closes a PC's /session and /tunnel with `code`, and destroys its other
|
|
182
|
+
// sockets a moment later (so the close message arrives first).
|
|
183
|
+
function disconnect(id, code, reason) {
|
|
184
|
+
const c = conns.get(id);
|
|
185
|
+
const sessions = c ? [...c.sessions] : [];
|
|
186
|
+
const sockets = c ? [...c.sockets.keys()] : [];
|
|
187
|
+
if (c) {
|
|
188
|
+
for (const s of sessions) c.sessions.delete(s);
|
|
189
|
+
for (const s of sockets) { c.sockets.delete(s); owner.delete(s); }
|
|
190
|
+
}
|
|
191
|
+
for (const s of sessions) {
|
|
192
|
+
try { s.ws.close(code, reason.slice(0, 120)); } catch { /* closing */ }
|
|
193
|
+
}
|
|
194
|
+
try { tunnel.closeFor(id, code, reason.slice(0, 120)); } catch { /* no tunnel */ }
|
|
195
|
+
// A socket another PC used in the meantime (a keep-alive connection) is now its.
|
|
196
|
+
if (sockets.length) setTimeout(() => { for (const socket of sockets) if (!owner.has(socket)) socket.destroy(); }, 300).unref();
|
|
197
|
+
reportConnected();
|
|
198
|
+
return sessions.length + sockets.length;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// Remember a connection, so it can be cut when its PC goes away, is replaced
|
|
202
|
+
// or is unpaired. `clientId` is the PC (the active one when left out); `via`
|
|
203
|
+
// is how it authenticated (always "pc" since 0.8). A
|
|
204
|
+
// keep-alive socket belongs to the PC whose request came on it last.
|
|
205
|
+
const owner = new WeakMap(); // socket -> clientId
|
|
206
|
+
export function track(socket, clientId = db.active, via = 'pc') {
|
|
207
|
+
if (!clientId) return;
|
|
208
|
+
const prev = owner.get(socket);
|
|
209
|
+
if (prev !== undefined && prev !== clientId) conns.get(prev)?.sockets.delete(socket);
|
|
210
|
+
const c = connsOf(clientId);
|
|
211
|
+
c.sockets.set(socket, via);
|
|
212
|
+
if (prev === undefined && !socket.destroyed) {
|
|
213
|
+
socket.once('close', () => {
|
|
214
|
+
conns.get(owner.get(socket))?.sockets.delete(socket);
|
|
215
|
+
owner.delete(socket);
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
owner.set(socket, clientId);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// Destroys every socket of one PC (its session is gone).
|
|
222
|
+
function dropAll(id) {
|
|
223
|
+
const c = conns.get(id);
|
|
224
|
+
if (!c) return;
|
|
225
|
+
for (const socket of c.sockets.keys()) { owner.delete(socket); socket.destroy(); }
|
|
226
|
+
c.sockets.clear();
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// `protocol` is the one negotiated with this PC (negotiateProtocol in common.js),
|
|
230
|
+
// reported in the hello. `via` is how it authenticated.
|
|
231
|
+
export function addSession(ws, client, { protocol = PROTOCOL, via = client.via || 'pc' } = {}) {
|
|
232
|
+
const c = connsOf(client.id);
|
|
233
|
+
// Keep the Mac awake while the PC is connected; released once, whichever way the session ends.
|
|
234
|
+
const entry = { ws, hb: null, release: awake.hold('pc'), via };
|
|
235
|
+
c.sessions.add(entry);
|
|
236
|
+
reportConnected();
|
|
237
|
+
log(`${client.name} connected`);
|
|
238
|
+
const lost = (why) => {
|
|
239
|
+
entry.release();
|
|
240
|
+
if (!c.sessions.delete(entry)) return;
|
|
241
|
+
reportConnected();
|
|
242
|
+
// If no other control connection from the PC is still answering (another
|
|
243
|
+
// session, or its tunnel), the PC is gone: end its streams, live views and
|
|
244
|
+
// log tails so nothing keeps running for it.
|
|
245
|
+
const others = [...c.sessions].some((s) => Date.now() - s.hb.lastSeen() < HEARTBEAT_TIMEOUT_MS)
|
|
246
|
+
|| isConnected(client.id);
|
|
247
|
+
log(`${client.name} ${why}${others ? '' : '; closing its connections'}`);
|
|
248
|
+
if (!others) dropAll(client.id);
|
|
249
|
+
};
|
|
250
|
+
entry.hb = heartbeat(ws, { onDead: () => lost('stopped answering') });
|
|
251
|
+
ws.on('close', (code) => {
|
|
252
|
+
entry.release();
|
|
253
|
+
// 1006: the connection ended without a close handshake (network loss, crash).
|
|
254
|
+
if (code === 1006) lost('dropped the connection');
|
|
255
|
+
else if (c.sessions.delete(entry)) {
|
|
256
|
+
reportConnected();
|
|
257
|
+
log(`${client.name} disconnected`);
|
|
258
|
+
}
|
|
259
|
+
});
|
|
260
|
+
ws.send(JSON.stringify({ t: 'hello', version: VERSION, protocol }));
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// Agent shutdown: 1001 to every session.
|
|
264
|
+
export function stopAll() {
|
|
265
|
+
for (const c of conns.values()) {
|
|
266
|
+
for (const s of c.sessions) {
|
|
267
|
+
try { s.ws.close(1001, 'The agent is stopping'); } catch { /* closing */ }
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// ---- identity and authentication ----------------------------------------------
|
|
273
|
+
|
|
274
|
+
// { id, name } from the x-simcast-client headers, or null when the id is missing or malformed.
|
|
275
|
+
export function clientOf(req) {
|
|
276
|
+
const id = String(req.headers['x-simcast-client'] || '');
|
|
277
|
+
const name = String(req.headers['x-simcast-client-name'] || '').replace(/[^\x20-\x7e]/g, '').slice(0, 80) || 'another PC';
|
|
278
|
+
return /^[A-Za-z0-9_-]{8,64}$/.test(id) ? { id, name } : null;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function bearer(req) {
|
|
282
|
+
const m = /^Bearer (\S+)$/.exec(String(req.headers.authorization || ''));
|
|
283
|
+
return m ? m[1] : null;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function sameHash(a, b) {
|
|
287
|
+
if (!a || !b) return false;
|
|
288
|
+
const x = Buffer.from(a);
|
|
289
|
+
const y = Buffer.from(b);
|
|
290
|
+
return x.length === y.length && crypto.timingSafeEqual(x, y);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// The record whose own token (or, during its grace, previous token) this is.
|
|
294
|
+
function recordForToken(token) {
|
|
295
|
+
const h = hashToken(token);
|
|
296
|
+
const t = now();
|
|
297
|
+
let found = null;
|
|
298
|
+
for (const pc of db.pcs) {
|
|
299
|
+
// Every record is checked, so the time doesn't say which one matched.
|
|
300
|
+
const cur = sameHash(pc.tokenHash, h);
|
|
301
|
+
const prev = sameHash(pc.prevTokenHash, h) && pc.prevValidUntil && Date.parse(pc.prevValidUntil) > t;
|
|
302
|
+
if ((cur || prev) && !found) found = pc;
|
|
303
|
+
}
|
|
304
|
+
return found;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// Steps 4 to 6 of the order of checks (docs/protocol.md): the bearer token,
|
|
308
|
+
// then the client id. Returns { client: { id, name, via }, record, via }, where
|
|
309
|
+
// `via` is "pc" (the PC's own token, the only kind).
|
|
310
|
+
// Throws an HttpError (401, or 403 other-client).
|
|
311
|
+
export function authenticate(req) {
|
|
312
|
+
const token = bearer(req);
|
|
313
|
+
const record = token ? recordForToken(token) : null;
|
|
314
|
+
if (!record) throw new HttpError(401, NOT_PAIRED);
|
|
315
|
+
const via = 'pc';
|
|
316
|
+
const header = clientOf(req);
|
|
317
|
+
if (!header) throw new HttpError(403, OLD_PC, { code: 'other-client' });
|
|
318
|
+
if (header.id !== record.id) throw new HttpError(401, OTHER_PCS_TOKEN);
|
|
319
|
+
touch(record, header.name);
|
|
320
|
+
return { client: { ...header, via }, record, via };
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function touch(record, name) {
|
|
324
|
+
record.lastSeenAt = iso();
|
|
325
|
+
if (name && name !== 'another PC' && name !== record.name) record.name = name;
|
|
326
|
+
saveSoon();
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// ---- records -------------------------------------------------------------------
|
|
330
|
+
|
|
331
|
+
function tooMany() {
|
|
332
|
+
return new HttpError(403, `This Mac already has ${MAX_PCS} paired PCs. Unpair one on the Mac first: simcast-host pcs, then simcast-host unpair <name>.`, { code: 'too-many-pcs' });
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// Whether `id` could get a record (it has one, or there is room).
|
|
336
|
+
export const canPair = (id) => Boolean(find(id)) || db.pcs.length < MAX_PCS;
|
|
337
|
+
|
|
338
|
+
function ensureRecord(client) {
|
|
339
|
+
let rec = find(client.id);
|
|
340
|
+
if (rec) {
|
|
341
|
+
if (client.name && client.name !== 'another PC') rec.name = client.name;
|
|
342
|
+
return rec;
|
|
343
|
+
}
|
|
344
|
+
if (db.pcs.length >= MAX_PCS) throw tooMany();
|
|
345
|
+
rec = cleanRecord({ id: client.id, name: client.name, pairedAt: iso(), lastSeenAt: iso() });
|
|
346
|
+
db.pcs.push(rec);
|
|
347
|
+
return rec;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// Makes `rec` the active PC. The PC it replaces gets 4003 on its /session and
|
|
351
|
+
// /tunnel and its other sockets are destroyed (when it was idle, that is only
|
|
352
|
+
// stray sockets: live views, streams).
|
|
353
|
+
function activate(rec, how) {
|
|
354
|
+
const previous = activeRecord();
|
|
355
|
+
db.active = rec.id;
|
|
356
|
+
if (previous && previous.id !== rec.id) {
|
|
357
|
+
log(`${how} ${rec.name}; disconnecting ${previous.name}`);
|
|
358
|
+
disconnect(previous.id, 4003, `This Mac was paired with ${rec.name}`);
|
|
359
|
+
} else if (!previous) {
|
|
360
|
+
log(`${how} ${rec.name}`);
|
|
361
|
+
}
|
|
362
|
+
reportConnected();
|
|
363
|
+
return previous && previous.id !== rec.id ? previous : null;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
// The active PC: { id, name, pairedAt, ... } or null.
|
|
367
|
+
export const pairedClient = () => activeRecord();
|
|
368
|
+
|
|
369
|
+
// The name of the PC that keeps `id` from becoming the active one right now:
|
|
370
|
+
// the active PC, when it is another PC and connected. Else null.
|
|
371
|
+
export function inUseBy(id) {
|
|
372
|
+
const active = activeRecord();
|
|
373
|
+
return active && active.id !== id && isConnected(active.id) ? active.name : null;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
function inUse(name) {
|
|
377
|
+
return new HttpError(403, `This Mac is in use by ${name} right now. Run "simcast pair --force" on this PC to take it over.`, { code: 'in-use', by: name });
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// Step 8: lets `client` ({ id, name, via }) in, or throws an HttpError.
|
|
381
|
+
// - No active PC: the client becomes it (a record is made if needed).
|
|
382
|
+
// - The active PC goes through.
|
|
383
|
+
// - Another paired PC becomes the active one if the active PC isn't connected;
|
|
384
|
+
// else 403 in-use.
|
|
385
|
+
export function admit(client) {
|
|
386
|
+
const active = activeRecord();
|
|
387
|
+
if (!active) {
|
|
388
|
+
activate(ensureRecord(client), 'paired with');
|
|
389
|
+
save();
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
if (active.id === client.id) return;
|
|
393
|
+
if (isConnected(active.id)) throw inUse(active.name);
|
|
394
|
+
activate(ensureRecord(client), 'switched to');
|
|
395
|
+
save();
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
// POST /pair: makes `client` the active PC. 409 in-use while another PC is
|
|
399
|
+
// connected, unless `force`. Returns { previous: name | null }.
|
|
400
|
+
export function claim(client, { force = false } = {}) {
|
|
401
|
+
const by = inUseBy(client.id);
|
|
402
|
+
if (by && !force) {
|
|
403
|
+
throw new HttpError(409, `This Mac is in use by ${by} right now. Pair again with --force to take it over.`, { code: 'in-use', by });
|
|
404
|
+
}
|
|
405
|
+
const rec = ensureRecord(client);
|
|
406
|
+
const previous = activate(rec, 'paired with');
|
|
407
|
+
save();
|
|
408
|
+
return { previous: previous?.name || null };
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
// A new own token for `client` (made the record's only token). Returns { token, issuedAt }.
|
|
412
|
+
export function issueToken(client) {
|
|
413
|
+
const rec = ensureRecord(client);
|
|
414
|
+
const token = newToken();
|
|
415
|
+
rec.tokenHash = hashToken(token);
|
|
416
|
+
rec.prevTokenHash = null;
|
|
417
|
+
rec.prevValidUntil = null;
|
|
418
|
+
rec.tokenIssuedAt = iso();
|
|
419
|
+
save();
|
|
420
|
+
return { token, issuedAt: rec.tokenIssuedAt };
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// Code pairing, once the code was right: a new token, and `client` becomes the
|
|
424
|
+
// active PC (the one it replaces gets 4003). { token, issuedAt, previous }.
|
|
425
|
+
export function pairWithCode(client) {
|
|
426
|
+
if (!canPair(client.id)) throw tooMany();
|
|
427
|
+
const rec = ensureRecord(client);
|
|
428
|
+
rec.pairedAt = iso();
|
|
429
|
+
const issued = issueToken(client);
|
|
430
|
+
const previous = activate(rec, 'paired with');
|
|
431
|
+
save();
|
|
432
|
+
return { ...issued, previous: previous?.name || null };
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
// POST /token/rotate: a new token, and the old one stays valid for 7 days.
|
|
436
|
+
// Returns { token, issuedAt }.
|
|
437
|
+
export function rotate(client) {
|
|
438
|
+
const rec = find(client.id);
|
|
439
|
+
const token = newToken();
|
|
440
|
+
rec.prevTokenHash = rec.tokenHash;
|
|
441
|
+
rec.prevValidUntil = iso(now() + GRACE_MS);
|
|
442
|
+
rec.tokenHash = hashToken(token);
|
|
443
|
+
rec.tokenIssuedAt = iso();
|
|
444
|
+
save();
|
|
445
|
+
log(`${rec.name} rotated its token`);
|
|
446
|
+
return { token, issuedAt: rec.tokenIssuedAt };
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
// Removes a PC: its record and token go, its connections get 4001. Returns the
|
|
450
|
+
// removed record, or null when there was none.
|
|
451
|
+
export function unpair(id, why = 'unpaired') {
|
|
452
|
+
const rec = find(id);
|
|
453
|
+
if (rec) {
|
|
454
|
+
db.pcs = db.pcs.filter((pc) => pc.id !== id);
|
|
455
|
+
if (db.active === id) db.active = null;
|
|
456
|
+
save();
|
|
457
|
+
log(`${rec.name} ${why}`);
|
|
458
|
+
}
|
|
459
|
+
disconnect(id, 4001, UNPAIRED_REASON);
|
|
460
|
+
return rec;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
// The paired PCs, without their hashes: [{ id, name, via, pairedAt, lastSeenAt,
|
|
464
|
+
// tokenIssuedAt, ownToken, active, connected }].
|
|
465
|
+
export function list() {
|
|
466
|
+
return db.pcs.map((pc) => publicRecord(pc, { active: pc.id === db.active, connected: isConnected(pc.id) }));
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
export function publicRecord(pc, extra = {}) {
|
|
470
|
+
return {
|
|
471
|
+
id: pc.id, name: pc.name, via: pc.via, pairedAt: pc.pairedAt, lastSeenAt: pc.lastSeenAt,
|
|
472
|
+
tokenIssuedAt: pc.tokenIssuedAt, ownToken: Boolean(pc.tokenHash), ...extra,
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import readline from 'node:readline';
|
|
6
|
+
import { agentConfigFile, readAgentConfigSafe } from './state.js';
|
|
7
|
+
|
|
8
|
+
// ':' on the Mac. Using the platform's delimiter keeps Windows drive letters
|
|
9
|
+
// ("C:\...") intact when the tests run there.
|
|
10
|
+
const SEP = path.delimiter;
|
|
11
|
+
const isWin = process.platform === 'win32';
|
|
12
|
+
|
|
13
|
+
function splitPath(value) {
|
|
14
|
+
if (Array.isArray(value)) return value.map(String);
|
|
15
|
+
return typeof value === 'string' ? value.split(SEP) : [];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// agent.json's extraPath, parsed again only when the file changes: agentEnv()
|
|
19
|
+
// runs for every tool the agent spawns, so a stat per call, not a parse.
|
|
20
|
+
let extraCache = { key: null, value: [] };
|
|
21
|
+
function configExtraPath() {
|
|
22
|
+
let key;
|
|
23
|
+
try {
|
|
24
|
+
const st = fs.statSync(agentConfigFile);
|
|
25
|
+
key = `${st.mtimeMs}:${st.size}`;
|
|
26
|
+
} catch {
|
|
27
|
+
key = 'missing';
|
|
28
|
+
}
|
|
29
|
+
if (key !== extraCache.key) extraCache = { key, value: key === 'missing' ? [] : splitPath(readAgentConfigSafe().extraPath) };
|
|
30
|
+
return extraCache.value;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// LaunchAgents start with a bare PATH and no locale; CocoaPods needs UTF-8.
|
|
34
|
+
// Order: SIMCAST_EXTRA_PATH, agent.json extraPath (custom toolchains such as
|
|
35
|
+
// rbenv/asdf Ruby for CocoaPods), Homebrew, this Node, then the inherited PATH.
|
|
36
|
+
export function agentEnv(extra = {}) {
|
|
37
|
+
const env = { ...process.env };
|
|
38
|
+
// Windows env keys are case-insensitive; drop "Path" so only PATH is passed on.
|
|
39
|
+
let inherited = process.env.PATH;
|
|
40
|
+
if (isWin) {
|
|
41
|
+
for (const key of Object.keys(env)) {
|
|
42
|
+
if (key.toUpperCase() === 'PATH') {
|
|
43
|
+
inherited ??= env[key];
|
|
44
|
+
delete env[key];
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
const entries = [
|
|
49
|
+
...splitPath(process.env.SIMCAST_EXTRA_PATH),
|
|
50
|
+
...configExtraPath(),
|
|
51
|
+
'/opt/homebrew/bin', '/usr/local/bin', path.dirname(process.execPath),
|
|
52
|
+
...splitPath(inherited || '/usr/bin:/bin:/usr/sbin:/sbin'),
|
|
53
|
+
];
|
|
54
|
+
const seen = new Set();
|
|
55
|
+
const dirs = [];
|
|
56
|
+
for (const dir of entries) {
|
|
57
|
+
const key = isWin ? dir.toLowerCase() : dir;
|
|
58
|
+
if (!dir || seen.has(key)) continue;
|
|
59
|
+
seen.add(key);
|
|
60
|
+
dirs.push(dir);
|
|
61
|
+
}
|
|
62
|
+
return {
|
|
63
|
+
...env,
|
|
64
|
+
PATH: dirs.join(SEP),
|
|
65
|
+
LANG: 'en_US.UTF-8',
|
|
66
|
+
LC_ALL: 'en_US.UTF-8',
|
|
67
|
+
...extra,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Test hook: with SIMCAST_FAKE_TOOLS set to a folder, a command that has a
|
|
72
|
+
// <folder>/<cmd>.js script runs that script with Node instead (see test/fakes/).
|
|
73
|
+
// Unset, nothing changes.
|
|
74
|
+
function fakeScript(cmd) {
|
|
75
|
+
const dir = process.env.SIMCAST_FAKE_TOOLS;
|
|
76
|
+
if (!dir) return null;
|
|
77
|
+
const script = path.join(dir, `${path.basename(cmd)}.js`);
|
|
78
|
+
return fs.existsSync(script) ? script : null;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function fakeTool(cmd, args) {
|
|
82
|
+
const script = fakeScript(cmd);
|
|
83
|
+
return script ? [process.execPath, [script, ...args]] : [cmd, args];
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// child_process.spawn with the fake-tools hook and agentEnv() as the default env.
|
|
87
|
+
export function spawnTool(cmd, args = [], opts = {}) {
|
|
88
|
+
return spawn(...fakeTool(cmd, args), { ...opts, env: opts.env || agentEnv() });
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// For fixes that may prompt (sudo, xcodebuild -license): the terminal is the
|
|
92
|
+
// child's. Resolves with the exit code (128 + signal number when killed).
|
|
93
|
+
export function runInteractive(cmd, args = [], { env, cwd } = {}) {
|
|
94
|
+
return new Promise((resolve, reject) => {
|
|
95
|
+
const child = spawnTool(cmd, args, { env, cwd, stdio: 'inherit' });
|
|
96
|
+
child.on('error', reject);
|
|
97
|
+
child.on('close', (code, signal) => {
|
|
98
|
+
resolve(code ?? 128 + (os.constants.signals[signal] || 0));
|
|
99
|
+
});
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function isExecutable(file) {
|
|
104
|
+
try {
|
|
105
|
+
if (!fs.statSync(file).isFile()) return false;
|
|
106
|
+
if (!isWin) fs.accessSync(file, fs.constants.X_OK);
|
|
107
|
+
return true;
|
|
108
|
+
} catch {
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Like `command -v`, without a shell: the fake script when one exists, else the
|
|
114
|
+
// first executable match on agentEnv().PATH. On Windows the bare name is tried
|
|
115
|
+
// before each PATHEXT extension.
|
|
116
|
+
export function which(cmd) {
|
|
117
|
+
if (!cmd) return null;
|
|
118
|
+
const fake = fakeScript(cmd);
|
|
119
|
+
if (fake) return path.resolve(fake);
|
|
120
|
+
const exts = isWin ? ['', ...(process.env.PATHEXT || '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean)] : [''];
|
|
121
|
+
if (cmd.includes('/') || (isWin && cmd.includes('\\'))) {
|
|
122
|
+
for (const ext of exts) if (isExecutable(cmd + ext)) return path.resolve(cmd + ext);
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
for (const dir of agentEnv().PATH.split(SEP)) {
|
|
126
|
+
if (!dir) continue;
|
|
127
|
+
for (const ext of exts) {
|
|
128
|
+
const file = path.resolve(dir, cmd + ext);
|
|
129
|
+
if (isExecutable(file)) return file;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function run(cmd, args, { cwd, env, onLine, capture = false } = {}) {
|
|
136
|
+
return new Promise((resolve, reject) => {
|
|
137
|
+
const child = spawnTool(cmd, args, { cwd, env, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
138
|
+
const out = [];
|
|
139
|
+
const tail = [];
|
|
140
|
+
const lines = (stream, name) => {
|
|
141
|
+
readline.createInterface({ input: stream }).on('line', (line) => {
|
|
142
|
+
tail.push(line);
|
|
143
|
+
if (tail.length > 60) tail.shift();
|
|
144
|
+
onLine?.(line, name);
|
|
145
|
+
});
|
|
146
|
+
};
|
|
147
|
+
if (capture) child.stdout.on('data', (d) => out.push(d));
|
|
148
|
+
else lines(child.stdout, 'stdout');
|
|
149
|
+
lines(child.stderr, 'stderr');
|
|
150
|
+
child.on('error', reject);
|
|
151
|
+
child.on('close', (code) => resolve({ code, stdout: Buffer.concat(out), tail }));
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export async function runOk(cmd, args, opts = {}) {
|
|
156
|
+
const res = await run(cmd, args, opts);
|
|
157
|
+
if (res.code !== 0) {
|
|
158
|
+
const err = new Error(`${[cmd, ...args.slice(0, 2)].join(' ')} failed with exit code ${res.code}`);
|
|
159
|
+
err.tail = res.tail.slice(-30);
|
|
160
|
+
throw err;
|
|
161
|
+
}
|
|
162
|
+
return res;
|
|
163
|
+
}
|