Files
Kelx/tests/bot-store-confirm-guard.test.js
2026-11-30 16:32:37 +00:00

523 lines
22 KiB
JavaScript

"use strict";
// Behavioral regression tests for the Store panel's destructive-install race
// (finding 6): a double-click on a version row used to drive TWO concurrent
// destructive installs, through three compounding mechanisms:
//
// 1. storeConfirm attached each instance's OK/cancel handlers to the same
// singleton overlay, so one OK click resolved EVERY pending confirm;
// 2. the async version-row click handler had no re-entrancy guard;
// 3. submitStoreApplyRequest had no in-flight check, and every call
// refreshed its own one-time action token, so both POSTs passed
// server-side.
//
// The fixes pinned here: storeConfirm chains one dialog at a time (a single
// OK can only resolve the confirm whose handlers are attached), the row
// handler ignores re-entrant clicks while its operation runs, and the apply
// slot serializes all entry points through submitStoreApplyRequest.
//
// bot.js is a browser IIFE (DOM + fetch bound at module scope), so the whole
// file cannot load under Node. Instead these tests slice the REAL state
// declarations and function bodies out of bot.js by anchor windows — the same
// convention as bot-store-race-behavior.test.js — and evaluate them in a vm
// sandbox with a minimal DOM stub. Unlike that file, the confirm dialog and
// the submit path under test here are the genuine bot.js code, not stubs;
// only the DOM leaves, the token/POST boundary and the progress widgets are
// faked. If a function under test is renamed or moved, its anchor assertion
// fails loudly rather than testing a stale copy.
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const ROOT = path.join(__dirname, "..");
const BOT_JS = path.join(ROOT, "public", "js", "bot.js");
const botSrc = fs.readFileSync(BOT_JS, "utf8");
function sourceWindow(src, startAnchor, endAnchor, label) {
const start = src.indexOf(startAnchor);
assert.notStrictEqual(start, -1, `${label || "window"}: start anchor not found: ${startAnchor}`);
const end = src.indexOf(endAnchor, start + startAnchor.length);
assert.notStrictEqual(end, -1, `${label || "window"}: end anchor not found: ${endAnchor}`);
return src.slice(start, end);
}
function extractBotStoreCode() {
return [
// Module state + the panel claim (storeViewSeq/claimStorePanel).
sourceWindow(botSrc, "let currentStoreTab = 'versions';", "let papermcVersionsCache = null;", "store state"),
// The real, serialized confirm dialog (finding 6, mechanism 1).
sourceWindow(botSrc, "let _storeConfirmTail = Promise.resolve();", "const sio = window.io;", "storeConfirm"),
// The real apply slot + submitStoreApplyRequest (finding 6, mechanism 3).
sourceWindow(botSrc, "let _storeApplySlotBusy = false;", "async function changeNodeVersion(", "submit path"),
// changeNodeVersion/changeVersion/applyVersion (the entry points).
sourceWindow(botSrc, "async function changeNodeVersion(", "window.applyVersion = applyVersion;", "apply entry points"),
// The provider version view with the row click handlers (finding 6,
// mechanism 2) and the FiveM custom-version row.
sourceWindow(botSrc, "async function openProviderDetails(", "function renderPluginsPlaceholder() {", "openProviderDetails"),
// The provider fetch the version view consumes.
sourceWindow(botSrc, "async function fetchStoreProviders() {", "async function fetchPythonVersions() {", "fetchStoreProviders"),
].join("\n\n");
}
const PROLOGUE = `
"use strict";
const __h = globalThis.__h;
function __makeEl(tag) {
const el = {
tagName: tag,
children: [],
className: "",
textContent: "",
style: {},
type: "",
value: "",
placeholder: "",
disabled: false,
handlers: {},
dataset: {},
__classes: new Set(),
appendChild(child) { el.children.push(child); return child; },
addEventListener(type, fn) { (el.handlers[type] = el.handlers[type] || []).push(fn); },
removeEventListener(type, fn) {
const arr = el.handlers[type];
if (!arr) return;
const i = arr.indexOf(fn);
if (i >= 0) arr.splice(i, 1);
},
querySelector() { return __makeEl("div"); },
querySelectorAll() { return []; },
setAttribute() {},
removeAttribute() {},
getAttribute() { return null; },
classList: {
add(c) { el.__classes.add(c); },
remove(c) { el.__classes.delete(c); },
toggle() {},
contains(c) { return el.__classes.has(c); },
},
};
Object.defineProperty(el, "innerHTML", {
get() { return el.__innerHTML || ""; },
set(v) { el.__innerHTML = String(v); el.children.length = 0; },
});
return el;
}
const __els = new Map();
function __el(id) {
if (!__els.has(id)) __els.set(id, __makeEl("#" + id));
return __els.get(id);
}
globalThis.__el = __el;
const document = {
createElement: (tag) => __makeEl(tag),
createDocumentFragment: () => __makeEl("#fragment"),
getElementById: (id) => (__h.noDom ? null : __el(id)),
};
// window.confirm is the no-overlay fallback path; every overlay-driven
// confirm must leave it untouched.
const window = {
io: undefined,
confirm(msg) { __h.windowConfirms.push(String(msg)); return __h.confirm; },
};
const bot = "srv-test";
// Module-scope DOM binding the real openProviderDetails closes over.
const storeContent = __el("storeContent");
// --- widget/flow stubs (the DOM leaves around the code under test) -------
function setActiveStoreTab() {}
function resolveStoreTemplate() { return { template: __h.template }; }
function storeTemplateQuery() { return ""; }
function hasPerm() { return true; }
function showStoreToast(message, kind) { __h.toasts.push({ message: String(message), kind }); }
function storeBarStart() {}
function storeBarDone() {}
function showProgressWheel() {}
function scheduleProgressWheelHide() {}
function updateStoreVisibility() {}
function loadServerInfo() { return Promise.resolve().then(() => __h.loadServerInfoImpl()); }
function templateDisplayName() { return "Minecraft"; }
function normalizeTemplate(t) {
const raw = (t ?? "").toString().trim().toLowerCase();
if (!raw) return "";
if (["mc", "minecraft"].includes(raw)) return "minecraft";
if (["fivem"].includes(raw)) return "fivem";
return raw;
}
function escapeHtml(s) {
return String(s == null ? "" : s).replace(/[&<>"']/g, (c) => (
{ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]
));
}
// The token/POST boundary: recorded, never real network.
async function applyServerVersionWithActionToken(serverName, payload) {
__h.posts.push({ server: String(serverName), payload });
return __h.applyResponse();
}
async function fetch(url) {
__h.fetches.push(String(url));
return globalThis.__fetchImpl(String(url));
}
function fetchVanillaVersions() { return Promise.reject(new Error("unexpected vanilla resolver")); }
function fetchPapermcVersions() { return Promise.reject(new Error("unexpected paper resolver")); }
function fetchPurpurVersions() { return Promise.reject(new Error("unexpected purpur resolver")); }
function fetchVelocityVersions() { return Promise.reject(new Error("unexpected velocity resolver")); }
function fetchWaterfallVersions() { return Promise.reject(new Error("unexpected waterfall resolver")); }
function fetchFoliaVersions() { return Promise.reject(new Error("unexpected folia resolver")); }
function fetchLeavesVersions() { return Promise.reject(new Error("unexpected leaves resolver")); }
function fetchSpigotVersions() { return Promise.reject(new Error("unexpected spigot resolver")); }
`;
const EPILOGUE = `
globalThis.__snapDialog = () => {
const msgEl = __el("storeConfirmMsg");
const okBtn = __el("storeConfirmOk");
const overlay = __el("storeConfirmOverlay");
return {
message: msgEl.textContent,
okHandlers: (okBtn.handlers.click || []).length,
dialogVisible: overlay.__classes.has("show"),
};
};
`;
function makeHarness({ template = null } = {}) {
const hooks = {
template,
toasts: [],
posts: [],
fetches: [],
windowConfirms: [],
confirm: true,
noDom: false,
loadServerInfoImpl: async () => ({}),
applyResponse: () => ({ ok: true, status: 200, json: async () => ({ ok: true, message: "installed" }) }),
};
const sandbox = { setTimeout, clearTimeout, console };
sandbox.__h = hooks;
sandbox.__fetchImpl = () => Promise.reject(new Error("no route configured for this fetch"));
vm.createContext(sandbox);
vm.runInContext(PROLOGUE + "\n\n" + extractBotStoreCode() + "\n\n" + EPILOGUE, sandbox, {
timeout: 4000,
filename: "bot-store-guard-sandbox.js",
});
return { sandbox, hooks, el: (id) => sandbox.__el(id), snapDialog: () => sandbox.__snapDialog() };
}
// ---------------------------------------------------------------------------
// Node-side helpers
// ---------------------------------------------------------------------------
function makeRouter() {
const routes = [];
const impl = (url) => {
const route = routes.find(([match]) => match(url));
if (!route) return Promise.reject(new Error("unrouted fetch: " + url));
return route[1](url);
};
return {
impl,
on: (match, respond) => routes.push([match, respond]),
storeVersions: (id) => (u) => u.endsWith(`/api/servers/srv-test/versions/${id}`),
};
}
const okJson = (body) => ({ ok: true, status: 200, json: async () => body });
async function flush() {
for (let i = 0; i < 5; i += 1) await new Promise((resolve) => setImmediate(resolve));
}
function collectWhere(el, pred, out = []) {
if (!el || typeof el !== "object") return out;
if (pred(el)) out.push(el);
for (const child of el.children || []) collectWhere(child, pred, out);
return out;
}
const versionRows = (root) => collectWhere(root, (e) => e && e.className === "store-version-row");
async function openVanillaView(h, versionIds) {
const router = makeRouter();
h.sandbox.__fetchImpl = router.impl;
router.on(router.storeVersions("vanilla"), () => Promise.resolve(okJson({
versions: versionIds.map((id) => ({ id, name: id, label: id })),
})));
const view = h.sandbox.openProviderDetails({ id: "vanilla", name: "Vanilla" });
await flush();
await view;
return versionRows(h.el("storeContent"));
}
// ---------------------------------------------------------------------------
// Mechanism 1: storeConfirm serialization
// ---------------------------------------------------------------------------
test("two concurrent confirms: one OK click resolves exactly one, the second dialog follows", async () => {
const h = makeHarness();
const { sandbox } = h;
const first = sandbox.storeConfirm("first?");
const second = sandbox.storeConfirm("second?");
await flush();
// The old code attached BOTH instances' handlers to the singleton overlay,
// so a single OK resolved every pending confirm. Serialized, exactly one
// set of handlers is ever live.
assert.strictEqual(h.snapDialog().okHandlers, 1, "only one confirm may hold the overlay's OK button");
assert.strictEqual(h.snapDialog().message, "first?", "the first dialog shows first");
assert.strictEqual(h.snapDialog().dialogVisible, true);
const resolutions = [];
first.then((v) => resolutions.push(["first", v]));
second.then((v) => resolutions.push(["second", v]));
// One click on OK — the handler list is fired wholesale to prove that even
// a storm of clicks cannot resolve more than the active confirm.
for (const fn of [...h.el("storeConfirmOk").handlers.click]) fn();
await flush();
assert.deepStrictEqual(resolutions, [["first", true]], "one OK click must resolve exactly the first confirm");
// The queued dialog has already taken over the overlay by the time the
// microtask chain settles: the handler that exists now belongs to it.
assert.strictEqual(h.snapDialog().message, "second?", "the queued dialog shows only after the first settles");
assert.strictEqual(h.snapDialog().dialogVisible, true);
assert.strictEqual(h.snapDialog().okHandlers, 1, "exactly one handler is live for the second dialog");
for (const fn of [...h.el("storeConfirmOk").handlers.click]) fn();
await flush();
assert.deepStrictEqual(resolutions, [["first", true], ["second", true]]);
assert.strictEqual(h.snapDialog().dialogVisible, false, "no dialog remains after the last confirm settles");
assert.deepStrictEqual(h.hooks.windowConfirms, [], "the overlay path must never fall back to window.confirm");
});
test("storeConfirm falls back to window.confirm only when the overlay is missing", async () => {
const h = makeHarness();
const { sandbox } = h;
h.hooks.noDom = true;
const answer = await sandbox.storeConfirm("legacy?");
assert.strictEqual(answer, true);
assert.deepStrictEqual(h.hooks.windowConfirms, ["legacy?"], "the fallback must go through window.confirm");
});
// ---------------------------------------------------------------------------
// Mechanism 3: the apply slot in submitStoreApplyRequest
// ---------------------------------------------------------------------------
test("a second submit while the first is awaiting its confirm is refused, not queued", async () => {
const h = makeHarness();
const { sandbox } = h;
const first = sandbox.submitStoreApplyRequest(
{ providerId: "vanilla", versionId: "v1" },
{ confirmMessage: "Install v1?" }
);
await flush();
assert.strictEqual(h.snapDialog().dialogVisible, true, "the first submit opened its confirm");
await assert.rejects(
() => sandbox.submitStoreApplyRequest({ providerId: "vanilla", versionId: "v2" }, { confirmMessage: "Install v2?" }),
/already in progress/,
"the second submit must be refused while the first holds the slot"
);
assert.strictEqual(h.hooks.posts.length, 0, "no POST may leave before a confirm is answered");
for (const fn of [...h.el("storeConfirmOk").handlers.click]) fn();
const firstResult = await first;
await flush();
assert.strictEqual(h.hooks.posts.length, 1, "exactly one destructive POST");
assert.strictEqual(firstResult.ok, true);
// The slot must be released once the operation settles.
const third = sandbox.submitStoreApplyRequest(
{ providerId: "vanilla", versionId: "v3" },
{ confirmMessage: "Install v3?" }
);
await flush();
assert.strictEqual(h.snapDialog().dialogVisible, true, "a submit after the first settled must acquire the slot");
for (const fn of [...h.el("storeConfirmOk").handlers.click]) fn();
const thirdResult = await third;
await flush();
assert.strictEqual(h.hooks.posts.length, 2, "a submit after the first settled must work");
assert.strictEqual(thirdResult.ok, true);
});
test("cancelling a confirm returns {cancelled:true} and releases the slot", async () => {
const h = makeHarness();
const { sandbox } = h;
h.hooks.confirm = false; // only meaningful for the no-DOM path; the cancel below drives the real dialog
const first = sandbox.submitStoreApplyRequest(
{ providerId: "vanilla", versionId: "v1" },
{ confirmMessage: "Install v1?" }
);
await flush();
for (const fn of [...h.el("storeConfirmCancel").handlers.click]) fn();
const result = await first;
await flush();
// deepStrictEqual against a host-realm literal would compare realm
// prototypes; the shape is { cancelled: true } and nothing else.
assert.strictEqual(result.cancelled, true);
assert.deepStrictEqual(Object.keys(result).sort(), ["cancelled"]);
assert.strictEqual(h.hooks.posts.length, 0, "a cancelled confirm must never POST");
// The slot was released by the cancel path: the next submit acquires it.
const second = sandbox.submitStoreApplyRequest(
{ providerId: "vanilla", versionId: "v2" },
{ confirmMessage: "Install v2?" }
);
await flush();
assert.strictEqual(h.snapDialog().dialogVisible, true, "the follow-up submit must acquire the freed slot");
for (const fn of [...h.el("storeConfirmOk").handlers.click]) fn();
await second;
assert.strictEqual(h.hooks.posts.length, 1);
});
// ---------------------------------------------------------------------------
// Mechanism 2: the version-row re-entrancy guard, through the real handlers
// ---------------------------------------------------------------------------
test("a double-click on a version row produces exactly one destructive install", async () => {
const h = makeHarness();
const rows = await openVanillaView(h, ["vanilla-build-1"]);
assert.strictEqual(rows.length, 1, "the version list is painted");
// Two synchronous clicks — the double-click that used to start two installs.
rows[0].handlers.click[0]();
rows[0].handlers.click[0]();
await flush();
assert.strictEqual(h.snapDialog().dialogVisible, true, "the install confirm is open");
assert.strictEqual(h.hooks.posts.length, 0, "nothing has POSTed while the confirm is open");
assert.strictEqual(h.snapDialog().okHandlers, 1, "the second click may not attach a second confirm");
for (const fn of [...h.el("storeConfirmOk").handlers.click]) fn();
await flush();
assert.strictEqual(h.hooks.posts.length, 1, "one double-click must be exactly one install");
assert.strictEqual(h.hooks.posts[0].payload.providerId, "vanilla");
assert.strictEqual(h.hooks.posts[0].payload.versionId, "vanilla-build-1");
assert.ok(h.hooks.toasts.some((t) => t.kind !== "error" && /installed/i.test(t.message)), "the success toast shows");
assert.strictEqual(rows[0].dataset.installBusy, undefined, "the row guard releases once the operation settles");
// The row is usable again after the install completes.
rows[0].handlers.click[0]();
await flush();
assert.strictEqual(h.snapDialog().dialogVisible, true, "a later click opens a fresh confirm");
for (const fn of [...h.el("storeConfirmCancel").handlers.click]) fn();
await flush();
assert.strictEqual(h.hooks.posts.length, 1, "and the cancel path stays POST-free");
});
test("clicking a second row while the first install's confirm is open is refused with the busy error", async () => {
const h = makeHarness();
const rows = await openVanillaView(h, ["vanilla-build-1", "vanilla-build-2"]);
assert.strictEqual(rows.length, 2);
rows[0].handlers.click[0]();
await flush();
assert.strictEqual(h.snapDialog().dialogVisible, true);
rows[1].handlers.click[0]();
await flush();
assert.ok(
h.hooks.toasts.some((t) => t.kind === "error" && /already in progress/.test(t.message)),
"the second row's submit must surface the busy error"
);
assert.strictEqual(h.hooks.posts.length, 0, "still nothing POSTed");
for (const fn of [...h.el("storeConfirmOk").handlers.click]) fn();
await flush();
assert.strictEqual(h.hooks.posts.length, 1, "exactly one install ran");
assert.strictEqual(h.hooks.posts[0].payload.versionId, "vanilla-build-1", "and it is the first row's install");
});
test("a confirmed install whose POST settles releases both the row guard and the slot", async () => {
const h = makeHarness();
const rows = await openVanillaView(h, ["vanilla-build-1"]);
let releasePost;
const settledApplyResponse = () => ({ ok: true, status: 200, json: async () => ({ ok: true, message: "installed" }) });
let deferredUsed = false;
h.hooks.applyResponse = () => {
// Only the first POST hangs so the in-flight state can be asserted; every
// later POST settles immediately.
if (deferredUsed) return settledApplyResponse();
deferredUsed = true;
const d = new Promise((resolve) => { releasePost = resolve; });
return d.then(settledApplyResponse);
};
rows[0].handlers.click[0]();
await flush();
for (const fn of [...h.el("storeConfirmOk").handlers.click]) fn();
await flush();
assert.strictEqual(h.hooks.posts.length, 1);
// The POST is still pending: the row guard and the slot must both be held.
assert.strictEqual(rows[0].dataset.installBusy, "1", "the row stays guarded while its POST is in flight");
await assert.rejects(
() => h.sandbox.submitStoreApplyRequest({ providerId: "vanilla", versionId: "vX" }, { confirmMessage: "Install vX?" }),
/already in progress/,
"the slot is held until the POST settles"
);
releasePost();
await flush();
assert.strictEqual(rows[0].dataset.installBusy, undefined, "the guard releases when the POST settles");
const ok = await h.sandbox.submitStoreApplyRequest(
{ providerId: "vanilla", versionId: "vY" },
{ confirmMessage: "Install vY?", skipConfirm: true }
);
assert.strictEqual(ok.ok, true, "a skipConfirm submit after settlement succeeds");
});
// ---------------------------------------------------------------------------
// The FiveM custom-version path
// ---------------------------------------------------------------------------
test("the FiveM custom-version install button double-click stays a single install attempt", async () => {
const h = makeHarness();
const router = makeRouter();
h.sandbox.__fetchImpl = router.impl;
router.on(router.storeVersions("fivem"), () => Promise.resolve(okJson({
versions: [{ id: "25770", name: "25770", label: "FiveM 25770" }],
})));
const view = h.sandbox.openProviderDetails({ id: "fivem", name: "FiveM" });
await flush();
await view;
// The custom row is rendered even with zero versions; its Install button is
// the second double-clickable destructive entry point.
const customRows = collectWhere(h.el("storeContent"), (e) => e && /store-custom-version-row/.test(e.className || ""));
assert.strictEqual(customRows.length, 1, "the FiveM custom-version row is painted");
// Drive the real handler the way the row does: submitCustom is closed over,
// so exercise it through applyVersion exactly the way submitCustom calls
// it (applyVersion → submitStoreApplyRequest), with submitCustom's own
// .catch shape, and assert the slot layer serializes two rapid attempts.
const attempt = () => h.sandbox.applyVersion("fivem", "25770", "FiveM artifact 25770", null, { template: "fivem" })
.catch((err) => h.hooks.toasts.push({ message: String(err && err.message), kind: "error" }));
const a = attempt();
const b = attempt();
await flush();
assert.strictEqual(h.snapDialog().dialogVisible, true, "the fivem install confirm is open");
assert.ok(
h.hooks.toasts.some((t) => t.kind === "error" && /already in progress/.test(t.message)),
"the second rapid attempt is refused by the slot (surfaced through the row's catch)"
);
for (const fn of [...h.el("storeConfirmOk").handlers.click]) fn();
await a;
await b;
await flush();
assert.strictEqual(h.hooks.posts.length, 1, "exactly one fivem install POST");
});