brickproof-adb 0.0.0-stage → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +47 -0
- package/LICENSE +21 -0
- package/PRIVACY.md +31 -0
- package/README.md +151 -2
- package/package.json +41 -4
- package/src/adb.js +376 -0
- package/src/apps.js +1156 -0
- package/src/body.js +73 -0
- package/src/cli.js +502 -0
- package/src/config.js +632 -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 +326 -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 +163 -0
- package/src/session.js +388 -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/watcher.js +188 -0
package/src/config.js
ADDED
|
@@ -0,0 +1,632 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* brickproof-adb — configuration: config file, environment and flags. No
|
|
4
|
+
* network, no adb; writes only in ensureStateDir() and writeSetting().
|
|
5
|
+
*
|
|
6
|
+
* The server works without any file. A file is looked up at env
|
|
7
|
+
* BRICKPROOF_CONFIG (must exist), then <config_dir>/config.json, then none;
|
|
8
|
+
* `brickproof-adb set` writes it.
|
|
9
|
+
* Precedence: flags (and the stdio directory arguments) > env > file > defaults.
|
|
10
|
+
* On Windows, with file_roots set by no source, loadConfig() reads where the
|
|
11
|
+
* Downloads folder is from the registry (powershell.exe, 15 s at most).
|
|
12
|
+
*
|
|
13
|
+
* The settings directories follow the operating system:
|
|
14
|
+
* Linux config $XDG_CONFIG_HOME/brickproof-adb (~/.config/brickproof-adb)
|
|
15
|
+
* state $XDG_STATE_HOME/brickproof-adb (~/.local/state/brickproof-adb)
|
|
16
|
+
* macOS both ~/Library/Application Support/brickproof-adb
|
|
17
|
+
* Windows config %APPDATA%\brickproof-adb, state %LOCALAPPDATA%\brickproof-adb
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
const fs = require('fs');
|
|
21
|
+
const os = require('os');
|
|
22
|
+
const path = require('path');
|
|
23
|
+
|
|
24
|
+
const APP_DIR = 'brickproof-adb';
|
|
25
|
+
|
|
26
|
+
const DEFAULTS = {
|
|
27
|
+
port: 3200,
|
|
28
|
+
host: '127.0.0.1',
|
|
29
|
+
allowed_hosts: [],
|
|
30
|
+
log_requests: false,
|
|
31
|
+
allow_shell: false,
|
|
32
|
+
allow_uninstall: false,
|
|
33
|
+
devices: [],
|
|
34
|
+
scan_subnets: [],
|
|
35
|
+
adb_path: 'adb',
|
|
36
|
+
reconnect_interval: 60,
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const KEYS = new Set(['$comment', 'port', 'host', 'allowed_hosts', 'log_requests', 'allow_shell', 'allow_uninstall',
|
|
40
|
+
'devices', 'file_roots', 'scan_subnets', 'store', 'state_dir', 'adb_path', 'reconnect_interval']);
|
|
41
|
+
|
|
42
|
+
// The environment variable of each key that has one.
|
|
43
|
+
const ENV_OF = {
|
|
44
|
+
log_requests: 'BRICKPROOF_LOG_REQUESTS', allow_shell: 'BRICKPROOF_ALLOW_SHELL', allow_uninstall: 'BRICKPROOF_ALLOW_UNINSTALL',
|
|
45
|
+
devices: 'BRICKPROOF_DEVICES', file_roots: 'BRICKPROOF_FILE_ROOTS', scan_subnets: 'BRICKPROOF_SCAN_SUBNETS',
|
|
46
|
+
store: 'BRICKPROOF_STORE', state_dir: 'BRICKPROOF_STATE_DIR', adb_path: 'BRICKPROOF_ADB',
|
|
47
|
+
reconnect_interval: 'BRICKPROOF_RECONNECT_INTERVAL',
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
class ConfigError extends Error {
|
|
51
|
+
constructor(message) {
|
|
52
|
+
super(message);
|
|
53
|
+
this.name = 'ConfigError';
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// An unset value: absent, empty, or a placeholder a launcher left unresolved
|
|
58
|
+
// (an optional field of a desktop extension's form that was not filled in).
|
|
59
|
+
function envValue(env, name) {
|
|
60
|
+
const v = env[name];
|
|
61
|
+
if (v === undefined || v === '' || /^\$\{user_config\.[A-Za-z0-9_]+\}$/.test(v)) return undefined;
|
|
62
|
+
return v;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function isPort(n) {
|
|
66
|
+
return Number.isInteger(n) && n >= 0 && n <= 65535;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// reconnect_interval: seconds between two rounds of the watcher; 0 turns it off.
|
|
70
|
+
const RECONNECT_MIN = 15;
|
|
71
|
+
const RECONNECT_MAX = 3600;
|
|
72
|
+
const RECONNECT_RULE = `0 (off) or an integer ${RECONNECT_MIN}-${RECONNECT_MAX} (seconds)`;
|
|
73
|
+
|
|
74
|
+
function isReconnectInterval(n) {
|
|
75
|
+
return n === 0 || (Number.isInteger(n) && n >= RECONNECT_MIN && n <= RECONNECT_MAX);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// A reconnect_interval given as text (environment, `set`): a number or NaN.
|
|
79
|
+
function reconnectOf(text) {
|
|
80
|
+
return /^\s*\d+\s*$/.test(text) ? Number(text) : NaN;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// Path functions of the given platform, so the directory rules can be tested
|
|
84
|
+
// for every operating system on any of them.
|
|
85
|
+
function pathFor(platform) {
|
|
86
|
+
return platform === 'win32' ? path.win32 : path.posix;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** config_dir and state_dir defaults for a platform. */
|
|
90
|
+
function platformDirs({ platform = process.platform, env = process.env, homedir = os.homedir() } = {}) {
|
|
91
|
+
const P = pathFor(platform);
|
|
92
|
+
if (platform === 'win32') {
|
|
93
|
+
const roaming = envValue(env, 'APPDATA') || P.join(homedir, 'AppData', 'Roaming');
|
|
94
|
+
const local = envValue(env, 'LOCALAPPDATA') || P.join(homedir, 'AppData', 'Local');
|
|
95
|
+
return { configDir: P.join(roaming, APP_DIR), stateDir: P.join(local, APP_DIR) };
|
|
96
|
+
}
|
|
97
|
+
if (platform === 'darwin') {
|
|
98
|
+
const dir = P.join(homedir, 'Library', 'Application Support', APP_DIR);
|
|
99
|
+
return { configDir: dir, stateDir: dir };
|
|
100
|
+
}
|
|
101
|
+
// XDG: a relative value is invalid and ignored.
|
|
102
|
+
const xdg = name => {
|
|
103
|
+
const v = envValue(env, name);
|
|
104
|
+
return v && P.isAbsolute(v) ? v : undefined;
|
|
105
|
+
};
|
|
106
|
+
return {
|
|
107
|
+
configDir: P.join(xdg('XDG_CONFIG_HOME') || P.join(homedir, '.config'), APP_DIR),
|
|
108
|
+
stateDir: P.join(xdg('XDG_STATE_HOME') || P.join(homedir, '.local', 'state'), APP_DIR),
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// ------------------------------------------------- Windows: the Downloads folder
|
|
113
|
+
|
|
114
|
+
const DOWNLOADS_GUID = '{374DE290-123F-4565-9164-39C4925E467B}';
|
|
115
|
+
|
|
116
|
+
// Prints the raw Downloads value of User Shell Folders, then of Shell Folders,
|
|
117
|
+
// one line each: base64 of the UTF-16 text, or "-". The output is ASCII
|
|
118
|
+
// whatever the console code page, so a localized, non-ASCII folder name
|
|
119
|
+
// arrives intact; reg.exe prints in the OEM code page instead.
|
|
120
|
+
const SHELL_FOLDERS_SCRIPT = [
|
|
121
|
+
"$ErrorActionPreference = 'SilentlyContinue'",
|
|
122
|
+
"foreach ($n in 'User Shell Folders', 'Shell Folders') {",
|
|
123
|
+
' $v = $null',
|
|
124
|
+
" $k = Get-Item -LiteralPath ('HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\' + $n)",
|
|
125
|
+
` if ($k) { $v = $k.GetValue('${DOWNLOADS_GUID}', $null, 'DoNotExpandEnvironmentNames') }`,
|
|
126
|
+
" if ($v -is [string] -and $v -ne '') { [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($v)) } else { '-' }",
|
|
127
|
+
'}',
|
|
128
|
+
].join('\n');
|
|
129
|
+
|
|
130
|
+
/** { user, shell } of the script's output; null for a value that is absent. */
|
|
131
|
+
function parseShellFolders(stdout) {
|
|
132
|
+
const lines = String(stdout || '').split(/\r?\n/).map(l => l.trim()).filter(Boolean);
|
|
133
|
+
const value = line => {
|
|
134
|
+
if (!line || line === '-' || !/^[A-Za-z0-9+/]+={0,2}$/.test(line)) return null;
|
|
135
|
+
const buf = Buffer.from(line, 'base64');
|
|
136
|
+
return buf.length && buf.length % 2 === 0 ? buf.toString('utf16le') : null;
|
|
137
|
+
};
|
|
138
|
+
return { user: value(lines[0]), shell: value(lines[1]) };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** %NAME% replaced from the environment, names in any case; unknown ones stay. */
|
|
142
|
+
function expandWindowsEnv(value, env) {
|
|
143
|
+
return value.replace(/%([^%]+)%/g, (all, name) => {
|
|
144
|
+
const key = Object.keys(env).find(k => k.toLowerCase() === name.toLowerCase());
|
|
145
|
+
return key !== undefined && env[key] !== undefined && env[key] !== '' ? env[key] : all;
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// The longest the registry read may take: powershell.exe starts slowly on a
|
|
150
|
+
// busy or freshly booted machine.
|
|
151
|
+
const REGISTRY_TIMEOUT_MS = 15000;
|
|
152
|
+
|
|
153
|
+
// A Windows PowerShell script: { stdout } or { error: why it failed }. The
|
|
154
|
+
// script goes in as UTF-16 (-EncodedCommand), so no quoting or code page
|
|
155
|
+
// touches it.
|
|
156
|
+
function runPowerShellResult(script, { env = process.env, timeout = REGISTRY_TIMEOUT_MS } = {}) {
|
|
157
|
+
try {
|
|
158
|
+
const root = envValue(env, 'SystemRoot') || envValue(env, 'SYSTEMROOT') || envValue(env, 'windir') || 'C:\\Windows';
|
|
159
|
+
const ps = path.win32.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
|
|
160
|
+
const r = require('child_process').spawnSync(ps,
|
|
161
|
+
['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')],
|
|
162
|
+
{ encoding: 'ascii', timeout, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
163
|
+
if (r.error) return { error: r.error.code === 'ETIMEDOUT' ? `timed out after ${+(timeout / 1000).toFixed(3)} s` : `powershell.exe could not run: ${r.error.code || r.error.message}` };
|
|
164
|
+
if (r.status !== 0) return { error: r.signal ? `powershell.exe was stopped by ${r.signal}` : `powershell.exe exited with code ${r.status}` };
|
|
165
|
+
return { stdout: r.stdout };
|
|
166
|
+
} catch (e) { return { error: `powershell.exe could not run: ${e.code || e.message}` }; }
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// The stdout of a Windows PowerShell script, or null on any failure.
|
|
170
|
+
function runPowerShell(script, opts) {
|
|
171
|
+
const r = runPowerShellResult(script, opts);
|
|
172
|
+
return r.error ? null : r.stdout;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* The Downloads values of the registry, { user, shell }, or { error } when
|
|
177
|
+
* they cannot be read (REGISTRY_TIMEOUT_MS at most).
|
|
178
|
+
*/
|
|
179
|
+
function readShellFolders({ env = process.env } = {}) {
|
|
180
|
+
const r = runPowerShellResult(SHELL_FOLDERS_SCRIPT, { env });
|
|
181
|
+
return r.error ? { error: r.error } : parseShellFolders(r.stdout);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* The user's downloads folder. Windows: the Downloads value of User Shell
|
|
186
|
+
* Folders (with %VAR% expanded), then of Shell Folders, then <home>\Downloads;
|
|
187
|
+
* the first that is a directory. macOS: ~/Downloads. Linux: XDG_DOWNLOAD_DIR
|
|
188
|
+
* (environment, else ~/.config/user-dirs.dirs, where a localized system names
|
|
189
|
+
* it), else ~/Downloads. null when it does not exist.
|
|
190
|
+
*/
|
|
191
|
+
function downloadsDir(opts = {}) {
|
|
192
|
+
return findDownloads(opts).dir;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* downloadsDir() with the reason a Windows registry read failed:
|
|
197
|
+
* { dir, registryError, fallback }; fallback is <home>/Downloads, the place
|
|
198
|
+
* looked at last.
|
|
199
|
+
*/
|
|
200
|
+
function findDownloads({ platform = process.platform, env = process.env, homedir = os.homedir(), isDir = isDirectory,
|
|
201
|
+
readFile = p => fs.readFileSync(p, 'utf8'), shellFolders = readShellFolders } = {}) {
|
|
202
|
+
const P = pathFor(platform);
|
|
203
|
+
const fallback = P.join(homedir, 'Downloads');
|
|
204
|
+
let dir = fallback;
|
|
205
|
+
let registryError = null;
|
|
206
|
+
if (platform === 'win32') {
|
|
207
|
+
const sf = shellFolders({ env }) || {};
|
|
208
|
+
if (sf.error) registryError = sf.error;
|
|
209
|
+
for (const v of [sf.user, sf.shell]) {
|
|
210
|
+
if (typeof v !== 'string' || !v) continue;
|
|
211
|
+
const e = expandWindowsEnv(v, env);
|
|
212
|
+
if (P.isAbsolute(e) && isDir(e)) return { dir: e, registryError, fallback };
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
if (platform !== 'win32' && platform !== 'darwin') {
|
|
216
|
+
const expand = v => v.replace(/^\$HOME(?=\/|$)/, homedir).replace(/^~(?=\/|$)/, homedir);
|
|
217
|
+
let xdg = envValue(env, 'XDG_DOWNLOAD_DIR');
|
|
218
|
+
if (!xdg) {
|
|
219
|
+
const confHome = envValue(env, 'XDG_CONFIG_HOME') && P.isAbsolute(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : P.join(homedir, '.config');
|
|
220
|
+
try {
|
|
221
|
+
const text = readFile(P.join(confHome, 'user-dirs.dirs'));
|
|
222
|
+
const m = /^\s*XDG_DOWNLOAD_DIR\s*=\s*"([^"]*)"\s*$/m.exec(text);
|
|
223
|
+
if (m) xdg = m[1];
|
|
224
|
+
} catch {}
|
|
225
|
+
}
|
|
226
|
+
if (xdg) {
|
|
227
|
+
const e = expand(xdg);
|
|
228
|
+
// A value equal to $HOME means "no downloads folder".
|
|
229
|
+
if (P.isAbsolute(e) && P.resolve(e) !== P.resolve(homedir)) dir = e;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
return { dir: isDir(dir) ? dir : null, registryError, fallback };
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function isDirectory(p) {
|
|
236
|
+
try { return fs.statSync(p).isDirectory(); } catch { return false; }
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// ------------------------------------------------------------- subnets (CIDR)
|
|
240
|
+
|
|
241
|
+
function ipToInt(ip) {
|
|
242
|
+
const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(ip);
|
|
243
|
+
if (!m) return null;
|
|
244
|
+
const o = m.slice(1).map(Number);
|
|
245
|
+
if (o.some(n => n > 255)) return null;
|
|
246
|
+
return ((o[0] << 24) >>> 0) + (o[1] << 16) + (o[2] << 8) + o[3];
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function intToIp(n) {
|
|
250
|
+
return [n >>> 24, (n >>> 16) & 255, (n >>> 8) & 255, n & 255].join('.');
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function isPrivateIp(n) {
|
|
254
|
+
return (n >>> 24) === 10 || (n >>> 20) === ((172 << 4) | 1) || (n >>> 16) === ((192 << 8) | 168);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** "192.0.2.0/24" -> { base, prefix } or a problem string. Private ranges only, no wider than /22. */
|
|
258
|
+
function parseSubnet(s) {
|
|
259
|
+
const m = /^([\d.]+)\/(\d{1,2})$/.exec(String(s).trim());
|
|
260
|
+
if (!m) return `"${s}" is not a subnet in CIDR form (e.g. 192.168.77.0/24)`;
|
|
261
|
+
const ip = ipToInt(m[1]);
|
|
262
|
+
const prefix = Number(m[2]);
|
|
263
|
+
if (ip === null || prefix > 32) return `"${s}" is not a valid subnet`;
|
|
264
|
+
if (prefix < 22) return `"${s}" is wider than /22`;
|
|
265
|
+
const mask = prefix === 0 ? 0 : (0xffffffff << (32 - prefix)) >>> 0;
|
|
266
|
+
const base = (ip & mask) >>> 0;
|
|
267
|
+
if (!isPrivateIp(base)) return `"${s}" is not a private range (10/8, 172.16/12, 192.168/16)`;
|
|
268
|
+
return { base, prefix, text: `${intToIp(base)}/${prefix}` };
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// An entry of allowed_hosts: a host name or address without scheme, port or
|
|
272
|
+
// path; an IPv6 address in brackets. null when it is valid.
|
|
273
|
+
function hostNameProblem(h) {
|
|
274
|
+
if (typeof h !== 'string' || h === '') return 'every entry must be a non-empty string';
|
|
275
|
+
if (h.includes('/')) return `"${h}" must be a host name, without a scheme or a path`;
|
|
276
|
+
const v6 = /^\[[0-9A-Fa-f:.]+\]$/.test(h);
|
|
277
|
+
if (!v6 && h.includes(':')) return `"${h}" must be a host name without a port (an IPv6 address goes in brackets)`;
|
|
278
|
+
let parsed;
|
|
279
|
+
try { parsed = new URL(`http://${h}`); } catch { return `"${h}" is not a valid host name`; }
|
|
280
|
+
if (!parsed.hostname || parsed.port || parsed.username || parsed.pathname !== '/' || parsed.search || parsed.hash)
|
|
281
|
+
return `"${h}" is not a valid host name`;
|
|
282
|
+
return null;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// An entry of devices: ip, ip:port or a host name, no spaces. null when valid.
|
|
286
|
+
function deviceProblem(d) {
|
|
287
|
+
if (typeof d !== 'string' || d === '') return 'every entry must be a non-empty string';
|
|
288
|
+
if (/[\s,]/.test(d)) return `"${d}" must be one host (ip or ip:port), without spaces or commas`;
|
|
289
|
+
return null;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// Validates the parsed file and returns its settings; defaults are not filled
|
|
293
|
+
// in here.
|
|
294
|
+
function parseConfig(raw, file) {
|
|
295
|
+
const problems = [];
|
|
296
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new ConfigError(`${file}: must be a JSON object`);
|
|
297
|
+
for (const k of Object.keys(raw)) if (!KEYS.has(k)) problems.push(`unknown key "${k}"`);
|
|
298
|
+
|
|
299
|
+
const c = raw.$comment;
|
|
300
|
+
if (c !== undefined && typeof c !== 'string' && !(Array.isArray(c) && c.every(s => typeof s === 'string')))
|
|
301
|
+
problems.push('"$comment" must be a string or an array of strings');
|
|
302
|
+
for (const k of ['store', 'state_dir']) {
|
|
303
|
+
if (raw[k] === undefined) continue;
|
|
304
|
+
if (typeof raw[k] !== 'string' || !path.isAbsolute(raw[k])) problems.push(`"${k}" must be an absolute path`);
|
|
305
|
+
}
|
|
306
|
+
if (raw.port !== undefined && !isPort(raw.port)) problems.push('"port" must be an integer 0-65535');
|
|
307
|
+
if (raw.reconnect_interval !== undefined && !isReconnectInterval(raw.reconnect_interval))
|
|
308
|
+
problems.push(`"reconnect_interval" must be ${RECONNECT_RULE}`);
|
|
309
|
+
if (raw.host !== undefined && (typeof raw.host !== 'string' || !raw.host)) problems.push('"host" must be a non-empty string');
|
|
310
|
+
for (const k of ['log_requests', 'allow_shell', 'allow_uninstall']) {
|
|
311
|
+
if (raw[k] !== undefined && typeof raw[k] !== 'boolean') problems.push(`"${k}" must be true or false`);
|
|
312
|
+
}
|
|
313
|
+
if (raw.adb_path !== undefined && (typeof raw.adb_path !== 'string' || !raw.adb_path)) problems.push('"adb_path" must be a non-empty string');
|
|
314
|
+
if (raw.allowed_hosts !== undefined) {
|
|
315
|
+
if (!Array.isArray(raw.allowed_hosts)) problems.push('"allowed_hosts" must be an array of host names');
|
|
316
|
+
else for (const h of raw.allowed_hosts) {
|
|
317
|
+
const why = hostNameProblem(h);
|
|
318
|
+
if (why) problems.push(`"allowed_hosts": ${why}`);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
if (raw.devices !== undefined) {
|
|
322
|
+
if (!Array.isArray(raw.devices)) problems.push('"devices" must be an array of hosts');
|
|
323
|
+
else for (const d of raw.devices) {
|
|
324
|
+
const why = deviceProblem(d);
|
|
325
|
+
if (why) problems.push(`"devices": ${why}`);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
if (raw.file_roots !== undefined) {
|
|
329
|
+
if (!Array.isArray(raw.file_roots)) problems.push('"file_roots" must be an array of absolute paths');
|
|
330
|
+
else for (const r of raw.file_roots) {
|
|
331
|
+
if (typeof r !== 'string' || !path.isAbsolute(r)) problems.push(`"file_roots": ${JSON.stringify(r)} must be an absolute path`);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
if (raw.scan_subnets !== undefined) {
|
|
335
|
+
if (!Array.isArray(raw.scan_subnets)) problems.push('"scan_subnets" must be an array of subnets');
|
|
336
|
+
else for (const s of raw.scan_subnets) {
|
|
337
|
+
const r = parseSubnet(s);
|
|
338
|
+
if (typeof r === 'string') problems.push(`"scan_subnets": ${r}`);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
if (problems.length) throw new ConfigError(`${file}: invalid config\n ${problems.join('\n ')}`);
|
|
342
|
+
return raw;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function configCandidates({ env = process.env, cwd = process.cwd(), platform = process.platform, homedir = os.homedir() } = {}) {
|
|
346
|
+
const list = [];
|
|
347
|
+
const fromEnv = envValue(env, 'BRICKPROOF_CONFIG');
|
|
348
|
+
if (fromEnv) list.push({ path: path.resolve(cwd, fromEnv), source: 'env BRICKPROOF_CONFIG', required: true });
|
|
349
|
+
const { configDir } = platformDirs({ platform, env, homedir });
|
|
350
|
+
list.push({ path: path.join(configDir, 'config.json'), source: 'config directory' });
|
|
351
|
+
return list;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
function readConfigFile(file) {
|
|
355
|
+
let text;
|
|
356
|
+
try { text = fs.readFileSync(file, 'utf8'); }
|
|
357
|
+
catch (e) { throw new ConfigError(`${file}: cannot read (${e.code || e.message})`); }
|
|
358
|
+
try { return JSON.parse(text.replace(/^/, '')); }
|
|
359
|
+
catch (e) {
|
|
360
|
+
// The engine message may quote a slice of the file; only the position is
|
|
361
|
+
// reported.
|
|
362
|
+
const m = /position (\d+)/.exec(e.message);
|
|
363
|
+
let where = '';
|
|
364
|
+
if (m) {
|
|
365
|
+
const before = text.slice(0, Number(m[1]));
|
|
366
|
+
where = ` at line ${before.split('\n').length}, column ${Number(m[1]) - before.lastIndexOf('\n')}`;
|
|
367
|
+
}
|
|
368
|
+
throw new ConfigError(`${file}: not valid JSON${where}`);
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// A boolean from the environment: true/1 or false/0, anything else is an error.
|
|
373
|
+
function envBool(env, name) {
|
|
374
|
+
const v = envValue(env, name);
|
|
375
|
+
if (v === undefined) return undefined;
|
|
376
|
+
const s = v.trim().toLowerCase();
|
|
377
|
+
if (s === 'true' || s === '1') return true;
|
|
378
|
+
if (s === 'false' || s === '0') return false;
|
|
379
|
+
throw new ConfigError(`env ${name} must be true or false (or 1 / 0), got ${JSON.stringify(v.slice(0, 40))}`);
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
// BRICKPROOF_RECONNECT_INTERVAL: 0 or 15-3600, anything else is an error.
|
|
383
|
+
function envReconnect(env) {
|
|
384
|
+
const v = envValue(env, ENV_OF.reconnect_interval);
|
|
385
|
+
if (v === undefined) return undefined;
|
|
386
|
+
const n = reconnectOf(v);
|
|
387
|
+
if (!isReconnectInterval(n))
|
|
388
|
+
throw new ConfigError(`env ${ENV_OF.reconnect_interval} must be ${RECONNECT_RULE}, got ${JSON.stringify(v.slice(0, 40))}`);
|
|
389
|
+
return n;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** BRICKPROOF_FILE_ROOTS: absolute paths separated by path.delimiter; empty items dropped. */
|
|
393
|
+
function splitRoots(value, delimiter = path.delimiter) {
|
|
394
|
+
return String(value).split(delimiter).map(s => s.trim()).filter(Boolean);
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/** BRICKPROOF_DEVICES, BRICKPROOF_SCAN_SUBNETS: separated by commas and/or whitespace; empty items dropped. */
|
|
398
|
+
function splitDevices(value) {
|
|
399
|
+
return String(value).split(/[\s,]+/).filter(Boolean);
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* Resolved settings with the source of each in `sources`. `flags` holds the
|
|
404
|
+
* command-line values: port, host (serve) and file_roots (the directory
|
|
405
|
+
* arguments of stdio).
|
|
406
|
+
*/
|
|
407
|
+
function loadConfig({ env = process.env, cwd = process.cwd(), platform = process.platform, homedir = os.homedir(), flags = {}, isDir = isDirectory,
|
|
408
|
+
shellFolders = readShellFolders } = {}) {
|
|
409
|
+
const candidates = configCandidates({ env, cwd, platform, homedir });
|
|
410
|
+
let hit = null;
|
|
411
|
+
for (const c of candidates) {
|
|
412
|
+
if (fs.existsSync(c.path)) { hit = c; break; }
|
|
413
|
+
if (c.required) throw new ConfigError(`config file from env BRICKPROOF_CONFIG not found: ${c.path}`);
|
|
414
|
+
}
|
|
415
|
+
const file = hit ? parseConfig(readConfigFile(hit.path), hit.path) : {};
|
|
416
|
+
const fileSrc = hit ? `config ${hit.path}` : null;
|
|
417
|
+
const dirs = platformDirs({ platform, env, homedir });
|
|
418
|
+
|
|
419
|
+
const settings = {};
|
|
420
|
+
const sources = {};
|
|
421
|
+
const pick = (key, ...options) => {
|
|
422
|
+
for (const [value, source] of options) {
|
|
423
|
+
if (value !== undefined) { settings[key] = value; sources[key] = source; return; }
|
|
424
|
+
}
|
|
425
|
+
};
|
|
426
|
+
const fromEnv = (name, convert = v => v) => (envValue(env, name) !== undefined ? convert(env[name]) : undefined);
|
|
427
|
+
|
|
428
|
+
pick('port', [flags.port, 'flag --port'], [file.port, fileSrc], [DEFAULTS.port, 'default']);
|
|
429
|
+
pick('host', [flags.host, 'flag --host'], [file.host, fileSrc], [DEFAULTS.host, 'default']);
|
|
430
|
+
pick('allowed_hosts', [file.allowed_hosts, fileSrc], [DEFAULTS.allowed_hosts, 'default']);
|
|
431
|
+
for (const key of ['log_requests', 'allow_shell', 'allow_uninstall'])
|
|
432
|
+
pick(key, [envBool(env, ENV_OF[key]), `env ${ENV_OF[key]}`], [file[key], fileSrc], [DEFAULTS[key], 'default']);
|
|
433
|
+
|
|
434
|
+
pick('devices', [fromEnv('BRICKPROOF_DEVICES', splitDevices), 'env BRICKPROOF_DEVICES'], [file.devices, fileSrc], [DEFAULTS.devices, 'default']);
|
|
435
|
+
pick('reconnect_interval', [envReconnect(env), `env ${ENV_OF.reconnect_interval}`], [file.reconnect_interval, fileSrc],
|
|
436
|
+
[DEFAULTS.reconnect_interval, 'default']);
|
|
437
|
+
|
|
438
|
+
const envSubnets = fromEnv('BRICKPROOF_SCAN_SUBNETS', splitDevices);
|
|
439
|
+
if (envSubnets) {
|
|
440
|
+
const bad = envSubnets.map(parseSubnet).filter(r => typeof r === 'string');
|
|
441
|
+
if (bad.length) throw new ConfigError(`env BRICKPROOF_SCAN_SUBNETS: ${bad.join('; ')}`);
|
|
442
|
+
}
|
|
443
|
+
pick('scan_subnets', [envSubnets, 'env BRICKPROOF_SCAN_SUBNETS'], [file.scan_subnets, fileSrc], [DEFAULTS.scan_subnets, 'default']);
|
|
444
|
+
settings.scan_subnets = settings.scan_subnets.map(s => parseSubnet(s).text);
|
|
445
|
+
|
|
446
|
+
// file_roots: an empty value counts as set (to nothing), unlike the other
|
|
447
|
+
// lists. Not set by any source: the downloads folder, when it exists.
|
|
448
|
+
const envRootsRaw = env.BRICKPROOF_FILE_ROOTS;
|
|
449
|
+
const envRoots = envRootsRaw === undefined || /^\$\{user_config\.[A-Za-z0-9_]+\}$/.test(envRootsRaw) ? undefined : splitRoots(envRootsRaw);
|
|
450
|
+
if (envRoots) {
|
|
451
|
+
const bad = envRoots.filter(r => !path.isAbsolute(r));
|
|
452
|
+
if (bad.length) throw new ConfigError(`env BRICKPROOF_FILE_ROOTS: every entry must be an absolute path (separator "${path.delimiter}"): ${bad.map(b => JSON.stringify(b)).join(', ')}`);
|
|
453
|
+
}
|
|
454
|
+
const flagRoots = flags.file_roots && flags.file_roots.length ? flags.file_roots.map(r => path.resolve(cwd, r)) : undefined;
|
|
455
|
+
const found = flagRoots || envRoots || file.file_roots ? null : findDownloads({ platform, env, homedir, isDir, shellFolders });
|
|
456
|
+
const downloads = found && found.dir;
|
|
457
|
+
// A failed registry read is said, not passed over: the folder found, or not
|
|
458
|
+
// found, may not be the one the system has for Downloads.
|
|
459
|
+
const registryNote = found && found.registryError
|
|
460
|
+
? `the registry could not be read: ${found.registryError}; ${found.fallback} ${downloads ? 'used' : 'not found'}`
|
|
461
|
+
: null;
|
|
462
|
+
pick('file_roots',
|
|
463
|
+
[flagRoots, 'arguments'],
|
|
464
|
+
[envRoots, 'env BRICKPROOF_FILE_ROOTS'],
|
|
465
|
+
[file.file_roots, fileSrc],
|
|
466
|
+
[downloads ? [downloads] : undefined, registryNote ? `default: ${registryNote}` : 'default'],
|
|
467
|
+
[[], registryNote ? `default: ${registryNote}` : 'default: no Downloads folder found']);
|
|
468
|
+
settings.file_roots = settings.file_roots.map(r => path.resolve(r));
|
|
469
|
+
|
|
470
|
+
pick('state_dir',
|
|
471
|
+
[fromEnv('BRICKPROOF_STATE_DIR', v => path.resolve(cwd, v)), 'env BRICKPROOF_STATE_DIR'],
|
|
472
|
+
[file.state_dir !== undefined ? path.resolve(file.state_dir) : undefined, fileSrc],
|
|
473
|
+
[dirs.stateDir, 'default']);
|
|
474
|
+
pick('store',
|
|
475
|
+
[fromEnv('BRICKPROOF_STORE', v => path.resolve(cwd, v)), 'env BRICKPROOF_STORE'],
|
|
476
|
+
[file.store !== undefined ? path.resolve(file.store) : undefined, fileSrc],
|
|
477
|
+
[path.join(settings.state_dir, 'snapshots'), 'default: <state_dir>/snapshots']);
|
|
478
|
+
|
|
479
|
+
// A bare name ("adb") is looked up on PATH by the system; a path with a
|
|
480
|
+
// directory part is resolved against the working directory. The default is
|
|
481
|
+
// not a path: the adb search of platform-tools.js decides.
|
|
482
|
+
const adbOf = v => (/[\\/]/.test(v) ? path.resolve(cwd, v) : v);
|
|
483
|
+
pick('adb_path',
|
|
484
|
+
[fromEnv('BRICKPROOF_ADB', adbOf), 'env BRICKPROOF_ADB'],
|
|
485
|
+
[file.adb_path !== undefined ? adbOf(file.adb_path) : undefined, fileSrc],
|
|
486
|
+
[DEFAULTS.adb_path, 'default']);
|
|
487
|
+
|
|
488
|
+
return {
|
|
489
|
+
settings,
|
|
490
|
+
sources,
|
|
491
|
+
settingsUi: envValue(env, 'BRICKPROOF_SETTINGS_UI') || null,
|
|
492
|
+
file: hit ? hit.path : null,
|
|
493
|
+
fileSource: hit ? hit.source : null,
|
|
494
|
+
searched: candidates.map(c => c.path),
|
|
495
|
+
configDir: dirs.configDir,
|
|
496
|
+
writeTarget: candidates[0].path,
|
|
497
|
+
// For a warning line at start: why the Downloads folder may be wrong.
|
|
498
|
+
downloadsWarning: registryNote ? `the Downloads folder is uncertain: ${registryNote}; set file_roots to choose the folder` : null,
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
// The BRICKPROOF_SETTINGS_UI of the Docker image (Dockerfile).
|
|
503
|
+
const CONTAINER_UI = 'the environment of the container';
|
|
504
|
+
|
|
505
|
+
/**
|
|
506
|
+
* What a person does to change a setting, for refusal texts: the settings UI
|
|
507
|
+
* of the launcher when there is one (BRICKPROOF_SETTINGS_UI; the container's
|
|
508
|
+
* environment names the variable), else the environment variable the value
|
|
509
|
+
* came from, else `brickproof-adb set`.
|
|
510
|
+
*/
|
|
511
|
+
function settingAction(key, loaded) {
|
|
512
|
+
const ui = loaded && loaded.settingsUi;
|
|
513
|
+
const source = loaded && loaded.sources ? loaded.sources[key] : null;
|
|
514
|
+
const fromEnv = typeof source === 'string' && source.startsWith('env ');
|
|
515
|
+
// The Docker image: settings are environment variables of the container.
|
|
516
|
+
if (ui === CONTAINER_UI) {
|
|
517
|
+
if (key === 'file_roots')
|
|
518
|
+
return `mount a host folder into the container and set ${ENV_OF.file_roots} in ${CONTAINER_UI} to its path inside the container, then recreate the container (docker compose up -d)`;
|
|
519
|
+
return `set ${ENV_OF[key]}=true in ${CONTAINER_UI} and recreate the container (docker compose up -d)`;
|
|
520
|
+
}
|
|
521
|
+
if (key === 'file_roots') {
|
|
522
|
+
if (ui) return `add a folder to file_roots in ${ui}`;
|
|
523
|
+
if (fromEnv) return `add a folder to the environment variable ${ENV_OF.file_roots} where the server is started, and restart it`;
|
|
524
|
+
return 'run `brickproof-adb set file_roots <folder>` and restart the server';
|
|
525
|
+
}
|
|
526
|
+
if (ui) return `turn on ${key} in ${ui}`;
|
|
527
|
+
if (fromEnv) return `set the environment variable ${ENV_OF[key]}=true where the server is started, and restart it`;
|
|
528
|
+
return `run \`brickproof-adb set ${key} on\` and restart the server`;
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
/** The action texts of the settings refusals name, for server.init(). */
|
|
532
|
+
function settingHints(loaded) {
|
|
533
|
+
return {
|
|
534
|
+
allow_shell: settingAction('allow_shell', loaded),
|
|
535
|
+
allow_uninstall: settingAction('allow_uninstall', loaded),
|
|
536
|
+
file_roots: settingAction('file_roots', loaded),
|
|
537
|
+
};
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
// ---------------------------------------------------------------- set command
|
|
541
|
+
|
|
542
|
+
const SETTABLE = ['port', 'host', 'allowed_hosts', 'log_requests', 'allow_shell', 'allow_uninstall', 'devices', 'file_roots',
|
|
543
|
+
'scan_subnets', 'store', 'state_dir', 'adb_path', 'reconnect_interval'];
|
|
544
|
+
const LISTS = new Set(['allowed_hosts', 'devices', 'file_roots', 'scan_subnets']);
|
|
545
|
+
const BOOLS = new Set(['log_requests', 'allow_shell', 'allow_uninstall']);
|
|
546
|
+
|
|
547
|
+
/** The JSON value of `set <key> <words...>`; throws ConfigError with a hint. */
|
|
548
|
+
function settingValue(key, words, cwd = process.cwd()) {
|
|
549
|
+
if (!SETTABLE.includes(key)) throw new ConfigError(`unknown setting "${key}"; settings: ${SETTABLE.join(', ')}`);
|
|
550
|
+
if (BOOLS.has(key)) {
|
|
551
|
+
if (words.length !== 1) throw new ConfigError(`${key} takes one value: on or off`);
|
|
552
|
+
const w = words[0].toLowerCase();
|
|
553
|
+
if (w === 'on' || w === 'true') return true;
|
|
554
|
+
if (w === 'off' || w === 'false') return false;
|
|
555
|
+
throw new ConfigError(`${key} takes on or off, got "${words[0]}"`);
|
|
556
|
+
}
|
|
557
|
+
if (LISTS.has(key)) {
|
|
558
|
+
const items = key === 'file_roots' ? words : words.flatMap(splitDevices);
|
|
559
|
+
return key === 'file_roots' ? items.map(w => path.resolve(cwd, w)) : items;
|
|
560
|
+
}
|
|
561
|
+
if (words.length !== 1) throw new ConfigError(`${key} takes one value`);
|
|
562
|
+
if (key === 'port') {
|
|
563
|
+
if (!/^\d+$/.test(words[0])) throw new ConfigError('port must be an integer 0-65535');
|
|
564
|
+
return Number(words[0]);
|
|
565
|
+
}
|
|
566
|
+
if (key === 'reconnect_interval') {
|
|
567
|
+
const n = reconnectOf(words[0]);
|
|
568
|
+
if (!isReconnectInterval(n)) throw new ConfigError(`reconnect_interval must be ${RECONNECT_RULE}`);
|
|
569
|
+
return n;
|
|
570
|
+
}
|
|
571
|
+
if (key === 'store' || key === 'state_dir') return path.resolve(cwd, words[0]);
|
|
572
|
+
if (key === 'adb_path') return /[\\/]/.test(words[0]) ? path.resolve(cwd, words[0]) : words[0];
|
|
573
|
+
return words[0];
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
/**
|
|
577
|
+
* `brickproof-adb set <key> [<value>...]`: write one key into the settings
|
|
578
|
+
* file (created with its directory when missing); no value removes the key,
|
|
579
|
+
* so the default applies. Returns { file, value, removed }.
|
|
580
|
+
*/
|
|
581
|
+
function writeSetting(file, key, words, { cwd = process.cwd() } = {}) {
|
|
582
|
+
let current = {};
|
|
583
|
+
if (fs.existsSync(file)) current = readConfigFile(file);
|
|
584
|
+
if (!current || typeof current !== 'object' || Array.isArray(current)) throw new ConfigError(`${file}: must be a JSON object`);
|
|
585
|
+
const next = { ...current };
|
|
586
|
+
let value = null;
|
|
587
|
+
if (!words.length) {
|
|
588
|
+
if (!SETTABLE.includes(key)) throw new ConfigError(`unknown setting "${key}"; settings: ${SETTABLE.join(', ')}`);
|
|
589
|
+
delete next[key];
|
|
590
|
+
} else {
|
|
591
|
+
value = settingValue(key, words, cwd);
|
|
592
|
+
next[key] = value;
|
|
593
|
+
}
|
|
594
|
+
parseConfig(next, file);
|
|
595
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
596
|
+
const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
|
|
597
|
+
fs.writeFileSync(tmp, JSON.stringify(next, null, 2) + '\n', 'utf8');
|
|
598
|
+
fs.renameSync(tmp, file);
|
|
599
|
+
return { file, value, removed: !words.length };
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
// The state directory is created on start with mode 0700; an existing one is
|
|
603
|
+
// left as it is.
|
|
604
|
+
function ensureStateDir(dir) {
|
|
605
|
+
// Not writable (a Docker volume or bind mount owned by root while the
|
|
606
|
+
// process runs as another user): say what to do, not a stack trace.
|
|
607
|
+
const uid = typeof process.getuid === 'function' ? process.getuid() : null;
|
|
608
|
+
const hint = owner => `state_dir ${dir} is not writable by this process` +
|
|
609
|
+
(uid !== null ? ` (uid ${uid}${owner !== null ? `; the directory belongs to uid ${owner}` : ''})` : '') +
|
|
610
|
+
`: make it writable for${uid !== null ? ` uid ${uid}` : ' this user'} (for a Docker volume or bind mount: chown ${uid !== null ? `${uid}:${uid}` : '<uid>:<gid>'} on it), run as its owner, or set state_dir to another directory`;
|
|
611
|
+
try {
|
|
612
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
613
|
+
} catch (e) {
|
|
614
|
+
if (e.code === 'EACCES' || e.code === 'EPERM' || e.code === 'EROFS') throw new ConfigError(hint(null));
|
|
615
|
+
throw e;
|
|
616
|
+
}
|
|
617
|
+
try {
|
|
618
|
+
fs.accessSync(dir, fs.constants.W_OK | fs.constants.X_OK);
|
|
619
|
+
} catch {
|
|
620
|
+
let owner = null;
|
|
621
|
+
try { owner = fs.statSync(dir).uid; } catch {}
|
|
622
|
+
throw new ConfigError(hint(owner));
|
|
623
|
+
}
|
|
624
|
+
return dir;
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
module.exports = {
|
|
628
|
+
DEFAULTS, ConfigError, APP_DIR, KEYS, ENV_OF, SETTABLE, RECONNECT_MIN, RECONNECT_MAX,
|
|
629
|
+
platformDirs, downloadsDir, findDownloads, REGISTRY_TIMEOUT_MS, parseShellFolders, expandWindowsEnv, readShellFolders, runPowerShell, runPowerShellResult, parseConfig, configCandidates, loadConfig, ensureStateDir, splitRoots, splitDevices, envBool,
|
|
630
|
+
parseSubnet, ipToInt, intToIp, isPrivateIp,
|
|
631
|
+
settingAction, settingHints, settingValue, writeSetting,
|
|
632
|
+
};
|