@slack/radar-mcp 1.12.0 → 1.14.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.
@@ -7,11 +7,12 @@ import { fileURLToPath } from "url";
7
7
  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
+ import { friendlyFeatureFlagError } from "../shared/feature-flags.js";
10
11
  import { cleanupPulledDatabases, initializeDatabasePath, listDatabases, pullDatabase, pulledSize, queryDatabase, resetDbState, availableUsers, } from "../shared/db.js";
11
12
  import { listPrefsFiles, readPrefsFile, parsePrefsXml, searchPrefs, } from "../shared/prefs.js";
12
13
  import { LogSession } from "./log-session.js";
13
14
  import { BLANK_SPEC, coerceSpec, validateSpec } from "./spec.js";
14
- 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";
15
+ import { screenCapabilities, refreshScreenCapabilities, grantScreenConsent, hasScreenConsent, detectDisplay, displayNote, captureScreenshot, startLive, addViewer, removeViewer, reapLiveIfIdle, primeIfNeeded, startRecording, stopRecording, getLive, recordingPath, resetScreenState, registerScreenCleanup, resolveFfmpeg, ffmpegInstallHint, SCREEN_BOUNDARY, } from "../shared/screen.js";
15
16
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
16
17
  const WEB_PORT = Number(process.env.SLACK_RADAR_WEB_PORT ?? WEB_PORT_DEFAULT);
17
18
  const INDEX_PATH = path.join(__dirname, "public", "index.html");
@@ -143,11 +144,249 @@ export function cleanupOnBind() {
143
144
  process.once(sig, cleanupPulledDatabases);
144
145
  }
145
146
  }
