brickproof-adb 0.0.0-stage → 1.0.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 +36 -0
- package/LICENSE +21 -0
- package/README.md +146 -2
- package/package.json +40 -4
- package/src/adb.js +376 -0
- package/src/apps.js +1156 -0
- package/src/cli.js +497 -0
- package/src/config.js +597 -0
- package/src/device.js +669 -0
- package/src/discover.js +315 -0
- package/src/files.js +453 -0
- package/src/hostpath.js +110 -0
- package/src/http.js +314 -0
- package/src/image.js +209 -0
- package/src/main.js +7 -0
- package/src/platform-tools.js +258 -0
- package/src/registry.js +334 -0
- package/src/server.js +161 -0
- package/src/session.js +303 -0
- package/src/stdio.js +51 -0
- package/src/token.js +114 -0
- package/src/ui.js +942 -0
- package/src/version.js +10 -0
package/src/server.js
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* brickproof-adb — the MCP dispatcher, shared by both transports (http.js,
|
|
4
|
+
* stdio.js), plus the argument masking and error redaction of the tool log.
|
|
5
|
+
*
|
|
6
|
+
* init(settings) passes the settings to the tool modules once; no module reads
|
|
7
|
+
* the environment itself. Every log line goes to stderr: in stdio mode stdout
|
|
8
|
+
* belongs to the protocol.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
const { TOOLS, callTool } = require('./registry.js');
|
|
12
|
+
const { escapeInputText, sq, collectNotes } = require('./adb.js');
|
|
13
|
+
const { VERSION } = require('./version.js');
|
|
14
|
+
|
|
15
|
+
let LOG_REQUESTS = false;
|
|
16
|
+
let logSink = line => process.stderr.write(line + '\n');
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Pass the settings (config.js loadConfig().settings) to the modules, with
|
|
20
|
+
* the action texts of the settings refusals (config.settingHints) and the adb
|
|
21
|
+
* found by platform-tools.js. The defaults of every module are the safe ones:
|
|
22
|
+
* shell and uninstall off, no file roots, no store.
|
|
23
|
+
*/
|
|
24
|
+
function init(settings = {}, { log, hints = {}, adbPath } = {}) {
|
|
25
|
+
require('./adb.js').configure({ adbPath: adbPath || settings.adb_path });
|
|
26
|
+
require('./session.js').configure({
|
|
27
|
+
allowShell: settings.allow_shell === true,
|
|
28
|
+
shellHint: hints.allow_shell,
|
|
29
|
+
stateDir: settings.state_dir || null,
|
|
30
|
+
scanSubnets: settings.scan_subnets || [],
|
|
31
|
+
});
|
|
32
|
+
require('./files.js').configure({ fileRoots: settings.file_roots || [], rootsHint: hints.file_roots });
|
|
33
|
+
require('./apps.js').configure({
|
|
34
|
+
allowShell: settings.allow_shell === true,
|
|
35
|
+
allowUninstall: settings.allow_uninstall === true,
|
|
36
|
+
store: settings.store || null,
|
|
37
|
+
fileRoots: settings.file_roots || [],
|
|
38
|
+
hints,
|
|
39
|
+
});
|
|
40
|
+
LOG_REQUESTS = settings.log_requests === true;
|
|
41
|
+
if (log) logSink = log;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Arguments are masked BEFORE the cut to 300 characters, so no secret
|
|
46
|
+
* survives in a tail by luck of length. adb_shell.command is not masked: it is
|
|
47
|
+
* an arbitrary administrator command with no fixed shape (the docs say so).
|
|
48
|
+
*/
|
|
49
|
+
function maskArgs(name, args) {
|
|
50
|
+
const a = { ...(args || {}) };
|
|
51
|
+
if (name === 'adb_text' && a.text !== undefined) a.text = `<${String(a.text).length} chars>`;
|
|
52
|
+
if (name === 'adb_pair' && a.code !== undefined) a.code = '***';
|
|
53
|
+
for (const k of Object.keys(a)) {
|
|
54
|
+
if (/pass|secret|token/i.test(k)) a[k] = '***'; // a guard for future parameters
|
|
55
|
+
}
|
|
56
|
+
return a;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function fmtArgs(name, args) {
|
|
60
|
+
try {
|
|
61
|
+
const s = JSON.stringify(maskArgs(name, args));
|
|
62
|
+
return s.length > 300 ? s.slice(0, 300) + '…' : s;
|
|
63
|
+
} catch { return '(unserializable)'; }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The second leak besides the arguments: free text of an error message (an
|
|
68
|
+
* adb failure, a tool refusal) can carry the typed text or the pairing code.
|
|
69
|
+
* Removed here: the text itself, its argument of `input text` (quoted with
|
|
70
|
+
* sq() and bare) and its base64 form (the ADBKeyBoard broadcast). Values
|
|
71
|
+
* shorter than 2 characters are left alone, or any one-letter match would cut
|
|
72
|
+
* the message apart. Applied once, to the log line and to the text the client
|
|
73
|
+
* gets alike.
|
|
74
|
+
*/
|
|
75
|
+
function redact(name, args, str) {
|
|
76
|
+
if (!str) return str;
|
|
77
|
+
let out = String(str);
|
|
78
|
+
const wipe = secret => {
|
|
79
|
+
if (secret === undefined || secret === null) return;
|
|
80
|
+
const s = String(secret);
|
|
81
|
+
if (s.length < 2) return;
|
|
82
|
+
out = out.split(s).join('<secret>');
|
|
83
|
+
};
|
|
84
|
+
if (name === 'adb_text' && args && args.text !== undefined) {
|
|
85
|
+
const t = String(args.text);
|
|
86
|
+
wipe(t);
|
|
87
|
+
wipe(sq(escapeInputText(t)));
|
|
88
|
+
wipe(escapeInputText(t));
|
|
89
|
+
wipe(Buffer.from(t, 'utf8').toString('base64'));
|
|
90
|
+
}
|
|
91
|
+
if (name === 'adb_pair' && args && args.code !== undefined) wipe(args.code);
|
|
92
|
+
return out;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function fmtOutcome(content) {
|
|
96
|
+
if (!Array.isArray(content) || !content.length) return 'ok';
|
|
97
|
+
const c = content[0];
|
|
98
|
+
if (c.type === 'image') return `image ${Math.round((c.data || '').length * 3 / 4 / 1024)}KB`;
|
|
99
|
+
const len = (c.text || '').length;
|
|
100
|
+
return `ok ${len}B`;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function logTool(name, args, t0, outcome) {
|
|
104
|
+
if (!LOG_REQUESTS) return;
|
|
105
|
+
logSink(`[tool] ${new Date().toISOString()} ${name} ${fmtArgs(name, args)} -> ${outcome} ${Date.now() - t0}ms`);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// The client's version is echoed when supported, otherwise the newest one.
|
|
109
|
+
const SUPPORTED_PROTOCOL_VERSIONS = ['2025-06-18', '2025-03-26', '2024-11-05'];
|
|
110
|
+
|
|
111
|
+
function negotiateProtocolVersion(requested) {
|
|
112
|
+
return SUPPORTED_PROTOCOL_VERSIONS.includes(requested) ? requested : SUPPORTED_PROTOCOL_VERSIONS[0];
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async function handleMcpRequest(body) {
|
|
116
|
+
if (!body || typeof body !== 'object' || Array.isArray(body))
|
|
117
|
+
return { jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Invalid Request: each request must be a JSON object' } };
|
|
118
|
+
const { id, method, params } = body;
|
|
119
|
+
|
|
120
|
+
if (method === 'initialize') {
|
|
121
|
+
return { jsonrpc: '2.0', id, result: {
|
|
122
|
+
protocolVersion: negotiateProtocolVersion(params && params.protocolVersion),
|
|
123
|
+
capabilities: { tools: { listChanged: false } },
|
|
124
|
+
serverInfo: { name: 'brickproof-adb', version: VERSION }
|
|
125
|
+
}};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
if (method === 'notifications/initialized' || method === 'notifications/roots/list_changed') return null;
|
|
129
|
+
if (method === 'ping') return { jsonrpc: '2.0', id, result: {} };
|
|
130
|
+
if (method === 'tools/list') return { jsonrpc: '2.0', id, result: { tools: TOOLS } };
|
|
131
|
+
if (method === 'resources/list') return { jsonrpc: '2.0', id, result: { resources: [] } };
|
|
132
|
+
if (method === 'prompts/list') return { jsonrpc: '2.0', id, result: { prompts: [] } };
|
|
133
|
+
if (method === 'roots/list') return { jsonrpc: '2.0', id, result: { roots: [] } };
|
|
134
|
+
|
|
135
|
+
if (method === 'tools/call') {
|
|
136
|
+
const t0 = Date.now();
|
|
137
|
+
const name = params && params.name;
|
|
138
|
+
const args = (params && params.arguments) || {};
|
|
139
|
+
try {
|
|
140
|
+
const { value: content, notes } = await collectNotes(() => callTool(name, args));
|
|
141
|
+
// No structuredContent: the tools declare no outputSchema.
|
|
142
|
+
const out = notes.length ? [...content, { type: 'text', text: notes.join('\n') }] : content;
|
|
143
|
+
logTool(name, args, t0, fmtOutcome(out));
|
|
144
|
+
return { jsonrpc: '2.0', id, result: { content: out } };
|
|
145
|
+
} catch (e) {
|
|
146
|
+
// One redaction for the log line and the client text alike.
|
|
147
|
+
const notes = e.adbNotes && e.adbNotes.length ? `\n${e.adbNotes.join('\n')}` : '';
|
|
148
|
+
const msg = redact(name, args, e.message) + notes;
|
|
149
|
+
logTool(name, args, t0, `ERROR: ${msg}`);
|
|
150
|
+
return { jsonrpc: '2.0', id, result: { content: [{ type: 'text', text: `Error: ${msg}` }], isError: true } };
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
return { jsonrpc: '2.0', id, error: { code: -32601, message: `Method not found: ${method}` } };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
module.exports = {
|
|
158
|
+
init, TOOLS, handleMcpRequest,
|
|
159
|
+
negotiateProtocolVersion, SUPPORTED_PROTOCOL_VERSIONS,
|
|
160
|
+
fmtArgs, redact, maskArgs, fmtOutcome,
|
|
161
|
+
};
|
package/src/session.js
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* session.js — adb session and diagnostics: devices, connect, pair,
|
|
4
|
+
* disconnect, shell, logcat; the remembered devices (<state_dir>/devices.json).
|
|
5
|
+
*
|
|
6
|
+
* A successful adb_connect to ip:port remembers the address, adb_disconnect
|
|
7
|
+
* with an address forgets it, and the server connects the remembered ones at
|
|
8
|
+
* start. mDNS names and the random ports of Wireless debugging are not
|
|
9
|
+
* remembered: adb itself reconnects paired devices over mDNS.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
const fs = require('fs');
|
|
13
|
+
const path = require('path');
|
|
14
|
+
const { adb, withSerial, sq, text, ADB_TIMEOUT_MS, renameWithRetry } = require('./adb.js');
|
|
15
|
+
|
|
16
|
+
let ALLOW_SHELL = false;
|
|
17
|
+
let SHELL_HINT = 'run `brickproof-adb set allow_shell on` and restart the server';
|
|
18
|
+
let STATE_DIR = null;
|
|
19
|
+
let SCAN_SUBNETS = [];
|
|
20
|
+
|
|
21
|
+
function configure({ allowShell = false, shellHint, stateDir = null, scanSubnets = [] } = {}) {
|
|
22
|
+
ALLOW_SHELL = allowShell === true;
|
|
23
|
+
if (shellHint) SHELL_HINT = shellHint;
|
|
24
|
+
STATE_DIR = stateDir;
|
|
25
|
+
SCAN_SUBNETS = scanSubnets.slice();
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// ------------------------------------------------------- remembered devices
|
|
29
|
+
|
|
30
|
+
const KNOWN_FILE = 'devices.json';
|
|
31
|
+
// Ports from here up are the ephemeral range Wireless debugging draws from.
|
|
32
|
+
const EPHEMERAL_PORT = 32768;
|
|
33
|
+
|
|
34
|
+
/** ip:port to remember for a host given to adb_connect, or null. */
|
|
35
|
+
function rememberable(host) {
|
|
36
|
+
const h = String(host || '').trim();
|
|
37
|
+
if (!h || /_adb|\._tcp|\s/.test(h)) return null;
|
|
38
|
+
const m = /^(.+?)(?::(\d{1,5}))?$/.exec(h);
|
|
39
|
+
if (!m || m[1].includes(':')) return null; // IPv6 and anything odd: not remembered
|
|
40
|
+
const port = m[2] ? Number(m[2]) : 5555;
|
|
41
|
+
if (port <= 0 || port >= EPHEMERAL_PORT) return null;
|
|
42
|
+
return `${m[1]}:${port}`;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function knownPath() {
|
|
46
|
+
return STATE_DIR ? path.join(STATE_DIR, KNOWN_FILE) : null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The remembered devices: [{ address, key }], key the device's snapshot key
|
|
51
|
+
* (<model>_<serialno>, apps.js) or null when the device has no usable serial.
|
|
52
|
+
* [] when there is no file or it cannot be read.
|
|
53
|
+
*/
|
|
54
|
+
function readEntries() {
|
|
55
|
+
const p = knownPath();
|
|
56
|
+
if (!p) return [];
|
|
57
|
+
try {
|
|
58
|
+
const j = JSON.parse(fs.readFileSync(p, 'utf8'));
|
|
59
|
+
if (!Array.isArray(j.devices)) return [];
|
|
60
|
+
return j.devices
|
|
61
|
+
.map(d => (typeof d === 'string' ? { address: d, key: null } : d))
|
|
62
|
+
.filter(d => d && typeof d.address === 'string')
|
|
63
|
+
.map(d => ({ address: d.address, key: typeof d.key === 'string' ? d.key : null }));
|
|
64
|
+
} catch { return []; }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The remembered addresses. */
|
|
68
|
+
function readKnown() {
|
|
69
|
+
return readEntries().map(d => d.address);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function writeKnown(entries) {
|
|
73
|
+
const p = knownPath();
|
|
74
|
+
if (!p) return;
|
|
75
|
+
fs.mkdirSync(path.dirname(p), { recursive: true });
|
|
76
|
+
const tmp = `${p}.tmp-${process.pid}-${Date.now()}`;
|
|
77
|
+
fs.writeFileSync(tmp, JSON.stringify({ devices: entries, updated: new Date().toISOString() }, null, 2) + '\n', 'utf8');
|
|
78
|
+
await renameWithRetry(tmp, p);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Remember an address with its device key. A key already remembered under
|
|
83
|
+
* another address (the device got a new address from the router) has that
|
|
84
|
+
* address replaced. Returns { added, replaced: old address or null }.
|
|
85
|
+
*/
|
|
86
|
+
async function remember(addr, key = null) {
|
|
87
|
+
const entries = readEntries();
|
|
88
|
+
const same = entries.find(e => e.address === addr);
|
|
89
|
+
if (same) {
|
|
90
|
+
if (key && same.key !== key) { same.key = key; await writeKnown(entries); }
|
|
91
|
+
return { added: false, replaced: null };
|
|
92
|
+
}
|
|
93
|
+
const moved = key ? entries.find(e => e.key === key) : null;
|
|
94
|
+
if (moved) {
|
|
95
|
+
const old = moved.address;
|
|
96
|
+
moved.address = addr;
|
|
97
|
+
await writeKnown(entries);
|
|
98
|
+
return { added: false, replaced: old };
|
|
99
|
+
}
|
|
100
|
+
await writeKnown([...entries, { address: addr, key }]);
|
|
101
|
+
return { added: true, replaced: null };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async function forget(addr) {
|
|
105
|
+
const entries = readEntries();
|
|
106
|
+
if (!entries.some(e => e.address === addr)) return false;
|
|
107
|
+
await writeKnown(entries.filter(e => e.address !== addr));
|
|
108
|
+
return true;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// The device key behind a connected address; null when it cannot be read or
|
|
112
|
+
// the device has no usable serial number.
|
|
113
|
+
async function keyOf(addr) {
|
|
114
|
+
try {
|
|
115
|
+
const id = await require('./apps.js').deviceIdentity(addr);
|
|
116
|
+
return id.source === 'device' ? id.key : null;
|
|
117
|
+
} catch { return null; }
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// ------------------------------------------------------------------- tools
|
|
121
|
+
|
|
122
|
+
async function devices(args = {}) {
|
|
123
|
+
if (args.discover === true || args.discover === 'true') {
|
|
124
|
+
const { discover } = require('./discover.js');
|
|
125
|
+
return text(await discover({ scan: SCAN_SUBNETS }));
|
|
126
|
+
}
|
|
127
|
+
const out = (await adb(['devices', '-l'])).toString();
|
|
128
|
+
const connected = out.split(/\r?\n/).slice(1).map(l => l.trim().split(/\s+/)[0]).filter(Boolean);
|
|
129
|
+
const idle = readKnown().filter(d => !connected.includes(d));
|
|
130
|
+
let extra = idle.length ? `\nRemembered, not connected now: ${idle.join(', ')} (adb_connect reconnects; off or a new address: adb_devices discover=true)` : '';
|
|
131
|
+
if (!connected.length)
|
|
132
|
+
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
|
+
return text((await markSameDevice(out.trim()) || 'No devices') + extra);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// The longest a device may take to tell its key to adb_devices.
|
|
137
|
+
const SAME_DEVICE_TIMEOUT_MS = 3000;
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* One device is often listed under several serials: USB, ip:port, and the
|
|
141
|
+
* mDNS name adb connects a paired phone under by itself. Lines in state
|
|
142
|
+
* `device` whose device key (model and ro.serialno, the snapshot key) was
|
|
143
|
+
* seen on an earlier line get "same device as <that serial>". Keys are read
|
|
144
|
+
* in parallel, each within SAME_DEVICE_TIMEOUT_MS; a device that does not
|
|
145
|
+
* answer, or has no usable serial number, is left unmarked.
|
|
146
|
+
*/
|
|
147
|
+
async function markSameDevice(listing) {
|
|
148
|
+
const lines = listing.split(/\r?\n/);
|
|
149
|
+
const rows = lines.map((l, i) => ({ i, serial: l.trim().split(/\s+/)[0], state: l.trim().split(/\s+/)[1] }))
|
|
150
|
+
.filter(r => r.i > 0 && r.serial && r.state === 'device');
|
|
151
|
+
if (rows.length < 2) return listing;
|
|
152
|
+
const { deviceIdentity } = require('./apps.js');
|
|
153
|
+
const keyOf = serial => Promise.race([
|
|
154
|
+
deviceIdentity(serial).then(id => (id.source === 'device' ? id.key : null), () => null),
|
|
155
|
+
new Promise(r => setTimeout(() => r(null), SAME_DEVICE_TIMEOUT_MS).unref()),
|
|
156
|
+
]);
|
|
157
|
+
const keys = await Promise.all(rows.map(r => keyOf(r.serial)));
|
|
158
|
+
const first = new Map();
|
|
159
|
+
rows.forEach((r, n) => {
|
|
160
|
+
const k = keys[n];
|
|
161
|
+
if (!k) return;
|
|
162
|
+
if (first.has(k)) lines[r.i] = `${lines[r.i].trimEnd()} same device as ${first.get(k)}`;
|
|
163
|
+
else first.set(k, r.serial);
|
|
164
|
+
});
|
|
165
|
+
return lines.join('\n');
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// The state `adb devices` lists for a serial (device, unauthorized, offline,
|
|
169
|
+
// authorizing, connecting), or null when it is not listed.
|
|
170
|
+
async function stateOf(serial) {
|
|
171
|
+
const out = (await adb(['devices'], { timeout: 10000 })).toString();
|
|
172
|
+
for (const line of out.split(/\r?\n/).slice(1)) {
|
|
173
|
+
const [s, state] = line.trim().split(/\s+/);
|
|
174
|
+
if (s === serial) return state || null;
|
|
175
|
+
}
|
|
176
|
+
return null;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const SETTLING = new Set([null, 'authorizing', 'connecting']);
|
|
180
|
+
// How the state after adb connect is watched; replaced in tests.
|
|
181
|
+
// `unauthorized` settles too: a device that trusts this computer may say it
|
|
182
|
+
// for a moment first, so it counts only when it holds for unauthorizedMs.
|
|
183
|
+
const CONNECT_TIMING = { pollMs: 700, settlingPolls: 2, unauthorizedMs: 5000 };
|
|
184
|
+
|
|
185
|
+
async function connect(args) {
|
|
186
|
+
const host = args.host.includes(':') ? args.host : `${args.host}:5555`;
|
|
187
|
+
const out = (await adb(['connect', host], { timeout: 10000 })).toString().trim();
|
|
188
|
+
// adb reports a failed connect on stdout with exit code 0.
|
|
189
|
+
if (/failed to connect|unable to connect|cannot connect/i.test(out))
|
|
190
|
+
throw new Error(`${out}. Check the device is awake and the port is current (wireless-debug ports change after device reboot).`);
|
|
191
|
+
// "connected to" is printed also when the device has not allowed this
|
|
192
|
+
// computer ("failed to authenticate"): what counts is the state adb lists.
|
|
193
|
+
const t0 = Date.now();
|
|
194
|
+
let state = await stateOf(host).catch(() => null);
|
|
195
|
+
for (let settling = 0; ;) {
|
|
196
|
+
if (state === 'unauthorized') {
|
|
197
|
+
if (Date.now() - t0 >= CONNECT_TIMING.unauthorizedMs) break;
|
|
198
|
+
} else if (!SETTLING.has(state) || settling++ >= CONNECT_TIMING.settlingPolls) {
|
|
199
|
+
break;
|
|
200
|
+
}
|
|
201
|
+
await new Promise(r => setTimeout(r, CONNECT_TIMING.pollMs));
|
|
202
|
+
state = await stateOf(host).catch(() => null);
|
|
203
|
+
}
|
|
204
|
+
if (state === 'unauthorized')
|
|
205
|
+
throw 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
|
+
'If the screen is off, wake the device (its remote or power button) so the prompt shows. Not remembered.');
|
|
207
|
+
if (state !== 'device')
|
|
208
|
+
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.`);
|
|
209
|
+
const addr = rememberable(host);
|
|
210
|
+
let note = '';
|
|
211
|
+
if (addr) {
|
|
212
|
+
try {
|
|
213
|
+
const r = await remember(addr, await keyOf(addr));
|
|
214
|
+
if (r.replaced) note = `\nThis device was remembered at ${r.replaced}; its new address ${addr} replaces it.`;
|
|
215
|
+
else if (r.added) note = `\nRemembered ${addr}: the server reconnects it when it starts.`;
|
|
216
|
+
} catch (e) { note = `\nNot remembered (${e.message}).`; }
|
|
217
|
+
}
|
|
218
|
+
return text(out + note);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
async function pair(args) {
|
|
222
|
+
// Wireless debugging (Android 11+): the pairing port is random, there is no
|
|
223
|
+
// default, so ip:port is required.
|
|
224
|
+
if (!String(args.host).includes(':'))
|
|
225
|
+
throw new Error('Pairing requires ip:port — the random port from the "Pair device with pairing code" dialog (not 5555)');
|
|
226
|
+
const out = await adb(['pair', String(args.host), String(args.code)], { timeout: 20000 });
|
|
227
|
+
return text(out.trim());
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
async function disconnect(args) {
|
|
231
|
+
const out = (await adb(args.host ? ['disconnect', args.host] : ['disconnect'], { timeout: 10000 })).toString().trim();
|
|
232
|
+
let note = '';
|
|
233
|
+
if (args.host) {
|
|
234
|
+
const addr = rememberable(args.host);
|
|
235
|
+
if (addr && await forget(addr).catch(() => false)) note = `\nForgotten ${addr}: no longer reconnected at start.`;
|
|
236
|
+
} else {
|
|
237
|
+
const n = readKnown().length;
|
|
238
|
+
if (n) note = `\nThe ${n} remembered address${n === 1 ? ' is' : 'es are'} kept: adb_disconnect with host forgets one.`;
|
|
239
|
+
}
|
|
240
|
+
return text((out || 'Disconnected') + note);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
async function shell(args) {
|
|
244
|
+
if (!ALLOW_SHELL) throw new Error(`adb_shell is disabled: the server option allow_shell is off. To enable it, ${SHELL_HINT}.`);
|
|
245
|
+
const timeout = args.timeout_sec ? Math.min(args.timeout_sec * 1000, 120000) : ADB_TIMEOUT_MS;
|
|
246
|
+
const out = await adb(withSerial(args.serial, ['shell', args.command]), { timeout });
|
|
247
|
+
return text(out.toString().trim() || '(empty output)');
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
async function logcat(args) {
|
|
251
|
+
const serial = args.serial;
|
|
252
|
+
const lines = Math.min(args.lines || 200, 2000);
|
|
253
|
+
const raw = (args.filter || '').trim();
|
|
254
|
+
let out;
|
|
255
|
+
|
|
256
|
+
if (!raw) {
|
|
257
|
+
out = (await adb(withSerial(serial, ['logcat', '-d', '-t', String(lines)]), { timeout: 20000 })).toString();
|
|
258
|
+
} else if (/[:*]/.test(raw)) {
|
|
259
|
+
// filterspec: filter the WHOLE buffer, tail on the device. With -t N
|
|
260
|
+
// logcat cuts the buffer to N raw lines before filtering (empty output).
|
|
261
|
+
// Without *:S unmatched tags are not silenced.
|
|
262
|
+
const spec = raw.split(/\s+/);
|
|
263
|
+
if (!spec.some(x => x.startsWith('*'))) spec.push('*:S');
|
|
264
|
+
const cmd = `logcat -d ${spec.map(sq).join(' ')} 2>/dev/null | tail -n ${lines}`;
|
|
265
|
+
out = (await adb(withSerial(serial, ['shell', cmd]), { timeout: 20000 })).toString();
|
|
266
|
+
} else {
|
|
267
|
+
// substring: case-insensitive grep ON THE DEVICE. Some firmware (Fire OS)
|
|
268
|
+
// ships a BSD grep that matches everything after the binary bytes of the
|
|
269
|
+
// crash buffer, so toybox grep is used when present. The trailing `:`
|
|
270
|
+
// makes zero matches an empty result, not exit 1.
|
|
271
|
+
const cmd = `G="grep"; command -v toybox >/dev/null 2>&1 && toybox grep --help >/dev/null 2>&1 && G="toybox grep"; ` +
|
|
272
|
+
`logcat -d 2>/dev/null | $G -iF -- ${sq(raw)} | tail -n ${lines}; :`;
|
|
273
|
+
out = (await adb(withSerial(serial, ['shell', cmd]), { timeout: 20000 })).toString();
|
|
274
|
+
}
|
|
275
|
+
return text(out.trim().slice(-64000) || '(empty)');
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// ------------------------------------------------------------- reconnecting
|
|
279
|
+
|
|
280
|
+
const LOST_RE = /device '[^']*' not found|device offline/i;
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* After a tool failed with "device not found" or "offline" for a remembered
|
|
284
|
+
* address: one reconnect (disconnect first when offline). Returns null when
|
|
285
|
+
* this does not apply, else { ok, addr }.
|
|
286
|
+
*/
|
|
287
|
+
async function reconnectRemembered(serial, message) {
|
|
288
|
+
const addr = rememberable(serial);
|
|
289
|
+
if (!addr || !LOST_RE.test(String(message || '')) || !readKnown().includes(addr)) return null;
|
|
290
|
+
try {
|
|
291
|
+
if (/offline/i.test(message)) await adb(['disconnect', addr], { timeout: 10000 }).catch(() => {});
|
|
292
|
+
const out = (await adb(['connect', addr], { timeout: 10000 })).toString();
|
|
293
|
+
return { ok: !/failed to connect|unable to connect|cannot connect/i.test(out), addr };
|
|
294
|
+
} catch {
|
|
295
|
+
return { ok: false, addr };
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
module.exports = {
|
|
300
|
+
configure, devices, connect, pair, disconnect, shell, logcat,
|
|
301
|
+
rememberable, readKnown, readEntries, remember, forget, reconnectRemembered, KNOWN_FILE,
|
|
302
|
+
CONNECT_TIMING, markSameDevice,
|
|
303
|
+
};
|
package/src/stdio.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* brickproof-adb over stdio: newline-delimited JSON-RPC on stdin and stdout, the same
|
|
4
|
+
* dispatcher as HTTP. stdout carries the protocol and nothing else; every other
|
|
5
|
+
* line goes to stderr. No token: the client starts the process.
|
|
6
|
+
*
|
|
7
|
+
* Requests are answered as they finish, so a slow tool call does not hold up a
|
|
8
|
+
* ping. A batch (a JSON array) is answered with one array, as over HTTP.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
const readline = require('readline');
|
|
12
|
+
const S = require('./server');
|
|
13
|
+
|
|
14
|
+
function serveStdio({ input = process.stdin, output = process.stdout, dispatch = S.handleMcpRequest } = {}) {
|
|
15
|
+
const send = msg => output.write(JSON.stringify(msg) + '\n');
|
|
16
|
+
const pending = new Set();
|
|
17
|
+
|
|
18
|
+
async function handleLine(line) {
|
|
19
|
+
if (!line.trim()) return;
|
|
20
|
+
let body;
|
|
21
|
+
try { body = JSON.parse(line); }
|
|
22
|
+
catch {
|
|
23
|
+
send({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } });
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
const requests = Array.isArray(body) ? body : [body];
|
|
27
|
+
const responses = [];
|
|
28
|
+
for (const r of requests) {
|
|
29
|
+
const resp = await dispatch(r);
|
|
30
|
+
if (resp !== null) responses.push(resp);
|
|
31
|
+
}
|
|
32
|
+
const result = Array.isArray(body) ? responses : (responses[0] || null);
|
|
33
|
+
if (result !== null && !(Array.isArray(result) && !result.length)) send(result);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const rl = readline.createInterface({ input, crlfDelay: Infinity });
|
|
37
|
+
rl.on('line', line => {
|
|
38
|
+
const p = handleLine(line).catch(e => {
|
|
39
|
+
process.stderr.write(`brickproof-adb: stdio request failed: ${e && e.stack || e}\n`);
|
|
40
|
+
send({ jsonrpc: '2.0', id: null, error: { code: -32603, message: 'Internal error' } });
|
|
41
|
+
});
|
|
42
|
+
pending.add(p);
|
|
43
|
+
p.finally(() => pending.delete(p));
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
// Resolves when stdin ends and every answer has been written.
|
|
47
|
+
const closed = new Promise(resolve => rl.on('close', () => Promise.allSettled([...pending]).then(() => resolve())));
|
|
48
|
+
return { closed };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
module.exports = { serveStdio };
|
package/src/token.js
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* brickproof-adb — the HTTP token: where it comes from, how it is generated
|
|
4
|
+
* and kept.
|
|
5
|
+
*
|
|
6
|
+
* Order: --token-file, env BRICKPROOF_TOKEN, <state_dir>/token, else a new one
|
|
7
|
+
* is generated and saved there. Never from the config file or the command
|
|
8
|
+
* line. A generated token is 32 random bytes as 64 hex characters, saved with
|
|
9
|
+
* mode 0600 through a temporary file and a rename. On Windows the mode has no
|
|
10
|
+
* effect; the file is protected by the access rights of the user profile that
|
|
11
|
+
* holds state_dir.
|
|
12
|
+
*
|
|
13
|
+
* The token itself is printed only by `brickproof-adb token` and once at
|
|
14
|
+
* generation (cli.js); no message of this module carries it.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
const crypto = require('crypto');
|
|
18
|
+
const fs = require('fs');
|
|
19
|
+
const path = require('path');
|
|
20
|
+
const { validateToken, TokenError } = require('./http');
|
|
21
|
+
|
|
22
|
+
const TOKEN_FILE = 'token';
|
|
23
|
+
const HINT = 'run `brickproof-adb token --new` for a generated one';
|
|
24
|
+
|
|
25
|
+
function tokenPath(stateDir) {
|
|
26
|
+
return path.join(stateDir, TOKEN_FILE);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function generateToken() {
|
|
30
|
+
return crypto.randomBytes(32).toString('hex');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// null when the file does not exist.
|
|
34
|
+
function readStored(stateDir) {
|
|
35
|
+
try { return fs.readFileSync(tokenPath(stateDir), 'utf8').trim(); }
|
|
36
|
+
catch (e) { if (e.code === 'ENOENT') return null; throw e; }
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function writeStored(stateDir, token) {
|
|
40
|
+
const file = tokenPath(stateDir);
|
|
41
|
+
const tmp = path.join(stateDir, `.token.tmp-${process.pid}-${Date.now()}`);
|
|
42
|
+
fs.writeFileSync(tmp, token + '\n', { mode: 0o600, flag: 'wx' });
|
|
43
|
+
try { fs.renameSync(tmp, file); }
|
|
44
|
+
catch (e) { try { fs.unlinkSync(tmp); } catch {} throw e; }
|
|
45
|
+
return file;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function envValue(env, name) {
|
|
49
|
+
const v = env[name];
|
|
50
|
+
return v === undefined || v === '' ? undefined : v;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// A token kept from ha-adb-mcp 1.x that breaks the rules: honoured only inside
|
|
54
|
+
// Home Assistant (SUPERVISOR_TOKEN set) with BRICKPROOF_ALLOW_LEGACY_TOKEN=1.
|
|
55
|
+
function legacyAllowed(env) {
|
|
56
|
+
return env.BRICKPROOF_ALLOW_LEGACY_TOKEN === '1' && Boolean(envValue(env, 'SUPERVISOR_TOKEN'));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* The token in force. Returns { token, source, generated, legacy, file } or
|
|
61
|
+
* throws TokenError. With generate: false a missing token is an error instead.
|
|
62
|
+
*/
|
|
63
|
+
function resolveToken({ tokenFile, env = process.env, stateDir, generate = true }) {
|
|
64
|
+
let given, source;
|
|
65
|
+
if (tokenFile !== undefined) {
|
|
66
|
+
try { given = fs.readFileSync(tokenFile, 'utf8').trim(); }
|
|
67
|
+
catch (e) { throw new TokenError(`cannot read --token-file (${e.code || e.message})`); }
|
|
68
|
+
source = '--token-file';
|
|
69
|
+
} else if (envValue(env, 'BRICKPROOF_TOKEN') !== undefined) {
|
|
70
|
+
given = env.BRICKPROOF_TOKEN.trim();
|
|
71
|
+
source = 'env BRICKPROOF_TOKEN';
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
if (source) {
|
|
75
|
+
try {
|
|
76
|
+
validateToken(given);
|
|
77
|
+
return { token: given, source, generated: false, legacy: false, file: null };
|
|
78
|
+
} catch (e) {
|
|
79
|
+
if (given && legacyAllowed(env))
|
|
80
|
+
return { token: given, source, generated: false, legacy: true, file: null };
|
|
81
|
+
throw new TokenError(`token from ${source}: ${e.message}; ${HINT}`);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const file = tokenPath(stateDir);
|
|
86
|
+
const stored = readStored(stateDir);
|
|
87
|
+
if (stored !== null) {
|
|
88
|
+
try { validateToken(stored); }
|
|
89
|
+
catch (e) { throw new TokenError(`token in ${file}: ${e.message}; ${HINT}`); }
|
|
90
|
+
return { token: stored, source: file, generated: false, legacy: false, file };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
if (!generate) throw new TokenError(`no token yet: \`brickproof-adb serve\` generates one on its first start, or ${HINT}`);
|
|
94
|
+
const token = generateToken();
|
|
95
|
+
writeStored(stateDir, token);
|
|
96
|
+
return { token, source: file, generated: true, legacy: false, file };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// `brickproof-adb token --new`: replaces the stored token.
|
|
100
|
+
function replaceToken(stateDir) {
|
|
101
|
+
const token = generateToken();
|
|
102
|
+
const file = writeStored(stateDir, token);
|
|
103
|
+
return { token, file };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// The two lines `brickproof-adb token` prints and generation shows once.
|
|
107
|
+
function connectionLines(token) {
|
|
108
|
+
return [`/private_${token}/mcp`, `Authorization: Bearer ${token}`];
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
module.exports = {
|
|
112
|
+
TOKEN_FILE, tokenPath, generateToken, readStored, legacyAllowed,
|
|
113
|
+
resolveToken, replaceToken, connectionLines,
|
|
114
|
+
};
|