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/files.js
ADDED
|
@@ -0,0 +1,453 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* files.js — installing and removing APKs, file transfer with the device.
|
|
4
|
+
*
|
|
5
|
+
* Bundles (.apks/.xapk/.apkm) are unpacked on the host and the splits are
|
|
6
|
+
* chosen from the device's actual properties. `adb install` refuses a bundle,
|
|
7
|
+
* and the device may have no `unzip`.
|
|
8
|
+
*
|
|
9
|
+
* ⚠ The ZIP reader is our own: the host may have no `unzip` either (Windows,
|
|
10
|
+
* a minimal container), a bundle is a plain ZIP and Node has zlib.
|
|
11
|
+
*
|
|
12
|
+
* ⚠ Three split naming conventions are in use and all are recognised:
|
|
13
|
+
* bundletool splits/base-master.apk, base-arm64_v8a.apk, base-ru.apk
|
|
14
|
+
* APKMirror com.foo.apk + config.arm64_v8a.apk + config.ru.apk
|
|
15
|
+
* pulled base.apk + split_config.arm64_v8a.apk
|
|
16
|
+
*
|
|
17
|
+
* ⚠ A wrong ABI is FATAL (the app does not start), a wrong density is not:
|
|
18
|
+
* density splits fail softly and the resource comes from the base APK. So no
|
|
19
|
+
* ABI match is a refusal, no density match only a skipped split.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
const fs = require('fs');
|
|
23
|
+
const path = require('path');
|
|
24
|
+
const zlib = require('zlib');
|
|
25
|
+
const { adb, withSerial, text, coerceArray, makeTempDir } = require('./adb.js');
|
|
26
|
+
const { checkHostPath } = require('./hostpath.js');
|
|
27
|
+
const { getProps } = require('./device.js');
|
|
28
|
+
|
|
29
|
+
const BUNDLE_EXT = /\.(apks|xapk|apkm)$/i;
|
|
30
|
+
|
|
31
|
+
let FILE_ROOTS = [];
|
|
32
|
+
let ROOTS_HINT;
|
|
33
|
+
|
|
34
|
+
function configure({ fileRoots = [], rootsHint } = {}) {
|
|
35
|
+
FILE_ROOTS = fileRoots.slice();
|
|
36
|
+
ROOTS_HINT = rootsHint;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function hostPath(p, what) {
|
|
40
|
+
return checkHostPath(p, { roots: FILE_ROOTS, setting: 'file_roots', what, emptyHint: ROOTS_HINT });
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Android density buckets; tvdpi is common on TV boxes.
|
|
44
|
+
const DENSITY_BUCKETS = {
|
|
45
|
+
ldpi: 120, mdpi: 160, tvdpi: 213, hdpi: 240,
|
|
46
|
+
xhdpi: 320, xxhdpi: 480, xxxhdpi: 640,
|
|
47
|
+
};
|
|
48
|
+
const DENSITY_ANY = new Set(['nodpi', 'anydpi']);
|
|
49
|
+
|
|
50
|
+
const KNOWN_ABIS = new Set([
|
|
51
|
+
'armeabi', 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64', 'mips', 'mips64',
|
|
52
|
+
]);
|
|
53
|
+
|
|
54
|
+
const normAbi = s => String(s || '').replace(/_/g, '-').replace(/^x86-64$/, 'x86_64');
|
|
55
|
+
|
|
56
|
+
// ───────────────────────── minimal ZIP reader ─────────────────────────
|
|
57
|
+
|
|
58
|
+
function findEOCD(buf) {
|
|
59
|
+
const maxBack = Math.min(buf.length, 65557); // 22 + the longest comment
|
|
60
|
+
for (let i = buf.length - 22; i >= buf.length - maxBack && i >= 0; i--) {
|
|
61
|
+
if (buf.readUInt32LE(i) === 0x06054b50) return i;
|
|
62
|
+
}
|
|
63
|
+
return -1;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The ZIP entries, from the central directory. */
|
|
67
|
+
function zipEntries(buf) {
|
|
68
|
+
const eocd = findEOCD(buf);
|
|
69
|
+
if (eocd < 0) throw new Error('not a ZIP: End of Central Directory not found');
|
|
70
|
+
const count = buf.readUInt16LE(eocd + 10);
|
|
71
|
+
let off = buf.readUInt32LE(eocd + 16);
|
|
72
|
+
if (off === 0xffffffff || count === 0xffff)
|
|
73
|
+
throw new Error('ZIP64 bundles are not supported');
|
|
74
|
+
|
|
75
|
+
const entries = [];
|
|
76
|
+
for (let i = 0; i < count; i++) {
|
|
77
|
+
if (buf.readUInt32LE(off) !== 0x02014b50)
|
|
78
|
+
throw new Error(`corrupt ZIP central directory at entry ${i}`);
|
|
79
|
+
const method = buf.readUInt16LE(off + 10);
|
|
80
|
+
const compSize = buf.readUInt32LE(off + 20);
|
|
81
|
+
const size = buf.readUInt32LE(off + 24);
|
|
82
|
+
const nameLen = buf.readUInt16LE(off + 28);
|
|
83
|
+
const extraLen = buf.readUInt16LE(off + 30);
|
|
84
|
+
const cmtLen = buf.readUInt16LE(off + 32);
|
|
85
|
+
const attr = buf.readUInt32LE(off + 38); // external attributes: the unix mode in the high 16 bits
|
|
86
|
+
const local = buf.readUInt32LE(off + 42);
|
|
87
|
+
const name = buf.toString('utf8', off + 46, off + 46 + nameLen);
|
|
88
|
+
entries.push({ name, method, compSize, size, local, attr });
|
|
89
|
+
off += 46 + nameLen + extraLen + cmtLen;
|
|
90
|
+
}
|
|
91
|
+
return entries;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function zipRead(buf, e) {
|
|
95
|
+
if (buf.readUInt32LE(e.local) !== 0x04034b50)
|
|
96
|
+
throw new Error(`corrupt local header: ${e.name}`);
|
|
97
|
+
const nameLen = buf.readUInt16LE(e.local + 26);
|
|
98
|
+
const extraLen = buf.readUInt16LE(e.local + 28);
|
|
99
|
+
const start = e.local + 30 + nameLen + extraLen;
|
|
100
|
+
const raw = buf.subarray(start, start + e.compSize);
|
|
101
|
+
if (e.method === 0) return raw;
|
|
102
|
+
if (e.method === 8) return zlib.inflateRawSync(raw);
|
|
103
|
+
throw new Error(`unsupported compression method ${e.method} in ${e.name}`);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* The file name a bundle entry is written under: its last segment by either
|
|
108
|
+
* separator. Empty, ".", "..", or a name with ":" or NUL is refused, so an
|
|
109
|
+
* entry such as `a\..\..\x.apk` cannot leave the temporary directory on
|
|
110
|
+
* Windows.
|
|
111
|
+
*/
|
|
112
|
+
function safeEntryName(name) {
|
|
113
|
+
const base = String(name).split(/[\\/]/).pop();
|
|
114
|
+
if (!base || base === '.' || base === '..' || /[:\0]/.test(base))
|
|
115
|
+
throw new Error(`unsafe file name in the bundle: ${JSON.stringify(String(name)).slice(0, 120)}`);
|
|
116
|
+
return base;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// ──────────────────── classifying and choosing splits ────────────────────
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* The split qualifier of a file name; null for the base APK (base, master,
|
|
123
|
+
* universal, or the package name itself).
|
|
124
|
+
*/
|
|
125
|
+
function qualifierOf(entryName) {
|
|
126
|
+
const file = entryName.split('/').pop();
|
|
127
|
+
const stem = file.replace(/\.apk$/i, '');
|
|
128
|
+
|
|
129
|
+
// base.apk / <pkg>.apk / universal.apk / *-master.apk are bases
|
|
130
|
+
if (/^(base|universal)$/i.test(stem)) return null;
|
|
131
|
+
if (/-master$/i.test(stem)) return null;
|
|
132
|
+
|
|
133
|
+
// config.<q> / split_config.<q> / split_config_<q>
|
|
134
|
+
let m = /(?:^|[._-])config[._-](.+)$/i.exec(stem);
|
|
135
|
+
if (m) return m[1];
|
|
136
|
+
|
|
137
|
+
// bundletool: <module>-<q>
|
|
138
|
+
m = /^[A-Za-z0-9_]+-(.+)$/.exec(stem);
|
|
139
|
+
if (m) return m[1];
|
|
140
|
+
|
|
141
|
+
return null; // the whole package name => base
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function classify(q) {
|
|
145
|
+
if (!q) return { kind: 'base' };
|
|
146
|
+
const abi = normAbi(q);
|
|
147
|
+
if (KNOWN_ABIS.has(abi)) return { kind: 'abi', value: abi };
|
|
148
|
+
const low = q.toLowerCase();
|
|
149
|
+
if (DENSITY_BUCKETS[low] !== undefined) return { kind: 'density', value: low };
|
|
150
|
+
if (DENSITY_ANY.has(low)) return { kind: 'density_any', value: low };
|
|
151
|
+
// locale: ru, en, pt_BR, b+sr+Latn
|
|
152
|
+
if (/^[a-z]{2,3}([_-][A-Za-z]{2,4})?$/.test(q) || /^b\+/.test(q))
|
|
153
|
+
return { kind: 'locale', value: q.replace(/^b\+/, '').replace(/\+/g, '-') };
|
|
154
|
+
return { kind: 'unknown', value: q };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Choose the splits for a device. props: what device.getProps returns
|
|
159
|
+
* (abilist/density/locale).
|
|
160
|
+
*/
|
|
161
|
+
function chooseSplits(names, props, opts = {}) {
|
|
162
|
+
const items = names.map(n => ({ name: n, ...classify(qualifierOf(n)) }));
|
|
163
|
+
|
|
164
|
+
const bases = items.filter(i => i.kind === 'base');
|
|
165
|
+
const chosen = [];
|
|
166
|
+
const notes = [];
|
|
167
|
+
|
|
168
|
+
// universal.apk alone is a standalone build: no splits needed
|
|
169
|
+
const universal = names.find(n => /(^|\/)universal\.apk$/i.test(n));
|
|
170
|
+
const hasSplits = items.some(i => ['abi', 'density', 'locale'].includes(i.kind));
|
|
171
|
+
if (universal && !hasSplits) {
|
|
172
|
+
return { chosen: [universal], notes: ['bundle holds only universal.apk - installed as a plain APK'], items };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
if (!bases.length) throw new Error('no base APK in the bundle (base/master/<package>.apk)');
|
|
176
|
+
// Every master module (install-time feature modules) goes in whole
|
|
177
|
+
chosen.push(...bases.map(b => b.name));
|
|
178
|
+
|
|
179
|
+
// ── ABI: a mistake here is fatal, so a miss is a refusal ──
|
|
180
|
+
const abiItems = items.filter(i => i.kind === 'abi');
|
|
181
|
+
if (abiItems.length) {
|
|
182
|
+
const want = (opts.abi ? [normAbi(opts.abi)] : (props.abilist || []).map(normAbi));
|
|
183
|
+
const hit = want.map(a => abiItems.find(i => i.value === a)).find(Boolean);
|
|
184
|
+
if (!hit) {
|
|
185
|
+
throw new Error(
|
|
186
|
+
(opts.abi
|
|
187
|
+
? `no split for ABI "${opts.abi}" (device reports: ${(props.abilist || []).join(', ') || 'ABI unknown'}). `
|
|
188
|
+
: `no split for any ABI of the device (${(props.abilist || []).join(', ') || 'ABI unknown'}). `) +
|
|
189
|
+
`Available: ${abiItems.map(i => i.value).join(', ')}. Install cancelled.`);
|
|
190
|
+
}
|
|
191
|
+
chosen.push(hit.name);
|
|
192
|
+
notes.push(`ABI: ${hit.value} (device: ${(props.abilist || []).join(', ')})`);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// ── Density: a miss is not fatal, the base APK has the resource ──
|
|
196
|
+
const densItems = items.filter(i => i.kind === 'density');
|
|
197
|
+
if (densItems.length) {
|
|
198
|
+
const target = Number(opts.density || props.density) || null;
|
|
199
|
+
if (!target) {
|
|
200
|
+
notes.push('device density not determined - density split skipped (resources come from the base APK)');
|
|
201
|
+
} else {
|
|
202
|
+
let best = null, bestDelta = Infinity;
|
|
203
|
+
for (const i of densItems) {
|
|
204
|
+
const d = Math.abs(DENSITY_BUCKETS[i.value] - target);
|
|
205
|
+
if (d < bestDelta) { best = i; bestDelta = d; }
|
|
206
|
+
}
|
|
207
|
+
chosen.push(best.name);
|
|
208
|
+
notes.push(bestDelta === 0
|
|
209
|
+
? `density: ${best.value} (${target} dpi, exact match)`
|
|
210
|
+
: `density: ${best.value} - no exact bucket for ${target} dpi in the bundle, nearest used (a density mismatch is not fatal)`);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
for (const i of items.filter(i => i.kind === 'density_any')) chosen.push(i.name);
|
|
214
|
+
|
|
215
|
+
// ── Locales: the device language plus everything asked for ──
|
|
216
|
+
const locItems = items.filter(i => i.kind === 'locale');
|
|
217
|
+
if (locItems.length) {
|
|
218
|
+
const wanted = new Set();
|
|
219
|
+
const devLang = String(props.locale || '').split('-')[0].toLowerCase();
|
|
220
|
+
if (devLang) wanted.add(devLang);
|
|
221
|
+
for (const l of coerceArray(opts.locales || [])) {
|
|
222
|
+
const s = String(l || '').split(/[-_]/)[0].toLowerCase();
|
|
223
|
+
if (s) wanted.add(s);
|
|
224
|
+
}
|
|
225
|
+
const picked = locItems.filter(i => wanted.has(String(i.value).split(/[-_]/)[0].toLowerCase()));
|
|
226
|
+
chosen.push(...picked.map(i => i.name));
|
|
227
|
+
if (picked.length)
|
|
228
|
+
notes.push(`locales: ${picked.map(i => i.value).join(', ')} (device language: ${devLang || '?'})`);
|
|
229
|
+
else
|
|
230
|
+
notes.push(`locales: no matching split (device language: ${devLang || '?'}; bundle has: ${locItems.map(i => i.value).join(', ')}) - strings come from the base APK`);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const unknown = items.filter(i => i.kind === 'unknown');
|
|
234
|
+
if (unknown.length)
|
|
235
|
+
notes.push(`not recognised, skipped: ${unknown.map(i => i.value).join(', ')}`);
|
|
236
|
+
|
|
237
|
+
return { chosen: Array.from(new Set(chosen)), notes, items };
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** Unpack a bundle into a temporary directory and choose the splits. */
|
|
241
|
+
function unpackBundle(bundlePath, props, opts) {
|
|
242
|
+
const buf = fs.readFileSync(bundlePath);
|
|
243
|
+
const entries = zipEntries(buf).filter(e => /\.apk$/i.test(e.name) && !e.name.endsWith('/'));
|
|
244
|
+
if (!entries.length) throw new Error('no .apk inside the bundle');
|
|
245
|
+
|
|
246
|
+
// standalones/ are builds for old devices without split support; next to
|
|
247
|
+
// splits/ they only confuse the choice.
|
|
248
|
+
const hasSplitsDir = entries.some(e => /(^|\/)splits\//i.test(e.name));
|
|
249
|
+
const usable = hasSplitsDir
|
|
250
|
+
? entries.filter(e => !/(^|\/)standalones\//i.test(e.name))
|
|
251
|
+
: entries;
|
|
252
|
+
|
|
253
|
+
const sel = chooseSplits(usable.map(e => e.name), props, opts);
|
|
254
|
+
const names = sel.chosen.map(name => ({ name, file: safeEntryName(name) }));
|
|
255
|
+
|
|
256
|
+
const dir = makeTempDir('apks-');
|
|
257
|
+
const files = [];
|
|
258
|
+
try {
|
|
259
|
+
for (const { name, file } of names) {
|
|
260
|
+
const e = usable.find(x => x.name === name);
|
|
261
|
+
const out = path.join(dir, file);
|
|
262
|
+
fs.writeFileSync(out, zipRead(buf, e));
|
|
263
|
+
files.push(out);
|
|
264
|
+
}
|
|
265
|
+
} catch (err) {
|
|
266
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
267
|
+
throw err;
|
|
268
|
+
}
|
|
269
|
+
return { dir, files, notes: sel.notes, total: usable.length };
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* dry_run of adb_install. Only an explicit false installs: the boolean, or the
|
|
274
|
+
* string "false" from clients that send booleans as strings. Everything else,
|
|
275
|
+
* absence included, reports without installing. coerceBool would not do here:
|
|
276
|
+
* it turns everything but "true" into false, so `1`, "0" or "yes" would
|
|
277
|
+
* install. implicit: the parameter was not passed at all.
|
|
278
|
+
*/
|
|
279
|
+
function installDryRun(v) {
|
|
280
|
+
const implicit = v === undefined || v === null || v === '';
|
|
281
|
+
const explicitFalse = v === false || (typeof v === 'string' && v.trim().toLowerCase() === 'false');
|
|
282
|
+
return { dryRun: !explicitFalse, implicit };
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
const DRY_RUN_TAIL = 'dry_run - nothing installed. Repeat with dry_run=false.';
|
|
286
|
+
const DRY_RUN_DEFAULT_NOTE = 'dry_run was not passed - adb_install only reports unless dry_run=false.';
|
|
287
|
+
|
|
288
|
+
function dryRunFooter(dr) {
|
|
289
|
+
return (dr.implicit ? `${DRY_RUN_DEFAULT_NOTE}\n` : '') + DRY_RUN_TAIL;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function deviceLine(props) {
|
|
293
|
+
return `Device: SDK ${props.sdk}, ABI ${(props.abilist || []).join(',') || '?'}, ` +
|
|
294
|
+
`${props.density || '?'} dpi, locale ${props.locale || '?'}`;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// ───────────────────────── installable files ─────────────────────────
|
|
298
|
+
// adb_install without apk_path: what can be installed, without adb. The
|
|
299
|
+
// server never downloads APKs: a person puts them into a file_roots folder.
|
|
300
|
+
|
|
301
|
+
const INSTALLABLE = /\.(apk|apks|xapk|apkm)$/i;
|
|
302
|
+
const LIST_LIMIT = 50;
|
|
303
|
+
const DEPTH_HINT = 'Only the top level and one level of subfolders are listed; for a deeper folder pass dir.';
|
|
304
|
+
|
|
305
|
+
function localTime(d) {
|
|
306
|
+
const p = n => String(n).padStart(2, '0');
|
|
307
|
+
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
function sizeText(n) {
|
|
311
|
+
return n >= 1048576 ? `${(n / 1048576).toFixed(1)} MB` : `${Math.max(1, Math.round(n / 1024))} KB`;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Installable files in `bases` and one folder level below them. Hidden
|
|
316
|
+
* entries (a leading dot) are skipped; every entry passes the host path check,
|
|
317
|
+
* so a symlink or junction that leads out of the roots is not followed.
|
|
318
|
+
* Returns [{ path, size, mtime }], newest first.
|
|
319
|
+
*/
|
|
320
|
+
function findInstallables(bases, roots) {
|
|
321
|
+
const seen = new Set();
|
|
322
|
+
const found = [];
|
|
323
|
+
const inRoots = p => { try { checkHostPath(p, { roots }); return true; } catch { return false; } };
|
|
324
|
+
const scan = (dir, depth) => {
|
|
325
|
+
let names;
|
|
326
|
+
try { names = fs.readdirSync(dir); } catch { return; }
|
|
327
|
+
for (const name of names) {
|
|
328
|
+
if (name.startsWith('.')) continue;
|
|
329
|
+
const full = path.join(dir, name);
|
|
330
|
+
if (!inRoots(full)) continue;
|
|
331
|
+
let st;
|
|
332
|
+
try { st = fs.statSync(full); } catch { continue; }
|
|
333
|
+
if (st.isDirectory()) { if (depth === 0) scan(full, 1); continue; }
|
|
334
|
+
if (!st.isFile() || !INSTALLABLE.test(name) || seen.has(full)) continue;
|
|
335
|
+
seen.add(full);
|
|
336
|
+
found.push({ path: full, size: st.size, mtime: st.mtime });
|
|
337
|
+
}
|
|
338
|
+
};
|
|
339
|
+
for (const b of bases) scan(b, 0);
|
|
340
|
+
return found.sort((a, b) => b.mtime - a.mtime || a.path.localeCompare(b.path));
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
function listInstallables(args) {
|
|
344
|
+
if (!FILE_ROOTS.length)
|
|
345
|
+
throw new Error(`adb_install has no folder to list: file_roots is empty, so no folder on this computer is open to the tools. To open one, ${ROOTS_HINT || 'run `brickproof-adb set file_roots <folder>` and restart the server'}.`);
|
|
346
|
+
const bases = args.dir !== undefined && args.dir !== null && String(args.dir).trim() !== ''
|
|
347
|
+
? [hostPath(String(args.dir), 'dir')]
|
|
348
|
+
: FILE_ROOTS.slice();
|
|
349
|
+
const where = bases.join(', ');
|
|
350
|
+
const files = findInstallables(bases, FILE_ROOTS);
|
|
351
|
+
if (!files.length)
|
|
352
|
+
return text(`No .apk, .apks, .xapk or .apkm file in ${where} (the folder itself and one folder below). ` +
|
|
353
|
+
`Download or copy the file into one of these folders, then call adb_install again; nothing was installed.\n${DEPTH_HINT}`);
|
|
354
|
+
const shown = files.slice(0, LIST_LIMIT).map(f => ` ${f.path} ${sizeText(f.size)} ${localTime(f.mtime)}`);
|
|
355
|
+
const more = files.length > LIST_LIMIT ? `\n …and ${files.length - LIST_LIMIT} more` : '';
|
|
356
|
+
return text(`Installable files in ${where} (the folder itself and one folder below), newest first:\n${shown.join('\n')}${more}\n` +
|
|
357
|
+
`Nothing was installed. Install one with adb_install apk_path=<path from this list>; it reports first unless dry_run=false.\n${DEPTH_HINT}`);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
async function install(args) {
|
|
361
|
+
const rawPaths = coerceArray(args.apk_path).filter(p => typeof p === 'string' && p.trim() !== '');
|
|
362
|
+
if (rawPaths.length === 0) return listInstallables(args);
|
|
363
|
+
const dr = installDryRun(args.dry_run);
|
|
364
|
+
|
|
365
|
+
// ── a bundle ──
|
|
366
|
+
if (rawPaths.length === 1 && BUNDLE_EXT.test(rawPaths[0])) {
|
|
367
|
+
const bundle = hostPath(rawPaths[0], 'apk_path');
|
|
368
|
+
if (!fs.existsSync(bundle)) throw new Error(`Bundle not found: ${bundle}`);
|
|
369
|
+
|
|
370
|
+
const props = await getProps(args.serial);
|
|
371
|
+
let tmp = null;
|
|
372
|
+
try {
|
|
373
|
+
tmp = unpackBundle(bundle, props, { abi: args.abi, density: args.density, locales: args.locales });
|
|
374
|
+
|
|
375
|
+
const head =
|
|
376
|
+
`Bundle: ${path.basename(bundle)} (${tmp.total} apk inside)\n` +
|
|
377
|
+
`${deviceLine(props)}\n` +
|
|
378
|
+
`Chose ${tmp.files.length}: ${tmp.files.map(f => path.basename(f)).join(', ')}\n` +
|
|
379
|
+
tmp.notes.map(n => ` · ${n}`).join('\n');
|
|
380
|
+
|
|
381
|
+
if (dr.dryRun)
|
|
382
|
+
return text(`${head}\n\n${dryRunFooter(dr)}`);
|
|
383
|
+
|
|
384
|
+
const verb = tmp.files.length > 1 ? 'install-multiple' : 'install';
|
|
385
|
+
const out = await adb(withSerial(args.serial, [verb, '-r', '-t', '-g', ...tmp.files]), { timeout: 300000 });
|
|
386
|
+
return text(`${head}\n\n${verb}: ${out.trim() || 'OK'}`);
|
|
387
|
+
} finally {
|
|
388
|
+
if (tmp && tmp.dir) fs.rmSync(tmp.dir, { recursive: true, force: true });
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// ── plain APKs / a list of splits ──
|
|
393
|
+
const apks = rawPaths.map(p => {
|
|
394
|
+
const r = hostPath(p, 'apk_path');
|
|
395
|
+
if (!fs.existsSync(r)) throw new Error(`APK not found: ${r}`);
|
|
396
|
+
return r;
|
|
397
|
+
});
|
|
398
|
+
const verb = apks.length > 1 ? 'install-multiple' : 'install';
|
|
399
|
+
|
|
400
|
+
// The paths are checked above, so the report and the install refuse alike.
|
|
401
|
+
if (dr.dryRun) {
|
|
402
|
+
const props = await getProps(args.serial);
|
|
403
|
+
const lines = apks.map(p => ` ${p} (${fs.statSync(p).size} bytes)`);
|
|
404
|
+
return text(
|
|
405
|
+
`APK: ${apks.length} file${apks.length === 1 ? '' : 's'}\n${lines.join('\n')}\n` +
|
|
406
|
+
`${deviceLine(props)}\n` +
|
|
407
|
+
`Would run: ${verb} -r -t -g ${apks.map(p => path.basename(p)).join(' ')} ` +
|
|
408
|
+
`on ${args.serial || 'the only connected device'}\n\n${dryRunFooter(dr)}`);
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
const out = await adb(withSerial(args.serial, [verb, '-r', '-t', '-g', ...apks]), { timeout: 180000 });
|
|
412
|
+
return text(out.trim() || `${verb}: ${apks.length} file(s) OK`);
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
async function uninstall(args) {
|
|
416
|
+
const a = ['uninstall'];
|
|
417
|
+
if (args.keep_data === true || args.keep_data === 'true') a.push('-k');
|
|
418
|
+
a.push(args.package);
|
|
419
|
+
// Counted by the package list afterwards, as adb_app counts its changes.
|
|
420
|
+
const [r] = await require('./apps.js').applyVerified(args.serial, [
|
|
421
|
+
{ package: args.package, change: 'uninstall', run: () => adb(withSerial(args.serial, a), { timeout: 60000 }) },
|
|
422
|
+
]);
|
|
423
|
+
// Without a package list the device's own error stays as it is (a lost
|
|
424
|
+
// device is recognised by it).
|
|
425
|
+
if (!r.ok) throw new Error(/^not removed/.test(r.error) ? `${args.package}: ${r.error}` : r.error);
|
|
426
|
+
return text(r.out + (r.warning ? `\nWarning: ${r.warning}` : ''));
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
async function push(args) {
|
|
430
|
+
const src = hostPath(args.host_path, 'host_path');
|
|
431
|
+
if (!fs.existsSync(src)) throw new Error(`File not found: ${src}`);
|
|
432
|
+
const size = fs.statSync(src).size;
|
|
433
|
+
// adb push prints its statistics to stderr when stdout is not a TTY
|
|
434
|
+
const r = await adb(withSerial(args.serial, ['push', src, args.device_path]), { timeout: 120000, withStderr: true });
|
|
435
|
+
const out = `${r.stdout}\n${r.stderr}`.trim();
|
|
436
|
+
return text(out || `Pushed ${src} -> ${args.device_path} (${size} bytes)`);
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
async function pull(args) {
|
|
440
|
+
const dst = hostPath(args.host_path, 'host_path');
|
|
441
|
+
fs.mkdirSync(path.dirname(dst), { recursive: true });
|
|
442
|
+
const r = await adb(withSerial(args.serial, ['pull', args.device_path, dst]), { timeout: 120000, withStderr: true });
|
|
443
|
+
const out = `${r.stdout}\n${r.stderr}`.trim();
|
|
444
|
+
let size = 0;
|
|
445
|
+
try { const st = fs.statSync(dst); size = st.isFile() ? st.size : 0; } catch { /* ignore */ }
|
|
446
|
+
return text(out || `Pulled ${args.device_path} -> ${dst}${size ? ` (${size} bytes)` : ''}`);
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
module.exports = {
|
|
450
|
+
configure, install, uninstall, push, pull, findInstallables, LIST_LIMIT,
|
|
451
|
+
zipEntries, zipRead, qualifierOf, classify, chooseSplits, unpackBundle, safeEntryName,
|
|
452
|
+
installDryRun, DRY_RUN_TAIL, DRY_RUN_DEFAULT_NOTE,
|
|
453
|
+
};
|
package/src/hostpath.js
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* hostpath.js — the one check for host paths: adb_push, adb_pull, adb_install,
|
|
4
|
+
* the adb_app store and every backup path read back from a snapshot.
|
|
5
|
+
*
|
|
6
|
+
* A path is accepted when it is absolute, lies inside one of the roots, and
|
|
7
|
+
* the real place of its nearest existing ancestor (the file of a pull may not
|
|
8
|
+
* exist yet) lies inside the real place of one of the roots, so a symlink or a
|
|
9
|
+
* junction that leads out is refused. "Inside" is path.relative() not
|
|
10
|
+
* climbing out, never a prefix test: /media2 is not inside /media. Windows
|
|
11
|
+
* and macOS compare without regard to letter case. On Windows UNC and device
|
|
12
|
+
* paths (\\server\share, \\?\, \\.\) and paths without a drive letter are
|
|
13
|
+
* refused.
|
|
14
|
+
*
|
|
15
|
+
* Nothing here creates a directory: callers check first, then mkdir.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
const fs = require('fs');
|
|
19
|
+
const path = require('path');
|
|
20
|
+
|
|
21
|
+
function caseInsensitive(platform = process.platform) {
|
|
22
|
+
return platform === 'win32' || platform === 'darwin';
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function fold(s) {
|
|
26
|
+
return caseInsensitive() ? s.toLowerCase() : s;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Whether p is root itself or below it (both absolute). */
|
|
30
|
+
function inside(p, root) {
|
|
31
|
+
const rel = path.relative(fold(root), fold(p));
|
|
32
|
+
if (rel === '') return true;
|
|
33
|
+
if (path.isAbsolute(rel)) return false;
|
|
34
|
+
return rel !== '..' && !rel.startsWith('..' + path.sep);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// realpath of the nearest existing ancestor, with the missing tail appended.
|
|
38
|
+
function realWithTail(p) {
|
|
39
|
+
const tail = [];
|
|
40
|
+
let probe = p;
|
|
41
|
+
for (;;) {
|
|
42
|
+
let real;
|
|
43
|
+
try {
|
|
44
|
+
real = fs.realpathSync.native(probe);
|
|
45
|
+
} catch (e) {
|
|
46
|
+
if (e.code !== 'ENOENT' && e.code !== 'ENOTDIR') throw e;
|
|
47
|
+
const up = path.dirname(probe);
|
|
48
|
+
if (up === probe) return p;
|
|
49
|
+
tail.unshift(path.basename(probe));
|
|
50
|
+
probe = up;
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
return tail.length ? path.join(real, ...tail) : real;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function describeRoots(roots) {
|
|
58
|
+
const shown = roots.join(', ');
|
|
59
|
+
return roots.length <= 3 && shown.length <= 200 ? shown : `${roots.length} directories`;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
class HostPathError extends Error {
|
|
63
|
+
constructor(message) {
|
|
64
|
+
super(message);
|
|
65
|
+
this.name = 'HostPathError';
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Check a host path. Returns the absolute (lexical) path or throws
|
|
71
|
+
* HostPathError naming the setting.
|
|
72
|
+
* roots allowed directories (absolute)
|
|
73
|
+
* exact paths accepted as they are, not their contents (the store setting
|
|
74
|
+
* for the adb_app store parameter)
|
|
75
|
+
* setting the setting the refusal names: 'file_roots' or 'store'
|
|
76
|
+
* what what the path is for, for the message
|
|
77
|
+
*/
|
|
78
|
+
const DEFAULT_ROOTS_HINT = 'run `brickproof-adb set file_roots <folder>` and restart the server';
|
|
79
|
+
|
|
80
|
+
function checkHostPath(p, { roots = [], exact = [], setting = 'file_roots', what = 'host path', emptyHint = DEFAULT_ROOTS_HINT } = {}) {
|
|
81
|
+
if (typeof p !== 'string' || !p.trim()) throw new HostPathError(`${what} must be a non-empty string`);
|
|
82
|
+
if (p.includes('\0')) throw new HostPathError(`${what} contains a NUL character`);
|
|
83
|
+
if (process.platform === 'win32') {
|
|
84
|
+
if (/^[\\/]{2}/.test(p)) throw new HostPathError(`${what} ${p}: UNC and device paths (\\\\server\\share, \\\\?\\, \\\\.\\) are not accepted`);
|
|
85
|
+
if (!/^[A-Za-z]:[\\/]/.test(p)) throw new HostPathError(`${what} ${p} must be an absolute path with a drive letter`);
|
|
86
|
+
}
|
|
87
|
+
if (!path.isAbsolute(p)) throw new HostPathError(`${what} ${p} must be an absolute path`);
|
|
88
|
+
const resolved = path.resolve(p);
|
|
89
|
+
|
|
90
|
+
for (const e of exact) {
|
|
91
|
+
if (e && inside(resolved, e) && inside(e, resolved)) return resolved;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (!roots.length) {
|
|
95
|
+
throw new HostPathError(setting === 'store'
|
|
96
|
+
? `${what} ${p}: the snapshot store must be the store setting or a directory inside file_roots, and file_roots is empty`
|
|
97
|
+
: `${what} ${p} is refused: file_roots is empty, so no folder on this computer is open to the tools. To open one, ${emptyHint}.`);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const lexical = roots.filter(r => inside(resolved, r));
|
|
101
|
+
const refuse = why => new HostPathError(`${what} ${p} is outside the allowed directories (${setting}: ${describeRoots(setting === 'store' ? [...exact, ...roots] : roots)})${why}`);
|
|
102
|
+
if (!lexical.length) throw refuse('');
|
|
103
|
+
|
|
104
|
+
const real = realWithTail(resolved);
|
|
105
|
+
const realRoots = roots.map(r => realWithTail(path.resolve(r)));
|
|
106
|
+
if (!realRoots.some(r => inside(real, r))) throw refuse(' - a symlink or junction on the way leads out of them');
|
|
107
|
+
return resolved;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
module.exports = { checkHostPath, HostPathError, inside, caseInsensitive };
|