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.
@@ -0,0 +1,87 @@
1
+ // The Mac-local admin API, /admin/* (docs/protocol.md, "Mac-local admin API";
2
+ // not part of the client protocol). Used by `simcast-host pair`, `pcs`,
3
+ // `unpair` while the agent runs.
4
+ // - The socket must come from 127.0.0.1 or ::1 (else 403), and
5
+ // `authorization: Bearer <adminToken>` (agent.json) must match (else 401).
6
+ // - POST /admin/pairing { seconds? } → { code, expiresAt, attemptsLeft }
7
+ // - GET /admin/pairing → pairing.status()
8
+ // - DELETE /admin/pairing → closes the window
9
+ // - GET /admin/pcs → { pcs: [{ ..., active, connected, tunnel }] }
10
+ // - DELETE /admin/pcs/:id → unpairs one PC (4001, sockets destroyed, tunnel closed)
11
+ import crypto from 'node:crypto';
12
+ import * as clients from './clients.js';
13
+ import * as pairing from './pairing.js';
14
+ import * as tunnel from './tunnel.js';
15
+
16
+ const LOOPBACK = new Set(['127.0.0.1', '::1', '::ffff:127.0.0.1']);
17
+
18
+ // Whether the request's socket comes from this Mac.
19
+ export function isLoopback(req) {
20
+ return LOOPBACK.has(req.socket?.remoteAddress);
21
+ }
22
+
23
+ function send(res, status, body) {
24
+ res.writeHead(status, { 'content-type': 'application/json' });
25
+ res.end(JSON.stringify(body));
26
+ }
27
+
28
+ function sameSecret(given, expected) {
29
+ if (!given || !expected) return false;
30
+ const h = (v) => crypto.createHash('sha256').update(String(v)).digest();
31
+ return crypto.timingSafeEqual(h(given), h(expected));
32
+ }
33
+
34
+ async function readBody(req, limit = 64 * 1024) {
35
+ const chunks = [];
36
+ let size = 0;
37
+ for await (const chunk of req) {
38
+ size += chunk.length;
39
+ if (size > limit) return { tooLarge: true };
40
+ chunks.push(chunk);
41
+ }
42
+ try {
43
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
44
+ return { body: body && typeof body === 'object' ? body : {} };
45
+ } catch {
46
+ return { bad: true };
47
+ }
48
+ }
49
+
50
+ // The PCs for `pcs` and `status`: each with `active`, `connected` and its tunnel.
51
+ export function pcsList() {
52
+ return clients.list().map((pc) => {
53
+ let t = { connected: false, ports: [] };
54
+ try { t = tunnel.portsFor(pc.id) || t; } catch { /* no tunnel */ }
55
+ return { ...pc, tunnel: t };
56
+ });
57
+ }
58
+
59
+ // Handles one /admin/* request: `url` is the parsed URL, `adminToken` the
60
+ // agent.json admin token. Writes the response itself.
61
+ export async function handle(req, res, { url = new URL(req.url, 'http://agent'), adminToken } = {}) {
62
+ if (!isLoopback(req)) return send(res, 403, { error: 'The admin API only answers on this Mac.' });
63
+ const m = /^Bearer (\S+)$/.exec(String(req.headers.authorization || ''));
64
+ if (!sameSecret(m?.[1], adminToken)) return send(res, 401, { error: 'Bad or missing admin token (agent.json adminToken).' });
65
+
66
+ const route = `${req.method} ${url.pathname}`;
67
+ try {
68
+ if (route === 'POST /admin/pairing') {
69
+ const { body, tooLarge, bad } = await readBody(req);
70
+ if (tooLarge) return send(res, 413, { error: 'Request body too large' });
71
+ if (bad) return send(res, 400, { error: 'Invalid JSON body' });
72
+ return send(res, 200, pairing.open(body.seconds));
73
+ }
74
+ if (route === 'GET /admin/pairing') return send(res, 200, pairing.status());
75
+ if (route === 'DELETE /admin/pairing') return send(res, 200, { ok: true, cancelled: pairing.cancel() });
76
+ if (route === 'GET /admin/pcs') return send(res, 200, { pcs: pcsList() });
77
+ const pc = /^\/admin\/pcs\/([A-Za-z0-9_-]{1,64})$/.exec(url.pathname);
78
+ if (req.method === 'DELETE' && pc) {
79
+ const removed = clients.unpair(pc[1], 'was unpaired on the Mac');
80
+ if (!removed) return send(res, 404, { error: `No paired PC has the id ${pc[1]}.` });
81
+ return send(res, 200, { ok: true, pc: clients.publicRecord(removed) });
82
+ }
83
+ return send(res, 404, { error: `No route ${route}` });
84
+ } catch (err) {
85
+ return send(res, err.status || 500, { error: err.message, ...(err.body || {}) });
86
+ }
87
+ }
@@ -0,0 +1,136 @@
1
+ // Keeps the Mac from idle-sleeping while a PC is connected or a sync or build
2
+ // runs: one `caffeinate -i -w <agent pid>` for all holds. After the last hold
3
+ // ends it stays a while (SIMCAST_AWAKE_GRACE_MS, default 2 minutes), so a PC
4
+ // that reconnects or runs again soon doesn't find the Mac asleep. caffeinate
5
+ // exits on its own if the agent dies (-w).
6
+ import { spawnTool } from './exec.js';
7
+ import { isMac } from './paths.js';
8
+ import { writeStatus } from './runtime.js';
9
+
10
+ let lastLog = null;
11
+ // Only changes: a sync right after another (manifest, then upload) logs once.
12
+ const log = (msg) => {
13
+ if (msg === lastLog) return;
14
+ lastLog = msg;
15
+ console.log(`[${new Date().toISOString()}] awake: ${msg}`);
16
+ };
17
+
18
+ const holds = new Map(); // reason -> number of active holds
19
+ let since = null; // when the current hold period began
20
+ let child = null;
21
+ let graceTimer = null;
22
+ let warned = false;
23
+
24
+ const graceMs = () => {
25
+ const ms = Number(process.env.SIMCAST_AWAKE_GRACE_MS);
26
+ return Number.isFinite(ms) && ms >= 0 ? ms : 120_000;
27
+ };
28
+
29
+ export function awakeStatus() {
30
+ return { held: holds.size > 0, reasons: [...holds.keys()], since };
31
+ }
32
+
33
+ const report = () => writeStatus({ awake: awakeStatus() });
34
+
35
+ function startCaffeinate() {
36
+ if (child) return;
37
+ let proc;
38
+ try {
39
+ proc = spawnTool('caffeinate', ['-i', '-w', String(process.pid)], { stdio: 'ignore' });
40
+ } catch (err) {
41
+ failed(err);
42
+ return;
43
+ }
44
+ child = proc;
45
+ proc.unref();
46
+ proc.on('error', (err) => {
47
+ if (child === proc) child = null;
48
+ failed(err);
49
+ });
50
+ proc.on('exit', () => {
51
+ if (child !== proc) return; // stopped on purpose, or already replaced
52
+ child = null;
53
+ if (holds.size) respawnSoon();
54
+ });
55
+ }
56
+
57
+ // caffeinate died (killed by hand, say) while the Mac should stay awake: start
58
+ // another after SIMCAST_AWAKE_RESPAWN_MS (default 5 s), so one that keeps
59
+ // dying restarts at most that often. One log line per burst of respawns.
60
+ const respawnMs = () => {
61
+ const ms = Number(process.env.SIMCAST_AWAKE_RESPAWN_MS);
62
+ return Number.isFinite(ms) && ms >= 0 ? ms : 5_000;
63
+ };
64
+ let respawnTimer = null;
65
+ let lastRespawn = 0;
66
+ let respawnLogged = false;
67
+
68
+ function respawnSoon() {
69
+ if (respawnTimer) return;
70
+ // A caffeinate that lived a while since the last respawn starts a new burst.
71
+ if (Date.now() - lastRespawn > 2 * respawnMs() + 1000) respawnLogged = false;
72
+ if (!respawnLogged) {
73
+ respawnLogged = true;
74
+ console.log(`[${new Date().toISOString()}] awake: caffeinate exited while the Mac should stay awake; starting it again`);
75
+ }
76
+ respawnTimer = setTimeout(() => {
77
+ respawnTimer = null;
78
+ if (!holds.size || child) return;
79
+ lastRespawn = Date.now();
80
+ startCaffeinate();
81
+ }, respawnMs());
82
+ respawnTimer.unref();
83
+ }
84
+
85
+ function failed(err) {
86
+ if (warned) return;
87
+ warned = true;
88
+ log(`could not start caffeinate, so the Mac may sleep while in use: ${err.message}`);
89
+ }
90
+
91
+ function stopCaffeinate() {
92
+ graceTimer = null;
93
+ if (holds.size) return;
94
+ if (child) {
95
+ try { child.kill('SIGTERM'); } catch { /* already gone */ }
96
+ child = null;
97
+ }
98
+ log('the Mac may sleep again');
99
+ }
100
+
101
+ // Returns release(); calling it more than once does nothing.
102
+ export function hold(reason) {
103
+ if (!isMac()) return () => {};
104
+ const fresh = !holds.has(reason);
105
+ holds.set(reason, (holds.get(reason) || 0) + 1);
106
+ if (graceTimer) {
107
+ clearTimeout(graceTimer);
108
+ graceTimer = null;
109
+ }
110
+ if (!since) since = new Date().toISOString();
111
+ startCaffeinate();
112
+ if (fresh) {
113
+ log(`keeping the Mac awake: ${awakeStatus().reasons.join(', ')}`);
114
+ report();
115
+ }
116
+
117
+ let released = false;
118
+ return () => {
119
+ if (released) return;
120
+ released = true;
121
+ const n = holds.get(reason) - 1;
122
+ if (n > 0) {
123
+ holds.set(reason, n);
124
+ return;
125
+ }
126
+ holds.delete(reason);
127
+ if (holds.size) {
128
+ log(`keeping the Mac awake: ${awakeStatus().reasons.join(', ')}`);
129
+ } else {
130
+ since = null;
131
+ graceTimer = setTimeout(stopCaffeinate, graceMs());
132
+ graceTimer.unref();
133
+ }
134
+ report();
135
+ };
136
+ }
@@ -0,0 +1,172 @@
1
+ // Bonjour advertising (docs/protocol.md, "Bonjour"): after listen, the agent
2
+ // runs
3
+ // dns-sd -R "<macName>" _simcast._tcp local <port> id=<agentId> name=<macName> proto=2 port=<port> ver=<VERSION>
4
+ // through spawnTool, logs "Name Registered" / "Name Conflict" and writes
5
+ // bonjour: { state, name } to the status file, restarts it with a backoff
6
+ // (1 s up to 30 s) if it exits, and kills it on SIGTERM, SIGINT and SIGHUP
7
+ // (server.js calls stop(); an exit hook here covers the rest).
8
+ // Off with agent.json `bonjour: false` or SIMCAST_BONJOUR=0.
9
+ //
10
+ // state: "starting" (the first dns-sd runs, nothing registered yet),
11
+ // "registered", "failed" (it exited, couldn't start, or the name was taken; it
12
+ // stays "failed" through the retries until a registration succeeds) or "off".
13
+ import readline from 'node:readline';
14
+ import { PROTOCOL, VERSION } from '../common.js';
15
+ import { spawnTool } from './exec.js';
16
+ import { computerName } from './macinfo.js';
17
+ import { writeStatus } from './runtime.js';
18
+ import { readAgentConfigSafe } from './state.js';
19
+
20
+ export const SERVICE_TYPE = '_simcast._tcp';
21
+ export const BACKOFF_MIN_MS = 1000;
22
+ export const BACKOFF_MAX_MS = 30_000;
23
+
24
+ const log = (msg) => console.log(`[${new Date().toISOString()}] bonjour: ${msg}`);
25
+
26
+ let run = null; // { port, agentId, macName, child, timer, backoff, stopped }
27
+ let current = { state: 'off', name: null };
28
+ let exitHooked = false;
29
+
30
+ function setStatus(state, name) {
31
+ current = { state, name: name ?? null };
32
+ writeStatus({ bonjour: current });
33
+ }
34
+
35
+ // Whether advertising is turned off (agent.json bonjour: false, SIMCAST_BONJOUR=0).
36
+ export function disabled() {
37
+ const env = String(process.env.SIMCAST_BONJOUR ?? '').trim().toLowerCase();
38
+ if (['0', 'false', 'off', 'no'].includes(env)) return true;
39
+ return readAgentConfigSafe().bonjour === false;
40
+ }
41
+
42
+ // A TXT string is at most 255 bytes, a DNS label (the service name) 63.
43
+ function clip(text, maxBytes) {
44
+ let s = String(text);
45
+ while (Buffer.byteLength(s) > maxBytes) s = s.slice(0, -1);
46
+ return s;
47
+ }
48
+
49
+ // dns-sd's arguments for one registration.
50
+ export function registerArgs({ port, agentId, macName }) {
51
+ const name = clip(macName, 63);
52
+ const txt = [
53
+ ...(agentId ? [`id=${agentId}`] : []),
54
+ `name=${name}`,
55
+ `proto=${PROTOCOL}`,
56
+ `port=${port}`,
57
+ `ver=${VERSION}`,
58
+ ].map((kv) => clip(kv, 255));
59
+ return ['-R', name, SERVICE_TYPE, 'local', String(port), ...txt];
60
+ }
61
+
62
+ // Starts advertising. Safe to call once; a second call restarts with the new
63
+ // values. `macName` defaults to macinfo.computerName().
64
+ export function start({ port, agentId, macName } = {}) {
65
+ stop();
66
+ // The status file is written a tick later: `serve` replaces the whole file
67
+ // in its own 'listening' handler, which runs after the one calling start().
68
+ if (disabled()) {
69
+ log('off (agent.json "bonjour": false or SIMCAST_BONJOUR=0)');
70
+ current = { state: 'off', name: null };
71
+ queueMicrotask(() => { if (!run) setStatus('off', null); });
72
+ return;
73
+ }
74
+ if (!port) return;
75
+ if (!exitHooked) {
76
+ exitHooked = true;
77
+ process.once('exit', () => kill(run?.child));
78
+ }
79
+ const r = { port, agentId, macName, child: null, timer: null, backoff: BACKOFF_MIN_MS, stopped: false };
80
+ run = r;
81
+ current = { state: 'starting', name: macName || null };
82
+ (macName ? Promise.resolve(macName) : computerName()).then((name) => {
83
+ if (r.stopped) return;
84
+ r.macName = name;
85
+ setStatus('starting', name);
86
+ spawnOnce(r);
87
+ });
88
+ }
89
+
90
+ function spawnOnce(r) {
91
+ r.timer = null;
92
+ let child;
93
+ try {
94
+ child = spawnTool('dns-sd', registerArgs(r), { stdio: ['ignore', 'pipe', 'pipe'] });
95
+ } catch (err) {
96
+ return ended(r, null, `could not start dns-sd: ${err.message}`);
97
+ }
98
+ r.child = child; // the state stays "failed" through retries, until it registers
99
+ // dns-sd alone must not keep this process alive (the server does that); the
100
+ // exit hook kills it.
101
+ child.unref();
102
+ child.stdout?.unref?.();
103
+ child.stderr?.unref?.();
104
+ let done = false;
105
+ const finish = (why) => {
106
+ if (done) return;
107
+ done = true;
108
+ if (r.child === child) r.child = null;
109
+ ended(r, child, why);
110
+ };
111
+ child.on('error', (err) => finish(err.code === 'ENOENT' ? 'dns-sd is not installed' : `dns-sd: ${err.message}`));
112
+ child.on('close', (code, signal) => finish(`dns-sd exited (${signal || `code ${code}`})`));
113
+ for (const stream of [child.stdout, child.stderr]) {
114
+ readline.createInterface({ input: stream }).on('line', (line) => onLine(r, child, line));
115
+ }
116
+ }
117
+
118
+ // "Got a reply for service Test Mac._simcast._tcp.local.: Name now registered and active"
119
+ // (the name can differ from the one asked for: mDNSResponder renames on a conflict).
120
+ const REPLY = /Got a reply for service (.+?)\._simcast\._tcp\.?(?:local\.?)?:\s*(.*)$/i;
121
+
122
+ function onLine(r, child, line) {
123
+ if (r.stopped || r.child !== child) return;
124
+ const m = REPLY.exec(line);
125
+ const name = m?.[1] || r.macName;
126
+ const what = m?.[2] || line;
127
+ if (/Name now registered and active|Name Registered/i.test(what)) {
128
+ r.backoff = BACKOFF_MIN_MS;
129
+ log(`Name Registered: "${name}" (${SERVICE_TYPE}, port ${r.port})`);
130
+ setStatus('registered', name);
131
+ } else if (/Name in use|Name Conflict/i.test(what)) {
132
+ log(`Name Conflict: "${name}" is taken on this network`);
133
+ setStatus('failed', name);
134
+ } else if (/registration removed/i.test(what)) {
135
+ log(`"${name}" is no longer registered`);
136
+ setStatus('failed', name);
137
+ } else if (/error|failed|-65\d\d\d/i.test(line)) {
138
+ log(`dns-sd: ${line.trim()}`);
139
+ }
140
+ }
141
+
142
+ function ended(r, child, why) {
143
+ if (r.stopped || run !== r) return;
144
+ const wait = r.backoff;
145
+ r.backoff = Math.min(r.backoff * 2, BACKOFF_MAX_MS);
146
+ log(`${why}; trying again in ${Math.round(wait / 1000)} s`);
147
+ setStatus('failed', current.name || r.macName);
148
+ r.timer = setTimeout(() => spawnOnce(r), wait);
149
+ r.timer.unref();
150
+ }
151
+
152
+ function kill(child) {
153
+ if (!child || child.exitCode !== null || child.signalCode !== null) return;
154
+ try { child.kill('SIGTERM'); } catch { /* gone */ }
155
+ }
156
+
157
+ // Stops advertising (kills dns-sd and cancels any restart).
158
+ export function stop() {
159
+ const r = run;
160
+ run = null;
161
+ if (!r) return;
162
+ r.stopped = true;
163
+ clearTimeout(r.timer);
164
+ kill(r.child);
165
+ r.child = null;
166
+ setStatus('off', null);
167
+ }
168
+
169
+ // { state: "starting" | "registered" | "failed" | "off", name }, for /info and the status file.
170
+ export function status() {
171
+ return { ...current };
172
+ }
@@ -0,0 +1,24 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ // Built .app files, keyed by the recipe's fingerprint hash.
5
+ export function cachedApp(buildsDir, hash) {
6
+ const dir = path.join(buildsDir, hash);
7
+ if (!fs.existsSync(dir)) return null;
8
+ const app = fs.readdirSync(dir).find((f) => f.endsWith('.app'));
9
+ return app ? path.join(dir, app) : null;
10
+ }
11
+
12
+ export function cacheApp(appPath, buildsDir, hash, keep = 3) {
13
+ const dir = path.join(buildsDir, hash);
14
+ fs.rmSync(dir, { recursive: true, force: true });
15
+ fs.mkdirSync(dir, { recursive: true });
16
+ const dest = path.join(dir, path.basename(appPath));
17
+ fs.cpSync(appPath, dest, { recursive: true, verbatimSymlinks: true });
18
+ const old = fs.readdirSync(buildsDir)
19
+ .map((name) => ({ name, mtime: fs.statSync(path.join(buildsDir, name)).mtimeMs }))
20
+ .sort((a, b) => b.mtime - a.mtime)
21
+ .slice(keep);
22
+ for (const { name } of old) fs.rmSync(path.join(buildsDir, name), { recursive: true, force: true });
23
+ return dest;
24
+ }