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,348 @@
|
||||
"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("<div", warningAt);
|
||||
const warningDiv = ejsSrc.slice(warningStart, ejsSrc.indexOf("</div>", warningAt));
|
||||
assert.ok(
|
||||
warningDiv.includes('class="scheduler-action-info hidden"'),
|
||||
"the warning must reuse the scene's scheduler-action-info idiom and start hidden"
|
||||
);
|
||||
// It lives in the Action Type section: after the action select, before the
|
||||
// first action config block.
|
||||
const selectAt = ejsSrc.indexOf('id="schedulerActionType"');
|
||||
const consoleConfigAt = ejsSrc.indexOf('id="schedulerActionConsole"');
|
||||
assert.ok(selectAt > -1 && selectAt < warningAt && warningAt < consoleConfigAt,
|
||||
"the warning must sit inside the Action Type form section");
|
||||
assert.ok(
|
||||
ejsSrc.slice(selectAt, consoleConfigAt).includes("adpanel:scheduler-action-perm-mirror"),
|
||||
"the constraint comment must travel with the warning markup"
|
||||
);
|
||||
// Non-submittable: empty selection hits createSchedulerTask's existing guard
|
||||
// before the POST, and nothing anywhere invents a stand-in action.
|
||||
const guardAt = createWindow.indexOf("if (!actionType) {");
|
||||
const alertAt = createWindow.indexOf("alert('Please select an action type');", guardAt);
|
||||
const postAt = createWindow.indexOf("fetchWithServerActionToken(`/api/scheduler/");
|
||||
assert.notStrictEqual(guardAt, -1, "the actionType guard is missing");
|
||||
assert.ok(alertAt !== -1 && alertAt < postAt, "the guard must alert and return before the create POST");
|
||||
const gateCode = gatingWindow.replace(/\/\/[^\n]*/g, "");
|
||||
assert.ok(!/new Option\(/.test(gateCode), "the gate must not fabricate option elements");
|
||||
assert.ok(!/createElement\('option'\)/.test(gateCode), "the gate must not fabricate option elements");
|
||||
assert.ok(
|
||||
!/value\s*=\s*'[^']+'/.test(gateCode.replace("schedulerActionType.value = firstAllowed ? firstAllowed.value : '';", "")),
|
||||
"the gate must not hard-code any action value outside the firstAllowed fallback"
|
||||
);
|
||||
});
|
||||
|
||||
test("the pre-existing agent-access and planner_access gating composes unchanged", () => {
|
||||
// openSchedulerModal still owns its own gates...
|
||||
assert.ok(
|
||||
openModalWindow.includes("hasPerm('scheduler_access')"),
|
||||
"the modal-level scheduler_access gate must stay"
|
||||
);
|
||||
assert.ok(
|
||||
openModalWindow.includes("hasPerm('scheduler_create')") && openModalWindow.includes("createTab.style.display"),
|
||||
"the create-tab scheduler_create toggle must stay"
|
||||
);
|
||||
// ...and updateActionConfig still alerts on agent access / planner access
|
||||
// for actions the map lets through (planner_next_to_agent needs BOTH).
|
||||
assert.ok(
|
||||
updateConfigWindow.includes("!hasAgentAccess()") &&
|
||||
updateConfigWindow.includes("'You do not have permission to access '"),
|
||||
"the agent-access alert branch must stay"
|
||||
);
|
||||
assert.ok(
|
||||
updateConfigWindow.includes("!hasPerm('planner_access')") &&
|
||||
updateConfigWindow.includes("'You do not have permission to access the planner.'"),
|
||||
"the planner_access alert branch must stay"
|
||||
);
|
||||
const plannerBranchAt = createWindow.indexOf("actionType === 'planner_next_to_agent'");
|
||||
const selectionAt = createWindow.indexOf("if (schedulerModelValue) payload.selection = schedulerModelValue;", plannerBranchAt);
|
||||
assert.ok(
|
||||
plannerBranchAt >= 0 && selectionAt > plannerBranchAt &&
|
||||
createWindow.slice(plannerBranchAt, selectionAt).includes("!hasAgentAccess()") &&
|
||||
createWindow.slice(plannerBranchAt, selectionAt).includes("!hasPerm('planner_access')"),
|
||||
"both permission checks must run before binding the explicit model choice to the request"
|
||||
);
|
||||
});
|
||||
|
||||
test("server enforcement stays untouched and authoritative", () => {
|
||||
// The create route still derives the required permission from the SAME map
|
||||
// the fire-time re-check uses and still 403s with the permission named.
|
||||
const routeAt = indexSrc.indexOf('app.post("/api/scheduler/:serverName/tasks"');
|
||||
assert.notStrictEqual(routeAt, -1, "scheduler create route not found");
|
||||
const routeWindow = indexSrc.slice(routeAt, indexSrc.indexOf("app.put(", routeAt));
|
||||
assert.ok(
|
||||
routeWindow.includes("const requiredPermission = schedulerRequiredPermissionForAction(actionType);"),
|
||||
"the create route must keep deriving the perm from the shared map"
|
||||
);
|
||||
assert.ok(
|
||||
routeWindow.includes("!perms[requiredPermission]") && routeWindow.includes("403"),
|
||||
"the create route must keep enforcing the per-action 403"
|
||||
);
|
||||
// The client fix is client-side only: index.js carries no mirror of the
|
||||
// gating beyond its own authoritative map.
|
||||
assert.strictEqual(
|
||||
(indexSrc.match(/SCHEDULER_ACTION_REQUIRED_PERM/g) || []).length,
|
||||
0,
|
||||
"the client map must not leak into the server file"
|
||||
);
|
||||
});
|
||||
Reference in new issue
Block a user