@slack/radar-mcp 1.10.0 → 1.12.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 +2 -2
- package/dist/mcp/index.js +75 -50
- package/dist/mcp/prefs-tools.d.ts +15 -0
- package/dist/mcp/prefs-tools.js +204 -0
- package/dist/mcp/session-enable.d.ts +18 -0
- package/dist/mcp/session-enable.js +131 -0
- package/dist/mcp/snapshot.js +6 -1
- package/dist/mcp/tools.js +65 -2
- package/dist/shared/android.d.ts +36 -1
- package/dist/shared/android.js +247 -13
- package/dist/shared/constants.d.ts +17 -2
- package/dist/shared/constants.js +22 -3
- package/dist/shared/db.d.ts +14 -0
- package/dist/shared/db.js +16 -5
- package/dist/shared/prefs.d.ts +78 -0
- package/dist/shared/prefs.js +416 -0
- package/dist/shared/stream.d.ts +23 -0
- package/dist/shared/stream.js +109 -16
- package/dist/shared/transport.d.ts +86 -0
- package/dist/web/log-session.d.ts +13 -0
- package/dist/web/log-session.js +16 -0
- package/dist/web/public/index.html +108 -3
- package/dist/web/public/next/app.js +58 -2
- package/dist/web/public/next/feed.js +261 -12
- package/dist/web/public/next/filter.js +200 -0
- package/dist/web/public/next/prefs.js +399 -0
- package/dist/web/public/next/registry.js +7 -6
- package/dist/web/public/next/store.js +201 -10
- package/dist/web/server.js +236 -21
- package/dist/web/spec.d.ts +7 -7
- package/dist/web/spec.js +12 -9
- package/package.json +1 -1
|
@@ -0,0 +1,78 @@
|
|
|
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
|
+
/**
|
|
15
|
+
* List SharedPreferences files for a user, with their sizes.
|
|
16
|
+
* Via `run-as ... ls -la shared_prefs/` and parse name+size.
|
|
17
|
+
* Returns null on run-as failure.
|
|
18
|
+
*/
|
|
19
|
+
export declare function listPrefsFiles(adbPath: string, user?: string): {
|
|
20
|
+
user: string;
|
|
21
|
+
files: {
|
|
22
|
+
name: string;
|
|
23
|
+
size: number;
|
|
24
|
+
}[];
|
|
25
|
+
} | null;
|
|
26
|
+
/**
|
|
27
|
+
* Read a SharedPreferences XML file from the device.
|
|
28
|
+
* Via `adb exec-out run-as ... cat shared_prefs/<name>`.
|
|
29
|
+
* Validates filename and user first. Caps read at 256KB (truncated: true if larger).
|
|
30
|
+
* Returns { xml: string, user: string, truncated?: boolean } on success or { error: string } on failure.
|
|
31
|
+
* Retries once after ~200ms if the first read fails (mid-write .bak swap).
|
|
32
|
+
*/
|
|
33
|
+
export declare function readPrefsFile(adbPath: string, name: string, user?: string): Promise<{
|
|
34
|
+
xml: string;
|
|
35
|
+
user: string;
|
|
36
|
+
truncated?: boolean;
|
|
37
|
+
} | {
|
|
38
|
+
error: string;
|
|
39
|
+
}>;
|
|
40
|
+
export type PrefsValue = string | boolean | number | string[];
|
|
41
|
+
export type PrefsType = "boolean" | "int" | "long" | "float" | "string" | "set";
|
|
42
|
+
export interface PrefsEntry {
|
|
43
|
+
key: string;
|
|
44
|
+
type: PrefsType;
|
|
45
|
+
value: PrefsValue;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Parse SharedPreferences XML into typed entries.
|
|
49
|
+
* Handles: boolean, int, long, float, string, set (with string children).
|
|
50
|
+
* Returns { entries: [...] } on success or { parseError: string } on failure.
|
|
51
|
+
* Handles: entity unescaping, self-closing and open-close forms, empty map, garbage input.
|
|
52
|
+
* Never throws.
|
|
53
|
+
*/
|
|
54
|
+
export declare function parsePrefsXml(xml: string): {
|
|
55
|
+
entries: PrefsEntry[];
|
|
56
|
+
} | {
|
|
57
|
+
parseError: string;
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* Search preferences across all files for a user.
|
|
61
|
+
* Case-insensitive substring search on key names and stringified values.
|
|
62
|
+
* Returns per-file match results, capped at 200 total matches across all files
|
|
63
|
+
* (truncated: true when the cap was hit, so a caller can tell "no more matches"
|
|
64
|
+
* apart from "matches exist beyond this page" — plain array truncation would lose
|
|
65
|
+
* that flag on JSON.stringify, since non-index array properties are not serialized).
|
|
66
|
+
* A file that fails to read (run-as denial, mid-write on both attempts) or fails to
|
|
67
|
+
* parse is skipped and named in `skipped`, so a caller can tell "no match in this file"
|
|
68
|
+
* apart from "this file could not be checked."
|
|
69
|
+
*/
|
|
70
|
+
export declare function searchPrefs(adbPath: string, query: string, user?: string): Promise<{
|
|
71
|
+
results: {
|
|
72
|
+
file: string;
|
|
73
|
+
matches: PrefsEntry[];
|
|
74
|
+
}[];
|
|
75
|
+
user: string;
|
|
76
|
+
truncated?: boolean;
|
|
77
|
+
skipped?: string[];
|
|
78
|
+
}>;
|
|
@@ -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
|
+
}
|
package/dist/shared/stream.d.ts
CHANGED
|
@@ -11,6 +11,20 @@ export interface ParsedSSE {
|
|
|
11
11
|
}
|
|
12
12
|
export declare const localNetworkBuffer: RadarEvent[];
|
|
13
13
|
export declare const localRtmBuffer: RadarEvent[];
|
|
14
|
+
/**
|
|
15
|
+
* Decide whether this reconnect attempt rebuilds the adb forward, perform the
|
|
16
|
+
* rebuild if so, and return the delay before the next connect. Does not call
|
|
17
|
+
* setTimeout itself so the decision is unit-testable without a live socket.
|
|
18
|
+
*
|
|
19
|
+
* Prefers dropForward() (drops only the cached forward flag) over resetState()
|
|
20
|
+
* so a rebuild does not wipe the detected user id mid-session: a full reset
|
|
21
|
+
* followed by a re-detect while the app process is down would rebind the
|
|
22
|
+
* session to user 0, losing a work-profile binding.
|
|
23
|
+
*
|
|
24
|
+
* @param t transport whose forward may be stale
|
|
25
|
+
* @param attempt 1-based failure count since the last successful connect
|
|
26
|
+
*/
|
|
27
|
+
export declare function planReconnect(t: DeviceTransport, attempt: number): number;
|
|
14
28
|
/** Set the reconnect hook. Called once after each successful reconnect. Pass null to clear it. */
|
|
15
29
|
export declare function setOnReconnect(fn: (() => void) | null): void;
|
|
16
30
|
export declare function noteStreamConnected(): void;
|
|
@@ -18,6 +32,15 @@ export declare function _resetReconnectStateForTest(): void;
|
|
|
18
32
|
export declare function isStreamConnected(): boolean;
|
|
19
33
|
export declare function clearLocalBuffers(): void;
|
|
20
34
|
export declare function getStreamConnection(): http.ClientRequest | null;
|
|
35
|
+
/**
|
|
36
|
+
* Deliberate teardown: destroy the live stream AND stop the reconnect loop.
|
|
37
|
+
* Cancelling the pending timer matters as much as the destroy — without it a
|
|
38
|
+
* disable (or an enable-restart) leaves a timer that resurrects the stream
|
|
39
|
+
* seconds later, refilling buffers the caller just cleared and churning adb
|
|
40
|
+
* forward rebuilds against a session the user turned off. The destroyed
|
|
41
|
+
* request's own async failure events are ignored by the ownership check in
|
|
42
|
+
* connectStream's handlers (they no longer own streamConnection).
|
|
43
|
+
*/
|
|
21
44
|
export declare function destroyStream(): void;
|
|
22
45
|
/**
|
|
23
46
|
* Push an event into the appropriate local buffer, enforcing MAX_LOCAL_BUFFER.
|