@slack/radar-mcp 1.13.0 → 1.17.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.
Files changed (46) hide show
  1. package/README.md +31 -3
  2. package/dist/mcp/db-tools.js +23 -0
  3. package/dist/mcp/dispatch.d.ts +4 -0
  4. package/dist/mcp/dispatch.js +26 -0
  5. package/dist/mcp/index.js +112 -33
  6. package/dist/mcp/platform-detect.d.ts +110 -0
  7. package/dist/mcp/platform-detect.js +246 -0
  8. package/dist/mcp/prefs-tools.d.ts +4 -3
  9. package/dist/mcp/prefs-tools.js +26 -3
  10. package/dist/mcp/session-enable.js +19 -1
  11. package/dist/mcp/snapshot.js +4 -1
  12. package/dist/mcp/sources-gate.js +6 -3
  13. package/dist/mcp/tools.d.ts +11 -0
  14. package/dist/mcp/tools.js +38 -0
  15. package/dist/shared/android.d.ts +40 -1
  16. package/dist/shared/android.js +114 -51
  17. package/dist/shared/constants.d.ts +25 -1
  18. package/dist/shared/constants.js +27 -1
  19. package/dist/shared/db.js +11 -2
  20. package/dist/shared/debug-log.js +6 -1
  21. package/dist/shared/enable-diagnosis.d.ts +28 -0
  22. package/dist/shared/enable-diagnosis.js +41 -0
  23. package/dist/shared/prefs.d.ts +0 -5
  24. package/dist/shared/prefs.js +6 -2
  25. package/dist/shared/screen.d.ts +46 -9
  26. package/dist/shared/screen.js +74 -11
  27. package/dist/shared/transport.d.ts +62 -5
  28. package/dist/shared/webapp.d.ts +50 -0
  29. package/dist/shared/webapp.js +65 -0
  30. package/dist/web/bin.js +16 -6
  31. package/dist/web/install-app.d.ts +87 -0
  32. package/dist/web/install-app.js +703 -0
  33. package/dist/web/macapp/RadarApp.swift +466 -0
  34. package/dist/web/public/icons/radar-1024.png +0 -0
  35. package/dist/web/public/icons/radar.svg +40 -0
  36. package/dist/web/public/index.html +42 -1
  37. package/dist/web/public/next/app.js +42 -1
  38. package/dist/web/public/next/db.js +153 -7
  39. package/dist/web/public/next/feed.js +18 -0
  40. package/dist/web/public/next/hooks.js +10 -1
  41. package/dist/web/public/next/screen.js +156 -46
  42. package/dist/web/public/next/store.js +164 -21
  43. package/dist/web/public/next/toast.js +134 -0
  44. package/dist/web/server.d.ts +151 -1
  45. package/dist/web/server.js +579 -22
  46. package/package.json +2 -2
@@ -8,14 +8,22 @@ import { AndroidTransport, resolveAdbPath } from "../shared/android.js";
8
8
  import { planReconnect } from "../shared/stream.js";
9
9
  import { RADAR_HOST, RADAR_PORT, RADAR_VERSION, WEB_PORT_DEFAULT } from "../shared/constants.js";
10
10
  import { friendlyFeatureFlagError } from "../shared/feature-flags.js";
11
+ import { deviceServerSilentError, readProcessState, } from "../shared/enable-diagnosis.js";
11
12
  import { cleanupPulledDatabases, initializeDatabasePath, listDatabases, pullDatabase, pulledSize, queryDatabase, resetDbState, availableUsers, } from "../shared/db.js";
12
13
  import { listPrefsFiles, readPrefsFile, parsePrefsXml, searchPrefs, } from "../shared/prefs.js";
13
14
  import { LogSession } from "./log-session.js";
14
15
  import { BLANK_SPEC, coerceSpec, validateSpec } from "./spec.js";
15
- import { screenCapabilities, refreshScreenCapabilities, grantScreenConsent, hasScreenConsent, detectDisplay, displayNote, captureScreenshot, startLive, addViewer, removeViewer, reapLiveIfIdle, primeIfNeeded, startRecording, stopRecording, recordingPath, resetScreenState, registerScreenCleanup, resolveFfmpeg, ffmpegInstallHint, SCREEN_BOUNDARY, } from "../shared/screen.js";
16
+ import { screenCapabilities, refreshScreenCapabilities, grantScreenConsent, hasScreenConsent, detectDisplay, displayNote, captureScreenshot, startLive, addViewer, removeViewer, reapLiveIfIdle, primeIfNeeded, startRecording, stopRecording, getLive, capturePath, saveScreenshot, screenshotSaveErrorMessage, resetScreenState, registerScreenCleanup, resolveFfmpeg, ffmpegInstallHint, SCREEN_BOUNDARY, } from "../shared/screen.js";
16
17
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
17
18
  const WEB_PORT = Number(process.env.SLACK_RADAR_WEB_PORT ?? WEB_PORT_DEFAULT);
18
19
  const INDEX_PATH = path.join(__dirname, "public", "index.html");
20
+ /**
21
+ * Ceiling for the diagnostic `ps` probe on the dashboard's failed-enable path. Deliberately
22
+ * shorter than the transport's default: /enable has already spent its own ping timeout
23
+ * proving the device server is unreachable, and this request blocks the dashboard's SSE
24
+ * tabs while it runs, so a fast "unknown" beats a slow confirmed answer here.
25
+ */
26
+ const DIAGNOSTIC_PS_TIMEOUT_MS = 1500;
19
27
  // Backpressure ceiling for an SSE connection's unwritten log frames. If a
20
28
  // client's socket buffer is already this deep (slow/backgrounded tab), new log
21
29
  // frames are dropped for that connection rather than queued without bound. ~4 MB
