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,621 @@
|
||||
"use strict";
|
||||
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const { EventEmitter } = require("node:events");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const vm = require("node:vm");
|
||||
const { getServerStatusRoom, getConsoleRoom, SERVER_STATUS_ROOM_PREFIX } = require("../utils/server-socket-rooms");
|
||||
|
||||
const root = path.join(__dirname, "..");
|
||||
const indexSource = fs.readFileSync(path.join(root, "index.js"), "utf8");
|
||||
const botSource = fs.readFileSync(path.join(root, "public", "js", "bot.js"), "utf8");
|
||||
const nodesSource = fs.readFileSync(path.join(root, "nodes.js"), "utf8");
|
||||
|
||||
function sourceWindow(source, startAnchor, endAnchor) {
|
||||
const start = source.indexOf(startAnchor);
|
||||
assert.ok(start >= 0, `missing ${startAnchor}`);
|
||||
const end = source.indexOf(endAnchor, start + startAnchor.length);
|
||||
assert.ok(end > start, `missing ${endAnchor}`);
|
||||
return source.slice(start, end);
|
||||
}
|
||||
|
||||
test("Console power requests deny out-of-scope targets before resolving the node", async () => {
|
||||
const sandbox = {
|
||||
checkServerAccess: async () => ({ ok: false, status: 403, error: "no access to server" }),
|
||||
remoteContext: () => assert.fail("denied power requests must not resolve a node"),
|
||||
};
|
||||
vm.runInNewContext(sourceWindow(nodesSource, "async function performPanelServerAction(", "// performPanelEulaAccept"), sandbox);
|
||||
for (const action of ["start", "stop", "kill", "restart", "status"]) {
|
||||
const result = await sandbox.performPanelServerAction({ session: { user: "fixture@example.invalid" } }, "fixture", action);
|
||||
assert.equal(result.status, 403, action);
|
||||
assert.equal(result.body.error, "no access to server", action);
|
||||
}
|
||||
});
|
||||
|
||||
test("shared Console history reset requires an administrator and an existing server", async () => {
|
||||
const route = sourceWindow(indexSource, 'app.post("/api/servers/:name/console-history/reset"', "// Cross-site read guard");
|
||||
let handler;
|
||||
let authenticated = false;
|
||||
let admin = false;
|
||||
let server = null;
|
||||
let lookups = 0;
|
||||
const resets = [];
|
||||
vm.runInNewContext(route, {
|
||||
app: { post: (_route, callback) => { handler = callback; } },
|
||||
isAuthenticated: async () => authenticated,
|
||||
isAdmin: async () => admin,
|
||||
findServer: async () => { lookups += 1; return server; },
|
||||
clearConsoleHistoryForServer: async (name) => { resets.push(name); return { resetAt: 123, nodeReset: { ok: true } }; },
|
||||
});
|
||||
const invoke = async () => {
|
||||
const res = { statusCode: 200, status(code) { this.statusCode = code; return this; }, json() {} };
|
||||
await handler({ params: { name: "fixture-alias" } }, res, (error) => { throw error; });
|
||||
return res.statusCode;
|
||||
};
|
||||
|
||||
assert.equal(await invoke(), 401);
|
||||
authenticated = true;
|
||||
assert.equal(await invoke(), 403);
|
||||
assert.equal(lookups, 0);
|
||||
assert.deepEqual(resets, []);
|
||||
admin = true;
|
||||
assert.equal(await invoke(), 404);
|
||||
assert.deepEqual(resets, []);
|
||||
server = { name: "fixture" };
|
||||
assert.equal(await invoke(), 200);
|
||||
assert.deepEqual(resets, ["fixture"]);
|
||||
});
|
||||
|
||||
test("Console history refuses a suspended server reached through an alias-only grant", async () => {
|
||||
const server = { name: "fixture", suspended: true };
|
||||
const handlers = {};
|
||||
const sandbox = {
|
||||
app: {
|
||||
get: (_route, _guard, handler) => { handlers.read = handler; },
|
||||
post: (_route, handler) => { handlers.record = handler; },
|
||||
},
|
||||
rejectCrossSiteRead() {},
|
||||
isAuthenticated: async () => true,
|
||||
findUserByEmail: async () => ({ admin: false }),
|
||||
userHasAccessToServer: async (_email, name) => name === "fixture-alias",
|
||||
findServer: async () => server,
|
||||
getEffectivePermsForUserOnServer: async (_email, name) => ({
|
||||
console_read: name === server.name, console_write: name === server.name,
|
||||
}),
|
||||
isServerSuspended: (entry) => entry.suspended,
|
||||
sendSuspendedServerJson: (res) => { res.statusCode = 423; },
|
||||
fetchConsoleServerState: () => assert.fail("must not read a suspended server's state"),
|
||||
getConsoleHistorySnapshot: () => assert.fail("must not read a suspended server's history"),
|
||||
rememberConsoleCommand: () => assert.fail("must not write a suspended server's history"),
|
||||
nodesRouter: {},
|
||||
isRemoteEntry: () => false,
|
||||
};
|
||||
vm.runInNewContext(sourceWindow(indexSource, 'app.get("/api/servers/:name/console-history"', 'io.on("connection"'), sandbox);
|
||||
vm.runInNewContext(sourceWindow(indexSource, 'app.post("/api/servers/:name/console-history/command"', 'app.post("/api/servers/:name/console-history/reset"'), sandbox);
|
||||
|
||||
const req = { params: { name: "fixture-alias" }, session: { user: "fixture@example.invalid" }, query: { clientResetAt: 123 }, body: { command: "fixture" } };
|
||||
for (const handler of Object.values(handlers)) {
|
||||
const res = { statusCode: 200 };
|
||||
await handler(req, res, (error) => { throw error; });
|
||||
assert.equal(res.statusCode, 423);
|
||||
}
|
||||
});
|
||||
|
||||
test("Console output stays bounded before and after a delayed render, including a single oversized line", () => {
|
||||
const rendered = { innerHTML: "", insertAdjacentHTML(_position, html) { this.innerHTML += html; } };
|
||||
const frames = [];
|
||||
const sandbox = {
|
||||
consoleEl: {}, consoleContentEl: rendered, clientClean: String, ansiToHtml: String,
|
||||
isNearBottom: () => false, suppressAutoScroll: false, hideConsoleSpinner() {}, updateJumpBtnVisibility() {},
|
||||
rememberRecentConsoleChunk() {}, rememberConsoleCommandRendered() {},
|
||||
requestAnimationFrame: (callback) => frames.push(callback),
|
||||
};
|
||||
vm.createContext(sandbox);
|
||||
vm.runInContext([
|
||||
sourceWindow(botSource, " const MAX_CONSOLE_CHARS", " function makeConsoleDedupeKey"),
|
||||
sourceWindow(botSource, " function formatConsoleHistoryCommand", " // Dedicated dedup"),
|
||||
sourceWindow(botSource, " function trimConsoleText", " async function fetchConsoleHistory"),
|
||||
].join("\n"), sandbox);
|
||||
const cap = vm.runInContext("MAX_CONSOLE_CHARS", sandbox);
|
||||
const flush = () => {
|
||||
assert.equal(frames.length, 1);
|
||||
assert.ok(vm.runInContext("_pendingConsoleText.length", sandbox) <= cap);
|
||||
frames.shift()();
|
||||
assert.ok(rendered.innerHTML.length <= cap);
|
||||
};
|
||||
|
||||
for (let index = 0; index < 5000; index++) {
|
||||
sandbox.appendToConsole(`Line ${index}: ${"Synthetic application output ".repeat(4)}\n`);
|
||||
}
|
||||
sandbox.appendConsoleCommandLine("fixture command");
|
||||
flush();
|
||||
assert.doesNotMatch(rendered.innerHTML, /^Line 0: /);
|
||||
assert.match(rendered.innerHTML, /Line 4999: /);
|
||||
assert.ok(rendered.innerHTML.endsWith("ADPANELCMD>> fixture command\n"));
|
||||
|
||||
sandbox.appendToConsole("next batch of log lines\n".repeat(4000));
|
||||
flush();
|
||||
assert.match(rendered.innerHTML, /Line 4999: /);
|
||||
assert.ok(rendered.innerHTML.endsWith("next batch of log lines\n"));
|
||||
|
||||
sandbox.appendToConsole("x".repeat(cap + 1000) + " last output\n");
|
||||
flush();
|
||||
assert.equal(rendered.innerHTML.length, cap);
|
||||
assert.ok(rendered.innerHTML.endsWith(" last output\n"));
|
||||
});
|
||||
|
||||
test("burst deduplication keeps only recent, bounded log fingerprints", () => {
|
||||
const sandbox = { ANSI_SGR_RE: /\x1b\[[0-9;]*m/g };
|
||||
vm.createContext(sandbox);
|
||||
vm.runInContext(sourceWindow(botSource, " const MAX_CONSOLE_CHARS", " function recentlySawConsoleLine"), sandbox);
|
||||
const burst = Array.from({ length: 700 }, (_, index) => `fixture log ${index}`).join("\n");
|
||||
sandbox.rememberRecentConsoleChunk(`${burst}\n${"x".repeat(5000)}`, 100);
|
||||
assert.equal(vm.runInContext("recentConsoleLineFingerprints.size", sandbox), 600);
|
||||
assert.equal(vm.runInContext("recentConsoleLineFingerprints.has('fixture log 699')", sandbox), true);
|
||||
sandbox.rememberRecentConsoleChunk("new log", 400);
|
||||
assert.equal(vm.runInContext("recentConsoleLineFingerprints.size", sandbox), 1);
|
||||
});
|
||||
|
||||
test("EULA consent resumes only a Start explicitly requested in that Console", async () => {
|
||||
const handlers = new Map();
|
||||
const classes = new Set();
|
||||
const modal = {
|
||||
style: {},
|
||||
classList: { add: (name) => classes.add(name), remove: (name) => classes.delete(name), contains: (name) => classes.has(name) },
|
||||
};
|
||||
const buttons = new Map(["eulaAccept", "eulaCancel"].map((id) => [id, {
|
||||
addEventListener: (_event, handler) => handlers.set(id, handler),
|
||||
}]));
|
||||
let starts = 0;
|
||||
const sandbox = {
|
||||
bot: "fixture", document: { getElementById: (id) => id === "eulaModal" ? modal : buttons.get(id) },
|
||||
hasPerm: () => true, isInstallingActive: false, powerState: "stopped", powerTransition: null,
|
||||
POWER_STATE: { INSTALLING: "installing" }, window: {}, consoleInstallingOverlay: null,
|
||||
isPowerActionAllowed: () => true, run: () => { starts += 1; },
|
||||
AbortSignal, CONSOLE_REQUEST_TIMEOUT_MS: 15_000,
|
||||
fetch: async () => ({ ok: true, json: async () => ({ ok: true }) }),
|
||||
requestAnimationFrame: (callback) => callback(), setTimeout: (callback) => callback(),
|
||||
toggleDock() {}, appendConsoleNotice() {}, alert: (message) => assert.fail(message),
|
||||
};
|
||||
vm.runInNewContext(sourceWindow(botSource, " const eulaModal =", " if (eulaCancelBtn)"), sandbox);
|
||||
const accept = handlers.get("eulaAccept");
|
||||
sandbox.maybeShowEulaPopup();
|
||||
await accept();
|
||||
assert.equal(starts, 0, "an automatic prompt must not start the server");
|
||||
|
||||
sandbox.maybeShowEulaPopup();
|
||||
sandbox.maybeShowEulaPopup({ resumeStart: true });
|
||||
await accept();
|
||||
assert.equal(starts, 1, "an explicit Start may resume after consent");
|
||||
|
||||
sandbox.maybeShowEulaPopup({ resumeStart: true });
|
||||
sandbox.cancelMinecraftEula();
|
||||
sandbox.maybeShowEulaPopup();
|
||||
await accept();
|
||||
assert.equal(starts, 1, "cancelling the prompt clears the pending Start intent");
|
||||
});
|
||||
|
||||
test("Console recall remains in the current page and discards legacy browser command records", () => {
|
||||
const bot = "fixture";
|
||||
const storage = new Map([
|
||||
[`adpanel:${bot}:command_history`, '["old command"]'],
|
||||
[`adpanel:${bot}:command_echo_history`, '[{"command":"old command"}]'],
|
||||
[`adpanel:${bot}:console_history_reset_at`, "123"],
|
||||
["adpanel:unrelated:preference", "keep"],
|
||||
]);
|
||||
const localStorage = {
|
||||
removeItem: (key) => storage.delete(key),
|
||||
getItem: () => assert.fail("legacy command text must not be read"),
|
||||
setItem: () => assert.fail("raw commands must not persist"),
|
||||
};
|
||||
const source = [
|
||||
sourceWindow(botSource, " const CONSOLE_COMMAND_HISTORY_LIMIT", " function normalizeConsoleCommandText"),
|
||||
sourceWindow(botSource, " function rememberConsoleCommandEcho", " // Stable ordering"),
|
||||
sourceWindow(botSource, " function rememberConsoleCommandForInput", " function isNearBottom"),
|
||||
].join("\n");
|
||||
const openPage = () => {
|
||||
const cmdInput = { value: "", setSelectionRange() {} };
|
||||
const sandbox = {
|
||||
bot, localStorage, cmdInput,
|
||||
normalizeConsoleCommandKey: (text) => String(text || "").trim(),
|
||||
rememberSubmittedConsoleCommand() {},
|
||||
};
|
||||
vm.runInNewContext(source, sandbox);
|
||||
return sandbox;
|
||||
};
|
||||
const firstPage = openPage();
|
||||
firstPage.rememberConsoleCommandForInput("fixture command");
|
||||
firstPage.rememberConsoleCommandEcho("fixture command", 123);
|
||||
firstPage.recallConsoleCommand(-1);
|
||||
assert.equal(firstPage.cmdInput.value, "fixture command");
|
||||
|
||||
const nextPage = openPage();
|
||||
nextPage.recallConsoleCommand(-1);
|
||||
assert.equal(nextPage.cmdInput.value, "");
|
||||
assert.deepEqual([...storage], [["adpanel:unrelated:preference", "keep"]]);
|
||||
});
|
||||
|
||||
test("Kill can interrupt an in-progress power transition but cannot be submitted twice", async () => {
|
||||
let finishKill;
|
||||
let requests = 0;
|
||||
const sandbox = {
|
||||
bot: "fixture", powerNodeOnline: true, isInstallingActive: false,
|
||||
POWER_STATE: { RUNNING: "running", STOPPED: "stopped", STARTING: "starting", STOPPING: "stopping" },
|
||||
powerState: "starting", killRequestInFlight: false, hasPerm: (permission) => permission === "server_stop",
|
||||
apiAction: () => { requests += 1; return new Promise((resolve) => { finishKill = resolve; }); },
|
||||
refreshPowerState: async () => {}, updatePowerControlsInteractivity() {},
|
||||
};
|
||||
sandbox.setPowerState = (state) => { sandbox.powerState = state; };
|
||||
vm.runInNewContext([
|
||||
sourceWindow(botSource, " function canRunNow()", " function updatePowerStatusLabel()"),
|
||||
sourceWindow(botSource, " function killServer()", " fileUploadModal.addEventListener"),
|
||||
].join("\n"), sandbox);
|
||||
assert.equal(sandbox.isPowerActionAllowed("stop"), false);
|
||||
assert.equal(sandbox.isPowerActionAllowed("kill"), true);
|
||||
sandbox.killServer();
|
||||
sandbox.killServer();
|
||||
assert.equal(requests, 1);
|
||||
finishKill();
|
||||
await new Promise(setImmediate);
|
||||
assert.equal(sandbox.isPowerActionAllowed("kill"), true);
|
||||
sandbox.hasPerm = () => false;
|
||||
assert.equal(sandbox.isPowerActionAllowed("kill"), false);
|
||||
});
|
||||
|
||||
test("power actions leave daemon history alone, including a refused Socket.IO Start", async () => {
|
||||
const server = { rowId: 1, name: "fixture", nodeId: "node", template: "minecraft", port: 25565 };
|
||||
const resets = [];
|
||||
let handler, observer;
|
||||
let nodeReply = { status: 409, json: { ok: false, code: "server_already_running" } };
|
||||
const sandbox = {
|
||||
socket: { on: (_event, callback) => { handler = callback; }, join() {} },
|
||||
nodesRouter: { setServerActionObserver: (callback) => { observer = callback; } },
|
||||
canAccessBot: () => true, hasPerm: async () => true,
|
||||
findServer: async () => server, isRemoteEntry: () => true, isServerSuspended: () => false,
|
||||
findNodeByIdOrName: async () => ({}), buildNodeBaseUrl: () => "http://fixture.invalid",
|
||||
nodeUnderCloudflare: () => false, nodeAuthHeadersFor: () => ({}), sanitizeNodeStorageName: (name) => name,
|
||||
getServerStatusRoom, getConsoleRoom, startRoomStatusWatcher() {}, tailLogsRemote() {},
|
||||
serverOpGuard: {
|
||||
getReinstallPowerConflict: () => null,
|
||||
withServerPowerStart: async (_deps, entry, dispatch) => ({ result: await dispatch(entry) }),
|
||||
},
|
||||
normalizeTemplateId: (id) => id, clampPort: (port) => port,
|
||||
httpRequestJson: async () => nodeReply, upsertServerStatusLabelUnlessGuarded: async () => {},
|
||||
clearConsoleHistoryForServer: async (name, options) => { resets.push([name, options.clearNode, options.emit]); },
|
||||
};
|
||||
vm.runInNewContext(sourceWindow(indexSource, ' socket.on("action"', ' socket.on("command"'), sandbox);
|
||||
vm.runInNewContext(sourceWindow(indexSource, 'if (typeof nodesRouter.setServerActionObserver', 'function rememberConsoleLine'), sandbox);
|
||||
const run = () => new Promise((resolve) => handler({ bot: "fixture", cmd: "run" }, resolve));
|
||||
|
||||
assert.equal((await run()).code, "server_already_running");
|
||||
assert.deepEqual(resets, []);
|
||||
nodeReply = { status: 200, json: { ok: true } };
|
||||
assert.equal((await run()).ok, true);
|
||||
await observer({ serverName: "fixture", action: "start" });
|
||||
assert.deepEqual(resets, [["fixture", false, false], ["fixture", false, false]]);
|
||||
});
|
||||
|
||||
test("invalid or unauthorized Socket.IO power actions have no shared side effects", async () => {
|
||||
let handler, allowed;
|
||||
const effects = [];
|
||||
const sandbox = {
|
||||
socket: { on: (_event, callback) => { handler = callback; }, join() { effects.push("room join"); } },
|
||||
canAccessBot: () => true, hasPerm: async (_server, permission) => allowed.has(permission), deny() {},
|
||||
findServer: async () => ({ name: "fixture", nodeId: "node" }),
|
||||
isRemoteEntry: () => true, isServerSuspended: () => false,
|
||||
findNodeByIdOrName: async () => { effects.push("node lookup"); return null; },
|
||||
_emitLine: () => effects.push("shared output"),
|
||||
};
|
||||
vm.runInNewContext(sourceWindow(indexSource, ' socket.on("action"', ' socket.on("command"'), sandbox);
|
||||
|
||||
for (const [cmd, grants, error] of [
|
||||
["unsupported", [], "unknown_cmd"],
|
||||
["run", [], "permission_denied"],
|
||||
["stop", [], "permission_denied"],
|
||||
["kill", [], "permission_denied"],
|
||||
["restart", ["server_start"], "permission_denied"],
|
||||
["restart", ["server_stop"], "permission_denied"],
|
||||
]) {
|
||||
allowed = new Set(["console_read", ...grants]);
|
||||
let reply;
|
||||
await handler({ bot: "fixture", cmd }, (result) => { reply = result; });
|
||||
assert.equal(reply.error, error, cmd);
|
||||
assert.deepEqual(effects, [], cmd);
|
||||
}
|
||||
});
|
||||
|
||||
test("Socket.IO command validation errors stay private to the sender", async () => {
|
||||
let handler;
|
||||
const sandbox = {
|
||||
socket: { on: (_event, callback) => { handler = callback; } },
|
||||
nodesRouter: { sanitizeConsoleCommand: () => ({
|
||||
ok: false, error: "invalid_command", detail: "Invalid console command.",
|
||||
}) },
|
||||
canAccessBot: () => false,
|
||||
_emitLine: () => assert.fail("private validation errors must not enter shared console history"),
|
||||
};
|
||||
vm.runInNewContext(sourceWindow(indexSource, ' socket.on("command"', "\n});\n\nlet httpsServer"), sandbox);
|
||||
|
||||
let reply;
|
||||
await handler({ bot: "fixture" }, (result) => { reply = result; });
|
||||
assert.equal(reply.ok, false);
|
||||
assert.equal(reply.detail, "Invalid console command.");
|
||||
});
|
||||
|
||||
test("an unconfirmed command never carries queued commands into a later submission", async () => {
|
||||
const commandQueue = [{ cmd: "first" }, { cmd: "unsent" }];
|
||||
const requests = [], notices = [];
|
||||
const sandbox = {
|
||||
commandQueue, commandQueueRunning: false, commandSendInFlight: true,
|
||||
lastCommandRequestId: null, setCommandSendingState() {}, console: { warn() {} },
|
||||
apiCommand: async (cmd) => {
|
||||
requests.push(cmd);
|
||||
if (cmd === "first") throw new Error("No reply");
|
||||
},
|
||||
appendConsoleNotice: (message) => { notices.push(message); },
|
||||
};
|
||||
vm.runInNewContext(sourceWindow(botSource, " async function drainCommandQueue()", " async function sendCommand()"), sandbox);
|
||||
await sandbox.drainCommandQueue();
|
||||
assert.equal(commandQueue.length, 0);
|
||||
assert.match(notices[0], /Unsent commands discarded: 1/);
|
||||
commandQueue.push({ cmd: "new submission" });
|
||||
await sandbox.drainCommandQueue();
|
||||
assert.deepEqual(requests, ["first", "new submission"]);
|
||||
});
|
||||
|
||||
test("remote command fallback has one bounded request and requires confirmation", async () => {
|
||||
const requests = [];
|
||||
const signal = {};
|
||||
let payload = null;
|
||||
const sandbox = {
|
||||
bot: "fixture", NODE_API_BASE: "/api/nodes/server/fixture", REMOTE_MODE: true,
|
||||
socket: { connected: false },
|
||||
AbortSignal: { timeout: (ms) => { assert.equal(ms, 25_000); return signal; } },
|
||||
scheduleConsoleHistoryResync() {},
|
||||
fetch: async (url, options) => {
|
||||
requests.push(url);
|
||||
assert.equal(options.signal, signal);
|
||||
return { ok: true, json: async () => payload };
|
||||
},
|
||||
};
|
||||
vm.runInNewContext(sourceWindow(botSource, " async function apiCommand(", " let IS_ADMIN"), sandbox);
|
||||
await assert.rejects(sandbox.apiCommand("fixture command"), /delivery was not confirmed/);
|
||||
payload = { ok: true };
|
||||
assert.equal(await sandbox.apiCommand("fixture command"), true);
|
||||
assert.deepEqual(requests, Array(2).fill("/api/nodes/server/fixture/command"));
|
||||
});
|
||||
|
||||
test("Console status joins and revokes in the server namespace, separate from admin monitoring", async () => {
|
||||
const serverName = "monitor";
|
||||
const rooms = new Set(["socket-id"]);
|
||||
const watcherStarts = [];
|
||||
const handlers = new Map();
|
||||
const socket = {
|
||||
id: "socket-id", rooms,
|
||||
on: (event, handler) => handlers.set(event, handler),
|
||||
join: async (room) => rooms.add(room),
|
||||
leave: async (room) => rooms.delete(room),
|
||||
emit() {},
|
||||
};
|
||||
const sandbox = {
|
||||
socket, isAdminUser: false, accessSet: new Set([serverName]),
|
||||
getServerStatusRoom, getConsoleRoom, SERVER_STATUS_ROOM_PREFIX,
|
||||
findServer: async () => ({ name: serverName, nodeId: "fixture-node" }),
|
||||
isServerSuspended: () => false, isRemoteEntry: () => true,
|
||||
hasPerm: async () => false, panel() {},
|
||||
findNodeByIdOrName: async () => ({}), buildNodeBaseUrl: () => "http://fixture.invalid",
|
||||
nodeUnderCloudflare: () => false, nodeAuthHeadersFor: () => ({}), sanitizeNodeStorageName: String,
|
||||
startRoomStatusWatcher: (name) => watcherStarts.push(name),
|
||||
tailLogsRemote: () => assert.fail("Console read permission is required to tail logs"),
|
||||
getResourceRoom: (name) => `res:${name}`, dashboardWatchers: new Map(),
|
||||
};
|
||||
sandbox.canAccessBot = (name) => sandbox.accessSet.has(name);
|
||||
vm.runInNewContext(sourceWindow(indexSource, ' socket.on("join"', ' socket.on("dashboard:watch"'), sandbox);
|
||||
vm.runInNewContext(sourceWindow(indexSource, " socket._updateAccessSet =", " function deny("), sandbox);
|
||||
|
||||
await handlers.get("join")(serverName);
|
||||
assert.deepEqual(watcherStarts, [serverName]);
|
||||
assert.deepEqual([...rooms], ["socket-id", "server-status:monitor"]);
|
||||
await socket._updateAccessSet(new Set(), false);
|
||||
assert.deepEqual([...rooms], ["socket-id"]);
|
||||
});
|
||||
|
||||
test("Socket.IO Console subscriptions stop on server suspension, also for admins", async () => {
|
||||
const refresh = sourceWindow(indexSource, " socket._updateAccessSet =", " function deny(");
|
||||
for (const admin of [false, true]) {
|
||||
const rooms = new Set(["socket-id", "console:fixture"]);
|
||||
const server = { suspended: false };
|
||||
const socket = { id: "socket-id", rooms, leave: async (room) => rooms.delete(room), emit() {} };
|
||||
vm.runInNewContext(refresh, {
|
||||
socket, isAdminUser: false, accessSet: new Set(), canAccessBot: () => true,
|
||||
withTimeout: (promise) => promise, findServer: async () => server,
|
||||
isServerSuspended: (entry) => entry.suspended, hasPerm: async () => true,
|
||||
dashboardWatchers: new Map(),
|
||||
});
|
||||
await socket._updateAccessSet(new Set(["fixture"]), admin);
|
||||
assert.equal(rooms.has("console:fixture"), true);
|
||||
server.suspended = true;
|
||||
await socket._updateAccessSet(new Set(["fixture"]), admin);
|
||||
assert.equal(rooms.has("console:fixture"), false);
|
||||
}
|
||||
});
|
||||
|
||||
test("a terminal EventSource error restores Socket.IO logs without disabling native reconnects", () => {
|
||||
class EventSource {
|
||||
static CLOSED = 2;
|
||||
constructor() { this.readyState = 0; }
|
||||
addEventListener() {}
|
||||
close() { this.readyState = EventSource.CLOSED; }
|
||||
}
|
||||
const joins = [];
|
||||
const sandbox = {
|
||||
bot: "fixture", REMOTE_MODE: true, NODE_API_BASE: "/fixture", URLSearchParams, EventSource,
|
||||
hasConsoleReadAccess: () => true,
|
||||
socket: { connected: true, emit: (...args) => joins.push(args) },
|
||||
};
|
||||
const transport = sourceWindow(botSource, " function ensureSocketConsoleJoin()", " // Use 'pagehide'");
|
||||
vm.runInNewContext("let logSource = null, activeRemoteLogUrl = '', remoteLogTransport = 'none';\n" + transport, sandbox);
|
||||
sandbox.attachLogStreamIfRemote();
|
||||
const current = vm.runInNewContext("logSource", sandbox);
|
||||
current.onerror();
|
||||
assert.equal(vm.runInNewContext("remoteLogTransport", sandbox), "eventsource");
|
||||
assert.deepEqual(joins, []);
|
||||
|
||||
current.readyState = EventSource.CLOSED;
|
||||
current.onerror();
|
||||
assert.equal(vm.runInNewContext("logSource", sandbox), null);
|
||||
assert.equal(vm.runInNewContext("remoteLogTransport", sandbox), "socket");
|
||||
assert.deepEqual(joins, [["join", "fixture"]]);
|
||||
});
|
||||
|
||||
test("a healthy status watcher restores a dropped log tail only for live Console readers", async () => {
|
||||
const watcherTicks = [];
|
||||
const dialNames = [];
|
||||
let logReaders = 0;
|
||||
let status = 200;
|
||||
const sandbox = {
|
||||
getServerStatusRoom,
|
||||
getRoomClientCount: (room) => Number(room === "server-status:fixture-alias"),
|
||||
getConsoleRoomClientCount: () => logReaders,
|
||||
stopTailLogsRemote() {},
|
||||
tailLogsRemote: (_room, _url, _headers, { dialName }) => dialNames.push(dialName),
|
||||
httpRequestJson: async () => ({ status, json: { status: "running" } }),
|
||||
normalizeStatusLabel: String, emitPanel() {},
|
||||
setInterval: (callback) => watcherTicks.push(callback),
|
||||
io: { to: () => ({ emit() {} }) },
|
||||
};
|
||||
vm.runInNewContext([
|
||||
sourceWindow(indexSource, "const ROOM_STATUS_INTERVAL_MS", "function getRoomClientCount"),
|
||||
sourceWindow(indexSource, "function startRoomStatusWatcher", "const LIVE_STATUS_TTL_MS"),
|
||||
].join("\n"), sandbox);
|
||||
sandbox.startRoomStatusWatcher("fixture-alias", "http://fixture.invalid", {}, "fixture-canonical");
|
||||
await new Promise(setImmediate);
|
||||
assert.deepEqual(dialNames, []);
|
||||
|
||||
logReaders = 1;
|
||||
status = 404;
|
||||
watcherTicks[0]();
|
||||
await new Promise(setImmediate);
|
||||
assert.deepEqual(dialNames, []);
|
||||
|
||||
status = 200;
|
||||
watcherTicks[0]();
|
||||
await new Promise(setImmediate);
|
||||
assert.deepEqual(dialNames, ["fixture-canonical"]);
|
||||
});
|
||||
|
||||
test("a failed node log tail is released before the watcher reconnects", async () => {
|
||||
const req = new EventEmitter();
|
||||
let destroyed = false;
|
||||
req.destroy = () => { destroyed = true; };
|
||||
const response = Object.assign(new EventEmitter(), { statusCode: 502, destroy() { destroyed = true; } });
|
||||
const remoteLogClients = Object.create(null);
|
||||
let readHeaders;
|
||||
const sandbox = {
|
||||
openNodeConsoleLogStream: (_url, _headers, onRequest) => {
|
||||
onRequest(req);
|
||||
return new Promise((resolve, reject) => { readHeaders = { resolve, reject }; });
|
||||
},
|
||||
remoteLogClients,
|
||||
};
|
||||
vm.runInNewContext(sourceWindow(indexSource, "function tailLogsRemote(", "function getConsoleRoomClientCount("), sandbox);
|
||||
|
||||
sandbox.tailLogsRemote("fixture", "http://fixture.invalid", {});
|
||||
assert.equal(remoteLogClients.fixture, req);
|
||||
readHeaders.reject(new Error("fixture header timeout"));
|
||||
await new Promise(setImmediate);
|
||||
assert.equal(destroyed, true);
|
||||
assert.equal(remoteLogClients.fixture, undefined);
|
||||
|
||||
destroyed = false;
|
||||
sandbox.tailLogsRemote("fixture", "http://fixture.invalid", {});
|
||||
readHeaders.resolve({ req, res: response });
|
||||
await new Promise(setImmediate);
|
||||
response.emit("aborted");
|
||||
assert.doesNotThrow(() => response.emit("error", new Error("truncated response")));
|
||||
assert.equal(destroyed, true);
|
||||
assert.equal(remoteLogClients.fixture, undefined);
|
||||
|
||||
sandbox.tailLogsRemote("fixture", "http://fixture.invalid", {});
|
||||
readHeaders.resolve({ req, res: Object.assign(response, { statusCode: 200, destroyed: true }) });
|
||||
await new Promise(setImmediate);
|
||||
assert.equal(remoteLogClients.fixture, undefined);
|
||||
});
|
||||
|
||||
test("Console socket mutations are refused while disconnected and use the Socket.IO ack deadline", async () => {
|
||||
let sends = 0;
|
||||
const socket = {
|
||||
connected: false,
|
||||
timeout(ms) { assert.equal(ms, 25_000); return this; },
|
||||
emit(_event, _body, ack) { sends += 1; ack(new Error("no ack")); },
|
||||
};
|
||||
const sandbox = { socket, createServerActionError: (code, message) => Object.assign(new Error(message), { code }) };
|
||||
vm.runInNewContext(sourceWindow(botSource, " function socketRequest(", " async function requestSocketServerAction("), sandbox);
|
||||
await assert.rejects(sandbox.socketRequest("command", {}, 25_000), { code: "socket_unavailable" });
|
||||
assert.equal(sends, 0);
|
||||
socket.connected = true;
|
||||
await assert.rejects(sandbox.socketRequest("command", {}, 25_000), { code: "timeout" });
|
||||
assert.equal(sends, 1);
|
||||
});
|
||||
|
||||
test("Socket.IO power actions allow the relay deadline and do not retry an unconfirmed result", async () => {
|
||||
const calls = [];
|
||||
const sandbox = {
|
||||
normalizeAiServerNameCandidate: (name) => name,
|
||||
normalizeServerPowerAction: (action) => action,
|
||||
createServerActionError: (code, message) => Object.assign(new Error(message), { code }),
|
||||
socketRequest: async (event, body, timeout) => {
|
||||
calls.push([event, body.cmd, timeout]);
|
||||
throw Object.assign(new Error("No reply"), { code: "timeout" });
|
||||
},
|
||||
};
|
||||
vm.runInNewContext(sourceWindow(botSource, " async function requestSocketServerAction(", " async function requestHttpServerAction("), sandbox);
|
||||
await assert.rejects(sandbox.requestSocketServerAction("fixture", "kill"), { code: "server_action_result_unconfirmed" });
|
||||
assert.deepEqual(calls, [["action", "kill", 25_000]]);
|
||||
});
|
||||
|
||||
test("a history response started before Clear cannot repaint that Console view", async () => {
|
||||
let resolveFetch;
|
||||
const sandbox = {
|
||||
bot: "fixture", URLSearchParams, consoleBufferGeneration: 0, consoleHistoryResetAt: 0,
|
||||
AbortSignal, CONSOLE_REQUEST_TIMEOUT_MS: 15_000,
|
||||
fetch: () => new Promise((resolve) => { resolveFetch = resolve; }),
|
||||
applyConsoleHistoryReset: () => assert.fail("old history must not change the current Console"),
|
||||
};
|
||||
vm.runInNewContext(sourceWindow(botSource, " async function fetchConsoleHistory(", " async function hydrateInitialConsoleHistory("), sandbox);
|
||||
const result = sandbox.fetchConsoleHistory();
|
||||
sandbox.consoleBufferGeneration += 1;
|
||||
resolveFetch({ ok: true, json: async () => ({ ok: true, resetAt: 123, lines: [{ line: "old output" }] }) });
|
||||
assert.equal((await result).length, 0);
|
||||
});
|
||||
|
||||
test("Console history and power state stop waiting when the request deadline aborts the body", async () => {
|
||||
const deadline = new AbortController();
|
||||
const signal = deadline.signal;
|
||||
const readers = [];
|
||||
const sandbox = {
|
||||
bot: "fixture", URLSearchParams, consoleBufferGeneration: 0,
|
||||
CONSOLE_REQUEST_TIMEOUT_MS: 15_000, AbortSignal: { timeout(ms) { assert.equal(ms, 15_000); return signal; } },
|
||||
fetch: async (_url, options) => {
|
||||
assert.equal(options.signal, signal);
|
||||
return { ok: true, json: () => new Promise((_, reject) => {
|
||||
readers.push(reject);
|
||||
if (signal.aborted) reject(signal.reason);
|
||||
else signal.addEventListener("abort", () => reject(signal.reason), { once: true });
|
||||
}) };
|
||||
},
|
||||
updateOfflineState() {},
|
||||
};
|
||||
vm.runInNewContext([
|
||||
sourceWindow(botSource, " async function fetchPowerSnapshot()", " function nextPowerPollDelay()"),
|
||||
sourceWindow(botSource, " async function fetchConsoleHistory(", " async function hydrateInitialConsoleHistory("),
|
||||
].join("\n"), sandbox);
|
||||
const history = sandbox.fetchConsoleHistory();
|
||||
const state = sandbox.fetchPowerSnapshot();
|
||||
await new Promise(setImmediate);
|
||||
assert.equal(readers.length, 2);
|
||||
deadline.abort(new Error("fixture deadline"));
|
||||
await Promise.all([assert.rejects(history, /history_http/), assert.rejects(state, /fixture deadline/)]);
|
||||
});
|
||||
Reference in new issue
Block a user