brickproof-adb 1.0.0 → 1.1.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/CHANGELOG.md +11 -0
- package/PRIVACY.md +31 -0
- package/README.md +6 -1
- package/package.json +2 -1
- package/src/body.js +73 -0
- package/src/cli.js +24 -19
- package/src/config.js +38 -3
- package/src/http.js +30 -18
- package/src/registry.js +2 -2
- package/src/server.js +2 -0
- package/src/session.js +106 -21
- package/src/watcher.js +188 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.1.0 — 2026-12-06
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
- **Remembered devices stay connected.** Every `reconnect_interval` seconds (new setting, default 60, `0` turns it off) the server runs one `adb devices` and reconnects the remembered devices and the `devices` of the settings that are missing or `offline`. A TV that restarted, lost power or dropped off the Wi-Fi comes back without a tool call, and the Android TV integration of Home Assistant picks it up on its next retry, without a reload. A device that asks to allow debugging is not asked again every minute: its address is paused until the device allows this computer, `adb_connect` or a restart, and `adb_devices` marks it. `adb_devices` also lists the addresses of the `devices` setting that are not connected. One line in stderr per reconnect and per pause; a failure only when a series of failures starts and ends.
|
|
7
|
+
- **Privacy policy.** `PRIVACY.md` says what the server keeps on your computer, the one thing it downloads and where screenshots and other device data go; the README and the Claude Desktop extension link to it.
|
|
8
|
+
|
|
9
|
+
### Changed
|
|
10
|
+
- **HTTP request body limit of 1 MiB.** A larger body gets 413 with a JSON-RPC error and `Connection: close`, and the client receives that answer rather than a reset connection. The body is still read only after the token check. No tool needs a larger body: files go by path.
|
|
11
|
+
- **`adb_disconnect` without `host`** keeps the remembered addresses, as before, and now also stops reconnecting them in the background until `adb_connect` to each or a restart. `adb_disconnect` of an address that comes from the `devices` setting, which cannot be forgotten, stops reconnecting it the same way.
|
|
12
|
+
- The start line and `brickproof-adb check` show `reconnect_interval`.
|
|
13
|
+
|
|
3
14
|
## 1.0.0 — 2026-10-21
|
|
4
15
|
|
|
5
16
|
Continues ha-adb-mcp 1.4.0: the same server and the same 18 tools, now a standalone npm package that runs on Windows, macOS and Linux, in Docker and as the Home Assistant app, with devices over USB and over the network.
|
package/PRIVACY.md
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# Privacy Policy
|
|
2
|
+
|
|
3
|
+
Last updated: 2026-12-06
|
|
4
|
+
|
|
5
|
+
brickproof-adb collects no data. It has no telemetry, no analytics and no account, and it sends nothing to its author or to anyone else. Everything it keeps stays on the computer that runs it and on your own devices.
|
|
6
|
+
|
|
7
|
+
## What it keeps on your computer
|
|
8
|
+
|
|
9
|
+
- **Settings:** `config.json` in the configuration directory, written only by you or by `brickproof-adb set`. The Claude Desktop extension and the Home Assistant app keep their settings in their own forms.
|
|
10
|
+
- **Remembered devices:** `devices.json` in the state directory: the network address of each device connected with `adb_connect`, with its model and serial number, so it can be connected again at start.
|
|
11
|
+
- **Snapshots:** in `<state_dir>/snapshots` (the `store` setting), one directory per device named by its model and serial number: `state.json` with the package changes made through `adb_app`, and the APK backups it makes before an uninstall or when asked.
|
|
12
|
+
- **Token:** `<state_dir>/token`, the secret of the HTTP server (`brickproof-adb serve` only).
|
|
13
|
+
- **adb:** `<state_dir>/platform-tools` when you download adb with `brickproof-adb get-adb`.
|
|
14
|
+
- **The adb key:** adb itself keeps the key your devices trust in `~/.android/adbkey` (in Docker `/data/.android/adbkey`).
|
|
15
|
+
- **Files you ask for:** `adb_pull` writes into the folders of `file_roots`, and nowhere else.
|
|
16
|
+
- **Temporary files:** screenshots and unpacked app bundles go through directories named `brickproof-*` in the system temp directory and are removed when the call ends.
|
|
17
|
+
|
|
18
|
+
[configuration.md](docs/configuration.md#where-settings-come-from) says where the configuration and state directories are on each system. Logs go to the standard error stream only, never to a file of their own; tool arguments appear there only with `log_requests` on, which is off by default.
|
|
19
|
+
|
|
20
|
+
## What it sends over the network
|
|
21
|
+
|
|
22
|
+
- **Your devices:** adb talks to the devices you connect, over USB or your local network. `adb_devices discover=true`, only when you ask, checks port 5555 of the addresses in your local network.
|
|
23
|
+
- **One download:** `brickproof-adb get-adb` downloads Google's Android SDK Platform-Tools from `dl.google.com`, after you accept Google's terms: https://developer.android.com/studio/releases/platform-tools. Google's terms and privacy policy apply to that download. Nothing else is fetched.
|
|
24
|
+
|
|
25
|
+
## What your AI client receives
|
|
26
|
+
|
|
27
|
+
Screenshots, lists of on-screen elements, log lines, file contents and every other tool result go only to the MCP client you connected brickproof-adb to, such as Claude Desktop or Claude Code. What that client does with them is governed by its own privacy policy.
|
|
28
|
+
|
|
29
|
+
## Contact
|
|
30
|
+
|
|
31
|
+
Questions about this policy: [GitHub issues](https://github.com/st412m/brickproof-adb/issues).
|
package/README.md
CHANGED
|
@@ -25,7 +25,7 @@ It runs on Windows, macOS and Linux, in Docker, and as a Home Assistant app; dev
|
|
|
25
25
|
>
|
|
26
26
|
> **You:** Yes.
|
|
27
27
|
>
|
|
28
|
-
> **Claude** calls `adb_connect host=192.0.2.50:5555`; you confirm the prompt to allow debugging on the TV screen, with "Always allow" checked. The address is remembered and connected
|
|
28
|
+
> **Claude** calls `adb_connect host=192.0.2.50:5555`; you confirm the prompt to allow debugging on the TV screen, with "Always allow" checked. The address is remembered, and the server keeps it connected: after the TV or the server restarts, it is back within a minute.
|
|
29
29
|
|
|
30
30
|
**Installing what you just downloaded.**
|
|
31
31
|
|
|
@@ -142,6 +142,11 @@ What protects your devices, and what does not: [docs/safety.md](docs/safety.md).
|
|
|
142
142
|
- Snapshots live on the machine that made them: a rollback has to run where the change was made.
|
|
143
143
|
- USB devices in Docker work only on a Linux host.
|
|
144
144
|
|
|
145
|
+
## Privacy Policy
|
|
146
|
+
|
|
147
|
+
brickproof-adb collects no data and has no telemetry: settings, remembered devices and snapshots stay on your computer, and tool results go only to the AI client you connected.
|
|
148
|
+
The one download, `brickproof-adb get-adb`, comes from Google. Details: [PRIVACY.md](PRIVACY.md).
|
|
149
|
+
|
|
145
150
|
## License
|
|
146
151
|
|
|
147
152
|
[MIT](LICENSE)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "brickproof-adb",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"mcpName": "io.github.st412m/brickproof-adb",
|
|
5
5
|
"description": "Lets an AI assistant look after your own Android devices over ADB without bricking them.",
|
|
6
6
|
"license": "MIT",
|
|
@@ -27,6 +27,7 @@
|
|
|
27
27
|
"src/",
|
|
28
28
|
"README.md",
|
|
29
29
|
"CHANGELOG.md",
|
|
30
|
+
"PRIVACY.md",
|
|
30
31
|
"LICENSE"
|
|
31
32
|
],
|
|
32
33
|
"engines": {
|
package/src/body.js
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Reads an HTTP request body up to a limit. Past the limit the rest is read and
|
|
3
|
+
// discarded within a budget, so the client can still receive the 413.
|
|
4
|
+
|
|
5
|
+
const MiB = 1024 * 1024;
|
|
6
|
+
const DRAIN_BYTES = 4 * MiB;
|
|
7
|
+
const DRAIN_MS = 5000;
|
|
8
|
+
|
|
9
|
+
// Resolves once to { ok: true, body }, { ok: false, destroy }, or { ok: false, aborted: true }.
|
|
10
|
+
function readBody(req, { limit, drainBytes = DRAIN_BYTES, drainMs = DRAIN_MS }) {
|
|
11
|
+
return new Promise(resolve => {
|
|
12
|
+
const declared = req.headers['content-length'];
|
|
13
|
+
if (typeof declared === 'string' && /^\d+$/.test(declared) && Number(declared) > limit + drainBytes) {
|
|
14
|
+
resolve({ ok: false, destroy: true });
|
|
15
|
+
req.pause();
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
let kept = [];
|
|
20
|
+
let total = 0;
|
|
21
|
+
let over = false;
|
|
22
|
+
let timer = null;
|
|
23
|
+
let done = false;
|
|
24
|
+
|
|
25
|
+
const finish = result => {
|
|
26
|
+
if (done) return;
|
|
27
|
+
done = true;
|
|
28
|
+
clearTimeout(timer);
|
|
29
|
+
req.off('data', onData);
|
|
30
|
+
req.off('end', onEnd);
|
|
31
|
+
req.off('error', onAbort);
|
|
32
|
+
req.off('aborted', onAbort);
|
|
33
|
+
resolve(result);
|
|
34
|
+
if (result.destroy) req.pause();
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
const onData = chunk => {
|
|
38
|
+
total += chunk.length;
|
|
39
|
+
if (!over) {
|
|
40
|
+
if (total <= limit) {
|
|
41
|
+
kept.push(chunk);
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
// Over the limit: drop what was kept and drain within the budget.
|
|
45
|
+
kept = [];
|
|
46
|
+
over = true;
|
|
47
|
+
timer = setTimeout(() => finish({ ok: false, destroy: true }), drainMs);
|
|
48
|
+
}
|
|
49
|
+
if (total - limit > drainBytes) finish({ ok: false, destroy: true });
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const onEnd = () => {
|
|
53
|
+
finish(over ? { ok: false, destroy: false } : { ok: true, body: Buffer.concat(kept) });
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const onAbort = () => finish({ ok: false, aborted: true });
|
|
57
|
+
|
|
58
|
+
req.on('data', onData);
|
|
59
|
+
req.on('end', onEnd);
|
|
60
|
+
req.on('error', onAbort);
|
|
61
|
+
req.on('aborted', onAbort);
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Sends the rejection with Connection: close; optionally destroys the socket once it is written.
|
|
66
|
+
function sendTooLarge(req, res, status, headers, payload, destroy) {
|
|
67
|
+
res.writeHead(status, { ...headers, 'Connection': 'close', 'Content-Length': Buffer.byteLength(payload) });
|
|
68
|
+
res.end(payload, () => {
|
|
69
|
+
if (destroy) req.socket.destroy();
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
module.exports = { MiB, DRAIN_BYTES, DRAIN_MS, readBody, sendTooLarge };
|
package/src/cli.js
CHANGED
|
@@ -49,26 +49,25 @@ function initServer(loaded) {
|
|
|
49
49
|
return { S, adb };
|
|
50
50
|
}
|
|
51
51
|
|
|
52
|
-
// What runs
|
|
52
|
+
// What runs once either transport serves: stale temp dirs from a killed
|
|
53
53
|
// process are removed, the devices of the settings and the remembered ones
|
|
54
54
|
// are connected in the background (a failure is a line in stderr, not a start
|
|
55
|
-
// failure)
|
|
55
|
+
// failure; with the watcher, one left unauthorized is paused), and after that
|
|
56
|
+
// the watcher keeps them connected every reconnect_interval seconds (none when
|
|
57
|
+
// it is 0). Returns the watcher, or null.
|
|
56
58
|
function startBackground(s) {
|
|
57
59
|
const A = require('./adb');
|
|
58
60
|
for (const dir of A.sweepTempDirs()) say(`removed a stale temporary directory: ${dir}`);
|
|
59
|
-
const
|
|
60
|
-
const
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
})();
|
|
61
|
+
const W = require('./watcher');
|
|
62
|
+
const watcher = W.watcherFor(s);
|
|
63
|
+
W.connectAtStart({ pauseUnauthorized: watcher !== null })
|
|
64
|
+
.catch(e => say(`connecting at start failed: ${e.message}`))
|
|
65
|
+
.then(() => { if (watcher) watcher.start(); });
|
|
66
|
+
return watcher;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function intervalText(s) {
|
|
70
|
+
return s.reconnect_interval ? `${s.reconnect_interval} s` : '0 (off)';
|
|
72
71
|
}
|
|
73
72
|
|
|
74
73
|
function rootsText(s, src) {
|
|
@@ -84,7 +83,7 @@ function startWarnings(loaded) {
|
|
|
84
83
|
function settingsLine(loaded, adb) {
|
|
85
84
|
const s = loaded.settings, src = loaded.sources;
|
|
86
85
|
return `allow_shell ${s.allow_shell ? 'ON' : 'off'}, allow_uninstall ${s.allow_uninstall ? 'ON' : 'off'}, ` +
|
|
87
|
-
`file roots ${rootsText(s, src)}, store ${s.store}, ` +
|
|
86
|
+
`file roots ${rootsText(s, src)}, store ${s.store}, reconnect_interval ${intervalText(s)}, ` +
|
|
88
87
|
`adb ${adb.chosen ? `${adb.path} (${adb.source}${adb.chosen.found ? '' : ', missing'})` : 'not found'}`;
|
|
89
88
|
}
|
|
90
89
|
|
|
@@ -154,9 +153,10 @@ async function serveCommand(rest) {
|
|
|
154
153
|
'brickproof-adb: shown once; `brickproof-adb token` shows it again');
|
|
155
154
|
}
|
|
156
155
|
process.stderr.write(lines.join('\n') + '\n');
|
|
157
|
-
startBackground(s);
|
|
156
|
+
const watcher = startBackground(s);
|
|
158
157
|
|
|
159
158
|
const stop = () => {
|
|
159
|
+
if (watcher) watcher.stop();
|
|
160
160
|
server.close();
|
|
161
161
|
process.exit(0);
|
|
162
162
|
};
|
|
@@ -184,8 +184,12 @@ async function stdioCommand(args) {
|
|
|
184
184
|
const { serveStdio } = require('./stdio');
|
|
185
185
|
const { closed } = serveStdio();
|
|
186
186
|
process.stderr.write([`brickproof-adb ${VERSION} on stdio, ${settingsLine(loaded, adb)}`, ...startWarnings(loaded)].join('\n') + '\n');
|
|
187
|
-
|
|
188
|
-
|
|
187
|
+
// The watcher's timer is unref()'d: a signal ends the process as before.
|
|
188
|
+
const watcher = startBackground(s);
|
|
189
|
+
closed.then(() => {
|
|
190
|
+
if (watcher) watcher.stop();
|
|
191
|
+
process.exit(0);
|
|
192
|
+
});
|
|
189
193
|
return null;
|
|
190
194
|
}
|
|
191
195
|
|
|
@@ -395,6 +399,7 @@ async function checkCommand(rest) {
|
|
|
395
399
|
known.configure({ stateDir: s.state_dir });
|
|
396
400
|
const remembered = known.readKnown();
|
|
397
401
|
out.push(`devices connected at start: ${s.devices.length ? s.devices.join(', ') : 'none'} (settings), ${remembered.length ? remembered.join(', ') : 'none'} (remembered)`);
|
|
402
|
+
out.push(`reconnect_interval: ${intervalText(s)} (${src.reconnect_interval})${s.reconnect_interval ? ' — those devices are kept connected' : ' — connected at start only'}`);
|
|
398
403
|
out.push(`scan_subnets: ${s.scan_subnets.length ? s.scan_subnets.join(', ') : 'none (the private /24 networks of this computer)'}`);
|
|
399
404
|
out.push(`serve: ${s.host}:${s.port}`);
|
|
400
405
|
|
package/src/config.js
CHANGED
|
@@ -33,16 +33,18 @@ const DEFAULTS = {
|
|
|
33
33
|
devices: [],
|
|
34
34
|
scan_subnets: [],
|
|
35
35
|
adb_path: 'adb',
|
|
36
|
+
reconnect_interval: 60,
|
|
36
37
|
};
|
|
37
38
|
|
|
38
39
|
const KEYS = new Set(['$comment', 'port', 'host', 'allowed_hosts', 'log_requests', 'allow_shell', 'allow_uninstall',
|
|
39
|
-
'devices', 'file_roots', 'scan_subnets', 'store', 'state_dir', 'adb_path']);
|
|
40
|
+
'devices', 'file_roots', 'scan_subnets', 'store', 'state_dir', 'adb_path', 'reconnect_interval']);
|
|
40
41
|
|
|
41
42
|
// The environment variable of each key that has one.
|
|
42
43
|
const ENV_OF = {
|
|
43
44
|
log_requests: 'BRICKPROOF_LOG_REQUESTS', allow_shell: 'BRICKPROOF_ALLOW_SHELL', allow_uninstall: 'BRICKPROOF_ALLOW_UNINSTALL',
|
|
44
45
|
devices: 'BRICKPROOF_DEVICES', file_roots: 'BRICKPROOF_FILE_ROOTS', scan_subnets: 'BRICKPROOF_SCAN_SUBNETS',
|
|
45
46
|
store: 'BRICKPROOF_STORE', state_dir: 'BRICKPROOF_STATE_DIR', adb_path: 'BRICKPROOF_ADB',
|
|
47
|
+
reconnect_interval: 'BRICKPROOF_RECONNECT_INTERVAL',
|
|
46
48
|
};
|
|
47
49
|
|
|
48
50
|
class ConfigError extends Error {
|
|
@@ -64,6 +66,20 @@ function isPort(n) {
|
|
|
64
66
|
return Number.isInteger(n) && n >= 0 && n <= 65535;
|
|
65
67
|
}
|
|
66
68
|
|
|
69
|
+
// reconnect_interval: seconds between two rounds of the watcher; 0 turns it off.
|
|
70
|
+
const RECONNECT_MIN = 15;
|
|
71
|
+
const RECONNECT_MAX = 3600;
|
|
72
|
+
const RECONNECT_RULE = `0 (off) or an integer ${RECONNECT_MIN}-${RECONNECT_MAX} (seconds)`;
|
|
73
|
+
|
|
74
|
+
function isReconnectInterval(n) {
|
|
75
|
+
return n === 0 || (Number.isInteger(n) && n >= RECONNECT_MIN && n <= RECONNECT_MAX);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// A reconnect_interval given as text (environment, `set`): a number or NaN.
|
|
79
|
+
function reconnectOf(text) {
|
|
80
|
+
return /^\s*\d+\s*$/.test(text) ? Number(text) : NaN;
|
|
81
|
+
}
|
|
82
|
+
|
|
67
83
|
// Path functions of the given platform, so the directory rules can be tested
|
|
68
84
|
// for every operating system on any of them.
|
|
69
85
|
function pathFor(platform) {
|
|
@@ -288,6 +304,8 @@ function parseConfig(raw, file) {
|
|
|
288
304
|
if (typeof raw[k] !== 'string' || !path.isAbsolute(raw[k])) problems.push(`"${k}" must be an absolute path`);
|
|
289
305
|
}
|
|
290
306
|
if (raw.port !== undefined && !isPort(raw.port)) problems.push('"port" must be an integer 0-65535');
|
|
307
|
+
if (raw.reconnect_interval !== undefined && !isReconnectInterval(raw.reconnect_interval))
|
|
308
|
+
problems.push(`"reconnect_interval" must be ${RECONNECT_RULE}`);
|
|
291
309
|
if (raw.host !== undefined && (typeof raw.host !== 'string' || !raw.host)) problems.push('"host" must be a non-empty string');
|
|
292
310
|
for (const k of ['log_requests', 'allow_shell', 'allow_uninstall']) {
|
|
293
311
|
if (raw[k] !== undefined && typeof raw[k] !== 'boolean') problems.push(`"${k}" must be true or false`);
|
|
@@ -361,6 +379,16 @@ function envBool(env, name) {
|
|
|
361
379
|
throw new ConfigError(`env ${name} must be true or false (or 1 / 0), got ${JSON.stringify(v.slice(0, 40))}`);
|
|
362
380
|
}
|
|
363
381
|
|
|
382
|
+
// BRICKPROOF_RECONNECT_INTERVAL: 0 or 15-3600, anything else is an error.
|
|
383
|
+
function envReconnect(env) {
|
|
384
|
+
const v = envValue(env, ENV_OF.reconnect_interval);
|
|
385
|
+
if (v === undefined) return undefined;
|
|
386
|
+
const n = reconnectOf(v);
|
|
387
|
+
if (!isReconnectInterval(n))
|
|
388
|
+
throw new ConfigError(`env ${ENV_OF.reconnect_interval} must be ${RECONNECT_RULE}, got ${JSON.stringify(v.slice(0, 40))}`);
|
|
389
|
+
return n;
|
|
390
|
+
}
|
|
391
|
+
|
|
364
392
|
/** BRICKPROOF_FILE_ROOTS: absolute paths separated by path.delimiter; empty items dropped. */
|
|
365
393
|
function splitRoots(value, delimiter = path.delimiter) {
|
|
366
394
|
return String(value).split(delimiter).map(s => s.trim()).filter(Boolean);
|
|
@@ -404,6 +432,8 @@ function loadConfig({ env = process.env, cwd = process.cwd(), platform = process
|
|
|
404
432
|
pick(key, [envBool(env, ENV_OF[key]), `env ${ENV_OF[key]}`], [file[key], fileSrc], [DEFAULTS[key], 'default']);
|
|
405
433
|
|
|
406
434
|
pick('devices', [fromEnv('BRICKPROOF_DEVICES', splitDevices), 'env BRICKPROOF_DEVICES'], [file.devices, fileSrc], [DEFAULTS.devices, 'default']);
|
|
435
|
+
pick('reconnect_interval', [envReconnect(env), `env ${ENV_OF.reconnect_interval}`], [file.reconnect_interval, fileSrc],
|
|
436
|
+
[DEFAULTS.reconnect_interval, 'default']);
|
|
407
437
|
|
|
408
438
|
const envSubnets = fromEnv('BRICKPROOF_SCAN_SUBNETS', splitDevices);
|
|
409
439
|
if (envSubnets) {
|
|
@@ -510,7 +540,7 @@ function settingHints(loaded) {
|
|
|
510
540
|
// ---------------------------------------------------------------- set command
|
|
511
541
|
|
|
512
542
|
const SETTABLE = ['port', 'host', 'allowed_hosts', 'log_requests', 'allow_shell', 'allow_uninstall', 'devices', 'file_roots',
|
|
513
|
-
'scan_subnets', 'store', 'state_dir', 'adb_path'];
|
|
543
|
+
'scan_subnets', 'store', 'state_dir', 'adb_path', 'reconnect_interval'];
|
|
514
544
|
const LISTS = new Set(['allowed_hosts', 'devices', 'file_roots', 'scan_subnets']);
|
|
515
545
|
const BOOLS = new Set(['log_requests', 'allow_shell', 'allow_uninstall']);
|
|
516
546
|
|
|
@@ -533,6 +563,11 @@ function settingValue(key, words, cwd = process.cwd()) {
|
|
|
533
563
|
if (!/^\d+$/.test(words[0])) throw new ConfigError('port must be an integer 0-65535');
|
|
534
564
|
return Number(words[0]);
|
|
535
565
|
}
|
|
566
|
+
if (key === 'reconnect_interval') {
|
|
567
|
+
const n = reconnectOf(words[0]);
|
|
568
|
+
if (!isReconnectInterval(n)) throw new ConfigError(`reconnect_interval must be ${RECONNECT_RULE}`);
|
|
569
|
+
return n;
|
|
570
|
+
}
|
|
536
571
|
if (key === 'store' || key === 'state_dir') return path.resolve(cwd, words[0]);
|
|
537
572
|
if (key === 'adb_path') return /[\\/]/.test(words[0]) ? path.resolve(cwd, words[0]) : words[0];
|
|
538
573
|
return words[0];
|
|
@@ -590,7 +625,7 @@ function ensureStateDir(dir) {
|
|
|
590
625
|
}
|
|
591
626
|
|
|
592
627
|
module.exports = {
|
|
593
|
-
DEFAULTS, ConfigError, APP_DIR, KEYS, ENV_OF, SETTABLE,
|
|
628
|
+
DEFAULTS, ConfigError, APP_DIR, KEYS, ENV_OF, SETTABLE, RECONNECT_MIN, RECONNECT_MAX,
|
|
594
629
|
platformDirs, downloadsDir, findDownloads, REGISTRY_TIMEOUT_MS, parseShellFolders, expandWindowsEnv, readShellFolders, runPowerShell, runPowerShellResult, parseConfig, configCandidates, loadConfig, ensureStateDir, splitRoots, splitDevices, envBool,
|
|
595
630
|
parseSubnet, ipToInt, intToIp, isPrivateIp,
|
|
596
631
|
settingAction, settingHints, settingValue, writeSetting,
|
package/src/http.js
CHANGED
|
@@ -16,13 +16,20 @@
|
|
|
16
16
|
* is not localhost, nor a name in allowed_hosts, is refused with 403 (DNS
|
|
17
17
|
* rebinding). On any other address there are no Host/Origin checks and the
|
|
18
18
|
* token alone protects the server.
|
|
19
|
+
*
|
|
20
|
+
* The body is read only after both checks passed, up to MAX_BODY_BYTES; a
|
|
21
|
+
* larger body gets 413 with Connection: close (body.js).
|
|
19
22
|
*/
|
|
20
23
|
|
|
21
24
|
const crypto = require('crypto');
|
|
22
25
|
const http = require('http');
|
|
23
26
|
const S = require('./server');
|
|
27
|
+
const B = require('./body');
|
|
24
28
|
|
|
25
29
|
const DEFAULT_HOST = '127.0.0.1';
|
|
30
|
+
// Request body limit of /mcp; a larger body gets 413. No tool needs more:
|
|
31
|
+
// files go by path.
|
|
32
|
+
const MAX_BODY_BYTES = 1024 * 1024;
|
|
26
33
|
const LOCAL_BINDS = new Set(['127.0.0.1', 'localhost', '::1', '[::1]']);
|
|
27
34
|
// Hostnames accepted in Host and Origin on a localhost bind, port-agnostic.
|
|
28
35
|
const LOCAL_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'];
|
|
@@ -180,8 +187,8 @@ function acceptsMcp(header) {
|
|
|
180
187
|
.some(type => ACCEPTED_MEDIA.has(type));
|
|
181
188
|
}
|
|
182
189
|
|
|
183
|
-
// /mcp, past the auth front.
|
|
184
|
-
function transport(req, res) {
|
|
190
|
+
// /mcp, past the auth front. onTooLarge runs before a 413 is sent.
|
|
191
|
+
async function transport(req, res, { onTooLarge }) {
|
|
185
192
|
res.setHeader('Access-Control-Allow-Origin', '*');
|
|
186
193
|
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, DELETE');
|
|
187
194
|
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Accept, mcp-session-id, mcp-protocol-version');
|
|
@@ -198,23 +205,26 @@ function transport(req, res) {
|
|
|
198
205
|
return;
|
|
199
206
|
}
|
|
200
207
|
|
|
201
|
-
const
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
208
|
+
const r = await B.readBody(req, { limit: MAX_BODY_BYTES });
|
|
209
|
+
if (r.aborted) return;
|
|
210
|
+
if (!r.ok) {
|
|
211
|
+
onTooLarge();
|
|
212
|
+
B.sendTooLarge(req, res, 413, { 'Content-Type': 'application/json' }, JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32600, message: `Request body too large (limit ${MAX_BODY_BYTES} bytes).` } }), r.destroy);
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
await answer(req, res, r.body);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// An unexpected exception answers 500; the process keeps serving.
|
|
219
|
+
function internalError(res, e) {
|
|
220
|
+
process.stderr.write(`request failed: ${e && e.stack || e}\n`);
|
|
221
|
+
if (!res.headersSent) res.writeHead(500, { 'Content-Type': 'application/json' });
|
|
222
|
+
res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32603, message: 'Internal error' } }));
|
|
213
223
|
}
|
|
214
224
|
|
|
215
|
-
async function answer(req, res,
|
|
225
|
+
async function answer(req, res, raw) {
|
|
216
226
|
let body;
|
|
217
|
-
try { body = JSON.parse(
|
|
227
|
+
try { body = JSON.parse(raw.toString('utf8')); }
|
|
218
228
|
catch { res.writeHead(400); res.end('Bad JSON'); return; }
|
|
219
229
|
|
|
220
230
|
const versionError = protocolHeaderError(req.rawHeaders, body);
|
|
@@ -284,7 +294,9 @@ function createHttpHandler({ token, host = DEFAULT_HOST, allowedHosts = [], logR
|
|
|
284
294
|
const o = originRefusal(req.headers.origin, allowed);
|
|
285
295
|
if (o) { note = '(Origin not local)'; log(`brickproof-adb: http ${req.method} 403 (Origin not local)`); return forbidden(res, o); }
|
|
286
296
|
}
|
|
287
|
-
transport(req, res
|
|
297
|
+
transport(req, res, {
|
|
298
|
+
onTooLarge: () => { note = '(too large)'; log(`brickproof-adb: http ${req.method} 413 (body too large)`); },
|
|
299
|
+
}).catch(e => internalError(res, e));
|
|
288
300
|
};
|
|
289
301
|
listener.localGuards = localGuards;
|
|
290
302
|
return listener;
|
|
@@ -307,7 +319,7 @@ function startHttp({ port, host = DEFAULT_HOST, token, allowedHosts = [], logReq
|
|
|
307
319
|
}
|
|
308
320
|
|
|
309
321
|
module.exports = {
|
|
310
|
-
DEFAULT_HOST, MIN_TOKEN_LENGTH, TokenError,
|
|
322
|
+
DEFAULT_HOST, MIN_TOKEN_LENGTH, MAX_BODY_BYTES, TokenError,
|
|
311
323
|
isLocalBind, validateToken, sameSecret, authorize, allowedHostnames, hostRefusal, originRefusal,
|
|
312
324
|
maskPath, protocolHeaderError, acceptsMcp,
|
|
313
325
|
createHttpHandler, startHttp, bindNote,
|
package/src/registry.js
CHANGED
|
@@ -41,7 +41,7 @@ const TOOLS = [
|
|
|
41
41
|
{
|
|
42
42
|
name: 'adb_devices',
|
|
43
43
|
...meta('List devices', { readOnly: true, destructive: false, idempotent: true, openWorld: false }),
|
|
44
|
-
description: 'List connected Android devices with serial, state and description (adb devices -l), and remembered addresses that are not connected now. Start here: the other tools take serial from this list. If the device the user means is not in the list, call again with discover=true: it searches the local network for devices to connect (mDNS and port 5555), any time and as often as needed, and connects none of them.',
|
|
44
|
+
description: 'List connected Android devices with serial, state and description (adb devices -l), and remembered or configured addresses that are not connected now. Start here: the other tools take serial from this list. If the device the user means is not in the list, call again with discover=true: it searches the local network for devices to connect (mDNS and port 5555), any time and as often as needed, and connects none of them.',
|
|
45
45
|
inputSchema: { type: 'object', properties: {
|
|
46
46
|
discover: { type: 'boolean', description: 'Search the local network (about 10 s) for devices with network or Wireless debugging on; returns candidates and the next step for each. Default false.' }
|
|
47
47
|
} }
|
|
@@ -66,7 +66,7 @@ const TOOLS = [
|
|
|
66
66
|
{
|
|
67
67
|
name: 'adb_disconnect',
|
|
68
68
|
...meta('Disconnect device', { readOnly: false, destructive: false, idempotent: true, openWorld: false }),
|
|
69
|
-
description: 'Disconnect a network ADB device, the reverse of adb_connect. Omit host to disconnect every network device. adb_disconnect then adb_connect recovers a device that adb_devices lists as offline. With host the address is also forgotten and
|
|
69
|
+
description: 'Disconnect a network ADB device, the reverse of adb_connect. Omit host to disconnect every network device; none is reconnected in the background until adb_connect or a server restart. adb_disconnect then adb_connect recovers a device that adb_devices lists as offline. With host the address is also forgotten and no longer reconnected.',
|
|
70
70
|
inputSchema: { type: 'object', properties: {
|
|
71
71
|
host: { type: 'string', description: 'ip:port as listed by adb_devices. Omit to disconnect all network devices.' }
|
|
72
72
|
} }
|
package/src/server.js
CHANGED
|
@@ -28,6 +28,8 @@ function init(settings = {}, { log, hints = {}, adbPath } = {}) {
|
|
|
28
28
|
shellHint: hints.allow_shell,
|
|
29
29
|
stateDir: settings.state_dir || null,
|
|
30
30
|
scanSubnets: settings.scan_subnets || [],
|
|
31
|
+
devices: settings.devices || [],
|
|
32
|
+
reconnectInterval: settings.reconnect_interval || 0,
|
|
31
33
|
});
|
|
32
34
|
require('./files.js').configure({ fileRoots: settings.file_roots || [], rootsHint: hints.file_roots });
|
|
33
35
|
require('./apps.js').configure({
|
package/src/session.js
CHANGED
|
@@ -5,8 +5,14 @@
|
|
|
5
5
|
*
|
|
6
6
|
* A successful adb_connect to ip:port remembers the address, adb_disconnect
|
|
7
7
|
* with an address forgets it, and the server connects the remembered ones at
|
|
8
|
-
* start
|
|
9
|
-
*
|
|
8
|
+
* start; with reconnect_interval above 0 the watcher (watcher.js) keeps them
|
|
9
|
+
* and the devices of the settings connected. mDNS names and the random ports
|
|
10
|
+
* of Wireless debugging are not remembered: adb itself reconnects paired
|
|
11
|
+
* devices over mDNS.
|
|
12
|
+
*
|
|
13
|
+
* The pauses of the watcher live here, in memory: the watcher does not
|
|
14
|
+
* connect a paused address. adb_connect ends a pause, the watcher ends it once
|
|
15
|
+
* adb lists the address as device again by any means, a restart ends them all.
|
|
10
16
|
*/
|
|
11
17
|
|
|
12
18
|
const fs = require('fs');
|
|
@@ -17,12 +23,23 @@ let ALLOW_SHELL = false;
|
|
|
17
23
|
let SHELL_HINT = 'run `brickproof-adb set allow_shell on` and restart the server';
|
|
18
24
|
let STATE_DIR = null;
|
|
19
25
|
let SCAN_SUBNETS = [];
|
|
26
|
+
let DEVICES = [];
|
|
27
|
+
let KEEP_CONNECTED = false;
|
|
20
28
|
|
|
21
|
-
function configure({ allowShell = false, shellHint, stateDir = null, scanSubnets = [] } = {}) {
|
|
29
|
+
function configure({ allowShell = false, shellHint, stateDir = null, scanSubnets = [], devices = [], reconnectInterval = 0 } = {}) {
|
|
22
30
|
ALLOW_SHELL = allowShell === true;
|
|
23
31
|
if (shellHint) SHELL_HINT = shellHint;
|
|
24
32
|
STATE_DIR = stateDir;
|
|
25
33
|
SCAN_SUBNETS = scanSubnets.slice();
|
|
34
|
+
DEVICES = [...new Set(devices.map(hostPort))];
|
|
35
|
+
KEEP_CONNECTED = reconnectInterval > 0;
|
|
36
|
+
PAUSED.clear();
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// The address adb connects for a host: ip means ip:5555.
|
|
40
|
+
function hostPort(host) {
|
|
41
|
+
const h = String(host).trim();
|
|
42
|
+
return h.includes(':') ? h : `${h}:5555`;
|
|
26
43
|
}
|
|
27
44
|
|
|
28
45
|
// ------------------------------------------------------- remembered devices
|
|
@@ -108,6 +125,42 @@ async function forget(addr) {
|
|
|
108
125
|
return true;
|
|
109
126
|
}
|
|
110
127
|
|
|
128
|
+
/** What the watcher keeps connected: the devices setting and the remembered addresses, each once. */
|
|
129
|
+
function watched() {
|
|
130
|
+
return [...new Set([...DEVICES, ...readKnown()])];
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// ------------------------------------------------------------------ pauses
|
|
134
|
+
// address -> { reason: 'unauthorized' | 'adb_disconnect', at: pauseMark() when set }
|
|
135
|
+
|
|
136
|
+
const PAUSED = new Map();
|
|
137
|
+
let PAUSE_CLOCK = 0;
|
|
138
|
+
|
|
139
|
+
/** A point in the order of pauses: a pause set later has a greater mark. */
|
|
140
|
+
function pauseMark() {
|
|
141
|
+
return ++PAUSE_CLOCK;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function pause(addr, reason) {
|
|
145
|
+
PAUSED.set(addr, { reason, at: pauseMark() });
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function resume(addr) {
|
|
149
|
+
PAUSED.delete(addr);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Why the watcher leaves an address alone, or null. */
|
|
153
|
+
function pausedReason(addr) {
|
|
154
|
+
const p = PAUSED.get(addr);
|
|
155
|
+
return p ? p.reason : null;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Whether the address was paused before the mark (so a listing taken after the mark may end the pause). */
|
|
159
|
+
function pausedBefore(addr, mark) {
|
|
160
|
+
const p = PAUSED.get(addr);
|
|
161
|
+
return p !== undefined && p.at < mark;
|
|
162
|
+
}
|
|
163
|
+
|
|
111
164
|
// The device key behind a connected address; null when it cannot be read or
|
|
112
165
|
// the device has no usable serial number.
|
|
113
166
|
async function keyOf(addr) {
|
|
@@ -126,8 +179,9 @@ async function devices(args = {}) {
|
|
|
126
179
|
}
|
|
127
180
|
const out = (await adb(['devices', '-l'])).toString();
|
|
128
181
|
const connected = out.split(/\r?\n/).slice(1).map(l => l.trim().split(/\s+/)[0]).filter(Boolean);
|
|
129
|
-
const
|
|
130
|
-
|
|
182
|
+
const tags = d => (DEVICES.includes(d) ? ' (devices setting)' : '') + (pausedReason(d) ? ` (paused: ${pausedReason(d)})` : '');
|
|
183
|
+
const idle = [...new Set([...readKnown(), ...DEVICES])].filter(d => !connected.includes(d)).map(d => d + tags(d));
|
|
184
|
+
let extra = idle.length ? `\nKnown, not connected now: ${idle.join(', ')} (adb_connect reconnects; off or a new address: adb_devices discover=true)` : '';
|
|
131
185
|
if (!connected.length)
|
|
132
186
|
extra += '\nNo device is connected. To find one on the network: adb_devices discover=true. A phone on a USB cable shows up here by itself once USB debugging is allowed on it.';
|
|
133
187
|
return text((await markSameDevice(out.trim()) || 'No devices') + extra);
|
|
@@ -165,17 +219,28 @@ async function markSameDevice(listing) {
|
|
|
165
219
|
return lines.join('\n');
|
|
166
220
|
}
|
|
167
221
|
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
222
|
+
/**
|
|
223
|
+
* One `adb devices`: serial -> state (device, unauthorized, offline,
|
|
224
|
+
* authorizing, connecting).
|
|
225
|
+
*/
|
|
226
|
+
async function deviceStates() {
|
|
171
227
|
const out = (await adb(['devices'], { timeout: 10000 })).toString();
|
|
228
|
+
const states = new Map();
|
|
172
229
|
for (const line of out.split(/\r?\n/).slice(1)) {
|
|
173
230
|
const [s, state] = line.trim().split(/\s+/);
|
|
174
|
-
if (s
|
|
231
|
+
if (s) states.set(s, state || null);
|
|
175
232
|
}
|
|
176
|
-
return
|
|
233
|
+
return states;
|
|
177
234
|
}
|
|
178
235
|
|
|
236
|
+
// The state `adb devices` lists for a serial, or null when it is not listed.
|
|
237
|
+
async function stateOf(serial) {
|
|
238
|
+
return (await deviceStates()).get(serial) || null;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// adb reports a failed connect on stdout with exit code 0.
|
|
242
|
+
const CONNECT_FAILED_RE = /failed to connect|unable to connect|cannot connect/i;
|
|
243
|
+
|
|
179
244
|
const SETTLING = new Set([null, 'authorizing', 'connecting']);
|
|
180
245
|
// How the state after adb connect is watched; replaced in tests.
|
|
181
246
|
// `unauthorized` settles too: a device that trusts this computer may say it
|
|
@@ -183,10 +248,9 @@ const SETTLING = new Set([null, 'authorizing', 'connecting']);
|
|
|
183
248
|
const CONNECT_TIMING = { pollMs: 700, settlingPolls: 2, unauthorizedMs: 5000 };
|
|
184
249
|
|
|
185
250
|
async function connect(args) {
|
|
186
|
-
const host = args.host
|
|
251
|
+
const host = hostPort(args.host);
|
|
187
252
|
const out = (await adb(['connect', host], { timeout: 10000 })).toString().trim();
|
|
188
|
-
|
|
189
|
-
if (/failed to connect|unable to connect|cannot connect/i.test(out))
|
|
253
|
+
if (CONNECT_FAILED_RE.test(out))
|
|
190
254
|
throw new Error(`${out}. Check the device is awake and the port is current (wireless-debug ports change after device reboot).`);
|
|
191
255
|
// "connected to" is printed also when the device has not allowed this
|
|
192
256
|
// computer ("failed to authenticate"): what counts is the state adb lists.
|
|
@@ -201,18 +265,24 @@ async function connect(args) {
|
|
|
201
265
|
await new Promise(r => setTimeout(r, CONNECT_TIMING.pollMs));
|
|
202
266
|
state = await stateOf(host).catch(() => null);
|
|
203
267
|
}
|
|
204
|
-
if (state === 'unauthorized')
|
|
205
|
-
|
|
268
|
+
if (state === 'unauthorized') {
|
|
269
|
+
const e = new Error(`${out}\nThe device has not allowed debugging from this computer yet (unauthorized): confirm the debugging prompt on the device's screen (tick "Always allow from this computer"), then call adb_connect again. ` +
|
|
206
270
|
'If the screen is off, wake the device (its remote or power button) so the prompt shows. Not remembered.');
|
|
271
|
+
e.unauthorized = true;
|
|
272
|
+
throw e;
|
|
273
|
+
}
|
|
207
274
|
if (state !== 'device')
|
|
208
275
|
return text(`${out}\nadb lists ${host} as ${state || 'not connected'}, not as a working device: not remembered. Check the device is awake, then call adb_connect again.`);
|
|
276
|
+
resume(host);
|
|
209
277
|
const addr = rememberable(host);
|
|
210
278
|
let note = '';
|
|
211
279
|
if (addr) {
|
|
212
280
|
try {
|
|
213
281
|
const r = await remember(addr, await keyOf(addr));
|
|
214
282
|
if (r.replaced) note = `\nThis device was remembered at ${r.replaced}; its new address ${addr} replaces it.`;
|
|
215
|
-
else if (r.added) note =
|
|
283
|
+
else if (r.added) note = KEEP_CONNECTED
|
|
284
|
+
? `\nRemembered ${addr}: the server keeps it connected.`
|
|
285
|
+
: `\nRemembered ${addr}: the server reconnects it when it starts.`;
|
|
216
286
|
} catch (e) { note = `\nNot remembered (${e.message}).`; }
|
|
217
287
|
}
|
|
218
288
|
return text(out + note);
|
|
@@ -232,10 +302,24 @@ async function disconnect(args) {
|
|
|
232
302
|
let note = '';
|
|
233
303
|
if (args.host) {
|
|
234
304
|
const addr = rememberable(args.host);
|
|
235
|
-
if (addr && await forget(addr).catch(() => false)) note = `\nForgotten ${addr}: no longer reconnected
|
|
305
|
+
if (addr && await forget(addr).catch(() => false)) note = `\nForgotten ${addr}: no longer reconnected.`;
|
|
306
|
+
// An address of the devices setting cannot be forgotten: paused instead.
|
|
307
|
+
const h = hostPort(args.host);
|
|
308
|
+
if (DEVICES.includes(h)) {
|
|
309
|
+
pause(h, 'adb_disconnect');
|
|
310
|
+
if (KEEP_CONNECTED) note += `\n${h} comes from the devices setting: not reconnected in the background until adb_connect or a restart of the server.`;
|
|
311
|
+
}
|
|
236
312
|
} else {
|
|
237
|
-
const
|
|
238
|
-
|
|
313
|
+
const known = readKnown();
|
|
314
|
+
const fromSetting = DEVICES.filter(d => !known.includes(d));
|
|
315
|
+
for (const a of [...known, ...fromSetting]) pause(a, 'adb_disconnect');
|
|
316
|
+
const n = known.length, m = fromSetting.length;
|
|
317
|
+
if (!KEEP_CONNECTED) {
|
|
318
|
+
if (n) note = `\nThe ${n} remembered address${n === 1 ? ' is' : 'es are'} kept: adb_disconnect with host forgets one.`;
|
|
319
|
+
} else {
|
|
320
|
+
if (n) note = `\nThe ${n} remembered address${n === 1 ? ' is' : 'es are'} kept but not reconnected in the background until adb_connect or a restart of the server; adb_disconnect with host forgets one.`;
|
|
321
|
+
if (m) note += `\nThe ${m} address${m === 1 ? '' : 'es'} of the devices setting ${m === 1 ? 'is' : 'are'} not reconnected in the background until adb_connect or a restart of the server.`;
|
|
322
|
+
}
|
|
239
323
|
}
|
|
240
324
|
return text((out || 'Disconnected') + note);
|
|
241
325
|
}
|
|
@@ -290,7 +374,7 @@ async function reconnectRemembered(serial, message) {
|
|
|
290
374
|
try {
|
|
291
375
|
if (/offline/i.test(message)) await adb(['disconnect', addr], { timeout: 10000 }).catch(() => {});
|
|
292
376
|
const out = (await adb(['connect', addr], { timeout: 10000 })).toString();
|
|
293
|
-
return { ok:
|
|
377
|
+
return { ok: !CONNECT_FAILED_RE.test(out), addr };
|
|
294
378
|
} catch {
|
|
295
379
|
return { ok: false, addr };
|
|
296
380
|
}
|
|
@@ -299,5 +383,6 @@ async function reconnectRemembered(serial, message) {
|
|
|
299
383
|
module.exports = {
|
|
300
384
|
configure, devices, connect, pair, disconnect, shell, logcat,
|
|
301
385
|
rememberable, readKnown, readEntries, remember, forget, reconnectRemembered, KNOWN_FILE,
|
|
302
|
-
CONNECT_TIMING, markSameDevice,
|
|
386
|
+
CONNECT_TIMING, CONNECT_FAILED_RE, markSameDevice,
|
|
387
|
+
hostPort, watched, deviceStates, pause, resume, pausedReason, pauseMark, pausedBefore,
|
|
303
388
|
};
|
package/src/watcher.js
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* watcher.js — keeps the remembered devices and the devices of the settings
|
|
4
|
+
* connected (reconnect_interval; 0 means no watcher).
|
|
5
|
+
*
|
|
6
|
+
* Every interval, for the addresses session.watched() returns: one
|
|
7
|
+
* `adb devices`, then one address after another:
|
|
8
|
+
* device, authorizing, connecting → nothing;
|
|
9
|
+
* not listed → adb connect;
|
|
10
|
+
* offline → adb disconnect, then adb connect;
|
|
11
|
+
* unauthorized → nothing.
|
|
12
|
+
* settleMs after a connect one more `adb devices` decides: unauthorized pauses
|
|
13
|
+
* the address (every connect shows the device's debugging prompt), see
|
|
14
|
+
* session.pause(). A paused address is never connected by the watcher; once
|
|
15
|
+
* adb lists it as device again, by whatever means, the pause ends.
|
|
16
|
+
*
|
|
17
|
+
* The watcher never writes devices.json and never reads a device key: that
|
|
18
|
+
* stays with adb_connect. A round still running when the next is due makes the
|
|
19
|
+
* next one skip. A failure is logged when a streak of failures starts and once
|
|
20
|
+
* when it ends; a round where nothing happened logs nothing.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
const { adb } = require('./adb.js');
|
|
24
|
+
const session = require('./session.js');
|
|
25
|
+
|
|
26
|
+
const ADB_CALL_MS = 10000;
|
|
27
|
+
const LEAVE = new Set(['device', 'authorizing', 'connecting']);
|
|
28
|
+
// The failure streak of `adb devices` itself.
|
|
29
|
+
const LISTING = 'adb devices';
|
|
30
|
+
|
|
31
|
+
const firstLine = s => String(s).trim().split(/\r?\n/)[0];
|
|
32
|
+
const attempts = n => `${n} failed attempt${n === 1 ? '' : 's'}`;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* A watcher with injected timing, so tests need no clock: intervalMs between
|
|
36
|
+
* rounds, settleMs before the state after a connect is read, sleep(ms) and the
|
|
37
|
+
* interval timer functions. listDevices is the `adb devices` of a round.
|
|
38
|
+
*/
|
|
39
|
+
function createWatcher({
|
|
40
|
+
intervalMs,
|
|
41
|
+
settleMs = session.CONNECT_TIMING.unauthorizedMs,
|
|
42
|
+
log = line => process.stderr.write(line + '\n'),
|
|
43
|
+
sleep = ms => new Promise(r => setTimeout(r, ms)),
|
|
44
|
+
timers = { setInterval, clearInterval },
|
|
45
|
+
listDevices = session.deviceStates,
|
|
46
|
+
} = {}) {
|
|
47
|
+
let timer = null;
|
|
48
|
+
let running = false;
|
|
49
|
+
const failing = new Map(); // address or LISTING -> failed attempts in a row
|
|
50
|
+
const say = msg => log(`brickproof-adb: watcher: ${msg}`);
|
|
51
|
+
const retry = `retrying every ${intervalMs / 1000} s, the next line when that changes`;
|
|
52
|
+
|
|
53
|
+
function failed(key, what, why) {
|
|
54
|
+
const n = failing.get(key) || 0;
|
|
55
|
+
failing.set(key, n + 1);
|
|
56
|
+
if (n === 0) say(`${what} failed (${firstLine(why)}): ${retry}`);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Ends a streak; the number of failed attempts it had (0: none).
|
|
60
|
+
function ended(key) {
|
|
61
|
+
const n = failing.get(key) || 0;
|
|
62
|
+
failing.delete(key);
|
|
63
|
+
return n;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function reconnect(addr, state) {
|
|
67
|
+
const what = `reconnect ${addr}`;
|
|
68
|
+
if (state === 'offline') await adb(['disconnect', addr], { timeout: ADB_CALL_MS }).catch(() => {});
|
|
69
|
+
let out;
|
|
70
|
+
try {
|
|
71
|
+
out = (await adb(['connect', addr], { timeout: ADB_CALL_MS })).toString().trim();
|
|
72
|
+
} catch (e) {
|
|
73
|
+
return failed(addr, what, e.message);
|
|
74
|
+
}
|
|
75
|
+
if (session.CONNECT_FAILED_RE.test(out)) return failed(addr, what, out);
|
|
76
|
+
await sleep(settleMs);
|
|
77
|
+
let now;
|
|
78
|
+
try {
|
|
79
|
+
now = (await session.deviceStates()).get(addr) || null;
|
|
80
|
+
} catch (e) {
|
|
81
|
+
return failed(addr, what, e.message);
|
|
82
|
+
}
|
|
83
|
+
if (now === 'unauthorized') {
|
|
84
|
+
ended(addr);
|
|
85
|
+
session.pause(addr, 'unauthorized');
|
|
86
|
+
return say(unauthorizedLine(addr));
|
|
87
|
+
}
|
|
88
|
+
if (now === 'device') {
|
|
89
|
+
const n = ended(addr);
|
|
90
|
+
return say(`reconnected ${addr}${n ? ` after ${attempts(n)}` : ''}`);
|
|
91
|
+
}
|
|
92
|
+
if (LEAVE.has(now)) return undefined;
|
|
93
|
+
return failed(addr, what, `adb lists it as ${now || 'not connected'}`);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** One round; false when the previous round is still running. */
|
|
97
|
+
async function tick() {
|
|
98
|
+
if (running) return false;
|
|
99
|
+
running = true;
|
|
100
|
+
try {
|
|
101
|
+
const addrs = session.watched();
|
|
102
|
+
for (const k of failing.keys()) if (k !== LISTING && !addrs.includes(k)) failing.delete(k);
|
|
103
|
+
if (!addrs.length) return true;
|
|
104
|
+
// Only a pause set before this listing may be ended by it: a pause set
|
|
105
|
+
// while it runs (adb_disconnect) is newer than what it shows.
|
|
106
|
+
const mark = session.pauseMark();
|
|
107
|
+
let listed;
|
|
108
|
+
try {
|
|
109
|
+
listed = await listDevices();
|
|
110
|
+
} catch (e) {
|
|
111
|
+
failed(LISTING, LISTING, e.message);
|
|
112
|
+
return true;
|
|
113
|
+
}
|
|
114
|
+
const n = ended(LISTING);
|
|
115
|
+
if (n) say(`adb devices works again after ${attempts(n)}`);
|
|
116
|
+
for (const addr of addrs) {
|
|
117
|
+
const state = listed.get(addr) || null;
|
|
118
|
+
if (session.pausedReason(addr)) {
|
|
119
|
+
if (state === 'device' && session.pausedBefore(addr, mark)) {
|
|
120
|
+
session.resume(addr);
|
|
121
|
+
ended(addr);
|
|
122
|
+
say(`${addr} is connected again: watching it again`);
|
|
123
|
+
}
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
if (LEAVE.has(state)) {
|
|
127
|
+
const m = ended(addr);
|
|
128
|
+
if (m && state === 'device') say(`${addr} is connected again after ${attempts(m)}`);
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
if (state === 'unauthorized') continue;
|
|
132
|
+
await reconnect(addr, state);
|
|
133
|
+
}
|
|
134
|
+
return true;
|
|
135
|
+
} finally {
|
|
136
|
+
running = false;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function start() {
|
|
141
|
+
if (timer) return;
|
|
142
|
+
timer = timers.setInterval(() => {
|
|
143
|
+
tick().catch(e => say(`round failed: ${firstLine(e && e.message || e)}`));
|
|
144
|
+
}, intervalMs);
|
|
145
|
+
if (timer && typeof timer.unref === 'function') timer.unref();
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function stop() {
|
|
149
|
+
if (!timer) return;
|
|
150
|
+
timers.clearInterval(timer);
|
|
151
|
+
timer = null;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
return { tick, start, stop, get started() { return timer !== null; } };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function unauthorizedLine(addr) {
|
|
158
|
+
return `${addr} is unauthorized: not retried until the device allows this computer, adb_connect or a restart`;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** The watcher for the settings, not started; null when reconnect_interval is 0. */
|
|
162
|
+
function watcherFor(settings, opts = {}) {
|
|
163
|
+
const s = Number(settings && settings.reconnect_interval) || 0;
|
|
164
|
+
return s > 0 ? createWatcher({ intervalMs: s * 1000, ...opts }) : null;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* The connects at start, one address after another (session.connect(), so
|
|
169
|
+
* a device that answers is remembered with its key). With pauseUnauthorized
|
|
170
|
+
* (the watcher runs) an address left unauthorized is paused like the
|
|
171
|
+
* watcher's own: the device shows its prompt once, not every round.
|
|
172
|
+
*/
|
|
173
|
+
async function connectAtStart({ pauseUnauthorized = false, log = line => process.stderr.write(line + '\n') } = {}) {
|
|
174
|
+
for (const d of session.watched()) {
|
|
175
|
+
try {
|
|
176
|
+
const r = await session.connect({ host: d });
|
|
177
|
+
log(`brickproof-adb: adb connect ${d}: ${firstLine(r[0].text)}`);
|
|
178
|
+
} catch (e) {
|
|
179
|
+
log(`brickproof-adb: adb connect ${d} failed (adb_connect can retry): ${firstLine(e.message)}`);
|
|
180
|
+
if (pauseUnauthorized && e.unauthorized) {
|
|
181
|
+
session.pause(d, 'unauthorized');
|
|
182
|
+
log(`brickproof-adb: watcher: ${unauthorizedLine(d)}`);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
module.exports = { createWatcher, watcherFor, connectAtStart };
|