@@ -47,6 +55,12 @@ export function shouldDropLogFrame(replay, writableLength, cap = MAX_SSE_WRITABL
47
55
  // Each server start resets its own file to blank.
48
56
  const SPEC_DIR = path.join(os.homedir(), ".slack-radar");
49
57
  const SPEC_PATH = path.join(SPEC_DIR, `web-spec-${WEB_PORT}.json`);
58
+ // install-app.ts's runSelfHealCheck() writes this on every dock launch, regardless of port -- it
59
+ // is a per-machine install check, not per-dashboard-instance. A dedicated route rather than a
60
+ // field on /spec's body: /spec's JSON is a change-detection fingerprint the client diffs
61
+ // (JSON.stringify of the body) on every poll, and adding fields here would perturb that
62
+ // fingerprint every launch for a reason unrelated to the actual spec.
63
+ const SELF_HEAL_PATH = path.join(SPEC_DIR, "self-heal.json");
50
64
  const transport = new AndroidTransport();
51
65
  // Reassert the shared adb forward before every HTTP-based device read. Mirrors
52
66
  // mcp/index.ts's forwardForRead(): this process's own portForwarded cache cannot see a
@@ -95,6 +109,16 @@ function loadSpec() {
95
109
  return BLANK_SPEC;
96
110
  }
97
111
  }
112
+ // {} (never missing/malformed) is a normal "never checked yet" state, not an error: a fresh
113
+ // install with no self-heal.json yet must not read as a failure.
114
+ function loadSelfHeal() {
115
+ try {
116
+ return JSON.parse(fs.readFileSync(SELF_HEAL_PATH, "utf8"));
117
+ }
118
+ catch {
119
+ return {};
120
+ }
121
+ }
98
122
  // Start every run from a clean slate so a refresh/restart opens blank — UNLESS the
99
123
  // process was spawned with an initial spec (SLACK_RADAR_INITIAL_SPEC). The MCP
100
124
  // open_radar_dashboard handler sets that env on a cold spawn so the spec file is
@@ -144,11 +168,249 @@ export function cleanupOnBind() {
144
168
  process.once(sig, cleanupPulledDatabases);
145
169
  }
146
170
  }
