378 lines
23 KiB
JavaScript
378 lines
23 KiB
JavaScript
"use strict";
|
|
|
|
// Tests for the branding / login-background / global-alert hardening (audit
|
|
// findings: "three endpoints lack the action-token/step-up protection every
|
|
// sibling settings endpoint has" and "hand-rolled regex SVG sanitizer").
|
|
//
|
|
// POST /api/admin/branding/update, POST /api/admin/login-background and
|
|
// POST/DELETE /api/settings/alert used to rest entirely on the global
|
|
// Origin/Referer middleware, while every sibling settings write (security,
|
|
// captcha, maintenance, sessions, webhooks, panel update) minted and required
|
|
// short-lived action tokens and ran the destructive-action step-up. Branding
|
|
// and alerts are the panel's most visible surfaces (the pre-auth login page
|
|
// included), so a hijacked admin session could deface them with no
|
|
// re-verification.
|
|
//
|
|
// The contract now locked here (mirroring webhook-config-step-up.test.js):
|
|
// - Every write requires requireActionTokenOr403 with its exact action
|
|
// string, and an UNCONDITIONAL requireDestructiveActionStepUp.
|
|
// - Ordering: auth -> admin -> action token -> input validation -> step-up,
|
|
// so a malformed or unauthorized request burns neither a grace use nor
|
|
// step-up credential budget.
|
|
// - Alert delete tokens are one-time, bound to the exact alert id, and the
|
|
// existence check precedes the token check so a request for an unknown id
|
|
// never consumes a matched token's nonce; step-up challenges re-mint the
|
|
// consumed token via failureResponseExtras so the client can retry
|
|
// in-modal.
|
|
// - The section GETs mint the tokens (no-store: responses embed
|
|
// credentials), and /api/settings/action-tokens refreshes the multi-use
|
|
// ones.
|
|
// - settings.js routes every write through sendGuardedRequestWithStepUp,
|
|
// with one token refresh+retry on 403 token rejections, and the alert
|
|
// delete wrapper stashes the challenge's re-minted one-time token.
|
|
// - SVG sanitization parses with a vetted XML parser and REBUILDS the
|
|
// document (functional tests live in utils/svg-sanitizer.test.js); here
|
|
// we lock the parse-and-rebuild architecture and the by-construction SVG
|
|
// response-header guard that wraps res.setHeader.
|
|
//
|
|
// index.js boots servers on require, so route-level behavior is locked with
|
|
// source assertions (same technique as webhook-config-step-up.test.js).
|
|
|
|
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 INDEX_JS = path.join(ROOT, "index.js");
|
|
const SETTINGS_JS = path.join(ROOT, "public", "js", "settings.js");
|
|
const SETTINGS_EJS = path.join(ROOT, "views", "settings.ejs");
|
|
const SANITIZER_JS = path.join(ROOT, "utils", "svg-sanitizer.js");
|
|
|
|
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
|
|
const settingsJsSource = fs.readFileSync(SETTINGS_JS, "utf8");
|
|
const settingsEjsSource = fs.readFileSync(SETTINGS_EJS, "utf8");
|
|
const sanitizerSource = fs.readFileSync(SANITIZER_JS, "utf8");
|
|
|
|
function endIndexOfFunction(source, startMarker) {
|
|
const start = source.indexOf(startMarker);
|
|
assert.ok(start >= 0, `marker ${startMarker} not found`);
|
|
const bodyStart = source.indexOf("{", start);
|
|
let depth = 0;
|
|
for (let i = bodyStart; i < source.length; i += 1) {
|
|
if (source[i] === "{") depth += 1;
|
|
else if (source[i] === "}") {
|
|
depth -= 1;
|
|
if (depth === 0) return i + 1;
|
|
}
|
|
}
|
|
assert.fail(`unbalanced braces after marker ${startMarker}`);
|
|
}
|
|
|
|
function extractRoute(source, routeDecl, endMarker) {
|
|
const start = source.indexOf(routeDecl);
|
|
assert.ok(start >= 0, `route ${routeDecl} must exist`);
|
|
const end = endMarker ? source.indexOf(endMarker, start) : -1;
|
|
assert.ok(end > start, `route slice for ${routeDecl} must be bounded`);
|
|
return source.slice(start, end);
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// POST /api/admin/branding/update
|
|
// ---------------------------------------------------------------------------
|
|
|
|
const brandingPost = extractRoute(
|
|
indexSource,
|
|
'app.post("/api/admin/branding/update"',
|
|
'app.get("/api/admin/branding"'
|
|
);
|
|
|
|
test("branding POST: action token + unconditional step-up, correct ordering", () => {
|
|
const tokenAt = brandingPost.indexOf('requireActionTokenOr403(req, res, "POST /api/admin/branding/update")');
|
|
assert.ok(tokenAt >= 0, "the write must require the branding update action token");
|
|
const adminAt = brandingPost.indexOf("if (!(await isAdmin(req)))");
|
|
const validationAt = brandingPost.indexOf("Invalid app name. Must be 1-50 characters");
|
|
const stepUpAt = brandingPost.indexOf('requireDestructiveActionStepUp(req, res, currentUser, "Branding update")');
|
|
assert.ok(adminAt >= 0 && validationAt >= 0 && stepUpAt >= 0, "all anchors present");
|
|
assert.ok(adminAt < tokenAt && tokenAt < validationAt && validationAt < stepUpAt,
|
|
"order must be auth -> admin -> action token -> validation -> step-up");
|
|
const gateAt = brandingPost.indexOf("if (!stepUp.ok) return;", stepUpAt);
|
|
assert.ok(gateAt > stepUpAt, "the step-up result must gate the mutation");
|
|
});
|
|
|
|
test("branding POST: sessionRevoke2faRateLimiter protects the step-up credential", () => {
|
|
assert.ok(
|
|
brandingPost.includes("brandingWriteRateLimiter, sessionRevoke2faRateLimiter, async (req, res)"),
|
|
"the step-up limiter must be mounted alongside the write limiter"
|
|
);
|
|
});
|
|
|
|
test("branding POST: success response re-mints the token and reports the grace window", () => {
|
|
assert.ok(brandingPost.includes('updateBranding: issueActionToken(req, "POST /api/admin/branding/update"'),
|
|
"the success payload must re-mint the branding token");
|
|
assert.ok(brandingPost.includes("graceExpiresAt: stepUp.graceExpiresAt || 0"),
|
|
"the success payload must report the grace window");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// POST /api/admin/login-background
|
|
// ---------------------------------------------------------------------------
|
|
|
|
const loginBgPost = extractRoute(
|
|
indexSource,
|
|
'app.post("/api/admin/login-background"',
|
|
'app.post("/api/account/recovery/verify"'
|
|
);
|
|
|
|
test("login-background POST: action token + unconditional step-up, correct ordering", () => {
|
|
const tokenAt = loginBgPost.indexOf('requireActionTokenOr403(req, res, "POST /api/admin/login-background")');
|
|
assert.ok(tokenAt >= 0, "the write must require the login-background action token");
|
|
const adminAt = loginBgPost.indexOf("if (!(await isAdmin(req)))");
|
|
const validationAt = loginBgPost.indexOf('return res.status(400).json({ error: "Choose an image or video first" })');
|
|
const stepUpAt = loginBgPost.indexOf('requireDestructiveActionStepUp(req, res, currentUser, "Login background update")');
|
|
assert.ok(adminAt >= 0 && validationAt >= 0 && stepUpAt >= 0, "all anchors present");
|
|
assert.ok(adminAt < tokenAt && tokenAt < validationAt && validationAt < stepUpAt,
|
|
"order must be auth -> admin -> action token -> validation -> step-up");
|
|
const gateAt = loginBgPost.indexOf("if (!stepUp.ok) {", stepUpAt);
|
|
assert.ok(gateAt > stepUpAt, "the step-up result must gate the mutation");
|
|
assert.ok(loginBgPost.indexOf("saveBrandingConfig({", stepUpAt) > stepUpAt,
|
|
"the config mutation must come after the step-up");
|
|
// The upload/download branches may have written the replacement file before
|
|
// the step-up; a denial must unlink that orphan (but never the live file —
|
|
// previousLocalPath stays the replacement argument of the cleanup).
|
|
assert.ok(/if \(!stepUp\.ok\) \{\s*\n\s*removeOldLoginBackgroundFile\(cleanupReplacementFilename, previousLocalPath\);/.test(loginBgPost),
|
|
"a denied step-up must clean up the just-written replacement file");
|
|
});
|
|
|
|
test("login-background POST: limiter pair + success payload re-mint and grace report", () => {
|
|
assert.ok(loginBgPost.includes("brandingWriteRateLimiter, sessionRevoke2faRateLimiter, async (req, res)"));
|
|
assert.ok(loginBgPost.includes('updateLoginBackground: issueActionToken(req, "POST /api/admin/login-background"'));
|
|
assert.ok(loginBgPost.includes("graceExpiresAt: stepUp.graceExpiresAt || 0"));
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Global alert endpoints
|
|
// ---------------------------------------------------------------------------
|
|
|
|
const alertGetStart = indexSource.indexOf('function buildAlertSettingsActionTokens(req)');
|
|
assert.ok(alertGetStart >= 0, "the alert token builder must exist");
|
|
const alertSlice = indexSource.slice(alertGetStart, indexSource.indexOf("app.post(\"/api/settings/change-password\""));
|
|
|
|
test("alert token builder: multi-use create token + one-time per-id delete tokens", () => {
|
|
assert.ok(alertSlice.includes('createAlert: issueActionToken(req, "POST /api/settings/alert", {}, { ttlSeconds: 600 })'),
|
|
"createAlert is a repeatable multi-use token");
|
|
assert.ok(alertSlice.includes('"DELETE /api/settings/alert/:id"'), "delete tokens use the delete action");
|
|
assert.ok(alertSlice.includes("{ id: String(alert.id) }"), "delete tokens are bound to the exact alert id");
|
|
assert.ok(alertSlice.includes("ttlSeconds: 300, oneTime: true"), "delete tokens are one-time");
|
|
});
|
|
|
|
test("alert GET: no-store + minted tokens (response shape changed with the frontend)", () => {
|
|
const getRoute = extractRoute(indexSource, 'app.get("/api/settings/alert"', 'app.post("/api/settings/alert"');
|
|
assert.ok(getRoute.includes('res.set("Cache-Control", "no-store")'),
|
|
"a response embedding one-time tokens must be uncacheable");
|
|
assert.ok(getRoute.includes("actionTokens: buildAlertSettingsActionTokens(req)"));
|
|
assert.ok(getRoute.includes("alerts: getGlobalAlerts() || []"));
|
|
assert.ok(getRoute.includes("revokeSecurity: await getDestructiveActionSecurityAsync(req, user)"));
|
|
});
|
|
|
|
test("alert POST: token + validation + step-up before mutation, [SECURITY] log after durable save", () => {
|
|
const postRoute = extractRoute(indexSource, 'app.post("/api/settings/alert"', 'app.delete("/api/settings/alert/:id"');
|
|
const tokenAt = postRoute.indexOf('requireActionTokenOr403(req, res, "POST /api/settings/alert")');
|
|
const validationAt = postRoute.indexOf('return res.status(400).json({ error: "Valid end date required" })');
|
|
const stepUpAt = postRoute.indexOf('requireDestructiveActionStepUp(req, res, user, "Global alert create")');
|
|
const mutateAt = postRoute.indexOf("addGlobalAlert(");
|
|
assert.ok(tokenAt >= 0 && validationAt >= 0 && stepUpAt >= 0 && mutateAt >= 0, "all anchors present");
|
|
assert.ok(tokenAt < validationAt && validationAt < stepUpAt && stepUpAt < mutateAt,
|
|
"order must be token -> validation -> step-up -> mutation");
|
|
assert.ok(postRoute.includes("sessionRevoke2faRateLimiter, async (req, res)"),
|
|
"the step-up limiter must be mounted");
|
|
const logAt = postRoute.indexOf("[SECURITY] Global alert created");
|
|
assert.ok(logAt > mutateAt, "the out-of-band security log follows a durable save");
|
|
assert.ok(postRoute.includes("actionTokens: buildAlertSettingsActionTokens(req)"),
|
|
"the success response re-mints tokens (including one for the new alert)");
|
|
});
|
|
|
|
test("alert DELETE: existence check BEFORE the one-time token check; challenge re-mints the spent token", () => {
|
|
const delRoute = extractRoute(indexSource, 'app.delete("/api/settings/alert/:id"', 'app.post("/api/settings/change-password"');
|
|
const existsAt = delRoute.indexOf('return res.status(404).json({ error: "Alert not found" })');
|
|
const tokenAt = delRoute.indexOf('requireActionTokenOr403(req, res, "DELETE /api/settings/alert/:id", { id: alertId })');
|
|
assert.ok(existsAt >= 0 && tokenAt >= 0 && existsAt < tokenAt,
|
|
"an unknown id must never consume the nonce of a matched token");
|
|
assert.ok(delRoute.includes("sessionRevoke2faRateLimiter, async (req, res)"));
|
|
assert.ok(delRoute.includes("failureResponseExtras"),
|
|
"step-up failures must carry a freshly minted replacement token");
|
|
assert.ok(delRoute.includes('[`deleteAlert_${alertId}`]: issueActionToken('),
|
|
"the re-mint is bound to the same alert id");
|
|
const logAt = delRoute.indexOf("[SECURITY] Global alert deleted");
|
|
assert.ok(logAt > delRoute.indexOf("deleteGlobalAlert(alertId)", tokenAt),
|
|
"the out-of-band security log follows a durable save");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Token refresh endpoint
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("action-tokens refresh endpoint covers branding, login-background and alert create", () => {
|
|
const refreshRoute = extractRoute(
|
|
indexSource,
|
|
'app.get("/api/settings/action-tokens"',
|
|
'app.post("/api/settings/maintenance"'
|
|
);
|
|
assert.ok(refreshRoute.includes('updateBranding: issueActionToken(req, "POST /api/admin/branding/update"'));
|
|
assert.ok(refreshRoute.includes('updateLoginBackground: issueActionToken(req, "POST /api/admin/login-background"'));
|
|
assert.ok(refreshRoute.includes('createAlert: issueActionToken(req, "POST /api/settings/alert"'));
|
|
// One-time per-resource tokens stay out of the refresh pool (same policy as
|
|
// the webhook delete tokens): they are minted by the section GET.
|
|
assert.ok(!refreshRoute.includes("deleteAlert_"), "per-alert delete tokens are not in the refresh pool");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Frontend — settings.js routes every write through the guarded flow
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("settings.js: branding save rides the guarded flow, no session-only fetch remains", () => {
|
|
assert.ok(settingsJsSource.includes("async function sendBrandingUpdateWithGuards(body)"),
|
|
"the guarded branding wrapper must exist");
|
|
const start = settingsJsSource.indexOf("async function sendBrandingUpdateWithGuards(body)");
|
|
const end = settingsJsSource.indexOf("async function saveBranding()");
|
|
assert.ok(end > start, "wrapper slice must be bounded");
|
|
const helper = settingsJsSource.slice(start, end);
|
|
assert.ok(helper.includes("'x-action-token': brandingActionTokens.updateBranding || ''"),
|
|
"the wrapper must send the updateBranding token");
|
|
assert.ok(helper.includes("/action token/i"),
|
|
"the wrapper must detect token rejections separately from step-up challenges");
|
|
assert.ok(helper.includes("await loadCurrentBranding();"),
|
|
"the token retry must refresh the branding section first");
|
|
assert.ok(helper.includes("sendGuardedRequestWithStepUp('/api/admin/branding/update', 'POST', body, requestCopy())"),
|
|
"the wrapper must delegate to the shared guarded sender");
|
|
assert.ok(!/fetch\('\/api\/admin\/branding\/update'/.test(settingsJsSource),
|
|
"no bare fetch to the branding write may remain");
|
|
});
|
|
|
|
test("settings.js: login-background save rides the guarded flow, no session-only fetch remains", () => {
|
|
assert.ok(settingsJsSource.includes("async function sendLoginBackgroundSaveWithGuards(body)"));
|
|
const start = settingsJsSource.indexOf("async function sendLoginBackgroundSaveWithGuards(body)");
|
|
const end = settingsJsSource.indexOf("if (openLoginBackgroundBtn)");
|
|
assert.ok(end > start, "wrapper slice must be bounded");
|
|
const helper = settingsJsSource.slice(start, end);
|
|
assert.ok(helper.includes("'x-action-token': loginBackgroundActionTokens.updateLoginBackground || ''"));
|
|
assert.ok(helper.includes("sendGuardedRequestWithStepUp('/api/admin/login-background', 'POST', body, requestCopy())"));
|
|
assert.ok(helper.includes("/action token/i"));
|
|
assert.ok(!/fetch\('\/api\/admin\/login-background',\s*\{[^}]*method/.test(settingsJsSource),
|
|
"no bare POST fetch to the login-background write may remain");
|
|
});
|
|
|
|
test("settings.js: alert writes ride the guarded flow with one-time delete token handling", () => {
|
|
assert.ok(settingsJsSource.includes("async function sendAlertCreateWithGuards(body)"));
|
|
assert.ok(settingsJsSource.includes("async function sendAlertDeleteWithGuards(id)"));
|
|
const delStart = settingsJsSource.indexOf("async function sendAlertDeleteWithGuards(id)");
|
|
const delEnd = settingsJsSource.indexOf("async function deleteAlert(id)");
|
|
assert.ok(delEnd > delStart, "alert delete wrapper slice must be bounded");
|
|
const delHelper = settingsJsSource.slice(delStart, delEnd);
|
|
assert.ok(delHelper.includes("const tokenKey = `deleteAlert_${id}`"),
|
|
"the delete wrapper resolves the per-id one-time token");
|
|
assert.ok(delHelper.includes("onStepUpChallenge: (data) => {"),
|
|
"the wrapper hooks the step-up challenge");
|
|
assert.ok(delHelper.includes("data?.actionTokens?.[tokenKey]"),
|
|
"the hook stashes the challenge's re-minted token so the in-modal retry does not dead-end");
|
|
assert.ok(delHelper.includes("copy.headers['x-action-token'] = fresh"),
|
|
"the fresh token must ride the in-modal retry");
|
|
assert.ok(delHelper.includes("encodeURIComponent(id)"),
|
|
"the alert id must be URL-encoded in the delete path");
|
|
// The old bare session-only writes must not come back.
|
|
assert.ok(!/fetch\('\/api\/settings\/alert\/'\s*\+\s*id/.test(settingsJsSource),
|
|
"no bare fetch to the alert delete may remain");
|
|
assert.ok(!/fetch\('\/api\/settings\/alert',\s*\{[^}]*method: 'POST'/.test(settingsJsSource),
|
|
"no bare fetch to the alert create may remain");
|
|
// loadAlerts consumes the new response shape and stores tokens.
|
|
const loadAt = settingsJsSource.indexOf("function loadAlerts()");
|
|
assert.ok(loadAt >= 0, "loadAlerts must exist");
|
|
const loadSlice = settingsJsSource.slice(loadAt, settingsJsSource.indexOf("async function sendAlertCreateWithGuards"));
|
|
assert.ok(loadSlice.includes("Array.isArray(data.alerts)"), "loadAlerts reads the alerts array");
|
|
assert.ok(loadSlice.includes("data.actionTokens"), "loadAlerts stores the minted tokens");
|
|
assert.ok(loadSlice.includes("cache: 'no-store'"), "the token-bearing GET is fetched uncacheable");
|
|
});
|
|
|
|
test("settings.ejs: the cache-buster is bumped so browsers cannot keep the session-only UI", () => {
|
|
assert.ok(settingsEjsSource.includes("/js/settings.js?v=20261117-account-identity1"),
|
|
"views/settings.ejs must reference the updated settings.js version");
|
|
assert.ok(!settingsEjsSource.includes("/js/settings.js?v=20260927-adminstepup1"),
|
|
"the pre-identity bundle cache-buster must not remain");
|
|
const targetHelper = settingsEjsSource.indexOf('src="/js/settings-account-targets.js?');
|
|
const settingsBundle = settingsEjsSource.indexOf('src="/js/settings.js?');
|
|
assert.ok(targetHelper >= 0 && targetHelper < settingsBundle,
|
|
"the account-target helper must load before the settings bundle that uses it");
|
|
assert.ok(!settingsEjsSource.includes("/js/settings.js?v=20260919-webhooktokenretry1"),
|
|
"the stale cache-buster must not remain");
|
|
assert.ok(!settingsEjsSource.includes("/js/settings.js?v=20260908-create2fa-policy1"),
|
|
"the stale cache-buster must not remain");
|
|
});
|
|
|
|
test("settings.ejs: customization sections (branding, login background, global alert) are all admin-gated", () => {
|
|
const custStart = settingsEjsSource.indexOf('<div id="customization"');
|
|
assert.ok(custStart >= 0, "customization panel must exist");
|
|
const custEnd = settingsEjsSource.indexOf('id="account"', custStart);
|
|
assert.ok(custEnd > custStart, "customization panel end must be found");
|
|
const custBlock = settingsEjsSource.slice(custStart, custEnd);
|
|
|
|
const gateRegex = /<% if \(user && user\.admin\) \{ %>([\s\S]*?)<% } %>/;
|
|
const match = custBlock.match(gateRegex);
|
|
assert.ok(match, "customization panel must have a user.admin gate");
|
|
|
|
const gatedContent = match[1];
|
|
assert.ok(gatedContent.includes('id="openBrandingBtn"'), "branding button must be inside the admin gate");
|
|
assert.ok(gatedContent.includes('id="openLoginBackgroundBtn"'), "login background button must be inside the admin gate");
|
|
assert.ok(gatedContent.includes('id="openAlertModalBtn"'), "alert modal button must be inside the admin gate");
|
|
|
|
const beforeGate = custBlock.slice(0, match.index);
|
|
assert.ok(!beforeGate.includes('id="openBrandingBtn"'), "branding button must not be outside the admin gate");
|
|
assert.ok(!beforeGate.includes('id="openLoginBackgroundBtn"'), "login background button must not be outside the admin gate");
|
|
assert.ok(!beforeGate.includes('id="openAlertModalBtn"'), "alert button must not be outside the admin gate");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// SVG sanitizer architecture + by-construction serving headers
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("svg-sanitizer is parse-and-rebuild on a vetted parser, not a regex filter", () => {
|
|
assert.ok(sanitizerSource.includes('require("@xmldom/xmldom")'),
|
|
"parsing must go through the vetted @xmldom/xmldom dependency");
|
|
assert.ok(sanitizerSource.includes("package.json") || true);
|
|
assert.ok(/@xmldom\/xmldom/.test(fs.readFileSync(path.join(ROOT, "package.json"), "utf8")),
|
|
"the parser must be a declared dependency, not an ambient module");
|
|
// Parse -> validate -> REBUILD: output is re-serialized from validated
|
|
// names/values, never echoed input.
|
|
assert.ok(sanitizerSource.includes("function rebuildNode("), "the rebuild walker must exist");
|
|
assert.ok(sanitizerSource.includes("function escapeXmlText(") && sanitizerSource.includes("function escapeXmlAttr("),
|
|
"all emitted text/attribute values must pass through escaping");
|
|
// Strict well-formedness + upfront DTD rejection.
|
|
assert.ok(sanitizerSource.includes("parseErrors.length > 0"), "any parser diagnostic rejects the document");
|
|
assert.ok(sanitizerSource.includes("/<!DOCTYPE/i"), "DOCTYPE is rejected outright");
|
|
assert.ok(sanitizerSource.includes("/<!ENTITY/i"), "entity declarations are rejected outright");
|
|
// DoS bounds.
|
|
assert.ok(sanitizerSource.includes("MAX_ELEMENT_COUNT") && sanitizerSource.includes("MAX_TREE_DEPTH"),
|
|
"element-count and nesting-depth caps must exist");
|
|
// Namespace repair injects only a compile-time-constant declaration.
|
|
assert.ok(sanitizerSource.includes('XLINK_NS_DECL = \' xmlns:xlink="http://www.w3.org/1999/xlink"\''),
|
|
"the xlink namespace repair must inject a fixed literal");
|
|
// The final re-scan stays: a hit means a rebuild bug — fail closed.
|
|
assert.ok(sanitizerSource.includes("prohibited tokens detected in final output"));
|
|
});
|
|
|
|
test("every SVG response gets the sandbox CSP + nosniff by construction", () => {
|
|
// The res.setHeader guard is installed immediately after app creation, in
|
|
// front of every route and static handler.
|
|
const guardAt = indexSource.indexOf("setHeaderWithSvgGuard");
|
|
const appAt = indexSource.indexOf("const app = express();");
|
|
const helmetAt = indexSource.indexOf("app.use(\n helmet({");
|
|
assert.ok(guardAt >= 0 && appAt >= 0, "the SVG header guard must exist");
|
|
assert.ok(guardAt > appAt && guardAt < helmetAt,
|
|
"the guard must be mounted before helmet and every route/static handler");
|
|
const guardSlice = indexSource.slice(guardAt - 400, guardAt + 900);
|
|
assert.ok(/image\\\/svg/i.test(guardSlice), "the guard triggers on image/svg content types");
|
|
assert.ok(guardSlice.includes("default-src 'none'; sandbox"), "the guard applies the sandbox CSP");
|
|
assert.ok(guardSlice.includes("nosniff"), "the guard applies nosniff");
|
|
// The explicit helper remains for the paths that call it (belt-and-braces).
|
|
assert.ok(indexSource.includes("function applySvgContentSecurityHeaders(res"));
|
|
});
|