@slack/radar-mcp 1.21.0 → 1.23.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 (87) hide show
  1. package/README.md +114 -18
  2. package/dist/mcp/api-paths.d.ts +2 -2
  3. package/dist/mcp/api-paths.js +4 -19
  4. package/dist/mcp/dashboard-identity.d.ts +6 -0
  5. package/dist/mcp/dashboard-identity.js +11 -0
  6. package/dist/mcp/index.js +210 -145
  7. package/dist/mcp/logs-result.d.ts +1 -0
  8. package/dist/mcp/logs-result.js +1 -0
  9. package/dist/mcp/radar-export-get.d.ts +30 -0
  10. package/dist/mcp/radar-export-get.js +49 -0
  11. package/dist/mcp/radar-http.d.ts +22 -0
  12. package/dist/mcp/radar-http.js +61 -0
  13. package/dist/mcp/radar-response.d.ts +5 -1
  14. package/dist/mcp/radar-response.js +8 -3
  15. package/dist/mcp/session-backfill.js +3 -4
  16. package/dist/mcp/session-enable.d.ts +15 -0
  17. package/dist/mcp/session-enable.js +268 -19
  18. package/dist/mcp/snapshot.js +42 -26
  19. package/dist/mcp/sources-gate.js +6 -0
  20. package/dist/mcp/stale-dashboard.d.ts +23 -0
  21. package/dist/mcp/stale-dashboard.js +122 -0
  22. package/dist/mcp/switchboard-spool.d.ts +12 -0
  23. package/dist/mcp/switchboard-spool.js +107 -0
  24. package/dist/mcp/switchboard-tools.d.ts +9 -0
  25. package/dist/mcp/switchboard-tools.js +144 -6
  26. package/dist/mcp/test-cases.d.ts +14 -0
  27. package/dist/mcp/test-cases.js +77 -0
  28. package/dist/mcp/test-runs-tools.d.ts +8 -0
  29. package/dist/mcp/test-runs-tools.js +95 -0
  30. package/dist/mcp/tools.d.ts +4 -1
  31. package/dist/mcp/tools.js +101 -21
  32. package/dist/mcp/web-child-env.d.ts +4 -1
  33. package/dist/mcp/web-child-env.js +4 -1
  34. package/dist/shared/android.d.ts +44 -0
  35. package/dist/shared/android.js +234 -24
  36. package/dist/shared/constants.d.ts +9 -4
  37. package/dist/shared/constants.js +9 -4
  38. package/dist/shared/feature-flags.d.ts +1 -0
  39. package/dist/shared/feature-flags.js +1 -0
  40. package/dist/shared/ios-logs.d.ts +10 -0
  41. package/dist/shared/ios-logs.js +91 -0
  42. package/dist/shared/ios.d.ts +25 -2
  43. package/dist/shared/ios.js +157 -3
  44. package/dist/{web → shared}/log-session.d.ts +45 -31
  45. package/dist/shared/log-session.js +300 -0
  46. package/dist/shared/logcat-capture.js +17 -1
  47. package/dist/shared/radar-request-raw.d.ts +7 -0
  48. package/dist/shared/radar-request-raw.js +89 -0
  49. package/dist/shared/radar-token.d.ts +25 -0
  50. package/dist/shared/radar-token.js +164 -0
  51. package/dist/shared/stream.d.ts +3 -0
  52. package/dist/shared/stream.js +107 -15
  53. package/dist/shared/switchboard-host-store.d.ts +21 -0
  54. package/dist/shared/switchboard-host-store.js +166 -0
  55. package/dist/shared/switchboard-note.d.ts +15 -0
  56. package/dist/shared/switchboard-note.js +92 -0
  57. package/dist/shared/switchboard-report-file.d.ts +5 -0
  58. package/dist/shared/switchboard-report-file.js +26 -0
  59. package/dist/shared/switchboard-report.d.ts +20 -0
  60. package/dist/shared/switchboard-report.js +406 -0
  61. package/dist/shared/switchboard.d.ts +111 -2
  62. package/dist/shared/switchboard.js +436 -3
  63. package/dist/shared/transport.d.ts +49 -3
  64. package/dist/shared/version.d.ts +2 -0
  65. package/dist/shared/version.js +18 -0
  66. package/dist/shared/wire.d.ts +14 -1
  67. package/dist/web/install-app.d.ts +75 -8
  68. package/dist/web/install-app.js +330 -67
  69. package/dist/web/macapp/RadarApp.swift +487 -23
  70. package/dist/web/public/index.html +51 -9
  71. package/dist/web/public/next/app.js +33 -18
  72. package/dist/web/public/next/feed.js +102 -15
  73. package/dist/web/public/next/flags.js +3 -0
  74. package/dist/web/public/next/inspector.js +69 -3
  75. package/dist/web/public/next/prefs.js +5 -2
  76. package/dist/web/public/next/registry.js +18 -5
  77. package/dist/web/public/next/store.js +455 -29
  78. package/dist/web/public/next/switchboard-note.js +93 -0
  79. package/dist/web/public/next/toast.js +9 -5
  80. package/dist/web/public/next/voice-model.js +215 -35
  81. package/dist/web/public/next/voice.js +173 -18
  82. package/dist/web/server.d.ts +15 -11
  83. package/dist/web/server.js +690 -168
  84. package/dist/web/spec.d.ts +2 -1
  85. package/dist/web/spec.js +2 -1
  86. package/package.json +2 -2
  87. package/dist/web/log-session.js +0 -166
@@ -1,20 +1,24 @@
1
1
  import http from "http";
2
- import { SWITCHBOARD_KIND, SWITCHBOARD_BACKFILL_DEADLINE_MS, SWITCHBOARD_BACKFILL_SESSIONS, newestSwitchboardSessionIds, switchboardListPath, switchboardPageEvents, switchboardSessionPath, } from "../shared/switchboard.js";
2
+ import { SWITCHBOARD_KIND, SWITCHBOARD_BACKFILL_DEADLINE_MS, SWITCHBOARD_BACKFILL_SESSIONS, SWITCHBOARD_EXPORT_SAFETY_CAP_BYTES, SWITCHBOARD_EXPORT_IDLE_MS, SWITCHBOARD_EXPORT_OVERALL_MS, assembleSwitchboardExport, newestSwitchboardSessionIds, nonNegativeIntArg, switchboardListPath, switchboardPageEvents, switchboardSessionPath, } from "../shared/switchboard.js";
3
+ import { buildSwitchboardReport, switchboardReportNotes } from "../shared/switchboard-report.js";
4
+ import { writeSwitchboardReportFile } from "../shared/switchboard-report-file.js";
5
+ import { clearSwitchboardHostStore, getHostSwitchboardRecords, newestHostSwitchboardSessionId, recordSwitchboardStreamed } from "../shared/switchboard-host-store.js";
3
6
  import fs from "fs";
4
7
  import os from "os";
5
8
  import path from "path";
6
- import { spawn } from "child_process";
9
+ import { StringDecoder } from "string_decoder";
7
10
  import { fileURLToPath } from "url";
8
11
  import { resolveAdbPath } from "../shared/android.js";
9
12
  import { createTransport } from "../shared/platform.js";
10
13
  import { planReconnect } from "../shared/stream.js";
11
14
  import { createDashboardScreenController, } from "../shared/dashboard-screen.js";
12
- import { RADAR_HOST, RADAR_PORT, RADAR_VERSION, WEB_PORT_DEFAULT } from "../shared/constants.js";
15
+ import { ENABLE_PING_WAITS_MS, RADAR_HOST, RADAR_PORT, RADAR_VERSION, WEB_PORT_DEFAULT } from "../shared/constants.js";
16
+ import { radarRequestRaw } from "../shared/radar-request-raw.js";
17
+ import { TokenFileError, clearRadarTokenCache, radarTokenHeaderFor, tokenFileMessage, unauthorizedMessageFor } from "../shared/radar-token.js";
13
18
  import { friendlyFeatureFlagError } from "../shared/feature-flags.js";
14
19
  import { deviceServerSilentError, readProcessState, } from "../shared/enable-diagnosis.js";
15
20
  import { cleanupPulledDatabases, initializeDatabasePath, listDatabases, pullDatabase, pulledSize, queryDatabase, resetDbState, availableUsers, } from "../shared/db.js";
16
21
  import { listPrefsFiles, readPrefsFile, parsePrefsXml, searchPrefs, } from "../shared/prefs.js";
17
- import { LogSession } from "./log-session.js";
18
22
  import { BLANK_SPEC, coerceSpec, validateSpec } from "./spec.js";
19
23
  import { grantScreenConsent, hasScreenConsent, detectDisplay, startLive, addViewer, removeViewer, reapLiveIfIdle, primeIfNeeded, capturePath, ffmpegInstallHint, SCREEN_BOUNDARY, } from "../shared/screen.js";
20
24
  // The disk half of the screen reap, imported from the module that owns the only implementation of
@@ -78,6 +82,8 @@ function mcpSeenPath() {
78
82
  return path.join(os.homedir(), ".slack-radar", "mcp-last-seen.json");
79
83
  }
80
84
  const transport = createTransport();
85
+ // When the forward is down nothing of ours is on the port, so the secret stays home.
86
+ const deviceTokenHeader = (forwarded) => forwarded ? radarTokenHeaderFor(transport, "dashboard") : {};
81
87
  const dashboardScreen = createDashboardScreenController(transport);
82
88
  // The serial this process last did screen housekeeping for: seeded by boot's orphan reap
83
89
  // (armDevice) and advanced by every /enable that pins real hardware. Kept here rather than
@@ -142,9 +148,9 @@ function reapScreenOnce(serial, clearFilesWithoutDevice) {
142
148
  }
143
149
  // The ONE ceiling for every device ping this file makes (boot-arm, /health, /enable all go
144
150
  // through pingDevice). A shorter one turns ordinary latency into a false negative: boot would
