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/apps.js
ADDED
|
@@ -0,0 +1,1156 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* apps.js — the `adb_app` tool: package operations with guard rails.
|
|
4
|
+
*
|
|
5
|
+
* 1. dry_run defaults to true for everything that changes state.
|
|
6
|
+
* 2. The protected set is derived from the device (device.js) and is a
|
|
7
|
+
* refusal in code, not a warning in a description. Any overlap means
|
|
8
|
+
* nothing is applied at all: a partial run is worse than a refusal.
|
|
9
|
+
* 3. An account canary after EVERY batch. Losing the device registration is
|
|
10
|
+
* a latent failure: the system boots and apps run, and it only shows in
|
|
11
|
+
* the store.
|
|
12
|
+
* 4. Everything applied goes into a snapshot, so one call rolls it back.
|
|
13
|
+
* 5. `uninstall --user 0` sits behind three locks: the allow_uninstall
|
|
14
|
+
* setting, an explicit mode in the call and a successful APK backup. A
|
|
15
|
+
* system package comes back with `cmd package install-existing`; a
|
|
16
|
+
* sideloaded one only from its backup.
|
|
17
|
+
* 6. A network guard on destructive actions: a package that serves a client
|
|
18
|
+
* outside the device right now (LISTEN plus an inbound ESTABLISHED from a
|
|
19
|
+
* non-loopback address) is not disabled, removed, stopped or cleared
|
|
20
|
+
* without `force_network`.
|
|
21
|
+
*
|
|
22
|
+
* ⚠ The guard has its own flag, apart from `force`. `force` exists to go on
|
|
23
|
+
* after a failed APK backup; one flag for both would lift the guard as a side
|
|
24
|
+
* effect of a decision about backups.
|
|
25
|
+
*
|
|
26
|
+
* Snapshot store layout: <store>/<key>/state.json and <store>/<key>/apk/...,
|
|
27
|
+
* where <key> is the device (`<ro.product.model>_<ro.serialno>`), so one
|
|
28
|
+
* device over USB, ip:5555 and wireless debugging shares one snapshot. A
|
|
29
|
+
* missing, "unknown" or shared serial falls back to the connection serial.
|
|
30
|
+
* Backups recorded since are relative to the device directory; older absolute
|
|
31
|
+
* ones are read as they are, and every one is checked against the store
|
|
32
|
+
* before an install.
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
const fs = require('fs');
|
|
36
|
+
const path = require('path');
|
|
37
|
+
const {
|
|
38
|
+
adb, adbSh, withSerial, sq, text, json,
|
|
39
|
+
coerceArray, coerceBool, coerceObject, ensureDir, sanitizeSerial, renameWithRetry,
|
|
40
|
+
} = require('./adb.js');
|
|
41
|
+
const { checkHostPath } = require('./hostpath.js');
|
|
42
|
+
const {
|
|
43
|
+
getProps, listPackages, accountSnapshot, protectedSet,
|
|
44
|
+
netListeners, servingHits, servingRefusal, resumedActivity, splitMarked, markedCommand,
|
|
45
|
+
CORE_PROTECTED, CORE_PREFIXES,
|
|
46
|
+
} = require('./device.js');
|
|
47
|
+
|
|
48
|
+
const DEFAULT_BATCH = 5;
|
|
49
|
+
|
|
50
|
+
// dry_run when it is not passed, per action: what changes packages or wipes
|
|
51
|
+
// data reports first; stop and backup act at once.
|
|
52
|
+
const DRY_RUN_DEFAULT = { disable: true, uninstall: true, enable: true, restore: true, clear: true, stop: false, backup: false };
|
|
53
|
+
// Actions that only read.
|
|
54
|
+
const READ_ONLY_ACTIONS = new Set(['list', 'info', 'protected', 'state']);
|
|
55
|
+
|
|
56
|
+
/** The dry_run in force for an action: as passed, else its default; null for an action without one. */
|
|
57
|
+
function dryRunOf(action, args) {
|
|
58
|
+
const dflt = DRY_RUN_DEFAULT[action];
|
|
59
|
+
return dflt === undefined ? null : coerceBool(args.dry_run, dflt);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const DEFAULT_HINTS = {
|
|
63
|
+
allow_shell: 'run `brickproof-adb set allow_shell on` and restart the server',
|
|
64
|
+
allow_uninstall: 'run `brickproof-adb set allow_uninstall on` and restart the server',
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
const OPTS = { allowShell: false, allowUninstall: false, store: null, fileRoots: [], hints: DEFAULT_HINTS };
|
|
68
|
+
|
|
69
|
+
function configure({ allowShell = false, allowUninstall = false, store = null, fileRoots = [], hints = {} } = {}) {
|
|
70
|
+
OPTS.hints = { ...DEFAULT_HINTS, ...hints };
|
|
71
|
+
OPTS.allowShell = allowShell === true;
|
|
72
|
+
OPTS.allowUninstall = allowUninstall === true;
|
|
73
|
+
OPTS.store = store;
|
|
74
|
+
OPTS.fileRoots = fileRoots.slice();
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// ------------------------------------------------------------------- store
|
|
78
|
+
|
|
79
|
+
// ro.serialno values shared by many devices: a key built on one of them could
|
|
80
|
+
// send a rollback to another device. Compared in upper case.
|
|
81
|
+
const SHARED_SERIALS = new Set([
|
|
82
|
+
'UNKNOWN', 'NULL', '0123456789ABCDEF', '0123456789', '1234567890', '123456789ABCDEF', '1234567890ABCDEF',
|
|
83
|
+
'00000000', '000000000000', '0000000000000000',
|
|
84
|
+
]);
|
|
85
|
+
|
|
86
|
+
function deviceSerialUsable(s) {
|
|
87
|
+
const v = String(s || '').trim();
|
|
88
|
+
return !!v && !SHARED_SERIALS.has(v.toUpperCase());
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const CONNECTION_NOTE = 'the snapshot is bound to this connection, not to the device: ro.serialno is empty, unknown or shared by many devices, ' +
|
|
92
|
+
'so another connection to the same device (USB, ip:5555, wireless debugging) will not find it';
|
|
93
|
+
|
|
94
|
+
const IDENTITY_TTL_MS = 5 * 60 * 1000;
|
|
95
|
+
const identityCache = new Map(); // connection serial -> { value, ts }
|
|
96
|
+
|
|
97
|
+
/** The connection serial: as given, else `adb get-serialno` (one device connected). */
|
|
98
|
+
async function connectionSerial(serial) {
|
|
99
|
+
if (serial) return String(serial);
|
|
100
|
+
const out = String(await adb(['get-serialno'])).trim();
|
|
101
|
+
if (!out || out === 'unknown')
|
|
102
|
+
throw new Error('adb get-serialno returned no serial - is a device connected? Call adb_devices, then pass serial.');
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* The snapshot key of the device behind a connection: { key, source:
|
|
108
|
+
* 'device'|'connection', connection, connectionKey, model, serialno }. Cached
|
|
109
|
+
* per connection serial for IDENTITY_TTL_MS.
|
|
110
|
+
*/
|
|
111
|
+
async function deviceIdentity(serial) {
|
|
112
|
+
const conn = await connectionSerial(serial);
|
|
113
|
+
const cached = identityCache.get(conn);
|
|
114
|
+
if (cached && Date.now() - cached.ts < IDENTITY_TTL_MS) return cached.value;
|
|
115
|
+
const m = splitMarked(await adbSh(serial || conn, markedCommand({
|
|
116
|
+
model: 'getprop ro.product.model',
|
|
117
|
+
serialno: 'getprop ro.serialno',
|
|
118
|
+
})));
|
|
119
|
+
const value = identityFrom(conn, m.model, m.serialno);
|
|
120
|
+
identityCache.set(conn, { value, ts: Date.now() });
|
|
121
|
+
return value;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Pure: the key from the connection serial and the two properties. */
|
|
125
|
+
function identityFrom(conn, model, serialno) {
|
|
126
|
+
const md = String(model || '').trim();
|
|
127
|
+
const sn = String(serialno || '').trim();
|
|
128
|
+
const connectionKey = sanitizeSerial(conn);
|
|
129
|
+
if (deviceSerialUsable(sn))
|
|
130
|
+
return { key: sanitizeSerial(`${md}_${sn}`), source: 'device', connection: conn, connectionKey, model: md, serialno: sn };
|
|
131
|
+
return { key: connectionKey, source: 'connection', connection: conn, connectionKey, model: md, serialno: sn };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* The store root of a call: the `store` setting, or the `store` parameter when
|
|
136
|
+
* it equals the setting or lies inside file_roots (the same check as the file
|
|
137
|
+
* tools).
|
|
138
|
+
*/
|
|
139
|
+
function storeRoot(args) {
|
|
140
|
+
if (!OPTS.store) throw new Error('the snapshot store is not set (setting store)');
|
|
141
|
+
if (args.store === undefined || args.store === null || args.store === '') return OPTS.store;
|
|
142
|
+
return checkHostPath(String(args.store), { roots: OPTS.fileRoots, exact: [OPTS.store], setting: 'store', what: 'store' });
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Where this call's snapshot lives: { root, id, dir, legacyDir }. */
|
|
146
|
+
async function storeContext(args, serial) {
|
|
147
|
+
const root = storeRoot(args);
|
|
148
|
+
const id = await deviceIdentity(serial);
|
|
149
|
+
const dir = path.join(root, id.key);
|
|
150
|
+
const legacy = path.join(root, id.connectionKey);
|
|
151
|
+
return { root, id, dir, legacyDir: id.source === 'device' && legacy !== dir ? legacy : null, readFrom: null };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function keyReport(ctx) {
|
|
155
|
+
const r = { key: ctx.id.key, source: ctx.id.source };
|
|
156
|
+
if (ctx.id.source === 'connection') r.note = CONNECTION_NOTE;
|
|
157
|
+
if (ctx.readFrom && ctx.readFrom !== path.join(ctx.dir, 'state.json')) r.read_from = ctx.readFrom;
|
|
158
|
+
return r;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function statePath(ctx) {
|
|
162
|
+
return path.join(ctx.dir, 'state.json');
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// { found: false } | { found: true, state } | { found: true, broken: why }
|
|
166
|
+
function readStateFile(p) {
|
|
167
|
+
let raw;
|
|
168
|
+
try { raw = fs.readFileSync(p, 'utf8'); }
|
|
169
|
+
catch (e) { if (e.code === 'ENOENT') return { found: false }; throw e; }
|
|
170
|
+
try {
|
|
171
|
+
const state = JSON.parse(raw);
|
|
172
|
+
if (!state || typeof state !== 'object' || !Array.isArray(state.entries)) throw new Error('no list of entries');
|
|
173
|
+
return { found: true, state };
|
|
174
|
+
} catch (e) {
|
|
175
|
+
return { found: true, broken: e.message };
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
class BrokenStateError extends Error {
|
|
180
|
+
constructor(message, moved) {
|
|
181
|
+
super(message);
|
|
182
|
+
this.name = 'BrokenStateError';
|
|
183
|
+
this.moved = moved;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** A name for a damaged state.json that no other file has: state.json.broken-<UTC time>[-n]. */
|
|
188
|
+
function brokenName(p, now = new Date()) {
|
|
189
|
+
const stamp = now.toISOString().replace(/\.\d+Z$/, 'Z').replace(/:/g, '-');
|
|
190
|
+
let name = `${p}.broken-${stamp}`;
|
|
191
|
+
for (let n = 2; fs.existsSync(name); n++) name = `${p}.broken-${stamp}-${n}`;
|
|
192
|
+
return name;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** The damaged snapshot files kept in a device directory. */
|
|
196
|
+
function brokenFiles(dir) {
|
|
197
|
+
try { return fs.readdirSync(dir).filter(n => n.startsWith('state.json.broken-')).sort().map(n => path.join(dir, n)); }
|
|
198
|
+
catch { return []; }
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* The snapshot: the device directory, else the connection directory of a 1.x
|
|
203
|
+
* layout (read only; the first write carries its entries over into the
|
|
204
|
+
* device directory and leaves the old one untouched).
|
|
205
|
+
*/
|
|
206
|
+
function readState(ctx) {
|
|
207
|
+
const empty = () => ({ device: ctx.id.key, key_source: ctx.id.source, updated: null, entries: [] });
|
|
208
|
+
const own = readStateFile(statePath(ctx));
|
|
209
|
+
if (own.found && own.broken) {
|
|
210
|
+
// Moved aside, never overwritten or removed; this call does nothing.
|
|
211
|
+
const p = statePath(ctx);
|
|
212
|
+
const dest = brokenName(p);
|
|
213
|
+
fs.renameSync(p, dest);
|
|
214
|
+
throw new BrokenStateError(`The snapshot file ${p} is damaged (${own.broken}); it was moved to ${dest}. ` +
|
|
215
|
+
'Its rollback entries are not used automatically, and calling again starts an empty snapshot. Nothing was done on the device.', dest);
|
|
216
|
+
}
|
|
217
|
+
if (own.found) {
|
|
218
|
+
ctx.readFrom = statePath(ctx);
|
|
219
|
+
return own.state;
|
|
220
|
+
}
|
|
221
|
+
if (ctx.legacyDir) {
|
|
222
|
+
const p = path.join(ctx.legacyDir, 'state.json');
|
|
223
|
+
const old = readStateFile(p);
|
|
224
|
+
// A damaged file of the old layout is left where it is and not used.
|
|
225
|
+
if (old.found && old.broken) ctx.legacyBroken = p;
|
|
226
|
+
if (old.found && old.state) {
|
|
227
|
+
ctx.readFrom = p;
|
|
228
|
+
return { ...old.state, device: ctx.id.key, key_source: ctx.id.source };
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
return empty();
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Write the snapshot through a uniquely named temporary file: a torn write
|
|
236
|
+
* must not leave broken JSON, it is the only source of a rollback. When the
|
|
237
|
+
* rename keeps failing, the error names the temporary file, which still holds
|
|
238
|
+
* the state.
|
|
239
|
+
*/
|
|
240
|
+
async function writeState(ctx, state, renameOpts) {
|
|
241
|
+
const p = statePath(ctx);
|
|
242
|
+
ensureDir(ctx.dir);
|
|
243
|
+
state.device = ctx.id.key;
|
|
244
|
+
state.key_source = ctx.id.source;
|
|
245
|
+
state.updated = new Date().toISOString();
|
|
246
|
+
const tmp = `${p}.tmp-${process.pid}-${Date.now()}`;
|
|
247
|
+
fs.writeFileSync(tmp, JSON.stringify(state, null, 2), 'utf8');
|
|
248
|
+
try {
|
|
249
|
+
await renameWithRetry(tmp, p, renameOpts);
|
|
250
|
+
} catch (e) {
|
|
251
|
+
throw new Error(`${p} could not be written (${e.code || e.message}). The snapshot state is kept in ${tmp}: ` +
|
|
252
|
+
'rename it to state.json before the next adb_app call, otherwise action=restore does not see the latest changes.');
|
|
253
|
+
}
|
|
254
|
+
ctx.readFrom = p;
|
|
255
|
+
return p;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** A backup directory as recorded in state.json: relative to the device directory, POSIX separators. */
|
|
259
|
+
function backupRef(ctx, absDir) {
|
|
260
|
+
return path.relative(ctx.dir, absDir).split(path.sep).join('/');
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* The absolute backup directory of an entry, checked against the store. A
|
|
265
|
+
* relative value is under the device directory; an absolute one (1.x) is
|
|
266
|
+
* taken as it is.
|
|
267
|
+
*/
|
|
268
|
+
function backupDirOf(ctx, entry) {
|
|
269
|
+
const b = entry.backup;
|
|
270
|
+
if (!b) return null;
|
|
271
|
+
const abs = path.isAbsolute(b) ? b : path.join(ctx.dir, ...String(b).split('/'));
|
|
272
|
+
return checkHostPath(abs, { roots: [ctx.root], setting: 'store', what: `backup of ${entry.package}` });
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// ------------------------------------------------------------------ helpers
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Version and ABI of a package. ⚠ No `grep -m2`: `primaryCpuAbi=` and
|
|
279
|
+
* `versionCode=` come first and would cut `versionName=` off. The first
|
|
280
|
+
* versionCode is taken: a "Hidden system packages" block may follow with the
|
|
281
|
+
* OLD version of an updated system package.
|
|
282
|
+
*/
|
|
283
|
+
async function packageVersion(serial, pkg) {
|
|
284
|
+
const out = await adbSh(serial,
|
|
285
|
+
`dumpsys package ${sq(pkg)} 2>/dev/null | grep -E "versionCode=|versionName=|primaryCpuAbi=" | head -n 20`);
|
|
286
|
+
const code = (out.match(/versionCode=(\d+)/) || [])[1] || '0';
|
|
287
|
+
const abi = (out.match(/primaryCpuAbi=(\S+)/) || [])[1] || '';
|
|
288
|
+
// versionName takes the rest of the line and may contain spaces ("1.0
|
|
289
|
+
// beta"), but some firmware appends other fields after it.
|
|
290
|
+
let name = ((out.match(/versionName=(.*)/) || [])[1] || '').trim();
|
|
291
|
+
if (/\s[A-Za-z_]\w*=/.test(name)) name = name.split(/\s+/)[0];
|
|
292
|
+
return { versionCode: code, versionName: name, primaryCpuAbi: abi };
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
async function packagePaths(serial, pkg) {
|
|
296
|
+
const out = await adbSh(serial, `pm path ${sq(pkg)} 2>/dev/null`);
|
|
297
|
+
return out.split('\n')
|
|
298
|
+
.map(l => l.trim())
|
|
299
|
+
.filter(l => l.startsWith('package:'))
|
|
300
|
+
.map(l => l.slice('package:'.length).trim())
|
|
301
|
+
.filter(Boolean);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* Pull every APK of a package into the store; returns the directory and its
|
|
306
|
+
* manifest. Works for system packages too, but those usually cannot be
|
|
307
|
+
* installed back as user apps (platform signature, shared uid): their
|
|
308
|
+
* rollback is pm enable or cmd package install-existing.
|
|
309
|
+
*/
|
|
310
|
+
async function backupPackage(serial, pkg, ctx, props) {
|
|
311
|
+
const remote = await packagePaths(serial, pkg);
|
|
312
|
+
if (!remote.length) throw new Error(`pm path returned nothing for ${pkg} - package not installed?`);
|
|
313
|
+
const ver = await packageVersion(serial, pkg);
|
|
314
|
+
const dir = path.join(ctx.dir, 'apk', pkg, ver.versionCode || '0');
|
|
315
|
+
ensureDir(dir);
|
|
316
|
+
|
|
317
|
+
const files = [];
|
|
318
|
+
for (const r of remote) {
|
|
319
|
+
const base = path.posix.basename(r);
|
|
320
|
+
const local = path.join(dir, base);
|
|
321
|
+
await adb(withSerial(serial, ['pull', r, local]), { timeout: 180000 });
|
|
322
|
+
const size = fs.existsSync(local) ? fs.statSync(local).size : 0;
|
|
323
|
+
if (!size) throw new Error(`Backup ${pkg}: file ${base} pulled empty`);
|
|
324
|
+
files.push({ name: base, size, device_path: r });
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
const manifest = {
|
|
328
|
+
package: pkg,
|
|
329
|
+
versionName: ver.versionName,
|
|
330
|
+
versionCode: ver.versionCode,
|
|
331
|
+
primaryCpuAbi: ver.primaryCpuAbi,
|
|
332
|
+
splits: files.map(f => f.name),
|
|
333
|
+
files,
|
|
334
|
+
device: { serial, model: props.model, sdk: props.sdk, density: props.density, locale: props.locale, abilist: props.abilist },
|
|
335
|
+
pulled_at: new Date().toISOString(),
|
|
336
|
+
};
|
|
337
|
+
fs.writeFileSync(path.join(dir, 'manifest.json'), JSON.stringify(manifest, null, 2), 'utf8');
|
|
338
|
+
return { dir, manifest };
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
async function installFromBackupDir(serial, dir) {
|
|
342
|
+
const apks = fs.readdirSync(dir).filter(f => f.endsWith('.apk')).map(f => path.join(dir, f));
|
|
343
|
+
if (!apks.length) throw new Error(`No .apk in ${dir}`);
|
|
344
|
+
const verb = apks.length > 1 ? 'install-multiple' : 'install';
|
|
345
|
+
const out = await adb(withSerial(serial, [verb, '-r', '-t', '-g', ...apks]), { timeout: 180000 });
|
|
346
|
+
return out.toString().trim() || `${verb}: ${apks.length} file(s) OK`;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// ------------------------------------------------------------------ canary
|
|
350
|
+
|
|
351
|
+
/** "The system is still whole", between batches, against the baseline taken before the first. */
|
|
352
|
+
async function canaryCheck(serial, baseline) {
|
|
353
|
+
const result = { ok: true, problems: [] };
|
|
354
|
+
|
|
355
|
+
const acc = await accountSnapshot(serial);
|
|
356
|
+
result.accounts = acc;
|
|
357
|
+
if (baseline.accounts.available && acc.available && acc.count < baseline.accounts.count) {
|
|
358
|
+
result.ok = false;
|
|
359
|
+
result.problems.push(
|
|
360
|
+
`account count went from ${baseline.accounts.count} to ${acc.count} - device registration lost`);
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
try {
|
|
364
|
+
const home = await adbSh(serial,
|
|
365
|
+
'cmd package resolve-activity --brief -a android.intent.action.MAIN -c android.intent.category.HOME 2>/dev/null | tail -n 1');
|
|
366
|
+
result.launcher = home.trim();
|
|
367
|
+
if (!result.launcher || /no activity|null/i.test(result.launcher)) {
|
|
368
|
+
result.ok = false;
|
|
369
|
+
result.problems.push('the launcher no longer resolves - the device would be left without a home screen');
|
|
370
|
+
}
|
|
371
|
+
} catch (e) {
|
|
372
|
+
result.ok = false;
|
|
373
|
+
result.problems.push(`launcher could not be checked: ${e.message}`);
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
return result;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// ------------------------------------------------------------ network guard
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* Refuse when any of the packages serves a client outside the device right
|
|
383
|
+
* now. The signal lives in device.js; here only the decision.
|
|
384
|
+
*
|
|
385
|
+
* A tier of its own, not part of the protected set: the set answers "may this
|
|
386
|
+
* package be lost" (disable/uninstall), the guard "does live work break right
|
|
387
|
+
* now", which applies to force-stop and clear as well.
|
|
388
|
+
*
|
|
389
|
+
* Checked BEFORE the protected set: its refusal names the port and the peer.
|
|
390
|
+
* force_network lifts only the guard; `force` (failed APK backup) never does.
|
|
391
|
+
*
|
|
392
|
+
* When the signal itself could not be read, the guard reports that it is
|
|
393
|
+
* blind: neither a silent pass nor a refusal of everything.
|
|
394
|
+
*/
|
|
395
|
+
async function networkGuard(serial, packages, what, forceNetwork, netSnapshot) {
|
|
396
|
+
let net = netSnapshot;
|
|
397
|
+
if (!net) {
|
|
398
|
+
try {
|
|
399
|
+
net = await netListeners(serial);
|
|
400
|
+
} catch (e) {
|
|
401
|
+
net = { ok: false, byPackage: {}, byUid: {}, unattributed: [],
|
|
402
|
+
note: `network signal not collected (${e.message}) - the guard did NOT run` };
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
const hits = servingHits(net, packages);
|
|
407
|
+
if (hits.length && !forceNetwork) throw new Error(servingRefusal(hits, what));
|
|
408
|
+
|
|
409
|
+
return {
|
|
410
|
+
hits,
|
|
411
|
+
overridden: hits, // non-empty only with force_network: otherwise it threw
|
|
412
|
+
blind: net.ok === false,
|
|
413
|
+
note: net.note || null,
|
|
414
|
+
net,
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/** The guard in the JSON output. A blind guard must be visible. */
|
|
419
|
+
function guardReport(guard) {
|
|
420
|
+
if (guard.blind)
|
|
421
|
+
return { status: 'blind', note: guard.note, checked: false,
|
|
422
|
+
why: 'the signal could not be read from the device - the destructive action runs without the network check' };
|
|
423
|
+
if (guard.overridden.length)
|
|
424
|
+
return { status: 'overridden', checked: true, overridden: guard.overridden, note: guard.note,
|
|
425
|
+
why: 'the network guard was lifted by force_network=true' };
|
|
426
|
+
return { status: 'not_serving', checked: true, note: guard.note };
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// ------------------------------------------------------------------ actions
|
|
430
|
+
|
|
431
|
+
async function actList(serial, args) {
|
|
432
|
+
const pkgs = await listPackages(serial);
|
|
433
|
+
const filter = String(args.filter || 'user').toLowerCase();
|
|
434
|
+
const q = args.q ? String(args.q).toLowerCase() : null;
|
|
435
|
+
|
|
436
|
+
let list;
|
|
437
|
+
if (filter === 'all') list = pkgs.all;
|
|
438
|
+
else if (filter === 'system') list = pkgs.all.filter(p => pkgs.system.has(p));
|
|
439
|
+
else if (filter === 'disabled') list = pkgs.all.filter(p => pkgs.disabled.has(p));
|
|
440
|
+
else list = pkgs.all.filter(p => !pkgs.system.has(p));
|
|
441
|
+
|
|
442
|
+
if (q) list = list.filter(p => p.toLowerCase().includes(q));
|
|
443
|
+
list = list.sort();
|
|
444
|
+
|
|
445
|
+
const lines = list.map(p => {
|
|
446
|
+
const flags = [pkgs.system.has(p) ? 'system' : 'user'];
|
|
447
|
+
if (pkgs.disabled.has(p)) flags.push('DISABLED');
|
|
448
|
+
return `${p} [${flags.join(',')}]`;
|
|
449
|
+
});
|
|
450
|
+
return text(
|
|
451
|
+
`filter=${filter}${q ? ` q=${q}` : ''} - ${list.length} of ${pkgs.all.length} packages\n\n` +
|
|
452
|
+
(lines.join('\n') || '(none)'));
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
async function actInfo(serial, args) {
|
|
456
|
+
const packages = coerceArray(args.packages || args.package).filter(Boolean);
|
|
457
|
+
if (!packages.length) throw new Error('action=info requires packages');
|
|
458
|
+
const pkgs = await listPackages(serial);
|
|
459
|
+
const out = [];
|
|
460
|
+
for (const p of packages) {
|
|
461
|
+
if (!pkgs.all.includes(p)) { out.push({ package: p, installed: false }); continue; }
|
|
462
|
+
const ver = await packageVersion(serial, p);
|
|
463
|
+
out.push({
|
|
464
|
+
package: p,
|
|
465
|
+
installed: true,
|
|
466
|
+
system: pkgs.system.has(p),
|
|
467
|
+
disabled: pkgs.disabled.has(p),
|
|
468
|
+
...ver,
|
|
469
|
+
paths: await packagePaths(serial, p),
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
return json(out);
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
// An am/intent token: the same limit as extras keys and the action, so no
|
|
476
|
+
// arbitrary `am` flags come in through a call.
|
|
477
|
+
const AM_TOKEN_RE = /^[A-Za-z0-9_.]+$/;
|
|
478
|
+
|
|
479
|
+
// A disabled shell must not come back as the ability to dial through an
|
|
480
|
+
// intent. Whether such an intent would place a call is not tested on hardware
|
|
481
|
+
// (the test would be a real call); the refusal stands regardless. With
|
|
482
|
+
// allow_shell on there is no refusal: adb_shell can dial anyway.
|
|
483
|
+
const CALL_ACTIONS = new Set([
|
|
484
|
+
'android.intent.action.CALL',
|
|
485
|
+
'android.intent.action.CALL_PRIVILEGED',
|
|
486
|
+
'android.intent.action.CALL_EMERGENCY',
|
|
487
|
+
]);
|
|
488
|
+
|
|
489
|
+
/**
|
|
490
|
+
* extras → `am start` flags: string → --es, boolean → --ez, int32 integer →
|
|
491
|
+
* --ei, larger integer → --el, anything else refused by key name. A JSON
|
|
492
|
+
* string of an object is accepted (coerceObject).
|
|
493
|
+
*/
|
|
494
|
+
function extrasToAmFlags(extras) {
|
|
495
|
+
const obj = coerceObject(extras);
|
|
496
|
+
const flags = [];
|
|
497
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
498
|
+
if (!AM_TOKEN_RE.test(k)) throw new Error(`extras.${k}: key name must match [A-Za-z0-9_.]+`);
|
|
499
|
+
if (typeof v === 'boolean') flags.push('--ez', sq(k), sq(String(v)));
|
|
500
|
+
else if (typeof v === 'string') flags.push('--es', sq(k), sq(v));
|
|
501
|
+
else if (typeof v === 'number' && Number.isInteger(v)) {
|
|
502
|
+
const isInt32 = v >= -2147483648 && v <= 2147483647;
|
|
503
|
+
flags.push(isInt32 ? '--ei' : '--el', sq(k), sq(String(v)));
|
|
504
|
+
} else {
|
|
505
|
+
throw new Error(`extras.${k}: unsupported value type (${typeof v}) - allowed: string, boolean, integer`);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
return flags;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/**
|
|
512
|
+
* The output of `am start -W` for an intent launch.
|
|
513
|
+
*
|
|
514
|
+
* ⚠ The -W format differs between SDK 28 and 36 (LaunchState/WaitTime/
|
|
515
|
+
* TotalTime come and go), so it is read line by line by prefix, never with
|
|
516
|
+
* one regex over the whole output. /Error|Exception/i over the whole text
|
|
517
|
+
* would fire on a URI containing "error" in the echo line, and "Warning: ...
|
|
518
|
+
* delivered to currently running top-most instance" contains "Activity not
|
|
519
|
+
* started" while being a success. The echo line `Starting: Intent { ... }` is
|
|
520
|
+
* not read at all: it holds the URI and extras as given.
|
|
521
|
+
*/
|
|
522
|
+
async function parseAmStartOutput(serial, out, ctx) {
|
|
523
|
+
const lines = String(out || '').split('\n').map(l => l.trim()).filter(Boolean);
|
|
524
|
+
const nonEcho = lines.filter(l => !/^Starting:\s*Intent\s*\{/.test(l));
|
|
525
|
+
const rawOut = String(out || '').trim();
|
|
526
|
+
|
|
527
|
+
// 1. No handler.
|
|
528
|
+
if (nonEcho.some(l => /^Error:\s*Activity not started, unable to resolve Intent/.test(l)))
|
|
529
|
+
throw new Error(`No handler for this intent (action=${ctx.action}).\n${rawOut}`);
|
|
530
|
+
|
|
531
|
+
// 2. Delivered to the running instance: a success, checked BEFORE the
|
|
532
|
+
// general errors because it says "Activity not started".
|
|
533
|
+
const delivered = nonEcho.find(l =>
|
|
534
|
+
/^Warning:\s*Activity not started, intent has been delivered to currently running top-most instance/.test(l));
|
|
535
|
+
if (delivered)
|
|
536
|
+
return text(`Delivered to the already running instance (${ctx.pkg || ctx.action}).\n${delivered}`);
|
|
537
|
+
|
|
538
|
+
// 3. A chooser dialog: the tool opened it, the tool closes it with ONE
|
|
539
|
+
// KEYCODE_BACK and reads the resumed activity again. Still on top: say
|
|
540
|
+
// so and send no more keys.
|
|
541
|
+
const activityLine = nonEcho.find(l => /^Activity:\s*/.test(l));
|
|
542
|
+
if (activityLine && /ResolverActivity|ChooserActivity/.test(activityLine)) {
|
|
543
|
+
await adb(withSerial(serial, ['shell', 'input keyevent KEYCODE_BACK']));
|
|
544
|
+
await new Promise(r => setTimeout(r, 500));
|
|
545
|
+
const after = await resumedActivity(serial);
|
|
546
|
+
if (after.raw && /ResolverActivity|ChooserActivity/.test(after.raw))
|
|
547
|
+
return text(`Several handlers; the chooser dialog is still on top: ${after.raw}`);
|
|
548
|
+
return text(`Several handlers; the chooser dialog was closed - pass packages.\n${activityLine}`);
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
// 4. Other errors: a line starting with `Error:` or containing "Exception"
|
|
552
|
+
// (a substring, not \bException\b: java.lang.SecurityException has no
|
|
553
|
+
// word boundary before "Exception"). Lines starting with `Starting:` or
|
|
554
|
+
// `Activity:` are skipped: a component such as pkg/.ExceptionHandlerActivity
|
|
555
|
+
// is a name, not a diagnosis.
|
|
556
|
+
const errPool = nonEcho.filter(l => !/^Starting:/.test(l) && !/^Activity:/.test(l));
|
|
557
|
+
const errLine = errPool.find(l => /^Error:/.test(l) || l.includes('Exception'));
|
|
558
|
+
if (errLine) throw new Error(`am start refused: ${errLine}\n${rawOut}`);
|
|
559
|
+
|
|
560
|
+
// 5. Status: ok, or no Status line: confirm by the resumed activity.
|
|
561
|
+
await new Promise(r => setTimeout(r, 1200));
|
|
562
|
+
const after = await resumedActivity(serial);
|
|
563
|
+
const okByResumed = ctx.pkg ? !!(after.raw && after.raw.includes(ctx.pkg)) : !!after.component;
|
|
564
|
+
|
|
565
|
+
const head = `intent (action=${ctx.action}${ctx.pkg ? `, -p ${ctx.pkg}` : ''})`;
|
|
566
|
+
if (okByResumed)
|
|
567
|
+
return text(`Launched via ${head}.\n${rawOut ? rawOut + '\n' : ''}Confirmed in the foreground: ${after.raw}`);
|
|
568
|
+
|
|
569
|
+
return text(
|
|
570
|
+
`⚠ ${head} was sent without error, but the package is not in the foreground.\n` +
|
|
571
|
+
`On top now: ${after.raw || '(not determined - neither ResumedActivity nor mCurrentFocus)'}\n${rawOut}`);
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/**
|
|
575
|
+
* Intent / deep-link launch, chosen by the presence of uri or intent_action.
|
|
576
|
+
* packages is optional: one value goes to `-p` (narrows the resolver and
|
|
577
|
+
* avoids the chooser); more than one is a refusal.
|
|
578
|
+
*/
|
|
579
|
+
async function actLaunchIntent(serial, args, packages) {
|
|
580
|
+
if (packages.length > 1)
|
|
581
|
+
throw new Error(`action=launch with uri/intent_action accepts at most one package (used as -p), got: ${packages.join(', ')}`);
|
|
582
|
+
const pkg = packages[0] || null;
|
|
583
|
+
|
|
584
|
+
const action = String(args.intent_action || 'android.intent.action.VIEW');
|
|
585
|
+
if (!AM_TOKEN_RE.test(action))
|
|
586
|
+
throw new Error(`intent_action \"${action}\" does not match [A-Za-z0-9_.]+`);
|
|
587
|
+
|
|
588
|
+
if (CALL_ACTIONS.has(action) && !OPTS.allowShell)
|
|
589
|
+
throw new Error(
|
|
590
|
+
`intent_action=${action} refused: the server option allow_shell is off. ` +
|
|
591
|
+
`If this is intended, ${OPTS.hints.allow_shell}, then use adb_shell.`);
|
|
592
|
+
|
|
593
|
+
const extraFlags = extrasToAmFlags(args.extras);
|
|
594
|
+
|
|
595
|
+
const parts = ['am', 'start', '-W', '-a', sq(action)];
|
|
596
|
+
if (args.uri) parts.push('-d', sq(String(args.uri)));
|
|
597
|
+
if (pkg) parts.push('-p', sq(pkg));
|
|
598
|
+
parts.push(...extraFlags);
|
|
599
|
+
const cmd = `${parts.join(' ')} 2>&1`;
|
|
600
|
+
|
|
601
|
+
let out = '';
|
|
602
|
+
try {
|
|
603
|
+
out = await adbSh(serial, cmd, { timeout: 20000 });
|
|
604
|
+
} catch (e) {
|
|
605
|
+
// A -W timeout is not a failed launch: report it and check the resumed
|
|
606
|
+
// activity. Other failures (device gone) are passed on.
|
|
607
|
+
if (!/timeout|killed/i.test(e.message)) throw e;
|
|
608
|
+
out = 'am -W did not answer in time (call timeout) - checking what started against the resumed activity.';
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
return parseAmStartOutput(serial, out, { pkg, action });
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
async function actLaunch(serial, args) {
|
|
615
|
+
const packages = coerceArray(args.packages || args.package).filter(Boolean);
|
|
616
|
+
|
|
617
|
+
if (args.uri || args.intent_action) return actLaunchIntent(serial, args, packages);
|
|
618
|
+
|
|
619
|
+
const pkg = packages[0];
|
|
620
|
+
if (!pkg) throw new Error('action=launch requires packages');
|
|
621
|
+
// Launching a package by name:
|
|
622
|
+
// · monkey with the LAUNCHER category refuses silently (rc != 0, no
|
|
623
|
+
// events); the only sign of a real launch is "Events injected".
|
|
624
|
+
// · TV apps declare MAIN with LEANBACK_LAUNCHER, not LAUNCHER.
|
|
625
|
+
// · Some activities resolve only for MAIN without any category.
|
|
626
|
+
// · ⚠ `resolve-activity -a MAIN` can return the system chooser
|
|
627
|
+
// (android/com.android.internal.app.ResolverActivity), which fits the
|
|
628
|
+
// package/activity shape: the activity must BELONG to the package, or
|
|
629
|
+
// the tool starts the wrong thing and reports success.
|
|
630
|
+
const CATS = ['android.intent.category.LAUNCHER', 'android.intent.category.LEANBACK_LAUNCHER'];
|
|
631
|
+
const tried = [];
|
|
632
|
+
|
|
633
|
+
for (const cat of CATS) {
|
|
634
|
+
const out = await adbSh(serial, `monkey -p ${sq(pkg)} -c ${cat} 1 2>&1 | tail -n 3`);
|
|
635
|
+
if (/Events injected:\s*[1-9]/.test(out))
|
|
636
|
+
return text(`Launched ${pkg} (monkey, ${cat.split('.').pop()})\n${out.trim()}`);
|
|
637
|
+
tried.push(`monkey ${cat.split('.').pop()}: no events injected`);
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
// Fallback: ask the system for the main activity and start it explicitly.
|
|
641
|
+
let act = '';
|
|
642
|
+
for (const q of [`-a android.intent.action.MAIN -c ${CATS[0]}`,
|
|
643
|
+
`-a android.intent.action.MAIN -c ${CATS[1]}`,
|
|
644
|
+
'-a android.intent.action.MAIN']) {
|
|
645
|
+
const r = (await adbSh(serial,
|
|
646
|
+
`cmd package resolve-activity --brief ${q} ${sq(pkg)} 2>/dev/null | tail -n 1`)).trim();
|
|
647
|
+
if (!/^[A-Za-z0-9_.]+\/[A-Za-z0-9_.$]+$/.test(r)) { tried.push(`resolve ${q}: ${r || 'empty'}`); continue; }
|
|
648
|
+
if (r.split('/')[0] !== pkg) {
|
|
649
|
+
// ResolverActivity and other foreign activities are not this package.
|
|
650
|
+
tried.push(`resolve ${q}: ${r} - activity of another package, discarded`);
|
|
651
|
+
continue;
|
|
652
|
+
}
|
|
653
|
+
act = r;
|
|
654
|
+
break;
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
if (!act)
|
|
658
|
+
throw new Error(
|
|
659
|
+
`Cannot launch ${pkg}: the main activity does not resolve.\n` +
|
|
660
|
+
tried.map(t => ` · ${t}`).join('\n') +
|
|
661
|
+
`\nTry \`adb_shell cmd package query-activities -a android.intent.action.MAIN\`; ` +
|
|
662
|
+
`the package may have no launchable activity at all (service, provider, overlay).`);
|
|
663
|
+
|
|
664
|
+
const started = await adbSh(serial, `am start -n ${sq(act)} 2>&1`);
|
|
665
|
+
if (/Error|Exception/i.test(started))
|
|
666
|
+
throw new Error(`Cannot launch ${pkg} via ${act}: ${started.trim()}`);
|
|
667
|
+
|
|
668
|
+
// Neither monkey nor am is taken at its word: the resumed activity is
|
|
669
|
+
// checked (mCurrentFocus alone is null on some devices even with the
|
|
670
|
+
// launcher up, so it is only the second opinion).
|
|
671
|
+
await new Promise(r => setTimeout(r, 1200));
|
|
672
|
+
const { raw: seen, resumedLine: resumed, focusLine: focus } = await resumedActivity(serial);
|
|
673
|
+
|
|
674
|
+
if (resumed.includes(pkg) || focus.includes(pkg))
|
|
675
|
+
return text(
|
|
676
|
+
`Launched ${pkg} via ${act} (monkey did not inject: ${tried[0]}).\n` +
|
|
677
|
+
`Package confirmed in the foreground.`);
|
|
678
|
+
|
|
679
|
+
// Started without error but not on top: usually the activity closed itself
|
|
680
|
+
// (a setup wizard checking its condition), less often it needs more time.
|
|
681
|
+
return text(
|
|
682
|
+
`⚠ ${pkg}: activity ${act} started without error, but it is not in the foreground.\n` +
|
|
683
|
+
`On top now: ${seen || '(not determined - neither ResumedActivity nor mCurrentFocus)'}\n` +
|
|
684
|
+
`The usual cause is that the activity closed itself (setup wizard, placeholder screen); ` +
|
|
685
|
+
`less often it needed more time. Take adb_screenshot if this matters.`);
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
async function actStopOrClear(serial, args, action) {
|
|
689
|
+
const packages = coerceArray(args.packages || args.package).filter(Boolean);
|
|
690
|
+
if (!packages.length) throw new Error(`action=${action} requires packages`);
|
|
691
|
+
const dryRun = dryRunOf(action, args); // clear wipes data: dry_run by default
|
|
692
|
+
const forceNetwork = coerceBool(args.force_network, false);
|
|
693
|
+
|
|
694
|
+
// The network guard covers stop and clear too: the protected set is checked
|
|
695
|
+
// only for disable/uninstall, and a force-stop of the package that holds an
|
|
696
|
+
// integration's channel cuts it just the same, until the service restarts.
|
|
697
|
+
// `pm clear` also wipes the data (a remote's pairing). ⚠ stop defaults to
|
|
698
|
+
// dry_run=false.
|
|
699
|
+
const guard = await networkGuard(serial, packages, action === 'stop' ? 'force-stop' : 'clear', forceNetwork);
|
|
700
|
+
|
|
701
|
+
if (dryRun) {
|
|
702
|
+
return text(`dry_run: ${action} for ${packages.length} package${packages.length === 1 ? '' : 's'}:\n` +
|
|
703
|
+
packages.map(p => ` ${p}`).join('\n') +
|
|
704
|
+
(guard.overridden.length
|
|
705
|
+
? `\n\n⚠ force_network=true overrides the network guard for: ` +
|
|
706
|
+
guard.overridden.map(h => `${h.package} (${h.serving.join(', ')})`).join('; ')
|
|
707
|
+
: '') +
|
|
708
|
+
(guard.blind ? `\n\n⚠ ${guard.note}` : '') +
|
|
709
|
+
`\n\nRepeat with dry_run=false to apply.`);
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
const done = [];
|
|
713
|
+
if (guard.overridden.length)
|
|
714
|
+
done.push(`⚠ force_network=true: the network guard is overridden for ` +
|
|
715
|
+
guard.overridden.map(h => `${h.package} (${h.serving.join(', ')})`).join('; '));
|
|
716
|
+
if (guard.blind) done.push(`⚠ ${guard.note}`);
|
|
717
|
+
|
|
718
|
+
for (const p of packages) {
|
|
719
|
+
const cmd = action === 'stop' ? `am force-stop ${sq(p)}` : `pm clear ${sq(p)}`;
|
|
720
|
+
const out = await adbSh(serial, `${cmd} 2>&1`);
|
|
721
|
+
done.push(`${p}: ${out.trim() || 'ok'}`);
|
|
722
|
+
}
|
|
723
|
+
return text(done.join('\n'));
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
/**
|
|
727
|
+
* Where a package in the protected set comes from, by the keys of `sources`
|
|
728
|
+
* (protectedSet in device.js): a string is the package itself, an array holds
|
|
729
|
+
* it, an object has it as a key; roles gets the role names from roles_detail.
|
|
730
|
+
* The core of the set (CORE_PROTECTED / CORE_PREFIXES) is in no source key
|
|
731
|
+
* and is marked `core` and `core (<prefix>*)`.
|
|
732
|
+
*/
|
|
733
|
+
function protectedSourcesOf(pkg, sources) {
|
|
734
|
+
const src = sources || {};
|
|
735
|
+
const found = [];
|
|
736
|
+
for (const [key, val] of Object.entries(src)) {
|
|
737
|
+
if (key === 'roles_detail') continue;
|
|
738
|
+
let hit = false;
|
|
739
|
+
if (typeof val === 'string') hit = val === pkg;
|
|
740
|
+
else if (Array.isArray(val)) hit = val.includes(pkg);
|
|
741
|
+
else if (val && typeof val === 'object') hit = Object.prototype.hasOwnProperty.call(val, pkg);
|
|
742
|
+
if (!hit) continue;
|
|
743
|
+
if (key === 'roles') {
|
|
744
|
+
const names = Object.entries(src.roles_detail || {})
|
|
745
|
+
.filter(([, holders]) => Array.isArray(holders) && holders.includes(pkg))
|
|
746
|
+
.map(([role]) => role);
|
|
747
|
+
found.push(names.length ? `roles (${names.join(', ')})` : 'roles');
|
|
748
|
+
} else {
|
|
749
|
+
found.push(key);
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
if (CORE_PROTECTED.includes(pkg)) found.push('core');
|
|
753
|
+
for (const pref of CORE_PREFIXES) {
|
|
754
|
+
if (pkg.startsWith(pref)) found.push(`core (${pref}*)`);
|
|
755
|
+
}
|
|
756
|
+
return found;
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
/**
|
|
760
|
+
* The protected-set refusal. ⚠ The first and the last lines are fixed: the
|
|
761
|
+
* documentation and the agent's habits rely on them. Between them one line
|
|
762
|
+
* per refused package with ITS sources only.
|
|
763
|
+
*/
|
|
764
|
+
function formatProtectedRefusal(hit, sources) {
|
|
765
|
+
return (
|
|
766
|
+
`REFUSED: the list contains protected packages - ${hit.join(', ')}.\n` +
|
|
767
|
+
hit.map(p => {
|
|
768
|
+
const from = protectedSourcesOf(p, sources);
|
|
769
|
+
return ` ${p} — ${from.length ? from.join(', ') : 'source not recorded'}`;
|
|
770
|
+
}).join('\n') + '\n' +
|
|
771
|
+
'The full set with every source: adb_app action=protected\n' +
|
|
772
|
+
'Nothing was applied. Remove them from the list by hand; the tool has no override.');
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
/** disable / uninstall — the one truly dangerous action. */
|
|
776
|
+
async function actRemove(serial, args) {
|
|
777
|
+
const packages = coerceArray(args.packages || args.package).filter(Boolean);
|
|
778
|
+
if (!packages.length) throw new Error('action requires packages');
|
|
779
|
+
|
|
780
|
+
const mode = String(args.mode || 'disable').toLowerCase();
|
|
781
|
+
if (!['disable', 'uninstall'].includes(mode))
|
|
782
|
+
throw new Error(`mode must be disable or uninstall, got: ${mode}`);
|
|
783
|
+
if (mode === 'uninstall' && !OPTS.allowUninstall)
|
|
784
|
+
throw new Error(
|
|
785
|
+
'mode=uninstall is refused: the server option allow_uninstall is off. ' +
|
|
786
|
+
`If removal is really needed rather than reversible disabling (mode=disable), ${OPTS.hints.allow_uninstall}.`);
|
|
787
|
+
|
|
788
|
+
const dryRun = dryRunOf('disable', args);
|
|
789
|
+
const doCanary = coerceBool(args.canary, true);
|
|
790
|
+
const doBackup = coerceBool(args.backup, mode === 'uninstall');
|
|
791
|
+
const force = coerceBool(args.force, false); // only about a failed APK backup
|
|
792
|
+
const forceNetwork = coerceBool(args.force_network, false); // only about the network guard
|
|
793
|
+
const batchSize = Math.max(1, Math.min(parseInt(args.batch_size, 10) || DEFAULT_BATCH, 25));
|
|
794
|
+
|
|
795
|
+
const props = await getProps(serial);
|
|
796
|
+
const pkgs = await listPackages(serial);
|
|
797
|
+
const prot = await protectedSet(serial, { props, packages: pkgs });
|
|
798
|
+
|
|
799
|
+
const unknown = packages.filter(p => !pkgs.all.includes(p));
|
|
800
|
+
if (unknown.length)
|
|
801
|
+
throw new Error(`Not installed on the device: ${unknown.join(', ')}`);
|
|
802
|
+
|
|
803
|
+
// The network guard BEFORE the protected set: its refusal names the port and
|
|
804
|
+
// the live client. The /proc/net snapshot comes from protectedSet.
|
|
805
|
+
const guard = await networkGuard(serial, packages, mode, forceNetwork, prot.net);
|
|
806
|
+
|
|
807
|
+
const hit = packages.filter(p => prot.packages.includes(p));
|
|
808
|
+
if (hit.length) throw new Error(formatProtectedRefusal(hit, prot.sources));
|
|
809
|
+
|
|
810
|
+
// Advisories for USER packages with external-connectivity signals: not a
|
|
811
|
+
// refusal (the APK backup makes them reversible), but not silence either:
|
|
812
|
+
// the consequence shows only outside the device, where the canary does not
|
|
813
|
+
// look.
|
|
814
|
+
const advisories = (prot.advisories || []).filter(a => packages.includes(a.package));
|
|
815
|
+
|
|
816
|
+
const plan = packages.map(p => ({
|
|
817
|
+
package: p,
|
|
818
|
+
system: pkgs.system.has(p),
|
|
819
|
+
already_disabled: pkgs.disabled.has(p),
|
|
820
|
+
action: mode,
|
|
821
|
+
warnings: advisories.filter(a => a.package === p).map(a => `${a.signal}: ${a.detail}`),
|
|
822
|
+
backup: doBackup && !pkgs.system.has(p) ? 'yes (user package)'
|
|
823
|
+
: doBackup ? 'yes (system package - the APK is saved, but it is restored via install-existing)' : 'no',
|
|
824
|
+
rollback: mode === 'disable' ? 'pm enable'
|
|
825
|
+
: pkgs.system.has(p) ? 'cmd package install-existing' : 'install from the APK backup',
|
|
826
|
+
}));
|
|
827
|
+
|
|
828
|
+
const baseline = { accounts: await accountSnapshot(serial) };
|
|
829
|
+
const ctx = await storeContext(args, serial);
|
|
830
|
+
|
|
831
|
+
if (dryRun) {
|
|
832
|
+
return json({
|
|
833
|
+
dry_run: true,
|
|
834
|
+
mode,
|
|
835
|
+
batch_size: batchSize,
|
|
836
|
+
canary: doCanary,
|
|
837
|
+
store: ctx.dir,
|
|
838
|
+
snapshot_key: keyReport(ctx),
|
|
839
|
+
baseline_accounts: baseline.accounts,
|
|
840
|
+
protected_count: prot.packages.length,
|
|
841
|
+
protected_sources: prot.sources,
|
|
842
|
+
protected_notes: prot.notes,
|
|
843
|
+
network_guard: guardReport(guard),
|
|
844
|
+
advisories,
|
|
845
|
+
plan,
|
|
846
|
+
hint: advisories.length
|
|
847
|
+
? 'Advisories present - read them before continuing. Repeat with dry_run=false. Rollback: adb_app action=restore.'
|
|
848
|
+
: 'Repeat with dry_run=false. Rollback: adb_app action=restore.',
|
|
849
|
+
});
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
if (mode === 'uninstall' && !doBackup && !force)
|
|
853
|
+
throw new Error('mode=uninstall with backup=false requires force=true - otherwise rollback is not possible for every package');
|
|
854
|
+
|
|
855
|
+
const state = readState(ctx);
|
|
856
|
+
const report = { mode, applied: [], failed: [], stopped: false, canary: [] };
|
|
857
|
+
report.snapshot_key = keyReport(ctx);
|
|
858
|
+
report.network_guard = guardReport(guard);
|
|
859
|
+
if (advisories.length) report.advisories = advisories;
|
|
860
|
+
|
|
861
|
+
for (let i = 0; i < packages.length; i += batchSize) {
|
|
862
|
+
const batch = packages.slice(i, i + batchSize);
|
|
863
|
+
const batchApplied = [];
|
|
864
|
+
|
|
865
|
+
const changes = [];
|
|
866
|
+
for (const p of batch) {
|
|
867
|
+
let backupDir = null;
|
|
868
|
+
if (doBackup) {
|
|
869
|
+
try {
|
|
870
|
+
backupDir = (await backupPackage(serial, p, ctx, props)).dir;
|
|
871
|
+
} catch (e) {
|
|
872
|
+
if (!force) {
|
|
873
|
+
report.failed.push({ package: p, error: `backup failed (${e.message}) - stopping; repeat with force=true if this is intended` });
|
|
874
|
+
continue;
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
const cmd = mode === 'disable'
|
|
879
|
+
? `pm disable-user --user 0 ${sq(p)} 2>&1`
|
|
880
|
+
: `pm uninstall --user 0 ${sq(p)} 2>&1`;
|
|
881
|
+
changes.push({ package: p, change: mode, backupDir, run: () => adbSh(serial, cmd) });
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
for (const r of await applyVerified(serial, changes)) {
|
|
885
|
+
if (!r.ok) { report.failed.push({ package: r.package, error: r.error }); continue; }
|
|
886
|
+
const entry = {
|
|
887
|
+
package: r.package, mode, system: pkgs.system.has(r.package), backup: r.backupDir ? backupRef(ctx, r.backupDir) : null,
|
|
888
|
+
ts: new Date().toISOString(), result: r.out,
|
|
889
|
+
};
|
|
890
|
+
if (r.warning) entry.warning = r.warning;
|
|
891
|
+
state.entries = state.entries.filter(e => e.package !== r.package);
|
|
892
|
+
state.entries.push(entry);
|
|
893
|
+
batchApplied.push(entry);
|
|
894
|
+
report.applied.push(entry);
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
await writeState(ctx, state);
|
|
898
|
+
|
|
899
|
+
if (doCanary) {
|
|
900
|
+
const c = await canaryCheck(serial, baseline);
|
|
901
|
+
report.canary.push({ after_batch: Math.floor(i / batchSize) + 1, ...c });
|
|
902
|
+
if (!c.ok) {
|
|
903
|
+
// Roll back THIS batch only, and stop.
|
|
904
|
+
const rolledBack = [];
|
|
905
|
+
for (const r of await applyVerified(serial, batchApplied.map(e => restoreChange(serial, e, ctx)))) {
|
|
906
|
+
if (r.ok) {
|
|
907
|
+
state.entries = state.entries.filter(x => x.package !== r.package);
|
|
908
|
+
rolledBack.push(r.package);
|
|
909
|
+
} else {
|
|
910
|
+
report.failed.push({ package: r.package, error: `rollback failed: ${r.error}` });
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
await writeState(ctx, state);
|
|
914
|
+
report.stopped = true;
|
|
915
|
+
report.rolled_back = rolledBack;
|
|
916
|
+
report.reason = c.problems.join('; ');
|
|
917
|
+
break;
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
report.state_file = statePath(ctx);
|
|
923
|
+
report.next = 'Check the device by eye: home screen, store, account sign-in. ' +
|
|
924
|
+
'Check again after a reboot - some failures only show up on the next boot.';
|
|
925
|
+
return json(report);
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
// The rollback of a snapshot entry as a change for applyVerified().
|
|
929
|
+
function restoreChange(serial, entry, ctx) {
|
|
930
|
+
if (entry.mode === 'disable')
|
|
931
|
+
return { package: entry.package, change: 'enable', run: () => adbSh(serial, `pm enable ${sq(entry.package)} 2>&1`) };
|
|
932
|
+
if (entry.system)
|
|
933
|
+
return { package: entry.package, change: 'install', run: () => adbSh(serial, `cmd package install-existing --user 0 ${sq(entry.package)} 2>&1`) };
|
|
934
|
+
return {
|
|
935
|
+
package: entry.package, change: 'install', run: async () => {
|
|
936
|
+
if (!entry.backup) throw new Error(`no APK backup for ${entry.package} - nothing to restore from`);
|
|
937
|
+
return installFromBackupDir(serial, backupDirOf(ctx, entry));
|
|
938
|
+
},
|
|
939
|
+
};
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
// The text pm prints is not the result on every firmware: some firmware
|
|
943
|
+
// answers `pm disable-user` with a warning and applies it only sometimes. So
|
|
944
|
+
// a package change counts by the package list read after it, once per batch.
|
|
945
|
+
const TOOK_EFFECT = {
|
|
946
|
+
disable: (pkgs, p) => pkgs.all.includes(p) && pkgs.disabled.has(p),
|
|
947
|
+
uninstall: (pkgs, p) => !pkgs.all.includes(p),
|
|
948
|
+
enable: (pkgs, p) => pkgs.all.includes(p) && !pkgs.disabled.has(p),
|
|
949
|
+
install: (pkgs, p) => pkgs.all.includes(p),
|
|
950
|
+
};
|
|
951
|
+
const NOT_DONE = {
|
|
952
|
+
disable: 'not disabled: the device still lists it as enabled',
|
|
953
|
+
uninstall: 'not removed: the device still lists it as installed',
|
|
954
|
+
enable: 'not enabled: the device does not list it as an enabled package',
|
|
955
|
+
install: 'not restored: the device does not list it as installed',
|
|
956
|
+
};
|
|
957
|
+
const SUSPECT_OUTPUT = /illegal|warning|failure|exception|error/i;
|
|
958
|
+
|
|
959
|
+
/**
|
|
960
|
+
* Run each change ({ package, change, run() → device output, ...extra }) in
|
|
961
|
+
* order, then read the package list once and judge every change by it.
|
|
962
|
+
* Returns the changes with { ok, out, error?, warning? }. When the list cannot
|
|
963
|
+
* be read, the device output decides, and an applied change says it was not
|
|
964
|
+
* verified.
|
|
965
|
+
*/
|
|
966
|
+
async function applyVerified(serial, changes) {
|
|
967
|
+
if (!changes.length) return [];
|
|
968
|
+
const runs = [];
|
|
969
|
+
for (const { run, ...c } of changes) {
|
|
970
|
+
try { runs.push({ ...c, out: String(await run()).trim(), runError: null }); }
|
|
971
|
+
catch (e) { runs.push({ ...c, out: '', runError: e.message }); }
|
|
972
|
+
}
|
|
973
|
+
let pkgs = null, listError = null;
|
|
974
|
+
try { pkgs = await listPackages(serial); } catch (e) { listError = e.message; }
|
|
975
|
+
return runs.map(({ runError, ...r }) => {
|
|
976
|
+
const said = runError || r.out;
|
|
977
|
+
if (!pkgs) {
|
|
978
|
+
if (runError || /Failure|Exception|Error/i.test(r.out)) return { ...r, ok: false, error: said };
|
|
979
|
+
return { ...r, ok: true, warning: `not verified: the package list could not be read afterwards (${listError})` };
|
|
980
|
+
}
|
|
981
|
+
if (TOOK_EFFECT[r.change](pkgs, r.package)) {
|
|
982
|
+
const odd = runError || (SUSPECT_OUTPUT.test(r.out) ? r.out : '');
|
|
983
|
+
return odd ? { ...r, ok: true, warning: `the device answered "${odd}", but the change took effect` } : { ...r, ok: true };
|
|
984
|
+
}
|
|
985
|
+
return { ...r, ok: false, error: `${NOT_DONE[r.change]}${said ? `; device output: ${said}` : ''}` };
|
|
986
|
+
});
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
function describeBackup(ctx, e) {
|
|
990
|
+
try { return backupDirOf(ctx, e) || '(no backup)'; } catch (err) { return `${e.backup} (refused: ${err.message})`; }
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
async function actEnableOrRestore(serial, args, action) {
|
|
994
|
+
const ctx = await storeContext(args, serial);
|
|
995
|
+
const state = readState(ctx);
|
|
996
|
+
const asked = coerceArray(args.packages || args.package).filter(Boolean);
|
|
997
|
+
const dryRun = dryRunOf(action, args);
|
|
998
|
+
|
|
999
|
+
let targets;
|
|
1000
|
+
if (action === 'enable' && asked.length) {
|
|
1001
|
+
// a direct enable, even for a package that is not in the snapshot
|
|
1002
|
+
targets = asked.map(p => {
|
|
1003
|
+
const known = state.entries.find(e => e.package === p);
|
|
1004
|
+
return known || { package: p, mode: 'disable', system: true, backup: null };
|
|
1005
|
+
});
|
|
1006
|
+
} else {
|
|
1007
|
+
targets = asked.length ? state.entries.filter(e => asked.includes(e.package)) : state.entries.slice();
|
|
1008
|
+
if (asked.length) {
|
|
1009
|
+
const missing = asked.filter(p => !state.entries.some(e => e.package === p));
|
|
1010
|
+
if (missing.length) throw new Error(`Not in the snapshot: ${missing.join(', ')}. Use action=enable for a direct enable.`);
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
if (!targets.length)
|
|
1015
|
+
return text('The snapshot is empty - nothing to restore.' + (ctx.id.source === 'connection' ? `\nNote: ${CONNECTION_NOTE}.` : ''));
|
|
1016
|
+
|
|
1017
|
+
if (dryRun) {
|
|
1018
|
+
return json({
|
|
1019
|
+
dry_run: true,
|
|
1020
|
+
state_file: ctx.readFrom || statePath(ctx),
|
|
1021
|
+
snapshot_key: keyReport(ctx),
|
|
1022
|
+
plan: targets.map(e => ({
|
|
1023
|
+
package: e.package,
|
|
1024
|
+
was: e.mode,
|
|
1025
|
+
how: e.mode === 'disable' ? 'pm enable'
|
|
1026
|
+
: e.system ? 'cmd package install-existing' : `install from ${describeBackup(ctx, e)}`,
|
|
1027
|
+
})),
|
|
1028
|
+
hint: 'Repeat with dry_run=false.',
|
|
1029
|
+
});
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
const done = [], failed = [];
|
|
1033
|
+
for (const r of await applyVerified(serial, targets.map(e => restoreChange(serial, e, ctx)))) {
|
|
1034
|
+
if (!r.ok) { failed.push({ package: r.package, error: r.error }); continue; }
|
|
1035
|
+
state.entries = state.entries.filter(x => x.package !== r.package);
|
|
1036
|
+
done.push({ package: r.package, result: r.out, ...(r.warning ? { warning: r.warning } : {}) });
|
|
1037
|
+
}
|
|
1038
|
+
await writeState(ctx, state);
|
|
1039
|
+
return json({ restored: done, failed, state_file: statePath(ctx), snapshot_key: keyReport(ctx) });
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
async function actBackup(serial, args) {
|
|
1043
|
+
const pkgs = await listPackages(serial);
|
|
1044
|
+
let packages = coerceArray(args.packages || args.package).filter(Boolean);
|
|
1045
|
+
const scope = String(args.scope || (packages.length ? 'list' : 'user')).toLowerCase();
|
|
1046
|
+
|
|
1047
|
+
if (!packages.length) {
|
|
1048
|
+
if (scope === 'user') packages = pkgs.all.filter(p => !pkgs.system.has(p));
|
|
1049
|
+
else if (scope === 'all') packages = pkgs.all.slice();
|
|
1050
|
+
else throw new Error('action=backup requires packages or scope=user|all');
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
const ctx = await storeContext(args, serial);
|
|
1054
|
+
const dryRun = dryRunOf('backup', args);
|
|
1055
|
+
if (dryRun) {
|
|
1056
|
+
return text(`dry_run: ${packages.length} package${packages.length === 1 ? '' : 's'} will be saved to ` +
|
|
1057
|
+
`${path.join(ctx.dir, 'apk')}:\n` + packages.map(p => ` ${p}`).join('\n') +
|
|
1058
|
+
(ctx.id.source === 'connection' ? `\nNote: ${CONNECTION_NOTE}.` : ''));
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
const props = await getProps(serial);
|
|
1062
|
+
const saved = [], failed = [];
|
|
1063
|
+
for (const p of packages) {
|
|
1064
|
+
try {
|
|
1065
|
+
const r = await backupPackage(serial, p, ctx, props);
|
|
1066
|
+
saved.push({ package: p, dir: r.dir, splits: r.manifest.splits, version: r.manifest.versionName });
|
|
1067
|
+
} catch (e) {
|
|
1068
|
+
failed.push({ package: p, error: e.message });
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
return json({ saved_count: saved.length, saved, failed, store: ctx.dir, snapshot_key: keyReport(ctx) });
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
function listBackups(dir) {
|
|
1075
|
+
try {
|
|
1076
|
+
const apkRoot = path.join(dir, 'apk');
|
|
1077
|
+
return fs.readdirSync(apkRoot).map(pkg => ({ package: pkg, versions: fs.readdirSync(path.join(apkRoot, pkg)) }));
|
|
1078
|
+
} catch { return []; } // no backups yet
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
async function actState(serial, args) {
|
|
1082
|
+
const ctx = await storeContext(args, serial);
|
|
1083
|
+
let state, damaged = null;
|
|
1084
|
+
try {
|
|
1085
|
+
state = readState(ctx);
|
|
1086
|
+
} catch (e) {
|
|
1087
|
+
if (e.name !== 'BrokenStateError') throw e;
|
|
1088
|
+
state = null;
|
|
1089
|
+
damaged = e.message;
|
|
1090
|
+
}
|
|
1091
|
+
const out = {
|
|
1092
|
+
store: ctx.dir,
|
|
1093
|
+
snapshot_key: { ...keyReport(ctx), connection: ctx.id.connection },
|
|
1094
|
+
state_file: ctx.readFrom || statePath(ctx),
|
|
1095
|
+
state,
|
|
1096
|
+
backups: listBackups(ctx.dir),
|
|
1097
|
+
};
|
|
1098
|
+
if (damaged) out.damaged = damaged;
|
|
1099
|
+
const broken = brokenFiles(ctx.dir);
|
|
1100
|
+
if (broken.length)
|
|
1101
|
+
out.broken_files = { files: broken, note: 'damaged snapshot files moved aside; never used, overwritten or removed by the server. Read them by hand if a rollback is needed.' };
|
|
1102
|
+
if (ctx.legacyBroken)
|
|
1103
|
+
out.legacy_broken = { file: ctx.legacyBroken, note: 'a damaged snapshot file of the older layout; left where it is and not used' };
|
|
1104
|
+
if (ctx.legacyDir && ctx.readFrom === path.join(ctx.legacyDir, 'state.json')) {
|
|
1105
|
+
out.legacy_backups = listBackups(ctx.legacyDir);
|
|
1106
|
+
out.legacy_note = `read from the connection directory of an older layout; the next change writes these entries to ${statePath(ctx)} and leaves the old directory as it is`;
|
|
1107
|
+
}
|
|
1108
|
+
const def = path.join(ctx.root, 'default');
|
|
1109
|
+
if (ctx.dir !== def && fs.existsSync(def)) {
|
|
1110
|
+
out.default_dir = { path: def,
|
|
1111
|
+
note: 'a snapshot directory of ha-adb-mcp 1.x for calls made without serial; it can belong to any device and is not read. Restore from it by hand if it is this device\'s.' };
|
|
1112
|
+
}
|
|
1113
|
+
return json(out);
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
// --------------------------------------------------------------- entry point
|
|
1117
|
+
|
|
1118
|
+
async function adbApp(args) {
|
|
1119
|
+
const serial = args.serial;
|
|
1120
|
+
const action = String(args.action || '').toLowerCase();
|
|
1121
|
+
|
|
1122
|
+
switch (action) {
|
|
1123
|
+
case 'list': return actList(serial, args);
|
|
1124
|
+
case 'info': return actInfo(serial, args);
|
|
1125
|
+
case 'launch': return actLaunch(serial, args);
|
|
1126
|
+
case 'stop': return actStopOrClear(serial, args, 'stop');
|
|
1127
|
+
case 'clear': return actStopOrClear(serial, args, 'clear');
|
|
1128
|
+
case 'disable': return actRemove(serial, { ...args, mode: args.mode || 'disable' });
|
|
1129
|
+
case 'uninstall': return actRemove(serial, { ...args, mode: 'uninstall' });
|
|
1130
|
+
case 'enable': return actEnableOrRestore(serial, args, 'enable');
|
|
1131
|
+
case 'restore': return actEnableOrRestore(serial, args, 'restore');
|
|
1132
|
+
case 'backup': return actBackup(serial, args);
|
|
1133
|
+
case 'state': return actState(serial, args);
|
|
1134
|
+
case 'protected': {
|
|
1135
|
+
const props = await getProps(serial);
|
|
1136
|
+
// net is the guard's raw snapshot; sources already show the same.
|
|
1137
|
+
const { net, ...prot } = await protectedSet(serial, { props });
|
|
1138
|
+
void net;
|
|
1139
|
+
return json({ device: props, ...prot });
|
|
1140
|
+
}
|
|
1141
|
+
default:
|
|
1142
|
+
throw new Error(`Unknown action: ${action || '(empty)'}. ` +
|
|
1143
|
+
`Allowed: list, info, protected, launch, stop, clear, disable, uninstall, enable, restore, backup, state`);
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1147
|
+
module.exports = {
|
|
1148
|
+
configure, adbApp, dryRunOf, READ_ONLY_ACTIONS,
|
|
1149
|
+
parseAmStartOutput, extrasToAmFlags, CALL_ACTIONS, AM_TOKEN_RE,
|
|
1150
|
+
protectedSourcesOf, formatProtectedRefusal,
|
|
1151
|
+
// snapshot store
|
|
1152
|
+
SHARED_SERIALS, deviceSerialUsable, identityFrom, deviceIdentity, storeRoot, storeContext,
|
|
1153
|
+
readState, writeState, renameWithRetry, backupRef, backupDirOf, keyReport, CONNECTION_NOTE, brokenFiles, brokenName,
|
|
1154
|
+
applyVerified,
|
|
1155
|
+
_identityCache: identityCache,
|
|
1156
|
+
};
|