diff --git a/craft/src/utils/sandboxed-preview.test.ts b/craft/src/utils/sandboxed-preview.test.ts index 1d81b8d..d309123 100644 --- a/craft/src/utils/sandboxed-preview.test.ts +++ b/craft/src/utils/sandboxed-preview.test.ts @@ -74,9 +74,61 @@ describe('no same-origin path for composed-page HTML remains in the source', () // never mention allow-scripts), fed only sanitizeCaptureHtml output, CSP-locked, and allow-same-origin is // there only so html-to-image can read the frame's layout. See sanitize-capture-html.test.ts and // scripts/e2e-capture-security.mjs for the hostile-page proof. - if (f.endsWith('self-review-capture.ts')) return /allow-scripts/.test(src.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, '')) || !/sanitizeCaptureHtml\(/.test(src); + if (f.endsWith('self-review-capture.ts')) return captureFileViolations(src).length > 0; return /srcdoc/i.test(src) && /allow-same-origin['"\s]/.test(src.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, '')); }); expect(offenders.map((f) => f.slice(root.length + 1))).toEqual([]); }); }); + +/** + * The rules the ONE sanctioned allow-same-origin srcdoc frame (utils/self-review-capture.ts) must keep + * (G7). Returns the broken rules; [] = compliant. Applied to the real source below, and to mutated copies + * of it so we know each rule actually bites. + * 1. The frame's sandbox is set exactly once, to exactly "allow-same-origin" (no allow-scripts / forms / + * popups / modals / top-navigation, no DOMTokenList .add, no .sandbox = assignment, no removeAttribute). + * 2. The string allow-scripts appears nowhere in code. + * 3. srcdoc is assigned exactly once, and only from inlineResources(clean.html, ...) -- the sanitiser output. + * 4. sanitizeCaptureHtml( is called, its result is checked (`!clean.ok` rejects), and that happens BEFORE + * the srcdoc assignment. + * 5. The frame is not given a src= (which would bypass srcdoc + the sanitiser). + */ +export function captureFileViolations(raw: string): string[] { + const src = raw.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, ''); + const v: string[] = []; + const sandboxSets = Array.from(src.matchAll(/setAttribute\(\s*['"]sandbox['"]\s*,\s*(['"`])([^'"`]*)\1\s*\)/g)).map((m) => m[2]); + if (sandboxSets.length !== 1 || sandboxSets[0].trim() !== 'allow-same-origin') v.push('sandbox must be set once, to exactly "allow-same-origin"'); + if (/\.sandbox\s*(\.\s*(add|toggle|replace|value)\b|=)/.test(src) || /removeAttribute\(\s*['"]sandbox['"]/.test(src)) v.push('sandbox changed outside the one setAttribute'); + if (/allow-scripts|allow-forms|allow-popups|allow-modals|allow-top-navigation/.test(src)) v.push('a script/form/popup/navigation sandbox token appears'); + const srcdocSets = Array.from(src.matchAll(/\.srcdoc\s*=\s*([^;\n]+)/g)).map((m) => m[1].trim()); + if (srcdocSets.length !== 1) v.push('srcdoc must be assigned exactly once'); + const inl = /inlineResources\(\s*clean\.html\s*,[^)]*\)\.then\(\s*\(\s*(\w+)\s*\)\s*=>/.exec(src); + if (!inl || srcdocSets[0] !== inl[1]) v.push('srcdoc must come only from inlineResources(clean.html, ..)'); + const san = src.search(/const\s+clean\s*=\s*sanitizeCaptureHtml\(/); + const chk = src.search(/if\s*\(\s*!clean\.ok\s*\)/); + const set = src.search(/\.srcdoc\s*=/); + if (san < 0 || chk < 0 || !(san < chk && chk < set)) v.push('sanitizeCaptureHtml must run and be checked before srcdoc is set'); + if (/\.src\s*=|setAttribute\(\s*['"]src['"]/.test(src.replace(/img\.setAttribute\(\s*'src'[^)]*\)/g, ''))) v.push('frame must not get a src='); + return v; +} + +describe('G7: the self-review capture frame exception stays narrow', () => { + const capture = Object.entries(import.meta.glob(['./self-review-capture.ts'], { query: '?raw', import: 'default', eager: true }) as Record)[0][1]; + test('the real capture source complies', () => { + expect(captureFileViolations(capture)).toEqual([]); + }); + test.each([ + ['adds allow-scripts to the sandbox', (s: string) => s.replace("setAttribute('sandbox', 'allow-same-origin')", "setAttribute('sandbox', 'allow-same-origin allow-scripts')")], + ['adds allow-scripts via DOMTokenList', (s: string) => s.replace("frame.setAttribute('aria-hidden'", "(frame as any).sandbox.add('x'); frame.setAttribute('aria-hidden'")], + ['adds allow-forms', (s: string) => s.replace("'allow-same-origin')", "'allow-same-origin allow-forms')")], + ['drops the sandbox entirely', (s: string) => s.replace("frame.setAttribute('sandbox', 'allow-same-origin');", '')], + ['skips the sanitiser (raw html into srcdoc)', (s: string) => s.replace('frame.srcdoc = inlined;', 'frame.srcdoc = html;')], + ['sanitises but ignores the verdict', (s: string) => s.replace(/if \(!clean\.ok\) \{[^}]*\}/, '')], + ['never calls the sanitiser', (s: string) => s.replace(/const clean = sanitizeCaptureHtml\([^;]*;/, 'const clean = { ok: true as const, html, csp: "" };')], + ['loads the page by src=', (s: string) => s.replace('frame.srcdoc = inlined;', 'frame.srcdoc = inlined; frame.src = url;')], + ])('the guard FAILS when capture %s', (_label, mutate) => { + const mutated = mutate(capture); + expect(mutated).not.toBe(capture); + expect(captureFileViolations(mutated).length).toBeGreaterThan(0); + }); +}); diff --git a/craft/src/utils/self-review-capture.frame.test.ts b/craft/src/utils/self-review-capture.frame.test.ts new file mode 100644 index 0000000..f7c27ff --- /dev/null +++ b/craft/src/utils/self-review-capture.frame.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, test, vi } from 'vitest'; +import { captureHtml } from './self-review-capture'; + +/** + * G7 behavioural half: run the real captureHtml on a hostile page and inspect the frame it actually + * builds (jsdom never loads it, so the call ends on its time limit -- that is fine, the frame is what + * we look at). The source-level rules live in sandboxed-preview.test.ts (captureFileViolations). + */ +describe('self-review capture frame (G7)', () => { + test('hostile page: script-less sandbox, sanitised srcdoc, CSP meta first in head', async () => { + const hostile = '' + + '' + + 'x' + + '
' + + '
t

Hello

'; + let frame: HTMLIFrameElement | null = null; + const orig = document.body.appendChild.bind(document.body); + const spy = vi.spyOn(document.body, 'appendChild').mockImplementation((n: T): T => { + if (n instanceof HTMLIFrameElement) frame = n; + return orig(n); + }); + try { + const res = await captureHtml(hostile, { timeoutMs: 400, settleMs: 0, injectFontAwesome: false }); + expect(res.ok).toBe(false); + } finally { spy.mockRestore(); } + expect(frame).not.toBeNull(); + const f = frame!; + expect(f.getAttribute('sandbox')).toBe('allow-same-origin'); + const doc = f.srcdoc; + expect(doc).toContain('Hello'); + for (const bad of ['