@slack/radar-mcp 1.20.0 → 1.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +75 -17
- package/dist/mcp/api-paths.d.ts +11 -0
- package/dist/mcp/api-paths.js +56 -20
- package/dist/mcp/dashboard-identity.d.ts +6 -0
- package/dist/mcp/dashboard-identity.js +11 -0
- package/dist/mcp/index.js +138 -36
- package/dist/mcp/logs-result.d.ts +1 -0
- package/dist/mcp/logs-result.js +1 -0
- package/dist/mcp/network-detail.d.ts +5 -0
- package/dist/mcp/network-detail.js +86 -0
- package/dist/mcp/radar-export-get.d.ts +30 -0
- package/dist/mcp/radar-export-get.js +49 -0
- package/dist/mcp/radar-response.d.ts +11 -1
- package/dist/mcp/radar-response.js +23 -3
- package/dist/mcp/session-backfill.d.ts +9 -3
- package/dist/mcp/session-backfill.js +76 -17
- package/dist/mcp/session-detail.js +54 -2
- package/dist/mcp/session-enable.d.ts +1 -0
- package/dist/mcp/session-enable.js +146 -15
- package/dist/mcp/session-query.js +53 -11
- package/dist/mcp/snapshot.js +42 -26
- package/dist/mcp/sources-gate.js +5 -0
- package/dist/mcp/stale-dashboard.d.ts +23 -0
- package/dist/mcp/stale-dashboard.js +122 -0
- package/dist/mcp/switchboard-spool.d.ts +12 -0
- package/dist/mcp/switchboard-spool.js +107 -0
- package/dist/mcp/switchboard-tools.d.ts +18 -0
- package/dist/mcp/switchboard-tools.js +178 -0
- package/dist/mcp/tools.d.ts +4 -1
- package/dist/mcp/tools.js +114 -23
- package/dist/mcp/web-child-env.d.ts +4 -1
- package/dist/mcp/web-child-env.js +4 -1
- package/dist/shared/android.d.ts +43 -0
- package/dist/shared/android.js +227 -19
- package/dist/shared/constants.d.ts +19 -4
- package/dist/shared/constants.js +19 -4
- package/dist/shared/event-spool.js +3 -2
- package/dist/shared/feature-flags.d.ts +1 -0
- package/dist/shared/feature-flags.js +1 -0
- package/dist/shared/form-body.d.ts +18 -0
- package/dist/shared/form-body.js +251 -0
- package/dist/shared/ios-logs.d.ts +10 -0
- package/dist/shared/ios-logs.js +91 -0
- package/dist/shared/ios.d.ts +25 -2
- package/dist/shared/ios.js +157 -3
- package/dist/{web → shared}/log-session.d.ts +45 -31
- package/dist/shared/log-session.js +300 -0
- package/dist/shared/radar-request-raw.d.ts +7 -0
- package/dist/shared/radar-request-raw.js +89 -0
- package/dist/shared/radar-token.d.ts +25 -0
- package/dist/shared/radar-token.js +164 -0
- package/dist/shared/stream.d.ts +4 -1
- package/dist/shared/stream.js +107 -15
- package/dist/shared/switchboard-host-store.d.ts +21 -0
- package/dist/shared/switchboard-host-store.js +166 -0
- package/dist/shared/switchboard-note.d.ts +15 -0
- package/dist/shared/switchboard-note.js +92 -0
- package/dist/shared/switchboard-report-file.d.ts +5 -0
- package/dist/shared/switchboard-report-file.js +26 -0
- package/dist/shared/switchboard-report.d.ts +20 -0
- package/dist/shared/switchboard-report.js +406 -0
- package/dist/shared/switchboard.d.ts +118 -0
- package/dist/shared/switchboard.js +487 -0
- package/dist/shared/transport.d.ts +43 -3
- package/dist/shared/version.d.ts +2 -0
- package/dist/shared/version.js +18 -0
- package/dist/shared/wire.d.ts +46 -1
- package/dist/web/install-app.d.ts +57 -8
- package/dist/web/install-app.js +270 -60
- package/dist/web/macapp/RadarApp.swift +340 -22
- package/dist/web/public/index.html +216 -12
- package/dist/web/public/next/app.js +43 -22
- package/dist/web/public/next/db.js +4 -1
- package/dist/web/public/next/feed.js +604 -59
- package/dist/web/public/next/filters.js +158 -40
- package/dist/web/public/next/flags.js +3 -0
- package/dist/web/public/next/form-body.js +252 -0
- package/dist/web/public/next/inspector.js +171 -14
- package/dist/web/public/next/prefs.js +5 -2
- package/dist/web/public/next/registry.js +35 -3
- package/dist/web/public/next/store.js +947 -69
- package/dist/web/public/next/switchboard-note.js +93 -0
- package/dist/web/public/next/toast.js +9 -5
- package/dist/web/public/next/voice-model.js +712 -0
- package/dist/web/public/next/voice.js +552 -0
- package/dist/web/server.d.ts +20 -9
- package/dist/web/server.js +834 -174
- package/dist/web/spec.d.ts +11 -6
- package/dist/web/spec.js +62 -6
- package/package.json +4 -4
- package/dist/web/log-session.js +0 -166
package/dist/web/server.js
CHANGED
|
@@ -1,19 +1,24 @@
|
|
|
1
1
|
import http from "http";
|
|
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";
|
|
2
6
|
import fs from "fs";
|
|
3
7
|
import os from "os";
|
|
4
8
|
import path from "path";
|
|
5
|
-
import {
|
|
9
|
+
import { StringDecoder } from "string_decoder";
|
|
6
10
|
import { fileURLToPath } from "url";
|
|
7
11
|
import { resolveAdbPath } from "../shared/android.js";
|
|
8
12
|
import { createTransport } from "../shared/platform.js";
|
|
9
13
|
import { planReconnect } from "../shared/stream.js";
|
|
10
14
|
import { createDashboardScreenController, } from "../shared/dashboard-screen.js";
|
|
11
|
-
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";
|
|
12
18
|
import { friendlyFeatureFlagError } from "../shared/feature-flags.js";
|
|
13
19
|
import { deviceServerSilentError, readProcessState, } from "../shared/enable-diagnosis.js";
|
|
14
20
|
import { cleanupPulledDatabases, initializeDatabasePath, listDatabases, pullDatabase, pulledSize, queryDatabase, resetDbState, availableUsers, } from "../shared/db.js";
|
|
15
21
|
import { listPrefsFiles, readPrefsFile, parsePrefsXml, searchPrefs, } from "../shared/prefs.js";
|
|
16
|
-
import { LogSession } from "./log-session.js";
|
|
17
22
|
import { BLANK_SPEC, coerceSpec, validateSpec } from "./spec.js";
|
|
18
23
|
import { grantScreenConsent, hasScreenConsent, detectDisplay, startLive, addViewer, removeViewer, reapLiveIfIdle, primeIfNeeded, capturePath, ffmpegInstallHint, SCREEN_BOUNDARY, } from "../shared/screen.js";
|
|
19
24
|
// The disk half of the screen reap, imported from the module that owns the only implementation of
|
|
@@ -77,6 +82,8 @@ function mcpSeenPath() {
|
|
|
77
82
|
return path.join(os.homedir(), ".slack-radar", "mcp-last-seen.json");
|
|
78
83
|
}
|
|
79
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") : {};
|
|
80
87
|
const dashboardScreen = createDashboardScreenController(transport);
|
|
81
88
|
// The serial this process last did screen housekeeping for: seeded by boot's orphan reap
|
|
82
89
|
// (armDevice) and advanced by every /enable that pins real hardware. Kept here rather than
|
|
@@ -141,9 +148,9 @@ function reapScreenOnce(serial, clearFilesWithoutDevice) {
|
|
|
141
148
|
}
|
|
142
149
|
// The ONE ceiling for every device ping this file makes (boot-arm, /health, /enable all go
|
|
143
150
|
// through pingDevice). A shorter one turns ordinary latency into a false negative: boot would
|
|
144
|
-
// read a live-but-slow session as absent, and /health would flap the connection dot.
|
|
145
|
-
//
|
|
146
|
-
const PING_PROBE_MS =
|
|
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;
|
|
147
154
|
// Reassert the shared adb forward before every HTTP-based device read. Mirrors
|
|
148
155
|
// mcp/index.ts's forwardForRead(): this process's own portForwarded cache cannot see a
|
|
149
156
|
// repoint made by a SEPARATE process (the MCP server) sharing the same host-global
|
|
@@ -152,20 +159,16 @@ const PING_PROBE_MS = 2500;
|
|
|
152
159
|
function forwardForRead() {
|
|
153
160
|
return transport.reassertForward?.() ?? transport.ensureForward();
|
|
154
161
|
}
|
|
155
|
-
// One session-long
|
|
156
|
-
// connection.
|
|
157
|
-
// keeps its own bounded session ring here and replays it to
|
|
158
|
-
// stream — this is what makes a tab switch (which reopens /stream)
|
|
159
|
-
// log history instead of only lines that arrive after the reconnect,
|
|
160
|
-
// how Android Studio retains logcat for the whole session.
|
|
161
|
-
//
|
|
162
|
-
//
|
|
163
|
-
const logSession = transport.
|
|
164
|
-
|
|
165
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
166
|
-
}), (line) => parseLogcat(line))
|
|
167
|
-
: null;
|
|
168
|
-
// 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
|
|
169
172
|
// dashboard is spawned and later terminated by the open_radar_dashboard MCP tool.
|
|
170
173
|
logSession?.registerCleanup();
|
|
171
174
|
// By design the capture is NOT stopped when the last log stream disconnects (e.g.
|
|
@@ -659,7 +662,7 @@ export async function shutdownDashboard(server, deps = {}) {
|
|
|
659
662
|
* session read identically through the forward), so the boot chain resolves it against the
|
|
660
663
|
* device's own socket table instead of guessing at this layer.
|
|
661
664
|
*/
|
|
662
|
-
function pingDevice(timeoutMs = PING_PROBE_MS) {
|
|
665
|
+
function pingDevice(forwarded, timeoutMs = PING_PROBE_MS) {
|
|
663
666
|
return new Promise((resolve) => {
|
|
664
667
|
let settled = false;
|
|
665
668
|
const done = (state, status = null, body = "") => {
|
|
@@ -668,7 +671,14 @@ function pingDevice(timeoutMs = PING_PROBE_MS) {
|
|
|
668
671
|
settled = true;
|
|
669
672
|
resolve({ state, status, body });
|
|
670
673
|
};
|
|
671
|
-
const req = http.request({
|
|
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) => {
|
|
672
682
|
// The ping body is the device's own small JSON status. Bound the accumulation anyway so a
|
|
673
683
|
// misbehaving local endpoint cannot grow it without limit; a truncated body simply fails
|
|
674
684
|
// the caller's JSON.parse, which every caller treats as "no extra detail".
|
|
@@ -689,6 +699,27 @@ function pingDevice(timeoutMs = PING_PROBE_MS) {
|
|
|
689
699
|
req.end();
|
|
690
700
|
});
|
|
691
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
|
+
}
|
|
692
723
|
/**
|
|
693
724
|
* Arm Radar once, at dashboard boot, so a launch against a freshly restarted app does not land on
|
|
694
725
|
* "waiting for device" until the human finds the Reconnect button. Called by bin.ts from the listen
|
|
@@ -823,7 +854,7 @@ async function armDevice() {
|
|
|
823
854
|
// default, which can be SHORTER than one another process explicitly asked for. An MCP session that
|
|
824
855
|
// armed for 30 minutes would have its idle window silently cut to the default by someone merely
|
|
825
856
|
// opening a dashboard to look, with no error surfaced to either side.
|
|
826
|
-
if ((await pingDevice()).state === "armed")
|
|
857
|
+
if ((await pingDevice(true)).state === "armed")
|
|
827
858
|
return;
|
|
828
859
|
// Anything else the ping says is inconclusive HERE, including a reset: the probe travels the
|
|
829
860
|
// adb forward, and the host adb server accepts every connection before discovering whether the
|
|
@@ -844,7 +875,8 @@ async function armDevice() {
|
|
|
844
875
|
}
|
|
845
876
|
// A device WAS reachable and the broadcast still failed, which is worth printing. Silence here is
|
|
846
877
|
// what left people staring at "waiting for device" with no idea a launch had already tried.
|
|
847
|
-
const
|
|
878
|
+
const tokenFileError = transport.getLastActivateTokenFileError?.() ?? null;
|
|
879
|
+
const error = tokenFileError ? tokenFileMessage(tokenFileError, "dashboard") : transport.getLastActivateError?.() ?? null;
|
|
848
880
|
if (error)
|
|
849
881
|
console.log(`Radar could not be armed at startup: ${error}`);
|
|
850
882
|
}
|
|
@@ -873,6 +905,8 @@ export function startAutoCloseSweep(server) {
|
|
|
873
905
|
* exercise the route without exiting the process. bin.ts calls createServer() with no args.
|
|
874
906
|
*/
|
|
875
907
|
export function createServer(onShutdown) {
|
|
908
|
+
// Catches exports left behind by a crash or a tab closed before its download ran.
|
|
909
|
+
sweepStaleSwitchboardWebExports();
|
|
876
910
|
const server = http.createServer((req, res) => {
|
|
877
911
|
// One chokepoint for every route: a request whose Host is not this loopback dashboard is a
|
|
878
912
|
// rebound foreign origin, not our client (see isLocalHostHeader). Rejected before routing so
|
|
@@ -1027,22 +1061,38 @@ export function createServer(onShutdown) {
|
|
|
1027
1061
|
handleStream(req, res);
|
|
1028
1062
|
return;
|
|
1029
1063
|
}
|
|
1030
|
-
|
|
1031
|
-
url.startsWith("/
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
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}` });
|
|
1036
1069
|
return;
|
|
1037
1070
|
}
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
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);
|
|
1041
1087
|
return;
|
|
1042
1088
|
}
|
|
1043
|
-
if (url.startsWith("/
|
|
1044
|
-
|
|
1045
|
-
|
|
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
|
+
}
|
|
1046
1096
|
}
|
|
1047
1097
|
if (url.startsWith("/dbs") && req.method === "GET") {
|
|
1048
1098
|
handleDbList(req, res);
|
|
@@ -1056,10 +1106,6 @@ export function createServer(onShutdown) {
|
|
|
1056
1106
|
handleDbQuery(req, res);
|
|
1057
1107
|
return;
|
|
1058
1108
|
}
|
|
1059
|
-
if (url.startsWith("/flags") && req.method === "GET") {
|
|
1060
|
-
handleFlags(req, res);
|
|
1061
|
-
return;
|
|
1062
|
-
}
|
|
1063
1109
|
if (url.split("?")[0] === "/prefs" && req.method === "GET") {
|
|
1064
1110
|
handlePrefsList(req, res);
|
|
1065
1111
|
return;
|
|
@@ -1089,12 +1135,22 @@ export function createServer(onShutdown) {
|
|
|
1089
1135
|
listDevices(res);
|
|
1090
1136
|
return;
|
|
1091
1137
|
}
|
|
1092
|
-
if (
|
|
1093
|
-
|
|
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
|
+
});
|
|
1094
1146
|
return;
|
|
1095
1147
|
}
|
|
1096
|
-
if (
|
|
1097
|
-
|
|
1148
|
+
if (urlPath === "/switchboard/download" && req.method === "GET") {
|
|
1149
|
+
handleSwitchboardDownload(req, res);
|
|
1150
|
+
return;
|
|
1151
|
+
}
|
|
1152
|
+
if (url.startsWith("/screen/")) {
|
|
1153
|
+
handleScreen(req, res);
|
|
1098
1154
|
return;
|
|
1099
1155
|
}
|
|
1100
1156
|
res.writeHead(404);
|
|
@@ -1102,6 +1158,36 @@ export function createServer(onShutdown) {
|
|
|
1102
1158
|
});
|
|
1103
1159
|
return server;
|
|
1104
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
|
+
}
|
|
1105
1191
|
function serveIndex(res) {
|
|
1106
1192
|
try {
|
|
1107
1193
|
const html = fs.readFileSync(INDEX_PATH);
|
|
@@ -1195,7 +1281,9 @@ function serveStatic(clean, res, isHead, ifNoneMatch) {
|
|
|
1195
1281
|
}
|
|
1196
1282
|
return true;
|
|
1197
1283
|
}
|
|
1198
|
-
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) {
|
|
1199
1287
|
// A device probe can fire both "end" and "error"/"timeout" for one request, so its
|
|
1200
1288
|
// callbacks may call sendJson twice. The second writeHead would throw
|
|
1201
1289
|
// ERR_HTTP_HEADERS_SENT and crash the whole process. Swallow the duplicate.
|
|
@@ -1211,19 +1299,41 @@ function sendJson(res, status, payload) {
|
|
|
1211
1299
|
// which is why it belongs in this helper rather than in one route that happened to need it.
|
|
1212
1300
|
const body = JSON.stringify(payload);
|
|
1213
1301
|
res.writeHead(status, {
|
|
1302
|
+
...headers,
|
|
1214
1303
|
"Content-Type": "application/json; charset=utf-8",
|
|
1304
|
+
"X-Content-Type-Options": "nosniff",
|
|
1215
1305
|
"Content-Length": Buffer.byteLength(body),
|
|
1216
1306
|
});
|
|
1217
1307
|
res.end(body);
|
|
1218
1308
|
}
|
|
1219
|
-
|
|
1220
|
-
|
|
1309
|
+
class BodyTooLargeError extends Error {
|
|
1310
|
+
}
|
|
1311
|
+
function readBody(req, maxBytes) {
|
|
1312
|
+
return new Promise((resolve, reject) => {
|
|
1221
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;
|
|
1222
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
|
+
}
|
|
1223
1327
|
body += chunk.toString();
|
|
1224
1328
|
});
|
|
1225
|
-
req.on("end", () =>
|
|
1226
|
-
|
|
1329
|
+
req.on("end", () => {
|
|
1330
|
+
if (!tooLarge)
|
|
1331
|
+
resolve(body);
|
|
1332
|
+
});
|
|
1333
|
+
req.on("error", () => {
|
|
1334
|
+
if (!tooLarge)
|
|
1335
|
+
resolve(body);
|
|
1336
|
+
});
|
|
1227
1337
|
});
|
|
1228
1338
|
}
|
|
1229
1339
|
/**
|
|
@@ -1295,16 +1405,32 @@ async function handleHealth(res) {
|
|
|
1295
1405
|
// actually reading. reassertForward's cheap check-first path (adb forward --list) keeps
|
|
1296
1406
|
// the cost low on the 2s poll cadence; it only pays for a real rebuild when the shared
|
|
1297
1407
|
// port is actually pointed somewhere else.
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
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
|
+
}
|
|
1301
1427
|
// The bound profile, read from the device ping body. This is the TRUTH about which
|
|
1302
1428
|
// profile owns the socket (the app that bound first), unlike the host-side activate
|
|
1303
1429
|
// guess in getActiveUserId() which can drift. The dashboard shows this so it never
|
|
1304
1430
|
// claims a profile you are not actually seeing.
|
|
1305
1431
|
let uid = null;
|
|
1306
1432
|
let profile = null;
|
|
1307
|
-
let sources = null;
|
|
1433
|
+
let sources = transport.supportsRadarHttpTools && !transport.acceptsRadarPeer ? null : [];
|
|
1308
1434
|
// Only trust the body on a healthy 200. A device 5xx-ing with a stale ping body must NOT
|
|
1309
1435
|
// surface a bound profile while device:false -- that would let the dashboard show a
|
|
1310
1436
|
// confident profile label for an unhealthy device.
|
|
@@ -1315,8 +1441,7 @@ async function handleHealth(res) {
|
|
|
1315
1441
|
uid = String(p.android_user_id);
|
|
1316
1442
|
if (typeof p.profile === "string")
|
|
1317
1443
|
profile = p.profile;
|
|
1318
|
-
|
|
1319
|
-
sources = p.sources;
|
|
1444
|
+
sources = Array.isArray(p.sources) ? p.sources : null;
|
|
1320
1445
|
}
|
|
1321
1446
|
catch {
|
|
1322
1447
|
// non-JSON / partial body: device is up but we cannot name the profile
|
|
@@ -1325,6 +1450,14 @@ async function handleHealth(res) {
|
|
|
1325
1450
|
const selected = transport.getSelectedDevice?.() ?? null;
|
|
1326
1451
|
sendJson(res, 200, {
|
|
1327
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
|
+
},
|
|
1328
1461
|
screen: dashboardScreen.capabilities(),
|
|
1329
1462
|
boundUserId: uid,
|
|
1330
1463
|
boundProfile: profile,
|
|
@@ -1413,7 +1546,9 @@ const READ_ONLY_EXACT = new Set([
|
|
|
1413
1546
|
// here opens every path beneath it forever. These two serve the dashboard's own static bundle.
|
|
1414
1547
|
// The server matches these with startsWith, so the guard has to as well or a real request 403s.
|
|
1415
1548
|
// /screen/download/<file> serves a finished recording the user asked to save.
|
|
1416
|
-
|
|
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"];
|
|
1417
1552
|
// Device-proxy reads. `/api/` as a whole is NOT safe (/api/clear wipes the device buffers), so the
|
|
1418
1553
|
// readable sources are named and everything else under /api/ falls through to the guard.
|
|
1419
1554
|
// Only names the device actually serves today (verified live: /api/prefs and /api/session 404).
|
|
@@ -1689,6 +1824,7 @@ tab) {
|
|
|
1689
1824
|
}
|
|
1690
1825
|
}
|
|
1691
1826
|
transport.resetState();
|
|
1827
|
+
clearRadarTokenCache();
|
|
1692
1828
|
// A reconnect may be a different device / re-armed profile, so drop the cached DB user
|
|
1693
1829
|
// set + sqlite path; the next /dbs re-detects the profiles fresh.
|
|
1694
1830
|
resetDbState();
|
|
@@ -1807,6 +1943,8 @@ tab) {
|
|
|
1807
1943
|
if (switched) {
|
|
1808
1944
|
cleanupPulledDatabases();
|
|
1809
1945
|
logSession?.restart();
|
|
1946
|
+
// The old device's streamed switchboard records belong to the wrong hardware.
|
|
1947
|
+
clearSwitchboardHostStore();
|
|
1810
1948
|
}
|
|
1811
1949
|
// Reassert the forward is pointed at the selected device before reading. On a device
|
|
1812
1950
|
// switch or after a multi-process repoint (e.g., MCP server switched to a different
|
|
@@ -1829,6 +1967,33 @@ tab) {
|
|
|
1829
1967
|
device_serial: pinnedSerial(),
|
|
1830
1968
|
} };
|
|
1831
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
|
+
}
|
|
1832
1997
|
// activateAsync() never throws; a failed broadcast is recorded on the transport.
|
|
1833
1998
|
// Surfacing it here gives the dashboard user the actual adb error instead of a bare
|
|
1834
1999
|
// enabled:false after the ping probe times out. Async for the same reason as the boot chain:
|
|
@@ -1840,25 +2005,56 @@ tab) {
|
|
|
1840
2005
|
else {
|
|
1841
2006
|
transport.activate(transport.getTimeoutMinutes());
|
|
1842
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
|
+
}
|
|
1843
2015
|
const activateError = transport.getLastActivateError?.() ?? null;
|
|
1844
2016
|
if (activateError) {
|
|
1845
2017
|
return { status: 200, body: {
|
|
1846
2018
|
enabled: false,
|
|
1847
|
-
error:
|
|
2019
|
+
error: transport.supportsRadarHttpTools
|
|
2020
|
+
? `Broadcast failed: ${activateError}. Is the device connected?`
|
|
2021
|
+
: `Log capture activation failed: ${activateError}`,
|
|
1848
2022
|
instructs: false,
|
|
1849
2023
|
device_serial: pinnedSerial(),
|
|
1850
2024
|
} };
|
|
1851
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
|
+
}
|
|
1852
2033
|
// Verify by pinging the device the same way /health does (the shared pingDevice, so the
|
|
1853
2034
|
// ceiling and the three-state rules cannot drift from the other probe sites).
|
|
1854
|
-
|
|
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
|
+
}
|
|
1855
2047
|
const enabled = ping.state === "armed" && ping.status === 200;
|
|
1856
2048
|
// A verified arm refutes any cached "no_session" the same way a stream connect does (the
|
|
1857
2049
|
// memo is evidence about a session this route just restored): without this, another stream
|
|
1858
2050
|
// client's mid-retry memo read could announce the pre-arm diagnosis for up to its TTL and
|
|
1859
2051
|
// drive that tab to fire a spurious /enable against the live session.
|
|
1860
|
-
if (enabled)
|
|
2052
|
+
if (enabled) {
|
|
1861
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
|
+
}
|
|
1862
2058
|
// Probe the process state only on the failure path: a successful enable needs no diagnosis,
|
|
1863
2059
|
// and the probe is a real adb round trip. Capped short, because by this point the failure is
|
|
1864
2060
|
// already established and the user is watching a request that has stalled their SSE tabs; an
|
|
@@ -1880,62 +2076,398 @@ export const DEVICE_SOURCES = {
|
|
|
1880
2076
|
clog: { segment: "clogs", arrayKey: "clogs" },
|
|
1881
2077
|
trace: { segment: "traces", arrayKey: "traces" },
|
|
1882
2078
|
};
|
|
2079
|
+
// Switchboard (the Slackbot voice transport) is not a row above because the device keeps it two
|
|
2080
|
+
// levels deep: `GET /api/switchboard` lists session summaries newest first (`total_captured` is
|
|
2081
|
+
// the records the plugin holds; there is no count named `events`), `GET /api/switchboard/<session_id>`
|
|
2082
|
+
// is that summary plus `events`, the page of records oldest first (the newest `limit` of them; the
|
|
2083
|
+
// device pages at 50 when the query is absent, so the caller's limit is forwarded per session or
|
|
2084
|
+
// a talkative session replays as its last few seconds). Records carry a plugin-minted `id`
|
|
2085
|
+
// (strictly increasing across sessions), but there is no per-record /detail, so it stays out of
|
|
2086
|
+
// the table /detail reads. The session cap bounds the round trips on connect (one list plus one
|
|
2087
|
+
// fetch per session); `limit` bounds the records, per session and again on the merged total.
|
|
2088
|
+
// Shapes: SwitchboardSessionSummary in src/shared/wire.ts; `levels` there is unread here (no
|
|
2089
|
+
// waveform yet). The session pick and the paths live in src/shared/switchboard.ts so the MCP's
|
|
2090
|
+
// spool backfill replays the same sessions; re-exported here for the tests that pin them.
|
|
2091
|
+
export { SWITCHBOARD_KIND, SWITCHBOARD_BACKFILL_SESSIONS, SWITCHBOARD_BACKFILL_DEADLINE_MS };
|
|
2092
|
+
// How much longer than the switchboard leg's own deadline the /backfill route waits before it
|
|
2093
|
+
// replies with what has landed. Same-length timers fire in the order they were armed, and the
|
|
2094
|
+
// route's is armed first, so without this the route would reply before the leg could hand back the
|
|
2095
|
+
// sessions that answered.
|
|
2096
|
+
export const BACKFILL_ROUTE_HEADROOM_MS = 250;
|
|
2097
|
+
function getDeviceJson(apiPath, forwarded, onUnauthorized) {
|
|
2098
|
+
let rq;
|
|
2099
|
+
const result = new Promise((resolve) => {
|
|
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
|
+
}
|
|
2114
|
+
let b = "";
|
|
2115
|
+
up.on("data", (c) => (b += c));
|
|
2116
|
+
up.on("end", () => {
|
|
2117
|
+
try {
|
|
2118
|
+
const j = JSON.parse(b);
|
|
2119
|
+
resolve(j !== null && typeof j === "object" && !Array.isArray(j) ? j : null);
|
|
2120
|
+
}
|
|
2121
|
+
catch {
|
|
2122
|
+
resolve(null);
|
|
2123
|
+
}
|
|
2124
|
+
});
|
|
2125
|
+
up.on("error", () => resolve(null));
|
|
2126
|
+
});
|
|
2127
|
+
rq.on("error", () => resolve(null));
|
|
2128
|
+
rq.on("timeout", () => {
|
|
2129
|
+
rq?.destroy();
|
|
2130
|
+
resolve(null);
|
|
2131
|
+
});
|
|
2132
|
+
rq.on("close", () => resolve(null));
|
|
2133
|
+
rq.end();
|
|
2134
|
+
});
|
|
2135
|
+
return { result, abort: () => rq?.destroy() };
|
|
2136
|
+
}
|
|
2137
|
+
// The switchboard replay: the newest SWITCHBOARD_BACKFILL_SESSIONS sessions' records, oldest first,
|
|
2138
|
+
// trimmed to the newest `limit` records overall, as `{type: "switchboard", event}` frames.
|
|
2139
|
+
// Exported so a test can drive it against a fake device without going through the route; the
|
|
2140
|
+
// deadline is a parameter for the same reason. Each session's page is kept as it lands, so when
|
|
2141
|
+
// the deadline fires the reply is whatever arrived by then (a device sitting on one session's
|
|
2142
|
+
// route costs that session, not the whole replay), and the requests still open are dropped.
|
|
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) {
|
|
2146
|
+
return new Promise((resolve) => {
|
|
2147
|
+
const landed = [];
|
|
2148
|
+
const inflight = new Set();
|
|
2149
|
+
let settled = false;
|
|
2150
|
+
const finish = () => {
|
|
2151
|
+
if (settled)
|
|
2152
|
+
return;
|
|
2153
|
+
settled = true;
|
|
2154
|
+
clearTimeout(timer);
|
|
2155
|
+
for (const g of inflight)
|
|
2156
|
+
g.abort();
|
|
2157
|
+
inflight.clear();
|
|
2158
|
+
resolve(newestSwitchboardRecords(landed.flat(), limit));
|
|
2159
|
+
};
|
|
2160
|
+
const timer = setTimeout(finish, deadlineMs);
|
|
2161
|
+
fetchSwitchboardSessions(limit, landed, inflight, forwarded, onUnauthorized).then(finish, finish);
|
|
2162
|
+
});
|
|
2163
|
+
}
|
|
2164
|
+
// Lists the sessions, then fetches the newest few in parallel, pushing each page onto `landed`
|
|
2165
|
+
// as it arrives and keeping the open requests in `inflight` for the deadline above.
|
|
2166
|
+
async function fetchSwitchboardSessions(limit, landed, inflight, forwarded, onUnauthorized) {
|
|
2167
|
+
const get = async (apiPath) => {
|
|
2168
|
+
const g = getDeviceJson(apiPath, forwarded, onUnauthorized);
|
|
2169
|
+
inflight.add(g);
|
|
2170
|
+
try {
|
|
2171
|
+
return await g.result;
|
|
2172
|
+
}
|
|
2173
|
+
finally {
|
|
2174
|
+
inflight.delete(g);
|
|
2175
|
+
}
|
|
2176
|
+
};
|
|
2177
|
+
const list = await get(switchboardListPath());
|
|
2178
|
+
await Promise.all(newestSwitchboardSessionIds(list).map(async (id) => {
|
|
2179
|
+
// `events` is the page of records on this route; the list route's count is `total_captured`.
|
|
2180
|
+
landed.push(switchboardPageEvents(await get(switchboardSessionPath(id, limit))));
|
|
2181
|
+
}));
|
|
2182
|
+
}
|
|
2183
|
+
// The merge order for every backfill: the record's own device timestamp, 0 when it has none.
|
|
2184
|
+
const when = (e) => Number(e.timestamp) || 0;
|
|
2185
|
+
// Oldest first by the record's own timestamp, then the newest `limit` kept. The pages arrive in
|
|
2186
|
+
// whatever order the device answers, so arrival order says nothing about time; the sort is stable,
|
|
2187
|
+
// so records sharing a timestamp keep the order the device wrote them in.
|
|
2188
|
+
function newestSwitchboardRecords(records, limit) {
|
|
2189
|
+
const sorted = [...records].sort((a, b) => when(a) - when(b));
|
|
2190
|
+
return sorted.slice(Math.max(0, sorted.length - limit)).map((e) => ({ type: SWITCHBOARD_KIND, event: e }));
|
|
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
|
+
}
|
|
1883
2365
|
/**
|
|
1884
2366
|
* Replay the device's recent ring buffers for a source so a freshly-built tab
|
|
1885
2367
|
* shows history immediately instead of filling only going forward. The device is
|
|
1886
|
-
* the source of truth. "all" pulls network+rtm+clog+trace and merges them
|
|
1887
|
-
* "log" is host-side (no device buffer) and so has nothing to replay. Returns
|
|
1888
|
-
* `[{type, event}]` frames mirroring the stream shape.
|
|
2368
|
+
* the source of truth. "all" pulls network+rtm+clog+trace+switchboard and merges them
|
|
2369
|
+
* oldest->newest; "log" is host-side (no device buffer) and so has nothing to replay. Returns
|
|
2370
|
+
* `[{type, event}]` frames mirroring the stream shape. Switchboard records carry `timestamp`
|
|
2371
|
+
* (epoch ms) like the ring kinds, so one sort key orders the merge.
|
|
1889
2372
|
*/
|
|
1890
2373
|
function handleBackfill(req, res) {
|
|
1891
2374
|
// Reassert before reading: see forwardForRead's doc comment. A failed reassert still
|
|
1892
2375
|
// falls through to the request below rather than erroring out here -- the device-side
|
|
1893
2376
|
// request will surface its own connection failure, matching the pre-existing behavior
|
|
1894
2377
|
// when the forward was never set up at all.
|
|
1895
|
-
forwardForRead();
|
|
2378
|
+
const forwarded = forwardForRead();
|
|
1896
2379
|
const u = new URL(req.url ?? "", `http://localhost:${WEB_PORT}`);
|
|
1897
2380
|
const src = u.searchParams.get("source") ?? "network";
|
|
1898
|
-
|
|
2381
|
+
// Clamped below at 1: a negative limit would slice the switchboard replay to nothing. Truncated
|
|
2382
|
+
// first so a fractional limit reaches the device as a whole number it can parse.
|
|
2383
|
+
const limit = Math.max(1, Math.min(500, Math.trunc(Number(u.searchParams.get("limit"))) || 200));
|
|
1899
2384
|
const kinds = src === "all"
|
|
1900
2385
|
? Object.keys(DEVICE_SOURCES)
|
|
1901
2386
|
: [src].filter((k) => Object.hasOwn(DEVICE_SOURCES, k));
|
|
2387
|
+
const wantsSwitchboard = src === "all" || src === SWITCHBOARD_KIND;
|
|
2388
|
+
// Every leg lands its frames here as it finishes; the reply is whatever has landed when the last
|
|
2389
|
+
// leg settles or the route's deadline fires, whichever is first. A ring leg has only the
|
|
2390
|
+
// socket's inactivity timeout, which measures silence, not progress: the device writes each
|
|
2391
|
+
// body in one go, but a large page over a slow adb pipe keeps bytes trickling and a wedged
|
|
2392
|
+
// tunnel can stall mid-body, and either would otherwise hold the whole reply. The switchboard
|
|
2393
|
+
// leg keeps its own deadline, armed later and for the same span, so the route gives it headroom
|
|
2394
|
+
// to fire first and hand back the sessions that did answer; a slow session route then costs that
|
|
2395
|
+
// session alone, not the replay.
|
|
2396
|
+
const landed = [];
|
|
2397
|
+
const inflight = new Set();
|
|
2398
|
+
let settled = false;
|
|
2399
|
+
let rejected = false;
|
|
2400
|
+
const refused = () => { rejected = true; };
|
|
2401
|
+
const finish = () => {
|
|
2402
|
+
if (settled)
|
|
2403
|
+
return;
|
|
2404
|
+
settled = true;
|
|
2405
|
+
clearTimeout(timer);
|
|
2406
|
+
for (const rq of inflight)
|
|
2407
|
+
rq.destroy();
|
|
2408
|
+
inflight.clear();
|
|
2409
|
+
const merged = landed.flat().sort((a, b) => when(a.event) - when(b.event));
|
|
2410
|
+
sendJson(res, 200, { frames: merged, ...(rejected ? { error: refusalSentence(forwarded) } : {}) });
|
|
2411
|
+
};
|
|
2412
|
+
// The ceiling for every leg, ring legs included: the switchboard span already sits above the
|
|
2413
|
+
// ring legs' 4 s socket timeout, so one number serves both.
|
|
2414
|
+
const timer = setTimeout(finish, SWITCHBOARD_BACKFILL_DEADLINE_MS + BACKFILL_ROUTE_HEADROOM_MS);
|
|
1902
2415
|
const fetchKind = (kind) => new Promise((resolve) => {
|
|
1903
2416
|
const apiPath = `/api/${DEVICE_SOURCES[kind].segment}?limit=${limit}`;
|
|
2417
|
+
// Settles once whichever of end, error, timeout or close comes first; the route's deadline
|
|
2418
|
+
// destroys the request, which raises close with no error, so close settles it too.
|
|
2419
|
+
let legDone = false;
|
|
2420
|
+
const done = (frames) => {
|
|
2421
|
+
if (legDone)
|
|
2422
|
+
return;
|
|
2423
|
+
legDone = true;
|
|
2424
|
+
inflight.delete(rq);
|
|
2425
|
+
landed.push(frames);
|
|
2426
|
+
resolve();
|
|
2427
|
+
};
|
|
1904
2428
|
const rq = http.request({
|
|
1905
2429
|
host: RADAR_HOST,
|
|
1906
2430
|
port: RADAR_PORT,
|
|
2431
|
+
headers: deviceTokenHeader(forwarded),
|
|
1907
2432
|
path: apiPath,
|
|
1908
2433
|
method: "GET",
|
|
1909
2434
|
timeout: 4000,
|
|
1910
2435
|
}, (up) => {
|
|
2436
|
+
if (up.statusCode === 401) {
|
|
2437
|
+
refused();
|
|
2438
|
+
up.resume();
|
|
2439
|
+
done([]);
|
|
2440
|
+
return;
|
|
2441
|
+
}
|
|
1911
2442
|
let b = "";
|
|
1912
2443
|
up.on("data", (c) => (b += c));
|
|
2444
|
+
up.on("error", () => done([]));
|
|
1913
2445
|
up.on("end", () => {
|
|
1914
2446
|
try {
|
|
1915
2447
|
const j = JSON.parse(b);
|
|
1916
2448
|
const arr = j[DEVICE_SOURCES[kind].arrayKey] ?? [];
|
|
1917
|
-
|
|
2449
|
+
done(arr.map((e) => ({ type: kind, event: e })));
|
|
1918
2450
|
}
|
|
1919
2451
|
catch {
|
|
1920
|
-
|
|
2452
|
+
done([]);
|
|
1921
2453
|
}
|
|
1922
2454
|
});
|
|
1923
2455
|
});
|
|
1924
|
-
|
|
2456
|
+
inflight.add(rq);
|
|
2457
|
+
rq.on("error", () => done([]));
|
|
2458
|
+
rq.on("close", () => done([]));
|
|
1925
2459
|
rq.on("timeout", () => {
|
|
1926
2460
|
rq.destroy();
|
|
1927
|
-
|
|
2461
|
+
done([]);
|
|
1928
2462
|
});
|
|
1929
2463
|
rq.end();
|
|
1930
2464
|
});
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
.
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
})
|
|
1938
|
-
.catch(() => sendJson(res, 200, { frames: [] }));
|
|
2465
|
+
const legs = kinds.map(fetchKind);
|
|
2466
|
+
if (wantsSwitchboard) {
|
|
2467
|
+
legs.push(fetchSwitchboardBackfill(limit, SWITCHBOARD_BACKFILL_DEADLINE_MS, forwarded, refused)
|
|
2468
|
+
.then((frames) => { landed.push(frames); }));
|
|
2469
|
+
}
|
|
2470
|
+
Promise.all(legs).then(finish, finish);
|
|
1939
2471
|
}
|
|
1940
2472
|
/**
|
|
1941
2473
|
* Finish a /detail proxy response after an upstream error or timeout. The success
|
|
@@ -1947,7 +2479,7 @@ function handleBackfill(req, res) {
|
|
|
1947
2479
|
*/
|
|
1948
2480
|
export function failDetailResponse(res, status) {
|
|
1949
2481
|
if (!res.headersSent) {
|
|
1950
|
-
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" });
|
|
1951
2483
|
res.end("{}");
|
|
1952
2484
|
}
|
|
1953
2485
|
else {
|
|
@@ -1960,7 +2492,7 @@ export function failDetailResponse(res, status) {
|
|
|
1960
2492
|
*/
|
|
1961
2493
|
function handleDetail(req, res) {
|
|
1962
2494
|
// Reassert before reading: see forwardForRead's doc comment.
|
|
1963
|
-
forwardForRead();
|
|
2495
|
+
const forwarded = forwardForRead();
|
|
1964
2496
|
const u = new URL(req.url ?? "", `http://localhost:${WEB_PORT}`);
|
|
1965
2497
|
const id = u.searchParams.get("id");
|
|
1966
2498
|
const kind = u.searchParams.get("kind") ?? "network";
|
|
@@ -1973,12 +2505,14 @@ function handleDetail(req, res) {
|
|
|
1973
2505
|
const upstream = http.request({
|
|
1974
2506
|
host: RADAR_HOST,
|
|
1975
2507
|
port: RADAR_PORT,
|
|
2508
|
+
headers: deviceTokenHeader(forwarded),
|
|
1976
2509
|
path: `/api/${route}/${encodeURIComponent(id)}`,
|
|
1977
2510
|
method: "GET",
|
|
1978
2511
|
timeout: 4000,
|
|
1979
2512
|
}, (up) => {
|
|
1980
2513
|
res.writeHead(up.statusCode ?? 502, {
|
|
1981
2514
|
"Content-Type": "application/json; charset=utf-8",
|
|
2515
|
+
"X-Content-Type-Options": "nosniff",
|
|
1982
2516
|
});
|
|
1983
2517
|
up.on("data", (c) => res.write(c));
|
|
1984
2518
|
up.on("end", () => res.end());
|
|
@@ -2002,9 +2536,15 @@ function handleDetail(req, res) {
|
|
|
2002
2536
|
// as `feature_flag` frames on /api/stream (the on-device observer). Builds predating the plugin
|
|
2003
2537
|
// 404, surfaced as a friendly message client-side.
|
|
2004
2538
|
function handleFlags(req, res) {
|
|
2539
|
+
const forwarded = forwardForRead();
|
|
2005
2540
|
const u = new URL(req.url ?? "", `http://localhost:${WEB_PORT}`);
|
|
2006
2541
|
const path = `/api/feature_flags${u.search}`;
|
|
2007
|
-
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
|
+
}
|
|
2008
2548
|
let body = "";
|
|
2009
2549
|
up.on("data", (c) => (body += c));
|
|
2010
2550
|
up.on("end", () => {
|
|
@@ -2503,82 +3043,6 @@ function handleScreen(req, res) {
|
|
|
2503
3043
|
res.writeHead(404);
|
|
2504
3044
|
res.end("Not found");
|
|
2505
3045
|
}
|
|
2506
|
-
// Logcat line parsing for the host-side log merge. Format:
|
|
2507
|
-
// "MM-DD HH:MM:SS.mmm PID TID L Tag: message"
|
|
2508
|
-
const LOG_LINE_RE = /^(\d\d-\d\d \d\d:\d\d:\d\d\.\d+)\s+(\d+)\s+(\d+)\s+([VDIWEF])\s+([^:]*?):\s?(.*)$/;
|
|
2509
|
-
const LOG_LEVELS = {
|
|
2510
|
-
V: "VERBOSE",
|
|
2511
|
-
D: "DEBUG",
|
|
2512
|
-
I: "INFO",
|
|
2513
|
-
W: "WARN",
|
|
2514
|
-
E: "ERROR",
|
|
2515
|
-
F: "FATAL",
|
|
2516
|
-
};
|
|
2517
|
-
// A logcat line carries a PID, not a package, but the dashboard filters logs by
|
|
2518
|
-
// package (e.g. "Slack app only"). Resolve PID -> process name from
|
|
2519
|
-
// `adb shell ps -A -o PID,NAME`, cached and refreshed on a miss (rate-limited), so
|
|
2520
|
-
// log rows get a readable `package` and the package filter works. Without this the
|
|
2521
|
-
// Live/Logs presets (match {package: ...}) drop every log line.
|
|
2522
|
-
const pidToPackage = new Map();
|
|
2523
|
-
let pidRefreshing = false;
|
|
2524
|
-
let lastPidRefresh = 0;
|
|
2525
|
-
function refreshPidMap() {
|
|
2526
|
-
if (pidRefreshing)
|
|
2527
|
-
return;
|
|
2528
|
-
const adb = resolveAdbPath();
|
|
2529
|
-
if (!adb)
|
|
2530
|
-
return;
|
|
2531
|
-
pidRefreshing = true;
|
|
2532
|
-
lastPidRefresh = Date.now();
|
|
2533
|
-
const ps = spawn(adb, ["shell", "ps", "-A", "-o", "PID,NAME"]);
|
|
2534
|
-
let out = "";
|
|
2535
|
-
ps.stdout?.on("data", (c) => (out += c.toString()));
|
|
2536
|
-
ps.on("error", () => {
|
|
2537
|
-
pidRefreshing = false;
|
|
2538
|
-
});
|
|
2539
|
-
ps.on("close", () => {
|
|
2540
|
-
pidRefreshing = false;
|
|
2541
|
-
for (const line of out.split("\n")) {
|
|
2542
|
-
const m = line.trim().match(/^(\d+)\s+(\S+)$/);
|
|
2543
|
-
if (m)
|
|
2544
|
-
pidToPackage.set(Number(m[1]), m[2]);
|
|
2545
|
-
}
|
|
2546
|
-
});
|
|
2547
|
-
}
|
|
2548
|
-
function packageForPid(pid) {
|
|
2549
|
-
const hit = pidToPackage.get(pid);
|
|
2550
|
-
if (hit)
|
|
2551
|
-
return hit;
|
|
2552
|
-
// Unknown pid: trigger a rate-limited refresh so the NEXT line resolves.
|
|
2553
|
-
if (Date.now() - lastPidRefresh > 3000)
|
|
2554
|
-
refreshPidMap();
|
|
2555
|
-
return undefined;
|
|
2556
|
-
}
|
|
2557
|
-
let logIdSeq = 0;
|
|
2558
|
-
/**
|
|
2559
|
-
* Parse one `adb logcat -v threadtime` line into a structured event, or null if it does
|
|
2560
|
-
* not match the format. `resolvePkg` maps a pid to its package name (defaults to the
|
|
2561
|
-
* live adb-backed resolver); injectable so this stays a pure, unit-testable function.
|
|
2562
|
-
* Exported for tests.
|
|
2563
|
-
*/
|
|
2564
|
-
export function parseLogcat(line, resolvePkg = packageForPid) {
|
|
2565
|
-
const m = line.match(LOG_LINE_RE);
|
|
2566
|
-
if (!m)
|
|
2567
|
-
return null;
|
|
2568
|
-
const [, ts, pid, tid, level, tag, message] = m;
|
|
2569
|
-
const pidN = Number(pid);
|
|
2570
|
-
return {
|
|
2571
|
-
id: ++logIdSeq,
|
|
2572
|
-
timestamp: Date.now(),
|
|
2573
|
-
log_ts: ts,
|
|
2574
|
-
pid: pidN,
|
|
2575
|
-
tid: Number(tid),
|
|
2576
|
-
level: LOG_LEVELS[level] ?? level,
|
|
2577
|
-
tag: tag.trim(),
|
|
2578
|
-
message,
|
|
2579
|
-
package: resolvePkg(pidN),
|
|
2580
|
-
};
|
|
2581
|
-
}
|
|
2582
3046
|
// How long a freshly opened device stream may go without response HEADERS before the attempt is
|
|
2583
3047
|
// declared dead. A healthy device answers /api/stream immediately; the pathological case this
|
|
2584
3048
|
// bounds is a dead device-side socket behind a LIVE adb forward, where the host adb server
|
|
@@ -2620,6 +3084,36 @@ let outageDiagnosisInflight = null;
|
|
|
2620
3084
|
// re-drop of this one would inherit "no_session" for the full TTL and re-arm against the
|
|
2621
3085
|
// live session.
|
|
2622
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
|
+
}
|
|
2623
3117
|
// Test seam: the real probe reaches a physical device over adb, which a test host may or may
|
|
2624
3118
|
// not have, so tests pin the answer instead of inheriting whatever hardware is attached.
|
|
2625
3119
|
let outageProbe = () => transport.radarSocketPresentAsync?.() ?? Promise.resolve("unknown");
|
|
@@ -2730,6 +3224,9 @@ function handleStream(req, res) {
|
|
|
2730
3224
|
let closed = false;
|
|
2731
3225
|
let lastState = "";
|
|
2732
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;
|
|
2733
3230
|
let headersDeadline = null;
|
|
2734
3231
|
const announce = (state, msg, reason) => {
|
|
2735
3232
|
// Dedup on state AND reason, with one asymmetry: a diagnosed outage keeps its diagnosis.
|
|
@@ -2758,14 +3255,14 @@ function handleStream(req, res) {
|
|
|
2758
3255
|
// proxy retry loop. Calling this on reconnect heals logs on the same path.
|
|
2759
3256
|
const spec = loadSpec();
|
|
2760
3257
|
const wantsLogs = spec.source === "log" || spec.source === "all";
|
|
2761
|
-
const
|
|
3258
|
+
const supportsDeviceStream = !!transport.supportsRadarHttpTools;
|
|
3259
|
+
const armLogs = () => {
|
|
2762
3260
|
if (!wantsLogs || closed)
|
|
2763
3261
|
return;
|
|
2764
3262
|
const ok = logSession?.start() ?? false;
|
|
2765
3263
|
if (!ok) {
|
|
2766
|
-
|
|
2767
|
-
|
|
2768
|
-
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`}`);
|
|
2769
3266
|
}
|
|
2770
3267
|
};
|
|
2771
3268
|
let retries = 0;
|
|
@@ -2823,15 +3320,18 @@ function handleStream(req, res) {
|
|
|
2823
3320
|
// cannot silently move only one of them.
|
|
2824
3321
|
setTimeout(connect, planReconnect(transport, retries));
|
|
2825
3322
|
};
|
|
2826
|
-
const
|
|
3323
|
+
const connectVerified = () => {
|
|
2827
3324
|
if (closed)
|
|
2828
3325
|
return;
|
|
3326
|
+
if (!supportsDeviceStream)
|
|
3327
|
+
return;
|
|
3328
|
+
const attempt = ++attemptSeq;
|
|
2829
3329
|
settled = false;
|
|
2830
3330
|
// Reassert before every connect (initial AND each retry): see forwardForRead's doc
|
|
2831
3331
|
// comment. planReconnect already forces a hard forward rebuild on every OTHER retry
|
|
2832
3332
|
// (tuned for "device end died"), which would only catch a foreign repoint by luck on
|
|
2833
3333
|
// half of attempts; this cheap check-first call covers every attempt instead.
|
|
2834
|
-
forwardForRead();
|
|
3334
|
+
const forwarded = forwardForRead();
|
|
2835
3335
|
// Bound the wait for response headers: see STREAM_RESPONSE_TIMEOUT_MS. Without this, the
|
|
2836
3336
|
// accepted-but-never-answered connect mode fires none of the callbacks below and the
|
|
2837
3337
|
// stream sits silent forever — no _status, no retry, nothing for a client to act on.
|
|
@@ -2839,6 +3339,8 @@ function handleStream(req, res) {
|
|
|
2839
3339
|
// teardown: each attempt's handlers clear their OWN deadline, so a stale attempt's late
|
|
2840
3340
|
// error event can never clear the live attempt's timer out from under it.
|
|
2841
3341
|
const myDeadline = setTimeout(() => {
|
|
3342
|
+
if (attempt !== attemptSeq)
|
|
3343
|
+
return;
|
|
2842
3344
|
if (closed)
|
|
2843
3345
|
return;
|
|
2844
3346
|
announce("waiting", "device not answering, retrying…");
|
|
@@ -2854,12 +3356,30 @@ function handleStream(req, res) {
|
|
|
2854
3356
|
upstream = http.request({
|
|
2855
3357
|
host: RADAR_HOST,
|
|
2856
3358
|
port: RADAR_PORT,
|
|
3359
|
+
headers: { Accept: "text/event-stream", ...deviceTokenHeader(forwarded) },
|
|
2857
3360
|
path: "/api/stream",
|
|
2858
3361
|
method: "GET",
|
|
2859
3362
|
}, (up) => {
|
|
3363
|
+
if (attempt !== attemptSeq)
|
|
3364
|
+
return;
|
|
2860
3365
|
clearTimeout(myDeadline);
|
|
2861
3366
|
if (headersDeadline === myDeadline)
|
|
2862
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
|
+
}
|
|
2863
3383
|
// A fresh outage on a long-lived connection must diagnose as early as the first one:
|
|
2864
3384
|
// the "second failure" trigger and planReconnect's every-other-attempt forward
|
|
2865
3385
|
// rebuild both key off this counter, and neither should inherit the count from an
|
|
@@ -2874,18 +3394,51 @@ function handleStream(req, res) {
|
|
|
2874
3394
|
// Re-arm logs on the same path the device proxy heals on: if the device
|
|
2875
3395
|
// dropped and came back, `adb logcat` had exited; restart it (idempotent)
|
|
2876
3396
|
// so the live log feed resumes without needing a browser reconnect.
|
|
2877
|
-
|
|
2878
|
-
|
|
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
|
+
});
|
|
2879
3426
|
up.on("end", () => {
|
|
3427
|
+
if (attempt !== attemptSeq)
|
|
3428
|
+
return;
|
|
2880
3429
|
announce("waiting", "device stream ended, retrying…");
|
|
2881
3430
|
retry();
|
|
2882
3431
|
});
|
|
2883
3432
|
up.on("error", () => {
|
|
3433
|
+
if (attempt !== attemptSeq)
|
|
3434
|
+
return;
|
|
2884
3435
|
announce("waiting", "device stream error, retrying…");
|
|
2885
3436
|
retry();
|
|
2886
3437
|
});
|
|
2887
3438
|
});
|
|
2888
3439
|
upstream.on("error", () => {
|
|
3440
|
+
if (attempt !== attemptSeq)
|
|
3441
|
+
return;
|
|
2889
3442
|
clearTimeout(myDeadline);
|
|
2890
3443
|
if (headersDeadline === myDeadline)
|
|
2891
3444
|
headersDeadline = null;
|
|
@@ -2894,7 +3447,47 @@ function handleStream(req, res) {
|
|
|
2894
3447
|
});
|
|
2895
3448
|
upstream.end();
|
|
2896
3449
|
};
|
|
2897
|
-
|
|
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
|
+
}
|
|
2898
3491
|
const heartbeat = setInterval(() => {
|
|
2899
3492
|
if (!closed)
|
|
2900
3493
|
res.write(": hb\n\n");
|
|
@@ -2907,9 +3500,22 @@ function handleStream(req, res) {
|
|
|
2907
3500
|
// is persistent and shared, so a tab switch only adds/removes a listener — it
|
|
2908
3501
|
// never tears down the capture or loses lines in a reconnect gap.
|
|
2909
3502
|
let unsubscribeLogs = null;
|
|
3503
|
+
let unsubscribeLogStatus = null;
|
|
2910
3504
|
if (wantsLogs) {
|
|
2911
|
-
|
|
2912
|
-
|
|
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
|
|
2913
3519
|
unsubscribeLogs = logSession?.subscribe((ev, replay) => {
|
|
2914
3520
|
if (closed)
|
|
2915
3521
|
return;
|
|
@@ -2944,11 +3550,15 @@ function handleStream(req, res) {
|
|
|
2944
3550
|
}
|
|
2945
3551
|
req.on("close", () => {
|
|
2946
3552
|
closed = true;
|
|
3553
|
+
// A closed response must not be woken or keep its closure in the set.
|
|
3554
|
+
refusedStreams.delete(wake);
|
|
2947
3555
|
clearInterval(heartbeat);
|
|
2948
3556
|
if (headersDeadline)
|
|
2949
3557
|
clearTimeout(headersDeadline);
|
|
2950
3558
|
if (unsubscribeLogs)
|
|
2951
3559
|
unsubscribeLogs(); // detach listener; capture stays up
|
|
3560
|
+
if (unsubscribeLogStatus)
|
|
3561
|
+
unsubscribeLogStatus();
|
|
2952
3562
|
try {
|
|
2953
3563
|
upstream?.destroy();
|
|
2954
3564
|
}
|
|
@@ -2958,9 +3568,13 @@ function handleStream(req, res) {
|
|
|
2958
3568
|
});
|
|
2959
3569
|
}
|
|
2960
3570
|
function listProfiles(res) {
|
|
2961
|
-
|
|
2962
|
-
|
|
2963
|
-
|
|
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
|
+
}
|
|
2964
3578
|
}
|
|
2965
3579
|
// The attached-device list + the currently pinned device, for the dashboard's device picker.
|
|
2966
3580
|
// listDevices() returns null when the platform listing itself failed (not "zero attached"). Keep
|
|
@@ -2981,6 +3595,7 @@ function activateRadar(res, userId) {
|
|
|
2981
3595
|
// Reset cached state so ensureForward() re-runs adb forward. This handles
|
|
2982
3596
|
// stale forwards after device-side idle timeout or profile switching.
|
|
2983
3597
|
transport.resetState();
|
|
3598
|
+
clearRadarTokenCache();
|
|
2984
3599
|
const forwarded = transport.ensureForward();
|
|
2985
3600
|
if (!forwarded) {
|
|
2986
3601
|
sendJson(res, 502, {
|
|
@@ -3000,36 +3615,59 @@ function activateRadar(res, userId) {
|
|
|
3000
3615
|
catch (e) {
|
|
3001
3616
|
sendJson(res, 502, {
|
|
3002
3617
|
ok: false,
|
|
3003
|
-
error:
|
|
3618
|
+
error: e instanceof TokenFileError
|
|
3619
|
+
? tokenFileMessage(e, "dashboard")
|
|
3620
|
+
: `Broadcast failed: ${e.message}. Is the device connected?`,
|
|
3004
3621
|
});
|
|
3005
3622
|
return;
|
|
3006
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
|
+
}
|
|
3007
3634
|
sendJson(res, 200, {
|
|
3008
3635
|
ok: true,
|
|
3009
3636
|
user_id: userId ?? transport.getActiveUserId() ?? "auto",
|
|
3010
3637
|
});
|
|
3011
3638
|
}
|
|
3639
|
+
/** Status and body pass through untouched, including a 401; dashboard sentences live on the named routes. */
|
|
3012
3640
|
function proxyToRadar(req, res) {
|
|
3641
|
+
const forwarded = forwardForRead();
|
|
3642
|
+
const headers = radarProxyHeaders(req.method, req.headers, forwarded);
|
|
3013
3643
|
const upstream = http.request({
|
|
3014
3644
|
host: RADAR_HOST,
|
|
3015
3645
|
port: RADAR_PORT,
|
|
3016
3646
|
path: req.url,
|
|
3017
3647
|
method: req.method,
|
|
3018
|
-
headers
|
|
3648
|
+
headers,
|
|
3019
3649
|
timeout: 0,
|
|
3020
3650
|
}, (upstreamRes) => {
|
|
3021
|
-
res.writeHead(upstreamRes.statusCode ?? 502,
|
|
3651
|
+
res.writeHead(upstreamRes.statusCode ?? 502, {
|
|
3652
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
3653
|
+
"X-Content-Type-Options": "nosniff",
|
|
3654
|
+
});
|
|
3022
3655
|
upstreamRes.on("data", (chunk) => res.write(chunk));
|
|
3023
3656
|
upstreamRes.on("end", () => res.end());
|
|
3024
3657
|
upstreamRes.on("error", () => res.end());
|
|
3025
3658
|
});
|
|
3026
3659
|
upstream.on("error", (err) => {
|
|
3027
|
-
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" });
|
|
3028
3661
|
res.end(JSON.stringify({
|
|
3029
3662
|
error: `Cannot reach radar at ${RADAR_HOST}:${RADAR_PORT}. Is ADB forwarding active? ${err.message}`,
|
|
3030
3663
|
}));
|
|
3031
3664
|
});
|
|
3032
|
-
req
|
|
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
|
+
});
|
|
3033
3671
|
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
3034
3672
|
req.pipe(upstream);
|
|
3035
3673
|
}
|
|
@@ -3037,4 +3675,26 @@ function proxyToRadar(req, res) {
|
|
|
3037
3675
|
upstream.end();
|
|
3038
3676
|
}
|
|
3039
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
|
+
}
|
|
3040
3700
|
export { WEB_PORT };
|