Files
co-lite/solvway-admin-portal/app/lib/security/noHtmlInjection.sweep.test.ts
T
ngqileandClaude Opus 5.5 5ee51d1913 chore: copy kept Tastefully modules and portals into Co-Lite
Backend modules from tastefully 8bd93d15: core-libs, core-session,
api-gateway, mobile-api, services-auth, services-system,
services-counter, services-member, services-log, services-email.
solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal
from tastefully 8bd93d15. Copied as tracked files only.

Literal secrets replaced with environment placeholders:
- services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY,
  MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default)
- services-system: JUMIO_TOKEN, JUMIO_SECRET (optional)
- services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed
- core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default
  removed, ipgeolocation key read from IPGEOLOCATION_API_KEY
- services-system EkycAppConfig: commented Jumio credentials removed

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

151 lines
5.8 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 (email bodies, templates) 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, no data.
"components/ui/chart.tsx": ["dangerouslySetInnerHTML"],
// POS gift-card slip: a print popup. Catalog text is HTML-escaped (tx); the code, amount and expiry come from the
// sell response and the storefront origin from config.
"pos/_components/SellGiftCardDialog.tsx": ["document.write"],
};
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(50);
});
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([]);
});
it("finds the iframes that exist, so the check is not vacuous", () => {
const withIframes = files.filter((f) => /<iframe\b/.test(f.src)).map((f) => f.rel);
expect(withIframes).toEqual(
expect.arrayContaining(["email-templates/TemplatePreviewPane.tsx", "email-templates/logs/[id]/page.tsx"]),
);
});
});
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);
});
});