Files
co-lite/solvway-admin-portal/app/lib/security/noHtmlInjection.sweep.test.ts
T
ngqileandClaude Opus 5.5 bb2c5c5db7 feat(portal): landing pages list, editor, preview and public page
Pages list and Tiptap editor (ported from babyboo) with image upload on
save, the FORM event picker, field errors at their fields, delete
confirmation, unsaved-edits guard and a draft preview. The public page
/p/<company>/<slug> renders on the server with metadata, sanitize-html,
the company's logo and accent, and the sign-up form with UTM tags.
Companies get branding; the event lead detail shows the web page and
campaign. Labels in English and Chinese.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 16:30:54 +08:00

144 lines
5.6 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[]> = {
// shadcn chart: a <style> built from the chart's own colour config (code constants), never from data.
"components/ui/chart.tsx": ["dangerouslySetInnerHTML"],
// add-landing-pages design decision 8: page authors' rich text, run through sanitize-html with a fixed allow-list
// (pageHtml.ts: no scripts, handlers, iframes, images or styles beyond text-align) on the server render.
"components/pages/SafeHtml.tsx": ["dangerouslySetInnerHTML"],
};
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);
});
});