Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

+448
View File
@@ -0,0 +1,448 @@
"use strict";
// Regression sweep for the Express-4 async-handler rejection class.
//
// Express 4 does not catch async-handler rejections: an `await` in a route
// handler that is not lexically enclosed by a try-with-catch turns any
// transient rejection (DB hiccup, Redis timeout, socket reset) into a request
// that is never answered — the process-level unhandledRejection handler only
// logs. Eight routes had already been fixed route-by-route (covered by
// tests/remote-apply-signing.test.js); this file pins the FULL sweep that
// guarded every remaining route in index.js and nodes.js.
//
// index.js is a ~51k-line application bundle (module side effects, DB and
// network at require time), and nodes.js shares that property,
// so these tests pin the fixes structurally on well-anchored source windows,
// matching the convention of the other route-level tests in this directory.
//
// Per fixed route the assertions are:
// 1. the first `try {` in the route window precedes the first awaited call
// the scanner originally flagged (the regression itself);
// 2. the route's catch logs its own bracketed marker;
// 3. the catch answers a 500 behind a res.headersSent guard (so a helper
// that responded before throwing can never let the handler fall through).
// Plus: 401-before-400 orderings for routes whose sync field 400s sit after
// auth gates, targeted shape assertions for the special guards (logout
// tombstone, planner context, the template change's
// try/finally body catch, the transfer setup-gate await), and a scanner run
// that must report ZERO unguarded awaits.
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const { execFileSync } = require("node:child_process");
const ROOT = path.join(__dirname, "..");
const SOURCES = {
"index.js": fs.readFileSync(path.join(ROOT, "index.js"), "utf8"),
"nodes.js": fs.readFileSync(path.join(ROOT, "nodes.js"), "utf8"),
};
// Every route/middleware registration in each file, in source order. Window
// ends are derived from these, so the table below never needs end anchors.
const REG_POSITIONS = {};
for (const [file, src] of Object.entries(SOURCES)) {
const re = /^(?:app|router)\.(?:get|post|put|delete|patch|all|use)\s*\(/gm;
const positions = [];
let m;
while ((m = re.exec(src)) !== null) positions.push(m.index);
REG_POSITIONS[file] = positions;
}
function routeWindow(file, regPrefix, label) {
const src = SOURCES[file];
const start = src.indexOf(regPrefix);
assert.notStrictEqual(start, -1, `${label}: route anchor not found: ${regPrefix}`);
let end = src.length;
for (const p of REG_POSITIONS[file]) {
if (p > start && p < end) end = p;
}
assert.ok(end > start, `${label}: empty window for ${regPrefix}`);
return src.slice(start, end);
}
function firstIndex(window, needle, label, why) {
const at = window.indexOf(needle);
assert.notStrictEqual(at, -1, `${label}: expected source to contain: ${needle}${why ? ` (${why})` : ""}`);
return at;
}
// The core regression: within the route window, the first `try {` must sit
// BEFORE the first awaited call the scanner flagged, so a rejection lands in
// a catch instead of escaping into the Express-4 void and hanging the client.
function assertGuardedPreFlight(file, regPrefix, firstAwaitNeedle, logTag, label) {
const w = routeWindow(file, regPrefix, label);
const tryAt = firstIndex(w, "try {", label, "the guard try");
const awaitAt = firstIndex(w, firstAwaitNeedle, label, "the originally flagged await");
assert.ok(
tryAt < awaitAt,
`${label}: the guard try { must precede the first awaited call (${firstAwaitNeedle}) — an await above the guard escapes Express 4's error handling and hangs the request`
);
firstIndex(w, `console.error("[${logTag}]`, label, "the route's own catch marker");
firstIndex(
w,
"if (!res.headersSent) return res.status(500).",
label,
"the headersSent-guarded 500 (a helper that responded before throwing must not fall through)"
);
return w;
}
// ── index.js — every route fixed by the sweep ──────────────────────────────
const INDEX_ROUTES = [
["/_stealth/nginx-auth", 'app.all("/_stealth/nginx-auth"', "await hasStealthAccess(req)", "/_stealth/nginx-auth"],
["/favicon.ico", 'app.get("/favicon.ico"', "await hasStealthAccess(req)", "/favicon.ico"],
["/api/captcha/verify", 'app.post("/api/captcha/verify"', "await verifyExternalCaptcha(token, clientIp)", "/api/captcha/verify"],
["/logout", 'app.post("/logout"', "await writeRevokedSidTombstone(req.sessionID)", "/logout"],
["GET /api/ai/keys", 'app.get("/api/ai/keys"', "await isAuthenticated(req)", "/api/ai/keys"],
["POST /api/ai/keys", 'app.post("/api/ai/keys"', "await isAuthenticated(req)", "/api/ai/keys"],
["DELETE /api/ai/keys/:provider", 'app.delete("/api/ai/keys/:provider"', "await isAuthenticated(req)", "/api/ai/keys/:provider"],
["GET /api/ai/selection", 'app.get("/api/ai/selection"', "await isAuthenticated(req)", "/api/ai/selection"],
["POST /api/ai/selection", 'app.post("/api/ai/selection"', "await isAuthenticated(req)", "/api/ai/selection"],
["GET /api/ai/models/:provider", 'app.get("/api/ai/models/:provider"', "await isAuthenticated(req)", "/api/ai/models/:provider"],
["GET /api/ai/chats", 'app.get("/api/ai/chats"', "await isAuthenticated(req)", "/api/ai/chats"],
["POST /api/ai/chats", 'app.post("/api/ai/chats"', "await isAuthenticated(req)", "/api/ai/chats"],
["GET /api/ai/chats/:id", 'app.get("/api/ai/chats/:id"', "await isAuthenticated(req)", "/api/ai/chats/:id"],
["PUT /api/ai/chats/:id", 'app.put("/api/ai/chats/:id"', "await isAuthenticated(req)", "/api/ai/chats/:id"],
["DELETE /api/ai/chats/:id", 'app.delete("/api/ai/chats/:id"', "await isAuthenticated(req)", "/api/ai/chats/:id"],
["GET planner", 'app.get("/api/servers/:name/planner"', "await resolvePlannerContext(req, res, req.params.name)", "/api/servers/:name/planner"],
["POST planner", 'app.post("/api/servers/:name/planner"', "await resolvePlannerContext(req, res, req.params.name)", "/api/servers/:name/planner"],
["POST planner send-agent", 'app.post("/api/servers/:name/planner/:id/send-agent"', "await resolvePlannerContext(req, res, req.params.name)", "/api/servers/:name/planner/:id/send-agent"],
["POST planner reorder", 'app.post("/api/servers/:name/planner/reorder"', "await resolvePlannerContext(req, res, req.params.name)", "/api/servers/:name/planner/reorder"],
["PUT planner :id", 'app.put("/api/servers/:name/planner/:id"', "await resolvePlannerContext(req, res, req.params.name)", "/api/servers/:name/planner/:id"],
["DELETE planner :id", 'app.delete("/api/servers/:name/planner/:id"', "await resolvePlannerContext(req, res, req.params.name)", "/api/servers/:name/planner/:id"],
["install-progress", 'app.get("/api/settings/database/install-progress/:jobId"', "await isAdmin(req)", "/api/settings/database/install-progress/:jobId"],
["database access-token", 'app.post("/api/settings/database/access-token"', "await isAdmin(req)", "/api/settings/database/access-token"],
["/db-open/:service", 'app.get("/db-open/:service"', "await isAdmin(req)", "/db-open/:service"],
["GET /api/settings/database", 'app.get("/api/settings/database"', "await isAdmin(req)", "/api/settings/database"],
["verify-install", 'app.post("/api/settings/database/verify-install"', "await isAdmin(req)", "/api/settings/database/verify-install"],
["database setup", 'app.post("/api/settings/database/setup"', "await isAdmin(req)", "/api/settings/database/setup"],
["database disable", 'app.post("/api/settings/database/disable"', "await isAdmin(req)", "/api/settings/database/disable"],
["database users create", 'app.post("/api/settings/database/users"', "await isAdmin(req)", "/api/settings/database/users"],
["database user password", 'app.post("/api/settings/database/users/:username/password"', "await isAdmin(req)", "/api/settings/database/users/:username/password"],
["database user delete", 'app.delete("/api/settings/database/users/:username"', "await isAdmin(req)", "/api/settings/database/users/:username delete"],
["database change-type", 'app.post("/api/settings/database/change-type"', "await isAdmin(req)", "/api/settings/database/change-type"],
["/pgadmin4 legacy redirect", "app.use(['/pgadmin4', '/pgadmin'", "await isAdmin(req)", "/pgadmin4"],
["/phpmyadmin legacy", "app.use('/phpmyadmin'", "await isAdmin(req)", "/phpmyadmin"],
["pgadmin status", 'app.get("/api/settings/database/pgadmin/status"', "await isAdmin(req)", "/api/settings/database/pgadmin/status"],
["pgadmin setup", 'app.post("/api/settings/database/pgadmin/setup"', "await isAdmin(req)", "/api/settings/database/pgadmin/setup"],
["pgadmin disable", 'app.post("/api/settings/database/pgadmin/disable"', "await isAdmin(req)", "/api/settings/database/pgadmin/disable"],
["pgadmin credentials", 'app.post("/api/settings/database/pgadmin/credentials"', "await isAdmin(req)", "/api/settings/database/pgadmin/credentials"],
["mongodb status", 'app.get("/api/settings/database/mongodb/status"', "await isAdmin(req)", "/api/settings/database/mongodb/status"],
["mongodb setup", 'app.post("/api/settings/database/mongodb/setup"', "await isAdmin(req)", "/api/settings/database/mongodb/setup"],
["mongodb disable", 'app.post("/api/settings/database/mongodb/disable"', "await isAdmin(req)", "/api/settings/database/mongodb/disable"],
["mongodb users create", 'app.post("/api/settings/database/mongodb/users"', "await isAdmin(req)", "/api/settings/database/mongodb/users"],
["mongodb users list", 'app.get("/api/settings/database/mongodb/users"', "await isAdmin(req)", "/api/settings/database/mongodb/users"],
["mongodb user delete", 'app.delete("/api/settings/database/mongodb/users/:username"', "await isAdmin(req)", "/api/settings/database/mongodb/users/:username delete"],
["mongodb user password", 'app.post("/api/settings/database/mongodb/users/:username/password"', "await isAdmin(req)", "/api/settings/database/mongodb/users/:username/password"],
["GET /api/templates", 'app.get("/api/templates"', "await isAuthenticated(req)", "/api/templates"],
["startup-command", 'app.post("/api/templates/startup-command"', "await isAuthenticated(req)", "/api/templates/startup-command"],
["template-store categories", 'app.get("/api/settings/template-store/categories"', "await isAdmin(req)", "/api/settings/template-store/categories"],
["template-store category", 'app.get("/api/settings/template-store/:category"', "await isAdmin(req)", "/api/settings/template-store/:category"],
["GET /api/account", 'app.get("/api/account"', "await findUserByEmail(req.session.user)", "/api/account"],
["username change", 'app.post("/api/account/username"', "await findUserByEmail(req.session.user)", "/api/account/username"],
["2fa generate", 'app.post("/api/account/2fa/generate"', "await findUserByEmail(req.session.user)", "/api/account/2fa/generate"],
["2fa confirm", 'app.post("/api/account/2fa/confirm"', "await findUserByEmail(req.session.user)", "/api/account/2fa/confirm"],
["admin reset-recovery-codes", 'app.post("/api/admin/user/reset-recovery-codes"', "await isAdmin(req)", "/api/admin/user/reset-recovery-codes"],
["admin user create", 'app.post("/api/admin/user/create"', "await getLoggedInUser(req)", "/api/admin/user/create"],
["branding update", 'app.post("/api/admin/branding/update"', "await isAdmin(req)", "/api/admin/branding/update"],
["GET branding", 'app.get("/api/admin/branding"', "await isAdmin(req)", "/api/admin/branding"],
["GET login-background", 'app.get("/api/admin/login-background"', "await isAdmin(req)", "/api/admin/login-background"],
["POST login-background", 'app.post("/api/admin/login-background"', "await isAdmin(req)", "/api/admin/login-background"],
["recovery verify", 'app.post("/api/account/recovery/verify"', "await findUserByEmail(req.session.user)", "/api/account/recovery/verify"],
["generate-recovery", 'app.post("/api/account/2fa/generate-recovery"', "await findUserByEmail(req.session.user)", "/api/account/2fa/generate-recovery"],
["regen verify-password", 'app.post("/api/account/2fa/regenerate-recovery-codes/verify-password"', "await findUserByEmail(req.session.user)", "/api/account/2fa/regenerate-recovery-codes/verify-password"],
["regen completion", 'app.post("/api/account/2fa/regenerate-recovery-codes",', "await findUserByEmail(req.session.user)", "/api/account/2fa/regenerate-recovery-codes"],
["password verify", 'app.post("/api/account/password/verify"', "await findUserByEmail(req.session.user)", "/api/account/password/verify"],
["password change", 'app.post("/api/account/password/change"', "await findUserByEmail(req.session.user)", "/api/account/password/change"],
["email verify", 'app.post("/api/account/email/verify"', "await findUserByEmail(req.session.user)", "/api/account/email/verify"],
["email change", 'app.post("/api/account/email/change"', "await findUserByEmail(req.session.user)", "/api/account/email/change"],
["usercount", 'app.get("/api/usercount"', "await isAdmin(req)", "/api/usercount"],
["GET webhooks", 'app.get("/api/settings/webhooks"', "await findUserByEmail(req.session.user)", "/api/settings/webhooks"],
["POST webhooks", 'app.post("/api/settings/webhooks"', 'await requireActionTokenOr403(req, res, "POST /api/settings/webhooks")', "/api/settings/webhooks"],
["DELETE webhooks", 'app.delete("/api/settings/webhooks"', "await findUserByEmail(req.session.user)", "/api/settings/webhooks delete"],
["webhooks test", 'app.post("/api/settings/webhooks/test"', 'await requireActionTokenOr403(req, res, "POST /api/settings/webhooks/test")', "/api/settings/webhooks/test"],
["GET alert", 'app.get("/api/settings/alert"', "await isAuthenticated(req)", "/api/settings/alert"],
["POST alert", 'app.post("/api/settings/alert"', "await isAuthenticated(req)", "/api/settings/alert"],
["DELETE alert", 'app.delete("/api/settings/alert/:id"', "await isAuthenticated(req)", "/api/settings/alert/:id"],
["files list", 'app.get("/api/servers/:name/files/list"', "await isAuthenticated(req)", "/api/servers/:name/files/list"],
["files read", 'app.get("/api/servers/:name/files/read"', "await isAuthenticated(req)", "/api/servers/:name/files/read"],
["files stream", 'app.get("/api/servers/:name/files/stream"', "await isAuthenticated(req)", "/api/servers/:name/files/stream"],
["files download", 'app.get("/api/servers/:name/files/download"', "await isAuthenticated(req)", "/api/servers/:name/files/download"],
["files write", 'app.put("/api/servers/:name/files/write"', "await isAuthenticated(req)", "/api/servers/:name/files/write"],
["files mkdir", 'app.post("/api/servers/:name/files/mkdir"', "await isAuthenticated(req)", "/api/servers/:name/files/mkdir"],
["files delete", 'app.delete("/api/servers/:name/files/delete"', "await isAuthenticated(req)", "/api/servers/:name/files/delete"],
["files rename", 'app.post("/api/servers/:name/files/rename"', "await isAuthenticated(req)", "/api/servers/:name/files/rename"],
["/upload", 'app.post("/upload"', "await isAuthenticated(req)", "/upload"],
["server delete", 'app.delete("/api/settings/servers/:name"', "await isAdmin(req)", "/api/settings/servers/:name"],
["server suspension", 'app.post("/api/settings/servers/:name/suspension"', "await isAdmin(req)", "/api/settings/servers/:name/suspension"],
["server template change", 'app.post("/api/settings/servers/:name/template"', "await isAdmin(req)", "/api/settings/servers/:name/template"],
["resources PATCH", 'app.patch("/api/settings/servers/:name/resources"', "await isAuthenticated(req)", "/api/settings/servers/:name/resources PATCH"],
["resources GET", 'app.get("/api/settings/servers/:name/resources"', "await findServer(name)", "/api/settings/servers/:name/resources"],
["server rename", 'app.post("/api/settings/servers/:name/rename"', "await isAuthenticated(req)", "/api/settings/servers/:name/rename"],
["transfer GET", 'app.get("/api/settings/servers/:name/transfer"', "await isAuthenticated(req)", "/api/settings/servers/:name/transfer"],
["transfer POST", 'app.post("/api/settings/servers/:name/transfer"', "await isAuthenticated(req)", "/api/settings/servers/:name/transfer"],
];
for (const [label, reg, firstAwait, tag] of INDEX_ROUTES) {
test(`[index.js] ${label} bounds its pre-flight`, () => {
assertGuardedPreFlight("index.js", reg, firstAwait, tag, label);
});
}
// ── index.js — delegated expression-bodied adapters (invisible to the
// scanner) ──────────────────────────────────────────────────────────────────
// scripts/find-unguarded-awaited-routes.js only analyzes inline block-bodied
// handlers; a route registered as `(req, res) => sharedHandler(req, res,
// {...})` has no handler body to scan, so an unguarded await inside the
// shared handler would be invisible to it AND to this file's window pins.
// The sweep table below is the real guard for those aliases: each delegated
// route must keep its THIN delegation shape (an expression-bodied arrow
// cannot contain a guard, so any inline pipeline would be unguarded
// pre-flight again) with its own action-token scope, and the shared module's
// exported handler must bound its ENTIRE awaited pipeline — the first
// `try {` precedes the first `await` — logging its own bracketed marker and
// answering the headersSent-guarded 500. That never-rejects contract is what
// makes the thin arrow safe under Express 4 (the handler's promise always
// settles; Express 4 ignores rejections).
const DELEGATED_INDEX_ROUTES = [
["admin 2fa reset", 'app.post("/api/admin/user/reset-2fa", sessionRevoke2faRateLimiter', "/api/admin/user/reset-2fa"],
["admin 2fa reset confirm", 'app.post("/api/admin/user/confirm-2fa-reset", sessionRevoke2faRateLimiter', "/api/admin/user/confirm-2fa-reset"],
];
const RESET_MODULE_SOURCE = fs.readFileSync(path.join(ROOT, "services", "admin-2fa-reset.js"), "utf8");
for (const [label, reg, route] of DELEGATED_INDEX_ROUTES) {
test(`[index.js] ${label} delegates to the guarded shared handler`, () => {
const w = routeWindow("index.js", reg, label);
firstIndex(w, `(req, res) => handleAdmin2faReset(req, res, {`, label, "the thin delegation shape");
firstIndex(w, `action: "POST ${route}"`, label, "the route's own action-token scope");
assert.ok(
!w.includes("await db.") && !w.includes("await findUserByEmail"),
`${label}: no inline pipeline may re-grow in the adapter`
);
});
}
test("[services/admin-2fa-reset.js] the shared 2FA reset handler bounds its whole pipeline (never rejects)", () => {
const fnStart = RESET_MODULE_SOURCE.indexOf("async function handleAdmin2faReset(");
const fnEnd = RESET_MODULE_SOURCE.indexOf("return { handleAdmin2faReset };", fnStart);
assert.ok(fnStart >= 0 && fnEnd > fnStart, "the shared handler must live once inside the service factory");
const handler = RESET_MODULE_SOURCE.slice(fnStart, fnEnd);
const tryAt = firstIndex(handler, "try {", "admin 2fa reset handler", "the guard try");
const awaitAt = firstIndex(handler, "await ", "admin 2fa reset handler", "the first awaited gate");
assert.ok(
tryAt < awaitAt,
"admin 2fa reset handler: the guard try { must precede the first awaited call — an await above the guard escapes Express 4's error handling and hangs the request"
);
firstIndex(handler, `"[admin-2fa-reset] pre-flight failed:"`, "admin 2fa reset handler", "the route's own catch marker (via the injected logger)");
firstIndex(
handler,
"if (!res.headersSent) return res.status(500).",
"admin 2fa reset handler",
"the headersSent-guarded 500 (a gate that responded before throwing must not be written twice)"
);
firstIndex(handler, "res.end();", "admin 2fa reset handler", "the exactly-once end for an already-answered response");
});
// ── nodes.js — every route fixed by the sweep ──────────────────────────────
const NODES_ROUTES = [
["GET /api/nodes", 'app.get("/api/nodes"', "await requireNodeAdmin(req, res)", "/api/nodes"],
["GET /api/nodes/:id", 'app.get("/api/nodes/:id"', "await requireNodeAdmin(req, res)", "/api/nodes/:id"],
["POST /api/nodes/:id/check", 'app.post("/api/nodes/:id/check"', "await requireNodeAdmin(req, res)", "/api/nodes/:id/check"],
["ports check", 'app.get("/api/nodes/:id/ports/check"', "await requireNodeAdmin(req, res)", "/api/nodes/:id/ports/check"],
["ports in-use", 'app.get("/api/nodes/:id/ports/in-use"', "await requireNodeAdmin(req, res)", "/api/nodes/:id/ports/in-use"],
["GET build", 'app.get("/api/nodes/:id/build"', "await requireNodeAdmin(req, res)", "/api/nodes/:id/build"],
["GET config.yml", 'app.get("/api/nodes/:id/config.yml"', "await findNodeByIdOrName(req.params.id)", "/api/nodes/:id/config.yml"],
["server info", 'app.get("/api/nodes/server/:name/info"', "await checkServerAccess(req, serverName)", "/api/nodes/server/:name/info"],
["server entries", 'app.get("/api/nodes/server/:name/entries"', "await checkServerAccess(req, serverName)", "/api/nodes/server/:name/entries"],
["server file read", 'app.get("/api/nodes/server/:name/file"', "await checkServerAccess(req, serverName)", "/api/nodes/server/:name/file"],
["server download", 'app.get("/api/nodes/server/:name/download"', "await checkServerAccess(req, serverName)", "/api/nodes/server/:name/download"],
["server file write", 'app.post("/api/nodes/server/:name/file"', "await checkServerAccess(req, serverName)", "/api/nodes/server/:name/file"],
["server delete", 'app.post("/api/nodes/server/:name/delete"', "ctx = await remoteContext(req.params.name)", "/api/nodes/server/:name/delete"],
["server delete-batch", 'app.post("/api/nodes/server/:name/delete-batch"', "ctx = await remoteContext(req.params.name)", "/api/nodes/server/:name/delete-batch"],
["server rename", 'app.post("/api/nodes/server/:name/rename"', "ctx = await remoteContext(req.params.name)", "/api/nodes/server/:name/rename"],
["server extract", 'app.post("/api/nodes/server/:name/extract"', "ctx = await remoteContext(req.params.name)", "/api/nodes/server/:name/extract"],
["server archive", 'app.post("/api/nodes/server/:name/archive"', "ctx = await remoteContext(req.params.name)", "/api/nodes/server/:name/archive"],
["server upload", 'app.post("/api/nodes/server/:name/upload"', "ctx = await remoteContext(req.params.name)", "/api/nodes/server/:name/upload"],
["server upload-url", 'app.post("/api/nodes/server/:name/upload-url"', "ctx = await remoteContext(req.params.name)", "/api/nodes/server/:name/upload-url"],
];
for (const [label, reg, firstAwait, tag] of NODES_ROUTES) {
test(`[nodes.js] ${label} bounds its pre-flight`, () => {
assertGuardedPreFlight("nodes.js", reg, firstAwait, tag, label);
});
}
// ── rejection order: sync field 400s stay after the auth gates ─────────────
// Guards must not move request validation ahead of auth: an unauthenticated
// malformed request must still get 401/403, not 400.
const ORDERINGS = [
// The captcha route's sync 400s legitimately precede the provider call (a
// malformed request must never reach the network) — assert that order.
["/api/captcha/verify", 'app.post("/api/captcha/verify"', '"missing-token"', "await verifyExternalCaptcha(token, clientIp)"],
["POST /api/ai/keys", 'app.post("/api/ai/keys"', "await isAuthenticated(req)", '"invalid provider"'],
["database setup", 'app.post("/api/settings/database/setup"', "await isAdmin(req)", '"Invalid database type"'],
["database users create", 'app.post("/api/settings/database/users"', "await isAdmin(req)", '"Invalid username (alphanumeric, _, - only)"'],
["pgadmin setup", 'app.post("/api/settings/database/pgadmin/setup"', "await isAdmin(req)", '"Valid email required for pgAdmin login"'],
["POST alert", 'app.post("/api/settings/alert"', "await isAuthenticated(req)", '"Message required"'],
["server rename", 'app.post("/api/settings/servers/:name/rename"', "await isAuthenticated(req)", '"missing server name"'],
["POST /upload-url (pre-existing fix)", 'app.post("/upload-url"', "await isAuthenticated(req)", '"missing bot"'],
];
for (const [label, reg, earlierNeedle, laterNeedle] of ORDERINGS) {
test(`[index.js] ${label}: sync validation keeps its original position relative to the awaited gate`, () => {
const w = routeWindow("index.js", reg, label);
assert.ok(
firstIndex(w, earlierNeedle, label, "the earlier check") < firstIndex(w, laterNeedle, label, "the awaited gate"),
`${label}: ${earlierNeedle} must keep its original position before ${laterNeedle}`
);
});
}
// ── targeted shape assertions for the special guards ───────────────────────
test("/logout: the tombstone flag is hoisted so the destroy still applies", () => {
const w = routeWindow("index.js", 'app.post("/logout"', "/logout");
const hoistAt = firstIndex(w, "let logoutTombstoneWritten = false;", "/logout", "the hoisted flag");
const assignAt = firstIndex(w, "logoutTombstoneWritten = await writeRevokedSidTombstone(req.sessionID);", "/logout", "the guarded await");
assert.ok(hoistAt < assignAt, "/logout: the flag must be declared before the guarded tombstone write");
assert.ok(firstIndex(w, "logoutTombstoneWritten = await writeRevokedSidTombstone", "/logout") < firstIndex(w, "if (!logoutTombstoneWritten)", "/logout"),
"/logout: the warn-on-false check must follow the guarded write (original order)");
});
test("planner routes hoist ctx so the body tries read it", () => {
for (const reg of [
'app.get("/api/servers/:name/planner"',
'app.post("/api/servers/:name/planner/:id/send-agent"',
'app.delete("/api/servers/:name/planner/:id"',
]) {
const w = routeWindow("index.js", reg, "planner ctx");
const hoistAt = firstIndex(w, "let ctx = null;", "planner ctx", "the hoisted context");
const assignAt = firstIndex(w, "ctx = await resolvePlannerContext(req, res, req.params.name);", "planner ctx", "the guarded lookup");
assert.ok(hoistAt < assignAt, `planner ctx: ctx must be hoisted before the guarded lookup (${reg})`);
}
});
test("template change: the reinstall body try gained a catch while keeping its finally", () => {
const w = routeWindow("index.js", 'app.post("/api/settings/servers/:name/template"', "template change");
firstIndex(w, "reinstall failed:", "template change", "the body catch added to the try/finally");
const finallyAt = firstIndex(w, "} finally {", "template change", "the claim-release finally");
const releaseAt = firstIndex(w, "await releaseReinstallClaim({ releaseReinstallOperation, setCachedServerStatus }, claimName, templateClaim.prevStatus,", "template change", "the shared release await");
assert.ok(finallyAt < releaseAt, "template change: the finally must still wrap the release");
// The release is guarded: a cleanup failure must not escape the finally.
firstIndex(w, "Failed to release reinstall claim:", "template change", "the cleanup guard");
});
test("transfer POST: the lock-setup await is contained in the handler's own context", () => {
const w = routeWindow("index.js", 'app.post("/api/settings/servers/:name/transfer"', "transfer POST");
const tryAt = firstIndex(w, "try {\n lockSetupOutcome = await lockSetupDone;", "transfer POST", "the guarded setup-gate await");
firstIndex(w, "lock setup await failed:", "transfer POST", "the setup-gate catch marker");
assert.ok(tryAt !== -1, "transfer POST: lockSetupDone must be awaited inside its own try");
});
test("resources PATCH: port validation and commits share a guarded node lock", () => {
const w = routeWindow("index.js", 'app.patch("/api/settings/servers/:name/resources"', "resources PATCH");
const checkAt = firstIndex(w, "isPortInNodeAllocation(node, port)", "resources PATCH", "fresh pool check");
const daemonAt = firstIndex(w, "const r = await httpRequestJson(", "resources PATCH", "daemon write");
const commitAt = firstIndex(w, "UPDATE servers SET resources = COALESCE(?, resources)", "resources PATCH", "scoped index commit");
const lockAt = firstIndex(w, 'await withKeyedLock(`node-ports:${node.id}`, save)', "resources PATCH", "guarded lock call");
assert.ok(checkAt < daemonAt && daemonAt < commitAt && commitAt < lockAt);
assert.match(w, /return applyResources\(lockedEntry\);[\s\S]*await withKeyedLock\(`node-ports:\$\{node\.id\}`, save\)/);
assert.match(w, /catch \(e\) \{\s*console\.error\("\[\/api\/settings\/servers\/:name\/resources\] failed:/);
});
test("webhooks POST/DELETE: the response snapshot awaits are guarded after the durable write", () => {
const post = routeWindow("index.js", 'app.post("/api/settings/webhooks"', "webhooks POST");
firstIndex(post, "response snapshot failed:", "webhooks POST", "the post-write snapshot guard");
const del = routeWindow("index.js", 'app.delete("/api/settings/webhooks"', "webhooks DELETE");
firstIndex(del, "delete response snapshot failed:", "webhooks DELETE", "the post-delete snapshot guard");
});
// ── hoisted bindings survive into the body ─────────────────────────────────
// The sweep's second bug class: a binding declared with const INSIDE a guard
// try but still read BELOW the guard's catch is a guaranteed ReferenceError at
// runtime (Express 4 answers it as a bogus 400/500 on every call, or — when
// the first below-guard read sits outside any try — hangs the request). The
// fix hoists each trapped binding above the guard try (`let X = <default>;`)
// and turns the in-guard declaration into a bare assignment. One data-driven
// pin per fixed route: the hoist must precede the guard try and the
// assignment must sit inside it (before the guard's catch), so the body
// below reads a defined binding instead of throwing.
const HOISTED_BINDINGS = [
["files write", "index.js", 'app.put("/api/servers/:name/files/write"', [
["writeMode", 'writeMode = canCreate ? "create" : "update";'],
["rel", 'rel = String(req.body?.path || "");'],
["content", 'content = String(req.body?.content ?? "");'],
["contentBase64", 'contentBase64 = typeof req.body?.contentBase64 === "string" && req.body.contentBase64 ? req.body.contentBase64 : "";'],
]],
["files mkdir", "index.js", 'app.post("/api/servers/:name/files/mkdir"', [
["rel", 'rel = String(req.body?.path || "");'],
]],
["files delete", "index.js", 'app.delete("/api/servers/:name/files/delete"', [
["rel", 'rel = String(req.query.path || req.body?.path || "");'],
]],
["files rename", "index.js", 'app.post("/api/servers/:name/files/rename"', [
["srcRel", 'srcRel = String(req.body?.src || "");'],
["destRel", 'destRel = String(req.body?.dest || "");'],
]],
["resources PATCH", "index.js", 'app.patch("/api/settings/servers/:name/resources"', [
["name", 'name = String(req.params.name || "").trim();'],
]],
["resources GET", "index.js", 'app.get("/api/settings/servers/:name/resources"', [
["isMinecraft", 'isMinecraft = isMinecraftTemplateLike(resultTemplateId, "");'],
]],
["server rename", "index.js", 'app.post("/api/settings/servers/:name/rename"', [
["name", 'name = String(req.params.name || "").trim();'],
["displayName", "displayName = sanitizeDisplayName(rawDisplayName);"],
]],
["server delete", "index.js", 'app.delete("/api/settings/servers/:name"', [
["serverName", 'serverName = String(req.params.name || "").trim();'],
["currentUser", "currentUser = await findUserByEmail(req.session.user);"],
]],
["transfer POST", "index.js", 'app.post("/api/settings/servers/:name/transfer"', [
["name", 'name = String(req.params.name || "").trim();'],
["srcId", 'srcId = String(sourceNode.id);'],
["dstId", 'dstId = String(destNode.id);'],
]],
["webhooks test", "index.js", 'app.post("/api/settings/webhooks/test"', [
["category", "({ category } = req.body || {});"],
]],
];
for (const [label, file, reg, bindings] of HOISTED_BINDINGS) {
test(`${label}: hoisted bindings survive into the body`, () => {
const w = routeWindow(file, reg, label);
const tryAt = firstIndex(w, "try {", label, "the guard try");
const catchAt = firstIndex(w, "} catch (err) {", label, "the guard's catch");
for (const [name, assignNeedle] of bindings) {
const hoistAt = firstIndex(w, `let ${name} =`, label, `the hoisted ${name} declaration`);
const assignAt = firstIndex(w, assignNeedle, label, `the in-guard ${name} assignment`);
assert.ok(
hoistAt < tryAt,
`${label}: let ${name} must be declared above the guard try so the body below the catch reads a defined binding`
);
assert.ok(
assignAt > tryAt && assignAt < catchAt,
`${label}: the ${name} assignment must sit inside the guard try (between try { and } catch (err) {)`
);
}
});
}
// ── the scanner itself must now report zero unguarded awaits ───────────────
test("the unguarded-awaited-route scanner reports zero findings", () => {
const stdout = execFileSync(
process.execPath,
["scripts/find-unguarded-awaited-routes.js", "index.js", "nodes.js"],
{ cwd: ROOT, encoding: "utf8" }
);
assert.strictEqual(
stdout.trim(),
"",
`the scanner must report zero unguarded awaits; got:\n${stdout}`
);
});