Files
Kelx/tests/template-export-import-roundtrip.test.js
2026-11-30 16:32:37 +00:00

514 lines
21 KiB
JavaScript

"use strict";
// Tests for the template export/import round trip on the settings page.
//
// Regression: exportTemplate() downloaded JSON.stringify([storedTemplate]) —
// a one-element array holding the canonical stored shape (id/name/docker.*) —
// while applyTemplateJsonImport() rejected arrays outright and only
// understood Pterodactyl egg files and the flat editor payload
// (template_name/template_id/docker_image). An exported file could therefore
// never be re-imported, so export→import backup/migration always failed.
//
// The reconciliation: export now emits a single stored-shape object
// (buildTemplateExportJson), and import unwraps the legacy array envelope
// and maps the stored shape onto the flat payload via
// adpanelStoredTemplateToTemplatePayload before the existing validation and
// form-fill code runs.
//
// settings.js cannot be imported directly (it expects a DOM), so — like
// runtime-process-command.test.js — this suite slices the relevant regions
// out of the bundle, evaluates them in isolation with form element stubs,
// and proves: the new round trip, the legacy envelope, the pre-existing
// flat/egg formats, the rejection paths, and that a hostile import file
// cannot pollute prototypes (the converter only picks known fields).
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const SETTINGS_SRC = path.join(__dirname, "..", "public", "js", "settings.js");
function extractSlice(source, startMarker, endMarker) {
const start = source.indexOf(startMarker);
assert.ok(start >= 0, `start marker ${startMarker} not found`);
const fnStart = source.indexOf(endMarker, start);
assert.ok(fnStart >= 0, `end marker ${endMarker} not found after ${startMarker}`);
const bodyStart = source.indexOf("{", fnStart);
let depth = 0;
let end = -1;
for (let i = bodyStart; i < source.length; i += 1) {
if (source[i] === "{") depth += 1;
else if (source[i] === "}") {
depth -= 1;
if (depth === 0) { end = i; break; }
}
}
assert.ok(end > bodyStart, `could not find end of ${endMarker}`);
return source.slice(start, end + 1);
}
const source = fs.readFileSync(SETTINGS_SRC, "utf8");
// The command validator lives further down the file than the template
// import block; both regions are needed because import runs every startup
// command through startupCommandNeedsManagedRuntime /
// validateRuntimeProcessCommandInput.
const validatorBlock = extractSlice(
source,
"const RUNTIME_PROCESS_BLOCKED_EXECUTABLES",
"function validateRuntimeProcessCommandInput"
);
const importBlock = extractSlice(
source,
"function startupCommandNeedsManagedRuntime",
"function applyTemplateJsonImport"
);
const exportBlock = extractSlice(
source,
"function sanitizeExportFilenamePart",
"function buildTemplateExportJson"
);
function loadTemplateImportRuntime(editorStateOverrides = {}) {
const editorState = {
mode: "create",
editTemplateId: "",
startupSource: "",
startupValue: "",
containerConfig: null,
...editorStateOverrides,
};
const factory = new Function(`
const templateEditorState = ${JSON.stringify(editorState)};
const mkEl = () => ({ value: "" });
const ct_name = mkEl();
const ct_id = mkEl();
const ct_description = mkEl();
const ct_image = mkEl();
const ct_tag = mkEl();
const ct_startup_command = mkEl();
const ct_template_image = mkEl();
const ct_workdir = mkEl();
const ct_default_port = mkEl();
const ct_env_json = mkEl();
const ct_install_image = mkEl();
const ct_install_mount = mkEl();
const ct_install_runtime = mkEl();
const ct_install_script = mkEl();
${validatorBlock}
${importBlock}
${exportBlock}
return {
templateEditorState,
els: {
ct_name, ct_id, ct_description, ct_image, ct_tag, ct_startup_command,
ct_template_image, ct_workdir, ct_default_port, ct_env_json,
ct_install_image, ct_install_mount, ct_install_runtime, ct_install_script,
},
applyTemplateJsonImport,
looksLikeStoredAdpanelTemplate,
adpanelStoredTemplateToTemplatePayload,
adpanelEggToTemplatePayload,
templateContainerConfigFromImportPayload,
parseTemplateEnvJsonInput,
buildTemplateExportJson,
cloneTemplateForExport,
getTemplateExportFilename,
};
`);
return factory();
}
// Mirrors the canonical stored shape the panel API serves and templates.json
// persists (id/name/docker.*) — the exact object templateExportMap holds.
const STORED_TEMPLATE = {
id: "minecraft",
name: "Minecraft",
description: "Minecraft Java Edition server",
defaultPort: 25565,
templateImage: "https://cdn.example.com/minecraft.avif",
docker: {
image: "eclipse-temurin",
tag: "21-jre",
ports: [25565],
portProtocols: { "25565": ["tcp", "udp"] },
volumes: ["{BOT_DIR}:/data"],
workdir: "/data",
env: {},
command: "java -Xms128M -Xmx{RAM_MB}M -jar /data/server.jar nogui",
adpanelStartup: "",
startupDisplay: "",
install: null,
restart: "unless-stopped",
readonlyRootfs: true,
runAsRoot: false,
console: { type: "stdin", targetProcesses: ["java", "bedrock_server"] },
javaVersion: "21",
},
};
const FLAT_PAYLOAD = {
template_name: "My Node Bot",
template_id: "my-node-bot",
description: "Custom bot",
docker_image: "node",
docker_tag: "20-alpine",
startup: "node /app/index.js",
workdir: "/app",
defaultPort: 3000,
env: { NODE_ENV: "production" },
};
function assertStoredTemplatePopulatedForm(runtime, expected) {
const { els } = runtime;
assert.equal(els.ct_name.value, expected.name);
assert.equal(els.ct_id.value, expected.id);
assert.equal(els.ct_description.value, expected.description);
assert.equal(els.ct_image.value, expected.image);
assert.equal(els.ct_tag.value, expected.tag);
assert.equal(els.ct_startup_command.value, expected.startup);
assert.equal(els.ct_workdir.value, expected.workdir);
assert.equal(els.ct_default_port.value, expected.defaultPort);
assert.equal(els.ct_template_image.value, expected.templateImage);
}
test("legacy array-wrapped export file imports (reported regression)", () => {
const runtime = loadTemplateImportRuntime();
// What exportTemplate() downloaded before the fix: a one-element array.
const legacyExportFile = JSON.parse(JSON.stringify([STORED_TEMPLATE]));
runtime.applyTemplateJsonImport(legacyExportFile);
assertStoredTemplatePopulatedForm(runtime, {
name: "Minecraft",
id: "minecraft",
description: "Minecraft Java Edition server",
image: "eclipse-temurin",
tag: "21-jre",
startup: "java -Xms128M -Xmx{RAM_MB}M -jar /data/server.jar nogui",
workdir: "/data",
defaultPort: "25565",
templateImage: "https://cdn.example.com/minecraft.avif",
});
assert.equal(runtime.els.ct_env_json.value, "");
assert.equal(runtime.templateEditorState.startupSource, "");
});
test("current export output is a single stored-shape object that re-imports", () => {
const runtime = loadTemplateImportRuntime();
const json = runtime.buildTemplateExportJson(runtime.cloneTemplateForExport(STORED_TEMPLATE));
// Byte-for-byte: pretty-printed single object with trailing newline.
assert.equal(json, `${JSON.stringify(STORED_TEMPLATE, null, 2)}\n`);
const parsed = JSON.parse(json);
assert.equal(Array.isArray(parsed), false, "export must not wrap the template in an array");
assert.equal(parsed.docker.image, "eclipse-temurin");
runtime.applyTemplateJsonImport(parsed);
assertStoredTemplatePopulatedForm(runtime, {
name: "Minecraft",
id: "minecraft",
description: "Minecraft Java Edition server",
image: "eclipse-temurin",
tag: "21-jre",
startup: "java -Xms128M -Xmx{RAM_MB}M -jar /data/server.jar nogui",
workdir: "/data",
defaultPort: "25565",
templateImage: "https://cdn.example.com/minecraft.avif",
});
});
test("stored-shape import maps env, install and prefers the managed startup", () => {
const runtime = loadTemplateImportRuntime();
const managed = "set -e\ncd /data\necho starting";
const template = JSON.parse(JSON.stringify(STORED_TEMPLATE));
template.docker.adpanelStartup = managed;
template.docker.env = { NODE_ENV: "production" };
template.docker.install = {
image: "ghcr.io/pterodactyl/installers:debian",
script: "echo installing",
mountPath: "/mnt/server",
runtimePath: "/home/container",
};
runtime.applyTemplateJsonImport([template]);
// Managed startup wins over the raw docker command (same precedence as the
// edit modal), and it is accepted without argv validation because it is
// shell syntax by design.
assert.equal(runtime.els.ct_startup_command.value, managed);
assert.equal(runtime.templateEditorState.startupSource, "managed");
assert.equal(runtime.templateEditorState.startupValue, managed);
assert.equal(runtime.els.ct_env_json.value, JSON.stringify({ NODE_ENV: "production" }, null, 2));
assert.equal(runtime.els.ct_install_image.value, "ghcr.io/pterodactyl/installers:debian");
assert.equal(runtime.els.ct_install_script.value, "echo installing");
assert.equal(runtime.els.ct_install_mount.value, "/mnt/server");
assert.equal(runtime.els.ct_install_runtime.value, "/home/container");
});
test("stored-shape import parks ports, protocols and volumes for the save request", () => {
// Regression: the export→import round trip silently dropped ports,
// portProtocols and volumes, so a cloned multi-volume template created
// servers whose plugin/world volumes never existed (data landed in the
// container layer and vanished on recreate). The converter must hoist the
// container-mount fields and the importer must park them in
// templateEditorState.containerConfig, which the save request forwards to
// the server's fail-closed boundary.
const runtime = loadTemplateImportRuntime();
const source = JSON.parse(JSON.stringify(STORED_TEMPLATE));
runtime.applyTemplateJsonImport(source);
assert.deepEqual(runtime.templateEditorState.containerConfig, {
ports: [25565],
portProtocols: { "25565": ["tcp", "udp"] },
volumes: ["{BOT_DIR}:/data"],
});
// Parked values are deep clones, never references into the export map —
// mutating the parked config must not corrupt the listing data.
runtime.templateEditorState.containerConfig.volumes.push("TAMPERED");
assert.deepEqual(source.docker.volumes, ["{BOT_DIR}:/data"]);
});
test("stored-shape import without container fields parks nothing", () => {
const runtime = loadTemplateImportRuntime();
const stripped = JSON.parse(JSON.stringify(STORED_TEMPLATE));
delete stripped.docker.ports;
delete stripped.docker.portProtocols;
delete stripped.docker.volumes;
runtime.applyTemplateJsonImport(stripped);
assert.strictEqual(runtime.templateEditorState.containerConfig, null);
});
test("flat payload with container fields carries them (API-shaped imports)", () => {
const runtime = loadTemplateImportRuntime();
runtime.applyTemplateJsonImport({
...JSON.parse(JSON.stringify(FLAT_PAYLOAD)),
ports: "3000,3001",
port_protocols: { "3000": ["tcp"] },
volumes: ["{BOT_DIR}:/app", "botdata:/data"],
});
assert.deepEqual(runtime.templateEditorState.containerConfig, {
ports: "3000,3001",
// The body-level alias chain mirrors the server's portProtocols ||
// port_protocols fallback.
portProtocols: { "3000": ["tcp"] },
volumes: ["{BOT_DIR}:/app", "botdata:/data"],
});
});
test("flat payload without container fields imports with no carried config", () => {
const runtime = loadTemplateImportRuntime();
runtime.applyTemplateJsonImport(JSON.parse(JSON.stringify(FLAT_PAYLOAD)));
assert.strictEqual(runtime.templateEditorState.containerConfig, null);
});
test("pterodactyl egg imports park nothing (the converter emits no container fields)", () => {
const runtime = loadTemplateImportRuntime();
const egg = {
meta: { version: "PLCN_v1" },
name: "Egg Bot",
docker_images: { "node:20-alpine": "Node" },
startup: "node index.js",
variables: [],
};
runtime.applyTemplateJsonImport(egg);
assert.strictEqual(runtime.templateEditorState.containerConfig, null);
});
test("templateContainerConfigFromImportPayload only picks the known container fields", () => {
const runtime = loadTemplateImportRuntime();
// Hostile payload: unknown keys (including prototype-pollution names) must
// never be carried into the save request — only ports/portProtocols/
// volumes are parked, and present-but-null values are skipped (the server
// treats null exactly like absent for these fields).
const parked = runtime.templateContainerConfigFromImportPayload(JSON.parse(
'{"ports":[8080],"volumes":["{BOT_DIR}:/data"],"adpanelStartup":"echo owned",' +
'"dockerWorkdir":"/owned","__proto__":{"polluted":1},"portProtocols":null}'
));
assert.deepEqual(parked, { ports: [8080], volumes: ["{BOT_DIR}:/data"] });
assert.equal(({}).polluted, undefined, "Object.prototype must stay clean");
// Non-object payloads park nothing.
assert.equal(runtime.templateContainerConfigFromImportPayload(null), null);
assert.equal(runtime.templateContainerConfigFromImportPayload("x"), null);
assert.equal(runtime.templateContainerConfigFromImportPayload([1]), null);
assert.equal(runtime.templateContainerConfigFromImportPayload({}), null);
});
test("env JSON parser fails closed instead of silently shrinking the reviewed env", () => {
const runtime = loadTemplateImportRuntime();
// A literal "__proto__" key used to vanish through the inherited setter
// (assignment is swallowed), so the save request silently lacked the entry
// the admin reviewed — the same silent-drop class the server boundary now
// 400s on. The parser must reject it before any request is built.
assert.throws(
() => runtime.parseTemplateEnvJsonInput('{"__proto__":"owned","FOO":"1"}'),
/reserved key "__proto__"/
);
// Empty and whitespace-only keys used to be skipped silently; the server
// answers 400 for them, so the client must surface the same failure.
assert.throws(
() => runtime.parseTemplateEnvJsonInput('{"": "v", "FOO": "1"}'),
/empty key/
);
assert.throws(
() => runtime.parseTemplateEnvJsonInput('{" ": "v"}'),
/empty key/
);
// Well-formed input still parses, keys are trimmed, values stringified.
assert.deepEqual(
runtime.parseTemplateEnvJsonInput('{" GOOD ": 1, "EMPTY": null}'),
{ GOOD: "1", EMPTY: "" }
);
// constructor/prototype keys survive as own properties (no setter issue)
// so the server boundary — not the client — names them in the 400.
const parsed = runtime.parseTemplateEnvJsonInput('{"constructor":"x","prototype":"y"}');
assert.equal(Object.prototype.hasOwnProperty.call(parsed, "constructor"), true);
assert.equal(Object.prototype.hasOwnProperty.call(parsed, "prototype"), true);
});
test("flat payload import keeps working", () => {
const runtime = loadTemplateImportRuntime();
runtime.applyTemplateJsonImport(JSON.parse(JSON.stringify(FLAT_PAYLOAD)));
assertStoredTemplatePopulatedForm(runtime, {
name: "My Node Bot",
id: "my-node-bot",
description: "Custom bot",
image: "node",
tag: "20-alpine",
startup: "node /app/index.js",
workdir: "/app",
defaultPort: "3000",
templateImage: "",
});
assert.equal(runtime.els.ct_env_json.value, JSON.stringify({ NODE_ENV: "production" }, null, 2));
});
test("pterodactyl egg import keeps working", () => {
const runtime = loadTemplateImportRuntime();
const egg = {
meta: { version: "PLCN_v1", author: "vendor@example.com" },
name: "Team Fortress 2",
description: "TF2 dedicated server",
docker_images: { "ghcr.io/pterodactyl/yolks:sourcecon": "Source console" },
startup: "./srcds_run -game tf -port 27015",
variables: [
{ env_variable: "SERVER_PORT", default_value: "27015" },
{ env_variable: "SRCDS_MAP", default_value: "cp_badlands" },
],
scripts: {
installation: {
container: "ghcr.io/pterodactyl/installers:debian",
entrypoint: "bash",
script: "apt-get install steamcmd",
},
},
};
runtime.applyTemplateJsonImport(egg);
assert.equal(runtime.els.ct_name.value, "Team Fortress 2");
assert.equal(runtime.els.ct_id.value, "team-fortress-2");
assert.equal(runtime.els.ct_image.value, "ghcr.io/pterodactyl/yolks");
assert.equal(runtime.els.ct_tag.value, "sourcecon");
assert.equal(runtime.els.ct_default_port.value, "27015");
assert.equal(runtime.els.ct_install_image.value, "ghcr.io/pterodactyl/installers:debian");
assert.equal(runtime.els.ct_install_script.value, "apt-get install steamcmd");
});
test("multi-template and empty array envelopes are rejected with guidance", () => {
const runtime = loadTemplateImportRuntime();
const second = JSON.parse(JSON.stringify(FLAT_PAYLOAD));
second.template_id = "second";
assert.throws(
() => runtime.applyTemplateJsonImport([FLAT_PAYLOAD, second]),
/contains 2 templates/
);
assert.throws(
() => runtime.applyTemplateJsonImport([]),
/contains no template/
);
});
test("junk payloads are still rejected", () => {
const runtime = loadTemplateImportRuntime();
assert.throws(() => runtime.applyTemplateJsonImport(null), /Invalid JSON format/);
assert.throws(() => runtime.applyTemplateJsonImport(42), /Invalid JSON format/);
assert.throws(() => runtime.applyTemplateJsonImport("template"), /Invalid JSON format/);
// Array envelope unwraps to a non-object.
assert.throws(() => runtime.applyTemplateJsonImport([5]), /Invalid JSON format/);
assert.throws(() => runtime.applyTemplateJsonImport([null]), /Invalid JSON format/);
// Flat payload missing required keys.
assert.throws(
() => runtime.applyTemplateJsonImport({}),
/Missing required field in JSON: template_name/
);
});
test("stored-shape import still enforces workdir and command validation", () => {
const runtime = loadTemplateImportRuntime();
const traversal = JSON.parse(JSON.stringify(STORED_TEMPLATE));
traversal.docker.workdir = "/data/../etc";
assert.throws(() => runtime.applyTemplateJsonImport(traversal), /traversal/);
const smuggled = JSON.parse(JSON.stringify(STORED_TEMPLATE));
smuggled.docker.command = "node app.js;curl";
assert.throws(() => runtime.applyTemplateJsonImport(smuggled), /operator/i);
const containerCli = JSON.parse(JSON.stringify(STORED_TEMPLATE));
containerCli.docker.command = "docker run -it alpine";
assert.throws(() => runtime.applyTemplateJsonImport(containerCli), /docker run/);
});
test("edit mode keeps the existing template id on import", () => {
const runtime = loadTemplateImportRuntime({ mode: "edit", editTemplateId: "minecraft" });
const renamed = JSON.parse(JSON.stringify(STORED_TEMPLATE));
renamed.id = "renamed-id";
runtime.applyTemplateJsonImport(renamed);
assert.equal(runtime.els.ct_id.value, "minecraft", "edit mode must keep the id being edited");
assert.equal(runtime.els.ct_name.value, "Minecraft");
});
test("hostile import file cannot pollute prototypes", () => {
const runtime = loadTemplateImportRuntime();
// JSON.parse gives "__proto__"/"constructor" as own properties; the
// converter must only pick known fields, never spread the payload.
const hostile = JSON.parse(
'{"__proto__":{"polluted":1},"constructor":{"prototype":{"polluted":2}},' +
'"name":"x","id":"x","description":"d",' +
'"docker":{"__proto__":{"polluted":3},"image":"node","tag":"latest",' +
'"workdir":"/app","command":"node index.js","env":{}}}'
);
runtime.applyTemplateJsonImport(hostile);
assert.equal(runtime.els.ct_image.value, "node");
assert.equal(({}).polluted, undefined, "Object.prototype must stay clean");
assert.equal(Object.prototype.polluted, undefined);
const hostileEnv = JSON.parse(
'{"name":"x","id":"x",' +
'"docker":{"image":"node","tag":"latest","workdir":"/app","command":"node index.js",' +
'"env":{"__proto__":{"polluted":4},"NODE_ENV":"production"}}}'
);
runtime.applyTemplateJsonImport(hostileEnv);
assert.equal(({}).polluted, undefined, "Object.prototype must stay clean");
assert.ok(runtime.els.ct_env_json.value.includes('"NODE_ENV"'));
});
test("export filename stays sanitized", () => {
const runtime = loadTemplateImportRuntime();
assert.equal(runtime.getTemplateExportFilename("My Template!"), "my-template.json");
assert.equal(runtime.getTemplateExportFilename(""), "template.json");
});
test("detector only claims the stored shape", () => {
const runtime = loadTemplateImportRuntime();
assert.equal(runtime.looksLikeStoredAdpanelTemplate(STORED_TEMPLATE), true);
assert.equal(runtime.looksLikeStoredAdpanelTemplate(FLAT_PAYLOAD), false, "flat payload must keep using the flat path");
assert.equal(runtime.looksLikeStoredAdpanelTemplate({ meta: { version: "PLCN_v1" }, docker: { image: "x" } }), false, "egg payload must keep using the egg path");
assert.equal(runtime.looksLikeStoredAdpanelTemplate({ name: "x", docker: "not-an-object" }), false);
assert.equal(runtime.looksLikeStoredAdpanelTemplate(null), false);
assert.equal(runtime.looksLikeStoredAdpanelTemplate([STORED_TEMPLATE]), false);
});