147
- export function createServer() {
171
+ // --- Dashboard presence + auto-close ------------------------------------------
172
+ //
173
+ // The dashboard never tore itself down: closing every browser tab left this Node
174
+ // process running forever. Two teardown paths fix that: a manual kill button (POST
175
+ // /shutdown) and an auto-close that fires only when NOBODY — no live browser tab AND
176
+ // no MCP-driven write — has touched the dashboard for a while.
177
+ //
178
+ // Presence is poll-only. Each browser tab rides its id on pollProfile()'s 5s /health
179
+ // fetch (see store.ts); the server records a last-seen timestamp per tab. No
180
+ // pagehide/beforeunload/visibilitychange/sendBeacon: those are unreliable on mobile and
181
+ // fire on backgrounding (not just closing), which is the ambiguity this poll design avoids.
182
+ // How stale a tab id can be before the sweep prunes it as "not live". pollProfile pings every
183
+ // 5s nominally, but a backgrounded (not closed) tab can be throttled hard: Chrome's intensive
184
+ // throttling batches chained timers to roughly once per minute after a tab is hidden past 5
185
+ // minutes, occasionally stretching to ~90s. 75s covers the common throttled gap; a rare longer
186
+ // gap still just flaps the tab out and back in (the 5-minute grace below absorbs that flap
187
+ // harmlessly), it does not misfire an auto-close. Exported so tests pin the real constant
188
+ // instead of a duplicated copy.
189
+ export const TAB_LIVENESS_MS = 75_000;
190
+ // How long the dashboard must have ZERO live tabs before auto-close fires. Sized at ~3x the
191
+ // worst-case legitimate gap between presence pings (~60-90s under intensive throttling), so a
192
+ // backgrounded tab is never mistaken for a closed one. Not 90s — that is barely one throttled
193
+ // gap and would kill a live-but-hidden tab. Chrome's Memory Saver can also discard a
194
+ // backgrounded tab outright, permanently stopping its polling; auto-close eventually firing in
195
+ // that case is correct behavior ("nobody is looking"), not a bug to work around.
196
+ export const AUTO_CLOSE_GRACE_MS = 5 * 60_000;
197
+ // Sweep cadence: cheap (a map prune + a subtraction), frequent enough that auto-close fires
198
+ // promptly once the grace window elapses.
199
+ const AUTO_CLOSE_SWEEP_MS = 15_000;
200
+ const presence = { tabs: new Map(), emptySince: null, everSeen: false };
201
+ /**
202
+ * Pure auto-close decision, mirroring screen.ts's nextViewerAction/shouldRelaunch precedent:
203
+ * the sweep owns the timestamp bookkeeping, this owns only the yes/no. Close only when there
204
+ * are no live tabs, at least one tab has EVER been seen (an MCP-spawned dashboard nobody has
205
+ * opened must never self-destruct), and the empty period has outlived the grace window.
206
+ * Exported for unit testing without a clock or a socket.
207
+ */
208
+ export function shouldAutoClose(liveTabs, everSeen, msSinceEmpty) {
209
+ if (liveTabs > 0)
210
+ return false;
211
+ if (!everSeen)
212
+ return false;
213
+ if (msSinceEmpty === null)
214
+ return false;
215
+ return msSinceEmpty >= AUTO_CLOSE_GRACE_MS;
216
+ }
217
+ // A tab pinged /health with its id: record it live and remember a tab was seen. A fresh id
218
+ // after zero live tabs is the 0->1 transition, so clear the empty marker immediately. `now` is
219
+ // injectable so the sweep's staleness math is unit-testable with a fake clock.
220
+ export function touchTab(id, now = Date.now()) {
221
+ const wasEmpty = presence.tabs.size === 0;
222
+ presence.tabs.set(id, now);
223
+ presence.everSeen = true;
224
+ if (wasEmpty)
225
+ presence.emptySince = null;
226
+ }
227
+ /**
228
+ * Treat an authored MCP write (a /setspec, a successful /enable) as a keep-alive equivalent to
229
+ * a tab being present: clear the empty marker so the idle timer never fires mid-session. NOT
230
+ * gated on any tab being tracked — an hour-long MCP debugging session with zero open tabs is a
231
+ * legitimate reason to stay up, and losing it would drop the session logcat ring, the device
232
+ * pin, and the pulled-DB cache. Deliberately does NOT set everSeen: an MCP-only dashboard that
233
+ * nobody ever opened stays protected by the everSeen guard even after the MCP goes quiet.
234
+ */
235
+ export function markKeepAlive() {
236
+ presence.emptySince = null;
237
+ }
238
+ /**
239
+ * Whether a request may buy the process more life. True for our own client and the MCP, false
240
+ * for anything else, so a foreign page cannot postpone auto-close forever.
241
+ *
242
+ * Two accepted proofs, both unforgeable cross-origin without a CORS preflight the foreign
243
+ * origin cannot satisfy: the `X-Radar-Dashboard` header `/shutdown` already requires, or an
244
+ * `application/json` content-type. JSON counts because every MCP version ever published sends
245
+ * it on `/setspec`; requiring only the header would silently strip the keep-alive from an older
246
+ * globally-installed MCP talking to a newer dashboard.
247
+ *
248
+ * The content-type test compares the MIME ESSENCE, never a substring. CORS safelists a
249
+ * content-type by its essence and ignores parameters, so `text/plain; charset=application/json`
250
+ * is a SIMPLE request that any page can send with no preflight while still containing the
251
+ * string "application/json". A substring match there would reopen the exact hole this closes.
252
+ *
253
+ * Exported so the route wiring is directly testable: the decision, not just its effect.
254
+ */
255
+ export function isAuthoredRequest(headers) {
256
+ if (headers["x-radar-dashboard"] === "1")
257
+ return true;
258
+ const contentType = headers["content-type"];
259
+ const value = Array.isArray(contentType) ? contentType[0] : contentType;
260
+ if (typeof value !== "string")
261
+ return false;
262
+ const essence = value.split(";")[0].trim().toLowerCase();
263
+ return essence === "application/json";
264
+ }
265
+ /**
266
+ * One sweep tick: prune stale tab ids, maintain the emptySince marker across the 1->0 / 0->1
267
+ * transitions, and return whether the dashboard should auto-close now. Owns all timestamp
268
+ * bookkeeping and delegates the decision to shouldAutoClose. `now` is injectable so the
269
+ * transition logic is unit-testable with a fake clock. Returns true only on the tick where the
270
+ * grace window has elapsed with no live tabs.
271
+ */
272
+ export function sweepPresence(now = Date.now()) {
273
+ for (const [id, ts] of presence.tabs) {
274
+ if (now - ts > TAB_LIVENESS_MS)
275
+ presence.tabs.delete(id);
276
+ }
277
+ const liveTabs = presence.tabs.size;
278
+ if (liveTabs > 0) {
279
+ presence.emptySince = null; // 0->1 (or still >0): tabs present, not idle
280
+ }
281
+ else if (presence.everSeen && presence.emptySince === null) {
282
+ presence.emptySince = now; // 1->0: just went empty, start the grace clock
283
+ }
284
+ const msSinceEmpty = presence.emptySince === null ? null : now - presence.emptySince;
285
+ return shouldAutoClose(liveTabs, presence.everSeen, msSinceEmpty);
286
+ }
287
+ /** Presence snapshot for tests. */
288
+ export function getPresenceState() {
289
+ return {
290
+ liveTabs: presence.tabs.size,
291
+ everSeen: presence.everSeen,
292
+ emptySince: presence.emptySince,
293
+ };
294
+ }
295
+ /** Reset presence between tests (module state is a process singleton). */
296
+ export function resetPresenceForTest() {
297
+ presence.tabs.clear();
298
+ presence.emptySince = null;
299
+ presence.everSeen = false;
300
+ }
301
+ // Servers already tearing down. Keyed on the server rather than a module flag so the latch
302
+ // scopes to the thing being closed: a second call for the SAME server is suppressed, while a
303
+ // different server (every test builds its own) is unaffected. A module-level boolean would leak
304
+ // one test's shutdown into the next and would need a reset hook the tests must remember.
305
+ const shuttingDown = new WeakSet();
306
+ /**
307
+ * Gracefully shut the dashboard down. Reached by the manual /shutdown route and the auto-close
308
+ * sweep, so the server.close + timeout-fallback exit logic lives in exactly one place. Before
309
+ * tearing down, if a screen recording is live, finalize it: bin.ts's exit-time cleanup SIGKILLs
310
+ * the cast's ffmpeg child, and an ffmpeg killed mid-write leaves an mp4 with no moov atom
311
+ * (unplayable). Awaiting stopRecording writes the moov and closes the file first.
312
+ *
313
+ * That mp4 safety covers THOSE TWO PATHS ONLY. bin.ts also registers this on SIGINT/SIGTERM,
314
+ * but screen.ts's own signal handlers exit synchronously and are registered first, so Ctrl-C
315
+ * never reaches here and a recording killed that way can still be corrupt. Pre-existing gap;
316
+ * see the bin.ts comment at the SIGINT registration for why fixing it means touching screen.ts.
317
+ *
318
+ * A second call for the same server is a no-op: the sweep tick and a manual /shutdown can both
319
+ * fire, and awaiting stopRecording gives the next tick a window to land mid-flight.
320
+ * Deps are injectable so the recording-safety path is testable without spawning ffmpeg or
321
+ * actually exiting the process.
322
+ */
323
+ export async function shutdownDashboard(server, deps = {}) {
324
+ const _getLive = deps.getLive ?? getLive;
325
+ const _stopRecording = deps.stopRecording ?? stopRecording;
326
+ const _exit = deps.exit ?? ((code) => process.exit(code));
327
+ const _log = deps.log ?? ((msg) => console.log(msg));
328
+ if (shuttingDown.has(server))
329
+ return;
330
+ shuttingDown.add(server);
331
+ _log("\nShutting down…");
332
+ const live = _getLive();
333
+ if (live && live.recording) {
334
+ try {
335
+ await _stopRecording(live);
336
+ }
337
+ catch {
338
+ // Best-effort finalize; proceed with shutdown even if the stop failed.
339
+ }
340
+ }
341
+ let done = false;
342
+ let fallback;
343
+ const finish = () => {
344
+ if (done)
345
+ return;
346
+ done = true;
347
+ if (fallback)
348
+ clearTimeout(fallback);
349
+ _exit(0);
350
+ };
351
+ server.close(() => finish());
352
+ // Fallback: force-exit if close() hangs on a lingering keep-alive socket. Unref'd so the
353
+ // timer itself never keeps the process alive against a real shutdown.
354
+ fallback = setTimeout(finish, 2000);
355
+ fallback.unref();
356
+ }
357
+ /**
358
+ * Start the periodic auto-close sweep. Called once by bin.ts AFTER a successful listen bind, not
359
+ * from createServer, so importing this module (or spinning a throwaway server in a test) never
360
+ * arms a timer that could process.exit the test runner. The interval is unref'd so it never
361
+ * keeps the process alive on its own.
362
+ */
363
+ export function startAutoCloseSweep(server) {
364
+ // Escape hatch for anyone whose workflow needs the old always-on lifetime, mirroring
365
+ // SLACK_RADAR_NO_FFMPEG. This changes default process lifetime in a published package, so it
366
+ // needs an off switch that does not require pinning an older version.
367
+ if (process.env.SLACK_RADAR_NO_AUTO_CLOSE === "1")
368
+ return null;
369
+ const timer = setInterval(() => {
370
+ if (sweepPresence(Date.now()))
371
+ void shutdownDashboard(server);
372
+ }, AUTO_CLOSE_SWEEP_MS);
373
+ timer.unref();
374
+ return timer;
375
+ }
376
+ /**
377
+ * Build the dashboard HTTP server. `onShutdown` is the hook the manual /shutdown route fires
378
+ * after answering; it defaults to the real graceful shutdown and is injectable so a test can
379
+ * exercise the route without exiting the process. bin.ts calls createServer() with no args.
380
+ */
381
+ export function createServer(onShutdown) {
148
382
  registerScreenCleanup(); // tear down any live screen cast on process exit/signals
149
383
  const server = http.createServer((req, res) => {
384
+ // One chokepoint for every route: a request whose Host is not this loopback dashboard is a
385
+ // rebound foreign origin, not our client (see isLocalHostHeader). Rejected before routing so
386
+ // no handler has to remember, and so /shutdown in particular cannot be reached that way.
387
+ if (!isLocalHostHeader(req.headers.host)) {
388
+ // Name the remedy in the body. A bare 403 on a URL that used to work reads as a broken
389
+ // dashboard, and the fix (add the hostname you are using) is not guessable.
390
+ sendJson(res, 403, {
391
+ error: `Refusing a request for host "${String(req.headers.host)}". The dashboard only answers on localhost. If you reach it by another name, set SLACK_RADAR_ALLOWED_HOSTS to include it.`,
392
+ });
393
+ return;
394
+ }
150
395
  const url = req.url ?? "";
151
396
  const urlPath = url.split("?")[0];
397
+ // Second chokepoint, DEFAULT DENY. A request must prove it came from our own client unless its
398
+ // path is a known read. Host alone is not enough: a page served from a real site can call
399
+ // localhost with no rebinding at all -- a text/plain POST and any GET are CORS simple requests,
400
+ // so no preflight is sent and the Host stays "localhost".
401
+ //
402
+ // This used to be an allowlist of five POST paths, and that shape failed twice in the same
403
+ // commit that introduced it: `/_control/activate` dispatched with startsWith so a suffix missed
404
+ // the exact-match Set, and `/api/clear` plus `/screen/redetect` reach the device on GET and
405
+ // were never listed at all. Enumerating what to protect fails open on everything forgotten, and
406
+ // cannot express prefix or method-agnostic handlers. Enumerating what is safe fails closed: a
407
+ // new route is protected until someone deliberately opens it.
408
+ if (!isOpenToAnyCaller(urlPath, req.method) && !isAuthoredRequest(req.headers)) {
409
+ sendJson(res, 403, {
410
+ error: `Refusing an unauthored ${String(req.method)} to ${urlPath}. Either this route can change state or reach the device (add the X-Radar-Dashboard: 1 header our own client sends, or Content-Type: application/json), or the path does not exist -- an unrecognized path is refused rather than 404'd so a new route is never open by accident.`,
411
+ });
412
+ return;
413
+ }
152
414
  if (urlPath === "/" || urlPath === "/index.html") {
153
415
  // The Preact dashboard is the default (and only) UI. The old vanilla dashboard + its
154
416
  // ?next opt-in seam were retired in the flip; index.html IS the Preact shell now.
@@ -170,17 +432,45 @@ export function createServer() {
170
432
  sendJson(res, 200, loadSpec());
171
433
  return;
172
434
  }
435
+ if (url === "/self-heal" && req.method === "GET") {
436
+ sendJson(res, 200, loadSelfHeal());
437
+ return;
438
+ }
173
439
  if (url === "/setspec" && req.method === "POST") {
174
- handleSetSpec(req, res);
440
+ handleSetSpec(req, res, isAuthoredRequest(req.headers));
175
441
  return;
176
442
  }
177
- if (url === "/health" && req.method === "GET") {
443
+ if (urlPath === "/health" && req.method === "GET") {
444
+ // Browser tabs ride their presence id on this poll (pollProfile's 5s /health fetch). A
445
+ // request without ?tab= (the MCP-side adopt probe, a plain curl) is just not a presence
446
+ // signal; the response shape is unchanged either way. The same X-Radar-Dashboard header
447
+ // /shutdown requires also gates presence: without it, a plain cross-origin GET (no
448
+ // preflight needed for a simple request) could set everSeen on an MCP-only dashboard or
449
+ // keep one alive forever from any page the user's browser has open -- the same process-
450
+ // kill/keep-alive threat model the header exists to close on /shutdown, reachable through
451
+ // this side door. A custom request header forces a real CORS preflight the foreign origin
452
+ // cannot satisfy. Silently ignoring an unauthenticated ?tab= (not 400ing) keeps a bare curl
453
+ // or an old MCP probe working exactly as before; it just never counts as presence.
454
+ //
455
+ // Deliberately the HEADER ALONE, not isAuthoredRequest. That predicate also accepts an
456
+ // application/json content-type, which exists only to keep older MCP /setspec writes
457
+ // working; on a bodyless GET it proves nothing about the caller. Keep this gate the
458
+ // narrower of the two rather than unifying them.
459
+ if (req.headers["x-radar-dashboard"] === "1") {
460
+ const tab = new URL(url, `http://localhost:${WEB_PORT}`).searchParams.get("tab");
461
+ if (tab)
462
+ touchTab(tab);
463
+ }
178
464
  handleHealth(res);
179
465
  return;
180
466
  }
467
+ if (urlPath === "/shutdown" && req.method === "POST") {
468
+ handleShutdown(req, res, () => (onShutdown ?? shutdownDashboard)(server));
469
+ return;
470
+ }
181
471
  if (urlPath === "/enable" && req.method === "POST") {
182
472
  const serial = new URL(url, `http://localhost:${WEB_PORT}`).searchParams.get("device_serial");
183
- handleEnable(res, serial);
473
+ handleEnable(res, serial, isAuthoredRequest(req.headers));
184
474
  return;
185
475
  }
186
476
  if (url === "/stream" && req.method === "GET") {
@@ -227,7 +517,10 @@ export function createServer() {
227
517
  listProfiles(res);
228
518
  return;
229
519
  }
230
- if (url.startsWith("/_control/activate") && req.method === "POST") {
520
+ // Match the exact path, not a prefix. A startsWith here disagreed with the authored-POST
521
+ // guard above (which keys on the exact urlPath), so `/_control/activateXYZ` skipped the guard
522
+ // and still re-armed the device. Any guarded route must match the same way the guard does.
523
+ if (urlPath === "/_control/activate" && req.method === "POST") {
231
524
  const parsed = new URL(url, `http://localhost:${WEB_PORT}`);
232
525
  const userId = parsed.searchParams.get("user_id") ?? undefined;
233
526
  activateRadar(res, userId);
@@ -366,8 +659,10 @@ function readBody(req) {
366
659
  * Persist a spec pushed by the client (a pre-built tab, a filter edit, a chip
367
660
  * cancel) or by an MCP caller. Coerce + validate before writing; a bad spec is
368
661
  * rejected with its reason so the UI can surface it rather than render zeros.
662
+ * `authored` means the caller proved it is our own client or the MCP; only then does the
663
+ * write count as a keep-alive (see below).
369
664
  */
370
- async function handleSetSpec(req, res) {
665
+ async function handleSetSpec(req, res, authored) {
371
666
  const body = await readBody(req);
372
667
  let parsed;
373
668
  try {
@@ -384,12 +679,36 @@ async function handleSetSpec(req, res) {
384
679
  return;
385
680
  }
386
681
  writeSpec(spec);
682
+ // An authored write keeps the dashboard alive with zero open tabs (see markKeepAlive): a human
683
+ // may have closed the tab while the MCP keeps driving a long debugging session. Gated on the
684
+ // same X-Radar-Dashboard header /shutdown and /health presence require, because the body is
685
+ // never content-type checked: a cross-origin POST with a text/plain body is a CORS simple
686
+ // request, so without the gate any page in the user's browser could postpone auto-close
687
+ // forever by pinging this every few minutes. The spec still gets written either way, which
688
+ // keeps a bare curl working; it just does not buy the process more life.
689
+ if (authored)
690
+ markKeepAlive();
387
691
  sendJson(res, 200, {
388
692
  ok: true,
389
693
  url: `http://localhost:${WEB_PORT}`,
390
694
  title: spec.title ?? "",
391
695
  });
392
696
  }
697
+ /**
698
+ * Manual kill. The client's own kill button sets X-Radar-Dashboard: 1; a bare cross-origin
699
+ * POST from any page the user's browser has open cannot set a custom header without a CORS
700
+ * preflight it will fail, so requiring the header is a lightweight CSRF guard on a loopback
701
+ * route that takes the whole process down. Answer BEFORE shutting down so the button's fetch
702
+ * resolves rather than seeing a dropped socket, then fire the shutdown on the next tick.
703
+ */
704
+ function handleShutdown(req, res, fire) {
705
+ if (req.headers["x-radar-dashboard"] !== "1") {
706
+ sendJson(res, 400, { error: "missing X-Radar-Dashboard header" });
707
+ return;
708
+ }
709
+ sendJson(res, 200, { ok: true, stopping: true });
710
+ setTimeout(fire, 0);
711
+ }
393
712
  /**
394
713
  * Always-available device-reachability probe, independent of whether a dashboard
395
714
  * is built. Drives the connection dot even on a blank dashboard. Reuses the same
@@ -479,13 +798,183 @@ function handleHealth(res) {
479
798
  });
480
799
  probe.end();
481
800
  }
801
+ /**
802
+ * The /enable response body for a completed device probe, plus its one side effect: a
803
+ * successful re-arm keeps the dashboard alive (an MCP-driven session can re-enable with no tab
804
+ * open, and that must not let the idle timer fire out from under it).
805
+ *
806
+ * `onEnabled` fires only on a successful probe. The route passes `markKeepAlive` when the
807
+ * request was authored (see isAuthoredRequest) and OMITS it otherwise, so an unauthored caller
808
+ * gets the same body but buys no extra process life. Injected rather than called directly so
809
+ * the keep-alive wiring is testable without a real device probe (handleEnable's ping goes over
810
+ * a real socket to RADAR_HOST:RADAR_PORT, which this function does not touch at all).
811
+ *
812
+ * A failed probe gets guidance, not a bare false: the broadcast landed (or exited 0 with no
813
+ * receiver), so the likely causes are a build without the slack-radar modules or the wrong
814
+ * profile. Mirrors the MCP enable message. Exported for unit testing.
815
+ */
816
+ /**
817
+ * Which keep-alive hook /enable hands to enableResultBody: the real one for an authored request,
818
+ * none otherwise. Its own function purely so a test can assert the CHOICE. Asserting the effect
819
+ * through the route cannot cover this — handleEnable's device probe fails with no hardware, which
820
+ * short-circuits before the hook is ever consulted, so a route-level test passes either way (a
821
+ * mutation deleting the gate survived the whole suite before this existed).
822
+ */
823
+ export function keepAliveHookFor(authored) {
824
+ return authored ? markKeepAlive : undefined;
825
+ }
826
+ // Reads the dashboard serves to any local caller. Everything NOT matching is treated as
827
+ // state-changing and needs proof it came from our own client (see isOpenToAnyCaller).
828
+ //
829
+ // Two rules for adding to this list, both learned from a real bypass:
830
+ // 1. It must be genuinely side-effect free. /api/clear looks like a read and wipes the device.
831
+ // 2. It must be reachable ONLY by the shape listed here. A prefix entry opens every path under
832
+ // it, so `/api/` cannot be blanket-opened while /api/clear lives behind the same proxy.
833
+ const READ_ONLY_EXACT = new Set([
834
+ "/",
835
+ "/index.html",
836
+ "/health",
837
+ "/spec",
838
+ "/self-heal",
839
+ "/stream", // EventSource cannot set headers, so this must stay open
840
+ "/backfill",
841
+ "/detail",
842
+ "/dbs", // only lists database names; no pull
843
+ // NOT /dbtables and NOT /dbquery. Both reach pullDatabase, which mkdirs a temp dir and writes a
844
+ // multi-MB PLAINTEXT copy of the on-device message store (plus -wal/-shm) to host disk;
845
+ // /dbtables?refresh=1 re-pulls unconditionally. They read like a listing and a select, but each
846
+ // is a data-exposure step and a repeatable multi-MB adb pull, so both need proof of origin.
847
+ // queryDatabase pulls too when no local copy exists (db.ts: `if (!existsSync(local)) await
848
+ // pullDatabase(...)`), so gating only /dbtables would leave the same pull reachable.
849
+ "/flags",
850
+ "/prefs",
851
+ "/prefsread",
852
+ "/prefssearch",
853
+ "/screen/caps",
854
+ "/screen/shot", // <img src> cannot set a header
855
+ "/screen/stream", // <img src> live MJPEG cast, same
856
+ "/_control/profiles",
857
+ "/_control/devices",
858
+ ]);
859
+ // Path PREFIXES that are read-only for their whole subtree. Kept tiny and audited: anything added
860
+ // here opens every path beneath it forever. These two serve the dashboard's own static bundle.
861
+ // The server matches these with startsWith, so the guard has to as well or a real request 403s.
862
+ // /screen/download/<file> serves a finished recording the user asked to save.
863
+ const READ_ONLY_PREFIXES = ["/next/", "/vendor/", "/screen/download"];
864
+ // Device-proxy reads. `/api/` as a whole is NOT safe (/api/clear wipes the device buffers), so the
865
+ // readable sources are named and everything else under /api/ falls through to the guard.
866
+ // Only names the device actually serves today (verified live: /api/prefs and /api/session 404).
867
+ // A dead entry here is worse than useless -- the device dispatches /api/<name> to any RadarPlugin
868
+ // claiming that name, and plugin handlers carry no side-effect guarantee, so listing a name nothing
869
+ // serves pre-authorizes whatever future plugin takes it.
870
+ const READ_ONLY_API_SOURCES = [
871
+ "ping",
872
+ "network",
873
+ "rtm",
874
+ "clogs",
875
+ "traces",
876
+ "feature_flags",
877
+ "search",
878
+ ];
879
+ /**
880
+ * Whether the dashboard serves this request without proof of origin. Everything else is refused
881
+ * unless authored. Exported so a test can drive the decision directly, and so the open surface is
882
+ * reviewable in one place instead of inferred from twenty route branches.
883
+ *
884
+ * Reads are open by path. Writes are closed with exactly two named exceptions, both justified
885
+ * below. A POST to a read path is NOT open: only GET and HEAD can ever be reads.
886
+ */
887
+ export function isOpenToAnyCaller(urlPath, method) {
888
+ // The two deliberate write carve-outs, POST only. /setspec is the one write anyone may make: it
889
+ // rewrites the local dashboard view, driving it with a bare `curl -X POST` is supported, and its
890
+ // keep-alive side effect is gated separately (see handleSetSpec). /shutdown carries its own
891
+ // header check inside handleShutdown, which answers before exiting.
892
+ //
893
+ // Pinned to POST because that is the only method either route dispatches. Allowing any method
894
+ // would repeat the mistake this whole guard exists to fix: a future non-POST handler on one of
895
+ // these paths would be born open.
896
+ if (method === "POST" && (urlPath === "/setspec" || urlPath === "/shutdown"))
897
+ return true;
898
+ if (method !== "GET" && method !== "HEAD")
899
+ return false;
900
+ if (READ_ONLY_EXACT.has(urlPath))
901
+ return true;
902
+ if (READ_ONLY_PREFIXES.some((prefix) => urlPath.startsWith(prefix)))
903
+ return true;
904
+ // /api/<source> and /api/<source>/<id> are reads; /api/clear and anything unrecognized are not.
905
+ const apiMatch = /^\/api\/([^/]+)(?:\/[^/]*)?$/.exec(urlPath);
906
+ return apiMatch !== null && READ_ONLY_API_SOURCES.includes(apiMatch[1]);
907
+ }
908
+ /**
909
+ * Whether a request's Host names this loopback dashboard. The listener is bound to 127.0.0.1, but
910
+ * that only limits which interface accepts the TCP connection: a browser resolving an attacker's
911
+ * domain to 127.0.0.1 (DNS rebinding) connects locally and arrives with that domain in Host. The
912
+ * page is then same-origin by the browser's reckoning, so it can set any header it likes and the
913
+ * X-Radar-Dashboard guard buys nothing against it. Checking Host is what makes the loopback bind
914
+ * an actual boundary, and it matters most for /shutdown, which kills the process.
915
+ *
916
+ * Accepts localhost / 127.0.0.1 / [::1] / ::1 / 0.0.0.0, with or without a port, and a missing
917
+ * Host (HTTP/1.0 and a bare socket client send none; those cannot be a rebound browser).
918
+ *
919
+ * SLACK_RADAR_ALLOWED_HOSTS adds names for the setups that reach the dashboard by something other
920
+ * than localhost -- a /etc/hosts alias, a container or Codespaces forwarded URL, a LAN hostname.
921
+ * Comma-separated, `host` or `host:port`; a bare name matches on any port. Without it those users
922
+ * would just get a 403 with nothing to do about it.
923
+ */
924
+ export function isLocalHostHeader(host, allowedHosts = process.env.SLACK_RADAR_ALLOWED_HOSTS) {
925
+ const value = Array.isArray(host) ? host[0] : host;
926
+ if (value === undefined || value === "")
927
+ return true;
928
+ const raw = value.trim().toLowerCase();
929
+ // Strip the port to compare the name alone. Three shapes to keep straight:
930
+ // host:8100 -> strip
931
+ // [::1]:8100 -> strip (the brackets survive, which is what we compare against)
932
+ // ::1 -> do NOT strip; a bare IPv6 literal is all colons, and stripping the last
933
+ // group would leave ":" and reject a legitimate loopback request.
934
+ // So only strip when the value is bracketed, or when it holds at most one colon.
935
+ const bracketed = raw.startsWith("[");
936
+ const name = bracketed || raw.split(":").length <= 2 ? raw.replace(/:\d+$/, "") : raw;
937
+ if (name === "localhost" ||
938
+ name === "127.0.0.1" ||
939
+ name === "0.0.0.0" ||
940
+ name === "[::1]" ||
941
+ name === "::1") {
942
+ return true;
943
+ }
944
+ // Operator-listed names. Both sides are compared with and without their port, so an entry
945
+ // matches whichever shape actually arrives: `radar.local` admits `radar.local:8100`, and
946
+ // `radar.local:8100` admits a bare `radar.local` (which is what a browser sends on 80/443,
947
+ // the forwarded-URL case this env var exists for).
948
+ for (const entry of (allowedHosts ?? "").split(",")) {
949
+ const allowed = entry.trim().toLowerCase();
950
+ if (allowed === "")
951
+ continue;
952
+ const allowedName = allowed.startsWith("[") || allowed.split(":").length <= 2
953
+ ? allowed.replace(/:\d+$/, "")
954
+ : allowed;
955
+ if (allowed === raw || allowed === name || allowedName === raw || allowedName === name) {
956
+ return true;
957
+ }
958
+ }
959
+ return false;
960
+ }
961
+ export function enableResultBody(enabled, onEnabled,
962
+ // Defaults to "unknown" so a caller that cannot probe keeps the generic message,
963
+ // which is also what every pre-existing two-argument call site gets.
964
+ processState = "unknown") {
965
+ if (enabled) {
966
+ onEnabled?.();
967
+ return { enabled };
968
+ }
969
+ return { enabled, error: deviceServerSilentError(processState) };
970
+ }
482
971
  /**
483
972
  * Re-arm Radar from the dashboard. Mirrors the recovery sequence: reset cached
484
973
  * forward state, rebuild a clean adb forward, and re-broadcast activation, so the
485
974
  * user never has to drop to a terminal. Delegates entirely to AndroidTransport;
486
975
  * no adb shelling here.
487
976
  */
488
- function handleEnable(res, deviceSerial) {
977
+ function handleEnable(res, deviceSerial, authored) {
489
978
  transport.resetState();
490
979
  // A reconnect may be a different device / re-armed profile, so drop the cached DB user
491
980
  // set + sqlite path; the next /dbs re-detects the profiles fresh.
@@ -557,15 +1046,13 @@ function handleEnable(res, deviceSerial) {
557
1046
  if (replied)
558
1047
  return;
559
1048
  replied = true;
560
- // A failed probe gets guidance, not a bare false: the broadcast landed (or
561
- // exited 0 with no receiver), so the likely causes are a build without the
562
- // radar modules or the wrong profile. Mirrors the MCP enable message.
563
- sendJson(res, 200, enabled
564
- ? { enabled }
565
- : {
566
- enabled,
567
- error: "Radar broadcast sent but the device server did not respond. Is a debug build with the slack-radar modules running on the active profile?",
568
- });
1049
+ // Probe only on the failure path: a successful enable needs no diagnosis, and the
1050
+ // probe is a real adb round trip. Capped short, because by this point the failure is
1051
+ // already established and the user is watching a request that has stalled their SSE
1052
+ // tabs; an explanation must not cost more than the operation it explains. The MCP path
1053
+ // keeps the patient default, where seconds of ping retries have already elapsed and a
1054
+ // real answer beats a fast "unknown".
1055
+ sendJson(res, 200, enableResultBody(enabled, keepAliveHookFor(authored), enabled ? "unknown" : readProcessState(transport, DIAGNOSTIC_PS_TIMEOUT_MS)));
569
1056
  };
570
1057
  const probe = http.request({
571
1058
  host: RADAR_HOST,
@@ -941,9 +1428,10 @@ async function handlePrefsSearch(req, res) {
941
1428
  * /screen/caps capabilities (ffmpeg/scrcpy present, install hint, consent state)
942
1429
  * /screen/consent POST: grant consent for this server process
943
1430
  * /screen/shot full-resolution PNG screenshot (pure screencap; works without ffmpeg)
1431
+ * /screen/shot/save capture a screenshot to disk and report the outcome (two-phase)
944
1432
  * /screen/stream multipart/x-mixed-replace MJPEG live cast (needs ffmpeg + consent)
945
1433
  * /screen/record/start|stop record the live cast to mp4 (needs ffmpeg + consent)
946
- * /screen/download download a finished recording
1434
+ * /screen/download download a finished recording or screenshot
947
1435
  * /screen/redetect re-detect the active display
948
1436
  */
949
1437
  function handleScreen(req, res) {
@@ -979,7 +1467,55 @@ function handleScreen(req, res) {
979
1467
  sendJson(res, 200, { consent: true });
980
1468
  return;
981
1469
  }
1470
+ // Screenshot, two-phase: capture to disk and report the outcome as JSON, exactly like
1471
+ // /screen/record/stop. The dashboard uses this rather than GET /screen/shot because a
1472
+ // Content-Disposition response is invisible to the page that asked for it -- it cannot
1473
+ // tell a saved PNG from a 403 or a 502, so it used to say "screenshot saved" either way.
1474
+ // The client downloads the file it names in a second step, once it knows there is one.
1475
+ if (url === "/screen/shot/save" && req.method === "POST") {
1476
+ if (!hasScreenConsent()) {
1477
+ sendJson(res, 403, { ok: false, error: "screen consent required" });
1478
+ return;
1479
+ }
1480
+ void (async () => {
1481
+ // Same guard as the /screen/caps refresh branch above, and for the same reason: an escaping
1482
+ // rejection would leave this request hanging until the client times out, and a route whose
1483
+ // whole purpose is reporting the outcome must not have a silent way to report nothing.
1484
+ try {
1485
+ await detectDisplay();
1486
+ const shot = await saveScreenshot();
1487
+ if (!shot.ok) {
1488
+ // Name the half that failed. A write failure is a host problem (no space, a dir mode the
1489
+ // process cannot write); calling it a capture failure would send the user to check a
1490
+ // phone that answered perfectly well.
1491
+ sendJson(res, 502, { ok: false, error: screenshotSaveErrorMessage(shot) });
1492
+ return;
1493
+ }
1494
+ const p = shot.path;
1495
+ let sizeBytes = 0;
1496
+ try {
1497
+ sizeBytes = fs.statSync(p).size;
1498
+ }
1499
+ catch {
1500
+ sizeBytes = 0;
1501
+ }
1502
+ const file = path.basename(p);
1503
+ sendJson(res, 200, {
1504
+ ok: true,
1505
+ file,
1506
+ sizeBytes,
1507
+ download: "/screen/download?f=" + encodeURIComponent(file),
1508
+ });
1509
+ }
1510
+ catch (e) {
1511
+ sendJson(res, 502, { ok: false, error: "screenshot failed: " + e.message });
1512
+ }
1513
+ })();
1514
+ return;
1515
+ }
982
1516
  // Screenshot: pure screencap, no ffmpeg. Still consent-gated — it is the live screen.
1517
+ // Kept as a direct PNG for anyone hitting the URL by hand; the dashboard uses the
1518
+ // two-phase route above so it can actually see whether the capture worked.
983
1519
  if (url.startsWith("/screen/shot")) {
984
1520
  if (!hasScreenConsent()) {
985
1521
  sendJson(res, 403, { error: "screen consent required" });
@@ -1086,24 +1622,45 @@ function handleScreen(req, res) {
1086
1622
  return;
1087
1623
  }
1088
1624
  if (url.startsWith("/screen/download")) {
1089
- // A recording is device-screen content, so gate download on consent too — a fresh
1090
- // (unconsented) process must not serve a prior session's screen recording.
1625
+ // A capture is device-screen content, so gate download on consent too — a fresh
1626
+ // (unconsented) process must not serve a prior session's screen recording or screenshot.
1091
1627
  if (!hasScreenConsent()) {
1092
1628
  sendJson(res, 403, { error: "screen consent required" });
1093
1629
  return;
1094
1630
  }
1095
1631
  const f = new URL(url, `http://localhost:${WEB_PORT}`).searchParams.get("f") ?? "";
1096
- const p = recordingPath(f);
1632
+ const p = capturePath(f);
1097
1633
  if (!p) {
1098
1634
  res.writeHead(404);
1099
1635
  res.end("Not found");
1100
1636
  return;
1101
1637
  }
1102
1638
  res.writeHead(200, {
1103
- "Content-Type": "video/mp4",
1639
+ // capturePath admits exactly two extensions, so the type follows from the name. It used to
1640
+ // be a hardcoded video/mp4, which served a screenshot as an mp4 once this route started
1641
+ // carrying them.
1642
+ "Content-Type": p.endsWith(".png") ? "image/png" : "video/mp4",
1104
1643
  "Content-Disposition": `attachment; filename="${path.basename(p)}"`,
1105
1644
  });
1106
1645
  fs.createReadStream(p).pipe(res);
1646
+ // Drop the server-side copy once it has been handed over. A capture is a full frame of
1647
+ // whatever is on the phone, and the download is the point of making it, so keeping it after
1648
+ // delivery just leaves device-screen content sitting in the tmp dir for the rest of the
1649
+ // session -- cleanupRecordings only runs on re-enable and exit. The user's own copy is
1650
+ // untouched, and reveal in the packaged app points at that copy in ~/Downloads, not at this
1651
+ // one. Unlinking a file mid-read is safe, this stream keeps its descriptor.
1652
+ //
1653
+ // Hung off "close" rather than "finish" so an ABORTED transfer drops the file too. Nothing
1654
+ // retries a download, so keeping it after an abort just leaves a full frame of the device
1655
+ // screen in the tmp dir until re-enable or exit, which is the leftover this removes.
1656
+ res.on("close", () => {
1657
+ try {
1658
+ fs.unlinkSync(p);
1659
+ }
1660
+ catch {
1661
+ // Already gone, or a reset cleaned the dir first. Nothing to report either way.
1662
+ }
1663
+ });
1107
1664
  return;
1108
1665
  }
1109
1666
  if (url === "/screen/redetect") {