146
- export function createServer() {
147
+ // --- Dashboard presence + auto-close ------------------------------------------
148
+ //
149
+ // The dashboard never tore itself down: closing every browser tab left this Node
150
+ // process running forever. Two teardown paths fix that: a manual kill button (POST
151
+ // /shutdown) and an auto-close that fires only when NOBODY — no live browser tab AND
152
+ // no MCP-driven write — has touched the dashboard for a while.
153
+ //
154
+ // Presence is poll-only. Each browser tab rides its id on pollProfile()'s 5s /health
155
+ // fetch (see store.ts); the server records a last-seen timestamp per tab. No
156
+ // pagehide/beforeunload/visibilitychange/sendBeacon: those are unreliable on mobile and
157
+ // fire on backgrounding (not just closing), which is the ambiguity this poll design avoids.
158
+ // How stale a tab id can be before the sweep prunes it as "not live". pollProfile pings every
159
+ // 5s nominally, but a backgrounded (not closed) tab can be throttled hard: Chrome's intensive
160
+ // throttling batches chained timers to roughly once per minute after a tab is hidden past 5
161
+ // minutes, occasionally stretching to ~90s. 75s covers the common throttled gap; a rare longer
162
+ // gap still just flaps the tab out and back in (the 5-minute grace below absorbs that flap
163
+ // harmlessly), it does not misfire an auto-close. Exported so tests pin the real constant
164
+ // instead of a duplicated copy.
165
+ export const TAB_LIVENESS_MS = 75_000;
166
+ // How long the dashboard must have ZERO live tabs before auto-close fires. Sized at ~3x the
167
+ // worst-case legitimate gap between presence pings (~60-90s under intensive throttling), so a
168
+ // backgrounded tab is never mistaken for a closed one. Not 90s — that is barely one throttled
169
+ // gap and would kill a live-but-hidden tab. Chrome's Memory Saver can also discard a
170
+ // backgrounded tab outright, permanently stopping its polling; auto-close eventually firing in
171
+ // that case is correct behavior ("nobody is looking"), not a bug to work around.
172
+ export const AUTO_CLOSE_GRACE_MS = 5 * 60_000;
173
+ // Sweep cadence: cheap (a map prune + a subtraction), frequent enough that auto-close fires
174
+ // promptly once the grace window elapses.
175
+ const AUTO_CLOSE_SWEEP_MS = 15_000;
176
+ const presence = { tabs: new Map(), emptySince: null, everSeen: false };
177
+ /**
178
+ * Pure auto-close decision, mirroring screen.ts's nextViewerAction/shouldRelaunch precedent:
179
+ * the sweep owns the timestamp bookkeeping, this owns only the yes/no. Close only when there
180
+ * are no live tabs, at least one tab has EVER been seen (an MCP-spawned dashboard nobody has
181
+ * opened must never self-destruct), and the empty period has outlived the grace window.
182
+ * Exported for unit testing without a clock or a socket.
183
+ */
184
+ export function shouldAutoClose(liveTabs, everSeen, msSinceEmpty) {
185
+ if (liveTabs > 0)
186
+ return false;
187
+ if (!everSeen)
188
+ return false;
189
+ if (msSinceEmpty === null)
190
+ return false;
191
+ return msSinceEmpty >= AUTO_CLOSE_GRACE_MS;
192
+ }
193
+ // A tab pinged /health with its id: record it live and remember a tab was seen. A fresh id
194
+ // after zero live tabs is the 0->1 transition, so clear the empty marker immediately. `now` is
195
+ // injectable so the sweep's staleness math is unit-testable with a fake clock.
196
+ export function touchTab(id, now = Date.now()) {
197
+ const wasEmpty = presence.tabs.size === 0;
198
+ presence.tabs.set(id, now);
199
+ presence.everSeen = true;
200
+ if (wasEmpty)
201
+ presence.emptySince = null;
202
+ }
203
+ /**
204
+ * Treat an authored MCP write (a /setspec, a successful /enable) as a keep-alive equivalent to
205
+ * a tab being present: clear the empty marker so the idle timer never fires mid-session. NOT
206
+ * gated on any tab being tracked — an hour-long MCP debugging session with zero open tabs is a
207
+ * legitimate reason to stay up, and losing it would drop the session logcat ring, the device
208
+ * pin, and the pulled-DB cache. Deliberately does NOT set everSeen: an MCP-only dashboard that
209
+ * nobody ever opened stays protected by the everSeen guard even after the MCP goes quiet.
210
+ */
211
+ export function markKeepAlive() {
212
+ presence.emptySince = null;
213
+ }
214
+ /**
215
+ * Whether a request may buy the process more life. True for our own client and the MCP, false
216
+ * for anything else, so a foreign page cannot postpone auto-close forever.
217
+ *
218
+ * Two accepted proofs, both unforgeable cross-origin without a CORS preflight the foreign
219
+ * origin cannot satisfy: the `X-Radar-Dashboard` header `/shutdown` already requires, or an
220
+ * `application/json` content-type. JSON counts because every MCP version ever published sends
221
+ * it on `/setspec`; requiring only the header would silently strip the keep-alive from an older
222
+ * globally-installed MCP talking to a newer dashboard.
223
+ *
224
+ * The content-type test compares the MIME ESSENCE, never a substring. CORS safelists a
225
+ * content-type by its essence and ignores parameters, so `text/plain; charset=application/json`
226
+ * is a SIMPLE request that any page can send with no preflight while still containing the
227
+ * string "application/json". A substring match there would reopen the exact hole this closes.
228
+ *
229
+ * Exported so the route wiring is directly testable: the decision, not just its effect.
230
+ */
231
+ export function isAuthoredRequest(headers) {
232
+ if (headers["x-radar-dashboard"] === "1")
233
+ return true;
234
+ const contentType = headers["content-type"];
235
+ const value = Array.isArray(contentType) ? contentType[0] : contentType;
236
+ if (typeof value !== "string")
237
+ return false;
238
+ const essence = value.split(";")[0].trim().toLowerCase();
239
+ return essence === "application/json";
240
+ }
241
+ /**
242
+ * One sweep tick: prune stale tab ids, maintain the emptySince marker across the 1->0 / 0->1
243
+ * transitions, and return whether the dashboard should auto-close now. Owns all timestamp
244
+ * bookkeeping and delegates the decision to shouldAutoClose. `now` is injectable so the
245
+ * transition logic is unit-testable with a fake clock. Returns true only on the tick where the
246
+ * grace window has elapsed with no live tabs.
247
+ */
248
+ export function sweepPresence(now = Date.now()) {
249
+ for (const [id, ts] of presence.tabs) {
250
+ if (now - ts > TAB_LIVENESS_MS)
251
+ presence.tabs.delete(id);
252
+ }
253
+ const liveTabs = presence.tabs.size;
254
+ if (liveTabs > 0) {
255
+ presence.emptySince = null; // 0->1 (or still >0): tabs present, not idle
256
+ }
257
+ else if (presence.everSeen && presence.emptySince === null) {
258
+ presence.emptySince = now; // 1->0: just went empty, start the grace clock
259
+ }
260
+ const msSinceEmpty = presence.emptySince === null ? null : now - presence.emptySince;
261
+ return shouldAutoClose(liveTabs, presence.everSeen, msSinceEmpty);
262
+ }
263
+ /** Presence snapshot for tests. */
264
+ export function getPresenceState() {
265
+ return {
266
+ liveTabs: presence.tabs.size,
267
+ everSeen: presence.everSeen,
268
+ emptySince: presence.emptySince,
269
+ };
270
+ }
271
+ /** Reset presence between tests (module state is a process singleton). */
272
+ export function resetPresenceForTest() {
273
+ presence.tabs.clear();
274
+ presence.emptySince = null;
275
+ presence.everSeen = false;
276
+ }
277
+ // Servers already tearing down. Keyed on the server rather than a module flag so the latch
278
+ // scopes to the thing being closed: a second call for the SAME server is suppressed, while a
279
+ // different server (every test builds its own) is unaffected. A module-level boolean would leak
280
+ // one test's shutdown into the next and would need a reset hook the tests must remember.
281
+ const shuttingDown = new WeakSet();
282
+ /**
283
+ * Gracefully shut the dashboard down. Reached by the manual /shutdown route and the auto-close
284
+ * sweep, so the server.close + timeout-fallback exit logic lives in exactly one place. Before
285
+ * tearing down, if a screen recording is live, finalize it: bin.ts's exit-time cleanup SIGKILLs
286
+ * the cast's ffmpeg child, and an ffmpeg killed mid-write leaves an mp4 with no moov atom
287
+ * (unplayable). Awaiting stopRecording writes the moov and closes the file first.
288
+ *
289
+ * That mp4 safety covers THOSE TWO PATHS ONLY. bin.ts also registers this on SIGINT/SIGTERM,
290
+ * but screen.ts's own signal handlers exit synchronously and are registered first, so Ctrl-C
291
+ * never reaches here and a recording killed that way can still be corrupt. Pre-existing gap;
292
+ * see the bin.ts comment at the SIGINT registration for why fixing it means touching screen.ts.
293
+ *
294
+ * A second call for the same server is a no-op: the sweep tick and a manual /shutdown can both
295
+ * fire, and awaiting stopRecording gives the next tick a window to land mid-flight.
296
+ * Deps are injectable so the recording-safety path is testable without spawning ffmpeg or
297
+ * actually exiting the process.
298
+ */
299
+ export async function shutdownDashboard(server, deps = {}) {
300
+ const _getLive = deps.getLive ?? getLive;
301
+ const _stopRecording = deps.stopRecording ?? stopRecording;
302
+ const _exit = deps.exit ?? ((code) => process.exit(code));
303
+ const _log = deps.log ?? ((msg) => console.log(msg));
304
+ if (shuttingDown.has(server))
305
+ return;
306
+ shuttingDown.add(server);
307
+ _log("\nShutting down…");
308
+ const live = _getLive();
309
+ if (live && live.recording) {
310
+ try {
311
+ await _stopRecording(live);
312
+ }
313
+ catch {
314
+ // Best-effort finalize; proceed with shutdown even if the stop failed.
315
+ }
316
+ }
317
+ let done = false;
318
+ let fallback;
319
+ const finish = () => {
320
+ if (done)
321
+ return;
322
+ done = true;
323
+ if (fallback)
324
+ clearTimeout(fallback);
325
+ _exit(0);
326
+ };
327
+ server.close(() => finish());
328
+ // Fallback: force-exit if close() hangs on a lingering keep-alive socket. Unref'd so the
329
+ // timer itself never keeps the process alive against a real shutdown.
330
+ fallback = setTimeout(finish, 2000);
331
+ fallback.unref();
332
+ }
333
+ /**
334
+ * Start the periodic auto-close sweep. Called once by bin.ts AFTER a successful listen bind, not
335
+ * from createServer, so importing this module (or spinning a throwaway server in a test) never
336
+ * arms a timer that could process.exit the test runner. The interval is unref'd so it never
337
+ * keeps the process alive on its own.
338
+ */
339
+ export function startAutoCloseSweep(server) {
340
+ // Escape hatch for anyone whose workflow needs the old always-on lifetime, mirroring
341
+ // SLACK_RADAR_NO_FFMPEG. This changes default process lifetime in a published package, so it
342
+ // needs an off switch that does not require pinning an older version.
343
+ if (process.env.SLACK_RADAR_NO_AUTO_CLOSE === "1")
344
+ return null;
345
+ const timer = setInterval(() => {
346
+ if (sweepPresence(Date.now()))
347
+ void shutdownDashboard(server);
348
+ }, AUTO_CLOSE_SWEEP_MS);
349
+ timer.unref();
350
+ return timer;
351
+ }
352
+ /**
353
+ * Build the dashboard HTTP server. `onShutdown` is the hook the manual /shutdown route fires
354
+ * after answering; it defaults to the real graceful shutdown and is injectable so a test can
355
+ * exercise the route without exiting the process. bin.ts calls createServer() with no args.
356
+ */
357
+ export function createServer(onShutdown) {
147
358
  registerScreenCleanup(); // tear down any live screen cast on process exit/signals
148
359
  const server = http.createServer((req, res) => {
360
+ // One chokepoint for every route: a request whose Host is not this loopback dashboard is a
361
+ // rebound foreign origin, not our client (see isLocalHostHeader). Rejected before routing so
362
+ // no handler has to remember, and so /shutdown in particular cannot be reached that way.
363
+ if (!isLocalHostHeader(req.headers.host)) {
364
+ // Name the remedy in the body. A bare 403 on a URL that used to work reads as a broken
365
+ // dashboard, and the fix (add the hostname you are using) is not guessable.
366
+ sendJson(res, 403, {
367
+ 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.`,
368
+ });
369
+ return;
370
+ }
149
371
  const url = req.url ?? "";
150
372
  const urlPath = url.split("?")[0];
373
+ // Second chokepoint, DEFAULT DENY. A request must prove it came from our own client unless its
374
+ // path is a known read. Host alone is not enough: a page served from a real site can call
375
+ // localhost with no rebinding at all -- a text/plain POST and any GET are CORS simple requests,
376
+ // so no preflight is sent and the Host stays "localhost".
377
+ //
378
+ // This used to be an allowlist of five POST paths, and that shape failed twice in the same
379
+ // commit that introduced it: `/_control/activate` dispatched with startsWith so a suffix missed
380
+ // the exact-match Set, and `/api/clear` plus `/screen/redetect` reach the device on GET and
381
+ // were never listed at all. Enumerating what to protect fails open on everything forgotten, and
382
+ // cannot express prefix or method-agnostic handlers. Enumerating what is safe fails closed: a
383
+ // new route is protected until someone deliberately opens it.
384
+ if (!isOpenToAnyCaller(urlPath, req.method) && !isAuthoredRequest(req.headers)) {
385
+ sendJson(res, 403, {
386
+ 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.`,
387
+ });
388
+ return;
389
+ }
151
390
  if (urlPath === "/" || urlPath === "/index.html") {
152
391
  // The Preact dashboard is the default (and only) UI. The old vanilla dashboard + its
153
392
  // ?next opt-in seam were retired in the flip; index.html IS the Preact shell now.
@@ -170,16 +409,40 @@ export function createServer() {
170
409
  return;
171
410
  }
172
411
  if (url === "/setspec" && req.method === "POST") {
173
- handleSetSpec(req, res);
412
+ handleSetSpec(req, res, isAuthoredRequest(req.headers));
174
413
  return;
175
414
  }
176
- if (url === "/health" && req.method === "GET") {
415
+ if (urlPath === "/health" && req.method === "GET") {
416
+ // Browser tabs ride their presence id on this poll (pollProfile's 5s /health fetch). A
417
+ // request without ?tab= (the MCP-side adopt probe, a plain curl) is just not a presence
418
+ // signal; the response shape is unchanged either way. The same X-Radar-Dashboard header
419
+ // /shutdown requires also gates presence: without it, a plain cross-origin GET (no
420
+ // preflight needed for a simple request) could set everSeen on an MCP-only dashboard or
421
+ // keep one alive forever from any page the user's browser has open -- the same process-
422
+ // kill/keep-alive threat model the header exists to close on /shutdown, reachable through
423
+ // this side door. A custom request header forces a real CORS preflight the foreign origin
424
+ // cannot satisfy. Silently ignoring an unauthenticated ?tab= (not 400ing) keeps a bare curl
425
+ // or an old MCP probe working exactly as before; it just never counts as presence.
426
+ //
427
+ // Deliberately the HEADER ALONE, not isAuthoredRequest. That predicate also accepts an
428
+ // application/json content-type, which exists only to keep older MCP /setspec writes
429
+ // working; on a bodyless GET it proves nothing about the caller. Keep this gate the
430
+ // narrower of the two rather than unifying them.
431
+ if (req.headers["x-radar-dashboard"] === "1") {
432
+ const tab = new URL(url, `http://localhost:${WEB_PORT}`).searchParams.get("tab");
433
+ if (tab)
434
+ touchTab(tab);
435
+ }
177
436
  handleHealth(res);
178
437
  return;
179
438
  }
439
+ if (urlPath === "/shutdown" && req.method === "POST") {
440
+ handleShutdown(req, res, () => (onShutdown ?? shutdownDashboard)(server));
441
+ return;
442
+ }
180
443
  if (urlPath === "/enable" && req.method === "POST") {
181
444
  const serial = new URL(url, `http://localhost:${WEB_PORT}`).searchParams.get("device_serial");
182
- handleEnable(res, serial);
445
+ handleEnable(res, serial, isAuthoredRequest(req.headers));
183
446
  return;
184
447
  }
185
448
  if (url === "/stream" && req.method === "GET") {
@@ -206,6 +469,10 @@ export function createServer() {
206
469
  handleDbQuery(req, res);
207
470
  return;
208
471
  }
472
+ if (url.startsWith("/flags") && req.method === "GET") {
473
+ handleFlags(req, res);
474
+ return;
475
+ }
209
476
  if (url.split("?")[0] === "/prefs" && req.method === "GET") {
210
477
  handlePrefsList(req, res);
211
478
  return;
@@ -222,7 +489,10 @@ export function createServer() {
222
489
  listProfiles(res);
223
490
  return;
224
491
  }
225
- if (url.startsWith("/_control/activate") && req.method === "POST") {
492
+ // Match the exact path, not a prefix. A startsWith here disagreed with the authored-POST
493
+ // guard above (which keys on the exact urlPath), so `/_control/activateXYZ` skipped the guard
494
+ // and still re-armed the device. Any guarded route must match the same way the guard does.
495
+ if (urlPath === "/_control/activate" && req.method === "POST") {
226
496
  const parsed = new URL(url, `http://localhost:${WEB_PORT}`);
227
497
  const userId = parsed.searchParams.get("user_id") ?? undefined;
228
498
  activateRadar(res, userId);
@@ -361,8 +631,10 @@ function readBody(req) {
361
631
  * Persist a spec pushed by the client (a pre-built tab, a filter edit, a chip
362
632
  * cancel) or by an MCP caller. Coerce + validate before writing; a bad spec is
363
633
  * rejected with its reason so the UI can surface it rather than render zeros.
634
+ * `authored` means the caller proved it is our own client or the MCP; only then does the
635
+ * write count as a keep-alive (see below).
364
636
  */
365
- async function handleSetSpec(req, res) {
637
+ async function handleSetSpec(req, res, authored) {
366
638
  const body = await readBody(req);
367
639
  let parsed;
368
640
  try {
@@ -379,12 +651,36 @@ async function handleSetSpec(req, res) {
379
651
  return;
380
652
  }
381
653
  writeSpec(spec);
654
+ // An authored write keeps the dashboard alive with zero open tabs (see markKeepAlive): a human
655
+ // may have closed the tab while the MCP keeps driving a long debugging session. Gated on the
656
+ // same X-Radar-Dashboard header /shutdown and /health presence require, because the body is
657
+ // never content-type checked: a cross-origin POST with a text/plain body is a CORS simple
658
+ // request, so without the gate any page in the user's browser could postpone auto-close
659
+ // forever by pinging this every few minutes. The spec still gets written either way, which
660
+ // keeps a bare curl working; it just does not buy the process more life.
661
+ if (authored)
662
+ markKeepAlive();
382
663
  sendJson(res, 200, {
383
664
  ok: true,
384
665
  url: `http://localhost:${WEB_PORT}`,
385
666
  title: spec.title ?? "",
386
667
  });
387
668
  }
669
+ /**
670
+ * Manual kill. The client's own kill button sets X-Radar-Dashboard: 1; a bare cross-origin
671
+ * POST from any page the user's browser has open cannot set a custom header without a CORS
672
+ * preflight it will fail, so requiring the header is a lightweight CSRF guard on a loopback
673
+ * route that takes the whole process down. Answer BEFORE shutting down so the button's fetch
674
+ * resolves rather than seeing a dropped socket, then fire the shutdown on the next tick.
675
+ */
676
+ function handleShutdown(req, res, fire) {
677
+ if (req.headers["x-radar-dashboard"] !== "1") {
678
+ sendJson(res, 400, { error: "missing X-Radar-Dashboard header" });
679
+ return;
680
+ }
681
+ sendJson(res, 200, { ok: true, stopping: true });
682
+ setTimeout(fire, 0);
683
+ }
388
684
  /**
389
685
  * Always-available device-reachability probe, independent of whether a dashboard
390
686
  * is built. Drives the connection dot even on a blank dashboard. Reuses the same
@@ -407,7 +703,7 @@ function handleHealth(res) {
407
703
  // profile owns the socket (the app that bound first), unlike the host-side activate
408
704
  // guess in getActiveUserId() which can drift. The dashboard shows this so it never
409
705
  // claims a profile you are not actually seeing.
410
- const reply = (device, boundUserId, boundProfile) => {
706
+ const reply = (device, boundUserId, boundProfile, sources) => {
411
707
  if (replied)
412
708
  return;
413
709
  replied = true;
@@ -419,6 +715,8 @@ function handleHealth(res) {
419
715
  boundProfile: boundProfile ?? null,
420
716
  device_serial: selected?.serial ?? null,
421
717
  device_label: selected?.label ?? null,
718
+ // Capture sources the build declares on ping (seam builds only); null on older builds.
719
+ sources: sources ?? null,
422
720
  });
423
721
  };
424
722
  const probe = http.request({
@@ -443,6 +741,7 @@ function handleHealth(res) {
443
741
  const ok = up.statusCode === 200;
444
742
  let uid = null;
445
743
  let profile = null;
744
+ let sources = null;
446
745
  // Only trust the body on a 200. A device 5xx-ing with a stale ping body must NOT
447
746
  // surface a bound profile while device:false — that would let the dashboard show a
448
747
  // confident profile label for an unhealthy device.
@@ -453,12 +752,14 @@ function handleHealth(res) {
453
752
  uid = String(p.android_user_id);
454
753
  if (typeof p.profile === "string")
455
754
  profile = p.profile;
755
+ if (Array.isArray(p.sources))
756
+ sources = p.sources;
456
757
  }
457
758
  catch {
458
759
  // non-JSON / partial body: device is up but we cannot name the profile
459
760
  }
460
761
  }
461
- reply(ok, uid, profile);
762
+ reply(ok, uid, profile, sources);
462
763
  });
463
764
  up.on("error", () => reply(false));
464
765
  });
@@ -469,13 +770,182 @@ function handleHealth(res) {
469
770
  });
470
771
  probe.end();
471
772
  }
773
+ /**
774
+ * The /enable response body for a completed device probe, plus its one side effect: a
775
+ * successful re-arm keeps the dashboard alive (an MCP-driven session can re-enable with no tab
776
+ * open, and that must not let the idle timer fire out from under it).
777
+ *
778
+ * `onEnabled` fires only on a successful probe. The route passes `markKeepAlive` when the
779
+ * request was authored (see isAuthoredRequest) and OMITS it otherwise, so an unauthored caller
780
+ * gets the same body but buys no extra process life. Injected rather than called directly so
781
+ * the keep-alive wiring is testable without a real device probe (handleEnable's ping goes over
782
+ * a real socket to RADAR_HOST:RADAR_PORT, which this function does not touch at all).
783
+ *
784
+ * A failed probe gets guidance, not a bare false: the broadcast landed (or exited 0 with no
785
+ * receiver), so the likely causes are a build without the slack-radar modules or the wrong
786
+ * profile. Mirrors the MCP enable message. Exported for unit testing.
787
+ */
788
+ /**
789
+ * Which keep-alive hook /enable hands to enableResultBody: the real one for an authored request,
790
+ * none otherwise. Its own function purely so a test can assert the CHOICE. Asserting the effect
791
+ * through the route cannot cover this — handleEnable's device probe fails with no hardware, which
792
+ * short-circuits before the hook is ever consulted, so a route-level test passes either way (a
793
+ * mutation deleting the gate survived the whole suite before this existed).
794
+ */
795
+ export function keepAliveHookFor(authored) {
796
+ return authored ? markKeepAlive : undefined;
797
+ }
798
+ // Reads the dashboard serves to any local caller. Everything NOT matching is treated as
799
+ // state-changing and needs proof it came from our own client (see isOpenToAnyCaller).
800
+ //
801
+ // Two rules for adding to this list, both learned from a real bypass:
802
+ // 1. It must be genuinely side-effect free. /api/clear looks like a read and wipes the device.
803
+ // 2. It must be reachable ONLY by the shape listed here. A prefix entry opens every path under
804
+ // it, so `/api/` cannot be blanket-opened while /api/clear lives behind the same proxy.
805
+ const READ_ONLY_EXACT = new Set([
806
+ "/",
807
+ "/index.html",
808
+ "/health",
809
+ "/spec",
810
+ "/stream", // EventSource cannot set headers, so this must stay open
811
+ "/backfill",
812
+ "/detail",
813
+ "/dbs", // only lists database names; no pull
814
+ // NOT /dbtables and NOT /dbquery. Both reach pullDatabase, which mkdirs a temp dir and writes a
815
+ // multi-MB PLAINTEXT copy of the on-device message store (plus -wal/-shm) to host disk;
816
+ // /dbtables?refresh=1 re-pulls unconditionally. They read like a listing and a select, but each
817
+ // is a data-exposure step and a repeatable multi-MB adb pull, so both need proof of origin.
818
+ // queryDatabase pulls too when no local copy exists (db.ts: `if (!existsSync(local)) await
819
+ // pullDatabase(...)`), so gating only /dbtables would leave the same pull reachable.
820
+ "/flags",
821
+ "/prefs",
822
+ "/prefsread",
823
+ "/prefssearch",
824
+ "/screen/caps",
825
+ "/screen/shot", // <img src> cannot set a header
826
+ "/screen/stream", // <img src> live MJPEG cast, same
827
+ "/_control/profiles",
828
+ "/_control/devices",
829
+ ]);
830
+ // Path PREFIXES that are read-only for their whole subtree. Kept tiny and audited: anything added
831
+ // here opens every path beneath it forever. These two serve the dashboard's own static bundle.
832
+ // The server matches these with startsWith, so the guard has to as well or a real request 403s.
833
+ // /screen/download/<file> serves a finished recording the user asked to save.
834
+ const READ_ONLY_PREFIXES = ["/next/", "/vendor/", "/screen/download"];
835
+ // Device-proxy reads. `/api/` as a whole is NOT safe (/api/clear wipes the device buffers), so the
836
+ // readable sources are named and everything else under /api/ falls through to the guard.
837
+ // Only names the device actually serves today (verified live: /api/prefs and /api/session 404).
838
+ // A dead entry here is worse than useless -- the device dispatches /api/<name> to any RadarPlugin
839
+ // claiming that name, and plugin handlers carry no side-effect guarantee, so listing a name nothing
840
+ // serves pre-authorizes whatever future plugin takes it.
841
+ const READ_ONLY_API_SOURCES = [
842
+ "ping",
843
+ "network",
844
+ "rtm",
845
+ "clogs",
846
+ "traces",
847
+ "feature_flags",
848
+ "search",
849
+ ];
850
+ /**
851
+ * Whether the dashboard serves this request without proof of origin. Everything else is refused
852
+ * unless authored. Exported so a test can drive the decision directly, and so the open surface is
853
+ * reviewable in one place instead of inferred from twenty route branches.
854
+ *
855
+ * Reads are open by path. Writes are closed with exactly two named exceptions, both justified
856
+ * below. A POST to a read path is NOT open: only GET and HEAD can ever be reads.
857
+ */
858
+ export function isOpenToAnyCaller(urlPath, method) {
859
+ // The two deliberate write carve-outs, POST only. /setspec is the one write anyone may make: it
860
+ // rewrites the local dashboard view, driving it with a bare `curl -X POST` is supported, and its
861
+ // keep-alive side effect is gated separately (see handleSetSpec). /shutdown carries its own
862
+ // header check inside handleShutdown, which answers before exiting.
863
+ //
864
+ // Pinned to POST because that is the only method either route dispatches. Allowing any method
865
+ // would repeat the mistake this whole guard exists to fix: a future non-POST handler on one of
866
+ // these paths would be born open.
867
+ if (method === "POST" && (urlPath === "/setspec" || urlPath === "/shutdown"))
868
+ return true;
869
+ if (method !== "GET" && method !== "HEAD")
870
+ return false;
871
+ if (READ_ONLY_EXACT.has(urlPath))
872
+ return true;
873
+ if (READ_ONLY_PREFIXES.some((prefix) => urlPath.startsWith(prefix)))
874
+ return true;
875
+ // /api/<source> and /api/<source>/<id> are reads; /api/clear and anything unrecognized are not.
876
+ const apiMatch = /^\/api\/([^/]+)(?:\/[^/]*)?$/.exec(urlPath);
877
+ return apiMatch !== null && READ_ONLY_API_SOURCES.includes(apiMatch[1]);
878
+ }
879
+ /**
880
+ * Whether a request's Host names this loopback dashboard. The listener is bound to 127.0.0.1, but
881
+ * that only limits which interface accepts the TCP connection: a browser resolving an attacker's
882
+ * domain to 127.0.0.1 (DNS rebinding) connects locally and arrives with that domain in Host. The
883
+ * page is then same-origin by the browser's reckoning, so it can set any header it likes and the
884
+ * X-Radar-Dashboard guard buys nothing against it. Checking Host is what makes the loopback bind
885
+ * an actual boundary, and it matters most for /shutdown, which kills the process.
886
+ *
887
+ * Accepts localhost / 127.0.0.1 / [::1] / ::1 / 0.0.0.0, with or without a port, and a missing
888
+ * Host (HTTP/1.0 and a bare socket client send none; those cannot be a rebound browser).
889
+ *
890
+ * SLACK_RADAR_ALLOWED_HOSTS adds names for the setups that reach the dashboard by something other
891
+ * than localhost -- a /etc/hosts alias, a container or Codespaces forwarded URL, a LAN hostname.
892
+ * Comma-separated, `host` or `host:port`; a bare name matches on any port. Without it those users
893
+ * would just get a 403 with nothing to do about it.
894
+ */
895
+ export function isLocalHostHeader(host, allowedHosts = process.env.SLACK_RADAR_ALLOWED_HOSTS) {
896
+ const value = Array.isArray(host) ? host[0] : host;
897
+ if (value === undefined || value === "")
898
+ return true;
899
+ const raw = value.trim().toLowerCase();
900
+ // Strip the port to compare the name alone. Three shapes to keep straight:
901
+ // host:8100 -> strip
902
+ // [::1]:8100 -> strip (the brackets survive, which is what we compare against)
903
+ // ::1 -> do NOT strip; a bare IPv6 literal is all colons, and stripping the last
904
+ // group would leave ":" and reject a legitimate loopback request.
905
+ // So only strip when the value is bracketed, or when it holds at most one colon.
906
+ const bracketed = raw.startsWith("[");
907
+ const name = bracketed || raw.split(":").length <= 2 ? raw.replace(/:\d+$/, "") : raw;
908
+ if (name === "localhost" ||
909
+ name === "127.0.0.1" ||
910
+ name === "0.0.0.0" ||
911
+ name === "[::1]" ||
912
+ name === "::1") {
913
+ return true;
914
+ }
915
+ // Operator-listed names. Both sides are compared with and without their port, so an entry
916
+ // matches whichever shape actually arrives: `radar.local` admits `radar.local:8100`, and
917
+ // `radar.local:8100` admits a bare `radar.local` (which is what a browser sends on 80/443,
918
+ // the forwarded-URL case this env var exists for).
919
+ for (const entry of (allowedHosts ?? "").split(",")) {
920
+ const allowed = entry.trim().toLowerCase();
921
+ if (allowed === "")
922
+ continue;
923
+ const allowedName = allowed.startsWith("[") || allowed.split(":").length <= 2
924
+ ? allowed.replace(/:\d+$/, "")
925
+ : allowed;
926
+ if (allowed === raw || allowed === name || allowedName === raw || allowedName === name) {
927
+ return true;
928
+ }
929
+ }
930
+ return false;
931
+ }
932
+ export function enableResultBody(enabled, onEnabled) {
933
+ if (enabled) {
934
+ onEnabled?.();
935
+ return { enabled };
936
+ }
937
+ return {
938
+ enabled,
939
+ 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?",
940
+ };
941
+ }
472
942
  /**
473
943
  * Re-arm Radar from the dashboard. Mirrors the recovery sequence: reset cached
474
944
  * forward state, rebuild a clean adb forward, and re-broadcast activation, so the
475
945
  * user never has to drop to a terminal. Delegates entirely to AndroidTransport;
476
946
  * no adb shelling here.
477
947
  */
478
- function handleEnable(res, deviceSerial) {
948
+ function handleEnable(res, deviceSerial, authored) {
479
949
  transport.resetState();
480
950
  // A reconnect may be a different device / re-armed profile, so drop the cached DB user
481
951
  // set + sqlite path; the next /dbs re-detects the profiles fresh.
@@ -547,15 +1017,7 @@ function handleEnable(res, deviceSerial) {
547
1017
  if (replied)
548
1018
  return;
549
1019
  replied = true;
550
- // A failed probe gets guidance, not a bare false: the broadcast landed (or
551
- // exited 0 with no receiver), so the likely causes are a build without the
552
- // radar modules or the wrong profile. Mirrors the MCP enable message.
553
- sendJson(res, 200, enabled
554
- ? { enabled }
555
- : {
556
- enabled,
557
- 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?",
558
- });
1020
+ sendJson(res, 200, enableResultBody(enabled, keepAliveHookFor(authored)));
559
1021
  };
560
1022
  const probe = http.request({
561
1023
  host: RADAR_HOST,
@@ -695,6 +1157,47 @@ function handleDetail(req, res) {
695
1157
  });
696
1158
  upstream.end();
697
1159
  }
1160
+ // --- Feature flags (source: "flags") ---
1161
+ //
1162
+ // Proxy the dashboard's /flags to the device's feature-flag RadarPlugin at GET
1163
+ // /api/feature_flags, forwarding the ?overridden= filter. The plugin returns the COMPLETE set
1164
+ // (no paging), so nothing to inject. Response is buffered so a device error becomes a clean 200
1165
+ // {error} the Feature Flags tab renders in-place rather than a half-streamed body.
1166
+ //
1167
+ // Device list shape: { feature_flags: [{ key, enabled, is_overridden }], total }. `enabled` is
1168
+ // the effective value (override if set, else the server value). Live changes arrive separately
1169
+ // as `feature_flag` frames on /api/stream (the on-device observer). Builds predating the plugin
1170
+ // 404, surfaced as a friendly message client-side.
1171
+ function handleFlags(req, res) {
1172
+ const u = new URL(req.url ?? "", `http://localhost:${WEB_PORT}`);
1173
+ const path = `/api/feature_flags${u.search}`;
1174
+ const upstream = http.request({ host: RADAR_HOST, port: RADAR_PORT, path, method: "GET", timeout: 4000 }, (up) => {
1175
+ let body = "";
1176
+ up.on("data", (c) => (body += c));
1177
+ up.on("end", () => {
1178
+ try {
1179
+ const j = JSON.parse(body);
1180
+ if (!Array.isArray(j.feature_flags)) {
1181
+ sendJson(res, 200, {
1182
+ error: j.error ? friendlyFeatureFlagError(j.error) : "Unexpected response from device.",
1183
+ feature_flags: [],
1184
+ });
1185
+ return;
1186
+ }
1187
+ sendJson(res, 200, j);
1188
+ }
1189
+ catch {
1190
+ sendJson(res, 200, { error: "Could not parse device response.", feature_flags: [] });
1191
+ }
1192
+ });
1193
+ });
1194
+ upstream.on("error", () => sendJson(res, 200, { error: "Device unreachable. Is Radar armed?", feature_flags: [] }));
1195
+ upstream.on("timeout", () => {
1196
+ upstream.destroy();
1197
+ sendJson(res, 200, { error: "Device request timed out.", feature_flags: [] });
1198
+ });
1199
+ upstream.end();
1200
+ }
698
1201
  // --- On-device SQLite browser (source: "db") ---
699
1202
  //
700
1203
  // These delegate to shared/db.ts (run-as + host sqlite3, read-only). Each computes its