// Copyright (C) 2026 Zaher Salman // SPDX-License-Identifier: GPL-3.0-or-later // Main-process offline runtime installation. New files are verified in a private // staging directory; neither system tools nor previously installed trees change. const fs = require('fs'); const path = require('path'); const os = require('os'); const { createHash, randomUUID } = require('crypto'); const { execFile } = require('child_process'); const { promisify, isDeepStrictEqual } = require('util'); const { Transform } = require('stream'); const { pipeline } = require('stream/promises'); const tar = require('tar'); const execute = promisify(execFile); const TOOLS = ['musrfit', 'musrview', 'msr2data', 'dump_header', 'musrt0']; const FILES = TOOLS.concat('root-config').map(function(name) { return 'bin/' + name; }).concat(['lib/libCore.so', 'lib/libPMusr.so']); async function hashFile(filename, signal) { const hash = createHash('sha256'); for await (const chunk of fs.createReadStream(filename, { signal: signal })) { hash.update(chunk); } return hash.digest('hex'); } class LocalRuntime { constructor(options) { this.directory = path.resolve(options.directory); this.platform = options.platform || process.platform; this.arch = options.arch || process.arch; this.timeout = options.timeout || 5000; } async checkTools(input, signal) { const results = []; for (const name of TOOLS) { const command = input.commands && input.commands[name]; if (typeof command !== 'string' || path.basename(command) !== name) { results.push({ name: name, ok: false, error: 'No executable selected.' }); continue; } try { const result = await execute(command, ['--version'], { env: input.env || process.env, cwd: os.tmpdir(), timeout: this.timeout, maxBuffer: 1024 * 1024, killSignal: 'SIGKILL', signal: signal }); const version = result.stdout.match(/version:\s*([^,\s]+)/i); results.push({ name: name, command: command, ok: true, version: version ? version[1] : 'available', output: result.stdout }); } catch (error) { if (signal && signal.aborted) throw error; results.push({ name: name, command: command, ok: false, error: error.killed ? 'Version check timed out.' : (error.stderr || error.message).trim() }); } } return { ok: results.every(function(result) { return result.ok; }), tools: results }; } async inspectBundle(descriptorPath) { if (this.platform !== 'linux' || !['x64', 'arm64'].includes(this.arch)) { throw new Error('Native runtime installation currently supports Linux x64/arm64 only.'); } const source = await fs.promises.realpath(descriptorPath); const stat = await fs.promises.stat(source); if (!stat.isFile() || stat.size > 1024 * 1024) throw new Error('Invalid runtime download descriptor.'); const descriptor = JSON.parse(await fs.promises.readFile(source, 'utf8')); const runtime = descriptor.runtime; const artifact = descriptor.artifact; if (descriptor.schemaVersion !== 1 || descriptor.kind !== 'musrflow-runtime-download' || !runtime || runtime.schemaVersion !== 1 || runtime.platform !== this.platform || runtime.arch !== this.arch || !runtime.root || !runtime.musrfit || typeof runtime.root.version !== 'string' || typeof runtime.musrfit.version !== 'string' || typeof runtime.runtimeId !== 'string' || !runtime.files || Array.isArray(runtime.files) || FILES.some(function(name) { return typeof runtime.files[name] !== 'string' || !/^[0-9a-f]{64}$/.test(runtime.files[name]); }) || !artifact || artifact.format !== 'tar.gz' || artifact.rootDirectory !== 'runtime' || typeof artifact.filename !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]*\.tar\.gz$/.test(artifact.filename) || typeof artifact.sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(artifact.sha256) || !Number.isSafeInteger(artifact.size) || artifact.size <= 0 || artifact.size > 8 * 1024 ** 3) { throw new Error('The runtime descriptor is invalid or does not match this computer (' + this.platform + '/' + this.arch + ').'); } const archive = path.join(path.dirname(source), artifact.filename); const archiveStat = await fs.promises.lstat(archive); if (!archiveStat.isFile() || archiveStat.size !== artifact.size) { throw new Error('The archive is missing or has the wrong size. Keep it beside runtime-download.json.'); } return { descriptor: descriptor, archive: archive, destination: path.join(this.directory, artifact.sha256, 'runtime') }; } async verifyInstalled(root, runtime, signal) { const manifest = JSON.parse(await fs.promises.readFile(path.join(root, 'runtime-manifest.json'), 'utf8')); if (!isDeepStrictEqual(manifest, runtime)) throw new Error('The extracted runtime manifest does not match the download.'); for (const relative of FILES) { if (signal) signal.throwIfAborted(); const filename = path.join(root, relative); const resolved = await fs.promises.realpath(filename); if (!resolved.startsWith(root + path.sep)) throw new Error('Runtime file points outside its installation: ' + relative); if (!(await fs.promises.stat(resolved)).isFile()) throw new Error('Runtime file is not a regular file: ' + relative); if (await hashFile(filename, signal) !== runtime.files[relative]) { throw new Error('Runtime file verification failed: ' + relative); } if (relative.startsWith('bin/')) await fs.promises.access(filename, fs.constants.X_OK); if (relative.startsWith('lib/')) { const handle = await fs.promises.open(filename, 'r'); try { const header = Buffer.alloc(20); await handle.read(header, 0, 20, 0); if (header.toString('hex', 0, 4) !== '7f454c46' || header[4] !== 2 || header[5] !== 1 || header.readUInt16LE(18) !== (this.arch === 'x64' ? 62 : 183)) { throw new Error('Runtime library architecture does not match this computer.'); } } finally { await handle.close(); } } } const startupPath = path.join(root, 'musrfit_startup.xml'); const startup = await fs.promises.stat(startupPath); if (!startup.isFile() || startup.size === 0) throw new Error('Runtime startup XML is missing or empty.'); await fs.promises.access(startupPath, fs.constants.R_OK); const commands = {}; for (const name of TOOLS) commands[name] = path.join(root, 'bin', name); const env = Object.assign({}, process.env, { ROOTSYS: root, MUSRFITPATH: root, LD_LIBRARY_PATH: path.join(root, 'lib'), PATH: path.join(root, 'bin') + ':/usr/bin:/bin' }); delete env.LD_PRELOAD; const result = await this.checkTools({ commands: commands, env: env }, signal); const failed = result.tools.find(function(tool) { return !tool.ok; }); if (failed) throw new Error(failed.name + ' cannot start: ' + failed.error); for (const tool of result.tools) { const reportedRoot = tool.output.match(/ROOT version:\s*([^,\s]+)/); if (tool.version !== runtime.musrfit.version || !reportedRoot || reportedRoot[1].replace('/', '.') !== runtime.root.version || (runtime.musrfit.revision && !tool.output.includes(runtime.musrfit.revision))) { throw new Error(tool.name + ' reports a different runtime version.'); } } return root; } async install(plan, signal, onProgress) { const descriptor = plan.descriptor; const artifact = descriptor.artifact; let lastPhase = ''; let lastUpdate = 0; const progress = function(state) { if (state.phase !== lastPhase || Date.now() - lastUpdate > 150) { lastPhase = state.phase; lastUpdate = Date.now(); if (onProgress) onProgress(state); } }; signal.throwIfAborted(); await fs.promises.mkdir(this.directory, { recursive: true, mode: 0o700 }); const stage = await fs.promises.mkdtemp(path.join(this.directory, '.install-')); try { progress({ phase: 'Verifying runtime archive' }); const archive = path.join(stage, 'runtime.tar.gz'); const digest = createHash('sha256'); let bytes = 0; const verifier = new Transform({ transform: function(chunk, encoding, callback) { bytes += chunk.length; if (bytes > artifact.size) return callback(new Error('The runtime archive changed during installation.')); digest.update(chunk); progress({ phase: 'Verifying runtime archive', received: bytes, total: artifact.size }); callback(null, chunk); } }); await pipeline(fs.createReadStream(plan.archive), verifier, fs.createWriteStream(archive, { flags: 'wx' }), { signal: signal }); if (bytes !== artifact.size || digest.digest('hex') !== artifact.sha256) { throw new Error('Runtime archive SHA-256 verification failed. Nothing was installed.'); } progress({ phase: 'Checking archive contents' }); const entries = new Set(); const links = new Set(); let unpackedBytes = 0; let invalid = ''; await tar.t({ file: archive, strict: true, filter: function(rawName, entry) { const name = entry.path.replace(/\/$/, ''); if (!name.startsWith('runtime/') && name !== 'runtime') invalid = 'Unexpected archive root.'; if (/[\\\x00-\x1f]/.test(name) || name.split('/').some(function(part) { return !part || part === '.' || part === '..'; }) || entries.has(name) || !['File', 'Directory', 'SymbolicLink'].includes(entry.type)) { invalid = 'Unsafe or duplicate runtime archive entry.'; } entries.add(name); if (entry.type === 'SymbolicLink') { const target = path.posix.normalize(path.posix.join(path.posix.dirname(name), entry.linkpath)); if (/[\\\x00-\x1f]/.test(entry.linkpath) || path.posix.isAbsolute(entry.linkpath) || (target !== 'runtime' && !target.startsWith('runtime/'))) invalid = 'Unsafe runtime library link.'; links.add(name); } unpackedBytes += entry.size; if (!Number.isSafeInteger(unpackedBytes) || unpackedBytes > 8 * 1024 ** 3 || entries.size > 200000) { invalid = 'Runtime archive expands beyond the supported size.'; } if (invalid || signal.aborted) { this.abort(new Error(invalid || 'Runtime installation cancelled.')); return false; } return true; } }); signal.throwIfAborted(); if (invalid) throw new Error(invalid); for (const name of entries) { const parts = name.split('/'); parts.pop(); while (parts.length) { if (links.has(parts.join('/'))) throw new Error('Runtime archive writes through a symbolic link.'); parts.pop(); } } const available = await fs.promises.statfs(stage); if (available.bavail * available.bsize < unpackedBytes + 16 * 1024 * 1024) { throw new Error('Not enough free disk space to install the runtime.'); } progress({ phase: 'Extracting runtime' }); signal.throwIfAborted(); const extracted = path.join(stage, 'extracted'); await fs.promises.mkdir(extracted); // Let queued writes finish before removing staging on cancellation; // later entries are skipped and nothing is activated afterwards. await tar.x({ file: archive, cwd: extracted, strict: true, preserveOwner: false, chmod: true, processUmask: 0o022, filter: function(name, entry) { entry.mode &= 0o777; return !signal.aborted; } }); signal.throwIfAborted(); progress({ phase: 'Checking installed tools' }); const root = path.join(extracted, 'runtime'); await this.verifyInstalled(root, descriptor.runtime, signal); signal.throwIfAborted(); let destination = path.dirname(plan.destination); if (fs.existsSync(destination)) { try { await this.verifyInstalled(path.join(destination, 'runtime'), descriptor.runtime, signal); return { ok: true, root: path.join(destination, 'runtime'), reused: true }; } catch (error) { signal.throwIfAborted(); // Keep a damaged/older tree intact; a fresh sibling permits // repair without changing files a running musrview may use. destination += '-' + randomUUID(); } } await fs.promises.rename(extracted, destination); return { ok: true, root: path.join(destination, 'runtime'), reused: false }; } finally { await fs.promises.rm(stage, { recursive: true, force: true }); } } } module.exports = { LocalRuntime, TOOLS };