Merge PR #4: head code to published pages + adversarial-review Minors
This commit was merged in pull request #4.
This commit is contained in:
@@ -21,3 +21,46 @@ describe('purifyHtml', () => {
|
|||||||
expect(purifyHtml('<form><input name="x"></form>')).not.toContain('<form');
|
expect(purifyHtml('<form><input name="x"></form>')).not.toContain('<form');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('purifyHtml iframe sandboxing (M-6)', () => {
|
||||||
|
test('forces a restrictive sandbox attribute onto every iframe', () => {
|
||||||
|
const out = purifyHtml('<iframe src="https://example.com/"></iframe>');
|
||||||
|
expect(out).toMatch(/<iframe[^>]*\bsandbox="[^"]+"/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('sandbox value omits allow-top-navigation (no top-level nav escape)', () => {
|
||||||
|
const out = purifyHtml('<iframe src="https://example.com/"></iframe>');
|
||||||
|
const sandbox = out.match(/sandbox="([^"]*)"/)![1];
|
||||||
|
expect(sandbox).not.toMatch(/allow-top-navigation/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('legitimate embeds (YouTube) still work and get sandboxed too', () => {
|
||||||
|
const out = purifyHtml('<iframe src="https://www.youtube.com/embed/abc" allowfullscreen></iframe>');
|
||||||
|
expect(out).toContain('youtube.com/embed/abc');
|
||||||
|
expect(out).toMatch(/<iframe[^>]*\bsandbox="[^"]+"/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('adds referrerpolicy=no-referrer to iframes', () => {
|
||||||
|
const out = purifyHtml('<iframe src="https://example.com/"></iframe>');
|
||||||
|
expect(out).toContain('referrerpolicy="no-referrer"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('script/on* attributes are still stripped alongside the sandboxed iframe', () => {
|
||||||
|
const out = purifyHtml('<iframe src="https://example.com/" onload="alert(1)"></iframe><script>alert(2)</script>');
|
||||||
|
expect(out).not.toContain('onload');
|
||||||
|
expect(out).not.toContain('<script');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('repeated calls do not leak/accumulate the hook (no duplicate sandbox attr, no cross-call state)', () => {
|
||||||
|
purifyHtml('<iframe src="https://a.example/"></iframe>');
|
||||||
|
purifyHtml('<iframe src="https://b.example/"></iframe>');
|
||||||
|
const out = purifyHtml('<iframe src="https://c.example/"></iframe>');
|
||||||
|
const sandboxMatches = out.match(/sandbox="/g) || [];
|
||||||
|
expect(sandboxMatches.length).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a non-iframe element sanitized alongside an iframe is not touched by the hook', () => {
|
||||||
|
const out = purifyHtml('<p>hi</p><iframe src="https://example.com/"></iframe>');
|
||||||
|
expect(out).toContain('<p>hi</p>');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -24,14 +24,42 @@ const PURIFY_CONFIG = {
|
|||||||
'href','src','alt','title','target','rel',
|
'href','src','alt','title','target','rel',
|
||||||
'width','height','class',
|
'width','height','class',
|
||||||
'allowfullscreen','allow','frameborder',
|
'allowfullscreen','allow','frameborder',
|
||||||
|
'sandbox','referrerpolicy',
|
||||||
],
|
],
|
||||||
ALLOWED_URI_REGEXP: /^(?:(?:https?|mailto|tel|data:image\/[a-z]+;base64,):|[^a-z]|[a-z+.-]+(?:[^a-z+.\-:]|$))/i,
|
ALLOWED_URI_REGEXP: /^(?:(?:https?|mailto|tel|data:image\/[a-z]+;base64,):|[^a-z]|[a-z+.-]+(?:[^a-z+.\-:]|$))/i,
|
||||||
FORBID_TAGS: ['script','style','object','embed','link','meta','form','input','button','select','textarea'],
|
FORBID_TAGS: ['script','style','object','embed','link','meta','form','input','button','select','textarea'],
|
||||||
FORBID_ATTR: [/^on/i],
|
FORBID_ATTR: [/^on/i],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// M-6: `<iframe>` is allowed (maps/video embeds are a legitimate use case)
|
||||||
|
// but an iframe with a `src` and NO `sandbox` attribute is a clickjacking/
|
||||||
|
// phishing vector (DOMPurify already strips <script>/on*=, but an
|
||||||
|
// unsandboxed iframe still gets full script execution, same-origin-ish
|
||||||
|
// access via document.domain tricks, top-level navigation, etc., inside
|
||||||
|
// itself). This hook force-sets a restrictive sandbox on every iframe that
|
||||||
|
// survives sanitization, keeping `allow-scripts`/`allow-same-origin`/
|
||||||
|
// `allow-popups`/`allow-forms` (needed for interactive maps/video/oauth
|
||||||
|
// popups) but deliberately omitting `allow-top-navigation` so an embedded
|
||||||
|
// page can never redirect/hijack the parent tab.
|
||||||
|
const IFRAME_SANDBOX_HOOK = (node: Element): void => {
|
||||||
|
if (node.nodeName === 'IFRAME') {
|
||||||
|
node.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-popups allow-forms');
|
||||||
|
node.setAttribute('referrerpolicy', 'no-referrer');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
export function purifyHtml(input: string): string {
|
export function purifyHtml(input: string): string {
|
||||||
|
// Hook is added immediately before sanitize() and removed immediately
|
||||||
|
// after, scoped tightly to this single call -- so it can never leak onto
|
||||||
|
// (or accumulate duplicate copies across) any other DOMPurify.sanitize()
|
||||||
|
// call elsewhere in the app, and repeated purifyHtml() calls never stack
|
||||||
|
// multiple copies of the same hook.
|
||||||
|
DOMPurify.addHook('afterSanitizeAttributes', IFRAME_SANDBOX_HOOK);
|
||||||
|
try {
|
||||||
return DOMPurify.sanitize(input || '', PURIFY_CONFIG as any) as unknown as string;
|
return DOMPurify.sanitize(input || '', PURIFY_CONFIG as any) as unknown as string;
|
||||||
|
} finally {
|
||||||
|
DOMPurify.removeHook('afterSanitizeAttributes', IFRAME_SANDBOX_HOOK as any);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const HtmlBlock: UserComponent<HtmlBlockProps> = ({ code = '', style = {} }) => {
|
export const HtmlBlock: UserComponent<HtmlBlockProps> = ({ code = '', style = {} }) => {
|
||||||
|
|||||||
@@ -5,28 +5,84 @@ const toHtml = (Navbar as any).toHtml;
|
|||||||
|
|
||||||
describe('Navbar.toHtml hamburger accessibility (F2.3)', () => {
|
describe('Navbar.toHtml hamburger accessibility (F2.3)', () => {
|
||||||
test('mobile toggle button has an accessible name, aria-expanded, and aria-controls', () => {
|
test('mobile toggle button has an accessible name, aria-expanded, and aria-controls', () => {
|
||||||
const { html } = toHtml({ showMobileMenu: true }, '');
|
const { html } = toHtml({ showMobileMenu: true }, '', 'node-nav1');
|
||||||
expect(html).toMatch(/class="navbar-hamburger"[^>]*aria-label="Toggle navigation menu"/);
|
expect(html).toMatch(/class="navbar-hamburger"[^>]*aria-label="Toggle navigation menu"/);
|
||||||
expect(html).toMatch(/aria-expanded="false"/);
|
expect(html).toMatch(/aria-expanded="false"/);
|
||||||
expect(html).toMatch(/aria-controls="navbar-links"/);
|
expect(html).toMatch(/aria-controls="[^"]+"/);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('aria-controls target id exists on the links container', () => {
|
test('aria-controls target id exists on the links container', () => {
|
||||||
const { html } = toHtml({ showMobileMenu: true }, '');
|
const { html } = toHtml({ showMobileMenu: true }, '', 'node-nav1');
|
||||||
expect(html).toContain('id="navbar-links"');
|
const controls = html.match(/aria-controls="([^"]+)"/)![1];
|
||||||
|
expect(html).toContain(`id="${controls}"`);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('toggle script flips aria-expanded on click', () => {
|
test('toggle script flips aria-expanded on click', () => {
|
||||||
const { html } = toHtml({ showMobileMenu: true }, '');
|
const { html } = toHtml({ showMobileMenu: true }, '', 'node-nav1');
|
||||||
expect(html).toMatch(/setAttribute\(['"]aria-expanded['"]/);
|
expect(html).toMatch(/setAttribute\(['"]aria-expanded['"]/);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('no mobile menu: no hamburger button emitted', () => {
|
test('no mobile menu: no hamburger button emitted', () => {
|
||||||
const { html } = toHtml({ showMobileMenu: false }, '');
|
const { html } = toHtml({ showMobileMenu: false }, '', 'node-nav1');
|
||||||
expect(html).not.toContain('navbar-hamburger');
|
expect(html).not.toContain('navbar-hamburger');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('Navbar.toHtml node-scoped ids/hover styles (M-1: two navbars must not collide)', () => {
|
||||||
|
test('no bare unscoped id="navbar-links" is emitted', () => {
|
||||||
|
const { html } = toHtml({ showMobileMenu: true }, '', 'node-nav1');
|
||||||
|
expect(html).not.toContain('id="navbar-links"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('two different node ids produce different links-container ids', () => {
|
||||||
|
const { html: html1 } = toHtml({ showMobileMenu: true }, '', 'node-nav1');
|
||||||
|
const { html: html2 } = toHtml({ showMobileMenu: true }, '', 'node-nav2');
|
||||||
|
const id1 = html1.match(/id="([^"]+)"/)![1];
|
||||||
|
const id2 = html2.match(/id="([^"]+)"/)![1];
|
||||||
|
expect(id1).not.toBe(id2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('aria-controls always equals the actual links-container id', () => {
|
||||||
|
const { html } = toHtml({ showMobileMenu: true }, '', 'node-nav1');
|
||||||
|
const controls = html.match(/aria-controls="([^"]+)"/)![1];
|
||||||
|
const linksId = html.match(/id="([^"]+)"/)![1];
|
||||||
|
expect(controls).toBe(linksId);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('hover style selectors are scoped per-instance, not bare .navbar-link/.navbar-cta', () => {
|
||||||
|
const { html } = toHtml({ hoverColor: '#ff0000' }, '', 'node-nav1');
|
||||||
|
// A selector rule that STARTS the line with .navbar-link:hover (i.e. not
|
||||||
|
// preceded by a per-instance ancestor class) would be the old, unscoped,
|
||||||
|
// globally-colliding form.
|
||||||
|
expect(html).not.toMatch(/^\s*\.navbar-link:hover/m);
|
||||||
|
expect(html).not.toMatch(/^\s*\.navbar-cta:hover/m);
|
||||||
|
// still present, just scoped under a per-instance ancestor class
|
||||||
|
expect(html).toMatch(/\.navbar-link:hover/);
|
||||||
|
expect(html).toMatch(/\.[\w-]+ \.navbar-link:hover/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('two navbars with different hoverColor do not leak style onto each other (scoped selectors differ)', () => {
|
||||||
|
const { html: html1 } = toHtml({ hoverColor: '#ff0000' }, '', 'node-nav1');
|
||||||
|
const { html: html2 } = toHtml({ hoverColor: '#00ff00' }, '', 'node-nav2');
|
||||||
|
const scope1 = html1.match(/<style>\s*\.([\w-]+)\s/)![1];
|
||||||
|
const scope2 = html2.match(/<style>\s*\.([\w-]+)\s/)![1];
|
||||||
|
expect(scope1).not.toBe(scope2);
|
||||||
|
expect(html1).toContain(`.${scope1} .navbar-link:hover`);
|
||||||
|
expect(html2).toContain(`.${scope2} .navbar-link:hover`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a normal single navbar still renders its hover style (visual output preserved)', () => {
|
||||||
|
const { html } = toHtml({ hoverColor: '#ff0000' }, '', 'node-nav1');
|
||||||
|
expect(html).toMatch(/:hover\s*\{\s*color:\s*#ff0000/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('same node id -> identical output across calls (deterministic)', () => {
|
||||||
|
const { html: html1 } = toHtml({ showMobileMenu: true }, '', 'node-nav1');
|
||||||
|
const { html: html2 } = toHtml({ showMobileMenu: true }, '', 'node-nav1');
|
||||||
|
expect(html1).toBe(html2);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('Navbar.toHtml XSS hardening (hoverColor/backgroundColor/ctaColor into <style>)', () => {
|
describe('Navbar.toHtml XSS hardening (hoverColor/backgroundColor/ctaColor into <style>)', () => {
|
||||||
test('a hoverColor value containing </style><script> is neutralized in the hover <style> block', () => {
|
test('a hoverColor value containing </style><script> is neutralized in the hover <style> block', () => {
|
||||||
const malicious = '#fff}</style><script>alert(1)</script><style>{';
|
const malicious = '#fff}</style><script>alert(1)</script><style>{';
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import React, { CSSProperties, useState } from 'react';
|
|||||||
import { useNode, UserComponent } from '@craftjs/core';
|
import { useNode, UserComponent } from '@craftjs/core';
|
||||||
import { cssPropsToString } from '../../utils/style-helpers';
|
import { cssPropsToString } from '../../utils/style-helpers';
|
||||||
import { useSiteDesign } from '../../state/SiteDesignContext';
|
import { useSiteDesign } from '../../state/SiteDesignContext';
|
||||||
import { escapeHtml, escapeAttr, safeUrl, cssValue } from '../../utils/escape';
|
import { escapeHtml, escapeAttr, safeUrl, cssValue, scopeId } from '../../utils/escape';
|
||||||
|
|
||||||
/* ---------- Types ---------- */
|
/* ---------- Types ---------- */
|
||||||
|
|
||||||
@@ -210,7 +210,7 @@ Navbar.craft = {
|
|||||||
|
|
||||||
/* ---------- HTML export ---------- */
|
/* ---------- HTML export ---------- */
|
||||||
|
|
||||||
(Navbar as any).toHtml = (props: NavbarProps, _childrenHtml: string) => {
|
(Navbar as any).toHtml = (props: NavbarProps, _childrenHtml: string, nodeId?: string) => {
|
||||||
// Sanitized once here -- these are raw string-interpolation sinks below
|
// Sanitized once here -- these are raw string-interpolation sinks below
|
||||||
// (hoverCol/bgColor go into a <style> block, the worst case: </style>
|
// (hoverCol/bgColor go into a <style> block, the worst case: </style>
|
||||||
// breakout -> arbitrary <script>), see task-cssxss-brief.md.
|
// breakout -> arbitrary <script>), see task-cssxss-brief.md.
|
||||||
@@ -224,6 +224,19 @@ Navbar.craft = {
|
|||||||
const sticky = props.isSticky;
|
const sticky = props.isSticky;
|
||||||
const mobile = props.showMobileMenu;
|
const mobile = props.showMobileMenu;
|
||||||
const logoUrl = props.logoUrl || '/';
|
const logoUrl = props.logoUrl || '/';
|
||||||
|
const links0 = props.links || defaultLinks;
|
||||||
|
|
||||||
|
// M-1: deterministic AND unique per-instance scope, keyed on the Craft
|
||||||
|
// node id. Two Navbars on the same page previously emitted an identical
|
||||||
|
// fixed id="navbar-links" (invalid duplicate-id HTML, ambiguous
|
||||||
|
// aria-controls target) and unscoped `.navbar-link:hover`/`.navbar-cta:hover`
|
||||||
|
// rules in each instance's own <style> block -- since both blocks target
|
||||||
|
// the SAME global selector, the later one in the DOM silently overrides
|
||||||
|
// the earlier one's hover color/behavior for BOTH navbars. Scoping the
|
||||||
|
// links-container id and adding a per-instance class on the <nav> root
|
||||||
|
// (used to prefix the hover selectors) eliminates both collisions.
|
||||||
|
const scope = scopeId(nodeId, JSON.stringify(links0) + alignment + pad, 'nav');
|
||||||
|
const linksId = `${scope}_links`;
|
||||||
|
|
||||||
const navStyle = cssPropsToString({
|
const navStyle = cssPropsToString({
|
||||||
display: 'flex',
|
display: 'flex',
|
||||||
@@ -272,21 +285,23 @@ Navbar.craft = {
|
|||||||
// via aria-expanded, kept in sync with the .navbar-open class by the
|
// via aria-expanded, kept in sync with the .navbar-open class by the
|
||||||
// inline onclick handler.
|
// inline onclick handler.
|
||||||
const hamburgerHtml = mobile
|
const hamburgerHtml = mobile
|
||||||
? `\n <button class="navbar-hamburger" aria-label="Toggle navigation menu" aria-expanded="false" aria-controls="navbar-links" onclick="var m=this.parentElement.querySelector('.navbar-links');var open=m.classList.toggle('navbar-open');this.setAttribute('aria-expanded', open ? 'true' : 'false');" style="display:none;background:none;border:none;cursor:pointer;padding:4px;flex-direction:column;gap:4px">
|
? `\n <button class="navbar-hamburger" aria-label="Toggle navigation menu" aria-expanded="false" aria-controls="${escapeAttr(linksId)}" onclick="var m=document.getElementById('${linksId}');var open=m.classList.toggle('navbar-open');this.setAttribute('aria-expanded', open ? 'true' : 'false');" style="display:none;background:none;border:none;cursor:pointer;padding:4px;flex-direction:column;gap:4px">
|
||||||
<span style="display:block;width:24px;height:2px;background-color:${escapeAttr(textCol)}"></span>
|
<span style="display:block;width:24px;height:2px;background-color:${escapeAttr(textCol)}"></span>
|
||||||
<span style="display:block;width:24px;height:2px;background-color:${escapeAttr(textCol)}"></span>
|
<span style="display:block;width:24px;height:2px;background-color:${escapeAttr(textCol)}"></span>
|
||||||
<span style="display:block;width:24px;height:2px;background-color:${escapeAttr(textCol)}"></span>
|
<span style="display:block;width:24px;height:2px;background-color:${escapeAttr(textCol)}"></span>
|
||||||
</button>`
|
</button>`
|
||||||
: '';
|
: '';
|
||||||
|
|
||||||
// Hover CSS
|
// Hover CSS -- scoped under `.${scope}` (a class on the <nav> root, added
|
||||||
|
// below) so it can only ever match THIS instance's links/CTA, never bleed
|
||||||
|
// into or get overridden by another Navbar instance's rules.
|
||||||
const hoverCss = `<style>
|
const hoverCss = `<style>
|
||||||
.navbar-link:hover { color: ${hoverCol} !important; }
|
.${scope} .navbar-link:hover { color: ${hoverCol} !important; }
|
||||||
.navbar-cta:hover { filter: brightness(1.1); }${mobile ? `
|
.${scope} .navbar-cta:hover { filter: brightness(1.1); }${mobile ? `
|
||||||
@media (max-width: 768px) {
|
@media (max-width: 768px) {
|
||||||
.navbar-hamburger { display: flex !important; }
|
.${scope} .navbar-hamburger { display: flex !important; }
|
||||||
.navbar-links { display: none !important; position: absolute; top: 100%; left: 0; right: 0; flex-direction: column !important; background-color: ${bgColor}; padding: 12px 24px; gap: 12px !important; box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
|
.${scope} .navbar-links { display: none !important; position: absolute; top: 100%; left: 0; right: 0; flex-direction: column !important; background-color: ${bgColor}; padding: 12px 24px; gap: 12px !important; box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
|
||||||
.navbar-links.navbar-open { display: flex !important; }
|
.${scope} .navbar-links.navbar-open { display: flex !important; }
|
||||||
}` : ''}
|
}` : ''}
|
||||||
</style>`;
|
</style>`;
|
||||||
|
|
||||||
@@ -309,9 +324,9 @@ Navbar.craft = {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
html: `${hoverCss}
|
html: `${hoverCss}
|
||||||
<nav${navStyle ? ` style="${navStyle}${mobile ? ';position:relative' : ''}"` : ''}>
|
<nav class="${scope}"${navStyle ? ` style="${navStyle}${mobile ? ';position:relative' : ''}"` : ''}>
|
||||||
${logoHtml}${hamburgerHtml}
|
${logoHtml}${hamburgerHtml}
|
||||||
<div class="navbar-links" id="navbar-links" style="display:flex;align-items:center;gap:24px">
|
<div class="navbar-links" id="${linksId}" style="display:flex;align-items:center;gap:24px">
|
||||||
${linksHtmlWithClass}
|
${linksHtmlWithClass}
|
||||||
</div>
|
</div>
|
||||||
</nav>`,
|
</nav>`,
|
||||||
|
|||||||
@@ -93,3 +93,33 @@ describe('Gallery.toHtml deterministic + unique scope ids (thread node id, no Ma
|
|||||||
expect(html1).toBe(html2);
|
expect(html1).toBe(html2);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('Gallery.toHtml lightbox focus management (M-2)', () => {
|
||||||
|
const props = { images: [{ src: '/a.jpg', alt: 'a' }], lightbox: true };
|
||||||
|
|
||||||
|
test('overlay includes a focusable close control with an accessible name and tabindex', () => {
|
||||||
|
const { html } = toHtml(props, '', 'node-gal1');
|
||||||
|
// A close control: a button (or the dialog container) with an accessible
|
||||||
|
// name (aria-label) and an explicit tabindex so it's keyboard-focusable.
|
||||||
|
expect(html).toMatch(/aria-label="[^"]*[Cc]lose[^"]*"[^>]*tabindex="-?\d+"|tabindex="-?\d+"[^>]*aria-label="[^"]*[Cc]lose[^"]*"/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('script saves document.activeElement on open (for focus restore)', () => {
|
||||||
|
const { html } = toHtml(props, '', 'node-gal1');
|
||||||
|
expect(html).toMatch(/document\.activeElement/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('script moves focus to the close control / dialog on open', () => {
|
||||||
|
const { html } = toHtml(props, '', 'node-gal1');
|
||||||
|
expect(html).toMatch(/\.focus\(\)/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('script restores the previously-saved focus on close', () => {
|
||||||
|
const { html } = toHtml(props, '', 'node-gal1');
|
||||||
|
// The close function references a stored "last focused element" variable
|
||||||
|
// and calls .focus() on it, not just moving focus INTO the dialog.
|
||||||
|
const closeFnMatch = html.match(/function\s+\w+_close\s*\(\)\s*\{[^}]*\}/);
|
||||||
|
expect(closeFnMatch).not.toBeNull();
|
||||||
|
expect(closeFnMatch![0]).toMatch(/\.focus\(\)/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -166,16 +166,37 @@ Gallery.craft = {
|
|||||||
let gridIdAttr = '';
|
let gridIdAttr = '';
|
||||||
if (lightbox) {
|
if (lightbox) {
|
||||||
gridIdAttr = ` id="${galleryId}_grid"`;
|
gridIdAttr = ` id="${galleryId}_grid"`;
|
||||||
|
// M-2: focus management for the lightbox dialog.
|
||||||
|
// - OPEN: stash `document.activeElement` (the thumbnail that triggered
|
||||||
|
// the open) in a module-scoped var, then move focus onto the close
|
||||||
|
// button -- so a screen-reader/keyboard user lands inside the dialog
|
||||||
|
// instead of focus staying on (or silently falling back to <body>)
|
||||||
|
// behind the now-visible overlay.
|
||||||
|
// - Tab trap: while the overlay is open, every Tab keypress is
|
||||||
|
// intercepted and refocuses the close button (the dialog's only
|
||||||
|
// focusable control besides Escape/click-to-close), so focus can
|
||||||
|
// never wander out into the page content hidden behind the overlay.
|
||||||
|
// - CLOSE (Escape, backdrop click, or the close button): restore focus
|
||||||
|
// to the element stashed on open.
|
||||||
lightboxHtml = `
|
lightboxHtml = `
|
||||||
<div id="${galleryId}_overlay" role="dialog" aria-modal="true" aria-label="Image preview" onclick="${galleryId}_close()" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.9);z-index:9999;justify-content:center;align-items:center;cursor:pointer">
|
<div id="${galleryId}_overlay" role="dialog" aria-modal="true" aria-label="Image preview" onclick="${galleryId}_close()" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.9);z-index:9999;justify-content:center;align-items:center;cursor:pointer">
|
||||||
|
<button type="button" id="${galleryId}_closebtn" aria-label="Close preview" tabindex="-1" onclick="event.stopPropagation();${galleryId}_close()" style="position:absolute;top:16px;right:16px;width:36px;height:36px;border-radius:50%;border:none;background:rgba(255,255,255,0.15);color:#ffffff;font-size:20px;line-height:1;cursor:pointer;display:flex;align-items:center;justify-content:center">×</button>
|
||||||
<img id="${galleryId}_img" src="" alt="" style="max-width:90%;max-height:90%;object-fit:contain;border-radius:8px" />
|
<img id="${galleryId}_img" src="" alt="" style="max-width:90%;max-height:90%;object-fit:contain;border-radius:8px" />
|
||||||
</div>
|
</div>
|
||||||
<script>
|
<script>
|
||||||
function ${galleryId}_close(){document.getElementById('${galleryId}_overlay').style.display='none';}
|
var ${galleryId}_lastFocus = null;
|
||||||
|
function ${galleryId}_close(){
|
||||||
|
document.getElementById('${galleryId}_overlay').style.display='none';
|
||||||
|
if(${galleryId}_lastFocus && ${galleryId}_lastFocus.focus) ${galleryId}_lastFocus.focus();
|
||||||
|
${galleryId}_lastFocus = null;
|
||||||
|
}
|
||||||
function ${galleryId}_open(src){
|
function ${galleryId}_open(src){
|
||||||
|
${galleryId}_lastFocus = document.activeElement;
|
||||||
var o = document.getElementById('${galleryId}_overlay');
|
var o = document.getElementById('${galleryId}_overlay');
|
||||||
document.getElementById('${galleryId}_img').src = src;
|
document.getElementById('${galleryId}_img').src = src;
|
||||||
o.style.display = 'flex';
|
o.style.display = 'flex';
|
||||||
|
var c = document.getElementById('${galleryId}_closebtn');
|
||||||
|
if(c) c.focus();
|
||||||
}
|
}
|
||||||
document.getElementById('${galleryId}_grid').addEventListener('click', function(e){
|
document.getElementById('${galleryId}_grid').addEventListener('click', function(e){
|
||||||
var t = e.target.closest('[data-lb-src]');
|
var t = e.target.closest('[data-lb-src]');
|
||||||
@@ -190,7 +211,14 @@ document.getElementById('${galleryId}_grid').addEventListener('keydown', functio
|
|||||||
${galleryId}_open(t.getAttribute('data-lb-src'));
|
${galleryId}_open(t.getAttribute('data-lb-src'));
|
||||||
});
|
});
|
||||||
document.addEventListener('keydown', function(e){
|
document.addEventListener('keydown', function(e){
|
||||||
if(e.key==='Escape'){ ${galleryId}_close(); }
|
var o = document.getElementById('${galleryId}_overlay');
|
||||||
|
if(!o || o.style.display==='none') return;
|
||||||
|
if(e.key==='Escape'){ ${galleryId}_close(); return; }
|
||||||
|
if(e.key==='Tab'){
|
||||||
|
e.preventDefault();
|
||||||
|
var c = document.getElementById('${galleryId}_closebtn');
|
||||||
|
if(c) c.focus();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
</script>`;
|
</script>`;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { describe, test, expect } from 'vitest';
|
import { describe, test, expect } from 'vitest';
|
||||||
import { buildSavePayload } from './useWhpApi';
|
import { buildSavePayload } from './useWhpApi';
|
||||||
import { PageData } from '../types';
|
import { PageData } from '../types';
|
||||||
|
import { DEFAULT_SITE_DESIGN } from '../state/SiteDesignContext';
|
||||||
|
|
||||||
const pageA: PageData = { id: 'home', name: 'Home', slug: 'index', craftState: 'STORED_HOME' };
|
const pageA: PageData = { id: 'home', name: 'Home', slug: 'index', craftState: 'STORED_HOME' };
|
||||||
const pageB: PageData = { id: 'page_2', name: 'About', slug: 'about', craftState: 'STORED_ABOUT' };
|
const pageB: PageData = { id: 'page_2', name: 'About', slug: 'about', craftState: 'STORED_ABOUT' };
|
||||||
@@ -19,6 +20,8 @@ describe('buildSavePayload', () => {
|
|||||||
activePageId: '__header__',
|
activePageId: '__header__',
|
||||||
isEditingHeader: true,
|
isEditingHeader: true,
|
||||||
isEditingFooter: false,
|
isEditingFooter: false,
|
||||||
|
headCode: DEFAULT_SITE_DESIGN.headCode,
|
||||||
|
design: DEFAULT_SITE_DESIGN,
|
||||||
});
|
});
|
||||||
|
|
||||||
// The fresh live canvas must be reflected in header_craft_state, not the stale stored one.
|
// The fresh live canvas must be reflected in header_craft_state, not the stale stored one.
|
||||||
@@ -52,6 +55,8 @@ describe('buildSavePayload', () => {
|
|||||||
activePageId: '__footer__',
|
activePageId: '__footer__',
|
||||||
isEditingHeader: false,
|
isEditingHeader: false,
|
||||||
isEditingFooter: true,
|
isEditingFooter: true,
|
||||||
|
headCode: DEFAULT_SITE_DESIGN.headCode,
|
||||||
|
design: DEFAULT_SITE_DESIGN,
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(payload.footer_craft_state).toBe('LIVE_FOOTER');
|
expect(payload.footer_craft_state).toBe('LIVE_FOOTER');
|
||||||
@@ -75,6 +80,8 @@ describe('buildSavePayload', () => {
|
|||||||
activePageId: 'home',
|
activePageId: 'home',
|
||||||
isEditingHeader: false,
|
isEditingHeader: false,
|
||||||
isEditingFooter: false,
|
isEditingFooter: false,
|
||||||
|
headCode: DEFAULT_SITE_DESIGN.headCode,
|
||||||
|
design: DEFAULT_SITE_DESIGN,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Live canvas goes to the active page and top-level slots.
|
// Live canvas goes to the active page and top-level slots.
|
||||||
@@ -105,6 +112,8 @@ describe('buildSavePayload', () => {
|
|||||||
activePageId: 'home',
|
activePageId: 'home',
|
||||||
isEditingHeader: false,
|
isEditingHeader: false,
|
||||||
isEditingFooter: false,
|
isEditingFooter: false,
|
||||||
|
headCode: DEFAULT_SITE_DESIGN.headCode,
|
||||||
|
design: DEFAULT_SITE_DESIGN,
|
||||||
});
|
});
|
||||||
|
|
||||||
// The live edit must land in pages_craft_state[0] (index.html slot),
|
// The live edit must land in pages_craft_state[0] (index.html slot),
|
||||||
@@ -116,4 +125,26 @@ describe('buildSavePayload', () => {
|
|||||||
// The other page is untouched.
|
// The other page is untouched.
|
||||||
expect(payload.pages_craft_state.find((p) => p.id === 'p2')?.craftState).toBe('STORED_ABOUT_2');
|
expect(payload.pages_craft_state.find((p) => p.id === 'p2')?.craftState).toBe('STORED_ABOUT_2');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('head code + design tokens are included in the save payload', () => {
|
||||||
|
const design = { ...DEFAULT_SITE_DESIGN, headCode: '<meta name="x">' };
|
||||||
|
|
||||||
|
const payload = buildSavePayload({
|
||||||
|
siteId: 1,
|
||||||
|
siteName: 'Test Site',
|
||||||
|
liveCraftState: 'LIVE_PAGE_HOME',
|
||||||
|
pages: [pageA, pageB],
|
||||||
|
headerPage,
|
||||||
|
footerPage,
|
||||||
|
activePageId: 'home',
|
||||||
|
isEditingHeader: false,
|
||||||
|
isEditingFooter: false,
|
||||||
|
headCode: '<meta name="x">',
|
||||||
|
design,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(payload.head_code).toBe('<meta name="x">');
|
||||||
|
expect(payload.design).toEqual(design);
|
||||||
|
expect(payload.design.headCode).toBe('<meta name="x">');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { useCallback } from 'react';
|
|||||||
import { useEditor } from '@craftjs/core';
|
import { useEditor } from '@craftjs/core';
|
||||||
import { useEditorConfig } from '../state/EditorConfigContext';
|
import { useEditorConfig } from '../state/EditorConfigContext';
|
||||||
import { usePages } from '../state/PageContext';
|
import { usePages } from '../state/PageContext';
|
||||||
|
import { useSiteDesign, SiteDesign } from '../state/SiteDesignContext';
|
||||||
import { exportBodyHtml } from '../utils/html-export';
|
import { exportBodyHtml } from '../utils/html-export';
|
||||||
import { PageData } from '../types';
|
import { PageData } from '../types';
|
||||||
|
|
||||||
@@ -18,6 +19,10 @@ export interface BuildSavePayloadInput {
|
|||||||
isEditingHeader: boolean;
|
isEditingHeader: boolean;
|
||||||
/** True when the live canvas is showing the footer zone (activePageId === '__footer__'). */
|
/** True when the live canvas is showing the footer zone (activePageId === '__footer__'). */
|
||||||
isEditingFooter: boolean;
|
isEditingFooter: boolean;
|
||||||
|
/** Site-wide custom `<head>` code (also present on `design.headCode`). */
|
||||||
|
headCode: string;
|
||||||
|
/** Full site design tokens object -- lets load() restore colors/fonts/headCode. */
|
||||||
|
design: SiteDesign;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -45,6 +50,8 @@ export function buildSavePayload(input: BuildSavePayloadInput) {
|
|||||||
activePageId,
|
activePageId,
|
||||||
isEditingHeader,
|
isEditingHeader,
|
||||||
isEditingFooter,
|
isEditingFooter,
|
||||||
|
headCode,
|
||||||
|
design,
|
||||||
} = input;
|
} = input;
|
||||||
|
|
||||||
const isPageActive = !isEditingHeader && !isEditingFooter;
|
const isPageActive = !isEditingHeader && !isEditingFooter;
|
||||||
@@ -173,6 +180,8 @@ export function buildSavePayload(input: BuildSavePayloadInput) {
|
|||||||
header_craft_state: headerCraftState,
|
header_craft_state: headerCraftState,
|
||||||
footer_craft_state: footerCraftState,
|
footer_craft_state: footerCraftState,
|
||||||
pages_craft_state: pagesGrapesjs,
|
pages_craft_state: pagesGrapesjs,
|
||||||
|
head_code: headCode,
|
||||||
|
design,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -191,6 +200,7 @@ export function useWhpApi() {
|
|||||||
setPagesCraftState,
|
setPagesCraftState,
|
||||||
setActivePageIdDirect,
|
setActivePageIdDirect,
|
||||||
} = usePages();
|
} = usePages();
|
||||||
|
const { design, updateDesign } = useSiteDesign();
|
||||||
|
|
||||||
const save = useCallback(async () => {
|
const save = useCallback(async () => {
|
||||||
if (!isWHP || !whpConfig) return null;
|
if (!isWHP || !whpConfig) return null;
|
||||||
@@ -210,6 +220,8 @@ export function useWhpApi() {
|
|||||||
activePageId,
|
activePageId,
|
||||||
isEditingHeader,
|
isEditingHeader,
|
||||||
isEditingFooter,
|
isEditingFooter,
|
||||||
|
headCode: design.headCode,
|
||||||
|
design,
|
||||||
});
|
});
|
||||||
|
|
||||||
const resp = await fetch(`${whpConfig.apiUrl}?action=save`, {
|
const resp = await fetch(`${whpConfig.apiUrl}?action=save`, {
|
||||||
@@ -221,7 +233,7 @@ export function useWhpApi() {
|
|||||||
body: JSON.stringify(payload),
|
body: JSON.stringify(payload),
|
||||||
});
|
});
|
||||||
return resp.json();
|
return resp.json();
|
||||||
}, [isWHP, whpConfig, query, pages, activePageId, headerPage, footerPage, isEditingHeader, isEditingFooter]);
|
}, [isWHP, whpConfig, query, pages, activePageId, headerPage, footerPage, isEditingHeader, isEditingFooter, design]);
|
||||||
|
|
||||||
const publish = useCallback(async () => {
|
const publish = useCallback(async () => {
|
||||||
if (!isWHP || !whpConfig) return null;
|
if (!isWHP || !whpConfig) return null;
|
||||||
@@ -255,6 +267,17 @@ export function useWhpApi() {
|
|||||||
if (data.success && data.project) {
|
if (data.success && data.project) {
|
||||||
const proj = data.project;
|
const proj = data.project;
|
||||||
|
|
||||||
|
// Restore site design tokens (colors/fonts/headCode) so the editor
|
||||||
|
// reflects what was last saved. Prefer the full `design` object when
|
||||||
|
// present; fall back to just `head_code` for older project.json files
|
||||||
|
// saved before this field existed (backward-compatible: defaults for
|
||||||
|
// everything else).
|
||||||
|
if (proj.design && typeof proj.design === 'object') {
|
||||||
|
updateDesign(proj.design);
|
||||||
|
} else if (typeof proj.head_code === 'string') {
|
||||||
|
updateDesign({ headCode: proj.head_code });
|
||||||
|
}
|
||||||
|
|
||||||
// Restore header craft state
|
// Restore header craft state
|
||||||
if (proj.header_craft_state) {
|
if (proj.header_craft_state) {
|
||||||
setHeaderCraftState(typeof proj.header_craft_state === 'string'
|
setHeaderCraftState(typeof proj.header_craft_state === 'string'
|
||||||
@@ -300,7 +323,7 @@ export function useWhpApi() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
return data;
|
return data;
|
||||||
}, [isWHP, whpConfig, actions, setHeaderCraftState, setFooterCraftState, setPagesCraftState, setActivePageIdDirect, isEditingHeader, isEditingFooter]);
|
}, [isWHP, whpConfig, actions, setHeaderCraftState, setFooterCraftState, setPagesCraftState, setActivePageIdDirect, isEditingHeader, isEditingFooter, updateDesign]);
|
||||||
|
|
||||||
const uploadAsset = useCallback(
|
const uploadAsset = useCallback(
|
||||||
async (file: File) => {
|
async (file: File) => {
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest';
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { createRoot, Root } from 'react-dom/client';
|
import { createRoot, Root } from 'react-dom/client';
|
||||||
import { act } from 'react-dom/test-utils';
|
import { act } from 'react-dom/test-utils';
|
||||||
import { PageProvider, usePages, uniqueSlug } from './PageContext';
|
import { PageProvider, usePages, uniqueSlug, nextPageId } from './PageContext';
|
||||||
|
|
||||||
/* PageContext only needs `useEditor` from @craftjs/core (for query.serialize /
|
/* PageContext only needs `useEditor` from @craftjs/core (for query.serialize /
|
||||||
actions.deserialize during page switches) — mock just that so PageProvider
|
actions.deserialize during page switches) — mock just that so PageProvider
|
||||||
@@ -15,11 +15,10 @@ vi.mock('@craftjs/core', () => ({
|
|||||||
}),
|
}),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
/* addPage mints ids from `Date.now()`. Two adds inside the same test can land
|
/* addPage mints ids via nextPageId() (timestamp + monotonic counter, M-3),
|
||||||
in the same millisecond and collide on id, which is an existing, unrelated
|
so same-millisecond calls no longer collide on id. Date.now() is still
|
||||||
bug (id collision, not slug collision) — out of scope here but it makes
|
pinned/advanced here for determinism across the slug-dedupe assertions
|
||||||
these tests flaky since a colliding id defeats the "other pages" slug
|
below, independent of wall-clock timing. */
|
||||||
lookup. Force distinct ids so the slug-dedupe assertions below are stable. */
|
|
||||||
let dateNowSpy: ReturnType<typeof vi.spyOn>;
|
let dateNowSpy: ReturnType<typeof vi.spyOn>;
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
let counter = 1_700_000_000_000;
|
let counter = 1_700_000_000_000;
|
||||||
@@ -48,6 +47,23 @@ function unmount() {
|
|||||||
container.remove();
|
container.remove();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
describe('nextPageId (M-3: no same-millisecond id collision)', () => {
|
||||||
|
test('two calls yield distinct ids even when Date.now() is pinned to a constant', () => {
|
||||||
|
const spy = vi.spyOn(Date, 'now').mockReturnValue(1_700_000_000_000);
|
||||||
|
try {
|
||||||
|
const id1 = nextPageId();
|
||||||
|
const id2 = nextPageId();
|
||||||
|
expect(id1).not.toBe(id2);
|
||||||
|
} finally {
|
||||||
|
spy.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('ids are prefixed with "page_"', () => {
|
||||||
|
expect(nextPageId()).toMatch(/^page_/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('uniqueSlug', () => {
|
describe('uniqueSlug', () => {
|
||||||
test('returns base unchanged when no collision', () => {
|
test('returns base unchanged when no collision', () => {
|
||||||
expect(uniqueSlug('about', ['index', 'contact'])).toBe('about');
|
expect(uniqueSlug('about', ['index', 'contact'])).toBe('about');
|
||||||
|
|||||||
@@ -43,6 +43,20 @@ interface PageContextValue {
|
|||||||
const HEADER_ID = '__header__';
|
const HEADER_ID = '__header__';
|
||||||
const FOOTER_ID = '__footer__';
|
const FOOTER_ID = '__footer__';
|
||||||
|
|
||||||
|
// M-3: `page_${Date.now()}` alone collides when two pages are minted inside
|
||||||
|
// the same millisecond (addPage called twice in quick succession, or two AI
|
||||||
|
// replaceAllPages entries) -- then rename/delete/save operate on both pages
|
||||||
|
// at once since they share an id. A module-scoped monotonic counter,
|
||||||
|
// combined with the timestamp, guarantees uniqueness regardless of how many
|
||||||
|
// ids are minted within the same millisecond. This is state/id-minting code
|
||||||
|
// (not toHtml/export), so Date.now() here is fine -- see task-minors-brief.md.
|
||||||
|
let pageIdCounter = 0;
|
||||||
|
|
||||||
|
/** Mints a unique page id: timestamp (base36) + a monotonic per-process counter (base36). */
|
||||||
|
export function nextPageId(): string {
|
||||||
|
return 'page_' + Date.now().toString(36) + '_' + (++pageIdCounter).toString(36);
|
||||||
|
}
|
||||||
|
|
||||||
const EMPTY_CANVAS =
|
const EMPTY_CANVAS =
|
||||||
'{"ROOT":{"type":{"resolvedName":"Container"},"isCanvas":true,"props":{"style":{"minHeight":"100vh","backgroundColor":"#ffffff"},"tag":"div"},"displayName":"Container","custom":{},"hidden":false,"nodes":[],"linkedNodes":{}}}';
|
'{"ROOT":{"type":{"resolvedName":"Container"},"isCanvas":true,"props":{"style":{"minHeight":"100vh","backgroundColor":"#ffffff"},"tag":"div"},"displayName":"Container","custom":{},"hidden":false,"nodes":[],"linkedNodes":{}}}';
|
||||||
|
|
||||||
@@ -338,7 +352,7 @@ export const PageProvider: React.FC<{ children: ReactNode }> = ({ children }) =>
|
|||||||
const addPage = useCallback(
|
const addPage = useCallback(
|
||||||
(name: string, slug: string) => {
|
(name: string, slug: string) => {
|
||||||
const requestedSlug = slug || slugify(name);
|
const requestedSlug = slug || slugify(name);
|
||||||
const id = `page_${Date.now()}`;
|
const id = nextPageId();
|
||||||
|
|
||||||
// Save current page first
|
// Save current page first
|
||||||
saveCurrentState();
|
saveCurrentState();
|
||||||
@@ -452,7 +466,7 @@ export const PageProvider: React.FC<{ children: ReactNode }> = ({ children }) =>
|
|||||||
const slug = i === 0 ? 'index' : uniqueSlug(slugify(p.name), seenSlugs);
|
const slug = i === 0 ? 'index' : uniqueSlug(slugify(p.name), seenSlugs);
|
||||||
seenSlugs.push(slug);
|
seenSlugs.push(slug);
|
||||||
return {
|
return {
|
||||||
id: i === 0 ? 'home' : `page_${Date.now()}_${i}`,
|
id: i === 0 ? 'home' : nextPageId(),
|
||||||
name: p.name,
|
name: p.name,
|
||||||
slug,
|
slug,
|
||||||
craftState: treeToCraftState(p.tree),
|
craftState: treeToCraftState(p.tree),
|
||||||
|
|||||||
@@ -71,6 +71,24 @@ describe('safeUrl', () => {
|
|||||||
expect(safeUrl(s)).toBe(s);
|
expect(safeUrl(s)).toBe(s);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('M-5: blocks data:image/svg+xml (can execute script when navigated to directly)', () => {
|
||||||
|
expect(safeUrl('data:image/svg+xml,<svg onload=alert(1)>')).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('M-5: blocks data:image/svg+xml;base64 variant', () => {
|
||||||
|
expect(safeUrl('data:image/svg+xml;base64,PHN2ZyBvbmxvYWQ9YWxlcnQoMSk+')).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('M-5: blocks obfuscated (whitespace/case) data:image/svg+xml', () => {
|
||||||
|
expect(safeUrl(' DATA:IMAGE/SVG+XML,<svg onload=alert(1)>')).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('M-5: still allows other data:image/* types unchanged', () => {
|
||||||
|
expect(safeUrl('data:image/jpeg;base64,/9j/4AAQ')).toBe('data:image/jpeg;base64,/9j/4AAQ');
|
||||||
|
expect(safeUrl('data:image/gif;base64,R0lGOD')).toBe('data:image/gif;base64,R0lGOD');
|
||||||
|
expect(safeUrl('data:image/webp;base64,UklGR')).toBe('data:image/webp;base64,UklGR');
|
||||||
|
});
|
||||||
|
|
||||||
test.each([
|
test.each([
|
||||||
'https://x.com/a?b=1&c=2',
|
'https://x.com/a?b=1&c=2',
|
||||||
'http://x',
|
'http://x',
|
||||||
@@ -120,8 +138,24 @@ describe('scopeId', () => {
|
|||||||
expect(id1).not.toBe(id2);
|
expect(id1).not.toBe(id2);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('node id is slugified (non-alphanumeric characters stripped, lowercased)', () => {
|
test('output is a valid CSS ident: prefix_hash', () => {
|
||||||
expect(scopeId('Node ID! 123', 'seed', 'sb')).toBe('sb_nodeid123');
|
expect(scopeId('Node ID! 123', 'seed', 'sb')).toMatch(/^sb_[a-z0-9]+$/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('M-4: case-differing node ids do not collapse to the same scope (no case-fold collision)', () => {
|
||||||
|
expect(scopeId('AbC', 'seed', 'sb')).not.toBe(scopeId('abc', 'seed', 'sb'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('M-4: punctuation-differing node ids do not collapse to the same scope', () => {
|
||||||
|
expect(scopeId('a-b', 'seed', 'sb')).not.toBe(scopeId('ab', 'seed', 'sb'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('M-4: same input always yields the identical scope id', () => {
|
||||||
|
expect(scopeId('some-node-id', 'seed', 'sb')).toBe(scopeId('some-node-id', 'seed', 'sb'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('M-4: output always matches a valid CSS ident pattern', () => {
|
||||||
|
expect(scopeId('Weird!! Node--ID__123', 'seed', 'sb')).toMatch(/^[a-z]+_[a-z0-9]+$/i);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('no nodeId (legacy 2-arg call sites) falls back to a deterministic hash of the seed, not Math.random', () => {
|
test('no nodeId (legacy 2-arg call sites) falls back to a deterministic hash of the seed, not Math.random', () => {
|
||||||
|
|||||||
@@ -36,7 +36,14 @@ export function escapeAttr(s: string): string {
|
|||||||
// Dangerous scheme prefixes, checked against a normalized copy with all
|
// Dangerous scheme prefixes, checked against a normalized copy with all
|
||||||
// colons removed (see safeUrl) so that colon-splicing obfuscation like
|
// colons removed (see safeUrl) so that colon-splicing obfuscation like
|
||||||
// "java:script:alert(1)" can't slip past a literal "javascript:" check.
|
// "java:script:alert(1)" can't slip past a literal "javascript:" check.
|
||||||
const DANGEROUS_SCHEME_PREFIXES = ['javascript', 'vbscript', 'datatext/html'];
|
// M-5: `data:image/svg+xml` is blocked alongside `data:text/html` -- an SVG
|
||||||
|
// document can carry an inline <script>/onload= just like an HTML document,
|
||||||
|
// so it executes script when loaded as a document/navigation target (e.g. an
|
||||||
|
// <a href> or window.open), even though it's nominally an "image" MIME type.
|
||||||
|
// Other `data:image/*` types (png/jpeg/gif/webp, ...) stay allowed below --
|
||||||
|
// only this specific scriptable subtype is blocked, regardless of a
|
||||||
|
// trailing `;base64` or other parameters.
|
||||||
|
const DANGEROUS_SCHEME_PREFIXES = ['javascript', 'vbscript', 'datatext/html', 'dataimage/svg+xml'];
|
||||||
|
|
||||||
/** Decodes &#NN; and &#xNN; numeric HTML entities (used to obfuscate scheme names). */
|
/** Decodes &#NN; and &#xNN; numeric HTML entities (used to obfuscate scheme names). */
|
||||||
function decodeNumericEntities(s: string): string {
|
function decodeNumericEntities(s: string): string {
|
||||||
@@ -151,8 +158,14 @@ export function stableHash(seed: string): string {
|
|||||||
* available.
|
* available.
|
||||||
*/
|
*/
|
||||||
export function scopeId(nodeId: string | undefined, fallbackSeed: string, prefix: string): string {
|
export function scopeId(nodeId: string | undefined, fallbackSeed: string, prefix: string): string {
|
||||||
const slug = (nodeId || '').toString().toLowerCase().replace(/[^a-z0-9]+/g, '');
|
// M-4: hash the raw node id (via the same djb2 `stableHash` used for the
|
||||||
return `${prefix}_${slug || stableHash(fallbackSeed)}`;
|
// fallback path below) rather than lowercasing + stripping punctuation
|
||||||
|
// into a slug. A slug collapses distinct ids that differ only by
|
||||||
|
// case/punctuation (e.g. "AbC" and "abc", or "a-b" and "ab") onto the same
|
||||||
|
// scope; hashing the untouched string keeps them distinct while staying
|
||||||
|
// deterministic and producing a valid CSS ident (prefix + '_' + [a-z0-9]+).
|
||||||
|
const seed = (nodeId || '').toString();
|
||||||
|
return `${prefix}_${stableHash(seed || fallbackSeed)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Shared enum allowlists for `toHtml` attribute sinks fed by props that are
|
// Shared enum allowlists for `toHtml` attribute sinks fed by props that are
|
||||||
|
|||||||
Reference in New Issue
Block a user