@slack/radar-mcp 1.11.0 → 1.13.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 +12 -2
- package/dist/mcp/api-paths.js +2 -0
- package/dist/mcp/flags-tools.d.ts +71 -0
- package/dist/mcp/flags-tools.js +158 -0
- package/dist/mcp/index.js +103 -5
- package/dist/mcp/prefs-tools.d.ts +15 -0
- package/dist/mcp/prefs-tools.js +204 -0
- package/dist/mcp/session-enable.d.ts +2 -1
- package/dist/mcp/session-enable.js +29 -2
- package/dist/mcp/snapshot.js +6 -1
- package/dist/mcp/sources-gate.d.ts +23 -0
- package/dist/mcp/sources-gate.js +63 -0
- package/dist/mcp/tools.js +102 -2
- package/dist/shared/android.d.ts +33 -1
- package/dist/shared/android.js +203 -6
- package/dist/shared/constants.d.ts +8 -0
- package/dist/shared/constants.js +13 -1
- package/dist/shared/db.d.ts +21 -3
- package/dist/shared/db.js +89 -23
- package/dist/shared/feature-flags.d.ts +6 -0
- package/dist/shared/feature-flags.js +17 -0
- package/dist/shared/prefs.d.ts +78 -0
- package/dist/shared/prefs.js +416 -0
- package/dist/shared/transport.d.ts +68 -0
- package/dist/web/log-session.d.ts +13 -0
- package/dist/web/log-session.js +16 -0
- package/dist/web/public/index.html +129 -3
- package/dist/web/public/next/app.js +82 -4
- package/dist/web/public/next/feed.js +270 -14
- package/dist/web/public/next/filter.js +200 -0
- package/dist/web/public/next/flags.js +179 -0
- package/dist/web/public/next/prefs.js +399 -0
- package/dist/web/public/next/registry.js +16 -6
- package/dist/web/public/next/store.js +250 -11
- package/dist/web/server.js +267 -7
- package/dist/web/spec.d.ts +7 -7
- package/dist/web/spec.js +15 -9
- package/package.json +1 -1
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* On-device SharedPreferences reader (host-side, read-only).
|
|
3
|
+
*
|
|
4
|
+
* The Slack app stores configuration, feature flags, and user preferences in standard
|
|
5
|
+
* Android SharedPreferences XML files under `shared_prefs/`. This reader streams them
|
|
6
|
+
* off-device via `adb exec-out run-as`, parses the XML, and offers search/filter.
|
|
7
|
+
* Nothing is written on the device; no app rebuild needed. Dual-profile aware (personal
|
|
8
|
+
* user 0 and work profiles user 10+).
|
|
9
|
+
*
|
|
10
|
+
* SECURITY: preference values can include user IDs, team IDs, org IDs, and feature flag
|
|
11
|
+
* state. This reader only returns files/keys/values to the caller (no host-side file
|
|
12
|
+
* written), with a privacy note reminding the caller to review before sharing.
|
|
13
|
+
*/
|
|
14
|
+
import { execFileSync, execFile } from "child_process";
|
|
15
|
+
import { promisify } from "util";
|
|
16
|
+
import { SLACK_DEBUG_PKG } from "./constants.js";
|
|
17
|
+
import { detectRunAsError } from "./debug-log.js";
|
|
18
|
+
import { availableUsers } from "./db.js";
|
|
19
|
+
const PREFS_PKG = SLACK_DEBUG_PKG;
|
|
20
|
+
const ADB_MAX_BUFFER = 2 * 1024 * 1024; // prefs can be large; user 10 observed 1.2MB total
|
|
21
|
+
// ASYNC, not execFileSync: Node is single-threaded, so a blocking adb call freezes the whole
|
|
22
|
+
// event loop -- every other in-flight HTTP request (a file click, /health) queues behind it.
|
|
23
|
+
// readPrefsFile is the HEAVY, repeated op here: searchPrefs calls it once per file (up to ~76
|
|
24
|
+
// on a real work profile), so a sync exec means one search blocks the server for the sum of
|
|
25
|
+
// every file's adb round-trip -- reproduced live: a file click queued behind an in-flight
|
|
26
|
+
// search's remaining reads and showed "loading..." for several seconds. listPrefsFiles (one
|
|
27
|
+
// `ls`, not called in a per-file loop) stays sync, mirroring db.ts's own stated rule: light
|
|
28
|
+
// cached probes stay sync, heavy/repeated ops go async (see db.ts's runAdbAsync comment).
|
|
29
|
+
const execFileP = promisify(execFile);
|
|
30
|
+
function runAdbAsync(adbPath, args) {
|
|
31
|
+
return execFileP(adbPath, args, { timeout: 10000, maxBuffer: ADB_MAX_BUFFER, encoding: "utf-8" }).then((r) => r.stdout);
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Resolve the Android user to read from: explicit user wins; else use the first available
|
|
35
|
+
* user. An explicit user is trusted WITHOUT checking availableUsers() on purpose: doing so
|
|
36
|
+
* would call the device unconditionally (availableUsers() has no adbPath param, so it always
|
|
37
|
+
* shells to the real adb on PATH — this broke every prefs unit test's hermeticity, real device
|
|
38
|
+
* or not, until reverted here). Trusting an unknown explicit id is safe because the actual
|
|
39
|
+
* mislabel risk lives downstream, not here: if the flagged run-as denies, the no-flag retry
|
|
40
|
+
* reports user:"" (see readPrefsFile/listPrefsFiles), never the requested id — so an unknown
|
|
41
|
+
* or wrong user id can never be reported as successfully read.
|
|
42
|
+
* Returns the resolved user ID (never undefined for normal operation).
|
|
43
|
+
*/
|
|
44
|
+
function resolveUser(user) {
|
|
45
|
+
if (user)
|
|
46
|
+
return user;
|
|
47
|
+
const available = availableUsers();
|
|
48
|
+
return available.length > 0 ? available[0] : "0";
|
|
49
|
+
}
|
|
50
|
+
/** Reject filenames that are not bare XML files (path traversal guard). */
|
|
51
|
+
function assertSafePrefsName(name) {
|
|
52
|
+
if (!name || !/^[A-Za-z0-9._-]+\.xml$/.test(name)) {
|
|
53
|
+
throw new Error(`invalid prefs filename: ${name}`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/** Reject user IDs that are not non-negative integers (command injection guard). */
|
|
57
|
+
function assertSafeUser(user) {
|
|
58
|
+
if (user && !/^[0-9]+$/.test(user)) {
|
|
59
|
+
throw new Error(`invalid android user id: ${user}`);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* List SharedPreferences files for a user, with their sizes.
|
|
64
|
+
* Via `run-as ... ls -la shared_prefs/` and parse name+size.
|
|
65
|
+
* Returns null on run-as failure.
|
|
66
|
+
*/
|
|
67
|
+
export function listPrefsFiles(adbPath, user) {
|
|
68
|
+
if (user)
|
|
69
|
+
assertSafeUser(user);
|
|
70
|
+
try {
|
|
71
|
+
const resolvedUser = resolveUser(user);
|
|
72
|
+
const userFlag = `--user ${resolvedUser} `;
|
|
73
|
+
const out = execFileSync(adbPath, ["shell", `run-as ${PREFS_PKG} ${userFlag}ls -la shared_prefs/`], { timeout: 10000, maxBuffer: ADB_MAX_BUFFER, encoding: "utf-8" });
|
|
74
|
+
const runAsErr = detectRunAsError(out);
|
|
75
|
+
if (runAsErr) {
|
|
76
|
+
// Try without user flag as fallback (see debug-log.ts for rationale). Which user this
|
|
77
|
+
// no-flag read actually lands on is NOT necessarily resolvedUser (that is precisely the
|
|
78
|
+
// profile it just failed to reach) — report "" (db.ts's convention for "ambiguous/
|
|
79
|
+
// implicit user") rather than mislabeling the result with the requested id.
|
|
80
|
+
try {
|
|
81
|
+
const retry = execFileSync(adbPath, ["shell", `run-as ${PREFS_PKG} ls -la shared_prefs/`], { timeout: 10000, maxBuffer: ADB_MAX_BUFFER, encoding: "utf-8" });
|
|
82
|
+
if (!detectRunAsError(retry)) {
|
|
83
|
+
return parseListOutput(retry, "");
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
// fall through
|
|
88
|
+
}
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
return parseListOutput(out, resolvedUser);
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
/** Parse `ls -la` output and extract filename + size. Tolerates busybox/toybox variants. */
|
|
98
|
+
function parseListOutput(output, user) {
|
|
99
|
+
const files = [];
|
|
100
|
+
for (const line of output.split("\n")) {
|
|
101
|
+
const trimmed = line.trim();
|
|
102
|
+
if (!trimmed || trimmed.startsWith("total"))
|
|
103
|
+
continue;
|
|
104
|
+
// ls -la format: permissions links owner group size <date> [time] name. The date/time
|
|
105
|
+
// portion varies: some toybox builds print "month day time" (3 tokens), others print
|
|
106
|
+
// an ISO date + time as 2 tokens (e.g. "2026-06-15 15:18", observed on-device) — 8
|
|
107
|
+
// fields total in that case, 9 in the "month day time" case. The size is always at
|
|
108
|
+
// index 4 (0-based) and the name is always the last field, so a floor of 8 covers both.
|
|
109
|
+
const parts = trimmed.split(/\s+/);
|
|
110
|
+
if (parts.length < 8)
|
|
111
|
+
continue;
|
|
112
|
+
// The 5th field (index 4) is typically the size; verify it is numeric.
|
|
113
|
+
const sizeStr = parts[4];
|
|
114
|
+
const size = parseInt(sizeStr, 10);
|
|
115
|
+
if (isNaN(size))
|
|
116
|
+
continue;
|
|
117
|
+
const name = parts[parts.length - 1];
|
|
118
|
+
if (name && name.endsWith(".xml")) {
|
|
119
|
+
files.push({ name, size });
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return { user, files };
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* True when the output is a complete `<map>...</map>` (or self-closing `<map/>`) document,
|
|
126
|
+
* allowing for a leading XML declaration/whitespace. Used to detect a mid-write `.bak`
|
|
127
|
+
* swap, where `cat` succeeds but returns a truncated read (most commonly an unclosed
|
|
128
|
+
* `<map>` with no matching `</map>`) instead of a run-as error or a thrown exception.
|
|
129
|
+
* Requiring the closing tag (not just the opening one) is what actually catches a
|
|
130
|
+
* truncated read — a prefix-only check would pass on `<map><string name="x">incomplete`.
|
|
131
|
+
*/
|
|
132
|
+
function looksLikeValidPrefsXml(xml) {
|
|
133
|
+
return /^\s*(<\?xml[^>]*>\s*)?(<map\s*\/>|<map\b[^>]*>[\s\S]*<\/map>)\s*$/.test(xml);
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Read a SharedPreferences XML file from the device.
|
|
137
|
+
* Via `adb exec-out run-as ... cat shared_prefs/<name>`.
|
|
138
|
+
* Validates filename and user first. Caps read at 256KB (truncated: true if larger).
|
|
139
|
+
* Returns { xml: string, user: string, truncated?: boolean } on success or { error: string } on failure.
|
|
140
|
+
* Retries once after ~200ms if the first read fails (mid-write .bak swap).
|
|
141
|
+
*/
|
|
142
|
+
export async function readPrefsFile(adbPath, name, user) {
|
|
143
|
+
assertSafePrefsName(name);
|
|
144
|
+
if (user)
|
|
145
|
+
assertSafeUser(user);
|
|
146
|
+
const MAX_PREFS_BYTES = 256 * 1024;
|
|
147
|
+
const resolvedUser = resolveUser(user);
|
|
148
|
+
// Tracks whether a read actually landed via the no-flag fallback (some OTHER, unknown
|
|
149
|
+
// profile) rather than resolvedUser, so the caller is never told it read a user it did not.
|
|
150
|
+
let readViaFallback = false;
|
|
151
|
+
// One exec attempt with a given --user flag (or "" for none). Never recurses -- returns
|
|
152
|
+
// whether the output was a run-as denial so the caller decides what to do next. Isolating
|
|
153
|
+
// the single exec from the retry policy is what makes doRead below have NO way to loop: a
|
|
154
|
+
// recursive version (doRead calling doRead) only stayed bounded because the recursive call
|
|
155
|
+
// always happened to pass a falsy flag; that is a convention, not something the type system
|
|
156
|
+
// or control flow enforces, and a mutation test proved it -- feeding the SAME truthy flag
|
|
157
|
+
// back into the recursive call spun forever with no timeout ever catching it (each single
|
|
158
|
+
// exec has its own 10s bound, but nothing bounds how many times it can recurse). A flat,
|
|
159
|
+
// non-recursive shape has no such failure mode: it is structurally impossible to loop,
|
|
160
|
+
// regardless of what flag value ends up passed in here.
|
|
161
|
+
const attemptRead = async (userFlag) => {
|
|
162
|
+
try {
|
|
163
|
+
// maxBuffer must fit the FULL on-device file, not just the truncation cap below:
|
|
164
|
+
// exec-out has no way to stop the device mid-stream, so a buffer sized to
|
|
165
|
+
// MAX_PREFS_BYTES would make this throw (ERR_CHILD_PROCESS_STDIO_MAXBUFFER) on any file
|
|
166
|
+
// bigger than the cap — observed live against a 422KB prefs file — instead of the
|
|
167
|
+
// intended behavior of reading it fully and truncating the string afterward.
|
|
168
|
+
const out = await runAdbAsync(adbPath, [
|
|
169
|
+
"exec-out",
|
|
170
|
+
`run-as ${PREFS_PKG} ${userFlag}cat shared_prefs/${name}`,
|
|
171
|
+
]);
|
|
172
|
+
return { out, denied: !!detectRunAsError(out) };
|
|
173
|
+
}
|
|
174
|
+
catch {
|
|
175
|
+
return { out: null, denied: false };
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
// At most two exec attempts, ever: the flagged read, then (only on a run-as denial WITH a
|
|
179
|
+
// flag) one no-flag retry. No loop, no recursion -- bounded by construction.
|
|
180
|
+
const doRead = async (userFlag) => {
|
|
181
|
+
const first = await attemptRead(userFlag);
|
|
182
|
+
if (!first.denied)
|
|
183
|
+
return first.out;
|
|
184
|
+
if (!userFlag)
|
|
185
|
+
return null; // already the no-flag attempt; nothing left to try
|
|
186
|
+
const second = await attemptRead("");
|
|
187
|
+
if (second.denied || second.out === null)
|
|
188
|
+
return null;
|
|
189
|
+
readViaFallback = true;
|
|
190
|
+
return second.out;
|
|
191
|
+
};
|
|
192
|
+
const userFlag = `--user ${resolvedUser} `;
|
|
193
|
+
let xml = await doRead(userFlag);
|
|
194
|
+
// A mid-write `.bak` swap can make the exec succeed with truncated/garbage content —
|
|
195
|
+
// not a run-as denial, not a thrown error — so retry on structurally-invalid XML too,
|
|
196
|
+
// not just on a null (exec-failed) result. parsePrefsXml itself never fails structurally
|
|
197
|
+
// (garbage input just yields fewer/no entries by design), so use a dedicated shape check.
|
|
198
|
+
if (xml === null || !looksLikeValidPrefsXml(xml)) {
|
|
199
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
200
|
+
const retry = await doRead(userFlag);
|
|
201
|
+
if (retry !== null && looksLikeValidPrefsXml(retry)) {
|
|
202
|
+
xml = retry;
|
|
203
|
+
}
|
|
204
|
+
else if (xml === null) {
|
|
205
|
+
return { error: "Failed to read prefs file from device" };
|
|
206
|
+
}
|
|
207
|
+
else if (!looksLikeValidPrefsXml(xml)) {
|
|
208
|
+
return { error: "Failed to read prefs file from device (mid-write on retry)" };
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
const truncated = xml.length > MAX_PREFS_BYTES;
|
|
212
|
+
if (truncated) {
|
|
213
|
+
xml = xml.substring(0, MAX_PREFS_BYTES);
|
|
214
|
+
}
|
|
215
|
+
// readViaFallback means the content actually came from the no-flag retry, an unknown
|
|
216
|
+
// profile that is NOT necessarily resolvedUser (that is the profile the flagged read just
|
|
217
|
+
// failed against) — report "" (db.ts's convention) rather than mislabeling it.
|
|
218
|
+
const actualUser = readViaFallback ? "" : resolvedUser;
|
|
219
|
+
return { xml, user: actualUser, ...(truncated ? { truncated: true } : {}) };
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Parse SharedPreferences XML into typed entries.
|
|
223
|
+
* Handles: boolean, int, long, float, string, set (with string children).
|
|
224
|
+
* Returns { entries: [...] } on success or { parseError: string } on failure.
|
|
225
|
+
* Handles: entity unescaping, self-closing and open-close forms, empty map, garbage input.
|
|
226
|
+
* Never throws.
|
|
227
|
+
*/
|
|
228
|
+
export function parsePrefsXml(xml) {
|
|
229
|
+
try {
|
|
230
|
+
const entries = [];
|
|
231
|
+
// Match direct child elements of <map>: boolean, int, long, float, string, set.
|
|
232
|
+
// One ordered pass over both forms (so document order is preserved — matching
|
|
233
|
+
// self-closing and open-close tags in two separate passes scrambled entry order
|
|
234
|
+
// and dropped the value attribute on open-close tags that carry one):
|
|
235
|
+
// - Self-closing: <type name="key" value="val"/>
|
|
236
|
+
// - Open-close: <type name="key" [value="val"]>contents</type> (the value
|
|
237
|
+
// attribute wins over contents when both are present).
|
|
238
|
+
// The tag-name allowlist means <map> itself is never matched.
|
|
239
|
+
const elementRegex = /<(boolean|int|long|float|string|set)\s+name="([^"]*)"(?:\s+value="([^"]*)")?\s*(?:\/>|>([\s\S]*?)<\/\1>)/g;
|
|
240
|
+
let m;
|
|
241
|
+
// eslint-disable-next-line no-cond-assign
|
|
242
|
+
while ((m = elementRegex.exec(xml)) !== null) {
|
|
243
|
+
const type = m[1];
|
|
244
|
+
const key = unescape(m[2] || "");
|
|
245
|
+
const attrValue = m[3];
|
|
246
|
+
const contents = m[4] || "";
|
|
247
|
+
let value = null;
|
|
248
|
+
if (type === "set") {
|
|
249
|
+
// Set: extract string children.
|
|
250
|
+
const items = [];
|
|
251
|
+
const stringRegex = /<string[^>]*>([^<]*)<\/string>/g;
|
|
252
|
+
let stringMatch;
|
|
253
|
+
// eslint-disable-next-line no-cond-assign
|
|
254
|
+
while ((stringMatch = stringRegex.exec(contents)) !== null) {
|
|
255
|
+
items.push(unescape(stringMatch[1] || ""));
|
|
256
|
+
}
|
|
257
|
+
value = items;
|
|
258
|
+
}
|
|
259
|
+
else {
|
|
260
|
+
// Scalar type: the value attribute wins when present; else use contents.
|
|
261
|
+
value = coerceValue(type, attrValue !== undefined ? attrValue : contents);
|
|
262
|
+
}
|
|
263
|
+
if (key && value !== null) {
|
|
264
|
+
entries.push({ key, type, value });
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
return { entries };
|
|
268
|
+
}
|
|
269
|
+
catch (e) {
|
|
270
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
271
|
+
return { parseError: `XML parse error: ${msg}` };
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
function coerceValue(type, raw) {
|
|
275
|
+
switch (type) {
|
|
276
|
+
case "boolean":
|
|
277
|
+
return raw.toLowerCase() === "true";
|
|
278
|
+
case "int": {
|
|
279
|
+
const parsed = parseInt(raw, 10);
|
|
280
|
+
return isNaN(parsed) ? raw : parsed;
|
|
281
|
+
}
|
|
282
|
+
case "long":
|
|
283
|
+
// Keep long as string to preserve precision (native JS numbers lose precision above 2^53).
|
|
284
|
+
return raw;
|
|
285
|
+
case "float": {
|
|
286
|
+
const parsed = parseFloat(raw);
|
|
287
|
+
return isNaN(parsed) ? raw : parsed;
|
|
288
|
+
}
|
|
289
|
+
case "string":
|
|
290
|
+
return unescape(raw);
|
|
291
|
+
default:
|
|
292
|
+
return raw;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
/** Unescape XML entities: " & < > ' */
|
|
296
|
+
function unescape(s) {
|
|
297
|
+
return s
|
|
298
|
+
.replace(/"/g, '"')
|
|
299
|
+
.replace(/'/g, "'")
|
|
300
|
+
.replace(/</g, "<")
|
|
301
|
+
.replace(/>/g, ">")
|
|
302
|
+
.replace(/&/g, "&"); // must come last to avoid double-unescaping
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Search preferences across all files for a user.
|
|
306
|
+
* Case-insensitive substring search on key names and stringified values.
|
|
307
|
+
* Returns per-file match results, capped at 200 total matches across all files
|
|
308
|
+
* (truncated: true when the cap was hit, so a caller can tell "no more matches"
|
|
309
|
+
* apart from "matches exist beyond this page" — plain array truncation would lose
|
|
310
|
+
* that flag on JSON.stringify, since non-index array properties are not serialized).
|
|
311
|
+
* A file that fails to read (run-as denial, mid-write on both attempts) or fails to
|
|
312
|
+
* parse is skipped and named in `skipped`, so a caller can tell "no match in this file"
|
|
313
|
+
* apart from "this file could not be checked."
|
|
314
|
+
*/
|
|
315
|
+
export async function searchPrefs(adbPath, query, user) {
|
|
316
|
+
if (user)
|
|
317
|
+
assertSafeUser(user);
|
|
318
|
+
const results = [];
|
|
319
|
+
const skipped = [];
|
|
320
|
+
let truncated = false;
|
|
321
|
+
const queryLower = query.toLowerCase();
|
|
322
|
+
let totalMatches = 0;
|
|
323
|
+
const MAX_MATCHES = 200;
|
|
324
|
+
// Resolve user: if not provided, use the first available user.
|
|
325
|
+
const targetUser = resolveUser(user);
|
|
326
|
+
// List files for the user. listResult.user is the ACTUAL user this landed on, which is ""
|
|
327
|
+
// (not targetUser) when the flagged read denied and the no-flag fallback recovered against
|
|
328
|
+
// some other, unknown profile (see listPrefsFiles's own "" convention). Report that, not
|
|
329
|
+
// targetUser, so a search on a flag-denying device does not claim it searched the requested
|
|
330
|
+
// user when it actually hit the ambiguous default -- the same convention readPrefsFile
|
|
331
|
+
// already honors for get_prefs.
|
|
332
|
+
const listResult = listPrefsFiles(adbPath, targetUser);
|
|
333
|
+
if (!listResult) {
|
|
334
|
+
return { results, user: targetUser }; // run-as failed, nothing was read either way
|
|
335
|
+
}
|
|
336
|
+
const actualUser = listResult.user;
|
|
337
|
+
// Read and search each file. One run-as exec per file (readPrefsFile's own 200ms
|
|
338
|
+
// mid-write retry applies per-file). A single-run-as-for-all-files batch was tried and
|
|
339
|
+
// reverted: it requires shell control flow (a for/do/done loop) inside the run-as command
|
|
340
|
+
// string, but run-as has no shell of its own — `run-as PKG for f in ...; do ...; done` is
|
|
341
|
+
// literal argv, not a script, and threw a syntax error on a real device even though the
|
|
342
|
+
// mocked tests (which pattern-match the command string instead of executing it) all passed.
|
|
343
|
+
// Per-file execs are slower on a many-file profile but each one is a KNOWN-correct
|
|
344
|
+
// `cat <name>` invocation with no embedded control flow, so there is no equivalent failure
|
|
345
|
+
// mode. See book chapter 4, 2026-07-21, "a mock that pattern-matches a shell command cannot
|
|
346
|
+
// catch a shell syntax error in that string."
|
|
347
|
+
//
|
|
348
|
+
// readPrefsFile's exec is synchronous, N of them in a row is a deliberate choice HERE: this
|
|
349
|
+
// module is called only from the MCP stdio server, which serves one request at a time, so a
|
|
350
|
+
// blocking loop just makes that one request take longer, it never starves a concurrent
|
|
351
|
+
// caller. This is NOT safe to reuse verbatim in a process with concurrent HTTP callers (the
|
|
352
|
+
// web dashboard) — there, the equivalent read path was converted to async execFile, because a
|
|
353
|
+
// sync exec loop blocks Node's single event loop and stalls every OTHER in-flight request for
|
|
354
|
+
// the whole search's duration, not just the caller who asked for it. If this module ever gets
|
|
355
|
+
// imported into the dashboard server, that conversion needs to happen here too.
|
|
356
|
+
for (const file of listResult.files) {
|
|
357
|
+
if (totalMatches >= MAX_MATCHES) {
|
|
358
|
+
truncated = true;
|
|
359
|
+
break;
|
|
360
|
+
}
|
|
361
|
+
// readPrefsFile throws synchronously (assertSafePrefsName) rather than returning {error}
|
|
362
|
+
// for a filename that fails its shape check. Every name here comes from listPrefsFiles'
|
|
363
|
+
// own parser, which already only keeps .xml-suffixed names, so reachability is low. Still,
|
|
364
|
+
// one bad device-reported name must skip-and-report like any other unreadable file, not
|
|
365
|
+
// escape the loop and fail the ENTIRE search -- catch and treat exactly like {error}.
|
|
366
|
+
let readResult;
|
|
367
|
+
try {
|
|
368
|
+
readResult = await readPrefsFile(adbPath, file.name, targetUser);
|
|
369
|
+
}
|
|
370
|
+
catch (e) {
|
|
371
|
+
skipped.push(file.name);
|
|
372
|
+
continue;
|
|
373
|
+
}
|
|
374
|
+
if ("error" in readResult) {
|
|
375
|
+
skipped.push(file.name);
|
|
376
|
+
continue;
|
|
377
|
+
}
|
|
378
|
+
const parseResult = parsePrefsXml(readResult.xml);
|
|
379
|
+
if ("parseError" in parseResult) {
|
|
380
|
+
skipped.push(file.name);
|
|
381
|
+
continue;
|
|
382
|
+
}
|
|
383
|
+
const fileMatches = [];
|
|
384
|
+
for (const entry of parseResult.entries) {
|
|
385
|
+
if (totalMatches >= MAX_MATCHES) {
|
|
386
|
+
truncated = true;
|
|
387
|
+
break;
|
|
388
|
+
}
|
|
389
|
+
const keyMatch = entry.key.toLowerCase().includes(queryLower);
|
|
390
|
+
const valueStr = stringifyValue(entry.value);
|
|
391
|
+
const valueMatch = valueStr.toLowerCase().includes(queryLower);
|
|
392
|
+
if (keyMatch || valueMatch) {
|
|
393
|
+
fileMatches.push(entry);
|
|
394
|
+
totalMatches++;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
if (fileMatches.length > 0) {
|
|
398
|
+
results.push({ file: file.name, matches: fileMatches });
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
const result = { results, user: actualUser };
|
|
402
|
+
if (truncated)
|
|
403
|
+
result.truncated = true;
|
|
404
|
+
if (skipped.length > 0)
|
|
405
|
+
result.skipped = skipped;
|
|
406
|
+
return result;
|
|
407
|
+
}
|
|
408
|
+
function stringifyValue(v) {
|
|
409
|
+
if (typeof v === "string")
|
|
410
|
+
return v;
|
|
411
|
+
if (typeof v === "boolean" || typeof v === "number")
|
|
412
|
+
return String(v);
|
|
413
|
+
if (Array.isArray(v))
|
|
414
|
+
return v.join(", ");
|
|
415
|
+
return String(v);
|
|
416
|
+
}
|
|
@@ -13,6 +13,18 @@ export interface LogResult {
|
|
|
13
13
|
lines: string[];
|
|
14
14
|
source: LogSource;
|
|
15
15
|
}
|
|
16
|
+
/**
|
|
17
|
+
* One attached device as reported by the platform's device listing. serial is the
|
|
18
|
+
* stable id used to target a specific device (Android: `adb -s <serial>`); label is a
|
|
19
|
+
* human-readable name (device model) falling back to the serial; state is the raw
|
|
20
|
+
* connection state ("device", "offline", "unauthorized"). Only state "device" entries
|
|
21
|
+
* are selectable.
|
|
22
|
+
*/
|
|
23
|
+
export interface DeviceInfo {
|
|
24
|
+
serial: string;
|
|
25
|
+
label: string;
|
|
26
|
+
state: string;
|
|
27
|
+
}
|
|
16
28
|
export interface DeviceTransport {
|
|
17
29
|
/** Human-readable platform name (e.g. "android", "ios"). */
|
|
18
30
|
readonly platform: string;
|
|
@@ -39,6 +51,22 @@ export interface DeviceTransport {
|
|
|
39
51
|
* to resetState() when absent.
|
|
40
52
|
*/
|
|
41
53
|
dropForward?(): void;
|
|
54
|
+
/**
|
|
55
|
+
* Re-issue the adb forward for this process's pinned device, UNCONDITIONALLY --
|
|
56
|
+
* unlike ensureForward(), a cached "already forwarded" is not trusted. The forward
|
|
57
|
+
* this MCP process set up is host-global (keyed by local port only), and a SEPARATE
|
|
58
|
+
* process on the same host (the web dashboard) can repoint that same port to a
|
|
59
|
+
* different device at any time via its own selectDevice call. That process's repoint
|
|
60
|
+
* does not touch this process's `portForwarded` cache, so a plain ensureForward()
|
|
61
|
+
* would skip re-forwarding and this session would silently start reading the other
|
|
62
|
+
* process's device over its HTTP-based tools while its direct-adb tools (which honor
|
|
63
|
+
* process.env.ANDROID_SERIAL per-call, not the shared port) keep reading the correct
|
|
64
|
+
* one -- a split-brain within one MCP session. Call this immediately before every
|
|
65
|
+
* device HTTP read so the shared port is always pointed at OUR pinned serial first.
|
|
66
|
+
* Optional; platforms without a shared host-level forward may omit it, and callers
|
|
67
|
+
* fall back to ensureForward() when absent.
|
|
68
|
+
*/
|
|
69
|
+
reassertForward?(): boolean;
|
|
42
70
|
/** Whether forwarding has been established. */
|
|
43
71
|
isForwarded(): boolean;
|
|
44
72
|
/** Current auto-shutdown timeout in minutes. */
|
|
@@ -133,4 +161,44 @@ export interface DeviceTransport {
|
|
|
133
161
|
* @param timeoutMinutes Auto-shutdown timeout in minutes
|
|
134
162
|
*/
|
|
135
163
|
activateForUser?(userId: string, timeoutMinutes: number): void;
|
|
164
|
+
/**
|
|
165
|
+
* List the devices currently attached to the host. Android runs `adb devices -l`;
|
|
166
|
+
* iOS and test fakes may omit it (single-device or no listing support). Selection
|
|
167
|
+
* treats an absent listing as "cannot tell", not "no devices", so existing flows
|
|
168
|
+
* that fake adb without `devices -l` support stay a no-op.
|
|
169
|
+
*/
|
|
170
|
+
listDevices?(): DeviceInfo[] | null;
|
|
171
|
+
/**
|
|
172
|
+
* Pick which attached device every later adb call targets, for the whole session.
|
|
173
|
+
* Selection is transport-owned (not the enable body's job) because only the transport
|
|
174
|
+
* knows how targeting works on its platform: on Android this pins process.env.ANDROID_SERIAL
|
|
175
|
+
* once, and every adb call site inherits it, so no per-call-site plumbing is needed.
|
|
176
|
+
*
|
|
177
|
+
* @param serial An explicit device serial to target, or null to auto-select (keep a
|
|
178
|
+
* sticky prior pin if still attached, else the sole attached device).
|
|
179
|
+
* @returns ok:true with the pinned serial (null when nothing could be selected and the
|
|
180
|
+
* downstream forward path reports no-device on its own), or ok:false with a
|
|
181
|
+
* human-readable error plus the device list when the choice is ambiguous or the
|
|
182
|
+
* requested serial is not attached. switched is true when this pin differs from the
|
|
183
|
+
* session's prior device: a switch invalidates device-scoped session state, and the
|
|
184
|
+
* orchestrator owns the reset.
|
|
185
|
+
*/
|
|
186
|
+
selectDevice?(serial: string | null): {
|
|
187
|
+
ok: true;
|
|
188
|
+
serial: string | null;
|
|
189
|
+
switched?: boolean;
|
|
190
|
+
} | {
|
|
191
|
+
ok: false;
|
|
192
|
+
error: string;
|
|
193
|
+
devices: DeviceInfo[];
|
|
194
|
+
};
|
|
195
|
+
/**
|
|
196
|
+
* The device pinned by the last successful selectDevice, or null when none is pinned.
|
|
197
|
+
* The enable body and the web /health response surface this so a user can see which
|
|
198
|
+
* hardware the session is bound to. Optional; single-device platforms may omit it.
|
|
199
|
+
*/
|
|
200
|
+
getSelectedDevice?(): {
|
|
201
|
+
serial: string;
|
|
202
|
+
label: string;
|
|
203
|
+
} | null;
|
|
136
204
|
}
|
|
@@ -67,6 +67,19 @@ export declare class LogSession {
|
|
|
67
67
|
start(): boolean;
|
|
68
68
|
/** Stop the capture and drop the child. The ring buffer is preserved. */
|
|
69
69
|
stop(): void;
|
|
70
|
+
/**
|
|
71
|
+
* Stop the capture AND drop the retained ring, for when the underlying device
|
|
72
|
+
* actually changed (PR #94 multi-device switch), not just dropped transiently.
|
|
73
|
+
* stop() alone preserves the ring by design (a transient adb-server hiccup or
|
|
74
|
+
* device unplug/replug is the SAME device coming back, so its history is still
|
|
75
|
+
* valid and should survive) -- but a switch to DIFFERENT hardware means every
|
|
76
|
+
* retained frame belongs to the wrong device, and replaying them into a freshly
|
|
77
|
+
* opened /stream on the new device would show device A's logs mislabeled as
|
|
78
|
+
* device B's. The caller (handleEnable's switched branch) is responsible for
|
|
79
|
+
* calling armLogcat() / start() again afterward if a log tab is active; this
|
|
80
|
+
* method only tears down, matching stop()'s existing division of labor.
|
|
81
|
+
*/
|
|
82
|
+
restart(): void;
|
|
70
83
|
/**
|
|
71
84
|
* Install process-exit handlers (once) so the persistent `adb logcat` child is
|
|
72
85
|
* killed when the server process exits. Without this, the capture orphans when
|
package/dist/web/log-session.js
CHANGED
|
@@ -75,6 +75,22 @@ export class LogSession {
|
|
|
75
75
|
}
|
|
76
76
|
}
|
|
77
77
|
}
|
|
78
|
+
/**
|
|
79
|
+
* Stop the capture AND drop the retained ring, for when the underlying device
|
|
80
|
+
* actually changed (PR #94 multi-device switch), not just dropped transiently.
|
|
81
|
+
* stop() alone preserves the ring by design (a transient adb-server hiccup or
|
|
82
|
+
* device unplug/replug is the SAME device coming back, so its history is still
|
|
83
|
+
* valid and should survive) -- but a switch to DIFFERENT hardware means every
|
|
84
|
+
* retained frame belongs to the wrong device, and replaying them into a freshly
|
|
85
|
+
* opened /stream on the new device would show device A's logs mislabeled as
|
|
86
|
+
* device B's. The caller (handleEnable's switched branch) is responsible for
|
|
87
|
+
* calling armLogcat() / start() again afterward if a log tab is active; this
|
|
88
|
+
* method only tears down, matching stop()'s existing division of labor.
|
|
89
|
+
*/
|
|
90
|
+
restart() {
|
|
91
|
+
this.stop();
|
|
92
|
+
this.ring.length = 0;
|
|
93
|
+
}
|
|
78
94
|
/**
|
|
79
95
|
* Install process-exit handlers (once) so the persistent `adb logcat` child is
|
|
80
96
|
* killed when the server process exits. Without this, the capture orphans when
|