Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -0,0 +1,933 @@
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const vm = require("node:vm");
|
||||
const { EventEmitter } = require("node:events");
|
||||
const { createHmac } = require("node:crypto");
|
||||
const { signPanelProbeRequest, verifyNodeProbeResponse } = require("../utils/node-hmac");
|
||||
|
||||
const source = fs.readFileSync(path.join(__dirname, "../public/js/settings.js"), "utf8");
|
||||
|
||||
function extract(start, end, text = source) {
|
||||
const first = text.indexOf(start);
|
||||
const last = text.indexOf(end, first + start.length);
|
||||
assert.ok(first >= 0 && last > first);
|
||||
return text.slice(first, last);
|
||||
}
|
||||
|
||||
test("resource editor stays read-only until its current settings load succeeds", async () => {
|
||||
const content = { inert: false, setAttribute() {}, removeAttribute() {} };
|
||||
const applied = [];
|
||||
const pending = new Map();
|
||||
const context = vm.createContext({
|
||||
console: { error() {} }, resourcesViewVersion: 0, currentResourcesTargetId: null,
|
||||
serverManageInlineView: { querySelector: () => content, style: {} },
|
||||
serverManageSubtitle: {}, serverManageTitle: {}, resourcesModalSubtitle: {},
|
||||
resServerNameInput: {}, resRenameServerBtn: {}, resourcesSave: null,
|
||||
resNewPort: null, resStartupSection: null, serversOverviewView: null,
|
||||
_resourcesPrefetch: null, document: { getElementById: () => null },
|
||||
clearAllCategoryFeedback() {}, resetMinecraftJavaSelector() {},
|
||||
findServerItemByName: () => ({ resources: { ramMb: 256 } }),
|
||||
_applyResourcesFormData: (data, name) => applied.push([name, data.resources.ramMb]),
|
||||
_getCachedResourcesData: () => null, renderPortsList() {}, renderPortDropdown() {}, switchServerCategory() {},
|
||||
_fetchResourcesData: (name) => new Promise((resolve, reject) => pending.set(name, { resolve, reject })),
|
||||
});
|
||||
vm.runInContext(extract("async function openResourcesModal(", "function hasServerManageUnsavedChanges("), context, { timeout: 1000 });
|
||||
const first = context.openResourcesModal("first");
|
||||
const second = context.openResourcesModal("second");
|
||||
assert.equal(content.inert, true);
|
||||
pending.get("first").resolve({ targetId: 17, resources: { ramMb: 512 } });
|
||||
await first;
|
||||
assert.equal(content.inert, true);
|
||||
assert.equal(context.currentResourcesTargetId, null);
|
||||
pending.get("second").resolve({ targetId: 18, resources: { ramMb: 1024 } });
|
||||
await second;
|
||||
assert.equal(content.inert, false);
|
||||
assert.equal(context.currentResourcesTargetId, 18);
|
||||
assert.deepEqual(applied, [["first", 256], ["second", 256], ["second", 1024]]);
|
||||
|
||||
const failed = context.openResourcesModal("failed");
|
||||
pending.get("failed").reject(new Error("read failed"));
|
||||
await failed;
|
||||
assert.equal(content.inert, true);
|
||||
assert.match(context.serverManageSubtitle.textContent, /Failed to load/);
|
||||
});
|
||||
|
||||
test("resource editor detects unsaved changes in every settings category", () => {
|
||||
const ram = { value: "512", validity: { badInput: false } };
|
||||
const backups = { value: "5" };
|
||||
const bandwidth = { value: "64" };
|
||||
const name = { value: "Alpha" };
|
||||
const command = { value: "node index.js", readOnly: false };
|
||||
const java = { value: "21" };
|
||||
const context = vm.createContext({
|
||||
currentResourcesServer: "alpha", currentResourcesTargetId: 18,
|
||||
resServerNameInput: name, originalServerDisplayName: "Alpha",
|
||||
resStartupCommand: command, originalStartupCommand: "node index.js",
|
||||
resJavaVersion: java, currentMinecraftJavaEnabled: true, originalMinecraftJavaVersion: "21",
|
||||
currentServerMainPort: 8080, originalServerMainPort: 8080,
|
||||
currentServerPorts: [8082, 8081], originalServerPorts: [8081, 8082],
|
||||
serverResourceEditorInputs: { ramMb: ram, backupsMax: backups, networkInboundLimitMb: bandwidth },
|
||||
savedServerResourceValues: { ramMb: 512, backupsMax: 5, networkInboundLimitMb: 64 },
|
||||
});
|
||||
vm.runInContext(extract("function readServerResourceEditorValue(", "function closeResourcesModal("), context);
|
||||
assert.equal(context.hasServerManageUnsavedChanges(), false);
|
||||
for (const [input, value] of [[name, "Beta"], [ram, "1024"], [backups, "0"], [bandwidth, ""], [command, "node other.js"], [java, "17"]]) {
|
||||
const original = input.value;
|
||||
input.value = value;
|
||||
assert.equal(context.hasServerManageUnsavedChanges(), true, `should detect ${original} changing to ${value}`);
|
||||
input.value = original;
|
||||
}
|
||||
context.currentServerMainPort = 8081;
|
||||
assert.equal(context.hasServerManageUnsavedChanges(), true);
|
||||
context.currentServerMainPort = 8080;
|
||||
ram.validity.badInput = true;
|
||||
assert.equal(context.hasServerManageUnsavedChanges(), true);
|
||||
context.currentResourcesTargetId = null;
|
||||
assert.equal(context.hasServerManageUnsavedChanges(), false);
|
||||
});
|
||||
|
||||
test("resource editor preserves the complete numeric value and refuses partial input", () => {
|
||||
const ram = { value: "1e3", valueAsNumber: 1000, validity: { badInput: false } };
|
||||
const context = vm.createContext({
|
||||
resRamMb: ram,
|
||||
resCpuCores: { value: "1.5", valueAsNumber: 1.5, validity: { badInput: false } },
|
||||
resStorageMb: null,
|
||||
resSwapMb: { value: "0" },
|
||||
});
|
||||
vm.runInContext(extract("function readOptionalResourceNumber(", "if (resStorageMb) {"), context, { timeout: 1000 });
|
||||
vm.runInContext(extract("function readHardwareResourceEdits(", "async function saveResourcesCategory("), context, { timeout: 1000 });
|
||||
assert.deepEqual({ ...context.readHardwareResourceEdits() }, { ramMb: 1000, cpuCores: 1.5, swapMb: 0 });
|
||||
Object.assign(ram, { value: "", valueAsNumber: NaN, validity: { badInput: true } });
|
||||
assert.throws(() => context.readHardwareResourceEdits(), /RAM limit must be a number/);
|
||||
});
|
||||
|
||||
test("resource editor saves only changes and updates the baseline only for a confirmed current save", async () => {
|
||||
const requests = [];
|
||||
const baseline = { ramMb: 512, cpuCores: 1, swapMb: -1, networkInboundLimitMb: 64, networkOutboundLimitMb: 0 };
|
||||
const context = vm.createContext({
|
||||
savedServerResourceValues: baseline,
|
||||
resourcesViewVersion: 1,
|
||||
currentResourcesTargetId: 18,
|
||||
_resourcesCache: new Map(),
|
||||
fetch: async (_url, { body }) => {
|
||||
requests.push(JSON.parse(body));
|
||||
return { ok: requests.length !== 2, json: async () => ({ ok: requests.length !== 2 }) };
|
||||
},
|
||||
});
|
||||
vm.runInContext(extract("async function patchResourcesForEditor(", "function readHardwareResourceEdits("), context, { timeout: 1000 });
|
||||
await context.patchResourcesForEditor("alpha", 1, { resources: { ramMb: 512, cpuCores: 2, swapMb: -1 } });
|
||||
assert.equal(baseline.cpuCores, 2);
|
||||
const unchanged = await context.patchResourcesForEditor("alpha", 1, { resources: { ramMb: 512, cpuCores: 2, swapMb: -1 } });
|
||||
assert.equal(unchanged.data.restarted, false);
|
||||
await context.patchResourcesForEditor("alpha", 1, { resources: { networkInboundLimitMb: 0, networkOutboundLimitMb: 0 } });
|
||||
assert.equal(baseline.networkInboundLimitMb, 64);
|
||||
await context.patchResourcesForEditor("alpha", 1, { resources: { networkInboundLimitMb: 0, networkOutboundLimitMb: 0 } });
|
||||
assert.equal(baseline.networkInboundLimitMb, 0);
|
||||
assert.equal(await context.patchResourcesForEditor("alpha", 0, { resources: { ramMb: 1024 } }), null);
|
||||
assert.equal(baseline.ramMb, 512);
|
||||
assert.deepEqual(requests, [
|
||||
{ resources: { cpuCores: 2 }, expectedTargetId: 18 },
|
||||
{ resources: { networkInboundLimitMb: 0 }, expectedTargetId: 18 },
|
||||
{ resources: { networkInboundLimitMb: 0 }, expectedTargetId: 18 },
|
||||
{ resources: { ramMb: 1024 }, expectedTargetId: 18 },
|
||||
]);
|
||||
});
|
||||
|
||||
test("server list ignores stale responses and resolves rows by technical name", async () => {
|
||||
const pending = [];
|
||||
const rendered = [];
|
||||
const rows = ["other", "alpha"].map(name => ({
|
||||
dataset: { name }, querySelector: () => ({ textContent: "alpha" }),
|
||||
}));
|
||||
const context = vm.createContext({
|
||||
URLSearchParams, window: {},
|
||||
_serversPage: 1, _serversSearch: "", _serversLimit: 50,
|
||||
serversListEl: { querySelector: () => ({}), querySelectorAll: () => rows },
|
||||
fetchWithTimeout: () => new Promise(resolve => pending.push(resolve)),
|
||||
renderServers: items => rendered.push(items),
|
||||
renderServersPagination() {},
|
||||
});
|
||||
vm.runInContext(extract("function clampServedPage(", "function shortId("), context);
|
||||
vm.runInContext(extract("let _cachedServersList =", "function renderServers("), context);
|
||||
vm.runInContext(extract("function findServerRowByName(", "let _templatesRenderToken"), context);
|
||||
const first = context.loadServers(1, "stale");
|
||||
const second = context.loadServers(1, "current");
|
||||
const items = [{ name: "other", displayName: "alpha" }, { name: "alpha", displayName: "alpha" }];
|
||||
pending[1]({ ok: true, json: async () => ({ items }) });
|
||||
await second;
|
||||
pending[0]({ ok: true, json: async () => ({ items: [] }) });
|
||||
await first;
|
||||
assert.deepEqual(rendered, [items]);
|
||||
context.items = items;
|
||||
vm.runInContext("_cachedServersList = items", context);
|
||||
assert.equal(context.findServerItemByName("ALPHA"), items[1]);
|
||||
assert.equal(context.findServerRowByName("ALPHA"), rows[1]);
|
||||
});
|
||||
|
||||
test("the admin server list reads past a stale worker snapshot and includes pending deletes", async () => {
|
||||
const index = fs.readFileSync(path.join(__dirname, "../index.js"), "utf8");
|
||||
const pending = [];
|
||||
const context = vm.createContext({
|
||||
process: { env: {} }, mapServerRow: row => row,
|
||||
db: { query: () => new Promise(resolve => pending.push(resolve)) },
|
||||
});
|
||||
vm.runInContext(extract("let _siCache =", "// Resolution for the resource-metrics", index), context);
|
||||
vm.runInContext(extract("async function loadServersIndexIncludingDeleting(", "// Cached snapshot backing", index), context);
|
||||
const older = context.loadServersIndex();
|
||||
const fresh = context.loadServersIndexIncludingDeleting();
|
||||
assert.equal(pending.length, 2);
|
||||
pending[1]([{ name: "pending", status: "deleting" }]);
|
||||
assert.equal((await fresh)[0].status, "deleting");
|
||||
pending[0]([{ name: "deleted" }]);
|
||||
assert.equal((await older).length, 1);
|
||||
const route = extract('app.get("/api/settings/servers",', 'app.get("/api/my-servers",', index);
|
||||
assert.match(route, /loadServersIndexIncludingDeleting\(\)/);
|
||||
assert.match(route, /deleting: String\(e\.status \|\| ""\)\.toLowerCase\(\) === "deleting"/);
|
||||
});
|
||||
|
||||
test("a pending delete row keeps its existing retry control without other server actions", () => {
|
||||
const rows = [];
|
||||
const context = vm.createContext({
|
||||
document: { createElement: () => ({ dataset: {} }) },
|
||||
serversListEl: { appendChild: row => rows.push(row) },
|
||||
_cachedServersList: [], _cacheResourcesData() {},
|
||||
displayTemplateName: String, escapeHtml: String,
|
||||
});
|
||||
vm.runInContext(extract("function renderServers(list)", "function getServerDeleteToken("), context);
|
||||
context.renderServers([{ name: "pending", targetId: 18, deleting: true }, { name: "normal", targetId: 19 }]);
|
||||
assert.equal(rows[0].dataset.targetId, "18");
|
||||
assert.match(rows[0].innerHTML, /Deletion pending/);
|
||||
assert.match(rows[0].innerHTML, /delete-server/);
|
||||
assert.doesNotMatch(rows[0].innerHTML, /manage-resources|transfer-server|change-template|server-suspension-action/);
|
||||
assert.match(rows[1].innerHTML, /manage-resources/);
|
||||
});
|
||||
|
||||
test("node allocation forms reject partial port numbers and overflowing ranges", () => {
|
||||
const context = vm.createContext({});
|
||||
vm.runInContext(extract("function parsePortsInput(", "function countPorts("), context);
|
||||
const input = (value) => ({ value });
|
||||
assert.throws(() => context.parsePortsInput("range", input("65535"), input("2")), /exceeds 65535/);
|
||||
assert.throws(() => context.parsePortsInput("range", input("22000"), input("1.5")), /Invalid count/);
|
||||
assert.throws(() => context.parsePortsInput("list", null, null, input("22000, 22001junk")), /whole port number/);
|
||||
assert.deepEqual(Array.from(context.parsePortsInput("list", null, null, input("22000, 22001, 22000")).ports), [22000, 22001]);
|
||||
});
|
||||
|
||||
test("port pickers use configured addresses and reject obsolete wizard allocations", () => {
|
||||
const feedback = [];
|
||||
const select = { value: "" };
|
||||
const context = vm.createContext({
|
||||
cn_address: { value: "192.0.2.10" },
|
||||
cn_additional_ips_container: { querySelectorAll: () => [{ value: "192.0.2.11" }] },
|
||||
cn_under_cloudflare: { checked: false },
|
||||
createNodeAllocatedPorts: [{ ip: "192.0.2.10", port: 22000 }],
|
||||
nm_address: { value: "192.0.2.99" },
|
||||
nm_port_ip_select: select,
|
||||
nm_port_ip_selected_text: null,
|
||||
nm_port_ip_dropdown_menu: { querySelectorAll: () => [] },
|
||||
escapeHtml: String,
|
||||
isNodeUnderCloudflare: (node) => node.under_cloudflare,
|
||||
showCreateStepFeedback: (_, message) => feedback.push(message),
|
||||
});
|
||||
vm.runInContext(
|
||||
extract("function getAdditionalIpsFromContainer(", "function populateCreateNodePortsIpDropdown(") +
|
||||
extract("function validateCreateNodeStep(", "function renderCreateNodePortsList("),
|
||||
context,
|
||||
);
|
||||
context.populateNodePortsIpDropdown({ address: "192.0.2.10", additional_ips: ["192.0.2.11"] });
|
||||
assert.equal(select.value, "192.0.2.10");
|
||||
assert.doesNotMatch(select.innerHTML, /192\.0\.2\.99/);
|
||||
context.populateNodePortsIpDropdown({ address: "node.example.test", additional_ips: ["192.0.2.11"], under_cloudflare: true });
|
||||
assert.equal(select.value, "192.0.2.11");
|
||||
assert.doesNotMatch(select.innerHTML, /node\.example\.test/);
|
||||
|
||||
assert.equal(context.validateCreateNodeStep(3), true);
|
||||
context.cn_address.value = "192.0.2.12";
|
||||
assert.equal(context.validateCreateNodeStep(3), false);
|
||||
assert.match(feedback.at(-1), /22000 uses 192\.0\.2\.10/);
|
||||
context.createNodeAllocatedPorts[0].ip = "192.0.2.11";
|
||||
assert.equal(context.validateCreateNodeStep(3), true);
|
||||
});
|
||||
|
||||
test("an older Nodes response cannot overwrite the latest list and page", async () => {
|
||||
const replies = [];
|
||||
const rendered = [];
|
||||
const context = vm.createContext({
|
||||
URLSearchParams,
|
||||
nodesListEl: { querySelector: () => ({}) },
|
||||
fetch: () => new Promise(resolve => replies.push(resolve)),
|
||||
clampServedPage: (served) => served,
|
||||
renderNodes: (nodes) => rendered.push(nodes[0].id),
|
||||
renderNodesPagination: (page) => rendered.push(page),
|
||||
});
|
||||
vm.runInContext(extract("async function loadNodes(", "let _serversPage"), context);
|
||||
|
||||
const oldPage = context.loadNodes(3);
|
||||
let finishOldBody;
|
||||
await new Promise(started => {
|
||||
replies[0]({ ok: true, json: () => new Promise(resolve => {
|
||||
finishOldBody = resolve;
|
||||
started();
|
||||
}) });
|
||||
});
|
||||
const search = context.loadNodes(1, "current");
|
||||
replies[1]({ ok: true, json: async () => ({ nodes: [{ id: "current" }], page: 1 }) });
|
||||
await search;
|
||||
finishOldBody({ nodes: [{ id: "old" }], page: 3, totalPages: 3 });
|
||||
await oldPage;
|
||||
|
||||
assert.deepEqual(rendered, ["current", 1]);
|
||||
assert.equal(vm.runInContext("_nodesPage", context), 1);
|
||||
});
|
||||
|
||||
test("the Nodes list does not turn a panel-reported offline node green", () => {
|
||||
const rows = [];
|
||||
const context = vm.createContext({
|
||||
Date: { now: () => 200000 },
|
||||
nodesListEl: { appendChild() {} },
|
||||
document: {
|
||||
createDocumentFragment: () => ({ appendChild: (row) => rows.push(row.innerHTML) }),
|
||||
createElement: () => ({
|
||||
dataset: {},
|
||||
querySelector: () => ({ addEventListener() {} }),
|
||||
addEventListener() {},
|
||||
}),
|
||||
},
|
||||
escapeHtml: String,
|
||||
countPorts: () => 0,
|
||||
});
|
||||
vm.runInContext(extract("function renderNodes(", "if (typeof window.io === 'function') {\n try {\n const _nodeStatusSocket"), context);
|
||||
context.renderNodes([
|
||||
{ id: "offline", port_ok: true, last_seen: 100000, online: false },
|
||||
{ id: "online", port_ok: true, last_seen: 100000, online: true },
|
||||
]);
|
||||
assert.match(rows[0], /status-dot red" title="Offline"/);
|
||||
assert.match(rows[1], /status-dot green" title="Online"/);
|
||||
});
|
||||
|
||||
test("live Nodes status resubscribes and matches the daemon UUID", () => {
|
||||
const socket = new EventEmitter();
|
||||
const subscriptions = [];
|
||||
const updates = [];
|
||||
socket.on("dashboard:subscribe", (nodes) => subscriptions.push(nodes));
|
||||
const row = { dataset: { id: "database-node-id", uuid: "daemon-node-uuid" } };
|
||||
const context = vm.createContext({
|
||||
window: { io: () => socket },
|
||||
nodesListEl: { querySelectorAll: () => [row] },
|
||||
setNodeStatus: (target, status) => updates.push([target, status]),
|
||||
});
|
||||
vm.runInContext(extract("if (typeof window.io === 'function') {\n try {\n const _nodeStatusSocket", "function isIPAddress("), context);
|
||||
socket.emit("connect");
|
||||
socket.emit("disconnect");
|
||||
socket.emit("connect");
|
||||
socket.emit("node:status", { id: "daemon-node-uuid", online: false });
|
||||
assert.equal(subscriptions.length, 2);
|
||||
assert.deepEqual(updates, [[row, "red"]]);
|
||||
});
|
||||
|
||||
test("out-of-order allocation and disk responses stay on their own node", async () => {
|
||||
const replies = new Map();
|
||||
const renders = [];
|
||||
const context = vm.createContext({
|
||||
CURRENT_NODE: { id: "first" },
|
||||
nodeManageRequest: 1,
|
||||
nm_allocated_ports_container: {},
|
||||
nm_disks_list: {},
|
||||
console,
|
||||
fetch: (url) => new Promise(resolve => replies.set(url, resolve)),
|
||||
nodeApiId: () => context.CURRENT_NODE.id,
|
||||
updateAllocatedPortsSelectionUI() {},
|
||||
showCategoryFeedback() {},
|
||||
renderNodeAllocatedPorts: (node) => renders.push(node.id),
|
||||
renderNodeDisks: (disks) => renders.push(...disks),
|
||||
});
|
||||
vm.runInContext(
|
||||
extract("let currentNodeInUsePorts = {};", "function renderAdditionalIpRows") +
|
||||
extract("async function loadNodeDisks()", "async function addNodeDisk()"),
|
||||
context,
|
||||
);
|
||||
|
||||
const loadNode = () => vm.runInContext("Promise.all([loadNodeInUsePorts(CURRENT_NODE), loadNodeDisks()])", context);
|
||||
const first = loadNode();
|
||||
context.CURRENT_NODE = { id: "second" };
|
||||
context.nodeManageRequest++;
|
||||
const second = loadNode();
|
||||
const finish = (node) => {
|
||||
replies.get(`/api/nodes/${node}/ports/in-use`)({ ok: true, json: async () => ({ inUse: { [node]: true } }) });
|
||||
replies.get(`/api/nodes/${node}/disks`)({ ok: true, json: async () => ({ disks: [`disk:${node}`] }) });
|
||||
};
|
||||
finish("second");
|
||||
await second;
|
||||
finish("first");
|
||||
await first;
|
||||
assert.deepEqual(renders, ["second", "disk:second"]);
|
||||
assert.equal(vm.runInContext("JSON.stringify(currentNodeInUsePorts)", context), '{"second":true}');
|
||||
});
|
||||
|
||||
test("leaving the Nodes tab locks credentials and stops its pending polls", () => {
|
||||
const calls = [];
|
||||
const context = vm.createContext({
|
||||
_nodesSearchTimer: 1,
|
||||
_nodesLoadRequest: 3,
|
||||
stopNodesPolling: () => calls.push("list"),
|
||||
clearTimeout: (timer) => calls.push(timer),
|
||||
stopCreateNodeHealthCheck: () => calls.push("health"),
|
||||
lockNodeSecret: (view, kind) => calls.push(`${view}:${kind}`),
|
||||
resetNodeDangerZone: () => calls.push("delete"),
|
||||
});
|
||||
vm.runInContext(extract("function leaveNodesPanel(", "if (nodesSearchInput)"), context);
|
||||
context.leaveNodesPanel();
|
||||
assert.deepEqual(calls, ["list", 1, "health", "cn:config", "cn:command", "nm:config", "nm:command", "delete"]);
|
||||
assert.equal(context._nodesLoadRequest, 4);
|
||||
assert.match(source, /panel !== 'nodes' && sidebarNav\.querySelector\('button\[data-panel="nodes"\]\.active'\)\) leaveNodesPanel\(\)/);
|
||||
});
|
||||
|
||||
test("dismissing a node secret dialog discards a verification response still in flight", async () => {
|
||||
let finish;
|
||||
const context = vm.createContext({
|
||||
nodeSecretRevealState: { context: "nm", kind: "config", request: Symbol() },
|
||||
nodeSecretModalOverlay: { classList: { remove() {} }, setAttribute() {} },
|
||||
nodeSecretCredential: { value: "fixture-password" },
|
||||
nodeSecretModalConfirm: { disabled: false },
|
||||
setNodeSecretModalError() {},
|
||||
validateStepUpCredential: (input) => input.value,
|
||||
requestNodeSecret: () => new Promise(resolve => { finish = resolve; }),
|
||||
revealNodeSecretSurface: () => assert.fail("a dismissed dialog must not reveal credentials"),
|
||||
});
|
||||
vm.runInContext(
|
||||
extract("function closeNodeSecretModal()", "async function requestNodeSecret(") +
|
||||
extract("async function confirmNodeSecretReveal()", "// Post-rotation refresh:"),
|
||||
context,
|
||||
);
|
||||
const verification = context.confirmNodeSecretReveal();
|
||||
assert.equal(context.nodeSecretModalConfirm.disabled, true);
|
||||
context.closeNodeSecretModal();
|
||||
assert.equal(context.nodeSecretCredential.value, "");
|
||||
finish({ value: "synthetic config" });
|
||||
await verification;
|
||||
assert.equal(context.nodeSecretModalConfirm.disabled, false);
|
||||
});
|
||||
|
||||
test("only a valid daemon response proof verifies a setup probe", () => {
|
||||
const secret = "fixture-node-signing-key";
|
||||
const nodeId = "fixture-node";
|
||||
const probe = signPanelProbeRequest(secret, nodeId, "stats");
|
||||
const response = { panel_nonce: probe.nonce };
|
||||
assert.equal(verifyNodeProbeResponse(secret, nodeId, "stats", probe, response), false);
|
||||
response.panel_nonce_proof = createHmac("sha256", secret)
|
||||
.update(`${nodeId}|probe-response|stats|${probe.nonce}`).digest("hex");
|
||||
assert.equal(verifyNodeProbeResponse(secret, nodeId, "stats", probe, response), true);
|
||||
assert.equal(verifyNodeProbeResponse(secret, nodeId, "info", probe, response), false);
|
||||
assert.equal(verifyNodeProbeResponse(secret, nodeId, "stats", signPanelProbeRequest(secret, nodeId, "stats"), response), false);
|
||||
});
|
||||
|
||||
test("statistics polling keeps one request per view and ignores closed views", async () => {
|
||||
const requests = [];
|
||||
const rendered = [];
|
||||
const intervals = new Map();
|
||||
const context = vm.createContext({
|
||||
AbortController,
|
||||
nodeStatsModalOverlay: { classList: { add() {}, remove() {} } },
|
||||
statsNodeNameEl: {},
|
||||
statsModalBody: {},
|
||||
document: { body: { style: {} } },
|
||||
setInterval: (tick) => { const id = Symbol(); intervals.set(id, tick); return id; },
|
||||
clearInterval: (id) => intervals.delete(id),
|
||||
fetch: (_, options) => new Promise(resolve => requests.push({ resolve, signal: options.signal })),
|
||||
renderOfflineStats: () => assert.fail("stale responses must not render an offline state"),
|
||||
renderStats: (data) => rendered.push(data.nodeName),
|
||||
});
|
||||
vm.runInContext(extract("let statsPollingInterval =", "function renderOfflineStats("), context);
|
||||
context.openNodeStatsModal("first", "First");
|
||||
await [...intervals.values()][0]();
|
||||
assert.equal(requests.length, 1);
|
||||
context.openNodeStatsModal("second", "Second");
|
||||
assert.equal(intervals.size, 1);
|
||||
assert.equal(requests[0].signal.aborted, true);
|
||||
const finish = async (index, nodeName) => {
|
||||
requests[index].resolve({ ok: true, json: async () => ({ ok: true, online: true, nodeName }) });
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
};
|
||||
await finish(1, "Second");
|
||||
await finish(0, "First");
|
||||
assert.deepEqual(rendered, ["Second"]);
|
||||
[...intervals.values()][0]();
|
||||
context.closeNodeStatsModal();
|
||||
assert.equal(intervals.size, 0);
|
||||
assert.equal(requests[2].signal.aborted, true);
|
||||
await finish(2, "Closed");
|
||||
assert.deepEqual(rendered, ["Second"]);
|
||||
});
|
||||
|
||||
test("late node update info cannot replace the selected update target", async () => {
|
||||
const requests = [];
|
||||
const documentElements = new Map();
|
||||
for (const id of ["nodeUpdateOverlay", "nodeUpdateModal", "nodeUpdateSelect", "nodeUpdateVersion", "checkNodeUpdatesBtn"]) {
|
||||
documentElements.set(id, { dataset: {}, classList: { add() {}, remove() {} }, addEventListener() {} });
|
||||
}
|
||||
const context = vm.createContext({
|
||||
URLSearchParams,
|
||||
document: { getElementById: (id) => documentElements.get(id), addEventListener() {} },
|
||||
window: { setTimeout() {} },
|
||||
escapeHtml: String,
|
||||
fetch: (url) => new Promise(resolve => requests.push({ url, resolve })),
|
||||
});
|
||||
const first = source.indexOf("(function () {\n const overlay = document.getElementById('nodeUpdateOverlay');");
|
||||
assert.ok(first >= 0);
|
||||
const last = source.indexOf("\n})();", first);
|
||||
assert.ok(last > first);
|
||||
vm.runInContext(source.slice(first, last + "\n})();".length), context);
|
||||
context.window.openNodeUpdateModal("first");
|
||||
context.window.openNodeUpdateModal("second");
|
||||
const checkBtn = documentElements.get("checkNodeUpdatesBtn");
|
||||
assert.equal(checkBtn.disabled, true);
|
||||
const finish = async (index, nodeId) => {
|
||||
assert.match(requests[index].url, new RegExp(`nodeId=${nodeId}$`));
|
||||
requests[index].resolve({ ok: true, json: async () => ({
|
||||
nodes: [{ id: "first" }, { id: "second" }], selectedNode: { id: nodeId },
|
||||
version: nodeId, actionTokens: { checkUpdate: nodeId },
|
||||
}) });
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
};
|
||||
await finish(1, "second");
|
||||
await finish(0, "first");
|
||||
assert.equal(documentElements.get("nodeUpdateVersion").innerHTML, "<code>second</code>");
|
||||
assert.match(documentElements.get("nodeUpdateSelect").innerHTML, /value="second" selected/);
|
||||
assert.equal(checkBtn.disabled, false);
|
||||
});
|
||||
|
||||
test("setup only counts authenticated samples from the current wizard run", async () => {
|
||||
const replies = [];
|
||||
const complete = { disabled: true };
|
||||
const context = vm.createContext({
|
||||
AbortController,
|
||||
createNodeCreatedId: "first",
|
||||
createNodeHealthRun: null,
|
||||
createNodeHealthPollingInterval: null,
|
||||
createNodeVerifiedStreak: 0,
|
||||
nodeCreateCompleteBtn: complete,
|
||||
document: { getElementById: (id) => id === "nodeCreateCompleteBtn" ? complete : null },
|
||||
setInterval: () => 1,
|
||||
clearInterval() {},
|
||||
fetch: (_, options) => new Promise(resolve => replies.push({ resolve, signal: options.signal })),
|
||||
});
|
||||
vm.runInContext(extract("function startCreateNodeHealthCheck()", "if (openCreateNodeBtn)"), context);
|
||||
const finish = async (index, data) => {
|
||||
replies[index].resolve({ ok: true, json: async () => ({ online: true, ...data }) });
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
};
|
||||
context.startCreateNodeHealthCheck();
|
||||
await context.checkCreateNodeHealth();
|
||||
assert.equal(replies.length, 1);
|
||||
context.stopCreateNodeHealthCheck();
|
||||
assert.equal(replies[0].signal.aborted, true);
|
||||
context.createNodeCreatedId = "second";
|
||||
context.startCreateNodeHealthCheck();
|
||||
await finish(0, { verified: true });
|
||||
await finish(1, { verified: false, verificationAvailable: false });
|
||||
assert.equal(context.createNodeVerifiedStreak, 0);
|
||||
const verifiedOnce = context.checkCreateNodeHealth();
|
||||
await finish(2, { verified: true });
|
||||
await verifiedOnce;
|
||||
assert.equal(complete.disabled, true);
|
||||
const verifiedTwice = context.checkCreateNodeHealth();
|
||||
await finish(3, { verified: true });
|
||||
await verifiedTwice;
|
||||
assert.equal(complete.disabled, false);
|
||||
});
|
||||
|
||||
test("the creation summary uses the current saved draft, not a previous registration", async () => {
|
||||
const saves = [];
|
||||
const feedback = [];
|
||||
let healthStarts = 0;
|
||||
const next = { style: {}, disabled: false };
|
||||
const context = vm.createContext({
|
||||
createNodeCurrentStep: 4,
|
||||
createNodeMaxStepReached: 6,
|
||||
createNodeDraftSave: null,
|
||||
createNodeCreatedId: "previous",
|
||||
createNodeCreatedNode: { id: "previous" },
|
||||
nodeCreateCategoriesNav: null,
|
||||
nodeCreatePrevBtn: null,
|
||||
nodeCreateNextBtn: next,
|
||||
nodeCreateCompleteBtn: null,
|
||||
document: { getElementById: () => null },
|
||||
validateCreateNodeStep: () => true,
|
||||
lockNodeSecret() {},
|
||||
showCreateStepFeedback: (_, message) => feedback.push(message),
|
||||
registerCreateNodeDraft: () => new Promise((resolve, reject) => saves.push({ resolve, reject })),
|
||||
renderCreateNodeSummary() {},
|
||||
stopCreateNodeHealthCheck() {},
|
||||
startCreateNodeHealthCheck: () => { healthStarts++; },
|
||||
autoFitPanelInputs() {},
|
||||
triggerAutoResizeInputs() {},
|
||||
});
|
||||
vm.runInContext(
|
||||
extract("function goToCreateNodeStep(", "function showCreateStepFeedback(") +
|
||||
extract("async function renderCreateNodeLinking()", "function renderCreateNodeSummary()") +
|
||||
extract("async function resolveNodeSecretNodeId(", "async function confirmNodeSecretReveal()"),
|
||||
context,
|
||||
);
|
||||
context.goToCreateNodeStep(6);
|
||||
assert.equal(context.createNodeCurrentStep, 5);
|
||||
assert.equal(next.disabled, true);
|
||||
context.goToCreateNodeStep(6);
|
||||
assert.equal(saves.length, 1);
|
||||
await assert.rejects(context.resolveNodeSecretNodeId("cn"), /Save the current node configuration/);
|
||||
assert.equal(saves.length, 1);
|
||||
saves[0].reject(new Error("Port allocations changed"));
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
assert.deepEqual(feedback, ["Port allocations changed"]);
|
||||
assert.equal(healthStarts, 0);
|
||||
assert.equal(next.disabled, false);
|
||||
|
||||
context.goToCreateNodeStep(6);
|
||||
assert.equal(context.createNodeCurrentStep, 5);
|
||||
context.createNodeDraftSave = null;
|
||||
saves[1].resolve({ id: "abandoned" });
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
assert.equal(context.createNodeCreatedId, "previous");
|
||||
|
||||
context.goToCreateNodeStep(5);
|
||||
saves[2].resolve({ id: "current" });
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
context.goToCreateNodeStep(6);
|
||||
assert.equal(context.createNodeCreatedId, "current");
|
||||
assert.equal(context.createNodeCurrentStep, 6);
|
||||
assert.equal(healthStarts, 1);
|
||||
assert.equal(await context.resolveNodeSecretNodeId("cn"), "current");
|
||||
});
|
||||
|
||||
test("node step-up middleware stops on a missing target or a lookup error", async () => {
|
||||
const routes = new Map();
|
||||
const app = Object.fromEntries(["delete", "patch", "post"].map(method => [method,
|
||||
(route, _limiter, handler) => routes.set(`${method} ${route}`, handler),
|
||||
]));
|
||||
const index = fs.readFileSync(path.join(__dirname, "../index.js"), "utf8");
|
||||
const lookupError = new Error("synthetic database failure");
|
||||
let failLookup;
|
||||
let foundNode;
|
||||
const verifiedScopes = [];
|
||||
const context = vm.createContext({
|
||||
app,
|
||||
sessionRevoke2faRateLimiter() {},
|
||||
isAdmin: async () => true,
|
||||
findUserByEmail: async () => ({ admin: true }),
|
||||
findNodeByIdOrName: async () => {
|
||||
if (failLookup) throw lookupError;
|
||||
return foundNode;
|
||||
},
|
||||
requireDestructiveActionStepUp: (_req, _res, _user, _subject, options) => {
|
||||
assert.ok(foundNode, "a missing target must not prompt for verification");
|
||||
verifiedScopes.push(options.scopeKey);
|
||||
return { ok: true, usedFreshVerification: false };
|
||||
},
|
||||
nodeConnectionState: require("../services/node-http").nodeConnectionState,
|
||||
});
|
||||
vm.runInContext(extract("function nodeStepUpScopeKey(", "// --- Node credential reveal", index), context);
|
||||
|
||||
for (const key of ["delete /api/nodes/:id", "patch /api/nodes/:id", "post /api/nodes/:id/build"]) {
|
||||
const handler = routes.get(key);
|
||||
assert.equal(typeof handler, "function", key);
|
||||
const req = { params: { id: "fixture-node" }, session: { user: "admin@example.test" } };
|
||||
const statuses = [];
|
||||
const next = [];
|
||||
const res = { status: (code) => ({ json: () => statuses.push(code) }) };
|
||||
failLookup = false;
|
||||
foundNode = null;
|
||||
await handler(req, res, (error) => next.push(error));
|
||||
assert.deepEqual(statuses, [404], key);
|
||||
assert.deepEqual(next, [], key);
|
||||
failLookup = true;
|
||||
await handler(req, res, (error) => next.push(error));
|
||||
assert.deepEqual(statuses, [404], key);
|
||||
assert.deepEqual(next, [lookupError], key);
|
||||
failLookup = false;
|
||||
foundNode = { id: "canonical-node" };
|
||||
await handler(req, res, (error) => next.push(error));
|
||||
assert.equal(req.verifiedNodeMutationId, "canonical-node");
|
||||
assert.equal(req.nodeMutationUsedGrace, key.startsWith("delete ") ? undefined : true);
|
||||
assert.deepEqual(next, [lookupError, undefined], key);
|
||||
}
|
||||
assert.deepEqual(verifiedScopes, Array(3).fill("node:canonical-node"));
|
||||
});
|
||||
|
||||
test("Cloudflare validation permits real bind IPs and cleanup of legacy allocations", async () => {
|
||||
const nodes = fs.readFileSync(path.join(__dirname, "../nodes.js"), "utf8");
|
||||
const hostname = "node.example.test";
|
||||
const bind = { ip: "192.0.2.10", port: 25565 };
|
||||
const legacy = { ip: hostname, port: 25566 };
|
||||
const context = vm.createContext({
|
||||
net: require("node:net"),
|
||||
ipRangeCheck: require("ip-range-check"),
|
||||
nodeSsrfGuard: require("../utils/node-ssrf-guard"),
|
||||
...require("../services/server-create"),
|
||||
nodeUnderCloudflare: require("../services/node-http").nodeUnderCloudflare,
|
||||
getNodeAllocations: (node) => node?.ports?.allocations || [],
|
||||
resolvePublicHostnameIps: async () => ({ ips: ["198.51.100.20"], resolver: "fixture" }),
|
||||
getCloudflareIpRanges: async () => ["198.51.100.0/24"],
|
||||
});
|
||||
vm.runInContext(extract("async function verifyCloudflareProxiedAddress(", "// nodeUnderCloudflare", nodes), context);
|
||||
const verify = context.verifyCloudflareProxiedAddress;
|
||||
const previous = { ports: { allocations: [legacy] }, under_cloudflare: true };
|
||||
assert.equal((await verify(hostname, [bind])).ok, true);
|
||||
assert.equal((await verify(hostname, [bind, legacy], previous)).ok, true);
|
||||
assert.equal((await verify(hostname, [bind], previous)).ok, true);
|
||||
previous.under_cloudflare = false;
|
||||
assert.equal((await verify(hostname, [bind, legacy], previous, new Map([[legacy.port, ["fixture-server"]]]))).ok, true);
|
||||
assert.equal((await verify(hostname, [bind, legacy], previous, new Map())).ok, false);
|
||||
assert.equal((await verify(hostname, [bind, legacy])).ok, false);
|
||||
assert.equal((await verify(hostname, [{ ...bind, ip: "2001:db8::2" }])).ok, true);
|
||||
for (const ip of ["0.0.0.0", "::", "0:0:0:0:0:0:0:0", "::ffff:0.0.0.0"]) {
|
||||
assert.equal((await verify(hostname, [{ ...bind, ip }])).ok, false, ip);
|
||||
}
|
||||
});
|
||||
|
||||
test("credential-bearing Nodes responses require trusted HTTPS unless explicitly overridden", () => {
|
||||
const root = path.join(__dirname, "..");
|
||||
const index = fs.readFileSync(path.join(root, "index.js"), "utf8");
|
||||
const nodes = fs.readFileSync(path.join(root, "nodes.js"), "utf8");
|
||||
const context = vm.createContext({
|
||||
ALLOW_INSECURE_NODE_BOOTSTRAP: false,
|
||||
nodeBootstrapTransport: { secure: (req) => req.secure },
|
||||
});
|
||||
vm.runInContext(extract("function requireNodeBootstrapTransport(", "\n}\n", nodes) + "\n}", context);
|
||||
assert.match(nodes, /module\.exports\.requireNodeBootstrapTransport = requireNodeBootstrapTransport/);
|
||||
for (const route of ["config.yml", "one-time-command", "rotate-token"]) {
|
||||
assert.ok(index.includes(`app.post("/api/nodes/:id/${route}", sessionRevoke2faRateLimiter, nodesRouter.requireNodeBootstrapTransport,`));
|
||||
}
|
||||
const response = () => ({
|
||||
set(name, value) { this[name] = value; return this; },
|
||||
status(status) { this.statusCode = status; return this; },
|
||||
json(body) { this.body = body; },
|
||||
});
|
||||
const insecure = response();
|
||||
context.requireNodeBootstrapTransport({ method: "POST", secure: false }, insecure, () => assert.fail("insecure requests cannot reveal credentials"));
|
||||
assert.equal(insecure.statusCode, 403);
|
||||
assert.equal(insecure["Cache-Control"], "no-store");
|
||||
assert.match(insecure.body.error, /HTTPS required/);
|
||||
let allowed = 0;
|
||||
const secure = response();
|
||||
context.requireNodeBootstrapTransport({ method: "POST", secure: true }, secure, () => allowed++);
|
||||
assert.equal(secure["Cache-Control"], "no-store");
|
||||
context.ALLOW_INSECURE_NODE_BOOTSTRAP = true;
|
||||
context.requireNodeBootstrapTransport({ method: "POST", secure: false }, response(), () => allowed++);
|
||||
assert.equal(allowed, 2);
|
||||
});
|
||||
|
||||
test("node credential operations refuse an alias fallback after step-up", async () => {
|
||||
const index = fs.readFileSync(path.join(__dirname, "../index.js"), "utf8");
|
||||
const routes = new Map();
|
||||
const context = vm.createContext({
|
||||
app: { post: (route, ...handlers) => routes.set(route, handlers.at(-1)) },
|
||||
sessionRevoke2faRateLimiter() {},
|
||||
isAdmin: async () => true,
|
||||
findUserByEmail: async () => ({ admin: true }),
|
||||
nodeStepUpScopeKey: (node) => `node:${node.id}`,
|
||||
requireDestructiveActionStepUp: async (_req, _res, _user, _subject, options) => {
|
||||
assert.equal(options.scopeKey, "node:verified");
|
||||
return { ok: true };
|
||||
},
|
||||
withKeyedLock: async (key, task) => {
|
||||
assert.equal(key, "node-ports:verified");
|
||||
return task();
|
||||
},
|
||||
findNodeByIdOrName: async (id) => id === "requested" ? { id: "verified" }
|
||||
: { id: "different", name: "verified", token: "synthetic-token" },
|
||||
nodesRouter: { requireNodeBootstrapTransport() {}, buildConfigYml: assert.fail, oneTimeCommand: assert.fail },
|
||||
callNodeUpdateApi: assert.fail,
|
||||
});
|
||||
vm.runInContext(
|
||||
extract('app.post("/api/nodes/:id/config.yml"', "nodesRouter.setNodeBootstrapTransport(", index) +
|
||||
extract('app.post("/api/nodes/:id/rotate-token"', 'app.get("/api/nodes/:id/disks"', index),
|
||||
context,
|
||||
);
|
||||
for (const suffix of ["config.yml", "one-time-command", "rotate-token"]) {
|
||||
const response = {};
|
||||
const req = { params: { id: "requested" }, session: { user: "admin@example.test" } };
|
||||
const res = { status: (status) => ({ json: (body) => Object.assign(response, { status, body }) }) };
|
||||
await routes.get(`/api/nodes/:id/${suffix}`)(req, res, (err) => { throw err; });
|
||||
assert.equal(response.status, 404, suffix);
|
||||
assert.equal(response.body.error, "node not found");
|
||||
}
|
||||
});
|
||||
|
||||
test("wizard disks stay queued through temporary daemon and proxy rejections", async () => {
|
||||
const index = fs.readFileSync(path.join(__dirname, "../index.js"), "utf8");
|
||||
const node = { id: "fixture-node", buildConfig: { requestedDisks: [{ mount: "/mnt/fixture", limitGb: 10 }] } };
|
||||
const saved = [];
|
||||
let reply;
|
||||
const context = vm.createContext({
|
||||
_pendingDiskApplyInFlight: new Set(),
|
||||
callNodeUpdateApi: async () => reply,
|
||||
withKeyedLock: async (_key, task) => task(),
|
||||
nodesRouter: { findNodeByIdOrName: async () => node, saveNode: async () => saved.push(node.id) },
|
||||
console: { warn() {}, log() {} },
|
||||
});
|
||||
vm.runInContext(extract("async function applyPendingNodeDisks(", "const _pendingDiskApplyTimer", index), context);
|
||||
for (const rejected of [
|
||||
{ status: 401, json: { ok: false, error: "unauthorized" } },
|
||||
{ status: 403, json: { ok: false, error: "bad-signature" } },
|
||||
{ status: 404, json: { error: "not found" } },
|
||||
{ status: 409, json: { ok: false, error: "proxy conflict" } },
|
||||
{ status: 429, json: { error: "rate limited" } },
|
||||
{ status: 400, json: null },
|
||||
]) {
|
||||
reply = rejected;
|
||||
await context.applyPendingNodeDisks(node);
|
||||
assert.equal(node.buildConfig.requestedDisks.length, 1, String(reply.status));
|
||||
assert.deepEqual(saved, []);
|
||||
}
|
||||
reply = { status: 409, json: { ok: false, error: "disk already registered" } };
|
||||
await context.applyPendingNodeDisks(node);
|
||||
assert.equal(node.buildConfig.requestedDisks, undefined);
|
||||
assert.deepEqual(saved, [node.id]);
|
||||
});
|
||||
|
||||
test("saving unrelated node settings preserves TLS on an IP-addressed node", async () => {
|
||||
const writes = [];
|
||||
const context = vm.createContext({
|
||||
CURRENT_NODE: { id: "fixture-node", address: "192.0.2.10", ssl_enabled: true },
|
||||
nodeManageRequest: 1,
|
||||
nm_name: { value: "Renamed node" },
|
||||
nm_address: { value: "192.0.2.10" },
|
||||
nm_ssl_enabled: { checked: true },
|
||||
nm_under_cloudflare: { checked: false },
|
||||
nm_additional_ips_container: null,
|
||||
nm_cpu_cores: null,
|
||||
nm_ram_gb: null,
|
||||
nm_disk_gb: null,
|
||||
nm_max_upload_mb: null,
|
||||
nm_daemon_port: { value: "8443" },
|
||||
nm_save_config_btn: null,
|
||||
nm_save_resources_btn: null,
|
||||
showCategoryFeedback() {},
|
||||
getAdditionalIpsFromContainer: () => [],
|
||||
canUseHttpsForNodeAddress: () => false,
|
||||
sendNodeWriteWithStepUp: async (_url, _method, payload) => {
|
||||
writes.push(payload);
|
||||
return { res: { ok: false }, data: {} };
|
||||
},
|
||||
});
|
||||
vm.runInContext(extract("async function saveNodeCategory(", "if (nm_save_config_btn)"), context);
|
||||
await context.saveNodeCategory("node-config");
|
||||
assert.equal(writes[0].ssl_enabled, true);
|
||||
assert.equal(writes[0].under_cloudflare, false);
|
||||
context.nm_ssl_enabled.checked = false;
|
||||
await context.saveNodeCategory("node-config");
|
||||
assert.equal(writes[1].ssl_enabled, false);
|
||||
});
|
||||
|
||||
test("a rejected live node status sample does not update the fleet cache or badge", async () => {
|
||||
const index = fs.readFileSync(path.join(__dirname, "../index.js"), "utf8");
|
||||
const nodes = new Map();
|
||||
const published = [];
|
||||
const samples = [];
|
||||
let accept = false;
|
||||
const context = vm.createContext({
|
||||
statusCache: { nodes },
|
||||
nodesRouter: { async saveNodeHealth(sample) { samples.push(sample); return accept ? sample : null; } },
|
||||
redisClient: null,
|
||||
broadcastNodeUpdate: (id, data) => published.push([id, data.online]),
|
||||
markNodeServersOnline: async () => {},
|
||||
markNodeServersOffline: async () => {},
|
||||
});
|
||||
vm.runInContext(extract("async function setCachedNodeStatus(", "function nodeIdentityVariants(", index), context);
|
||||
const connection = { id: "node-one", api_port: 8443, token: "fixture" };
|
||||
assert.equal(await context.setCachedNodeStatus("node-one", { online: true, checkedAt: 10 }, connection), false);
|
||||
assert.equal(nodes.size, 0);
|
||||
assert.deepEqual(published, []);
|
||||
assert.equal(samples[0].api_port, 8443);
|
||||
assert.equal(samples[0].last_check, 10);
|
||||
accept = true;
|
||||
await context.setCachedNodeStatus("node-one", { online: true }, connection);
|
||||
assert.deepEqual(published, [["node-one", true]]);
|
||||
accept = false;
|
||||
assert.equal(await context.setCachedNodeStatus("node-one", { online: false }, connection), false);
|
||||
assert.equal(nodes.get("node-one").online, true);
|
||||
assert.deepEqual(published, [["node-one", true]]);
|
||||
});
|
||||
|
||||
test("the live Nodes status poll requires an accepted server-list response", async () => {
|
||||
const writes = [];
|
||||
let reply;
|
||||
const index = fs.readFileSync(path.join(__dirname, "../index.js"), "utf8");
|
||||
const context = vm.createContext({
|
||||
buildNodeBaseUrl: () => "https://node.example.test",
|
||||
nodeUnderCloudflare: () => false,
|
||||
nodeAuthHeadersFor: () => ({}),
|
||||
NODE_POLL_TIMEOUT_MS: 1000,
|
||||
httpRequestJson: async () => reply,
|
||||
setCachedNodeStatus: async (_id, state) => writes.push(state.online),
|
||||
filterOwnedReportedServers: async (_node, servers) => servers,
|
||||
});
|
||||
vm.runInContext(extract("async function fetchNodeServerStatuses(", "async function pollAllNodes(", index), context);
|
||||
const node = { id: "node-one" };
|
||||
for (reply of [
|
||||
{ status: 0, json: null }, { status: 401, json: { error: "unauthorized" } },
|
||||
{ status: 502, json: null }, { status: 200, json: { ok: true } },
|
||||
{ status: 200, json: { ok: false, servers: [] } },
|
||||
]) {
|
||||
assert.equal((await context.fetchNodeServerStatuses(node)).online, false);
|
||||
}
|
||||
for (reply of [
|
||||
{ status: 200, json: { ok: true, servers: [] } }, { status: 200, json: { ok: true, servers: null } },
|
||||
{ status: 200, json: [] },
|
||||
]) {
|
||||
assert.equal((await context.fetchNodeServerStatuses(node)).online, true);
|
||||
}
|
||||
assert.deepEqual(writes, [false, false, false, false, false, true, true, true]);
|
||||
});
|
||||
|
||||
test("a change to a node's TLS or token retires its old status connection", async () => {
|
||||
const sockets = [];
|
||||
const status = [];
|
||||
const tlsAgent = {};
|
||||
class FakeWebSocket extends EventEmitter {
|
||||
static CONNECTING = 0;
|
||||
static OPEN = 1;
|
||||
readyState = FakeWebSocket.OPEN;
|
||||
constructor(url, options) {
|
||||
super();
|
||||
Object.assign(this, { url, options });
|
||||
sockets.push(this);
|
||||
}
|
||||
close() {
|
||||
this.readyState = 3;
|
||||
this.emit("close", 1000);
|
||||
}
|
||||
}
|
||||
const index = fs.readFileSync(path.join(__dirname, "../index.js"), "utf8");
|
||||
const context = vm.createContext({
|
||||
WS_RECONNECT_BASE_MS: 1000,
|
||||
getLazyWebSocket: () => FakeWebSocket,
|
||||
getNodeWsUrl: (node) => `${node.ssl_enabled ? "wss" : "ws"}://node.example/v1/ws`,
|
||||
nodeTlsAgent: (url) => url.startsWith("wss:") ? tlsAgent : undefined,
|
||||
setCachedNodeStatus: async (id, state) => status.push(state.online),
|
||||
filterOwnedReportedServers: async () => [],
|
||||
nodeSsrfGuard: { assertNodeUrlHostAllowed: () => null },
|
||||
markNodeServersOffline: () => assert.fail("retired socket emitted a close event"),
|
||||
isShuttingDown: false,
|
||||
console,
|
||||
});
|
||||
vm.runInContext(
|
||||
"const nodeWsConnections = new Map();\n" +
|
||||
extract("function connectNodeWebSocket(", "function scheduleReconnect(", index) +
|
||||
extract("function cleanupNodeWs(", "function cleanupAllNodeWs(", index),
|
||||
context,
|
||||
);
|
||||
const connect = (node) => context.connectNodeWebSocket({ id: "node-one", ...node });
|
||||
connect({ token: "previous" });
|
||||
connect({ token: "previous" });
|
||||
assert.equal(sockets.length, 1);
|
||||
connect({ token: "previous", ssl_enabled: true });
|
||||
connect({ token: "new", ssl_enabled: true });
|
||||
assert.deepEqual(sockets.map(socket => socket.url), ["ws://node.example/v1/ws", "wss://node.example/v1/ws", "wss://node.example/v1/ws"]);
|
||||
assert.equal(sockets[0].options.agent, undefined);
|
||||
assert.equal(sockets[2].options.agent, tlsAgent);
|
||||
assert.equal(sockets[2].options.headers.Authorization, "Bearer new");
|
||||
await sockets[0].listeners("message")[0](Buffer.from('{"type":"status","ok":true}'));
|
||||
await sockets[2].listeners("message")[0](Buffer.from('{"type":"status","ok":true}'));
|
||||
assert.deepEqual(status, [false, false, true]);
|
||||
});
|
||||
Reference in new issue
Block a user