145
- // read a live-but-slow session as absent, and /health would flap the connection dot. Observed
146
- // latency reaches past 2.2 seconds against an unauthorized device, so this must stay above that.
147
- const PING_PROBE_MS = 2500;
151
+ // read a live-but-slow session as absent, and /health would flap the connection dot. A slow 401
152
+ // over adb must not read as silence, so this stays above the observed 2.2-second latency.
153
+ const PING_PROBE_MS = 4000;
148
154
  // Reassert the shared adb forward before every HTTP-based device read. Mirrors
149
155
  // mcp/index.ts's forwardForRead(): this process's own portForwarded cache cannot see a
150
156
  // repoint made by a SEPARATE process (the MCP server) sharing the same host-global
@@ -153,20 +159,16 @@ const PING_PROBE_MS = 2500;
153
159
  function forwardForRead() {
154
160
  return transport.reassertForward?.() ?? transport.ensureForward();
155
161
  }
156
- // One session-long logcat capture shared across every dashboard stream
157
- // connection. The device cannot replay logcat history to us, so the dashboard
158
- // keeps its own bounded session ring here and replays it to each newly opened
159
- // stream — this is what makes a tab switch (which reopens /stream) show the full
160
- // log history instead of only lines that arrive after the reconnect, matching
161
- // how Android Studio retains logcat for the whole session. Spawn + parse are
162
- // injected so the capture logic is unit-testable without a real `adb logcat`.
163
- // Only spawn when the transport supports local device access (i.e. Android).
164
- const logSession = transport.supportsLocalFileAccess
165
- ? new LogSession(() => spawn(resolveAdbPath() ?? "adb", ["logcat", "-v", "threadtime", "-T", "1"], {
166
- stdio: ["ignore", "pipe", "ignore"],
167
- }), (line) => parseLogcat(line))
168
- : null;
169
- // Kill the persistent logcat child on process exit so it does not orphan when the
162
+ // One session-long host log capture shared across every dashboard stream
163
+ // connection. Neither adb logcat nor the Simulator's unified log can replay history
164
+ // to us, so the dashboard keeps its own bounded session ring here and replays it to
165
+ // each newly opened stream — this is what makes a tab switch (which reopens /stream)
166
+ // show the full log history instead of only lines that arrive after the reconnect,
167
+ // matching how Android Studio retains logcat for the whole session. The transport
168
+ // owns the platform-specific child and parser (adb logcat on Android,
169
+ // `simctl spawn … log stream` on iOS); the server only consumes the LogSession.
170
+ const logSession = transport.logSession ?? null;
171
+ // Kill the persistent capture child on process exit so it does not orphan when the
170
172
  // dashboard is spawned and later terminated by the open_radar_dashboard MCP tool.
171
173
  logSession?.registerCleanup();
172
174
  // By design the capture is NOT stopped when the last log stream disconnects (e.g.
@@ -660,7 +662,7 @@ export async function shutdownDashboard(server, deps = {}) {
660
662
  * session read identically through the forward), so the boot chain resolves it against the
661
663
  * device's own socket table instead of guessing at this layer.
662
664
  */
