brickproof-adb 0.0.0-stage → 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.
@@ -0,0 +1,315 @@
1
+ 'use strict';
2
+ /**
3
+ * discover.js — `adb_devices discover=true`: find devices that could be
4
+ * connected, connect none of them (connecting shows a prompt on the device,
5
+ * which is for the person to decide).
6
+ *
7
+ * Source 1: mDNS through adb itself (`adb mdns services`): phones, watches and
8
+ * tablets with Wireless debugging, Android 11 and newer. adb prints a header
9
+ * line, then one service per line: "<instance>\t<service>\t<ip>:<port>".
10
+ * Parsed tolerantly; an empty or unsupported answer is a note, not an error.
11
+ *
12
+ * Source 2: TCP port 5555 (TV boxes with network debugging) in the private
13
+ * IPv4 subnets of the host's interfaces, at most the /24 around each address,
14
+ * or in scan_subnets. Only a TCP connect and a close: nothing is sent.
15
+ */
16
+
17
+ const net = require('net');
18
+ const os = require('os');
19
+ const { adb } = require('./adb.js');
20
+ const { ipToInt, intToIp, isPrivateIp, parseSubnet } = require('./config.js');
21
+
22
+ const PORT = 5555;
23
+ const CONNECT_TIMEOUT_MS = 400;
24
+ const PARALLEL = 64;
25
+ // The second pass over the hosts that only timed out.
26
+ const RETRY_TIMEOUT_MS = 1500;
27
+ const RETRY_PARALLEL = 128;
28
+ const BUDGET_MS = 10000;
29
+
30
+ // Interfaces that are not the home network: containers, VMs, VPNs, tunnels.
31
+ const VIRTUAL_IF = /^(docker|br-|veth|virbr|vmnet|vboxnet|vnic|vEthernet|wsl|tun|tap|utun|wg|tailscale|zt|ppp|ipsec|gif|stf|awdl|llw|bridge|cni|flannel|cali|kube|lxc|lxd|podman|nordlynx|proton|ham)|virtual|vmware|virtualbox|hyper-v|loopback|vpn|tunnel/i;
32
+
33
+ /**
34
+ * Parse `adb mdns services`: [{ instance, service, host, port, kind }], kind
35
+ * 'pairing' | 'connect' | 'adb'. Lines without an ip:port and an _adb service
36
+ * are skipped.
37
+ */
38
+ function parseMdnsServices(out) {
39
+ const found = [];
40
+ for (const raw of String(out || '').split(/\r?\n/)) {
41
+ const line = raw.trim();
42
+ if (!line || /^list of discovered/i.test(line)) continue;
43
+ const svc = /(_adb(?:-tls-(?:pairing|connect))?\._tcp)\.?/.exec(line);
44
+ const addr = /((?:\d{1,3}\.){3}\d{1,3}):(\d{1,5})\b/.exec(line);
45
+ if (!svc || !addr) continue;
46
+ const fields = line.split(/\t+|\s{2,}/);
47
+ const instance = fields[0] && !fields[0].startsWith('_adb') && !/^\d/.test(fields[0]) ? fields[0].trim() : '';
48
+ const service = svc[1];
49
+ found.push({
50
+ instance, service, host: addr[1], port: Number(addr[2]),
51
+ kind: service === '_adb-tls-pairing._tcp' ? 'pairing' : service === '_adb-tls-connect._tcp' ? 'connect' : 'adb',
52
+ });
53
+ }
54
+ return found;
55
+ }
56
+
57
+ /**
58
+ * The subnets to scan: scan_subnets when set, else the private IPv4 networks
59
+ * of the host's interfaces, each at most the /24 around the host's address.
60
+ * Returns { subnets: [{ text, base, prefix, self }], skipped: [names] }.
61
+ */
62
+ function scanSubnets({ scan = [], interfaces = os.networkInterfaces() } = {}) {
63
+ if (scan.length) {
64
+ return { subnets: scan.map(s => ({ ...parseSubnet(s), self: null })), skipped: [], from: 'scan_subnets' };
65
+ }
66
+ const subnets = [], skipped = [];
67
+ for (const [name, addrs] of Object.entries(interfaces || {})) {
68
+ if (VIRTUAL_IF.test(name)) { skipped.push(name); continue; }
69
+ for (const a of addrs || []) {
70
+ if (a.internal || (a.family !== 'IPv4' && a.family !== 4)) continue;
71
+ const ip = ipToInt(a.address);
72
+ if (ip === null || !isPrivateIp(ip)) continue;
73
+ const maskBits = a.cidr ? Number(a.cidr.split('/')[1]) : 24;
74
+ const prefix = Math.max(24, Math.min(maskBits, 30));
75
+ const mask = (0xffffffff << (32 - prefix)) >>> 0;
76
+ const base = (ip & mask) >>> 0;
77
+ const text = `${intToIp(base)}/${prefix}`;
78
+ if (!subnets.some(s => s.text === text)) subnets.push({ text, base, prefix, self: a.address });
79
+ }
80
+ }
81
+ return { subnets, skipped, from: 'interfaces' };
82
+ }
83
+
84
+ /** The host addresses of a subnet, without the network and broadcast addresses and the host itself. */
85
+ function hostsOf(subnet) {
86
+ const size = 2 ** (32 - subnet.prefix);
87
+ const out = [];
88
+ for (let i = 1; i < size - 1; i++) {
89
+ const ip = intToIp(subnet.base + i);
90
+ if (ip !== subnet.self) out.push(ip);
91
+ }
92
+ return out;
93
+ }
94
+
95
+ /**
96
+ * One pass of TCP connects: each host within timeoutMs, `parallel` at a time,
97
+ * all before `deadline`. Resolves { open, timedOut: [hosts that did not
98
+ * answer in time], probed, cut: whether the deadline stopped it }. A refused
99
+ * or failed connect is a verdict; a timeout is not.
100
+ */
101
+ function probePass(hosts, port, { timeoutMs, parallel, deadline, connect }) {
102
+ return new Promise(resolve => {
103
+ const open = [], silent = [];
104
+ const sockets = new Set();
105
+ let next = 0, running = 0, probed = 0, done = false;
106
+ const finish = cut => {
107
+ if (done) return;
108
+ done = true;
109
+ clearTimeout(budget);
110
+ for (const s of sockets) s.destroy();
111
+ resolve({ open, timedOut: silent, probed, cut });
112
+ };
113
+ const budget = setTimeout(() => finish(true), Math.max(0, deadline - Date.now()));
114
+ const launch = () => {
115
+ if (done) return;
116
+ while (running < parallel && next < hosts.length && Date.now() < deadline) {
117
+ const host = hosts[next++];
118
+ running++;
119
+ const s = connect(host, port);
120
+ sockets.add(s);
121
+ let settled = false;
122
+ const end = verdict => {
123
+ if (settled) return;
124
+ settled = true;
125
+ sockets.delete(s);
126
+ s.destroy();
127
+ running--;
128
+ if (verdict === 'timeout') silent.push(host);
129
+ else probed++;
130
+ if (verdict === 'open') open.push(host);
131
+ if (next >= hosts.length && running === 0) finish(false);
132
+ else launch();
133
+ };
134
+ s.setTimeout(timeoutMs, () => end('timeout'));
135
+ s.once('connect', () => end('open'));
136
+ s.once('error', () => end('closed'));
137
+ }
138
+ if (next >= hosts.length && running === 0) finish(false);
139
+ };
140
+ launch();
141
+ });
142
+ }
143
+
144
+ /**
145
+ * TCP connect to port on every host: a first pass within timeoutMs each,
146
+ * PARALLEL at a time; then the hosts that only timed out (a cold ARP entry, a
147
+ * Wi-Fi radio asleep), once more within retryTimeoutMs each, RETRY_PARALLEL at
148
+ * a time. Both passes within budgetMs. Returns { open: [ip], probed, timedOut }:
149
+ * probed counts the hosts with an answer or a second chance, timedOut that
150
+ * the budget stopped the scan. Exported for tests (a listener on 127.0.0.1,
151
+ * `connect` replaced); the tool always uses 5555 and net.connect.
152
+ */
153
+ async function probeHosts(hosts, port = PORT, { timeoutMs = CONNECT_TIMEOUT_MS, retryTimeoutMs = RETRY_TIMEOUT_MS,
154
+ parallel = PARALLEL, retryParallel = RETRY_PARALLEL, budgetMs = BUDGET_MS,
155
+ connect = (host, p) => net.connect({ host, port: p }) } = {}) {
156
+ const deadline = Date.now() + budgetMs;
157
+ const first = await probePass(hosts, port, { timeoutMs, parallel, deadline, connect });
158
+ let open = first.open, probed = first.probed, cut = first.cut;
159
+ if (!cut && first.timedOut.length) {
160
+ const second = await probePass(first.timedOut, port, { timeoutMs: retryTimeoutMs, parallel: retryParallel, deadline, connect });
161
+ open = open.concat(second.open);
162
+ probed += second.probed + second.timedOut.length;
163
+ cut = second.cut;
164
+ } else if (!cut) {
165
+ probed += first.timedOut.length;
166
+ }
167
+ return { open: open.sort((a, b) => ipToInt(a) - ipToInt(b)), probed, timedOut: cut };
168
+ }
169
+
170
+ function connectedSerials(devicesOut) {
171
+ return String(devicesOut || '').split(/\r?\n/).slice(1)
172
+ .map(l => l.trim().split(/\s+/)[0]).filter(Boolean);
173
+ }
174
+
175
+ // A freshly started adb server answers `mdns services` before its mDNS
176
+ // browser has heard everything: one more ask after this pause.
177
+ const MDNS_RETRY_MS = 2000;
178
+ // Starting the adb server can take about 20 s on Windows; it is not part of
179
+ // the search's own budget.
180
+ const START_SERVER_TIMEOUT_MS = 45000;
181
+
182
+ // `adb start-server`: { started: whether this call started it, ms }.
183
+ async function startServer() {
184
+ const t = Date.now();
185
+ const r = await adb(['start-server'], { timeout: START_SERVER_TIMEOUT_MS, withStderr: true });
186
+ return { started: /daemon not running|daemon started/i.test(String(r.stderr)), ms: Date.now() - t };
187
+ }
188
+
189
+ async function mdnsServices() {
190
+ return String(await adb(['mdns', 'services'], { timeout: 10000 }));
191
+ }
192
+
193
+ // `adb mdns check`: whether adb's mDNS works at all.
194
+ async function mdnsCheck() {
195
+ const out = String(await adb(['mdns', 'check'], { timeout: 5000 }));
196
+ return !/unavailable|error/i.test(out);
197
+ }
198
+
199
+ /**
200
+ * The discovery report. `deps` replace the network and adb in tests:
201
+ * { startServer(): Promise<{ started, ms }>, mdns(): Promise<string>,
202
+ * mdnsCheck(): Promise<boolean>, devices(): Promise<string>, probe(hosts),
203
+ * interfaces, sleep(ms) }.
204
+ * The port scan runs from the start, while the adb server starts and mDNS is
205
+ * asked. mDNS is asked a second time after MDNS_RETRY_MS when this call
206
+ * started the adb server, or when the first answer is empty while
207
+ * `mdns check` works; the answers are merged.
208
+ */
209
+ async function discover({ scan = [], deps = {} } = {}) {
210
+ const t0 = Date.now();
211
+ const notes = [];
212
+ const sleep = deps.sleep || (ms => new Promise(r => setTimeout(r, ms)));
213
+
214
+ const { subnets, skipped, from } = scanSubnets({ scan, interfaces: deps.interfaces });
215
+ const hosts = subnets.flatMap(hostsOf);
216
+ const probe = deps.probe || (h => probeHosts(h, PORT));
217
+ const tcpRun = hosts.length ? probe(hosts) : Promise.resolve({ open: [], probed: 0, timedOut: false });
218
+
219
+ let server = null;
220
+ try {
221
+ server = await (deps.startServer || startServer)();
222
+ if (server.started) notes.push(`adb server started (${(server.ms / 1000).toFixed(1)} s)`);
223
+ } catch (e) {
224
+ notes.push(`adb server could not be started (${e.message.split('\n')[0]}): mDNS was not asked, only port ${PORT} was checked`);
225
+ }
226
+
227
+ let services = [];
228
+ if (server) {
229
+ const tMdns = Date.now();
230
+ const ask = () => (deps.mdns || mdnsServices)();
231
+ const first = await ask().catch(e => {
232
+ notes.push(`mDNS: not available from this adb (${e.message.split('\n')[0]})`);
233
+ return null;
234
+ });
235
+ if (first !== null) {
236
+ services = parseMdnsServices(first);
237
+ const again = server.started ||
238
+ (!services.length && await (deps.mdnsCheck || mdnsCheck)().catch(() => false));
239
+ if (again && Date.now() - tMdns + MDNS_RETRY_MS < BUDGET_MS) {
240
+ await sleep(MDNS_RETRY_MS);
241
+ const second = await ask().catch(() => null);
242
+ if (second !== null) services = services.concat(parseMdnsServices(second));
243
+ }
244
+ if (!services.length) notes.push('mDNS: no device announced Wireless debugging');
245
+ }
246
+ }
247
+
248
+ let connected = [];
249
+ if (server) {
250
+ try { connected = connectedSerials(await (deps.devices || (() => adb(['devices'])))()); } catch { /* listed as not connected */ }
251
+ }
252
+
253
+ const tcp = await tcpRun;
254
+
255
+ // One line per ip:port, with every source that found it.
256
+ const found = new Map();
257
+ const entry = addr => {
258
+ if (!found.has(addr)) found.set(addr, { addr, name: '', sources: [], kinds: new Set(), tcp: false });
259
+ return found.get(addr);
260
+ };
261
+ for (const s of services) {
262
+ const e = entry(`${s.host}:${s.port}`);
263
+ if (s.instance && !e.name) e.name = s.instance;
264
+ if (!e.sources.includes(`mDNS ${s.service}`)) e.sources.push(`mDNS ${s.service}`);
265
+ e.kinds.add(s.kind);
266
+ }
267
+ for (const ip of tcp.open) {
268
+ const e = entry(`${ip}:${PORT}`);
269
+ e.sources.push(`port ${PORT} open`);
270
+ e.tcp = true;
271
+ }
272
+ // The pairing address a device announces next to its connect address (the
273
+ // same ip, another port), while its pairing screen is open.
274
+ const pairingOf = addr => {
275
+ const ip = addr.slice(0, addr.lastIndexOf(':'));
276
+ const p = [...found.values()].find(x => x.kinds.has('pairing') && x.addr.startsWith(`${ip}:`));
277
+ return p ? p.addr : null;
278
+ };
279
+ const lines = [];
280
+ for (const e of found.values()) {
281
+ const name = e.name ? `${e.name} ` : '';
282
+ const where = `${name}${e.addr} (${e.sources.join(', ')}`;
283
+ if (e.kinds.has('pairing'))
284
+ lines.push(` ${where}) - the pairing screen is open: adb_pair host=${e.addr} code=<the 6-digit code on its screen>`);
285
+ else if (connected.includes(e.addr))
286
+ lines.push(` ${where}) - already connected`);
287
+ else if (e.tcp)
288
+ lines.push(` ${where}, network debugging) - adb_connect host=${e.addr}; if this computer is new to the device, it asks on its screen to allow debugging`);
289
+ else if (e.kinds.has('connect')) {
290
+ // Wireless debugging announces this whoever is paired: it does not say
291
+ // that this computer is.
292
+ const pairing = pairingOf(e.addr);
293
+ lines.push(pairing
294
+ ? ` ${where}) - pair first: adb_pair host=${pairing} code=<the 6-digit code on its screen>, then adb_connect host=${e.addr}`
295
+ : ` ${where}) - adb_connect host=${e.addr} if this computer is paired with the device; otherwise pair first: on the device, Wireless debugging -> Pair device with pairing code, then adb_pair`);
296
+ } else
297
+ lines.push(` ${where}) - network debugging: adb_connect host=${e.addr}`);
298
+ }
299
+
300
+ const secs = ((Date.now() - t0) / 1000).toFixed(1);
301
+ const scanned = subnets.length ? `${subnets.map(s => s.text).join(', ')} (${from})` : 'no private subnet found';
302
+ const startNote = server && server.started ? ` (${(server.ms / 1000).toFixed(1)} s of it starting the adb server)` : '';
303
+ const head = `Discovery in ${secs} s${startNote}: mDNS through adb, port ${PORT} in ${scanned}${tcp.timedOut ? `, stopped at the ${BUDGET_MS / 1000} s limit after ${tcp.probed} of ${hosts.length} addresses` : ''}. Nothing was connected.`;
304
+ const body = lines.length ? `Found:\n${lines.join('\n')}`
305
+ : 'Found nothing. Check: debugging is on on the device (Developer options: USB/network debugging, or Wireless debugging); ' +
306
+ 'the device is on the same network as this computer (not a guest network, no Wi-Fi client isolation); the TV is awake. ' +
307
+ 'An address read off the device screen works too: adb_connect host=<ip> (port 5555) or adb_pair for Wireless debugging.';
308
+ const tail = [...notes, ...(skipped.length ? [`interfaces not scanned (virtual): ${skipped.join(', ')}`] : [])];
309
+ return `${head}\n${body}${tail.length ? `\n${tail.map(n => `Note: ${n}`).join('\n')}` : ''}`;
310
+ }
311
+
312
+ module.exports = {
313
+ PORT, CONNECT_TIMEOUT_MS, PARALLEL, RETRY_TIMEOUT_MS, RETRY_PARALLEL, BUDGET_MS, VIRTUAL_IF, MDNS_RETRY_MS, START_SERVER_TIMEOUT_MS,
314
+ parseMdnsServices, scanSubnets, hostsOf, probeHosts, connectedSerials, discover,
315
+ };