Files
co-lite/solvway-admin-portal/app/lib/security/noHtmlInjection.sweep.test.ts
T
ngqileandClaude Opus 5.5 1071ddaa2a feat(admin-portal): cut babyboo portal down to Co-Lite login, users and roles
Removes every other screen, API route, component, test and the dependencies only
they used. Cookie colite_admin, Co-Lite branding, BO_USERS/BO_ROLES modules only.
The user form no longer loads branches, events or country scope.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-26 21:24:30 +08:00

138 lines
5.1 KiB
TypeScript

import { describe, it, expect } from "vitest";
import fs from "node:fs";
import path from "node:path";
import ts from "typescript";
// Spec (admin-portal-markup-safety), security finding F09: the admin portal never injects HTML into its own origin.
// Data HTML goes into <iframe sandbox="" srcDoc>. Allow-listing a file here is a security
// decision for review: only code-generated or escaped content may be injected, and the reason is written down.
const APP_DIR = path.resolve(__dirname, "..", "..");
const HTML_SINKS = [
"dangerouslySetInnerHTML",
"innerHTML",
"outerHTML",
"insertAdjacentHTML",
"document.write",
"createContextualFragment",
] as const;
type Sink = (typeof HTML_SINKS)[number];
const SINK_ALLOWED: Record<string, Sink[]> = {};
function sourceFiles(dir: string, out: string[] = []): string[] {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
if (entry.name === "node_modules" || entry.name === ".next") continue;
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
sourceFiles(full, out);
} else if (/\.(ts|tsx)$/.test(entry.name) && !/\.test\.tsx?$/.test(entry.name)) {
out.push(full);
}
}
return out;
}
/**
* Problems with iframes in one source file: every <iframe> must carry the literal sandbox="" and no spread props
* (a spread could override the sandbox), and iframes must not be created imperatively.
*/
function iframeProblems(fileName: string, src: string): string[] {
const problems: string[] = [];
const sf = ts.createSourceFile(fileName, src, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const visit = (node: ts.Node) => {
if (
(ts.isJsxSelfClosingElement(node) || ts.isJsxOpeningElement(node)) &&
node.tagName.getText(sf) === "iframe"
) {
const line = sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;
const props = node.attributes.properties;
if (props.some(ts.isJsxSpreadAttribute)) problems.push(`${fileName}:${line} iframe with spread props`);
const sandbox = props.find(
(p): p is ts.JsxAttribute => ts.isJsxAttribute(p) && p.name.getText(sf) === "sandbox",
);
const value = sandbox?.initializer;
if (!value || !ts.isStringLiteral(value) || value.text !== "") {
problems.push(`${fileName}:${line} iframe without sandbox=""`);
}
}
if (
ts.isCallExpression(node) &&
node.expression.getText(sf).endsWith("createElement") &&
node.arguments[0] &&
ts.isStringLiteral(node.arguments[0]) &&
node.arguments[0].text.toLowerCase() === "iframe"
) {
const line = sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;
problems.push(`${fileName}:${line} iframe created imperatively`);
}
ts.forEachChild(node, visit);
};
visit(sf);
return problems;
}
const files = sourceFiles(APP_DIR).map((f) => ({
rel: path.relative(APP_DIR, f).split(path.sep).join("/"),
src: fs.readFileSync(f, "utf8"),
}));
describe("admin portal never injects HTML into its own origin", () => {
it("scans real source files", () => {
expect(files.length).toBeGreaterThan(20);
});
it("uses HTML sinks only where allow-listed", () => {
const offenders: string[] = [];
for (const f of files) {
for (const sink of HTML_SINKS) {
if (f.src.includes(sink) && !(SINK_ALLOWED[f.rel] ?? []).includes(sink)) offenders.push(`${f.rel}: ${sink}`);
}
}
expect(offenders).toEqual([]);
});
it("keeps the allow-list honest: every listed file still exists and still uses its sink", () => {
for (const [rel, sinks] of Object.entries(SINK_ALLOWED)) {
const file = files.find((f) => f.rel === rel);
expect(file, rel).toBeDefined();
for (const sink of sinks) expect(file!.src.includes(sink), `${rel}: ${sink}`).toBe(true);
}
});
it("gives every iframe a literal empty sandbox", () => {
const problems = files.flatMap((f) => iframeProblems(f.rel, f.src));
expect(problems).toEqual([]);
});
});
describe("iframe checker", () => {
const check = (jsx: string) => iframeProblems("fixture.tsx", `export const X = () => ${jsx};`);
it("accepts a literal empty sandbox", () => {
expect(check(`<iframe title="t" sandbox="" srcDoc={html} />`)).toEqual([]);
});
it("is not fooled by '>' inside an attribute expression", () => {
expect(check(`<iframe onLoad={() => a > b} srcDoc={html} />`)).toHaveLength(1);
});
it("rejects a spread that could override the sandbox", () => {
expect(check(`<iframe sandbox="" {...props} srcDoc={html} />`)).toHaveLength(1);
});
it("rejects a non-empty or computed sandbox", () => {
expect(check(`<iframe sandbox="allow-scripts" srcDoc={html} />`)).toHaveLength(1);
expect(check(`<iframe sandbox={mode} srcDoc={html} />`)).toHaveLength(1);
});
it("rejects an unsandboxed frame loading a blob or any other src", () => {
expect(check(`<iframe src={URL.createObjectURL(blob)} />`)).toHaveLength(1);
});
it("rejects iframes created imperatively", () => {
expect(check(`React.createElement("iframe", { srcDoc: html })`)).toHaveLength(1);
expect(check(`document.createElement("iframe")`)).toHaveLength(1);
});
});