@ds-hu/dsh-tailcat-remote 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/NOTICE +33 -0
- package/README.en.md +115 -0
- package/README.md +114 -2
- package/client.js +1205 -0
- package/cordis.patch.yml +39 -0
- package/docs/CONTRACT.md +186 -0
- package/docs/SECURITY.md +97 -0
- package/docs/TECHNICAL.md +156 -0
- package/docs/screenshots/01-pairing.png +0 -0
- package/docs/screenshots/02-security.png +0 -0
- package/docs/screenshots/03-install.png +0 -0
- package/icon.svg +18 -0
- package/index.js +34 -0
- package/locale/de.json +6 -0
- package/locale/en.json +6 -0
- package/locale/es.json +6 -0
- package/locale/fr.json +6 -0
- package/locale/ja.json +6 -0
- package/locale/pt.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +78 -4
- package/src/config.js +130 -0
- package/src/control.js +84 -0
- package/src/devices.js +153 -0
- package/src/door.js +472 -0
- package/src/errors.js +24 -0
- package/src/installer.js +824 -0
- package/src/parse.js +241 -0
- package/src/paths.js +109 -0
- package/src/qr.js +61 -0
- package/src/remote.js +272 -0
- package/src/tailcat.js +715 -0
- package/vendor/qrcode.mjs +2289 -0
package/src/installer.js
ADDED
|
@@ -0,0 +1,824 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import fsp from 'node:fs/promises';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { Readable, Transform } from 'node:stream';
|
|
7
|
+
import { pipeline } from 'node:stream/promises';
|
|
8
|
+
import { RemoteAccessError, errorMessage } from './errors.js';
|
|
9
|
+
import { dataDir, findKnownTailcat, managedBinaryDir, managedBinaryPath } from './paths.js';
|
|
10
|
+
|
|
11
|
+
/** The upstream tailcat build this plugin knows how to install. */
|
|
12
|
+
export const TAILCAT_VERSION = '0.8.0';
|
|
13
|
+
export const TAILCAT_TAG = 'v0.8.0';
|
|
14
|
+
export const UPSTREAM_RELEASES = `https://github.com/tailscale/tailcat/releases/download/${TAILCAT_TAG}`;
|
|
15
|
+
export const MANUAL_INSTALL_URL = 'https://github.com/tailscale/tailcat#install';
|
|
16
|
+
/** Minimum tailcat release: Unix-socket serve targets and --log arrived in 0.8.0. */
|
|
17
|
+
export const MIN_TAILCAT_VERSION = '0.8.0';
|
|
18
|
+
|
|
19
|
+
const MAX_ARCHIVE_BYTES = 64 * 1024 * 1024;
|
|
20
|
+
const MAX_TEXT_BYTES = 512 * 1024;
|
|
21
|
+
const COMMAND_TIMEOUT_MS = 180_000;
|
|
22
|
+
const BREW_TIMEOUT_MS = 30 * 60_000;
|
|
23
|
+
const METADATA_FILE = 'tailcat.json';
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* One installable target. `archive` downloads an upstream release archive;
|
|
27
|
+
* `brew` delegates to Homebrew because tailcat does not publish macOS static
|
|
28
|
+
* binaries. `unsupported` still carries the manual instructions.
|
|
29
|
+
* @typedef {{kind: 'archive', os: string, arch: string, asset: string, format: 'tar.gz'|'zip', binary: string, source: 'upstream', assetUrl: string, checksumsUrl: string}
|
|
30
|
+
* | {kind: 'brew', os: string, arch: string, binary: string, source: 'homebrew', formula: string, command: string}
|
|
31
|
+
* | {kind: 'unsupported', os: string, arch: string}} PlatformSpec
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Map Node's `process.platform`/`process.arch` to a tailcat distribution
|
|
36
|
+
* target. Kept pure so the panel and tests can describe the platform without
|
|
37
|
+
* starting a download.
|
|
38
|
+
* @param {string} [platform] - Node platform, defaults to the Host's.
|
|
39
|
+
* @param {string} [arch] - Node architecture, defaults to the Host's.
|
|
40
|
+
* @returns {PlatformSpec} install target.
|
|
41
|
+
*/
|
|
42
|
+
export function platformSpec(platform = process.platform, arch = process.arch) {
|
|
43
|
+
const key = `${platform}:${arch}`;
|
|
44
|
+
/** @type {Record<string, PlatformSpec>} */
|
|
45
|
+
const specs = {
|
|
46
|
+
'linux:x64': archiveSpec('linux', 'amd64', 'linux_amd64.tar.gz', 'tar.gz'),
|
|
47
|
+
'linux:arm64': archiveSpec('linux', 'arm64', 'linux_arm64.tar.gz', 'tar.gz'),
|
|
48
|
+
'linux:arm': archiveSpec('linux', 'armv7', 'linux_armv7.tar.gz', 'tar.gz'),
|
|
49
|
+
'win32:x64': archiveSpec('windows', 'amd64', 'windows_amd64.zip', 'zip'),
|
|
50
|
+
'win32:arm64': archiveSpec('windows', 'arm64', 'windows_arm64.zip', 'zip'),
|
|
51
|
+
'darwin:x64': {
|
|
52
|
+
kind: 'brew',
|
|
53
|
+
os: 'darwin',
|
|
54
|
+
arch: 'x64',
|
|
55
|
+
binary: 'tailcat',
|
|
56
|
+
source: 'homebrew',
|
|
57
|
+
formula: 'tailcat',
|
|
58
|
+
command: 'brew install tailcat',
|
|
59
|
+
},
|
|
60
|
+
'darwin:arm64': {
|
|
61
|
+
kind: 'brew',
|
|
62
|
+
os: 'darwin',
|
|
63
|
+
arch: 'arm64',
|
|
64
|
+
binary: 'tailcat',
|
|
65
|
+
source: 'homebrew',
|
|
66
|
+
formula: 'tailcat',
|
|
67
|
+
command: 'brew install tailcat',
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
return specs[key] ?? { kind: 'unsupported', os: platform, arch };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* @param {string} osName - archive OS.
|
|
75
|
+
* @param {string} arch - archive architecture label.
|
|
76
|
+
* @param {string} suffix - asset filename suffix.
|
|
77
|
+
* @param {'tar.gz'|'zip'} format - archive format.
|
|
78
|
+
* @returns {PlatformSpec} archive target.
|
|
79
|
+
*/
|
|
80
|
+
function archiveSpec(osName, arch, suffix, format) {
|
|
81
|
+
const asset = `tailcat_${TAILCAT_VERSION}_${suffix}`;
|
|
82
|
+
return {
|
|
83
|
+
kind: 'archive',
|
|
84
|
+
os: osName,
|
|
85
|
+
arch,
|
|
86
|
+
asset,
|
|
87
|
+
format,
|
|
88
|
+
binary: osName === 'windows' ? 'tailcat.exe' : 'tailcat',
|
|
89
|
+
source: 'upstream',
|
|
90
|
+
assetUrl: `${UPSTREAM_RELEASES}/${asset}`,
|
|
91
|
+
checksumsUrl: `${UPSTREAM_RELEASES}/checksums.txt`,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Parse a release checksum manifest (sha256 + whitespace + filename).
|
|
97
|
+
* @param {string} text - manifest contents.
|
|
98
|
+
* @returns {Map<string, string>} filename to lowercase digest.
|
|
99
|
+
*/
|
|
100
|
+
export function parseChecksums(text) {
|
|
101
|
+
const checksums = new Map();
|
|
102
|
+
for (const line of String(text).split(/\r?\n/)) {
|
|
103
|
+
const match = /^([0-9a-fA-F]{64})\s+\*?(.+?)\s*$/.exec(line.trim());
|
|
104
|
+
if (match) checksums.set(path.basename(match[2]), match[1].toLowerCase());
|
|
105
|
+
}
|
|
106
|
+
return checksums;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* @param {string} file - path to hash.
|
|
111
|
+
* @returns {Promise<string>} lowercase sha256.
|
|
112
|
+
*/
|
|
113
|
+
export async function sha256File(file) {
|
|
114
|
+
const hash = crypto.createHash('sha256');
|
|
115
|
+
for await (const chunk of fs.createReadStream(file)) hash.update(chunk);
|
|
116
|
+
return hash.digest('hex');
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Parse a semantic version out of `tailcat version` output.
|
|
121
|
+
* @param {string | null | undefined} value - version text.
|
|
122
|
+
* @returns {[number, number, number] | null} numeric triple.
|
|
123
|
+
*/
|
|
124
|
+
export function versionParts(value) {
|
|
125
|
+
const match = /(\d+)\.(\d+)\.(\d+)/.exec(String(value ?? ''));
|
|
126
|
+
return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* @param {string | null | undefined} version - candidate.
|
|
131
|
+
* @param {string} minimum - required semantic version.
|
|
132
|
+
* @returns {boolean} whether candidate is at least minimum.
|
|
133
|
+
*/
|
|
134
|
+
export function versionAtLeast(version, minimum) {
|
|
135
|
+
const left = versionParts(version);
|
|
136
|
+
const right = versionParts(minimum);
|
|
137
|
+
if (!left || !right) return false;
|
|
138
|
+
for (let index = 0; index < 3; index += 1) {
|
|
139
|
+
if (left[index] !== right[index]) return left[index] > right[index];
|
|
140
|
+
}
|
|
141
|
+
return true;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Install and update the managed tailcat executable without modifying PATH.
|
|
146
|
+
* Downloads are verified against the release checksum before extraction, and
|
|
147
|
+
* the archive is staged under DSH_HOME before an atomic replace.
|
|
148
|
+
*
|
|
149
|
+
* Detection is deliberately separate from installation: a tailcat already
|
|
150
|
+
* installed by the user stays in place and is used by the supervisor. The
|
|
151
|
+
* managed copy is only created after an explicit install action.
|
|
152
|
+
*/
|
|
153
|
+
export class TailcatInstaller {
|
|
154
|
+
/**
|
|
155
|
+
* @param {object} ctx - Host plugin context.
|
|
156
|
+
* @param {object} [options] - installer options.
|
|
157
|
+
* @param {any} [options.logger] - Host logger.
|
|
158
|
+
* @param {string} [options.releaseTag] - plugin release tag.
|
|
159
|
+
* @param {string} [options.requestedBinary] - configured binaryPath (defaults to `tailcat`).
|
|
160
|
+
* @param {typeof fetch} [options.fetchImpl] - fetch implementation.
|
|
161
|
+
* @param {(name: string, env: NodeJS.ProcessEnv) => Promise<string>} [options.resolveExecutable] - executable resolver.
|
|
162
|
+
* @param {(argv: string[], options: {timeoutMs?: number, env?: NodeJS.ProcessEnv, signal?: AbortSignal}) => Promise<{stdout: string, stderr: string, exitCode: number | null}>} [options.runCommand] - command runner.
|
|
163
|
+
* @param {string} [options.platform] - Node platform override.
|
|
164
|
+
* @param {string} [options.arch] - Node architecture override.
|
|
165
|
+
* @param {{dataDir?: string, binaryDir?: string, binaryPath?: string, stagingRoot?: string}} [options.paths] - path overrides.
|
|
166
|
+
*/
|
|
167
|
+
constructor(ctx, options = {}) {
|
|
168
|
+
this.ctx = ctx;
|
|
169
|
+
this.logger = options.logger ?? ctx.logger;
|
|
170
|
+
this.releaseTag = options.releaseTag ?? 'v0.0.0';
|
|
171
|
+
this.requestedBinary = options.requestedBinary ?? 'tailcat';
|
|
172
|
+
this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
|
|
173
|
+
this.platform = options.platform ?? process.platform;
|
|
174
|
+
this.arch = options.arch ?? process.arch;
|
|
175
|
+
this.spec = platformSpec(this.platform, this.arch);
|
|
176
|
+
this.dataDir = options.paths?.dataDir ?? dataDir();
|
|
177
|
+
this.binaryDir = options.paths?.binaryDir ?? managedBinaryDir();
|
|
178
|
+
this.binaryPath = options.paths?.binaryPath ?? managedBinaryPath(this.platform);
|
|
179
|
+
this.metadataPath = path.join(this.binaryDir, METADATA_FILE);
|
|
180
|
+
this.stagingRoot = options.paths?.stagingRoot ?? path.join(this.dataDir, '.install');
|
|
181
|
+
this.resolveExecutable =
|
|
182
|
+
options.resolveExecutable ?? ((name, env) => this.ctx.subprocess.resolveExecutable(name, env));
|
|
183
|
+
this.runCommand = options.runCommand ?? ((argv, runOptions) => this.runInHost(argv, runOptions));
|
|
184
|
+
|
|
185
|
+
this.phase = 'idle';
|
|
186
|
+
this.busy = false;
|
|
187
|
+
this.progress = null;
|
|
188
|
+
this.lastError = null;
|
|
189
|
+
this.installedAt = null;
|
|
190
|
+
this.promise = null;
|
|
191
|
+
this.abort = null;
|
|
192
|
+
this.disposed = false;
|
|
193
|
+
this.system = null;
|
|
194
|
+
this.systemPromise = null;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** @returns {object} display-safe installer state. */
|
|
198
|
+
snapshot() {
|
|
199
|
+
const installed = this.readInstalled();
|
|
200
|
+
return {
|
|
201
|
+
supported: this.spec.kind !== 'unsupported',
|
|
202
|
+
method: this.spec.kind === 'unsupported' ? null : this.spec.kind,
|
|
203
|
+
platform: this.platform,
|
|
204
|
+
arch: this.arch,
|
|
205
|
+
version: TAILCAT_VERSION,
|
|
206
|
+
installed: installed !== null,
|
|
207
|
+
installedVersion: installed?.version ?? null,
|
|
208
|
+
installedAt: installed?.installedAt ?? null,
|
|
209
|
+
source: installed?.source ?? null,
|
|
210
|
+
binaryPath: this.binaryPath,
|
|
211
|
+
asset: this.spec.kind === 'archive' ? this.spec.asset : null,
|
|
212
|
+
command: this.spec.kind === 'brew' ? this.spec.command : null,
|
|
213
|
+
manualUrl: MANUAL_INSTALL_URL,
|
|
214
|
+
busy: this.busy,
|
|
215
|
+
phase: this.phase,
|
|
216
|
+
progress: this.progress ? { ...this.progress } : null,
|
|
217
|
+
error: this.lastError,
|
|
218
|
+
system: this.system ? { ...this.system } : null,
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** @returns {boolean} whether the plugin-managed executable is installed. */
|
|
223
|
+
hasInstalled() {
|
|
224
|
+
return this.readInstalled() !== null;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Find a tailcat the user installed independently (PATH, Homebrew, an
|
|
229
|
+
* explicit binaryPath, ...). This never downloads or writes anything.
|
|
230
|
+
* @returns {Promise<object>} cached detection result.
|
|
231
|
+
*/
|
|
232
|
+
detectSystem() {
|
|
233
|
+
if (this.systemPromise) return this.systemPromise;
|
|
234
|
+
this.system = { status: 'checking', path: null, version: null, checkedAt: null };
|
|
235
|
+
this.systemPromise = this.detectSystemInternal()
|
|
236
|
+
.catch((error) => {
|
|
237
|
+
this.system = {
|
|
238
|
+
status: 'missing',
|
|
239
|
+
path: null,
|
|
240
|
+
version: null,
|
|
241
|
+
checkedAt: new Date().toISOString(),
|
|
242
|
+
error: errorMessage(error),
|
|
243
|
+
};
|
|
244
|
+
return this.system;
|
|
245
|
+
})
|
|
246
|
+
.finally(() => {
|
|
247
|
+
this.systemPromise = null;
|
|
248
|
+
});
|
|
249
|
+
return this.systemPromise;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** @private */
|
|
253
|
+
async detectSystemInternal() {
|
|
254
|
+
let resolved = null;
|
|
255
|
+
try {
|
|
256
|
+
resolved = await this.resolveExecutable(this.requestedBinary, process.env);
|
|
257
|
+
} catch {
|
|
258
|
+
resolved = this.requestedBinary === 'tailcat' ? findKnownTailcat(this.platform) : null;
|
|
259
|
+
}
|
|
260
|
+
if (!resolved) {
|
|
261
|
+
this.system = { status: 'missing', path: null, version: null, checkedAt: new Date().toISOString() };
|
|
262
|
+
return this.system;
|
|
263
|
+
}
|
|
264
|
+
let version = null;
|
|
265
|
+
try {
|
|
266
|
+
const result = await this.runCommand([resolved, 'version'], { timeoutMs: 15_000 });
|
|
267
|
+
const match = /v?(\d+\.\d+\.\d+)/.exec(`${result.stdout}\n${result.stderr}`);
|
|
268
|
+
if (match) version = match[0].startsWith('v') ? match[0] : `v${match[0]}`;
|
|
269
|
+
} catch {
|
|
270
|
+
// A version probe is diagnostic only. A path that exists and runs as
|
|
271
|
+
// an executable is still more useful than treating it as missing.
|
|
272
|
+
}
|
|
273
|
+
this.system = {
|
|
274
|
+
status: 'found',
|
|
275
|
+
path: resolved,
|
|
276
|
+
version,
|
|
277
|
+
compatible: version ? versionAtLeast(version, MIN_TAILCAT_VERSION) : null,
|
|
278
|
+
checkedAt: new Date().toISOString(),
|
|
279
|
+
};
|
|
280
|
+
return this.system;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* Download, verify, and install the managed executable.
|
|
285
|
+
* @param {{force?: boolean}} [options] - force reinstalls over an existing copy.
|
|
286
|
+
* @returns {Promise<object>} installer snapshot after completion.
|
|
287
|
+
*/
|
|
288
|
+
install(options = {}) {
|
|
289
|
+
if (this.disposed) {
|
|
290
|
+
return Promise.reject(new RemoteAccessError('disposed', 'The remote-access runtime is shutting down.', 503));
|
|
291
|
+
}
|
|
292
|
+
if (this.promise) return this.promise;
|
|
293
|
+
if (!options.force && this.readInstalled() !== null) return Promise.resolve(this.snapshot());
|
|
294
|
+
|
|
295
|
+
this.busy = true;
|
|
296
|
+
this.phase = 'starting';
|
|
297
|
+
this.progress = null;
|
|
298
|
+
this.lastError = null;
|
|
299
|
+
const controller = new AbortController();
|
|
300
|
+
this.abort = controller;
|
|
301
|
+
this.promise = this.installInternal(controller.signal)
|
|
302
|
+
.catch((error) => {
|
|
303
|
+
this.phase = 'error';
|
|
304
|
+
this.lastError = errorMessage(error);
|
|
305
|
+
throw error;
|
|
306
|
+
})
|
|
307
|
+
.finally(() => {
|
|
308
|
+
this.busy = false;
|
|
309
|
+
this.abort = null;
|
|
310
|
+
this.promise = null;
|
|
311
|
+
});
|
|
312
|
+
return this.promise;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** Stop an in-flight download when the plugin unloads. */
|
|
316
|
+
dispose() {
|
|
317
|
+
this.disposed = true;
|
|
318
|
+
this.abort?.abort();
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** @private */
|
|
322
|
+
async installInternal(signal) {
|
|
323
|
+
if (this.spec.kind === 'unsupported') {
|
|
324
|
+
throw new RemoteAccessError(
|
|
325
|
+
'tailcat-platform-unsupported',
|
|
326
|
+
`Automatic tailcat install is not available for ${this.platform}/${this.arch}. Install it manually from ${MANUAL_INSTALL_URL}, then put it on PATH or set binaryPath.`,
|
|
327
|
+
400,
|
|
328
|
+
);
|
|
329
|
+
}
|
|
330
|
+
await fsp.mkdir(this.dataDir, { recursive: true, mode: 0o700 });
|
|
331
|
+
await fsp.mkdir(this.binaryDir, { recursive: true, mode: 0o700 });
|
|
332
|
+
await fsp.mkdir(this.stagingRoot, { recursive: true, mode: 0o700 });
|
|
333
|
+
const staging = await fsp.mkdtemp(path.join(this.stagingRoot, 'run-'));
|
|
334
|
+
try {
|
|
335
|
+
const result =
|
|
336
|
+
this.spec.kind === 'archive'
|
|
337
|
+
? await this.installArchive(staging, signal)
|
|
338
|
+
: await this.installBrew(staging, signal);
|
|
339
|
+
this.phase = 'done';
|
|
340
|
+
this.progress = null;
|
|
341
|
+
this.installedAt = result.installedAt;
|
|
342
|
+
this.system = null;
|
|
343
|
+
this.logger.info(`tailcat-remote: installed tailcat ${result.version ?? TAILCAT_VERSION} from ${result.source}`);
|
|
344
|
+
return this.snapshot();
|
|
345
|
+
} finally {
|
|
346
|
+
await fsp.rm(staging, { recursive: true, force: true }).catch(() => {});
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** @private */
|
|
351
|
+
async installArchive(staging, signal) {
|
|
352
|
+
const spec = this.spec;
|
|
353
|
+
if (spec.kind !== 'archive') throw new Error('not an archive target');
|
|
354
|
+
this.phase = 'checksums';
|
|
355
|
+
const manifest = await this.fetchText(spec.checksumsUrl, signal);
|
|
356
|
+
const expected = parseChecksums(manifest).get(spec.asset);
|
|
357
|
+
if (!expected) {
|
|
358
|
+
throw new RemoteAccessError(
|
|
359
|
+
'tailcat-checksum-missing',
|
|
360
|
+
`The tailcat release checksums do not list ${spec.asset}. Refusing to install an unverified executable.`,
|
|
361
|
+
502,
|
|
362
|
+
);
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
const archivePath = path.join(staging, spec.asset);
|
|
366
|
+
this.phase = 'downloading';
|
|
367
|
+
this.progress = { phase: 'downloading', received: 0, total: 0, percent: null };
|
|
368
|
+
await this.download(spec.assetUrl, archivePath, signal);
|
|
369
|
+
if (signal.aborted) throw new RemoteAccessError('tailcat-install-aborted', 'The tailcat install was cancelled.', 503);
|
|
370
|
+
|
|
371
|
+
this.phase = 'verifying';
|
|
372
|
+
this.progress = null;
|
|
373
|
+
const actual = await sha256File(archivePath);
|
|
374
|
+
if (actual !== expected) {
|
|
375
|
+
throw new RemoteAccessError(
|
|
376
|
+
'tailcat-checksum-mismatch',
|
|
377
|
+
`tailcat archive checksum mismatch: expected ${expected}, got ${actual}.`,
|
|
378
|
+
502,
|
|
379
|
+
);
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
const extracted = path.join(staging, 'extracted');
|
|
383
|
+
this.phase = 'extracting';
|
|
384
|
+
await fsp.mkdir(extracted, { recursive: true, mode: 0o700 });
|
|
385
|
+
await this.extractArchive(archivePath, extracted, spec);
|
|
386
|
+
const candidate = await findBinary(extracted, spec.binary);
|
|
387
|
+
if (!candidate) {
|
|
388
|
+
throw new RemoteAccessError('tailcat-archive-invalid', `The tailcat archive did not contain ${spec.binary}.`, 502);
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
this.phase = 'installing';
|
|
392
|
+
const version = await this.probe(candidate);
|
|
393
|
+
this.ensureCompatible(version);
|
|
394
|
+
const installedAt = new Date().toISOString();
|
|
395
|
+
await this.replaceBinary(candidate);
|
|
396
|
+
await this.writeMetadata({
|
|
397
|
+
version: version ?? TAILCAT_VERSION,
|
|
398
|
+
source: 'upstream',
|
|
399
|
+
asset: spec.asset,
|
|
400
|
+
checksum: expected,
|
|
401
|
+
installedAt,
|
|
402
|
+
platform: this.platform,
|
|
403
|
+
arch: this.arch,
|
|
404
|
+
});
|
|
405
|
+
return { version: version ?? TAILCAT_VERSION, source: 'upstream', installedAt };
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/** @private */
|
|
409
|
+
async installBrew(staging, signal) {
|
|
410
|
+
if (this.spec.kind !== 'brew') throw new Error('not a Homebrew target');
|
|
411
|
+
const brew = await this.findBrew();
|
|
412
|
+
if (!brew) {
|
|
413
|
+
throw new RemoteAccessError(
|
|
414
|
+
'tailcat-brew-missing',
|
|
415
|
+
`Homebrew was not found. Install Homebrew (https://brew.sh), then retry, or install tailcat manually from ${MANUAL_INSTALL_URL} and set binaryPath.`,
|
|
416
|
+
503,
|
|
417
|
+
);
|
|
418
|
+
}
|
|
419
|
+
this.phase = 'homebrew';
|
|
420
|
+
this.progress = { phase: 'homebrew', received: 0, total: 0, percent: null };
|
|
421
|
+
try {
|
|
422
|
+
await this.runCommand([brew, 'update'], {
|
|
423
|
+
timeoutMs: 10 * 60_000,
|
|
424
|
+
env: {
|
|
425
|
+
HOMEBREW_NO_INSTALL_CLEANUP: '1',
|
|
426
|
+
NONINTERACTIVE: '1',
|
|
427
|
+
},
|
|
428
|
+
signal,
|
|
429
|
+
});
|
|
430
|
+
} catch (error) {
|
|
431
|
+
if (signal.aborted) throw error;
|
|
432
|
+
this.logger.warn(`tailcat-remote: brew update failed, continuing with the local formula: ${errorMessage(error)}`);
|
|
433
|
+
}
|
|
434
|
+
const installArgs = this.system?.compatible === false ? ['upgrade', 'tailcat'] : ['install', 'tailcat'];
|
|
435
|
+
try {
|
|
436
|
+
await this.runCommand([brew, ...installArgs], {
|
|
437
|
+
timeoutMs: BREW_TIMEOUT_MS,
|
|
438
|
+
env: {
|
|
439
|
+
HOMEBREW_NO_INSTALL_CLEANUP: '1',
|
|
440
|
+
NONINTERACTIVE: '1',
|
|
441
|
+
},
|
|
442
|
+
signal,
|
|
443
|
+
});
|
|
444
|
+
} catch (error) {
|
|
445
|
+
if (installArgs[0] !== 'upgrade' || signal.aborted) throw error;
|
|
446
|
+
this.logger.warn(`tailcat-remote: brew upgrade failed, trying a fresh install: ${errorMessage(error)}`);
|
|
447
|
+
await this.runCommand([brew, 'install', 'tailcat'], {
|
|
448
|
+
timeoutMs: BREW_TIMEOUT_MS,
|
|
449
|
+
env: {
|
|
450
|
+
HOMEBREW_NO_INSTALL_CLEANUP: '1',
|
|
451
|
+
NONINTERACTIVE: '1',
|
|
452
|
+
},
|
|
453
|
+
signal,
|
|
454
|
+
});
|
|
455
|
+
}
|
|
456
|
+
const prefix = await this.runCommand([brew, '--prefix', 'tailcat'], {
|
|
457
|
+
timeoutMs: COMMAND_TIMEOUT_MS,
|
|
458
|
+
signal,
|
|
459
|
+
}).catch(() => null);
|
|
460
|
+
const candidates = [
|
|
461
|
+
prefix?.stdout?.trim() ? path.join(prefix.stdout.trim(), 'bin', this.spec.binary) : null,
|
|
462
|
+
path.join(path.dirname(brew), this.spec.binary),
|
|
463
|
+
].filter((value) => typeof value === 'string');
|
|
464
|
+
const candidate = candidates.find((value) => isFile(value));
|
|
465
|
+
if (!candidate) {
|
|
466
|
+
throw new RemoteAccessError(
|
|
467
|
+
'tailcat-brew-binary-missing',
|
|
468
|
+
'Homebrew finished but did not leave a tailcat executable in its prefix. Check `brew install tailcat`, or set binaryPath.',
|
|
469
|
+
502,
|
|
470
|
+
);
|
|
471
|
+
}
|
|
472
|
+
const staged = path.join(staging, this.spec.binary);
|
|
473
|
+
await fsp.copyFile(candidate, staged);
|
|
474
|
+
const version = await this.probe(staged);
|
|
475
|
+
this.ensureCompatible(version);
|
|
476
|
+
const installedAt = new Date().toISOString();
|
|
477
|
+
await this.replaceBinary(staged);
|
|
478
|
+
await this.writeMetadata({
|
|
479
|
+
version: version ?? TAILCAT_VERSION,
|
|
480
|
+
source: 'homebrew',
|
|
481
|
+
asset: null,
|
|
482
|
+
checksum: null,
|
|
483
|
+
installedAt,
|
|
484
|
+
platform: this.platform,
|
|
485
|
+
arch: this.arch,
|
|
486
|
+
});
|
|
487
|
+
return { version: version ?? TAILCAT_VERSION, source: 'homebrew', installedAt };
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/** @private */
|
|
491
|
+
async findBrew() {
|
|
492
|
+
const common = this.platform === 'darwin' ? ['/opt/homebrew/bin/brew', '/usr/local/bin/brew'] : [];
|
|
493
|
+
for (const candidate of common) {
|
|
494
|
+
if (isFile(candidate) && isExecutable(candidate)) return candidate;
|
|
495
|
+
}
|
|
496
|
+
try {
|
|
497
|
+
return await this.resolveExecutable('brew', process.env);
|
|
498
|
+
} catch {
|
|
499
|
+
return null;
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/** @private */
|
|
504
|
+
async download(url, destination, signal) {
|
|
505
|
+
const response = await this.fetchImpl(url, {
|
|
506
|
+
redirect: 'follow',
|
|
507
|
+
signal,
|
|
508
|
+
headers: {
|
|
509
|
+
accept: 'application/octet-stream',
|
|
510
|
+
'user-agent': `dsh-tailcat-remote/${this.releaseTag.replace(/^v/, '')}`,
|
|
511
|
+
},
|
|
512
|
+
});
|
|
513
|
+
if (!response.ok || !response.body) {
|
|
514
|
+
throw new RemoteAccessError('tailcat-download-failed', `Could not download ${url}: HTTP ${response.status}.`, 502);
|
|
515
|
+
}
|
|
516
|
+
const total = Number(response.headers.get('content-length')) || 0;
|
|
517
|
+
if (total > MAX_ARCHIVE_BYTES) {
|
|
518
|
+
throw new RemoteAccessError('tailcat-download-too-large', `The tailcat archive is larger than ${MAX_ARCHIVE_BYTES} bytes.`, 502);
|
|
519
|
+
}
|
|
520
|
+
let received = 0;
|
|
521
|
+
this.progress = { phase: 'downloading', received: 0, total, percent: total > 0 ? 0 : null };
|
|
522
|
+
const meter = new Transform({
|
|
523
|
+
transform: (chunk, _encoding, callback) => {
|
|
524
|
+
received += chunk.length;
|
|
525
|
+
if (received > MAX_ARCHIVE_BYTES) {
|
|
526
|
+
callback(new Error(`The tailcat archive is larger than ${MAX_ARCHIVE_BYTES} bytes.`));
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
529
|
+
this.progress = {
|
|
530
|
+
phase: 'downloading',
|
|
531
|
+
received,
|
|
532
|
+
total,
|
|
533
|
+
percent: total > 0 ? Math.min(100, Math.round((received / total) * 100)) : null,
|
|
534
|
+
};
|
|
535
|
+
callback(null, chunk);
|
|
536
|
+
},
|
|
537
|
+
});
|
|
538
|
+
try {
|
|
539
|
+
await pipeline(Readable.fromWeb(response.body), meter, fs.createWriteStream(destination, { mode: 0o600 }));
|
|
540
|
+
} catch (error) {
|
|
541
|
+
await fsp.rm(destination, { force: true }).catch(() => {});
|
|
542
|
+
if (signal.aborted) throw new RemoteAccessError('tailcat-install-aborted', 'The tailcat install was cancelled.', 503);
|
|
543
|
+
throw new RemoteAccessError('tailcat-download-failed', `Could not download ${url}: ${errorMessage(error)}`, 502);
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
/** @private */
|
|
548
|
+
async fetchText(url, signal) {
|
|
549
|
+
const response = await this.fetchImpl(url, {
|
|
550
|
+
redirect: 'follow',
|
|
551
|
+
signal,
|
|
552
|
+
headers: { accept: 'text/plain', 'user-agent': `dsh-tailcat-remote/${this.releaseTag.replace(/^v/, '')}` },
|
|
553
|
+
});
|
|
554
|
+
if (!response.ok) {
|
|
555
|
+
throw new RemoteAccessError('tailcat-checksum-download-failed', `Could not download ${url}: HTTP ${response.status}.`, 502);
|
|
556
|
+
}
|
|
557
|
+
const length = Number(response.headers.get('content-length')) || 0;
|
|
558
|
+
if (length > MAX_TEXT_BYTES) {
|
|
559
|
+
throw new RemoteAccessError('tailcat-checksum-too-large', `The checksum manifest at ${url} is too large.`, 502);
|
|
560
|
+
}
|
|
561
|
+
const text = await response.text();
|
|
562
|
+
if (text.length > MAX_TEXT_BYTES) {
|
|
563
|
+
throw new RemoteAccessError('tailcat-checksum-too-large', `The checksum manifest at ${url} is too large.`, 502);
|
|
564
|
+
}
|
|
565
|
+
return text;
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
/** @private */
|
|
569
|
+
async extractArchive(archive, destination, spec) {
|
|
570
|
+
let tar = null;
|
|
571
|
+
try {
|
|
572
|
+
tar = await this.resolveExecutable('tar', process.env);
|
|
573
|
+
} catch {
|
|
574
|
+
if (spec.format !== 'zip' || this.platform !== 'win32') {
|
|
575
|
+
throw new RemoteAccessError(
|
|
576
|
+
'tailcat-extract-unavailable',
|
|
577
|
+
'The system tar executable is unavailable; cannot extract the verified tailcat archive.',
|
|
578
|
+
503,
|
|
579
|
+
);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
if (!tar) {
|
|
583
|
+
await this.extractZipWithPowerShell(archive, destination);
|
|
584
|
+
return;
|
|
585
|
+
}
|
|
586
|
+
const args = spec.format === 'zip' ? ['-xf', archive, '-C', destination] : ['-xzf', archive, '-C', destination];
|
|
587
|
+
try {
|
|
588
|
+
await this.runCommand([tar, ...args], { timeoutMs: COMMAND_TIMEOUT_MS });
|
|
589
|
+
if (await findBinary(destination, spec.binary)) return;
|
|
590
|
+
} catch (error) {
|
|
591
|
+
if (spec.format !== 'zip' || this.platform !== 'win32') throw error;
|
|
592
|
+
}
|
|
593
|
+
if (spec.format !== 'zip' || this.platform !== 'win32') {
|
|
594
|
+
throw new RemoteAccessError('tailcat-archive-invalid', `The tailcat archive did not contain ${spec.binary}.`, 502);
|
|
595
|
+
}
|
|
596
|
+
await this.extractZipWithPowerShell(archive, destination);
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
/** @private */
|
|
600
|
+
async extractZipWithPowerShell(archive, destination) {
|
|
601
|
+
const powershell = await this.findWindowsPowerShell();
|
|
602
|
+
if (!powershell) throw new RemoteAccessError('tailcat-extract-unavailable', 'Could not extract the tailcat zip archive.', 503);
|
|
603
|
+
await this.runCommand([
|
|
604
|
+
powershell,
|
|
605
|
+
'-NoProfile',
|
|
606
|
+
'-NonInteractive',
|
|
607
|
+
'-Command',
|
|
608
|
+
`Expand-Archive -LiteralPath ${quotePowerShell(archive)} -DestinationPath ${quotePowerShell(destination)} -Force`,
|
|
609
|
+
], { timeoutMs: COMMAND_TIMEOUT_MS });
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
/** @private */
|
|
613
|
+
async findWindowsPowerShell() {
|
|
614
|
+
for (const name of ['powershell.exe', 'powershell']) {
|
|
615
|
+
try {
|
|
616
|
+
return await this.resolveExecutable(name, process.env);
|
|
617
|
+
} catch {
|
|
618
|
+
// Try the next spelling.
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
return null;
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
/** @private */
|
|
625
|
+
async probe(binary) {
|
|
626
|
+
let result;
|
|
627
|
+
try {
|
|
628
|
+
result = await this.runCommand([binary, 'version'], { timeoutMs: 20_000 });
|
|
629
|
+
} catch (error) {
|
|
630
|
+
throw new RemoteAccessError('tailcat-install-invalid', `The installed tailcat could not run: ${errorMessage(error)}`, 502);
|
|
631
|
+
}
|
|
632
|
+
if (result.exitCode !== 0) {
|
|
633
|
+
const detail = `${result.stderr}\n${result.stdout}`.trim().split(/\r?\n/).filter(Boolean).at(-1);
|
|
634
|
+
throw new RemoteAccessError(
|
|
635
|
+
'tailcat-install-invalid',
|
|
636
|
+
`The installed tailcat exited with code ${result.exitCode}${detail ? `: ${detail}` : ''}.`,
|
|
637
|
+
502,
|
|
638
|
+
);
|
|
639
|
+
}
|
|
640
|
+
const match = /v?(\d+\.\d+\.\d+)/.exec(`${result.stdout}\n${result.stderr}`);
|
|
641
|
+
return match ? (match[0].startsWith('v') ? match[0] : `v${match[0]}`) : null;
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
/** @private */
|
|
645
|
+
ensureCompatible(version) {
|
|
646
|
+
if (version && !versionAtLeast(version, MIN_TAILCAT_VERSION)) {
|
|
647
|
+
throw new RemoteAccessError(
|
|
648
|
+
'tailcat-version-too-old',
|
|
649
|
+
`tailcat ${version} is too old for this plugin; ${MIN_TAILCAT_VERSION} or newer is required. Update tailcat and retry.`,
|
|
650
|
+
503,
|
|
651
|
+
);
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
/** @private */
|
|
656
|
+
async replaceBinary(source) {
|
|
657
|
+
await fsp.chmod(source, 0o755).catch(() => {});
|
|
658
|
+
const target = this.binaryPath;
|
|
659
|
+
const backup = `${target}.previous`;
|
|
660
|
+
await fsp.mkdir(path.dirname(target), { recursive: true, mode: 0o700 });
|
|
661
|
+
await fsp.rm(backup, { force: true }).catch(() => {});
|
|
662
|
+
const hadTarget = isFile(target);
|
|
663
|
+
if (hadTarget) await fsp.rename(target, backup);
|
|
664
|
+
try {
|
|
665
|
+
await fsp.rename(source, target);
|
|
666
|
+
await fsp.chmod(target, 0o755).catch(() => {});
|
|
667
|
+
} catch (error) {
|
|
668
|
+
if (hadTarget) await fsp.rename(backup, target).catch(() => {});
|
|
669
|
+
throw new RemoteAccessError('tailcat-install-write-failed', `Could not install tailcat at ${target}: ${errorMessage(error)}`, 500);
|
|
670
|
+
}
|
|
671
|
+
await fsp.rm(backup, { force: true }).catch(() => {});
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
/** @private */
|
|
675
|
+
async writeMetadata(metadata) {
|
|
676
|
+
const temporary = `${this.metadataPath}.tmp-${process.pid}`;
|
|
677
|
+
try {
|
|
678
|
+
await fsp.writeFile(temporary, `${JSON.stringify(metadata, null, 2)}\n`, { mode: 0o600 });
|
|
679
|
+
await fsp.rename(temporary, this.metadataPath);
|
|
680
|
+
} catch (error) {
|
|
681
|
+
await fsp.rm(temporary, { force: true }).catch(() => {});
|
|
682
|
+
this.logger.warn(`tailcat-remote: installed tailcat but could not save metadata: ${errorMessage(error)}`);
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
/** @private */
|
|
687
|
+
readInstalled() {
|
|
688
|
+
try {
|
|
689
|
+
if (!isRegularFile(this.binaryPath)) return null;
|
|
690
|
+
if (this.platform !== 'win32' && !isExecutable(this.binaryPath)) return null;
|
|
691
|
+
try {
|
|
692
|
+
const metadata = JSON.parse(fs.readFileSync(this.metadataPath, 'utf8'));
|
|
693
|
+
return { version: metadata.version ?? null, source: metadata.source ?? null, installedAt: metadata.installedAt ?? null };
|
|
694
|
+
} catch {
|
|
695
|
+
return { version: null, source: null, installedAt: null };
|
|
696
|
+
}
|
|
697
|
+
} catch {
|
|
698
|
+
return null;
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
/** @private */
|
|
703
|
+
async runInHost(argv, options = {}) {
|
|
704
|
+
let handle;
|
|
705
|
+
try {
|
|
706
|
+
handle = this.ctx.subprocess.spawn({
|
|
707
|
+
argv,
|
|
708
|
+
cwd: os.homedir(),
|
|
709
|
+
env: { ...baseEnv(), ...options.env },
|
|
710
|
+
stdio: {
|
|
711
|
+
stdin: 'ignore',
|
|
712
|
+
stdout: { maxBytes: 128 * 1024 },
|
|
713
|
+
stderr: { maxBytes: 128 * 1024 },
|
|
714
|
+
},
|
|
715
|
+
graceMs: 5_000,
|
|
716
|
+
signal: options.signal
|
|
717
|
+
? AbortSignal.any([options.signal, AbortSignal.timeout(options.timeoutMs ?? COMMAND_TIMEOUT_MS)])
|
|
718
|
+
: AbortSignal.timeout(options.timeoutMs ?? COMMAND_TIMEOUT_MS),
|
|
719
|
+
});
|
|
720
|
+
} catch (error) {
|
|
721
|
+
throw new RemoteAccessError('tailcat-command-failed', `Could not run ${path.basename(argv[0])}: ${errorMessage(error)}`, 503);
|
|
722
|
+
}
|
|
723
|
+
let outcome;
|
|
724
|
+
try {
|
|
725
|
+
outcome = await handle.done;
|
|
726
|
+
} catch (error) {
|
|
727
|
+
throw new RemoteAccessError('tailcat-command-failed', `${path.basename(argv[0])} failed: ${errorMessage(error)}`, 502);
|
|
728
|
+
}
|
|
729
|
+
const stdout = handle.collected.stdout?.readFrom(0).text ?? '';
|
|
730
|
+
const stderr = handle.collected.stderr?.readFrom(0).text ?? '';
|
|
731
|
+
if (outcome.exitCode !== 0) {
|
|
732
|
+
const detail = lastLine(stderr) ?? lastLine(stdout);
|
|
733
|
+
throw new RemoteAccessError(
|
|
734
|
+
'tailcat-command-failed',
|
|
735
|
+
`${path.basename(argv[0])} exited with code ${outcome.exitCode ?? 'null'}${detail ? `: ${detail}` : ''}`,
|
|
736
|
+
502,
|
|
737
|
+
);
|
|
738
|
+
}
|
|
739
|
+
return { stdout, stderr, exitCode: outcome.exitCode };
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
/**
|
|
744
|
+
* Environment for installer commands. It forwards PATH so Homebrew can find
|
|
745
|
+
* its own helpers, and keeps only the non-secret XDG locations plus HOME.
|
|
746
|
+
* @returns {NodeJS.ProcessEnv} child environment.
|
|
747
|
+
*/
|
|
748
|
+
function baseEnv() {
|
|
749
|
+
const env = { HOME: os.homedir() };
|
|
750
|
+
for (const name of [
|
|
751
|
+
'PATH',
|
|
752
|
+
'APPDATA',
|
|
753
|
+
'LOCALAPPDATA',
|
|
754
|
+
'USERPROFILE',
|
|
755
|
+
'SYSTEMROOT',
|
|
756
|
+
'TEMP',
|
|
757
|
+
'TMP',
|
|
758
|
+
'TMPDIR',
|
|
759
|
+
'XDG_CONFIG_HOME',
|
|
760
|
+
'XDG_CACHE_HOME',
|
|
761
|
+
'XDG_DATA_HOME',
|
|
762
|
+
]) {
|
|
763
|
+
const value = process.env[name];
|
|
764
|
+
if (value) env[name] = value;
|
|
765
|
+
}
|
|
766
|
+
return env;
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
/**
|
|
770
|
+
* Find a binary in a staging directory, allowing one archive wrapper folder.
|
|
771
|
+
* @param {string} root - extracted root.
|
|
772
|
+
* @param {string} name - expected basename.
|
|
773
|
+
* @returns {Promise<string | null>} absolute path.
|
|
774
|
+
*/
|
|
775
|
+
async function findBinary(root, name) {
|
|
776
|
+
const direct = path.join(root, name);
|
|
777
|
+
if (isRegularFile(direct)) return direct;
|
|
778
|
+
const entries = await fsp.readdir(root, { withFileTypes: true }).catch(() => []);
|
|
779
|
+
for (const entry of entries) {
|
|
780
|
+
if (!entry.isDirectory() || entry.isSymbolicLink()) continue;
|
|
781
|
+
const candidate = path.join(root, entry.name, name);
|
|
782
|
+
if (isRegularFile(candidate)) return candidate;
|
|
783
|
+
}
|
|
784
|
+
return null;
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
/** @param {string} file - path. @returns {boolean} regular file that is not a symlink. */
|
|
788
|
+
function isRegularFile(file) {
|
|
789
|
+
try {
|
|
790
|
+
return fs.lstatSync(file).isFile();
|
|
791
|
+
} catch {
|
|
792
|
+
return false;
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
/** @param {string} file - path. @returns {boolean} regular file. */
|
|
797
|
+
function isFile(file) {
|
|
798
|
+
try {
|
|
799
|
+
return fs.statSync(file).isFile();
|
|
800
|
+
} catch {
|
|
801
|
+
return false;
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
/** @param {string} file - path. @returns {boolean} executable file. */
|
|
806
|
+
function isExecutable(file) {
|
|
807
|
+
try {
|
|
808
|
+
fs.accessSync(file, fs.constants.X_OK);
|
|
809
|
+
return true;
|
|
810
|
+
} catch {
|
|
811
|
+
return false;
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
/** @param {string} value - PowerShell string. @returns {string} single-quoted literal. */
|
|
816
|
+
function quotePowerShell(value) {
|
|
817
|
+
return `'${String(value).replaceAll("'", "''")}'`;
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
/** @param {string} text - command output. @returns {string | null} last non-empty line. */
|
|
821
|
+
function lastLine(text) {
|
|
822
|
+
const lines = String(text).split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
|
|
823
|
+
return lines.length > 0 ? lines[lines.length - 1] : null;
|
|
824
|
+
}
|