@slack/radar-mcp 1.13.0 → 1.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -0
- package/dist/mcp/index.js +9 -2
- package/dist/web/bin.js +16 -6
- package/dist/web/public/index.html +1 -0
- package/dist/web/public/next/app.js +39 -1
- package/dist/web/public/next/db.js +8 -2
- package/dist/web/public/next/screen.js +10 -4
- package/dist/web/public/next/store.js +50 -5
- package/dist/web/server.d.ts +150 -1
- package/dist/web/server.js +469 -17
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -65,6 +65,19 @@ A **▣ Screen** button opens a side panel that mirrors the live device screen,
|
|
|
65
65
|
* ADB with a single connected device (USB or wireless debug)
|
|
66
66
|
* A debug build of Slack installed on the device (must include the `slack-radar` modules)
|
|
67
67
|
|
|
68
|
+
## Environment Variables
|
|
69
|
+
|
|
70
|
+
All optional. Set them on the process that runs the MCP server or the dashboard. One further variable, `SLACK_RADAR_INITIAL_SPEC`, is set automatically when a tool spawns the dashboard and is not meant to be set by hand.
|
|
71
|
+
|
|
72
|
+
| Variable | Effect |
|
|
73
|
+
|---|---|
|
|
74
|
+
| `SLACK_RADAR_WEB_PORT` | Port the dashboard listens on. Default `8100`. |
|
|
75
|
+
| `SLACK_RADAR_DEVICE_PORT` | Host port forwarded to the device-side server. Default `8099`. |
|
|
76
|
+
| `SLACK_RADAR_NO_AUTO_CLOSE=1` | Keep the dashboard running forever instead of closing it once every tab is gone. |
|
|
77
|
+
| `SLACK_RADAR_ALLOWED_HOSTS` | Extra `Host` values the dashboard will answer, comma-separated (`radar.local,myhost:8100`). Only needed when you reach it by a name other than localhost. See Security. |
|
|
78
|
+
| `SLACK_RADAR_NO_OPEN=1` | Do not open a browser window on launch. Set automatically when an MCP tool spawns the dashboard. |
|
|
79
|
+
| `SLACK_RADAR_NO_FFMPEG=1` | Pretend ffmpeg is absent, so screen recording degrades to screenshots. |
|
|
80
|
+
|
|
68
81
|
## Session Management
|
|
69
82
|
|
|
70
83
|
Radar starts **disabled** each session. All tools except `ping` return an error until enabled.
|
|
@@ -140,6 +153,9 @@ All device-specific logic lives behind the `DeviceTransport` interface (`src/sha
|
|
|
140
153
|
* **Debug builds only.** Release builds bind a no-op implementation. Server code is eliminated at compile time.
|
|
141
154
|
* **Lazy activation.** Dormant until explicitly triggered.
|
|
142
155
|
* **Auto-shutdown.** Device-side server shuts down after idle timeout (default 5 minutes). Zero cost when unused.
|
|
156
|
+
* **Dashboard auto-close.** Once a dashboard has been opened in a browser, the process shuts itself down roughly 6 minutes after the last tab closes, so a dashboard you walked away from does not linger. Opening a dashboard again (`open_radar_dashboard`, which writes a spec) pushes that deadline out by another grace window, but nothing else does: the other MCP tools read the device directly and never touch the dashboard, so a long agent session with no tab open will still close on schedule. Reopen it, or use the opt-out below, if you want it to stay. Two more exceptions: a dashboard that no tab has **ever** opened (one an agent spawned and nobody visited) stays up until you visit it once or stop it, because there is no "last tab closed" moment to measure from; and when you first upgrade to a version that has auto-close, **reload any tab that was already open** — page code from before this feature does not report itself as present, so it will not keep the process alive even while you are looking at it. Reloading once is enough; later upgrades do not need it. Click **⏻ Stop dashboard** in the header to stop it immediately instead (click twice to confirm — it kills the process with no undo). Set `SLACK_RADAR_NO_AUTO_CLOSE=1` to turn auto-close off entirely.
|
|
157
|
+
* **Keep-alive is not forgeable from a web page.** Only the dashboard's own client and the MCP can postpone auto-close. A write to `/setspec` or `/enable` has to carry `X-Radar-Dashboard: 1`, or a content-type whose type is exactly `application/json`; the `/health` presence ping requires the header specifically, since a content-type says nothing about a request with no body. A cross-origin request cannot set either one without a CORS preflight it will fail. A request without either still works and still writes, it just does not extend the process lifetime, so `curl -X POST .../setspec -H 'Content-Type: text/plain'` sets the spec but will not stop the dashboard closing on schedule; use `-H 'Content-Type: application/json'` if you want it to count. This is a CSRF guard, not authentication: any local process can send either header, and the port is loopback-only by design.
|
|
158
|
+
* **Loopback `Host` only.** The dashboard answers a request only when its `Host` header names this machine (`localhost`, `127.0.0.1`, `[::1]`, `0.0.0.0`, with or without a port). Anything else gets a 403 whose body names the host it refused and how to allow it. Binding to 127.0.0.1 alone is not enough: a page that resolves its own domain to 127.0.0.1 connects locally, counts as same-origin in the browser, and could otherwise set the header above and stop your dashboard. If you reach the dashboard by some other name — a `/etc/hosts` alias, a container or Codespaces forwarded URL, your machine's LAN hostname — list it in `SLACK_RADAR_ALLOWED_HOSTS` (comma-separated, host or `host:port`). A plain SSH or VS Code port forward needs nothing, because the `Host` stays `localhost`.
|
|
143
159
|
|
|
144
160
|
## Data Capture
|
|
145
161
|
|
package/dist/mcp/index.js
CHANGED
|
@@ -100,7 +100,14 @@ function postSpec(spec) {
|
|
|
100
100
|
port: WEB_PORT,
|
|
101
101
|
path: "/setspec",
|
|
102
102
|
method: "POST",
|
|
103
|
-
|
|
103
|
+
// X-Radar-Dashboard marks this as an authored write, which is what lets it keep an
|
|
104
|
+
// MCP-driven dashboard alive with no tab open. A foreign page cannot set the header
|
|
105
|
+
// without a CORS preflight it fails, so it cannot forge the keep-alive.
|
|
106
|
+
headers: {
|
|
107
|
+
"Content-Type": "application/json",
|
|
108
|
+
"Content-Length": Buffer.byteLength(body),
|
|
109
|
+
"X-Radar-Dashboard": "1",
|
|
110
|
+
},
|
|
104
111
|
timeout: 4000,
|
|
105
112
|
}, (res) => {
|
|
106
113
|
let b = "";
|
|
@@ -707,7 +714,7 @@ async function runMcpServer() {
|
|
|
707
714
|
}
|
|
708
715
|
}
|
|
709
716
|
// --- MCP Server ---
|
|
710
|
-
const server = new Server({ name: "slack-radar", version: "1.
|
|
717
|
+
const server = new Server({ name: "slack-radar", version: "1.14.0" }, { capabilities: { tools: {} }, instructions: SERVER_INSTRUCTIONS });
|
|
711
718
|
server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
712
719
|
tools: TOOL_DEFINITIONS,
|
|
713
720
|
}));
|
package/dist/web/bin.js
CHANGED
|
@@ -3,7 +3,7 @@ import { execSync } from "child_process";
|
|
|
3
3
|
import { realpathSync } from "fs";
|
|
4
4
|
import http from "http";
|
|
5
5
|
import { fileURLToPath } from "url";
|
|
6
|
-
import { cleanupOnBind, createServer, seedInitialSpec, WEB_PORT } from "./server.js";
|
|
6
|
+
import { cleanupOnBind, createServer, seedInitialSpec, shutdownDashboard, startAutoCloseSweep, WEB_PORT, } from "./server.js";
|
|
7
7
|
import { RADAR_VERSION } from "../shared/constants.js";
|
|
8
8
|
/**
|
|
9
9
|
* One loopback GET against the dashboard's own port, used by the adopt path. Resolves with the
|
|
@@ -144,6 +144,10 @@ export function startWebServer() {
|
|
|
144
144
|
// so adopting it leaves its view and open DB-browser tab intact.
|
|
145
145
|
seedInitialSpec();
|
|
146
146
|
cleanupOnBind();
|
|
147
|
+
// Arm the auto-close sweep only now that THIS process owns the port. Doing it post-bind (not
|
|
148
|
+
// in createServer) keeps importing the module — or a second launcher that loses the bind —
|
|
149
|
+
// from arming a timer that could process.exit. The interval is unref'd inside.
|
|
150
|
+
startAutoCloseSweep(server);
|
|
147
151
|
const url = `http://localhost:${WEB_PORT}`;
|
|
148
152
|
console.log(`Slack Radar Web running at ${url}`);
|
|
149
153
|
// Auto-open the browser for the HUMAN launcher (`slack-radar web` / `slack-radar-web`),
|
|
@@ -155,11 +159,17 @@ export function startWebServer() {
|
|
|
155
159
|
return;
|
|
156
160
|
openBrowser(url);
|
|
157
161
|
});
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
162
|
+
// The /shutdown route and the auto-close sweep both funnel through shutdownDashboard, so the
|
|
163
|
+
// server.close + timeout-fallback exit -- and the finalize-a-live-recording safety step --
|
|
164
|
+
// cannot drift between THOSE two paths. Ctrl-C / SIGTERM do NOT reach this handler: screen.ts's
|
|
165
|
+
// registerScreenCleanup() (called earlier, inside createServer()) registers its own SIGINT/
|
|
166
|
+
// SIGTERM listeners that call process.exit() synchronously, and Node runs signal listeners in
|
|
167
|
+
// registration order -- so screen.ts's handler always wins the race and this one below never
|
|
168
|
+
// runs. That handler's own signalCleanup() does its own (fire-and-forget, non-recording-safe)
|
|
169
|
+
// teardown. Pre-existing gap, not introduced here; fixing it means touching screen.ts, which is
|
|
170
|
+
// out of scope for this change. Registering below anyway costs nothing and is the load-bearing
|
|
171
|
+
// path IF screen.ts's signal handling ever stops calling process.exit() synchronously.
|
|
172
|
+
const shutdown = () => void shutdownDashboard(server);
|
|
163
173
|
process.on("SIGINT", shutdown);
|
|
164
174
|
process.on("SIGTERM", shutdown);
|
|
165
175
|
}
|
|
@@ -60,6 +60,7 @@
|
|
|
60
60
|
h1 .version { margin-left:auto; font-size:11px; font-weight:400; color:var(--muted-2); letter-spacing:0; }
|
|
61
61
|
.themebtn, .screenbtn { background:var(--surface); border:1px solid var(--border-2); color:var(--muted-2); border-radius:8px; padding:5px 12px; font:inherit; font-size:12.5px; cursor:pointer; }
|
|
62
62
|
.themebtn:hover, .screenbtn:hover { border-color:var(--accent); color:var(--text); } .screenbtn.on { background:var(--accent-bg); border-color:var(--accent); color:var(--accent-text); }
|
|
63
|
+
.killbtn.armed { border-color:var(--error); color:var(--error); } .killbtn.armed:hover { border-color:var(--error-2); color:var(--error-2); }
|
|
63
64
|
.modebar { display:flex; gap:6px; margin:0 0 6px; flex-wrap:wrap; flex:0 0 auto; align-items:center; }
|
|
64
65
|
.modebtn { background:var(--surface); border:1px solid var(--border-2); color:var(--muted-2); border-radius:8px; padding:6px 14px; font:inherit; font-size:12.5px; cursor:pointer; }
|
|
65
66
|
.modebtn:hover { border-color:var(--accent); color:var(--text); }
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
// router sibling toggled by ▣ Screen: a fixed right-docked panel that floats over any view.
|
|
7
7
|
import { html } from "./html.js";
|
|
8
8
|
import { render } from "preact";
|
|
9
|
-
import { useState, useEffect, useCallback } from "preact/hooks";
|
|
9
|
+
import { useState, useEffect, useCallback, useRef } from "preact/hooks";
|
|
10
10
|
import { useStoreValue } from "./hooks.js";
|
|
11
11
|
import { store, MODES, modeServed, describeConstraints } from "./store.js";
|
|
12
12
|
import { SOURCES } from "./registry.js";
|
|
@@ -55,13 +55,42 @@ function Header({ screenOpen, onScreenToggle }) {
|
|
|
55
55
|
const conn = useStoreValue(store, "conn", () => store.conn);
|
|
56
56
|
const profile = useStoreValue(store, "profile", () => store.profileLabel);
|
|
57
57
|
const version = useStoreValue(store, "version", () => store.serverVersion);
|
|
58
|
+
const stopped = useStoreValue(store, "stopped", () => store.stopped);
|
|
58
59
|
const [busy, setBusy] = useState(false);
|
|
60
|
+
const [killing, setKilling] = useState(false);
|
|
61
|
+
// Arm/confirm for the destructive kill button: the FIRST click only arms a "sure?" state
|
|
62
|
+
// (auto-disarms after a few seconds so a stray click never leaves a live trap); the SECOND
|
|
63
|
+
// click, while armed, actually fires. Kills the whole process with no undo (drops the session
|
|
64
|
+
// logcat ring and the pulled-DB cache), so a same-styled-as-Theme single click is not safe --
|
|
65
|
+
// this is the confirmation without adding a dialog/modal that would change the header layout.
|
|
66
|
+
const [killArmed, setKillArmed] = useState(false);
|
|
67
|
+
const killArmTimer = useRef(null);
|
|
68
|
+
useEffect(() => () => { if (killArmTimer.current)
|
|
69
|
+
clearTimeout(killArmTimer.current); }, []);
|
|
59
70
|
const [theme, setTheme] = useState(readTheme);
|
|
60
71
|
const reconnect = useCallback(async () => {
|
|
61
72
|
setBusy(true);
|
|
62
73
|
await store.reconnect();
|
|
63
74
|
setBusy(false);
|
|
64
75
|
}, []);
|
|
76
|
+
const kill = useCallback(async () => {
|
|
77
|
+
if (!killArmed) {
|
|
78
|
+
setKillArmed(true);
|
|
79
|
+
if (killArmTimer.current)
|
|
80
|
+
clearTimeout(killArmTimer.current);
|
|
81
|
+
killArmTimer.current = setTimeout(() => setKillArmed(false), 4000);
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
if (killArmTimer.current)
|
|
85
|
+
clearTimeout(killArmTimer.current);
|
|
86
|
+
setKillArmed(false);
|
|
87
|
+
setKilling(true);
|
|
88
|
+
const ok = await store.kill();
|
|
89
|
+
// On success the store flips `stopped` and the terminal state renders below; on failure the
|
|
90
|
+
// server is still up, so drop the busy flag and let the user try again.
|
|
91
|
+
if (!ok)
|
|
92
|
+
setKilling(false);
|
|
93
|
+
}, [killArmed]);
|
|
65
94
|
const toggleTheme = useCallback(() => {
|
|
66
95
|
const next = readTheme() === "light" ? "dark" : "light";
|
|
67
96
|
document.documentElement.classList.toggle("light", next === "light");
|
|
@@ -73,6 +102,14 @@ function Header({ screenOpen, onScreenToggle }) {
|
|
|
73
102
|
}
|
|
74
103
|
setTheme(next);
|
|
75
104
|
}, []);
|
|
105
|
+
// The server is gone. Render a terminal state in place of the live header rather than leaving
|
|
106
|
+
// stale controls that would all fail against a dead port. Every hook above runs on EVERY
|
|
107
|
+
// render regardless of `stopped` -- an early return before a hook call would skip it once
|
|
108
|
+
// stopped flips true, changing the hook count between renders (Preact/React both require the
|
|
109
|
+
// same hooks, same order, every render).
|
|
110
|
+
if (stopped) {
|
|
111
|
+
return html `<h1>SLACK RADAR DASHBOARD <span class="conn waiting">● dashboard stopped</span></h1>`;
|
|
112
|
+
}
|
|
76
113
|
const connected = conn.state === "connected";
|
|
77
114
|
return html `
|
|
78
115
|
<h1>
|
|
@@ -83,6 +120,7 @@ function Header({ screenOpen, onScreenToggle }) {
|
|
|
83
120
|
${!connected ? html `<button class="reconnect" disabled=${busy} onClick=${reconnect}>${busy ? "⟳ enabling…" : "⟳ Reconnect Radar"}</button>` : null}
|
|
84
121
|
<button class="themebtn" onClick=${toggleTheme} title="Toggle light / dark theme">${theme === "light" ? "🌙 Dark" : "☀ Light"}</button>
|
|
85
122
|
<button class=${"screenbtn" + (screenOpen ? " on" : "")} onClick=${onScreenToggle} title="Mirror the live device screen">▣ Screen</button>
|
|
123
|
+
<button class=${"themebtn killbtn" + (killArmed ? " armed" : "")} disabled=${killing} onClick=${kill} title=${killArmed ? "Click again to confirm" : "Stop the dashboard server"}>${killing ? "⏻ stopping…" : killArmed ? "⏻ Confirm stop?" : "⏻ Stop dashboard"}</button>
|
|
86
124
|
${version ? html `<span class="version" title="Version of the dashboard process. It can differ from your Claude Code MCP session if a dashboard from an earlier launch still holds the port; restart the dashboard to match.">v${version}</span>` : null}
|
|
87
125
|
</h1>
|
|
88
126
|
`;
|
|
@@ -59,7 +59,10 @@ export function DbBrowser({ spec }) {
|
|
|
59
59
|
setOut({ msg: "pick a table or write a query" });
|
|
60
60
|
setTables(null);
|
|
61
61
|
try {
|
|
62
|
-
const r = await (
|
|
62
|
+
const r = await (
|
|
63
|
+
// Authored: /dbtables pulls a plaintext copy of the device database to local disk, so
|
|
64
|
+
// the server refuses it without proof this is our own client.
|
|
65
|
+
await fetch("/dbtables?db=" + encodeURIComponent(name) + userQS(user) + (refresh ? "&refresh=1" : ""), { headers: { "X-Radar-Dashboard": "1" } })).json();
|
|
63
66
|
setTables(r);
|
|
64
67
|
if (!r.error)
|
|
65
68
|
setMeta(name + " — " + (((r.sizeBytes ?? 0) / 1024) | 0) + " KB snapshot, " + (r.tables ?? []).length + " tables · " + profileLabel(user));
|
|
@@ -75,7 +78,10 @@ export function DbBrowser({ spec }) {
|
|
|
75
78
|
return;
|
|
76
79
|
setOut({ msg: "running…" });
|
|
77
80
|
try {
|
|
78
|
-
const r = await (
|
|
81
|
+
const r = await (
|
|
82
|
+
// Authored for the same reason as /dbtables: queryDatabase pulls the device database to
|
|
83
|
+
// local disk when no copy exists yet.
|
|
84
|
+
await fetch("/dbquery?db=" + encodeURIComponent(db) + "&sql=" + encodeURIComponent(theSql) + userQS(user), { headers: { "X-Radar-Dashboard": "1" } })).json();
|
|
79
85
|
if (r.error)
|
|
80
86
|
setOut({ error: r.error });
|
|
81
87
|
else if (!r.rows || !r.rows.length) {
|
|
@@ -27,7 +27,7 @@ export function ScreenOverlay({ open, onClose }) {
|
|
|
27
27
|
// Download whatever /screen/record/stop returns, then unset recording. Shared by the
|
|
28
28
|
// explicit stop button and the close-while-recording teardown so both behave identically.
|
|
29
29
|
const stopAndSave = useCallback(async () => {
|
|
30
|
-
const r = await (await fetch("/screen/record/stop", { method: "POST" })).json().catch(() => ({}));
|
|
30
|
+
const r = await (await fetch("/screen/record/stop", { method: "POST", headers: { "X-Radar-Dashboard": "1" } })).json().catch(() => ({}));
|
|
31
31
|
setRecording(false);
|
|
32
32
|
if (!r.download)
|
|
33
33
|
return;
|
|
@@ -82,7 +82,9 @@ export function ScreenOverlay({ open, onClose }) {
|
|
|
82
82
|
}, [open, consent, caps]);
|
|
83
83
|
const accept = useCallback(async () => {
|
|
84
84
|
try {
|
|
85
|
-
|
|
85
|
+
// X-Radar-Dashboard marks this as coming from our own client. Without it the server refuses
|
|
86
|
+
// the write: consent gates mirroring the device screen, so a foreign page must not set it.
|
|
87
|
+
await fetch("/screen/consent", { method: "POST", headers: { "X-Radar-Dashboard": "1" } });
|
|
86
88
|
setConsent(true);
|
|
87
89
|
}
|
|
88
90
|
catch {
|
|
@@ -116,7 +118,7 @@ export function ScreenOverlay({ open, onClose }) {
|
|
|
116
118
|
}
|
|
117
119
|
if (!recording) {
|
|
118
120
|
setRecording(true);
|
|
119
|
-
await fetch("/screen/record/start", { method: "POST" }).catch(() => { });
|
|
121
|
+
await fetch("/screen/record/start", { method: "POST", headers: { "X-Radar-Dashboard": "1" } }).catch(() => { });
|
|
120
122
|
}
|
|
121
123
|
else {
|
|
122
124
|
await stopAndSave();
|
|
@@ -128,7 +130,11 @@ export function ScreenOverlay({ open, onClose }) {
|
|
|
128
130
|
}, [consent, caps, recording, stopAndSave]);
|
|
129
131
|
const redetect = useCallback(async () => {
|
|
130
132
|
setHint("re-detecting active panel…");
|
|
131
|
-
|
|
133
|
+
// Authored: redetect tears down the live cast and deletes finished recordings, so the server
|
|
134
|
+
// refuses it without proof this is our own client.
|
|
135
|
+
const r = await (await fetch("/screen/redetect", { headers: { "X-Radar-Dashboard": "1" } }))
|
|
136
|
+
.json()
|
|
137
|
+
.catch(() => ({}));
|
|
132
138
|
if (consent && caps && caps.liveCast && imgRef.current)
|
|
133
139
|
imgRef.current.src = streamSrc();
|
|
134
140
|
setHint("display: " + (r.display || "default"));
|
|
@@ -90,6 +90,10 @@ export function specMatchesMode(spec) {
|
|
|
90
90
|
class Store {
|
|
91
91
|
spec = { blank: true, viz: [] };
|
|
92
92
|
conn = { state: "waiting", msg: "connecting…" };
|
|
93
|
+
// Set true once the kill button has shut the server down. The header swaps to a "dashboard
|
|
94
|
+
// stopped" state, and the poll loops are torn down so a now-dead server does not spam the
|
|
95
|
+
// console with failed fetches. Emitted as "stopped".
|
|
96
|
+
stopped = false;
|
|
93
97
|
profileLabel = "detecting…";
|
|
94
98
|
serverVersion = "";
|
|
95
99
|
profiles = [];
|
|
@@ -156,6 +160,13 @@ class Store {
|
|
|
156
160
|
_lastSerial = null;
|
|
157
161
|
_rafPending = false;
|
|
158
162
|
_intervals = [];
|
|
163
|
+
// Per-tab presence id, generated once when this Store is constructed. Rides pollProfile's 5s
|
|
164
|
+
// /health fetch (below) so the server can tell how many tabs are live and auto-close when the
|
|
165
|
+
// last one is gone. In-memory only, never persisted: a page reload naturally gets a fresh id,
|
|
166
|
+
// which is fine — the old id ages out of the server's presence map. Rides pollProfile, NOT
|
|
167
|
+
// pollHealth: pollHealth early-returns without fetching while a stream is busy (<6s since the
|
|
168
|
+
// last event), so a user actively watching a chatty stream would send zero presence signals.
|
|
169
|
+
_tabId = typeof crypto !== "undefined" && crypto.randomUUID ? crypto.randomUUID() : String(Math.random()).slice(2);
|
|
159
170
|
// ---- shared detail cache (bounded FIFO) ----
|
|
160
171
|
cacheDetail(kind, id, detail) {
|
|
161
172
|
const key = kind + ":" + id;
|
|
@@ -234,6 +245,7 @@ class Store {
|
|
|
234
245
|
_resetForTest() {
|
|
235
246
|
this.spec = { blank: true, viz: [] };
|
|
236
247
|
this.conn = { state: "waiting", msg: "connecting…" };
|
|
248
|
+
this.stopped = false;
|
|
237
249
|
this.profileLabel = "detecting…";
|
|
238
250
|
this.serverVersion = "";
|
|
239
251
|
this.profiles = [];
|
|
@@ -373,7 +385,7 @@ class Store {
|
|
|
373
385
|
try {
|
|
374
386
|
const cur = await (await fetch("/spec")).json();
|
|
375
387
|
if (!cur || cur.blank) {
|
|
376
|
-
await fetch("/setspec", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(MODES[0].spec) }).catch(() => { });
|
|
388
|
+
await fetch("/setspec", { method: "POST", headers: { "Content-Type": "application/json", "X-Radar-Dashboard": "1" }, body: JSON.stringify(MODES[0].spec) }).catch(() => { });
|
|
377
389
|
}
|
|
378
390
|
}
|
|
379
391
|
catch {
|
|
@@ -387,7 +399,9 @@ class Store {
|
|
|
387
399
|
if (opts.local)
|
|
388
400
|
this.markLocalPush(spec);
|
|
389
401
|
try {
|
|
390
|
-
|
|
402
|
+
// X-Radar-Dashboard marks this as an authored write (see the server's handleSetSpec): it is
|
|
403
|
+
// what lets the write count as a keep-alive, and a foreign origin cannot forge it.
|
|
404
|
+
return await (await fetch("/setspec", { method: "POST", headers: { "Content-Type": "application/json", "X-Radar-Dashboard": "1" }, body: JSON.stringify(spec) })).json();
|
|
391
405
|
}
|
|
392
406
|
catch {
|
|
393
407
|
return { ok: false, error: "request failed" };
|
|
@@ -813,7 +827,16 @@ class Store {
|
|
|
813
827
|
try {
|
|
814
828
|
const [profilesR, healthR] = await Promise.all([
|
|
815
829
|
fetch("/_control/profiles").then((r) => r.json()).catch(() => null),
|
|
816
|
-
fetch(
|
|
830
|
+
// Tab id rides THIS fetch (not pollHealth's) as the poll-only presence signal the
|
|
831
|
+
// server counts for auto-close. pollProfile fires unconditionally every 5s, so a busy
|
|
832
|
+
// stream cannot starve it the way it starves pollHealth's fresh-frame fast path. The
|
|
833
|
+
// X-Radar-Dashboard header is the same CSRF guard /shutdown requires: without it, a
|
|
834
|
+
// foreign origin's plain GET could forge presence (fake a tab open forever, or arm
|
|
835
|
+
// everSeen on an MCP-only session it should never touch). A cross-origin request cannot
|
|
836
|
+
// set a custom header without a CORS preflight it will fail.
|
|
837
|
+
fetch("/health?tab=" + encodeURIComponent(this._tabId), {
|
|
838
|
+
headers: { "X-Radar-Dashboard": "1" },
|
|
839
|
+
}).then((r) => r.json()).catch(() => null),
|
|
817
840
|
]);
|
|
818
841
|
const uid = healthR && healthR.boundUserId;
|
|
819
842
|
// pollHealth's fresh-frame fast path can skip its /health fetch indefinitely on a chatty
|
|
@@ -868,7 +891,7 @@ class Store {
|
|
|
868
891
|
// list is refreshed so the dropdown is current and the user can pick a valid device.
|
|
869
892
|
async selectDevice(serial) {
|
|
870
893
|
try {
|
|
871
|
-
const r = await fetch("/enable?device_serial=" + encodeURIComponent(serial), { method: "POST" });
|
|
894
|
+
const r = await fetch("/enable?device_serial=" + encodeURIComponent(serial), { method: "POST", headers: { "X-Radar-Dashboard": "1" } });
|
|
872
895
|
if (!r.ok && r.status === 409) {
|
|
873
896
|
const body = await r.json().catch(() => null);
|
|
874
897
|
// Surface the failure on the device chip itself, not via conn: a healthy pollHealth flips
|
|
@@ -920,7 +943,7 @@ class Store {
|
|
|
920
943
|
}
|
|
921
944
|
async reconnect() {
|
|
922
945
|
try {
|
|
923
|
-
const r = await fetch("/enable", { method: "POST" });
|
|
946
|
+
const r = await fetch("/enable", { method: "POST", headers: { "X-Radar-Dashboard": "1" } });
|
|
924
947
|
// 409 = ambiguous device (multiple attached, none picked). Surface the server's
|
|
925
948
|
// reason through the existing connection-status line so the user sees why enable
|
|
926
949
|
// did not connect, instead of a silent stall on "reconnecting…".
|
|
@@ -938,6 +961,28 @@ class Store {
|
|
|
938
961
|
this.pollSpec();
|
|
939
962
|
this.resyncStream();
|
|
940
963
|
}
|
|
964
|
+
// Kill the dashboard server from the header button. The X-Radar-Dashboard header is the
|
|
965
|
+
// CSRF guard the /shutdown route requires (a foreign origin's fetch cannot set it without a
|
|
966
|
+
// preflight it will fail). On success the server is going away, so tear down every poll
|
|
967
|
+
// loop + the stream: any further fetch would just fail against a dead port and spam the
|
|
968
|
+
// console. Flip `stopped` so the header renders the terminal "dashboard stopped" state.
|
|
969
|
+
async kill() {
|
|
970
|
+
try {
|
|
971
|
+
const r = await fetch("/shutdown", {
|
|
972
|
+
method: "POST",
|
|
973
|
+
headers: { "X-Radar-Dashboard": "1" },
|
|
974
|
+
});
|
|
975
|
+
if (!r.ok)
|
|
976
|
+
return false;
|
|
977
|
+
}
|
|
978
|
+
catch {
|
|
979
|
+
return false;
|
|
980
|
+
}
|
|
981
|
+
this.stop();
|
|
982
|
+
this.stopped = true;
|
|
983
|
+
this.emit("stopped", true);
|
|
984
|
+
return true;
|
|
985
|
+
}
|
|
941
986
|
}
|
|
942
987
|
// ---- aggregate math (moved here from widgets per the plan: it belongs WITH the aggregate
|
|
943
988
|
// engine, not the renderer). seriesValues turns a graph series' raw buckets into plotted
|
package/dist/web/server.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import http from "http";
|
|
2
2
|
import { type LogFrame } from "./log-session.js";
|
|
3
|
+
import { stopRecording, getLive } from "../shared/screen.js";
|
|
3
4
|
declare const WEB_PORT: number;
|
|
4
5
|
/**
|
|
5
6
|
* Decide whether to drop a log frame under backpressure. LIVE frames are dropped
|
|
@@ -29,7 +30,155 @@ export declare function seedInitialSpec(): void;
|
|
|
29
30
|
* Same post-bind discipline as seedInitialSpec: the port owner is the sole legitimate writer.
|
|
30
31
|
*/
|
|
31
32
|
export declare function cleanupOnBind(): void;
|
|
32
|
-
export declare
|
|
33
|
+
export declare const TAB_LIVENESS_MS = 75000;
|
|
34
|
+
export declare const AUTO_CLOSE_GRACE_MS: number;
|
|
35
|
+
/**
|
|
36
|
+
* Pure auto-close decision, mirroring screen.ts's nextViewerAction/shouldRelaunch precedent:
|
|
37
|
+
* the sweep owns the timestamp bookkeeping, this owns only the yes/no. Close only when there
|
|
38
|
+
* are no live tabs, at least one tab has EVER been seen (an MCP-spawned dashboard nobody has
|
|
39
|
+
* opened must never self-destruct), and the empty period has outlived the grace window.
|
|
40
|
+
* Exported for unit testing without a clock or a socket.
|
|
41
|
+
*/
|
|
42
|
+
export declare function shouldAutoClose(liveTabs: number, everSeen: boolean, msSinceEmpty: number | null): boolean;
|
|
43
|
+
export declare function touchTab(id: string, now?: number): void;
|
|
44
|
+
/**
|
|
45
|
+
* Treat an authored MCP write (a /setspec, a successful /enable) as a keep-alive equivalent to
|
|
46
|
+
* a tab being present: clear the empty marker so the idle timer never fires mid-session. NOT
|
|
47
|
+
* gated on any tab being tracked — an hour-long MCP debugging session with zero open tabs is a
|
|
48
|
+
* legitimate reason to stay up, and losing it would drop the session logcat ring, the device
|
|
49
|
+
* pin, and the pulled-DB cache. Deliberately does NOT set everSeen: an MCP-only dashboard that
|
|
50
|
+
* nobody ever opened stays protected by the everSeen guard even after the MCP goes quiet.
|
|
51
|
+
*/
|
|
52
|
+
export declare function markKeepAlive(): void;
|
|
53
|
+
/**
|
|
54
|
+
* Whether a request may buy the process more life. True for our own client and the MCP, false
|
|
55
|
+
* for anything else, so a foreign page cannot postpone auto-close forever.
|
|
56
|
+
*
|
|
57
|
+
* Two accepted proofs, both unforgeable cross-origin without a CORS preflight the foreign
|
|
58
|
+
* origin cannot satisfy: the `X-Radar-Dashboard` header `/shutdown` already requires, or an
|
|
59
|
+
* `application/json` content-type. JSON counts because every MCP version ever published sends
|
|
60
|
+
* it on `/setspec`; requiring only the header would silently strip the keep-alive from an older
|
|
61
|
+
* globally-installed MCP talking to a newer dashboard.
|
|
62
|
+
*
|
|
63
|
+
* The content-type test compares the MIME ESSENCE, never a substring. CORS safelists a
|
|
64
|
+
* content-type by its essence and ignores parameters, so `text/plain; charset=application/json`
|
|
65
|
+
* is a SIMPLE request that any page can send with no preflight while still containing the
|
|
66
|
+
* string "application/json". A substring match there would reopen the exact hole this closes.
|
|
67
|
+
*
|
|
68
|
+
* Exported so the route wiring is directly testable: the decision, not just its effect.
|
|
69
|
+
*/
|
|
70
|
+
export declare function isAuthoredRequest(headers: {
|
|
71
|
+
"x-radar-dashboard"?: string | string[];
|
|
72
|
+
"content-type"?: string | string[];
|
|
73
|
+
}): boolean;
|
|
74
|
+
/**
|
|
75
|
+
* One sweep tick: prune stale tab ids, maintain the emptySince marker across the 1->0 / 0->1
|
|
76
|
+
* transitions, and return whether the dashboard should auto-close now. Owns all timestamp
|
|
77
|
+
* bookkeeping and delegates the decision to shouldAutoClose. `now` is injectable so the
|
|
78
|
+
* transition logic is unit-testable with a fake clock. Returns true only on the tick where the
|
|
79
|
+
* grace window has elapsed with no live tabs.
|
|
80
|
+
*/
|
|
81
|
+
export declare function sweepPresence(now?: number): boolean;
|
|
82
|
+
/** Presence snapshot for tests. */
|
|
83
|
+
export declare function getPresenceState(): {
|
|
84
|
+
liveTabs: number;
|
|
85
|
+
everSeen: boolean;
|
|
86
|
+
emptySince: number | null;
|
|
87
|
+
};
|
|
88
|
+
/** Reset presence between tests (module state is a process singleton). */
|
|
89
|
+
export declare function resetPresenceForTest(): void;
|
|
90
|
+
interface ShutdownDeps {
|
|
91
|
+
getLive?: typeof getLive;
|
|
92
|
+
stopRecording?: typeof stopRecording;
|
|
93
|
+
exit?: (code: number) => void;
|
|
94
|
+
log?: (msg: string) => void;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Gracefully shut the dashboard down. Reached by the manual /shutdown route and the auto-close
|
|
98
|
+
* sweep, so the server.close + timeout-fallback exit logic lives in exactly one place. Before
|
|
99
|
+
* tearing down, if a screen recording is live, finalize it: bin.ts's exit-time cleanup SIGKILLs
|
|
100
|
+
* the cast's ffmpeg child, and an ffmpeg killed mid-write leaves an mp4 with no moov atom
|
|
101
|
+
* (unplayable). Awaiting stopRecording writes the moov and closes the file first.
|
|
102
|
+
*
|
|
103
|
+
* That mp4 safety covers THOSE TWO PATHS ONLY. bin.ts also registers this on SIGINT/SIGTERM,
|
|
104
|
+
* but screen.ts's own signal handlers exit synchronously and are registered first, so Ctrl-C
|
|
105
|
+
* never reaches here and a recording killed that way can still be corrupt. Pre-existing gap;
|
|
106
|
+
* see the bin.ts comment at the SIGINT registration for why fixing it means touching screen.ts.
|
|
107
|
+
*
|
|
108
|
+
* A second call for the same server is a no-op: the sweep tick and a manual /shutdown can both
|
|
109
|
+
* fire, and awaiting stopRecording gives the next tick a window to land mid-flight.
|
|
110
|
+
* Deps are injectable so the recording-safety path is testable without spawning ffmpeg or
|
|
111
|
+
* actually exiting the process.
|
|
112
|
+
*/
|
|
113
|
+
export declare function shutdownDashboard(server: {
|
|
114
|
+
close(cb?: () => void): void;
|
|
115
|
+
}, deps?: ShutdownDeps): Promise<void>;
|
|
116
|
+
/**
|
|
117
|
+
* Start the periodic auto-close sweep. Called once by bin.ts AFTER a successful listen bind, not
|
|
118
|
+
* from createServer, so importing this module (or spinning a throwaway server in a test) never
|
|
119
|
+
* arms a timer that could process.exit the test runner. The interval is unref'd so it never
|
|
120
|
+
* keeps the process alive on its own.
|
|
121
|
+
*/
|
|
122
|
+
export declare function startAutoCloseSweep(server: http.Server): ReturnType<typeof setInterval> | null;
|
|
123
|
+
/**
|
|
124
|
+
* Build the dashboard HTTP server. `onShutdown` is the hook the manual /shutdown route fires
|
|
125
|
+
* after answering; it defaults to the real graceful shutdown and is injectable so a test can
|
|
126
|
+
* exercise the route without exiting the process. bin.ts calls createServer() with no args.
|
|
127
|
+
*/
|
|
128
|
+
export declare function createServer(onShutdown?: (server: http.Server) => void): http.Server;
|
|
129
|
+
/**
|
|
130
|
+
* The /enable response body for a completed device probe, plus its one side effect: a
|
|
131
|
+
* successful re-arm keeps the dashboard alive (an MCP-driven session can re-enable with no tab
|
|
132
|
+
* open, and that must not let the idle timer fire out from under it).
|
|
133
|
+
*
|
|
134
|
+
* `onEnabled` fires only on a successful probe. The route passes `markKeepAlive` when the
|
|
135
|
+
* request was authored (see isAuthoredRequest) and OMITS it otherwise, so an unauthored caller
|
|
136
|
+
* gets the same body but buys no extra process life. Injected rather than called directly so
|
|
137
|
+
* the keep-alive wiring is testable without a real device probe (handleEnable's ping goes over
|
|
138
|
+
* a real socket to RADAR_HOST:RADAR_PORT, which this function does not touch at all).
|
|
139
|
+
*
|
|
140
|
+
* A failed probe gets guidance, not a bare false: the broadcast landed (or exited 0 with no
|
|
141
|
+
* receiver), so the likely causes are a build without the slack-radar modules or the wrong
|
|
142
|
+
* profile. Mirrors the MCP enable message. Exported for unit testing.
|
|
143
|
+
*/
|
|
144
|
+
/**
|
|
145
|
+
* Which keep-alive hook /enable hands to enableResultBody: the real one for an authored request,
|
|
146
|
+
* none otherwise. Its own function purely so a test can assert the CHOICE. Asserting the effect
|
|
147
|
+
* through the route cannot cover this — handleEnable's device probe fails with no hardware, which
|
|
148
|
+
* short-circuits before the hook is ever consulted, so a route-level test passes either way (a
|
|
149
|
+
* mutation deleting the gate survived the whole suite before this existed).
|
|
150
|
+
*/
|
|
151
|
+
export declare function keepAliveHookFor(authored: boolean): (() => void) | undefined;
|
|
152
|
+
/**
|
|
153
|
+
* Whether the dashboard serves this request without proof of origin. Everything else is refused
|
|
154
|
+
* unless authored. Exported so a test can drive the decision directly, and so the open surface is
|
|
155
|
+
* reviewable in one place instead of inferred from twenty route branches.
|
|
156
|
+
*
|
|
157
|
+
* Reads are open by path. Writes are closed with exactly two named exceptions, both justified
|
|
158
|
+
* below. A POST to a read path is NOT open: only GET and HEAD can ever be reads.
|
|
159
|
+
*/
|
|
160
|
+
export declare function isOpenToAnyCaller(urlPath: string, method: string | undefined): boolean;
|
|
161
|
+
/**
|
|
162
|
+
* Whether a request's Host names this loopback dashboard. The listener is bound to 127.0.0.1, but
|
|
163
|
+
* that only limits which interface accepts the TCP connection: a browser resolving an attacker's
|
|
164
|
+
* domain to 127.0.0.1 (DNS rebinding) connects locally and arrives with that domain in Host. The
|
|
165
|
+
* page is then same-origin by the browser's reckoning, so it can set any header it likes and the
|
|
166
|
+
* X-Radar-Dashboard guard buys nothing against it. Checking Host is what makes the loopback bind
|
|
167
|
+
* an actual boundary, and it matters most for /shutdown, which kills the process.
|
|
168
|
+
*
|
|
169
|
+
* Accepts localhost / 127.0.0.1 / [::1] / ::1 / 0.0.0.0, with or without a port, and a missing
|
|
170
|
+
* Host (HTTP/1.0 and a bare socket client send none; those cannot be a rebound browser).
|
|
171
|
+
*
|
|
172
|
+
* SLACK_RADAR_ALLOWED_HOSTS adds names for the setups that reach the dashboard by something other
|
|
173
|
+
* than localhost -- a /etc/hosts alias, a container or Codespaces forwarded URL, a LAN hostname.
|
|
174
|
+
* Comma-separated, `host` or `host:port`; a bare name matches on any port. Without it those users
|
|
175
|
+
* would just get a 403 with nothing to do about it.
|
|
176
|
+
*/
|
|
177
|
+
export declare function isLocalHostHeader(host: string | string[] | undefined, allowedHosts?: string | undefined): boolean;
|
|
178
|
+
export declare function enableResultBody(enabled: boolean, onEnabled?: () => void): {
|
|
179
|
+
enabled: boolean;
|
|
180
|
+
error?: string;
|
|
181
|
+
};
|
|
33
182
|
export declare const DEVICE_SOURCES: Record<string, {
|
|
34
183
|
segment: string;
|
|
35
184
|
arrayKey: string;
|
package/dist/web/server.js
CHANGED
|
@@ -12,7 +12,7 @@ import { cleanupPulledDatabases, initializeDatabasePath, listDatabases, pullData
|
|
|
12
12
|
import { listPrefsFiles, readPrefsFile, parsePrefsXml, searchPrefs, } from "../shared/prefs.js";
|
|
13
13
|
import { LogSession } from "./log-session.js";
|
|
14
14
|
import { BLANK_SPEC, coerceSpec, validateSpec } from "./spec.js";
|
|
15
|
-
import { screenCapabilities, refreshScreenCapabilities, grantScreenConsent, hasScreenConsent, detectDisplay, displayNote, captureScreenshot, startLive, addViewer, removeViewer, reapLiveIfIdle, primeIfNeeded, startRecording, stopRecording, recordingPath, resetScreenState, registerScreenCleanup, resolveFfmpeg, ffmpegInstallHint, SCREEN_BOUNDARY, } from "../shared/screen.js";
|
|
15
|
+
import { screenCapabilities, refreshScreenCapabilities, grantScreenConsent, hasScreenConsent, detectDisplay, displayNote, captureScreenshot, startLive, addViewer, removeViewer, reapLiveIfIdle, primeIfNeeded, startRecording, stopRecording, getLive, recordingPath, resetScreenState, registerScreenCleanup, resolveFfmpeg, ffmpegInstallHint, SCREEN_BOUNDARY, } from "../shared/screen.js";
|
|
16
16
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
17
17
|
const WEB_PORT = Number(process.env.SLACK_RADAR_WEB_PORT ?? WEB_PORT_DEFAULT);
|
|
18
18
|
const INDEX_PATH = path.join(__dirname, "public", "index.html");
|
|
@@ -144,11 +144,249 @@ export function cleanupOnBind() {
|
|
|
144
144
|
process.once(sig, cleanupPulledDatabases);
|
|
145
145
|
}
|
|
146
146
|
}
|
|
147
|
-
|
|
147
|
+
// --- Dashboard presence + auto-close ------------------------------------------
|
|
148
|
+
//
|
|
149
|
+
// The dashboard never tore itself down: closing every browser tab left this Node
|
|
150
|
+
// process running forever. Two teardown paths fix that: a manual kill button (POST
|
|
151
|
+
// /shutdown) and an auto-close that fires only when NOBODY — no live browser tab AND
|
|
152
|
+
// no MCP-driven write — has touched the dashboard for a while.
|
|
153
|
+
//
|
|
154
|
+
// Presence is poll-only. Each browser tab rides its id on pollProfile()'s 5s /health
|
|
155
|
+
// fetch (see store.ts); the server records a last-seen timestamp per tab. No
|
|
156
|
+
// pagehide/beforeunload/visibilitychange/sendBeacon: those are unreliable on mobile and
|
|
157
|
+
// fire on backgrounding (not just closing), which is the ambiguity this poll design avoids.
|
|
158
|
+
// How stale a tab id can be before the sweep prunes it as "not live". pollProfile pings every
|
|
159
|
+
// 5s nominally, but a backgrounded (not closed) tab can be throttled hard: Chrome's intensive
|
|
160
|
+
// throttling batches chained timers to roughly once per minute after a tab is hidden past 5
|
|
161
|
+
// minutes, occasionally stretching to ~90s. 75s covers the common throttled gap; a rare longer
|
|
162
|
+
// gap still just flaps the tab out and back in (the 5-minute grace below absorbs that flap
|
|
163
|
+
// harmlessly), it does not misfire an auto-close. Exported so tests pin the real constant
|
|
164
|
+
// instead of a duplicated copy.
|
|
165
|
+
export const TAB_LIVENESS_MS = 75_000;
|
|
166
|
+
// How long the dashboard must have ZERO live tabs before auto-close fires. Sized at ~3x the
|
|
167
|
+
// worst-case legitimate gap between presence pings (~60-90s under intensive throttling), so a
|
|
168
|
+
// backgrounded tab is never mistaken for a closed one. Not 90s — that is barely one throttled
|
|
169
|
+
// gap and would kill a live-but-hidden tab. Chrome's Memory Saver can also discard a
|
|
170
|
+
// backgrounded tab outright, permanently stopping its polling; auto-close eventually firing in
|
|
171
|
+
// that case is correct behavior ("nobody is looking"), not a bug to work around.
|
|
172
|
+
export const AUTO_CLOSE_GRACE_MS = 5 * 60_000;
|
|
173
|
+
// Sweep cadence: cheap (a map prune + a subtraction), frequent enough that auto-close fires
|
|
174
|
+
// promptly once the grace window elapses.
|
|
175
|
+
const AUTO_CLOSE_SWEEP_MS = 15_000;
|
|
176
|
+
const presence = { tabs: new Map(), emptySince: null, everSeen: false };
|
|
177
|
+
/**
|
|
178
|
+
* Pure auto-close decision, mirroring screen.ts's nextViewerAction/shouldRelaunch precedent:
|
|
179
|
+
* the sweep owns the timestamp bookkeeping, this owns only the yes/no. Close only when there
|
|
180
|
+
* are no live tabs, at least one tab has EVER been seen (an MCP-spawned dashboard nobody has
|
|
181
|
+
* opened must never self-destruct), and the empty period has outlived the grace window.
|
|
182
|
+
* Exported for unit testing without a clock or a socket.
|
|
183
|
+
*/
|
|
184
|
+
export function shouldAutoClose(liveTabs, everSeen, msSinceEmpty) {
|
|
185
|
+
if (liveTabs > 0)
|
|
186
|
+
return false;
|
|
187
|
+
if (!everSeen)
|
|
188
|
+
return false;
|
|
189
|
+
if (msSinceEmpty === null)
|
|
190
|
+
return false;
|
|
191
|
+
return msSinceEmpty >= AUTO_CLOSE_GRACE_MS;
|
|
192
|
+
}
|
|
193
|
+
// A tab pinged /health with its id: record it live and remember a tab was seen. A fresh id
|
|
194
|
+
// after zero live tabs is the 0->1 transition, so clear the empty marker immediately. `now` is
|
|
195
|
+
// injectable so the sweep's staleness math is unit-testable with a fake clock.
|
|
196
|
+
export function touchTab(id, now = Date.now()) {
|
|
197
|
+
const wasEmpty = presence.tabs.size === 0;
|
|
198
|
+
presence.tabs.set(id, now);
|
|
199
|
+
presence.everSeen = true;
|
|
200
|
+
if (wasEmpty)
|
|
201
|
+
presence.emptySince = null;
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Treat an authored MCP write (a /setspec, a successful /enable) as a keep-alive equivalent to
|
|
205
|
+
* a tab being present: clear the empty marker so the idle timer never fires mid-session. NOT
|
|
206
|
+
* gated on any tab being tracked — an hour-long MCP debugging session with zero open tabs is a
|
|
207
|
+
* legitimate reason to stay up, and losing it would drop the session logcat ring, the device
|
|
208
|
+
* pin, and the pulled-DB cache. Deliberately does NOT set everSeen: an MCP-only dashboard that
|
|
209
|
+
* nobody ever opened stays protected by the everSeen guard even after the MCP goes quiet.
|
|
210
|
+
*/
|
|
211
|
+
export function markKeepAlive() {
|
|
212
|
+
presence.emptySince = null;
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Whether a request may buy the process more life. True for our own client and the MCP, false
|
|
216
|
+
* for anything else, so a foreign page cannot postpone auto-close forever.
|
|
217
|
+
*
|
|
218
|
+
* Two accepted proofs, both unforgeable cross-origin without a CORS preflight the foreign
|
|
219
|
+
* origin cannot satisfy: the `X-Radar-Dashboard` header `/shutdown` already requires, or an
|
|
220
|
+
* `application/json` content-type. JSON counts because every MCP version ever published sends
|
|
221
|
+
* it on `/setspec`; requiring only the header would silently strip the keep-alive from an older
|
|
222
|
+
* globally-installed MCP talking to a newer dashboard.
|
|
223
|
+
*
|
|
224
|
+
* The content-type test compares the MIME ESSENCE, never a substring. CORS safelists a
|
|
225
|
+
* content-type by its essence and ignores parameters, so `text/plain; charset=application/json`
|
|
226
|
+
* is a SIMPLE request that any page can send with no preflight while still containing the
|
|
227
|
+
* string "application/json". A substring match there would reopen the exact hole this closes.
|
|
228
|
+
*
|
|
229
|
+
* Exported so the route wiring is directly testable: the decision, not just its effect.
|
|
230
|
+
*/
|
|
231
|
+
export function isAuthoredRequest(headers) {
|
|
232
|
+
if (headers["x-radar-dashboard"] === "1")
|
|
233
|
+
return true;
|
|
234
|
+
const contentType = headers["content-type"];
|
|
235
|
+
const value = Array.isArray(contentType) ? contentType[0] : contentType;
|
|
236
|
+
if (typeof value !== "string")
|
|
237
|
+
return false;
|
|
238
|
+
const essence = value.split(";")[0].trim().toLowerCase();
|
|
239
|
+
return essence === "application/json";
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* One sweep tick: prune stale tab ids, maintain the emptySince marker across the 1->0 / 0->1
|
|
243
|
+
* transitions, and return whether the dashboard should auto-close now. Owns all timestamp
|
|
244
|
+
* bookkeeping and delegates the decision to shouldAutoClose. `now` is injectable so the
|
|
245
|
+
* transition logic is unit-testable with a fake clock. Returns true only on the tick where the
|
|
246
|
+
* grace window has elapsed with no live tabs.
|
|
247
|
+
*/
|
|
248
|
+
export function sweepPresence(now = Date.now()) {
|
|
249
|
+
for (const [id, ts] of presence.tabs) {
|
|
250
|
+
if (now - ts > TAB_LIVENESS_MS)
|
|
251
|
+
presence.tabs.delete(id);
|
|
252
|
+
}
|
|
253
|
+
const liveTabs = presence.tabs.size;
|
|
254
|
+
if (liveTabs > 0) {
|
|
255
|
+
presence.emptySince = null; // 0->1 (or still >0): tabs present, not idle
|
|
256
|
+
}
|
|
257
|
+
else if (presence.everSeen && presence.emptySince === null) {
|
|
258
|
+
presence.emptySince = now; // 1->0: just went empty, start the grace clock
|
|
259
|
+
}
|
|
260
|
+
const msSinceEmpty = presence.emptySince === null ? null : now - presence.emptySince;
|
|
261
|
+
return shouldAutoClose(liveTabs, presence.everSeen, msSinceEmpty);
|
|
262
|
+
}
|
|
263
|
+
/** Presence snapshot for tests. */
|
|
264
|
+
export function getPresenceState() {
|
|
265
|
+
return {
|
|
266
|
+
liveTabs: presence.tabs.size,
|
|
267
|
+
everSeen: presence.everSeen,
|
|
268
|
+
emptySince: presence.emptySince,
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
/** Reset presence between tests (module state is a process singleton). */
|
|
272
|
+
export function resetPresenceForTest() {
|
|
273
|
+
presence.tabs.clear();
|
|
274
|
+
presence.emptySince = null;
|
|
275
|
+
presence.everSeen = false;
|
|
276
|
+
}
|
|
277
|
+
// Servers already tearing down. Keyed on the server rather than a module flag so the latch
|
|
278
|
+
// scopes to the thing being closed: a second call for the SAME server is suppressed, while a
|
|
279
|
+
// different server (every test builds its own) is unaffected. A module-level boolean would leak
|
|
280
|
+
// one test's shutdown into the next and would need a reset hook the tests must remember.
|
|
281
|
+
const shuttingDown = new WeakSet();
|
|
282
|
+
/**
|
|
283
|
+
* Gracefully shut the dashboard down. Reached by the manual /shutdown route and the auto-close
|
|
284
|
+
* sweep, so the server.close + timeout-fallback exit logic lives in exactly one place. Before
|
|
285
|
+
* tearing down, if a screen recording is live, finalize it: bin.ts's exit-time cleanup SIGKILLs
|
|
286
|
+
* the cast's ffmpeg child, and an ffmpeg killed mid-write leaves an mp4 with no moov atom
|
|
287
|
+
* (unplayable). Awaiting stopRecording writes the moov and closes the file first.
|
|
288
|
+
*
|
|
289
|
+
* That mp4 safety covers THOSE TWO PATHS ONLY. bin.ts also registers this on SIGINT/SIGTERM,
|
|
290
|
+
* but screen.ts's own signal handlers exit synchronously and are registered first, so Ctrl-C
|
|
291
|
+
* never reaches here and a recording killed that way can still be corrupt. Pre-existing gap;
|
|
292
|
+
* see the bin.ts comment at the SIGINT registration for why fixing it means touching screen.ts.
|
|
293
|
+
*
|
|
294
|
+
* A second call for the same server is a no-op: the sweep tick and a manual /shutdown can both
|
|
295
|
+
* fire, and awaiting stopRecording gives the next tick a window to land mid-flight.
|
|
296
|
+
* Deps are injectable so the recording-safety path is testable without spawning ffmpeg or
|
|
297
|
+
* actually exiting the process.
|
|
298
|
+
*/
|
|
299
|
+
export async function shutdownDashboard(server, deps = {}) {
|
|
300
|
+
const _getLive = deps.getLive ?? getLive;
|
|
301
|
+
const _stopRecording = deps.stopRecording ?? stopRecording;
|
|
302
|
+
const _exit = deps.exit ?? ((code) => process.exit(code));
|
|
303
|
+
const _log = deps.log ?? ((msg) => console.log(msg));
|
|
304
|
+
if (shuttingDown.has(server))
|
|
305
|
+
return;
|
|
306
|
+
shuttingDown.add(server);
|
|
307
|
+
_log("\nShutting down…");
|
|
308
|
+
const live = _getLive();
|
|
309
|
+
if (live && live.recording) {
|
|
310
|
+
try {
|
|
311
|
+
await _stopRecording(live);
|
|
312
|
+
}
|
|
313
|
+
catch {
|
|
314
|
+
// Best-effort finalize; proceed with shutdown even if the stop failed.
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
let done = false;
|
|
318
|
+
let fallback;
|
|
319
|
+
const finish = () => {
|
|
320
|
+
if (done)
|
|
321
|
+
return;
|
|
322
|
+
done = true;
|
|
323
|
+
if (fallback)
|
|
324
|
+
clearTimeout(fallback);
|
|
325
|
+
_exit(0);
|
|
326
|
+
};
|
|
327
|
+
server.close(() => finish());
|
|
328
|
+
// Fallback: force-exit if close() hangs on a lingering keep-alive socket. Unref'd so the
|
|
329
|
+
// timer itself never keeps the process alive against a real shutdown.
|
|
330
|
+
fallback = setTimeout(finish, 2000);
|
|
331
|
+
fallback.unref();
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* Start the periodic auto-close sweep. Called once by bin.ts AFTER a successful listen bind, not
|
|
335
|
+
* from createServer, so importing this module (or spinning a throwaway server in a test) never
|
|
336
|
+
* arms a timer that could process.exit the test runner. The interval is unref'd so it never
|
|
337
|
+
* keeps the process alive on its own.
|
|
338
|
+
*/
|
|
339
|
+
export function startAutoCloseSweep(server) {
|
|
340
|
+
// Escape hatch for anyone whose workflow needs the old always-on lifetime, mirroring
|
|
341
|
+
// SLACK_RADAR_NO_FFMPEG. This changes default process lifetime in a published package, so it
|
|
342
|
+
// needs an off switch that does not require pinning an older version.
|
|
343
|
+
if (process.env.SLACK_RADAR_NO_AUTO_CLOSE === "1")
|
|
344
|
+
return null;
|
|
345
|
+
const timer = setInterval(() => {
|
|
346
|
+
if (sweepPresence(Date.now()))
|
|
347
|
+
void shutdownDashboard(server);
|
|
348
|
+
}, AUTO_CLOSE_SWEEP_MS);
|
|
349
|
+
timer.unref();
|
|
350
|
+
return timer;
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* Build the dashboard HTTP server. `onShutdown` is the hook the manual /shutdown route fires
|
|
354
|
+
* after answering; it defaults to the real graceful shutdown and is injectable so a test can
|
|
355
|
+
* exercise the route without exiting the process. bin.ts calls createServer() with no args.
|
|
356
|
+
*/
|
|
357
|
+
export function createServer(onShutdown) {
|
|
148
358
|
registerScreenCleanup(); // tear down any live screen cast on process exit/signals
|
|
149
359
|
const server = http.createServer((req, res) => {
|
|
360
|
+
// One chokepoint for every route: a request whose Host is not this loopback dashboard is a
|
|
361
|
+
// rebound foreign origin, not our client (see isLocalHostHeader). Rejected before routing so
|
|
362
|
+
// no handler has to remember, and so /shutdown in particular cannot be reached that way.
|
|
363
|
+
if (!isLocalHostHeader(req.headers.host)) {
|
|
364
|
+
// Name the remedy in the body. A bare 403 on a URL that used to work reads as a broken
|
|
365
|
+
// dashboard, and the fix (add the hostname you are using) is not guessable.
|
|
366
|
+
sendJson(res, 403, {
|
|
367
|
+
error: `Refusing a request for host "${String(req.headers.host)}". The dashboard only answers on localhost. If you reach it by another name, set SLACK_RADAR_ALLOWED_HOSTS to include it.`,
|
|
368
|
+
});
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
150
371
|
const url = req.url ?? "";
|
|
151
372
|
const urlPath = url.split("?")[0];
|
|
373
|
+
// Second chokepoint, DEFAULT DENY. A request must prove it came from our own client unless its
|
|
374
|
+
// path is a known read. Host alone is not enough: a page served from a real site can call
|
|
375
|
+
// localhost with no rebinding at all -- a text/plain POST and any GET are CORS simple requests,
|
|
376
|
+
// so no preflight is sent and the Host stays "localhost".
|
|
377
|
+
//
|
|
378
|
+
// This used to be an allowlist of five POST paths, and that shape failed twice in the same
|
|
379
|
+
// commit that introduced it: `/_control/activate` dispatched with startsWith so a suffix missed
|
|
380
|
+
// the exact-match Set, and `/api/clear` plus `/screen/redetect` reach the device on GET and
|
|
381
|
+
// were never listed at all. Enumerating what to protect fails open on everything forgotten, and
|
|
382
|
+
// cannot express prefix or method-agnostic handlers. Enumerating what is safe fails closed: a
|
|
383
|
+
// new route is protected until someone deliberately opens it.
|
|
384
|
+
if (!isOpenToAnyCaller(urlPath, req.method) && !isAuthoredRequest(req.headers)) {
|
|
385
|
+
sendJson(res, 403, {
|
|
386
|
+
error: `Refusing an unauthored ${String(req.method)} to ${urlPath}. Either this route can change state or reach the device (add the X-Radar-Dashboard: 1 header our own client sends, or Content-Type: application/json), or the path does not exist -- an unrecognized path is refused rather than 404'd so a new route is never open by accident.`,
|
|
387
|
+
});
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
152
390
|
if (urlPath === "/" || urlPath === "/index.html") {
|
|
153
391
|
// The Preact dashboard is the default (and only) UI. The old vanilla dashboard + its
|
|
154
392
|
// ?next opt-in seam were retired in the flip; index.html IS the Preact shell now.
|
|
@@ -171,16 +409,40 @@ export function createServer() {
|
|
|
171
409
|
return;
|
|
172
410
|
}
|
|
173
411
|
if (url === "/setspec" && req.method === "POST") {
|
|
174
|
-
handleSetSpec(req, res);
|
|
412
|
+
handleSetSpec(req, res, isAuthoredRequest(req.headers));
|
|
175
413
|
return;
|
|
176
414
|
}
|
|
177
|
-
if (
|
|
415
|
+
if (urlPath === "/health" && req.method === "GET") {
|
|
416
|
+
// Browser tabs ride their presence id on this poll (pollProfile's 5s /health fetch). A
|
|
417
|
+
// request without ?tab= (the MCP-side adopt probe, a plain curl) is just not a presence
|
|
418
|
+
// signal; the response shape is unchanged either way. The same X-Radar-Dashboard header
|
|
419
|
+
// /shutdown requires also gates presence: without it, a plain cross-origin GET (no
|
|
420
|
+
// preflight needed for a simple request) could set everSeen on an MCP-only dashboard or
|
|
421
|
+
// keep one alive forever from any page the user's browser has open -- the same process-
|
|
422
|
+
// kill/keep-alive threat model the header exists to close on /shutdown, reachable through
|
|
423
|
+
// this side door. A custom request header forces a real CORS preflight the foreign origin
|
|
424
|
+
// cannot satisfy. Silently ignoring an unauthenticated ?tab= (not 400ing) keeps a bare curl
|
|
425
|
+
// or an old MCP probe working exactly as before; it just never counts as presence.
|
|
426
|
+
//
|
|
427
|
+
// Deliberately the HEADER ALONE, not isAuthoredRequest. That predicate also accepts an
|
|
428
|
+
// application/json content-type, which exists only to keep older MCP /setspec writes
|
|
429
|
+
// working; on a bodyless GET it proves nothing about the caller. Keep this gate the
|
|
430
|
+
// narrower of the two rather than unifying them.
|
|
431
|
+
if (req.headers["x-radar-dashboard"] === "1") {
|
|
432
|
+
const tab = new URL(url, `http://localhost:${WEB_PORT}`).searchParams.get("tab");
|
|
433
|
+
if (tab)
|
|
434
|
+
touchTab(tab);
|
|
435
|
+
}
|
|
178
436
|
handleHealth(res);
|
|
179
437
|
return;
|
|
180
438
|
}
|
|
439
|
+
if (urlPath === "/shutdown" && req.method === "POST") {
|
|
440
|
+
handleShutdown(req, res, () => (onShutdown ?? shutdownDashboard)(server));
|
|
441
|
+
return;
|
|
442
|
+
}
|
|
181
443
|
if (urlPath === "/enable" && req.method === "POST") {
|
|
182
444
|
const serial = new URL(url, `http://localhost:${WEB_PORT}`).searchParams.get("device_serial");
|
|
183
|
-
handleEnable(res, serial);
|
|
445
|
+
handleEnable(res, serial, isAuthoredRequest(req.headers));
|
|
184
446
|
return;
|
|
185
447
|
}
|
|
186
448
|
if (url === "/stream" && req.method === "GET") {
|
|
@@ -227,7 +489,10 @@ export function createServer() {
|
|
|
227
489
|
listProfiles(res);
|
|
228
490
|
return;
|
|
229
491
|
}
|
|
230
|
-
|
|
492
|
+
// Match the exact path, not a prefix. A startsWith here disagreed with the authored-POST
|
|
493
|
+
// guard above (which keys on the exact urlPath), so `/_control/activateXYZ` skipped the guard
|
|
494
|
+
// and still re-armed the device. Any guarded route must match the same way the guard does.
|
|
495
|
+
if (urlPath === "/_control/activate" && req.method === "POST") {
|
|
231
496
|
const parsed = new URL(url, `http://localhost:${WEB_PORT}`);
|
|
232
497
|
const userId = parsed.searchParams.get("user_id") ?? undefined;
|
|
233
498
|
activateRadar(res, userId);
|
|
@@ -366,8 +631,10 @@ function readBody(req) {
|
|
|
366
631
|
* Persist a spec pushed by the client (a pre-built tab, a filter edit, a chip
|
|
367
632
|
* cancel) or by an MCP caller. Coerce + validate before writing; a bad spec is
|
|
368
633
|
* rejected with its reason so the UI can surface it rather than render zeros.
|
|
634
|
+
* `authored` means the caller proved it is our own client or the MCP; only then does the
|
|
635
|
+
* write count as a keep-alive (see below).
|
|
369
636
|
*/
|
|
370
|
-
async function handleSetSpec(req, res) {
|
|
637
|
+
async function handleSetSpec(req, res, authored) {
|
|
371
638
|
const body = await readBody(req);
|
|
372
639
|
let parsed;
|
|
373
640
|
try {
|
|
@@ -384,12 +651,36 @@ async function handleSetSpec(req, res) {
|
|
|
384
651
|
return;
|
|
385
652
|
}
|
|
386
653
|
writeSpec(spec);
|
|
654
|
+
// An authored write keeps the dashboard alive with zero open tabs (see markKeepAlive): a human
|
|
655
|
+
// may have closed the tab while the MCP keeps driving a long debugging session. Gated on the
|
|
656
|
+
// same X-Radar-Dashboard header /shutdown and /health presence require, because the body is
|
|
657
|
+
// never content-type checked: a cross-origin POST with a text/plain body is a CORS simple
|
|
658
|
+
// request, so without the gate any page in the user's browser could postpone auto-close
|
|
659
|
+
// forever by pinging this every few minutes. The spec still gets written either way, which
|
|
660
|
+
// keeps a bare curl working; it just does not buy the process more life.
|
|
661
|
+
if (authored)
|
|
662
|
+
markKeepAlive();
|
|
387
663
|
sendJson(res, 200, {
|
|
388
664
|
ok: true,
|
|
389
665
|
url: `http://localhost:${WEB_PORT}`,
|
|
390
666
|
title: spec.title ?? "",
|
|
391
667
|
});
|
|
392
668
|
}
|
|
669
|
+
/**
|
|
670
|
+
* Manual kill. The client's own kill button sets X-Radar-Dashboard: 1; a bare cross-origin
|
|
671
|
+
* POST from any page the user's browser has open cannot set a custom header without a CORS
|
|
672
|
+
* preflight it will fail, so requiring the header is a lightweight CSRF guard on a loopback
|
|
673
|
+
* route that takes the whole process down. Answer BEFORE shutting down so the button's fetch
|
|
674
|
+
* resolves rather than seeing a dropped socket, then fire the shutdown on the next tick.
|
|
675
|
+
*/
|
|
676
|
+
function handleShutdown(req, res, fire) {
|
|
677
|
+
if (req.headers["x-radar-dashboard"] !== "1") {
|
|
678
|
+
sendJson(res, 400, { error: "missing X-Radar-Dashboard header" });
|
|
679
|
+
return;
|
|
680
|
+
}
|
|
681
|
+
sendJson(res, 200, { ok: true, stopping: true });
|
|
682
|
+
setTimeout(fire, 0);
|
|
683
|
+
}
|
|
393
684
|
/**
|
|
394
685
|
* Always-available device-reachability probe, independent of whether a dashboard
|
|
395
686
|
* is built. Drives the connection dot even on a blank dashboard. Reuses the same
|
|
@@ -479,13 +770,182 @@ function handleHealth(res) {
|
|
|
479
770
|
});
|
|
480
771
|
probe.end();
|
|
481
772
|
}
|
|
773
|
+
/**
|
|
774
|
+
* The /enable response body for a completed device probe, plus its one side effect: a
|
|
775
|
+
* successful re-arm keeps the dashboard alive (an MCP-driven session can re-enable with no tab
|
|
776
|
+
* open, and that must not let the idle timer fire out from under it).
|
|
777
|
+
*
|
|
778
|
+
* `onEnabled` fires only on a successful probe. The route passes `markKeepAlive` when the
|
|
779
|
+
* request was authored (see isAuthoredRequest) and OMITS it otherwise, so an unauthored caller
|
|
780
|
+
* gets the same body but buys no extra process life. Injected rather than called directly so
|
|
781
|
+
* the keep-alive wiring is testable without a real device probe (handleEnable's ping goes over
|
|
782
|
+
* a real socket to RADAR_HOST:RADAR_PORT, which this function does not touch at all).
|
|
783
|
+
*
|
|
784
|
+
* A failed probe gets guidance, not a bare false: the broadcast landed (or exited 0 with no
|
|
785
|
+
* receiver), so the likely causes are a build without the slack-radar modules or the wrong
|
|
786
|
+
* profile. Mirrors the MCP enable message. Exported for unit testing.
|
|
787
|
+
*/
|
|
788
|
+
/**
|
|
789
|
+
* Which keep-alive hook /enable hands to enableResultBody: the real one for an authored request,
|
|
790
|
+
* none otherwise. Its own function purely so a test can assert the CHOICE. Asserting the effect
|
|
791
|
+
* through the route cannot cover this — handleEnable's device probe fails with no hardware, which
|
|
792
|
+
* short-circuits before the hook is ever consulted, so a route-level test passes either way (a
|
|
793
|
+
* mutation deleting the gate survived the whole suite before this existed).
|
|
794
|
+
*/
|
|
795
|
+
export function keepAliveHookFor(authored) {
|
|
796
|
+
return authored ? markKeepAlive : undefined;
|
|
797
|
+
}
|
|
798
|
+
// Reads the dashboard serves to any local caller. Everything NOT matching is treated as
|
|
799
|
+
// state-changing and needs proof it came from our own client (see isOpenToAnyCaller).
|
|
800
|
+
//
|
|
801
|
+
// Two rules for adding to this list, both learned from a real bypass:
|
|
802
|
+
// 1. It must be genuinely side-effect free. /api/clear looks like a read and wipes the device.
|
|
803
|
+
// 2. It must be reachable ONLY by the shape listed here. A prefix entry opens every path under
|
|
804
|
+
// it, so `/api/` cannot be blanket-opened while /api/clear lives behind the same proxy.
|
|
805
|
+
const READ_ONLY_EXACT = new Set([
|
|
806
|
+
"/",
|
|
807
|
+
"/index.html",
|
|
808
|
+
"/health",
|
|
809
|
+
"/spec",
|
|
810
|
+
"/stream", // EventSource cannot set headers, so this must stay open
|
|
811
|
+
"/backfill",
|
|
812
|
+
"/detail",
|
|
813
|
+
"/dbs", // only lists database names; no pull
|
|
814
|
+
// NOT /dbtables and NOT /dbquery. Both reach pullDatabase, which mkdirs a temp dir and writes a
|
|
815
|
+
// multi-MB PLAINTEXT copy of the on-device message store (plus -wal/-shm) to host disk;
|
|
816
|
+
// /dbtables?refresh=1 re-pulls unconditionally. They read like a listing and a select, but each
|
|
817
|
+
// is a data-exposure step and a repeatable multi-MB adb pull, so both need proof of origin.
|
|
818
|
+
// queryDatabase pulls too when no local copy exists (db.ts: `if (!existsSync(local)) await
|
|
819
|
+
// pullDatabase(...)`), so gating only /dbtables would leave the same pull reachable.
|
|
820
|
+
"/flags",
|
|
821
|
+
"/prefs",
|
|
822
|
+
"/prefsread",
|
|
823
|
+
"/prefssearch",
|
|
824
|
+
"/screen/caps",
|
|
825
|
+
"/screen/shot", // <img src> cannot set a header
|
|
826
|
+
"/screen/stream", // <img src> live MJPEG cast, same
|
|
827
|
+
"/_control/profiles",
|
|
828
|
+
"/_control/devices",
|
|
829
|
+
]);
|
|
830
|
+
// Path PREFIXES that are read-only for their whole subtree. Kept tiny and audited: anything added
|
|
831
|
+
// here opens every path beneath it forever. These two serve the dashboard's own static bundle.
|
|
832
|
+
// The server matches these with startsWith, so the guard has to as well or a real request 403s.
|
|
833
|
+
// /screen/download/<file> serves a finished recording the user asked to save.
|
|
834
|
+
const READ_ONLY_PREFIXES = ["/next/", "/vendor/", "/screen/download"];
|
|
835
|
+
// Device-proxy reads. `/api/` as a whole is NOT safe (/api/clear wipes the device buffers), so the
|
|
836
|
+
// readable sources are named and everything else under /api/ falls through to the guard.
|
|
837
|
+
// Only names the device actually serves today (verified live: /api/prefs and /api/session 404).
|
|
838
|
+
// A dead entry here is worse than useless -- the device dispatches /api/<name> to any RadarPlugin
|
|
839
|
+
// claiming that name, and plugin handlers carry no side-effect guarantee, so listing a name nothing
|
|
840
|
+
// serves pre-authorizes whatever future plugin takes it.
|
|
841
|
+
const READ_ONLY_API_SOURCES = [
|
|
842
|
+
"ping",
|
|
843
|
+
"network",
|
|
844
|
+
"rtm",
|
|
845
|
+
"clogs",
|
|
846
|
+
"traces",
|
|
847
|
+
"feature_flags",
|
|
848
|
+
"search",
|
|
849
|
+
];
|
|
850
|
+
/**
|
|
851
|
+
* Whether the dashboard serves this request without proof of origin. Everything else is refused
|
|
852
|
+
* unless authored. Exported so a test can drive the decision directly, and so the open surface is
|
|
853
|
+
* reviewable in one place instead of inferred from twenty route branches.
|
|
854
|
+
*
|
|
855
|
+
* Reads are open by path. Writes are closed with exactly two named exceptions, both justified
|
|
856
|
+
* below. A POST to a read path is NOT open: only GET and HEAD can ever be reads.
|
|
857
|
+
*/
|
|
858
|
+
export function isOpenToAnyCaller(urlPath, method) {
|
|
859
|
+
// The two deliberate write carve-outs, POST only. /setspec is the one write anyone may make: it
|
|
860
|
+
// rewrites the local dashboard view, driving it with a bare `curl -X POST` is supported, and its
|
|
861
|
+
// keep-alive side effect is gated separately (see handleSetSpec). /shutdown carries its own
|
|
862
|
+
// header check inside handleShutdown, which answers before exiting.
|
|
863
|
+
//
|
|
864
|
+
// Pinned to POST because that is the only method either route dispatches. Allowing any method
|
|
865
|
+
// would repeat the mistake this whole guard exists to fix: a future non-POST handler on one of
|
|
866
|
+
// these paths would be born open.
|
|
867
|
+
if (method === "POST" && (urlPath === "/setspec" || urlPath === "/shutdown"))
|
|
868
|
+
return true;
|
|
869
|
+
if (method !== "GET" && method !== "HEAD")
|
|
870
|
+
return false;
|
|
871
|
+
if (READ_ONLY_EXACT.has(urlPath))
|
|
872
|
+
return true;
|
|
873
|
+
if (READ_ONLY_PREFIXES.some((prefix) => urlPath.startsWith(prefix)))
|
|
874
|
+
return true;
|
|
875
|
+
// /api/<source> and /api/<source>/<id> are reads; /api/clear and anything unrecognized are not.
|
|
876
|
+
const apiMatch = /^\/api\/([^/]+)(?:\/[^/]*)?$/.exec(urlPath);
|
|
877
|
+
return apiMatch !== null && READ_ONLY_API_SOURCES.includes(apiMatch[1]);
|
|
878
|
+
}
|
|
879
|
+
/**
|
|
880
|
+
* Whether a request's Host names this loopback dashboard. The listener is bound to 127.0.0.1, but
|
|
881
|
+
* that only limits which interface accepts the TCP connection: a browser resolving an attacker's
|
|
882
|
+
* domain to 127.0.0.1 (DNS rebinding) connects locally and arrives with that domain in Host. The
|
|
883
|
+
* page is then same-origin by the browser's reckoning, so it can set any header it likes and the
|
|
884
|
+
* X-Radar-Dashboard guard buys nothing against it. Checking Host is what makes the loopback bind
|
|
885
|
+
* an actual boundary, and it matters most for /shutdown, which kills the process.
|
|
886
|
+
*
|
|
887
|
+
* Accepts localhost / 127.0.0.1 / [::1] / ::1 / 0.0.0.0, with or without a port, and a missing
|
|
888
|
+
* Host (HTTP/1.0 and a bare socket client send none; those cannot be a rebound browser).
|
|
889
|
+
*
|
|
890
|
+
* SLACK_RADAR_ALLOWED_HOSTS adds names for the setups that reach the dashboard by something other
|
|
891
|
+
* than localhost -- a /etc/hosts alias, a container or Codespaces forwarded URL, a LAN hostname.
|
|
892
|
+
* Comma-separated, `host` or `host:port`; a bare name matches on any port. Without it those users
|
|
893
|
+
* would just get a 403 with nothing to do about it.
|
|
894
|
+
*/
|
|
895
|
+
export function isLocalHostHeader(host, allowedHosts = process.env.SLACK_RADAR_ALLOWED_HOSTS) {
|
|
896
|
+
const value = Array.isArray(host) ? host[0] : host;
|
|
897
|
+
if (value === undefined || value === "")
|
|
898
|
+
return true;
|
|
899
|
+
const raw = value.trim().toLowerCase();
|
|
900
|
+
// Strip the port to compare the name alone. Three shapes to keep straight:
|
|
901
|
+
// host:8100 -> strip
|
|
902
|
+
// [::1]:8100 -> strip (the brackets survive, which is what we compare against)
|
|
903
|
+
// ::1 -> do NOT strip; a bare IPv6 literal is all colons, and stripping the last
|
|
904
|
+
// group would leave ":" and reject a legitimate loopback request.
|
|
905
|
+
// So only strip when the value is bracketed, or when it holds at most one colon.
|
|
906
|
+
const bracketed = raw.startsWith("[");
|
|
907
|
+
const name = bracketed || raw.split(":").length <= 2 ? raw.replace(/:\d+$/, "") : raw;
|
|
908
|
+
if (name === "localhost" ||
|
|
909
|
+
name === "127.0.0.1" ||
|
|
910
|
+
name === "0.0.0.0" ||
|
|
911
|
+
name === "[::1]" ||
|
|
912
|
+
name === "::1") {
|
|
913
|
+
return true;
|
|
914
|
+
}
|
|
915
|
+
// Operator-listed names. Both sides are compared with and without their port, so an entry
|
|
916
|
+
// matches whichever shape actually arrives: `radar.local` admits `radar.local:8100`, and
|
|
917
|
+
// `radar.local:8100` admits a bare `radar.local` (which is what a browser sends on 80/443,
|
|
918
|
+
// the forwarded-URL case this env var exists for).
|
|
919
|
+
for (const entry of (allowedHosts ?? "").split(",")) {
|
|
920
|
+
const allowed = entry.trim().toLowerCase();
|
|
921
|
+
if (allowed === "")
|
|
922
|
+
continue;
|
|
923
|
+
const allowedName = allowed.startsWith("[") || allowed.split(":").length <= 2
|
|
924
|
+
? allowed.replace(/:\d+$/, "")
|
|
925
|
+
: allowed;
|
|
926
|
+
if (allowed === raw || allowed === name || allowedName === raw || allowedName === name) {
|
|
927
|
+
return true;
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
return false;
|
|
931
|
+
}
|
|
932
|
+
export function enableResultBody(enabled, onEnabled) {
|
|
933
|
+
if (enabled) {
|
|
934
|
+
onEnabled?.();
|
|
935
|
+
return { enabled };
|
|
936
|
+
}
|
|
937
|
+
return {
|
|
938
|
+
enabled,
|
|
939
|
+
error: "Radar broadcast sent but the device server did not respond. Is a debug build with the slack-radar modules running on the active profile?",
|
|
940
|
+
};
|
|
941
|
+
}
|
|
482
942
|
/**
|
|
483
943
|
* Re-arm Radar from the dashboard. Mirrors the recovery sequence: reset cached
|
|
484
944
|
* forward state, rebuild a clean adb forward, and re-broadcast activation, so the
|
|
485
945
|
* user never has to drop to a terminal. Delegates entirely to AndroidTransport;
|
|
486
946
|
* no adb shelling here.
|
|
487
947
|
*/
|
|
488
|
-
function handleEnable(res, deviceSerial) {
|
|
948
|
+
function handleEnable(res, deviceSerial, authored) {
|
|
489
949
|
transport.resetState();
|
|
490
950
|
// A reconnect may be a different device / re-armed profile, so drop the cached DB user
|
|
491
951
|
// set + sqlite path; the next /dbs re-detects the profiles fresh.
|
|
@@ -557,15 +1017,7 @@ function handleEnable(res, deviceSerial) {
|
|
|
557
1017
|
if (replied)
|
|
558
1018
|
return;
|
|
559
1019
|
replied = true;
|
|
560
|
-
|
|
561
|
-
// exited 0 with no receiver), so the likely causes are a build without the
|
|
562
|
-
// radar modules or the wrong profile. Mirrors the MCP enable message.
|
|
563
|
-
sendJson(res, 200, enabled
|
|
564
|
-
? { enabled }
|
|
565
|
-
: {
|
|
566
|
-
enabled,
|
|
567
|
-
error: "Radar broadcast sent but the device server did not respond. Is a debug build with the slack-radar modules running on the active profile?",
|
|
568
|
-
});
|
|
1020
|
+
sendJson(res, 200, enableResultBody(enabled, keepAliveHookFor(authored)));
|
|
569
1021
|
};
|
|
570
1022
|
const probe = http.request({
|
|
571
1023
|
host: RADAR_HOST,
|