663
- function pingDevice(timeoutMs = PING_PROBE_MS) {
665
+ function pingDevice(forwarded, timeoutMs = PING_PROBE_MS) {
664
666
  return new Promise((resolve) => {
665
667
  let settled = false;
666
668
  const done = (state, status = null, body = "") => {
@@ -669,7 +671,14 @@ function pingDevice(timeoutMs = PING_PROBE_MS) {
669
671
  settled = true;
670
672
  resolve({ state, status, body });
671
673
  };
672
- const req = http.request({ host: RADAR_HOST, port: RADAR_PORT, path: "/api/ping", method: "GET", timeout: timeoutMs }, (up) => {
674
+ const req = http.request({
675
+ host: RADAR_HOST,
676
+ port: RADAR_PORT,
677
+ path: "/api/ping",
678
+ method: "GET",
679
+ timeout: timeoutMs,
680
+ headers: deviceTokenHeader(forwarded),
681
+ }, (up) => {
673
682
  // The ping body is the device's own small JSON status. Bound the accumulation anyway so a
674
683
  // misbehaving local endpoint cannot grow it without limit; a truncated body simply fails
675
684
  // the caller's JSON.parse, which every caller treats as "no extra detail".
@@ -690,6 +699,27 @@ function pingDevice(timeoutMs = PING_PROBE_MS) {
690
699
  req.end();
691
700
  });
692
701
  }
702
+ function parsedPingBody(body) {
703
+ try {
704
+ const parsed = JSON.parse(body);
705
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)
706
+ ? parsed
707
+ : null;
708
+ }
709
+ catch {
710
+ return null;
711
+ }
712
+ }
713
+ function pingMatchesTransport(ping) {
714
+ if (!transport.acceptsRadarPeer)
715
+ return true;
716
+ const parsed = parsedPingBody(ping.body);
717
+ return parsed !== null && transport.acceptsRadarPeer(parsed);
718
+ }
719
+ // Without the token header, the device never saw this process's token.
720
+ function refusalSentence(forwarded) {
721
+ return unauthorizedMessageFor(forwarded ? transport : null, "dashboard");
722
+ }
693
723
  /**
694
724
  * Arm Radar once, at dashboard boot, so a launch against a freshly restarted app does not land on
695
725
  * "waiting for device" until the human finds the Reconnect button. Called by bin.ts from the listen
@@ -824,7 +854,7 @@ async function armDevice() {
824
854
  // default, which can be SHORTER than one another process explicitly asked for. An MCP session that
825
855
  // armed for 30 minutes would have its idle window silently cut to the default by someone merely
826
856
  // opening a dashboard to look, with no error surfaced to either side.
827
- if ((await pingDevice()).state === "armed")
857
+ if ((await pingDevice(true)).state === "armed")
828
858
  return;
829
859
  // Anything else the ping says is inconclusive HERE, including a reset: the probe travels the
830
860
  // adb forward, and the host adb server accepts every connection before discovering whether the
@@ -845,7 +875,8 @@ async function armDevice() {
845
875
  }
846
876
  // A device WAS reachable and the broadcast still failed, which is worth printing. Silence here is
847
877
  // what left people staring at "waiting for device" with no idea a launch had already tried.
848
- const error = transport.getLastActivateError?.() ?? null;
878
+ const tokenFileError = transport.getLastActivateTokenFileError?.() ?? null;
879
+ const error = tokenFileError ? tokenFileMessage(tokenFileError, "dashboard") : transport.getLastActivateError?.() ?? null;
849
880
  if (error)
850
881
  console.log(`Radar could not be armed at startup: ${error}`);
851
882
  }
@@ -874,6 +905,8 @@ export function startAutoCloseSweep(server) {
874
905
  * exercise the route without exiting the process. bin.ts calls createServer() with no args.
875
906
  */
876
907
  export function createServer(onShutdown) {
908
+ // Catches exports left behind by a crash or a tab closed before its download ran.
909
+ sweepStaleSwitchboardWebExports();
877
910
  const server = http.createServer((req, res) => {
878
911
  // One chokepoint for every route: a request whose Host is not this loopback dashboard is a
879
912
  // rebound foreign origin, not our client (see isLocalHostHeader). Rejected before routing so
@@ -1028,22 +1061,38 @@ export function createServer(onShutdown) {
1028
1061
  handleStream(req, res);
1029
1062
  return;
1030
1063
  }
1031
- if (url.startsWith("/backfill") || url.startsWith("/detail") || url.startsWith("/api/") ||
1032
- url.startsWith("/dbs") || url.startsWith("/dbtables") || url.startsWith("/dbquery") ||
1033
- url.startsWith("/flags") || url.split("?")[0] === "/prefs" ||
1034
- url.startsWith("/prefsread") || url.startsWith("/prefssearch")) {
1035
- if (!transport.supportsLocalFileAccess) {
1036
- sendJson(res, 400, { error: `Not supported on ${transport.platform}` });
1064
+ const radarHttpRoute = url.startsWith("/backfill") || url.startsWith("/detail") ||
1065
+ url.startsWith("/api/") || url.startsWith("/flags");
1066
+ if (radarHttpRoute) {
1067
+ if (!transport.supportsRadarHttpTools) {
1068
+ sendJson(res, 400, { error: `Radar HTTP tools are not supported on ${transport.platform}` });
1037
1069
  return;
1038
1070
  }
1039
- }
1040
- if (url.startsWith("/backfill")) {
1041
- handleBackfill(req, res);
1071
+ // Health, enable and the stream already check who answers the shared host port; these
1072
+ // routes read device data straight from it, so they need the same check first.
1073
+ if (transport.acceptsRadarPeer) {
1074
+ // Port ownership is unknown; keep the probe tokenless and let the route reassert for itself.
1075
+ void pingDevice(false).then((peer) => {
1076
+ if (peer.state === "armed" && !pingMatchesTransport(peer)) {
1077
+ sendJson(res, 502, {
1078
+ error: `The Radar listener on the shared host port does not belong to the selected ${transport.platform} app.`,
1079
+ });
1080
+ return;
1081
+ }
1082
+ routeRadarHttp(req, res, url, urlPath);
1083
+ });
1084
+ return;
1085
+ }
1086
+ routeRadarHttp(req, res, url, urlPath);
1042
1087
  return;
1043
1088
  }
1044
- if (url.startsWith("/detail")) {
1045
- handleDetail(req, res);
1046
- return;
1089
+ if (url.startsWith("/dbs") || url.startsWith("/dbtables") || url.startsWith("/dbquery") ||
1090
+ url.split("?")[0] === "/prefs" || url.startsWith("/prefsread") ||
1091
+ url.startsWith("/prefssearch")) {
1092
+ if (!transport.supportsLocalFileAccess) {
1093
+ sendJson(res, 400, { error: `Not supported on ${transport.platform}` });
1094
+ return;
1095
+ }
1047
1096
  }
1048
1097
  if (url.startsWith("/dbs") && req.method === "GET") {
1049
1098
  handleDbList(req, res);
@@ -1057,10 +1106,6 @@ export function createServer(onShutdown) {
1057
1106
  handleDbQuery(req, res);
1058
1107
  return;
1059
1108
  }
1060
- if (url.startsWith("/flags") && req.method === "GET") {
1061
- handleFlags(req, res);
1062
- return;
1063
- }
1064
1109
  if (url.split("?")[0] === "/prefs" && req.method === "GET") {
1065
1110
  handlePrefsList(req, res);
1066
1111
  return;
@@ -1090,12 +1135,22 @@ export function createServer(onShutdown) {
1090
1135
  listDevices(res);
1091
1136
  return;
1092
1137
  }
1093
- if (url.startsWith("/screen/")) {
1094
- handleScreen(req, res);
1138
+ if (urlPath === "/switchboard/export" && req.method === "POST") {
1139
+ // Backstop so an unexpected throw answers 500 instead of hanging. No "Export failed:"
1140
+ // prefix: the toast supplies it.
1141
+ void handleSwitchboardExport(req, res).catch((e) => {
1142
+ if (!res.headersSent && !res.writableEnded) {
1143
+ sendJson(res, 500, { error: e?.message || "internal error" });
1144
+ }
1145
+ });
1095
1146
  return;
1096
1147
  }
1097
- if (url.startsWith("/api/")) {
1098
- proxyToRadar(req, res);
1148
+ if (urlPath === "/switchboard/download" && req.method === "GET") {
1149
+ handleSwitchboardDownload(req, res);
1150
+ return;
1151
+ }
1152
+ if (url.startsWith("/screen/")) {
1153
+ handleScreen(req, res);
1099
1154
  return;
1100
1155
  }
1101
1156
  res.writeHead(404);
@@ -1103,6 +1158,36 @@ export function createServer(onShutdown) {
1103
1158
  });
1104
1159
  return server;
1105
1160
  }
1161
+ // The device-data routes, dispatched after the capability and peer checks in the request
1162
+ // handler. A route with the wrong method falls through to the same 404 as an unknown path.
1163
+ function routeRadarHttp(req, res, url, urlPath) {
1164
+ if (url.startsWith("/backfill")) {
1165
+ handleBackfill(req, res);
1166
+ return;
1167
+ }
1168
+ if (url.startsWith("/detail")) {
1169
+ handleDetail(req, res);
1170
+ return;
1171
+ }
1172
+ if (url.startsWith("/flags")) {
1173
+ if (req.method === "GET") {
1174
+ handleFlags(req, res);
1175
+ return;
1176
+ }
1177
+ }
1178
+ else if (urlPath === "/api/clear") {
1179
+ // A clear is a session boundary, like disable and a device switch.
1180
+ clearSwitchboardHostStore();
1181
+ proxyToRadar(req, res);
1182
+ return;
1183
+ }
1184
+ else {
1185
+ proxyToRadar(req, res);
1186
+ return;
1187
+ }
1188
+ res.writeHead(404);
1189
+ res.end("Not found");
1190
+ }
1106
1191
  function serveIndex(res) {
1107
1192
  try {
1108
1193
  const html = fs.readFileSync(INDEX_PATH);
@@ -1196,7 +1281,9 @@ function serveStatic(clean, res, isHead, ifNoneMatch) {
1196
1281
  }
1197
1282
  return true;
1198
1283
  }
1199
- function sendJson(res, status, payload) {
1284
+ function sendJson(res, status, payload,
1285
+ // Spread first, so a caller cannot override Content-Type or Content-Length.
1286
+ headers) {
1200
1287
  // A device probe can fire both "end" and "error"/"timeout" for one request, so its
1201
1288
  // callbacks may call sendJson twice. The second writeHead would throw
1202
1289
  // ERR_HTTP_HEADERS_SENT and crash the whole process. Swallow the duplicate.
@@ -1212,19 +1299,41 @@ function sendJson(res, status, payload) {
1212
1299
  // which is why it belongs in this helper rather than in one route that happened to need it.
1213
1300
  const body = JSON.stringify(payload);
1214
1301
  res.writeHead(status, {
1302
+ ...headers,
1215
1303
  "Content-Type": "application/json; charset=utf-8",
1304
+ "X-Content-Type-Options": "nosniff",
1216
1305
  "Content-Length": Buffer.byteLength(body),
1217
1306
  });
1218
1307
  res.end(body);
1219
1308
  }
1220
- function readBody(req) {
1221
- return new Promise((resolve) => {
1309
+ class BodyTooLargeError extends Error {
1310
+ }
1311
+ function readBody(req, maxBytes) {
1312
+ return new Promise((resolve, reject) => {
1222
1313
  let body = "";
1314
+ let bytes = 0;
1315
+ // Never req.destroy() on overflow: req and res share one socket, so the 413 would never
1316
+ // arrive. tooLarge stops a late end/error from resolving after the reject.
1317
+ let tooLarge = false;
1223
1318
  req.on("data", (chunk) => {
1319
+ if (tooLarge)
1320
+ return;
1321
+ bytes += chunk.length;
1322
+ if (maxBytes !== undefined && bytes > maxBytes) {
1323
+ tooLarge = true;
1324
+ reject(new BodyTooLargeError(`request body exceeds ${maxBytes} bytes`));
1325
+ return;
1326
+ }
1224
1327
  body += chunk.toString();
1225
1328
  });
1226
- req.on("end", () => resolve(body));
1227
- req.on("error", () => resolve(body));
1329
+ req.on("end", () => {
1330
+ if (!tooLarge)
1331
+ resolve(body);
1332
+ });
1333
+ req.on("error", () => {
1334
+ if (!tooLarge)
1335
+ resolve(body);
1336
+ });
1228
1337
  });
1229
1338
  }
1230
1339
  /**
@@ -1296,16 +1405,32 @@ async function handleHealth(res) {
1296
1405
  // actually reading. reassertForward's cheap check-first path (adb forward --list) keeps
1297
1406
  // the cost low on the 2s poll cadence; it only pays for a real rebuild when the shared
1298
1407
  // port is actually pointed somewhere else.
1299
- forwardForRead();
1300
- const ping = await pingDevice();
1301
- const ok = ping.state === "armed" && ping.status === 200;
1408
+ let ping = { state: "unknown", status: null, body: "" };
1409
+ let ok = false;
1410
+ let unauthorized = false;
1411
+ let forwarded = false;
1412
+ if (transport.supportsRadarHttpTools) {
1413
+ forwarded = forwardForRead();
1414
+ const startedAt = Date.now();
1415
+ ping = await pingDevice(forwarded);
1416
+ ok = ping.state === "armed" && ping.status === 200 && pingMatchesTransport(ping);
1417
+ unauthorized = ping.state === "armed" && ping.status === 401 && pingMatchesTransport(ping);
1418
+ noteHealthPing(ok, unauthorized, startedAt);
1419
+ }
1420
+ else if (transport.supportsHostLogs) {
1421
+ // A log-only transport has no app-side HTTP listener to probe. Resolve its selected host
1422
+ // device directly; touching RADAR_PORT here could report an unrelated Android listener as a
1423
+ // healthy iOS Simulator.
1424
+ const selection = transport.selectDevice?.(null);
1425
+ ok = !!selection?.ok && selection.serial !== null;
1426
+ }
1302
1427
  // The bound profile, read from the device ping body. This is the TRUTH about which
1303
1428
  // profile owns the socket (the app that bound first), unlike the host-side activate
1304
1429
  // guess in getActiveUserId() which can drift. The dashboard shows this so it never
1305
1430
  // claims a profile you are not actually seeing.
1306
1431
  let uid = null;
1307
1432
  let profile = null;
1308
- let sources = null;
1433
+ let sources = transport.supportsRadarHttpTools && !transport.acceptsRadarPeer ? null : [];
1309
1434
  // Only trust the body on a healthy 200. A device 5xx-ing with a stale ping body must NOT
1310
1435
  // surface a bound profile while device:false -- that would let the dashboard show a
1311
1436
  // confident profile label for an unhealthy device.
@@ -1316,8 +1441,7 @@ async function handleHealth(res) {
1316
1441
  uid = String(p.android_user_id);
1317
1442
  if (typeof p.profile === "string")
1318
1443
  profile = p.profile;
1319
- if (Array.isArray(p.sources))
1320
- sources = p.sources;
1444
+ sources = Array.isArray(p.sources) ? p.sources : null;
1321
1445
  }
1322
1446
  catch {
1323
1447
  // non-JSON / partial body: device is up but we cannot name the profile
@@ -1326,6 +1450,14 @@ async function handleHealth(res) {
1326
1450
  const selected = transport.getSelectedDevice?.() ?? null;
1327
1451
  sendJson(res, 200, {
1328
1452
  device: ok,
1453
+ ...(unauthorized ? { unauthorized: true, unauthorized_msg: refusalSentence(forwarded) } : {}),
1454
+ platform: transport.platform,
1455
+ log_package: transport.logPackage ?? null,
1456
+ capabilities: {
1457
+ radar_http: !!transport.supportsRadarHttpTools,
1458
+ host_logs: !!transport.supportsHostLogs,
1459
+ local_files: !!transport.supportsLocalFileAccess,
1460
+ },
1329
1461
  screen: dashboardScreen.capabilities(),
1330
1462
  boundUserId: uid,
1331
1463
  boundProfile: profile,
@@ -1414,7 +1546,9 @@ const READ_ONLY_EXACT = new Set([
1414
1546
  // here opens every path beneath it forever. These two serve the dashboard's own static bundle.
1415
1547
  // The server matches these with startsWith, so the guard has to as well or a real request 403s.
1416
1548
  // /screen/download/<file> serves a finished recording the user asked to save.
1417
- const READ_ONLY_PREFIXES = ["/next/", "/vendor/", "/screen/download"];
1549
+ // /switchboard/download only serves a report the gated POST /switchboard/export already wrote;
1550
+ // a hidden iframe navigation cannot send the dashboard header.
1551
+ const READ_ONLY_PREFIXES = ["/next/", "/vendor/", "/screen/download", "/switchboard/download"];
1418
1552
  // Device-proxy reads. `/api/` as a whole is NOT safe (/api/clear wipes the device buffers), so the
1419
1553
  // readable sources are named and everything else under /api/ falls through to the guard.
1420
1554
  // Only names the device actually serves today (verified live: /api/prefs and /api/session 404).
@@ -1690,6 +1824,7 @@ tab) {
1690
1824
  }
1691
1825
  }
1692
1826
  transport.resetState();
1827
+ clearRadarTokenCache();
1693
1828
  // A reconnect may be a different device / re-armed profile, so drop the cached DB user
1694
1829
  // set + sqlite path; the next /dbs re-detects the profiles fresh.
1695
1830
  resetDbState();
@@ -1808,6 +1943,8 @@ tab) {
1808
1943
  if (switched) {
1809
1944
  cleanupPulledDatabases();
1810
1945
  logSession?.restart();
1946
+ // The old device's streamed switchboard records belong to the wrong hardware.
1947
+ clearSwitchboardHostStore();
1811
1948
  }
1812
1949
  // Reassert the forward is pointed at the selected device before reading. On a device
1813
1950
  // switch or after a multi-process repoint (e.g., MCP server switched to a different
@@ -1830,6 +1967,33 @@ tab) {
1830
1967
  device_serial: pinnedSerial(),
1831
1968
  } };
1832
1969
  }
1970
+ const refusedReply = () => ({ status: 200, body: {
1971
+ enabled: false,
1972
+ error: refusalSentence(forwarded),
1973
+ instructs: true,
1974
+ device_serial: pinnedSerial(),
1975
+ } });
1976
+ let peer = null;
1977
+ if (transport.acceptsRadarPeer) {
1978
+ peer = await pingDevice(forwarded);
1979
+ // An inactive iOS Radar listener answers /api/ping with 503, but its JSON body still proves
1980
+ // which platform owns the host-global port. Requiring 200 here made activation impossible:
1981
+ // /api/enable is the operation that transitions that verified listener to an armed 200.
1982
+ if (peer.state !== "armed" || !pingMatchesTransport(peer)) {
1983
+ return { status: 200, body: {
1984
+ enabled: false,
1985
+ error: `The Radar listener on the shared host port does not belong to the selected ${transport.platform} app, or the app is not answering.`,
1986
+ instructs: true,
1987
+ device_serial: pinnedSerial(),
1988
+ } };
1989
+ }
1990
+ }
1991
+ if (auto && transport.supportsRadarHttpTools) {
1992
+ const held = peer ?? await pingDevice(forwarded);
1993
+ if (held.state === "armed" && held.status === 401) {
1994
+ return refusedReply();
1995
+ }
1996
+ }
1833
1997
  // activateAsync() never throws; a failed broadcast is recorded on the transport.
1834
1998
  // Surfacing it here gives the dashboard user the actual adb error instead of a bare
1835
1999
  // enabled:false after the ping probe times out. Async for the same reason as the boot chain:
@@ -1841,25 +2005,56 @@ tab) {
1841
2005
  else {
1842
2006
  transport.activate(transport.getTimeoutMinutes());
1843
2007
  }
2008
+ const tokenFileError = transport.getLastActivateTokenFileError?.() ?? null;
2009
+ if (tokenFileError) {
2010
+ return { status: 200, body: {
2011
+ enabled: false, error: tokenFileMessage(tokenFileError, "dashboard"),
2012
+ instructs: true, device_serial: pinnedSerial(),
2013
+ } };
2014
+ }
1844
2015
  const activateError = transport.getLastActivateError?.() ?? null;
1845
2016
  if (activateError) {
1846
2017
  return { status: 200, body: {
1847
2018
  enabled: false,
1848
- error: `Broadcast failed: ${activateError}. Is the device connected?`,
2019
+ error: transport.supportsRadarHttpTools
2020
+ ? `Broadcast failed: ${activateError}. Is the device connected?`
2021
+ : `Log capture activation failed: ${activateError}`,
1849
2022
  instructs: false,
1850
2023
  device_serial: pinnedSerial(),
1851
2024
  } };
1852
2025
  }
2026
+ if (!transport.supportsRadarHttpTools && transport.supportsHostLogs) {
2027
+ keepAliveHookFor(authored, tab)?.();
2028
+ return { status: 200, body: {
2029
+ enabled: true,
2030
+ device_serial: pinnedSerial(),
2031
+ } };
2032
+ }
1853
2033
  // Verify by pinging the device the same way /health does (the shared pingDevice, so the
1854
2034
  // ceiling and the three-state rules cannot drift from the other probe sites).
1855
- const ping = await pingDevice();
2035
+ let saw401 = false;
2036
+ let ping = await pingDevice(forwarded);
2037
+ for (const waitMs of ENABLE_PING_WAITS_MS) {
2038
+ if (!(ping.state === "armed" && ping.status === 401))
2039
+ break;
2040
+ saw401 = true;
2041
+ await new Promise((resolve) => setTimeout(resolve, waitMs));
2042
+ ping = await pingDevice(forwarded);
2043
+ }
2044
+ if (saw401 && !(ping.state === "armed" && ping.status === 200)) {
2045
+ return refusedReply();
2046
+ }
1856
2047
  const enabled = ping.state === "armed" && ping.status === 200;
1857
2048
  // A verified arm refutes any cached "no_session" the same way a stream connect does (the
1858
2049
  // memo is evidence about a session this route just restored): without this, another stream
1859
2050
  // client's mid-retry memo read could announce the pre-arm diagnosis for up to its TTL and
1860
2051
  // drive that tab to fire a spurious /enable against the live session.
1861
- if (enabled)
2052
+ if (enabled) {
1862
2053
  invalidateOutageDiagnosis();
2054
+ // Android treats every answering listener as the selected device; this guard matters only for peer-check transports.
2055
+ if (pingMatchesTransport(ping))
2056
+ wakeRefusedStreams();
2057
+ }
1863
2058
  // Probe the process state only on the failure path: a successful enable needs no diagnosis,
1864
2059
  // and the probe is a real adb round trip. Capped short, because by this point the failure is
1865
2060
  // already established and the user is watching a request that has stalled their SSE tabs; an
@@ -1899,10 +2094,23 @@ export { SWITCHBOARD_KIND, SWITCHBOARD_BACKFILL_SESSIONS, SWITCHBOARD_BACKFILL_D
1899
2094
  // route's is armed first, so without this the route would reply before the leg could hand back the
1900
2095
  // sessions that answered.
1901
2096
  export const BACKFILL_ROUTE_HEADROOM_MS = 250;
1902
- function getDeviceJson(apiPath) {
2097
+ function getDeviceJson(apiPath, forwarded, onUnauthorized) {
1903
2098
  let rq;
1904
2099
  const result = new Promise((resolve) => {
1905
- rq = http.request({ host: RADAR_HOST, port: RADAR_PORT, path: apiPath, method: "GET", timeout: 4000 }, (up) => {
2100
+ rq = http.request({
2101
+ host: RADAR_HOST,
2102
+ port: RADAR_PORT,
2103
+ path: apiPath,
2104
+ method: "GET",
2105
+ timeout: 4000,
2106
+ headers: deviceTokenHeader(forwarded),
2107
+ }, (up) => {
2108
+ if (up.statusCode === 401) {
2109
+ onUnauthorized?.();
2110
+ up.resume();
2111
+ resolve(null);
2112
+ return;
2113
+ }
1906
2114
  let b = "";
1907
2115
  up.on("data", (c) => (b += c));
1908
2116
  up.on("end", () => {
@@ -1932,7 +2140,9 @@ function getDeviceJson(apiPath) {
1932
2140
  // deadline is a parameter for the same reason. Each session's page is kept as it lands, so when
1933
2141
  // the deadline fires the reply is whatever arrived by then (a device sitting on one session's
1934
2142
  // route costs that session, not the whole replay), and the requests still open are dropped.
1935
- export function fetchSwitchboardBackfill(limit, deadlineMs = SWITCHBOARD_BACKFILL_DEADLINE_MS) {
2143
+ export function fetchSwitchboardBackfill(limit, deadlineMs,
2144
+ // Required so every caller says whether the forward came back good before the token goes out.
2145
+ forwarded, onUnauthorized) {
1936
2146
  return new Promise((resolve) => {
1937
2147
  const landed = [];
1938
2148
  const inflight = new Set();
@@ -1948,14 +2158,14 @@ export function fetchSwitchboardBackfill(limit, deadlineMs = SWITCHBOARD_BACKFIL
1948
2158
  resolve(newestSwitchboardRecords(landed.flat(), limit));
1949
2159
  };
1950
2160
  const timer = setTimeout(finish, deadlineMs);
1951
- fetchSwitchboardSessions(limit, landed, inflight).then(finish, finish);
2161
+ fetchSwitchboardSessions(limit, landed, inflight, forwarded, onUnauthorized).then(finish, finish);
1952
2162
  });
1953
2163
  }
1954
2164
  // Lists the sessions, then fetches the newest few in parallel, pushing each page onto `landed`
1955
2165
  // as it arrives and keeping the open requests in `inflight` for the deadline above.
1956
- async function fetchSwitchboardSessions(limit, landed, inflight) {
2166
+ async function fetchSwitchboardSessions(limit, landed, inflight, forwarded, onUnauthorized) {
1957
2167
  const get = async (apiPath) => {
1958
- const g = getDeviceJson(apiPath);
2168
+ const g = getDeviceJson(apiPath, forwarded, onUnauthorized);
1959
2169
  inflight.add(g);
1960
2170
  try {
1961
2171
  return await g.result;
@@ -1979,6 +2189,179 @@ function newestSwitchboardRecords(records, limit) {
1979
2189
  const sorted = [...records].sort((a, b) => when(a) - when(b));
1980
2190
  return sorted.slice(Math.max(0, sorted.length - limit)).map((e) => ({ type: SWITCHBOARD_KIND, event: e }));
1981
2191
  }
2192
+ // Keeps the real HTTP status, unlike getDeviceJson: a device 404 with a JSON error body would
2193
+ // otherwise parse as a valid object. status 0 means unreachable. Shares radarRequestRaw with the
2194
+ // MCP path so the two cannot drift onto different timeouts; idleMs/overallMs are test overrides.
2195
+ const switchboardExportGetFor = (forwarded) => (apiPath, capBytes = SWITCHBOARD_EXPORT_SAFETY_CAP_BYTES, deadline, idleMs = SWITCHBOARD_EXPORT_IDLE_MS, overallMs = SWITCHBOARD_EXPORT_OVERALL_MS) => {
2196
+ if (deadline !== undefined && deadline - Date.now() <= 0)
2197
+ return Promise.resolve({ status: 0, body: null });
2198
+ return radarRequestRaw(RADAR_HOST, RADAR_PORT, apiPath, idleMs, overallMs, capBytes, deadline, forwarded ? transport : null, "dashboard");
2199
+ };
2200
+ export const _switchboardExportGetForTest = switchboardExportGetFor(true);
2201
+ // The body is at most `{id?}`.
2202
+ const SWITCHBOARD_EXPORT_BODY_MAX_BYTES = 4096;
2203
+ /**
2204
+ * `POST /switchboard/export`: body is optional JSON `{id?}`, defaulting to the newest session.
2205
+ * Writes the report to disk and answers `{download: "/switchboard/download?f=..."}`, since the
2206
+ * hidden iframe that fetches it cannot read a POST response.
2207
+ */
2208
+ async function handleSwitchboardExport(req, res) {
2209
+ // The request still goes out on a failed reassert, only without the token header.
2210
+ const forwarded = forwardForRead();
2211
+ // Connection: close, since the unread remainder would otherwise be misread as the next request.
2212
+ const contentLength = Number(req.headers["content-length"]);
2213
+ if (Number.isFinite(contentLength) && contentLength > SWITCHBOARD_EXPORT_BODY_MAX_BYTES) {
2214
+ sendJson(res, 413, { error: "request body too large" }, { Connection: "close" });
2215
+ return;
2216
+ }
2217
+ let body;
2218
+ try {
2219
+ body = await readBody(req, SWITCHBOARD_EXPORT_BODY_MAX_BYTES);
2220
+ }
2221
+ catch (e) {
2222
+ if (e instanceof BodyTooLargeError) {
2223
+ sendJson(res, 413, { error: "request body too large" }, { Connection: "close" });
2224
+ return;
2225
+ }
2226
+ throw e;
2227
+ }
2228
+ let requestedId = null;
2229
+ if (body.trim()) {
2230
+ let parsed;
2231
+ try {
2232
+ parsed = JSON.parse(body);
2233
+ }
2234
+ catch {
2235
+ sendJson(res, 400, { error: "bad json" });
2236
+ return;
2237
+ }
2238
+ const rawId = parsed?.id;
2239
+ if (rawId !== undefined && rawId !== null) {
2240
+ // Not Number(rawId), which accepts true, "" and [] as valid integers.
2241
+ const n = nonNegativeIntArg(rawId);
2242
+ if (n === null) {
2243
+ sendJson(res, 400, { error: `id must be a non-negative integer session_id; got ${JSON.stringify(rawId)}.` });
2244
+ return;
2245
+ }
2246
+ requestedId = n;
2247
+ }
2248
+ }
2249
+ const assembled = await assembleSwitchboardExport(requestedId, switchboardExportGetFor(forwarded), getHostSwitchboardRecords, newestHostSwitchboardSessionId,
2250
+ // The same sender the GET used: a failed reassert sends no token, and the wording must say so.
2251
+ forwarded ? transport : null, "dashboard");
2252
+ if (!assembled.ok) {
2253
+ const status = assembled.reason === "no-sessions" || assembled.reason === "not-found" ? 404 : 502;
2254
+ sendJson(res, status, { error: assembled.message });
2255
+ return;
2256
+ }
2257
+ writeSwitchboardWebReport(res, assembled);
2258
+ }
2259
+ function writeSwitchboardWebReport(res, assembly) {
2260
+ // A record shape the builder chokes on must answer 500 instead of hanging the response.
2261
+ let report;
2262
+ try {
2263
+ report = buildSwitchboardReport(assembly, Date.now());
2264
+ }
2265
+ catch (e) {
2266
+ if (!res.headersSent && !res.writableEnded) {
2267
+ sendJson(res, 500, { error: `Failed to build the report: ${e?.message || "internal error"}` });
2268
+ }
2269
+ return;
2270
+ }
2271
+ const notes = switchboardReportNotes(report);
2272
+ if (res.headersSent || res.writableEnded)
2273
+ return;
2274
+ let filePath;
2275
+ try {
2276
+ sweepStaleSwitchboardWebExports();
2277
+ filePath = writeSwitchboardReportFile(SWITCHBOARD_WEB_EXPORT_DIR, `switchboard-web-export-${assembly.sessionId}`, report, Date.now());
2278
+ }
2279
+ catch (e) {
2280
+ sendJson(res, 500, { error: `Failed to write the report to disk: ${e.message}` });
2281
+ return;
2282
+ }
2283
+ const file = path.basename(filePath);
2284
+ // A download that never starts would otherwise wait for the next export's sweep. ENOENT (the
2285
+ // download route already deleted it) is the common case.
2286
+ const staleTimer = setTimeout(() => {
2287
+ fs.unlink(filePath, (e) => {
2288
+ if (e && e.code !== "ENOENT")
2289
+ console.error(`[radar] failed to sweep stale switchboard export ${filePath}: ${e.message}`);
2290
+ });
2291
+ }, SWITCHBOARD_EXPORT_STALE_MS);
2292
+ staleTimer.unref();
2293
+ sendJson(res, 200, { download: "/switchboard/download?f=" + encodeURIComponent(file), notes });
2294
+ }
2295
+ // The download route's "close" cleanup only fires for a transfer that started, so an abandoned
2296
+ // report relies on these sweeps.
2297
+ let SWITCHBOARD_EXPORT_STALE_MS = 10 * 60 * 1000;
2298
+ export function _setSwitchboardExportStaleMsForTest(ms) {
2299
+ SWITCHBOARD_EXPORT_STALE_MS = ms;
2300
+ }
2301
+ function sweepStaleSwitchboardWebExports() {
2302
+ let names;
2303
+ try {
2304
+ names = fs.readdirSync(SWITCHBOARD_WEB_EXPORT_DIR);
2305
+ }
2306
+ catch {
2307
+ return;
2308
+ }
2309
+ const cutoff = Date.now() - SWITCHBOARD_EXPORT_STALE_MS;
2310
+ for (const name of names) {
2311
+ if (!SWITCHBOARD_EXPORT_NAME.test(name))
2312
+ continue;
2313
+ const p = path.join(SWITCHBOARD_WEB_EXPORT_DIR, name);
2314
+ try {
2315
+ if (fs.statSync(p).mtimeMs < cutoff)
2316
+ fs.unlinkSync(p);
2317
+ }
2318
+ catch {
2319
+ // Best effort: races with the download route's own delete.
2320
+ }
2321
+ }
2322
+ }
2323
+ // Only names writeSwitchboardReportFile produces, so a request can never name an arbitrary file.
2324
+ const SWITCHBOARD_EXPORT_NAME = /^switchboard-web-export-\d+-\d+-[0-9a-f]+\.txt$/;
2325
+ // Separate from the MCP tool's exports/ dir, so neither process's cleanup touches the other's files.
2326
+ const SWITCHBOARD_WEB_EXPORT_DIR = path.join(os.homedir(), ".slack-radar", "web-exports");
2327
+ // basename blocks traversal and the name check limits requests to switchboard web exports.
2328
+ function switchboardExportFilePath(file) {
2329
+ const base = path.basename(file);
2330
+ if (!SWITCHBOARD_EXPORT_NAME.test(base))
2331
+ return null;
2332
+ const p = path.join(SWITCHBOARD_WEB_EXPORT_DIR, base);
2333
+ return fs.existsSync(p) ? p : null;
2334
+ }
2335
+ /**
2336
+ * `GET /switchboard/download?f=<file>`: serves a written report once, then deletes it, since it
2337
+ * is a full record dump. Ungated because a hidden iframe cannot send the dashboard header.
2338
+ */
2339
+ function handleSwitchboardDownload(req, res) {
2340
+ const f = new URL(req.url ?? "", `http://localhost:${WEB_PORT}`).searchParams.get("f") ?? "";
2341
+ const p = switchboardExportFilePath(f);
2342
+ if (!p) {
2343
+ res.writeHead(404);
2344
+ res.end("Not found");
2345
+ return;
2346
+ }
2347
+ res.writeHead(200, {
2348
+ "Content-Type": "text/plain; charset=utf-8",
2349
+ "Content-Disposition": `attachment; filename="${path.basename(p)}"`,
2350
+ });
2351
+ // Without this a mid-stream read failure would hang the response open.
2352
+ fs.createReadStream(p)
2353
+ .on("error", () => res.destroy())
2354
+ .pipe(res);
2355
+ // "close", not "finish", so an aborted transfer still drops the file.
2356
+ res.on("close", () => {
2357
+ try {
2358
+ fs.unlinkSync(p);
2359
+ }
2360
+ catch {
2361
+ // Best effort; the stale sweep catches leftovers.
2362
+ }
2363
+ });
2364
+ }
1982
2365
  /**
1983
2366
  * Replay the device's recent ring buffers for a source so a freshly-built tab
1984
2367
  * shows history immediately instead of filling only going forward. The device is
@@ -1992,7 +2375,7 @@ function handleBackfill(req, res) {
1992
2375
  // falls through to the request below rather than erroring out here -- the device-side
1993
2376
  // request will surface its own connection failure, matching the pre-existing behavior
1994
2377
  // when the forward was never set up at all.
1995
- forwardForRead();
2378
+ const forwarded = forwardForRead();
1996
2379
  const u = new URL(req.url ?? "", `http://localhost:${WEB_PORT}`);
1997
2380
  const src = u.searchParams.get("source") ?? "network";
1998
2381
  // Clamped below at 1: a negative limit would slice the switchboard replay to nothing. Truncated
@@ -2013,6 +2396,8 @@ function handleBackfill(req, res) {
2013
2396
  const landed = [];
2014
2397
  const inflight = new Set();
2015
2398
  let settled = false;
2399
+ let rejected = false;
2400
+ const refused = () => { rejected = true; };
2016
2401
  const finish = () => {
2017
2402
  if (settled)
2018
2403
  return;
@@ -2022,7 +2407,7 @@ function handleBackfill(req, res) {
2022
2407
  rq.destroy();
2023
2408
  inflight.clear();
2024
2409
  const merged = landed.flat().sort((a, b) => when(a.event) - when(b.event));
2025
- sendJson(res, 200, { frames: merged });
2410
+ sendJson(res, 200, { frames: merged, ...(rejected ? { error: refusalSentence(forwarded) } : {}) });
2026
2411
  };
2027
2412
  // The ceiling for every leg, ring legs included: the switchboard span already sits above the
2028
2413
  // ring legs' 4 s socket timeout, so one number serves both.
@@ -2043,10 +2428,17 @@ function handleBackfill(req, res) {
2043
2428
  const rq = http.request({
2044
2429
  host: RADAR_HOST,
2045
2430
  port: RADAR_PORT,
2431
+ headers: deviceTokenHeader(forwarded),
2046
2432
  path: apiPath,
2047
2433
  method: "GET",
2048
2434
  timeout: 4000,
2049
2435
  }, (up) => {
2436
+ if (up.statusCode === 401) {
2437
+ refused();
2438
+ up.resume();
2439
+ done([]);
2440
+ return;
2441
+ }
2050
2442
  let b = "";
2051
2443
  up.on("data", (c) => (b += c));
2052
2444
  up.on("error", () => done([]));
@@ -2071,8 +2463,10 @@ function handleBackfill(req, res) {
2071
2463
  rq.end();
2072
2464
  });
2073
2465
  const legs = kinds.map(fetchKind);
2074
- if (wantsSwitchboard)
2075
- legs.push(fetchSwitchboardBackfill(limit).then((frames) => { landed.push(frames); }));
2466
+ if (wantsSwitchboard) {
2467
+ legs.push(fetchSwitchboardBackfill(limit, SWITCHBOARD_BACKFILL_DEADLINE_MS, forwarded, refused)
2468
+ .then((frames) => { landed.push(frames); }));
2469
+ }
2076
2470
  Promise.all(legs).then(finish, finish);
2077
2471
  }
2078
2472
  /**
@@ -2085,7 +2479,7 @@ function handleBackfill(req, res) {
2085
2479
  */
2086
2480
  export function failDetailResponse(res, status) {
2087
2481
  if (!res.headersSent) {
2088
- res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
2482
+ res.writeHead(status, { "Content-Type": "application/json; charset=utf-8", "X-Content-Type-Options": "nosniff" });
2089
2483
  res.end("{}");
2090
2484
  }
2091
2485
  else {
@@ -2098,7 +2492,7 @@ export function failDetailResponse(res, status) {
2098
2492
  */
2099
2493
  function handleDetail(req, res) {
2100
2494
  // Reassert before reading: see forwardForRead's doc comment.
2101
- forwardForRead();
2495
+ const forwarded = forwardForRead();
2102
2496
  const u = new URL(req.url ?? "", `http://localhost:${WEB_PORT}`);
2103
2497
  const id = u.searchParams.get("id");
2104
2498
  const kind = u.searchParams.get("kind") ?? "network";
@@ -2111,12 +2505,14 @@ function handleDetail(req, res) {
2111
2505
  const upstream = http.request({
2112
2506
  host: RADAR_HOST,
2113
2507
  port: RADAR_PORT,
2508
+ headers: deviceTokenHeader(forwarded),
2114
2509
  path: `/api/${route}/${encodeURIComponent(id)}`,
2115
2510
  method: "GET",
2116
2511
  timeout: 4000,
2117
2512
  }, (up) => {
2118
2513
  res.writeHead(up.statusCode ?? 502, {
2119
2514
  "Content-Type": "application/json; charset=utf-8",
2515
+ "X-Content-Type-Options": "nosniff",
2120
2516
  });
2121
2517
  up.on("data", (c) => res.write(c));
2122
2518
  up.on("end", () => res.end());
@@ -2140,9 +2536,15 @@ function handleDetail(req, res) {
2140
2536
  // as `feature_flag` frames on /api/stream (the on-device observer). Builds predating the plugin
2141
2537
  // 404, surfaced as a friendly message client-side.
2142
2538
  function handleFlags(req, res) {
2539
+ const forwarded = forwardForRead();
2143
2540
  const u = new URL(req.url ?? "", `http://localhost:${WEB_PORT}`);
2144
2541
  const path = `/api/feature_flags${u.search}`;
2145
- const upstream = http.request({ host: RADAR_HOST, port: RADAR_PORT, path, method: "GET", timeout: 4000 }, (up) => {
2542
+ const upstream = http.request({ host: RADAR_HOST, port: RADAR_PORT, path, method: "GET", timeout: 4000, headers: deviceTokenHeader(forwarded) }, (up) => {
2543
+ if (up.statusCode === 401) {
2544
+ up.resume();
2545
+ sendJson(res, 200, { error: refusalSentence(forwarded), feature_flags: [] });
2546
+ return;
2547
+ }
2146
2548
  let body = "";
2147
2549
  up.on("data", (c) => (body += c));
2148
2550
  up.on("end", () => {
@@ -2641,82 +3043,6 @@ function handleScreen(req, res) {
2641
3043
  res.writeHead(404);
2642
3044
  res.end("Not found");
2643
3045
  }
2644
- // Logcat line parsing for the host-side log merge. Format:
2645
- // "MM-DD HH:MM:SS.mmm PID TID L Tag: message"
2646
- const LOG_LINE_RE = /^(\d\d-\d\d \d\d:\d\d:\d\d\.\d+)\s+(\d+)\s+(\d+)\s+([VDIWEF])\s+([^:]*?):\s?(.*)$/;
2647
- const LOG_LEVELS = {
2648
- V: "VERBOSE",
2649
- D: "DEBUG",
2650
- I: "INFO",
2651
- W: "WARN",
2652
- E: "ERROR",
2653
- F: "FATAL",
2654
- };
2655
- // A logcat line carries a PID, not a package, but the dashboard filters logs by
2656
- // package (e.g. "Slack app only"). Resolve PID -> process name from
2657
- // `adb shell ps -A -o PID,NAME`, cached and refreshed on a miss (rate-limited), so
2658
- // log rows get a readable `package` and the package filter works. Without this the
2659
- // Live/Logs presets (match {package: ...}) drop every log line.
2660
- const pidToPackage = new Map();
2661
- let pidRefreshing = false;
2662
- let lastPidRefresh = 0;
2663
- function refreshPidMap() {
2664
- if (pidRefreshing)
2665
- return;
2666
- const adb = resolveAdbPath();
2667
- if (!adb)
2668
- return;
2669
- pidRefreshing = true;
2670
- lastPidRefresh = Date.now();
2671
- const ps = spawn(adb, ["shell", "ps", "-A", "-o", "PID,NAME"]);
2672
- let out = "";
2673
- ps.stdout?.on("data", (c) => (out += c.toString()));
2674
- ps.on("error", () => {
2675
- pidRefreshing = false;
2676
- });
2677
- ps.on("close", () => {
2678
- pidRefreshing = false;
2679
- for (const line of out.split("\n")) {
2680
- const m = line.trim().match(/^(\d+)\s+(\S+)$/);
2681
- if (m)
2682
- pidToPackage.set(Number(m[1]), m[2]);
2683
- }
2684
- });
2685
- }
2686
- function packageForPid(pid) {
2687
- const hit = pidToPackage.get(pid);
2688
- if (hit)
2689
- return hit;
2690
- // Unknown pid: trigger a rate-limited refresh so the NEXT line resolves.
2691
- if (Date.now() - lastPidRefresh > 3000)
2692
- refreshPidMap();
2693
- return undefined;
2694
- }
2695
- let logIdSeq = 0;
2696
- /**
2697
- * Parse one `adb logcat -v threadtime` line into a structured event, or null if it does
2698
- * not match the format. `resolvePkg` maps a pid to its package name (defaults to the
2699
- * live adb-backed resolver); injectable so this stays a pure, unit-testable function.
2700
- * Exported for tests.
2701
- */
2702
- export function parseLogcat(line, resolvePkg = packageForPid) {
2703
- const m = line.match(LOG_LINE_RE);
2704
- if (!m)
2705
- return null;
2706
- const [, ts, pid, tid, level, tag, message] = m;
2707
- const pidN = Number(pid);
2708
- return {
2709
- id: ++logIdSeq,
2710
- timestamp: Date.now(),
2711
- log_ts: ts,
2712
- pid: pidN,
2713
- tid: Number(tid),
2714
- level: LOG_LEVELS[level] ?? level,
2715
- tag: tag.trim(),
2716
- message,
2717
- package: resolvePkg(pidN),
2718
- };
2719
- }
2720
3046
  // How long a freshly opened device stream may go without response HEADERS before the attempt is
2721
3047
  // declared dead. A healthy device answers /api/stream immediately; the pathological case this
2722
3048
  // bounds is a dead device-side socket behind a LIVE adb forward, where the host adb server
@@ -2758,6 +3084,36 @@ let outageDiagnosisInflight = null;
2758
3084
  // re-drop of this one would inherit "no_session" for the full TTL and re-arm against the
2759
3085
  // live session.
2760
3086
  let outageDiagnosisGeneration = 0;
3087
+ const refusedStreams = new Set();
3088
+ let pingsWithout401 = 0;
3089
+ let missEpochAt = 0;
3090
+ const PINGS_WITHOUT_401_TO_RETRY = 2;
3091
+ function wakeRefusedStreams(retract = false) {
3092
+ pingsWithout401 = 0;
3093
+ missEpochAt = Date.now();
3094
+ for (const wake of [...refusedStreams])
3095
+ wake(retract);
3096
+ }
3097
+ function noteHealthPing(ok, unauthorized, startedAt) {
3098
+ if (unauthorized) {
3099
+ pingsWithout401 = 0;
3100
+ missEpochAt = Date.now();
3101
+ return;
3102
+ }
3103
+ if (ok) {
3104
+ wakeRefusedStreams();
3105
+ return;
3106
+ }
3107
+ if (startedAt < missEpochAt)
3108
+ return;
3109
+ missEpochAt = Date.now();
3110
+ if (++pingsWithout401 >= PINGS_WITHOUT_401_TO_RETRY)
3111
+ wakeRefusedStreams(true);
3112
+ }
3113
+ export function _resetRefusalWakeForTest() {
3114
+ pingsWithout401 = 0;
3115
+ missEpochAt = 0;
3116
+ }
2761
3117
  // Test seam: the real probe reaches a physical device over adb, which a test host may or may
2762
3118
  // not have, so tests pin the answer instead of inheriting whatever hardware is attached.
2763
3119
  let outageProbe = () => transport.radarSocketPresentAsync?.() ?? Promise.resolve("unknown");
@@ -2868,6 +3224,9 @@ function handleStream(req, res) {
2868
3224
  let closed = false;
2869
3225
  let lastState = "";
2870
3226
  let lastReason = "";
3227
+ // A wake can replace a connect while its error is still in flight.
3228
+ // Each callback must check that it still owns the stream.
3229
+ let attemptSeq = 0;
2871
3230
  let headersDeadline = null;
2872
3231
  const announce = (state, msg, reason) => {
2873
3232
  // Dedup on state AND reason, with one asymmetry: a diagnosed outage keeps its diagnosis.
@@ -2896,14 +3255,14 @@ function handleStream(req, res) {
2896
3255
  // proxy retry loop. Calling this on reconnect heals logs on the same path.
2897
3256
  const spec = loadSpec();
2898
3257
  const wantsLogs = spec.source === "log" || spec.source === "all";
2899
- const armLogcat = () => {
3258
+ const supportsDeviceStream = !!transport.supportsRadarHttpTools;
3259
+ const armLogs = () => {
2900
3260
  if (!wantsLogs || closed)
2901
3261
  return;
2902
3262
  const ok = logSession?.start() ?? false;
2903
3263
  if (!ok) {
2904
- // Spawn failed (e.g. no adb on PATH). The capture is a named session-scoped
2905
- // thing now, so surface the reason rather than showing silent emptiness.
2906
- announce("waiting", "device logs unavailable (adb not found?)");
3264
+ const failure = logSession?.takeLastFailure();
3265
+ announce("waiting", `device logs unavailable: ${failure ?? `${transport.platform} capture could not start`}`);
2907
3266
  }
2908
3267
  };
2909
3268
  let retries = 0;
@@ -2961,15 +3320,18 @@ function handleStream(req, res) {
2961
3320
  // cannot silently move only one of them.
2962
3321
  setTimeout(connect, planReconnect(transport, retries));
2963
3322
  };
2964
- const connect = () => {
3323
+ const connectVerified = () => {
2965
3324
  if (closed)
2966
3325
  return;
3326
+ if (!supportsDeviceStream)
3327
+ return;
3328
+ const attempt = ++attemptSeq;
2967
3329
  settled = false;
2968
3330
  // Reassert before every connect (initial AND each retry): see forwardForRead's doc
2969
3331
  // comment. planReconnect already forces a hard forward rebuild on every OTHER retry
2970
3332
  // (tuned for "device end died"), which would only catch a foreign repoint by luck on
2971
3333
  // half of attempts; this cheap check-first call covers every attempt instead.
2972
- forwardForRead();
3334
+ const forwarded = forwardForRead();
2973
3335
  // Bound the wait for response headers: see STREAM_RESPONSE_TIMEOUT_MS. Without this, the
2974
3336
  // accepted-but-never-answered connect mode fires none of the callbacks below and the
2975
3337
  // stream sits silent forever — no _status, no retry, nothing for a client to act on.
@@ -2977,6 +3339,8 @@ function handleStream(req, res) {
2977
3339
  // teardown: each attempt's handlers clear their OWN deadline, so a stale attempt's late
2978
3340
  // error event can never clear the live attempt's timer out from under it.
2979
3341
  const myDeadline = setTimeout(() => {
3342
+ if (attempt !== attemptSeq)
3343
+ return;
2980
3344
  if (closed)
2981
3345
  return;
2982
3346
  announce("waiting", "device not answering, retrying…");
@@ -2992,12 +3356,30 @@ function handleStream(req, res) {
2992
3356
  upstream = http.request({
2993
3357
  host: RADAR_HOST,
2994
3358
  port: RADAR_PORT,
3359
+ headers: { Accept: "text/event-stream", ...deviceTokenHeader(forwarded) },
2995
3360
  path: "/api/stream",
2996
3361
  method: "GET",
2997
3362
  }, (up) => {
3363
+ if (attempt !== attemptSeq)
3364
+ return;
2998
3365
  clearTimeout(myDeadline);
2999
3366
  if (headersDeadline === myDeadline)
3000
3367
  headersDeadline = null;
3368
+ if (up.statusCode !== 200) {
3369
+ up.destroy();
3370
+ if (up.statusCode === 401) {
3371
+ settled = true;
3372
+ invalidateOutageDiagnosis();
3373
+ announce("waiting", refusalSentence(forwarded), "unauthorized");
3374
+ refusedStreams.add(wake);
3375
+ pingsWithout401 = 0;
3376
+ missEpochAt = Date.now();
3377
+ return;
3378
+ }
3379
+ announce("waiting", `device stream unavailable (HTTP ${up.statusCode}), retrying…`);
3380
+ retry();
3381
+ return;
3382
+ }
3001
3383
  // A fresh outage on a long-lived connection must diagnose as early as the first one:
3002
3384
  // the "second failure" trigger and planReconnect's every-other-attempt forward
3003
3385
  // rebuild both key off this counter, and neither should inherit the count from an
@@ -3012,18 +3394,51 @@ function handleStream(req, res) {
3012
3394
  // Re-arm logs on the same path the device proxy heals on: if the device
3013
3395
  // dropped and came back, `adb logcat` had exited; restart it (idempotent)
3014
3396
  // so the live log feed resumes without needing a browser reconnect.
3015
- armLogcat();
3016
- up.on("data", (c) => res.write(c));
3397
+ armLogs();
3398
+ // Also tee switchboard frames into the host-side copy, so a call the device ring later
3399
+ // evicts still exports whole. StringDecoder keeps a multi-byte character split across
3400
+ // chunks intact; the cap bounds partial if the device never sends a newline.
3401
+ const decoder = new StringDecoder("utf8");
3402
+ let partial = "";
3403
+ const PARTIAL_CAP_BYTES = 1024 * 1024;
3404
+ up.on("data", (c) => {
3405
+ if (attempt !== attemptSeq)
3406
+ return;
3407
+ res.write(c);
3408
+ partial += decoder.write(c);
3409
+ const lines = partial.split("\n");
3410
+ partial = lines.pop() ?? "";
3411
+ if (partial.length > PARTIAL_CAP_BYTES)
3412
+ partial = partial.slice(-PARTIAL_CAP_BYTES);
3413
+ for (const line of lines) {
3414
+ if (!line.startsWith("data: ") || !line.includes(SWITCHBOARD_KIND))
3415
+ continue;
3416
+ try {
3417
+ const parsed = JSON.parse(line.slice(6));
3418
+ if (parsed.type === SWITCHBOARD_KIND && parsed.event)
3419
+ recordSwitchboardStreamed(parsed.event);
3420
+ }
3421
+ catch {
3422
+ // Malformed line: the raw bytes were already forwarded; this parse is a side channel.
3423
+ }
3424
+ }
3425
+ });
3017
3426
  up.on("end", () => {
3427
+ if (attempt !== attemptSeq)
3428
+ return;
3018
3429
  announce("waiting", "device stream ended, retrying…");
3019
3430
  retry();
3020
3431
  });
3021
3432
  up.on("error", () => {
3433
+ if (attempt !== attemptSeq)
3434
+ return;
3022
3435
  announce("waiting", "device stream error, retrying…");
3023
3436
  retry();
3024
3437
  });
3025
3438
  });
3026
3439
  upstream.on("error", () => {
3440
+ if (attempt !== attemptSeq)
3441
+ return;
3027
3442
  clearTimeout(myDeadline);
3028
3443
  if (headersDeadline === myDeadline)
3029
3444
  headersDeadline = null;
@@ -3032,7 +3447,47 @@ function handleStream(req, res) {
3032
3447
  });
3033
3448
  upstream.end();
3034
3449
  };
3035
- connect();
3450
+ let peerCheckInFlight = false;
3451
+ const connect = () => {
3452
+ if (closed || !supportsDeviceStream || peerCheckInFlight)
3453
+ return;
3454
+ if (!transport.acceptsRadarPeer) {
3455
+ connectVerified();
3456
+ return;
3457
+ }
3458
+ settled = false;
3459
+ peerCheckInFlight = true;
3460
+ // Keep this identity probe tokenless too; connectVerified reasserts for itself.
3461
+ void pingDevice(false).then((peer) => {
3462
+ peerCheckInFlight = false;
3463
+ if (closed)
3464
+ return;
3465
+ if (peer.state !== "armed" || peer.status !== 200 || !pingMatchesTransport(peer)) {
3466
+ announce("waiting", `waiting for the selected ${transport.platform} Radar listener…`);
3467
+ retry();
3468
+ return;
3469
+ }
3470
+ connectVerified();
3471
+ });
3472
+ };
3473
+ const wake = (retract) => {
3474
+ if (closed)
3475
+ return;
3476
+ refusedStreams.delete(wake);
3477
+ settled = false;
3478
+ retries = 0;
3479
+ lastState = "";
3480
+ lastReason = "";
3481
+ if (retract)
3482
+ announce("waiting", "device not answering, retrying…", "undiagnosed");
3483
+ connect();
3484
+ };
3485
+ if (supportsDeviceStream) {
3486
+ connect();
3487
+ }
3488
+ else {
3489
+ announce("connected", "host log stream connected");
3490
+ }
3036
3491
  const heartbeat = setInterval(() => {
3037
3492
  if (!closed)
3038
3493
  res.write(": hb\n\n");
@@ -3045,9 +3500,22 @@ function handleStream(req, res) {
3045
3500
  // is persistent and shared, so a tab switch only adds/removes a listener — it
3046
3501
  // never tears down the capture or loses lines in a reconnect gap.
3047
3502
  let unsubscribeLogs = null;
3503
+ let unsubscribeLogStatus = null;
3048
3504
  if (wantsLogs) {
3049
- refreshPidMap(); // warm PID->package so the first log rows resolve their app
3050
- armLogcat(); // idempotent start; surfaces a status frame if spawn fails
3505
+ // Subscribe before starting so a synchronous spawn failure is announced with its
3506
+ // real cause. armLogs' fallback wording would otherwise win the status deduper and
3507
+ // hide the more useful failure emitted by LogSession.
3508
+ unsubscribeLogStatus = logSession?.subscribeStatus((running, failure) => {
3509
+ if (closed)
3510
+ return;
3511
+ if (!running) {
3512
+ announce("waiting", `device logs unavailable: ${failure ?? "capture stopped"}`);
3513
+ }
3514
+ else if (!supportsDeviceStream) {
3515
+ announce("connected", "host log stream connected");
3516
+ }
3517
+ });
3518
+ armLogs(); // idempotent start; surfaces a status frame if spawn fails
3051
3519
  unsubscribeLogs = logSession?.subscribe((ev, replay) => {
3052
3520
  if (closed)
3053
3521
  return;
@@ -3082,11 +3550,15 @@ function handleStream(req, res) {
3082
3550
  }
3083
3551
  req.on("close", () => {
3084
3552
  closed = true;
3553
+ // A closed response must not be woken or keep its closure in the set.
3554
+ refusedStreams.delete(wake);
3085
3555
  clearInterval(heartbeat);
3086
3556
  if (headersDeadline)
3087
3557
  clearTimeout(headersDeadline);
3088
3558
  if (unsubscribeLogs)
3089
3559
  unsubscribeLogs(); // detach listener; capture stays up
3560
+ if (unsubscribeLogStatus)
3561
+ unsubscribeLogStatus();
3090
3562
  try {
3091
3563
  upstream?.destroy();
3092
3564
  }
@@ -3096,9 +3568,13 @@ function handleStream(req, res) {
3096
3568
  });
3097
3569
  }
3098
3570
  function listProfiles(res) {
3099
- const profiles = transport.listProfiles?.() ?? [];
3100
- const activeUserId = transport.getActiveUserId();
3101
- sendJson(res, 200, { profiles, active_user_id: activeUserId });
3571
+ try {
3572
+ sendJson(res, 200, { profiles: transport.listProfiles?.() ?? [], active_user_id: transport.getActiveUserId() });
3573
+ }
3574
+ catch (error) {
3575
+ // listProfiles() throws when the debug build is stopped or the check cannot run; answer, do not hang.
3576
+ sendJson(res, 500, { error: error.message });
3577
+ }
3102
3578
  }
3103
3579
  // The attached-device list + the currently pinned device, for the dashboard's device picker.
3104
3580
  // listDevices() returns null when the platform listing itself failed (not "zero attached"). Keep
@@ -3119,6 +3595,7 @@ function activateRadar(res, userId) {
3119
3595
  // Reset cached state so ensureForward() re-runs adb forward. This handles
3120
3596
  // stale forwards after device-side idle timeout or profile switching.
3121
3597
  transport.resetState();
3598
+ clearRadarTokenCache();
3122
3599
  const forwarded = transport.ensureForward();
3123
3600
  if (!forwarded) {
3124
3601
  sendJson(res, 502, {
@@ -3138,36 +3615,59 @@ function activateRadar(res, userId) {
3138
3615
  catch (e) {
3139
3616
  sendJson(res, 502, {
3140
3617
  ok: false,
3141
- error: `Broadcast failed: ${e.message}. Debug build not running?`,
3618
+ error: e instanceof TokenFileError
3619
+ ? tokenFileMessage(e, "dashboard")
3620
+ : `Broadcast failed: ${e.message}. Is the device connected?`,
3142
3621
  });
3143
3622
  return;
3144
3623
  }
3624
+ const tokenFileError = transport.getLastActivateTokenFileError?.();
3625
+ if (tokenFileError) {
3626
+ sendJson(res, 502, { ok: false, error: tokenFileMessage(tokenFileError, "dashboard") });
3627
+ return;
3628
+ }
3629
+ const activateError = transport.getLastActivateError?.();
3630
+ if (activateError) {
3631
+ sendJson(res, 502, { ok: false, error: `Broadcast failed: ${activateError}. Is the device connected?` });
3632
+ return;
3633
+ }
3145
3634
  sendJson(res, 200, {
3146
3635
  ok: true,
3147
3636
  user_id: userId ?? transport.getActiveUserId() ?? "auto",
3148
3637
  });
3149
3638
  }
3639
+ /** Status and body pass through untouched, including a 401; dashboard sentences live on the named routes. */
3150
3640
  function proxyToRadar(req, res) {
3641
+ const forwarded = forwardForRead();
3642
+ const headers = radarProxyHeaders(req.method, req.headers, forwarded);
3151
3643
  const upstream = http.request({
3152
3644
  host: RADAR_HOST,
3153
3645
  port: RADAR_PORT,
3154
3646
  path: req.url,
3155
3647
  method: req.method,
3156
- headers: req.headers,
3648
+ headers,
3157
3649
  timeout: 0,
3158
3650
  }, (upstreamRes) => {
3159
- res.writeHead(upstreamRes.statusCode ?? 502, upstreamRes.headers);
3651
+ res.writeHead(upstreamRes.statusCode ?? 502, {
3652
+ "Content-Type": "application/json; charset=utf-8",
3653
+ "X-Content-Type-Options": "nosniff",
3654
+ });
3160
3655
  upstreamRes.on("data", (chunk) => res.write(chunk));
3161
3656
  upstreamRes.on("end", () => res.end());
3162
3657
  upstreamRes.on("error", () => res.end());
3163
3658
  });
3164
3659
  upstream.on("error", (err) => {
3165
- res.writeHead(502, { "Content-Type": "application/json; charset=utf-8" });
3660
+ res.writeHead(502, { "Content-Type": "application/json; charset=utf-8", "X-Content-Type-Options": "nosniff" });
3166
3661
  res.end(JSON.stringify({
3167
3662
  error: `Cannot reach radar at ${RADAR_HOST}:${RADAR_PORT}. Is ADB forwarding active? ${err.message}`,
3168
3663
  }));
3169
3664
  });
3170
- req.on("close", () => upstream.destroy());
3665
+ // A client that goes away closes the response before it finishes. Not req "close": that fires
3666
+ // once the request body has been read, which would cut every proxied write off mid-flight.
3667
+ res.on("close", () => {
3668
+ if (!res.writableFinished)
3669
+ upstream.destroy();
3670
+ });
3171
3671
  if (req.method !== "GET" && req.method !== "HEAD") {
3172
3672
  req.pipe(upstream);
3173
3673
  }
@@ -3175,4 +3675,26 @@ function proxyToRadar(req, res) {
3175
3675
  upstream.end();
3176
3676
  }
3177
3677
  }
3678
+ /**
3679
+ * Headers that cross from the dashboard server to the device Radar listener.
3680
+ *
3681
+ * The dashboard terminates the browser-facing HTTP hop, so its Host/Origin,
3682
+ * hop-by-hop connection and transfer framing, and X-Radar-Dashboard credentials
3683
+ * describe that hop rather than the device request. Forwarding them is especially
3684
+ * unsafe for a strict iOS listener reached through a different authority. Preserve
3685
+ * only representation negotiation and the body metadata needed to replay writes.
3686
+ */
3687
+ export function radarProxyHeaders(method, incoming, forwarded) {
3688
+ const headers = {
3689
+ Accept: incoming.accept ?? "application/json",
3690
+ ...deviceTokenHeader(forwarded),
3691
+ };
3692
+ if (method !== "GET" && method !== "HEAD") {
3693
+ if (incoming["content-type"])
3694
+ headers["Content-Type"] = incoming["content-type"];
3695
+ if (incoming["content-length"])
3696
+ headers["Content-Length"] = incoming["content-length"];
3697
+ }
3698
+ return headers;
3699
+ }
3178
3700
  export { WEB_PORT };