125 lines
4.7 KiB
JavaScript
125 lines
4.7 KiB
JavaScript
"use strict";
|
|
|
|
// Durable, file-backed mirror of the per-worker installationJobs Map in
|
|
// index.js. The panel runs under PM2 cluster mode, so a poll for
|
|
// /install-progress/:jobId can land on a worker process that never started
|
|
// the job: the in-memory Map is per-process and Redis is not guaranteed
|
|
// (SESSION_STORE=file leaves redisClient null). Small JSON records under
|
|
// data/install-jobs/ give every worker visibility into every job's state.
|
|
//
|
|
// Security note: req.params.jobId flows into a file path, so ids are validated
|
|
// with a STRICT allow-list regex (lowercase type prefix + crypto.randomUUID
|
|
// shape) before any filesystem access — traversal strings such as
|
|
// "../../etc/passwd" can never reach the filesystem through this module.
|
|
//
|
|
// Records are ephemeral progress telemetry: a missing or corrupt record fails
|
|
// open to "not found" (readInstallJob -> null). This is deliberate and unlike
|
|
// the panel's config bookkeeping files, where a torn read must fail closed.
|
|
|
|
const fs = require("fs");
|
|
const path = require("path");
|
|
const { atomicWriteFileSync } = require("./atomic-file");
|
|
|
|
// Lowercase type prefix ('mongodb' | 'pgadmin' today — job ids are created as
|
|
// `${type}-${crypto.randomUUID()}`) + crypto.randomUUID format. Anchored on
|
|
// both ends, so separators, dots, slashes, whitespace, NUL bytes, trailing
|
|
// junk and uppercase variants can never match.
|
|
const INSTALL_JOB_ID_RE = /^[a-z]+-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
|
|
// The jobs dir is created on first save and trusted afterwards; keyed per dir
|
|
// so tests (and any future second store location) stay independent.
|
|
const ensuredDirs = new Set();
|
|
|
|
/**
|
|
* Strict allow-list validation for install job ids. Non-strings and any
|
|
* string outside the exact "<lowercase-type>-<uuid>" shape are rejected.
|
|
* @param {unknown} jobId
|
|
* @returns {boolean}
|
|
*/
|
|
function isValidInstallJobId(jobId) {
|
|
return typeof jobId === "string" && INSTALL_JOB_ID_RE.test(jobId);
|
|
}
|
|
|
|
/**
|
|
* Resolve the record file path for a job id. Throws on an invalid id —
|
|
* callers must treat that as "never touch the filesystem".
|
|
* @param {string} jobsDir
|
|
* @param {string} jobId
|
|
* @returns {string}
|
|
*/
|
|
function installJobPath(jobsDir, jobId) {
|
|
if (!isValidInstallJobId(jobId)) {
|
|
// JSON.stringify escapes newlines/quotes so untrusted ids cannot inject
|
|
// log lines; String() first keeps symbols/objects from throwing here.
|
|
throw new Error(`[installJobStore] invalid install job id: ${JSON.stringify(String(jobId))}`);
|
|
}
|
|
return path.join(jobsDir, `${jobId}.json`);
|
|
}
|
|
|
|
/**
|
|
* Atomically persist a job record (0600: progress telemetry is admin-facing
|
|
* and messages can hint at the host's database layout).
|
|
* @param {string} jobsDir
|
|
* @param {string} jobId
|
|
* @param {object} record
|
|
* @returns {void} throws on failure
|
|
*/
|
|
function saveInstallJob(jobsDir, jobId, record) {
|
|
const filePath = installJobPath(jobsDir, jobId); // throws on invalid id
|
|
if (!ensuredDirs.has(jobsDir)) {
|
|
fs.mkdirSync(jobsDir, { recursive: true });
|
|
ensuredDirs.add(jobsDir);
|
|
}
|
|
atomicWriteFileSync(filePath, JSON.stringify(record, null, 2), { mode: 0o600 });
|
|
}
|
|
|
|
/**
|
|
* Load a job record. Missing -> null (the common cross-worker "not started
|
|
* here" case stays silent); unreadable or corrupt -> null + console.error
|
|
* (fail-open: telemetry is not worth 500ing a status poll over); a payload
|
|
* that parses to a non-object is treated as absent.
|
|
* @param {string} jobsDir
|
|
* @param {string} jobId
|
|
* @returns {object|null}
|
|
*/
|
|
function readInstallJob(jobsDir, jobId) {
|
|
if (!isValidInstallJobId(jobId)) return null;
|
|
let raw;
|
|
try {
|
|
raw = fs.readFileSync(path.join(jobsDir, `${jobId}.json`), "utf8");
|
|
} catch (err) {
|
|
if (err && err.code !== "ENOENT") {
|
|
console.error(`[installJobStore] Failed to read job record ${jobId}:`, err.message);
|
|
}
|
|
return null;
|
|
}
|
|
try {
|
|
const parsed = JSON.parse(raw);
|
|
return parsed && typeof parsed === "object" ? parsed : null;
|
|
} catch (err) {
|
|
console.error(`[installJobStore] Corrupt job record ${jobId}:`, err.message);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Remove a job record. Invalid ids are ignored; ENOENT is tolerated; any
|
|
* other unlink failure is logged and swallowed so sweeps and install flows
|
|
* never observe a throw.
|
|
* @param {string} jobsDir
|
|
* @param {string} jobId
|
|
* @returns {void}
|
|
*/
|
|
function deleteInstallJob(jobsDir, jobId) {
|
|
if (!isValidInstallJobId(jobId)) return;
|
|
try {
|
|
fs.unlinkSync(path.join(jobsDir, `${jobId}.json`));
|
|
} catch (err) {
|
|
if (err && err.code !== "ENOENT") {
|
|
console.error(`[installJobStore] Failed to delete job record ${jobId}:`, err.message);
|
|
}
|
|
}
|
|
}
|
|
|
|
module.exports = { isValidInstallJobId, installJobPath, saveInstallJob, readInstallJob, deleteInstallJob };
|