"use strict"; // Source-level pin for adpanel:scheduler-action-perm-mirror in bot.js. // // The scheduler create route enforces PER-ACTION permissions server-side // (index.js schedulerRequiredPermissionForAction, applied at create time by // POST /api/scheduler/:serverName/tasks: a subuser holding scheduler_create // but not, say, console_write could fill the whole form and only learn on // submit from a 403 "no permission to schedule console_command actions"). // The client already holds every key that map needs in the /permissions // payload (PERMS via fetchPerms — console_write, server_start, server_stop, // files_create, files_write, backups_create, planner_access, // scheduler_access), so the form must mirror the contract: options whose // mapped perm the user lacks are hidden from the action dropdown, a // selection knocked out by a perm change falls back to the first allowed // action (running the existing config-update path), and a user who holds NO // action's perm sees an inline warning while the form stays non-submittable // via createSchedulerTask's existing actionType guard — no fake action is // invented. The server check stays authoritative; this is UI truthfulness // only, and the pre-existing agent-access / planner_access gating composes // unchanged on top (planner_next_to_agent needs BOTH planner_access per the // map and agent access per the long-standing alert). // // bot.js is one IIFE with structure-pin precedent (the bot-*.test.js files // read the source and assert on well-anchored windows) — never require() it. const test = require("node:test"); const assert = require("node:assert"); const fs = require("node:fs"); const path = require("node:path"); const ROOT = path.join(__dirname, ".."); const BOT_JS = path.join(ROOT, "public", "js", "bot.js"); const INDEX_JS = path.join(ROOT, "index.js"); const BOT_EJS = path.join(ROOT, "views", "bot.ejs"); const botSrc = fs.readFileSync(BOT_JS, "utf8"); const indexSrc = fs.readFileSync(INDEX_JS, "utf8"); const ejsSrc = fs.readFileSync(BOT_EJS, "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); } // Parse the SERVER's authoritative map (index.js schedulerRequiredPermissionForAction) // and the CLIENT's mirror (bot.js SCHEDULER_ACTION_REQUIRED_PERM) and demand // exact parity — the two cannot be allowed to drift. function parseServerActionPermMap(src) { const fnAt = src.indexOf("function schedulerRequiredPermissionForAction(actionType) {"); assert.notStrictEqual(fnAt, -1, "server map function not found in index.js"); const body = src.slice(fnAt, src.indexOf("}", fnAt)); const map = {}; for (const m of body.matchAll(/case\s+"([a-z_]+)":\s*return\s+"([a-z_]+)";/g)) { map[m[1]] = m[2]; } return map; } function parseClientActionPermMap(src) { const start = src.indexOf("const SCHEDULER_ACTION_REQUIRED_PERM = {"); assert.notStrictEqual(start, -1, "client mirror map not found in bot.js"); const body = src.slice(start, src.indexOf("};", start)); const map = {}; for (const m of body.matchAll(/([a-z_]+):\s*'([a-z_]+)'/g)) { map[m[1]] = m[2]; } return map; } const gatingWindow = sourceWindow( botSrc, "function applySchedulerActionPermGating() {", "function openSchedulerModal() {", "applySchedulerActionPermGating" ); // The mirror map plus its constraint comment (the tag lives on the map, which // the gating function consumes — both must stay together). const mirrorWindow = sourceWindow( botSrc, "// adpanel:scheduler-action-perm-mirror", "function openSchedulerModal() {", "scheduler action perm mirror map" ); const openModalWindow = sourceWindow( botSrc, "function openSchedulerModal() {", "function closeSchedulerModal() {", "openSchedulerModal" ); const updateConfigWindow = sourceWindow( botSrc, "function updateActionConfig() {", "async function checkSchedulerStatus() {", "updateActionConfig" ); const createWindow = sourceWindow( botSrc, "async function createSchedulerTask() {", "function resetSchedulerForm() {", "createSchedulerTask" ); const syncWindow = sourceWindow( botSrc, "function syncCustomSelectOptions(selectId) {", "function bindUiActions() {", "syncCustomSelectOptions" ); test("the client mirror map is byte-for-byte the server's schedulerRequiredPermissionForAction", () => { const serverMap = parseServerActionPermMap(indexSrc); const clientMap = parseClientActionPermMap(botSrc); assert.deepStrictEqual( Object.keys(clientMap).sort(), Object.keys(serverMap).sort(), "the client mirror must cover exactly the server map's actions" ); for (const [action, perm] of Object.entries(serverMap)) { assert.strictEqual( clientMap[action], perm, `action ${action} must require ${perm} client-side exactly as the server enforces` ); } // The payload keys the mirror consumes actually reach the client: the // server's effective-perms projection (/permissions payload) carries every // mapped perm — including files_write, which is payload-delivered via // fetchPerms' Object.assign rather than seeded in the client default — and // bot.js merges that payload into PERMS, which hasPerm reads (admins pass // inside hasPerm). const permsTemplateAt = indexSrc.indexOf("const permsTemplate = {"); assert.notStrictEqual(permsTemplateAt, -1, "server effective-perms template not found"); const permsTemplate = indexSrc.slice(permsTemplateAt, indexSrc.indexOf("};", permsTemplateAt)); assert.ok( botSrc.includes("PERMS = Object.assign(PERMS, j.perms);"), "fetchPerms must merge the /permissions payload into PERMS" ); for (const perm of Object.values(serverMap)) { assert.ok( new RegExp(`\\b${perm}:\\s*false`).test(permsTemplate), `perm ${perm} must be carried by the /permissions payload's perms projection` ); } }); test("each action-type option is hidden by its mapped perm and kept out of the custom dropdown", () => { assert.ok( mirrorWindow.includes("adpanel:scheduler-action-perm-mirror"), "the constraint comment must travel with the mirror map and gating" ); assert.ok( mirrorWindow.includes("keep both maps in lockstep"), "the mirror must document its lockstep obligation to the server map" ); // The gate iterates the REAL option list and skips only the placeholder — // every value-bearing option is evaluated, none is exempt. assert.ok( gatingWindow.includes("Array.from(schedulerActionType.options).forEach"), "the gate must walk the action select's options" ); assert.ok( gatingWindow.includes("if (!opt.value) return;"), "only the value-less placeholder may skip the gate" ); assert.ok( gatingWindow.includes("hasPerm(required)"), "availability must be decided through hasPerm against the mapped perm" ); assert.ok( gatingWindow.includes("opt.hidden = !allowed;"), "a disallowed option must be marked hidden (the hide mechanism)" ); assert.ok( gatingWindow.includes("syncCustomSelectOptions('schedulerActionType');"), "the custom dropdown must be rebuilt after re-marking options" ); // The dropdown renderer must honor opt.hidden, or the custom list would // still offer 403-bound actions the native (display:none) select hides. const buildAt = syncWindow.indexOf("// Build new options"); assert.notStrictEqual(buildAt, -1, "syncCustomSelectOptions' build loop is missing"); const buildBody = syncWindow.slice(buildAt); assert.ok( buildBody.includes("if (opt.hidden) return;"), "syncCustomSelectOptions must skip hidden options when building the dropdown" ); assert.ok( buildBody.indexOf("if (opt.hidden) return;") > buildBody.indexOf("if (opt.disabled && !opt.value) return;"), "the hidden skip must sit alongside the existing disabled-placeholder skip" ); }); test("Agent Scheduler actions require an Agent grant in addition to Scheduler and Planner permissions", () => { const options = ["", "console_command", "planner_next_to_agent", "agent_prompt"].map((value) => ({ value })); const schedulerActionType = { options, value: "agent_prompt" }; options[3].selected = true; let entitled = false; const applyGating = require("node:vm").runInNewContext(`(${gatingWindow.trim()})`, { schedulerActionType, SCHEDULER_ACTION_REQUIRED_PERM: parseClientActionPermMap(botSrc), document: { getElementById: () => null }, hasPerm: () => true, hasAgentAccess: () => entitled, syncCustomSelectOptions() {}, }); assert.equal(applyGating(), true); assert.equal(schedulerActionType.value, "console_command"); assert.deepEqual(options.slice(1).map((option) => option.hidden), [false, true, true]); entitled = true; assert.equal(applyGating(), false); assert.deepEqual(options.slice(1).map((option) => option.hidden), [false, false, false]); }); test("an unavailable selected action falls back to the first ALLOWED action via the existing config-update path", () => { // The fallback targets the first non-hidden value-bearing option — DOM // order — never an invented value. assert.ok( gatingWindow.includes("Array.from(schedulerActionType.options).find(opt => opt.value && !opt.hidden)"), "the fallback must pick the first allowed option in DOM order" ); assert.ok( gatingWindow.includes("schedulerActionType.value = firstAllowed ? firstAllowed.value : '';"), "the fallback must assign an EXISTING option's value (or empty when none is allowed)" ); assert.ok( gatingWindow.includes("if (!selectionUnavailable) return false;"), "the gate must only rebase when the current selection actually became unavailable" ); // Modal open re-derives and, on a rebase, runs the existing config-update // path so the shown config section matches the effective action. assert.ok( openModalWindow.includes("if (applySchedulerActionPermGating()) {") && openModalWindow.includes("updateActionConfig();"), "openSchedulerModal must re-derive the gating and run updateActionConfig on a rebase" ); // Every change event re-derives too, BEFORE the value is read, so the // branch chain below always runs on the effective (possibly rebased) value. const gateAt = updateConfigWindow.indexOf("applySchedulerActionPermGating();"); const readAt = updateConfigWindow.indexOf("const action = schedulerActionType?.value;"); assert.notStrictEqual(gateAt, -1, "updateActionConfig must call the gating"); assert.notStrictEqual(readAt, -1, "updateActionConfig must read the action value"); assert.ok(gateAt < readAt, "the gating must run BEFORE the action value is read"); }); test("when NO action is available the form shows the inline warning and stays non-submittable — no fake action", () => { // Inline message in the scene's idiom, toggled by whether any action remains. assert.ok( gatingWindow.includes("document.getElementById('schedulerActionPermWarning')"), "the gate must locate the inline warning element" ); assert.ok( gatingWindow.includes("classList.toggle('hidden', !!firstAllowed)"), "the warning must show exactly when no allowed action remains" ); const warningAt = ejsSrc.indexOf('id="schedulerActionPermWarning"'); assert.notStrictEqual(warningAt, -1, "bot.ejs must carry the inline warning element"); const warningStart = ejsSrc.lastIndexOf("