Compare commits
17
Commits
+58
-46
@@ -41,14 +41,12 @@ craft/
|
||||
│ │ └── Canvas.tsx # Craft.js <Frame> with device-width switching
|
||||
│ │
|
||||
│ ├── components/
|
||||
│ │ ├── resolver.ts # Component map for Craft.js serialization (20 components)
|
||||
│ │ ├── resolver.ts # Component map for Craft.js serialization (39 components)
|
||||
│ │ ├── layout/
|
||||
│ │ │ ├── Container.tsx # Generic container (div/section/article/header/footer/main)
|
||||
│ │ │ ├── Section.tsx # Full-width section with centered inner container
|
||||
│ │ │ ├── ColumnLayout.tsx # Flex columns (1-6, with split ratios)
|
||||
│ │ │ ├── BackgroundSection.tsx # Section with background image/gradient overlay
|
||||
│ │ │ ├── HeaderZone.tsx # Page-level header zone wrapper
|
||||
│ │ │ └── FooterZone.tsx # Page-level footer zone wrapper
|
||||
│ │ │ └── BackgroundSection.tsx # Section with background image/gradient overlay
|
||||
│ │ ├── basic/
|
||||
│ │ │ ├── Heading.tsx # Inline-editable heading (h1-h6)
|
||||
│ │ │ ├── TextBlock.tsx # Inline-editable paragraph
|
||||
@@ -73,7 +71,8 @@ craft/
|
||||
│ ├── panels/
|
||||
│ │ ├── topbar/
|
||||
│ │ │ ├── TopBar.tsx # Back button, domain badge, device switcher, undo/redo, save, templates
|
||||
│ │ │ └── TemplateModal.tsx # Template browser with categories and one-click loading
|
||||
│ │ │ ├── TemplateModal.tsx # Template browser with categories and one-click loading
|
||||
│ │ │ └── HeadCodeModal.tsx # Edits SiteDesign.headCode (site-wide, not per-page)
|
||||
│ │ ├── left/
|
||||
│ │ │ ├── LeftPanel.tsx # Tabs: Blocks | Pages | Layers | Assets
|
||||
│ │ │ ├── BlocksPanel.tsx # Draggable block toolbox with categories
|
||||
@@ -81,9 +80,10 @@ craft/
|
||||
│ │ │ ├── LayersPanel.tsx # Component hierarchy tree view
|
||||
│ │ │ └── AssetsPanel.tsx # Asset browser with upload, drag-drop, thumbnails
|
||||
│ │ ├── right/
|
||||
│ │ │ ├── RightPanel.tsx # Tabs: Styles | Settings | Head
|
||||
│ │ │ ├── GuidedStyles.tsx # Context-aware style panel (shows selected type)
|
||||
│ │ │ └── SiteDesignPanel.tsx # Site-wide design tokens editor (Basic/Advanced tabs)
|
||||
│ │ │ ├── RightPanel.tsx # Single "Styles" tab -- renders GuidedStyles only
|
||||
│ │ │ ├── GuidedStyles.tsx # Context-aware dispatcher: picks a StylePanel by selected type
|
||||
│ │ │ ├── SiteDesignPanel.tsx # Site-wide design tokens editor (Basic/Advanced tabs)
|
||||
│ │ │ └── styles/ # Per-type StylePanels (Text, Button, Image, Container, Nav, Form, etc.)
|
||||
│ │ └── context-menu/
|
||||
│ │ └── ContextMenu.tsx # Right-click context menu (duplicate, copy, paste, delete, etc.)
|
||||
│ │
|
||||
@@ -98,7 +98,8 @@ craft/
|
||||
│ │ └── definitions.ts # 16 template definitions across 4 categories
|
||||
│ │
|
||||
│ ├── ui/
|
||||
│ │ └── SettingsTabs.tsx # Reusable General/Style/Advanced tabs for component settings
|
||||
│ │ ├── AssetPicker.tsx # Reusable image/video source picker (upload/browse-uploaded/URL), full+compact variants
|
||||
│ │ └── Modal.tsx # Reusable modal dialog shell
|
||||
│ │
|
||||
│ ├── constants/
|
||||
│ │ └── presets.ts # Color, font, spacing, radius, gradient, device width presets
|
||||
@@ -165,7 +166,7 @@ The PHP wrapper (`/docker/whp/web/site-builder/index.php`) injects `WHP_CONFIG`
|
||||
|
||||
5. **API compatibility** - The save endpoint sends data in the same format as the GrapesJS version (`{ site_id, name, html, css, grapesjs: serializedJson }`), so the PHP backend doesn't need changes.
|
||||
|
||||
6. **Component-based architecture** - Each visual element is a React component that doubles as a Craft.js `UserComponent`. All rendering, settings UI, and HTML export are co-located in one file.
|
||||
6. **Component-based architecture** - Each visual element is a React component that doubles as a Craft.js `UserComponent`. Rendering and HTML export are co-located in one file; style editing is handled by a shared per-type `StylePanel` in `src/panels/right/styles/` rather than a per-component settings panel.
|
||||
|
||||
7. **Site Design Tokens** - A `SiteDesignContext` provides 17 design properties (colors, fonts, radii, nav style) that components can reference. Templates import their own design tokens when loaded.
|
||||
|
||||
@@ -188,28 +189,21 @@ export const MyComponent: UserComponent<MyComponentProps> = ({ text, style }) =>
|
||||
return <div ref={(r) => { if (r) connect(drag(r)); }} style={style}>{text}</div>;
|
||||
};
|
||||
|
||||
// 3. Settings panel (rendered in right panel when selected)
|
||||
const MyComponentSettings: React.FC = () => {
|
||||
const { actions: { setProp }, props } = useNode((node) => ({
|
||||
props: node.data.props as MyComponentProps,
|
||||
}));
|
||||
return <div>/* preset buttons, inputs, etc. */</div>;
|
||||
};
|
||||
|
||||
// 4. Craft config (displayName, default props, rules, related settings)
|
||||
// 3. Craft config (displayName, default props, rules)
|
||||
MyComponent.craft = {
|
||||
displayName: 'My Component',
|
||||
props: { text: 'Default text', style: {} },
|
||||
rules: { canDrag: () => true, canMoveIn: () => false, canMoveOut: () => true },
|
||||
related: { settings: MyComponentSettings },
|
||||
};
|
||||
|
||||
// 5. HTML export (static method for serializing to HTML string)
|
||||
// 4. HTML export (static method for serializing to HTML string)
|
||||
(MyComponent as any).toHtml = (props: MyComponentProps, childrenHtml: string) => {
|
||||
return { html: `<div style="...">${childrenHtml}</div>` };
|
||||
};
|
||||
```
|
||||
|
||||
Style editing for the new type is added separately as a `StylePanel` under `src/panels/right/styles/` (or reuses an existing generic one), and wired into `GuidedStyles.tsx`'s type dispatch -- components no longer carry their own settings UI.
|
||||
|
||||
### Component Resolver
|
||||
|
||||
All components must be registered in `src/components/resolver.ts`. This map is passed to `<Editor resolver={componentResolver}>` so Craft.js can serialize/deserialize the node tree.
|
||||
@@ -270,7 +264,7 @@ The editor auto-saves every 30 seconds when running inside WHP. The save status
|
||||
- `whpConfig` - The full config object (or null in standalone mode)
|
||||
- `isWHP` - Boolean shorthand for whether we're running inside WHP
|
||||
|
||||
## All Components (22)
|
||||
## All Components (39)
|
||||
|
||||
| # | Component | Type | File | Features |
|
||||
|---|-----------|------|------|----------|
|
||||
@@ -278,24 +272,41 @@ The editor auto-saves every 30 seconds when running inside WHP. The save status
|
||||
| 2 | Section | Layout | `layout/Section.tsx` | Full-width with centered inner container, bg color/gradient, vertical padding, inner max-width |
|
||||
| 3 | ColumnLayout | Layout | `layout/ColumnLayout.tsx` | 1-6 columns, split ratios (50-50, 30-70, 70-30, 33-33-33, 25-25-25-25, etc.), gap control |
|
||||
| 4 | BackgroundSection | Layout | `layout/BackgroundSection.tsx` | Section with background image, gradient overlay, parallax-ready |
|
||||
| 5 | HeaderZone | Layout | `layout/HeaderZone.tsx` | Page-level header wrapper zone, used by PageContext |
|
||||
| 6 | FooterZone | Layout | `layout/FooterZone.tsx` | Page-level footer wrapper zone, used by PageContext |
|
||||
| 7 | Heading | Basic | `basic/Heading.tsx` | Inline-editable, h1-h6 level, color, font family/size/weight, text align |
|
||||
| 8 | TextBlock | Basic | `basic/TextBlock.tsx` | Inline-editable paragraph, color, font family/size/weight, text align, line height |
|
||||
| 9 | ButtonLink | Basic | `basic/ButtonLink.tsx` | Link text/URL/target, 8 color presets (auto text contrast), radius, padding, font size |
|
||||
| 5 | Heading | Basic | `basic/Heading.tsx` | Inline-editable, h1-h6 level, color, font family/size/weight, text align |
|
||||
| 6 | TextBlock | Basic | `basic/TextBlock.tsx` | Inline-editable paragraph, color, font family/size/weight, text align, line height |
|
||||
| 7 | ButtonLink | Basic | `basic/ButtonLink.tsx` | Link text/URL/target, 8 color presets (auto text contrast), radius, padding, font size |
|
||||
| 8 | Logo | Basic | `basic/Logo.tsx` | Text or image logo, link href, font family/size/weight, image width |
|
||||
| 9 | Menu | Basic | `basic/Menu.tsx` | Link list with optional CTA styling, horizontal/vertical orientation, alignment, hover colors |
|
||||
| 10 | Navbar | Basic | `basic/Navbar.tsx` | Text or image logo, page links, external links, CTA buttons, light/dark nav style |
|
||||
| 11 | Footer | Basic | `basic/Footer.tsx` | Footer with links, copyright, social links |
|
||||
| 12 | Divider | Basic | `basic/Divider.tsx` | Horizontal rule with color and thickness controls |
|
||||
| 13 | Spacer | Basic | `basic/Spacer.tsx` | Vertical spacing element with height control |
|
||||
| 14 | ImageBlock | Media | `media/ImageBlock.tsx` | SVG placeholder, URL input, upload, browse assets, alt text, width/height, object-fit, radius |
|
||||
| 15 | VideoBlock | Media | `media/VideoBlock.tsx` | YouTube, Vimeo, direct files (.mp4/.webm/.ogg), background mode, autoplay, loop |
|
||||
| 16 | HeroSimple | Section | `sections/HeroSimple.tsx` | Pre-built hero with heading, subtext, CTA button, gradient/color background |
|
||||
| 17 | FeaturesGrid | Section | `sections/FeaturesGrid.tsx` | 3-column feature cards with icons, titles, descriptions |
|
||||
| 18 | CTASection | Section | `sections/CTASection.tsx` | Call-to-action banner with heading, text, button |
|
||||
| 19 | FormContainer | Form | `forms/FormContainer.tsx` | Form wrapper with action URL and method |
|
||||
| 20 | InputField | Form | `forms/InputField.tsx` | Text input with label, placeholder, type (text/email/tel/password/number) |
|
||||
| 21 | TextareaField | Form | `forms/TextareaField.tsx` | Textarea with label and placeholder |
|
||||
| 22 | FormButton | Form | `forms/FormButton.tsx` | Submit button with color and style controls |
|
||||
| 14 | Icon | Basic | `basic/Icon.tsx` | Font Awesome icon, size/color, background shape, optional link |
|
||||
| 15 | ImageBlock | Media | `media/ImageBlock.tsx` | SVG placeholder, URL input, upload, browse assets, alt text, width/height, object-fit, radius |
|
||||
| 16 | VideoBlock | Media | `media/VideoBlock.tsx` | YouTube, Vimeo, direct files (.mp4/.webm/.ogg), background mode, autoplay, loop |
|
||||
| 17 | MapEmbed | Media | `media/MapEmbed.tsx` | Embedded map by address, zoom level, height |
|
||||
| 18 | HeroSimple | Section | `sections/HeroSimple.tsx` | Pre-built hero with heading, subtext, CTA button, gradient/color background |
|
||||
| 19 | FeaturesGrid | Section | `sections/FeaturesGrid.tsx` | 3-column feature cards with icons, titles, descriptions |
|
||||
| 20 | CTASection | Section | `sections/CTASection.tsx` | Call-to-action banner with heading, text, button |
|
||||
| 21 | Countdown | Section | `sections/Countdown.tsx` | Countdown timer to a target date, heading, digit/label colors |
|
||||
| 22 | Testimonials | Section | `sections/Testimonials.tsx` | Grid or single-layout testimonial cards, star color, card background |
|
||||
| 23 | FormContainer | Form | `forms/FormContainer.tsx` | Form wrapper with action URL and method |
|
||||
| 24 | InputField | Form | `forms/InputField.tsx` | Text input with label, placeholder, type (text/email/tel/password/number) |
|
||||
| 25 | TextareaField | Form | `forms/TextareaField.tsx` | Textarea with label and placeholder |
|
||||
| 26 | FormButton | Form | `forms/FormButton.tsx` | Submit button with color and style controls |
|
||||
| 27 | ContactForm | Form | `forms/ContactForm.tsx` | Configurable field list, recipient email, success message or thank-you URL redirect |
|
||||
| 28 | StarRating | Basic | `basic/StarRating.tsx` | Star rating display, rating/max stars, filled/empty color |
|
||||
| 29 | SocialLinks | Basic | `basic/SocialLinks.tsx` | Social icon links, size/color/shape, gap, alignment |
|
||||
| 30 | CallToAction | Section | `sections/CallToAction.tsx` | Heading/description with 1-2 buttons, color/gradient/image background with overlay |
|
||||
| 31 | Accordion | Section | `sections/Accordion.tsx` | Expand/collapse item list, header/content colors |
|
||||
| 32 | Tabs | Section | `sections/Tabs.tsx` | Tabbed content panels, active/inactive tab colors |
|
||||
| 33 | PricingTable | Section | `sections/PricingTable.tsx` | Pricing plan cards, featured plan highlight, bullet list |
|
||||
| 34 | Gallery | Section | `sections/Gallery.tsx` | Image grid gallery, configurable columns/gap, optional lightbox |
|
||||
| 35 | ContentSlider | Section | `sections/ContentSlider.tsx` | Auto-playing image/content slider, dots/arrows, configurable interval |
|
||||
| 36 | NumberCounter | Section | `sections/NumberCounter.tsx` | Animated stat counters, columns, number/label colors |
|
||||
| 37 | SubscribeForm | Form | `forms/SubscribeForm.tsx` | Inline/stacked email signup form, heading, button color |
|
||||
| 38 | SearchBar | Basic | `basic/SearchBar.tsx` | Search input with optional button, placeholder text |
|
||||
| 39 | HtmlBlock | Basic | `basic/HtmlBlock.tsx` | Raw/custom HTML embed block, sanitized on export |
|
||||
|
||||
## Site Design Tokens
|
||||
|
||||
@@ -351,7 +362,7 @@ Templates are loaded via the Template Modal (opened from TopBar). Loading a temp
|
||||
## Multi-Page System
|
||||
|
||||
Pages are managed through `PageContext`:
|
||||
- Each page has: `id`, `name`, `slug`, `craftState`, `headCode`
|
||||
- Each page has: `id`, `name`, `slug`, `craftState` (`headCode` is site-wide only, on `SiteDesignContext`/`SiteDesign`, edited via the TopBar's Head Code modal -- not a per-page field)
|
||||
- Header and Footer are stored as separate "page" entries with fixed IDs (`__header__`, `__footer__`)
|
||||
- Page switching serializes the current canvas, stores it, then deserializes the target page
|
||||
- Header/Footer editing puts the canvas in a distinct mode
|
||||
@@ -392,21 +403,22 @@ The Assets panel (`AssetsPanel.tsx`) provides:
|
||||
- Delete asset
|
||||
- Integration with WHP API for server-side storage
|
||||
|
||||
Image and Video components also have inline asset selection (browse button in settings).
|
||||
Image and video fields elsewhere in the editor (ImageStylePanel, MediaStylePanel, HeroStylePanel, NavStylePanel, BackgroundSectionStylePanel, and array-editor cards like FeaturesEditor) use the shared `AssetPicker` (`src/ui/AssetPicker.tsx`) for upload / browse-uploaded / paste-URL, in a `full` or `compact` variant depending on space.
|
||||
|
||||
## Adding New Components
|
||||
|
||||
1. Create `src/components/<category>/<ComponentName>.tsx` following the pattern above
|
||||
2. Add the component to `src/components/resolver.ts`
|
||||
3. Add a block entry in `src/panels/left/BlocksPanel.tsx` under the appropriate category
|
||||
4. Implement the `toHtml` static for HTML export
|
||||
5. Build and test: `npm run dev`, drag the block onto the canvas, verify settings panel, verify HTML export
|
||||
4. Add or extend a `StylePanel` in `src/panels/right/styles/` and wire it into `GuidedStyles.tsx`'s type dispatch so the new component is editable when selected
|
||||
5. Implement the `toHtml` static for HTML export
|
||||
6. Build and test: `npm run dev`, drag the block onto the canvas, verify the style panel, verify HTML export
|
||||
|
||||
### Checklist for a new component:
|
||||
- [ ] Props interface with `style?: CSSProperties`
|
||||
- [ ] `useNode()` with `connect(drag(ref))` on the root element
|
||||
- [ ] Settings panel using `useNode()` with `setProp()`
|
||||
- [ ] `.craft` config with `displayName`, default `props`, `rules`, `related.settings`
|
||||
- [ ] `StylePanel` entry (new or reused) wired into `GuidedStyles.tsx`
|
||||
- [ ] `.craft` config with `displayName`, default `props`, `rules`
|
||||
- [ ] `.toHtml()` static method using `cssPropsToString()`
|
||||
- [ ] Registered in `resolver.ts`
|
||||
- [ ] Block added to `BlocksPanel.tsx`
|
||||
@@ -421,7 +433,7 @@ The editor uses a dark theme defined via CSS custom properties in `src/styles/ed
|
||||
- **Border:** `#2d2d3a`
|
||||
- **Font:** Inter
|
||||
|
||||
All editor chrome (panels, topbar, settings) is styled via `editor.css`. User content on the canvas uses inline styles exclusively.
|
||||
All editor chrome (panels, topbar, style panels) is styled via `editor.css`. User content on the canvas uses inline styles exclusively.
|
||||
|
||||
## Presets
|
||||
|
||||
@@ -446,7 +458,7 @@ Every component has a static `toHtml(props, childrenHtml)` method. The `html-exp
|
||||
|
||||
## Testing Approach
|
||||
|
||||
- **Manual testing:** Run `npm run dev`, drag components, edit props, verify settings panels
|
||||
- **Manual testing:** Run `npm run dev`, drag components, edit props, verify style panels
|
||||
- **Type checking:** `tsc --noEmit` (part of build step)
|
||||
- **HTML export:** Verify `toHtml()` output matches expected HTML structure
|
||||
- **Device preview:** Switch between desktop/tablet/mobile and verify responsive behavior
|
||||
@@ -455,9 +467,9 @@ Every component has a static `toHtml(props, childrenHtml)` method. The `html-exp
|
||||
## Development Notes
|
||||
|
||||
- Path alias `@/` maps to `./src/` (configured in both tsconfig.json and vite.config.ts)
|
||||
- `GuidedStyles` shows selected component type and delegates to per-component settings panels
|
||||
- `GuidedStyles` shows the selected component type and dispatches to a shared `StylePanel` in `src/panels/right/styles/` (components no longer carry their own settings UI)
|
||||
- Text components (Heading, TextBlock) use `contentEditable` for inline editing when selected
|
||||
- Button/link navigation is prevented in the editor via `e.preventDefault()`
|
||||
- Image upload integrates with WHP API; in standalone mode falls back to local `blob:` URLs
|
||||
- Auto-save runs every 30 seconds when connected to WHP API
|
||||
- The SettingsTabs UI component provides a reusable General/Style/Advanced tab layout for component settings
|
||||
- `AssetPicker` (`src/ui/AssetPicker.tsx`) is the shared upload/browse/URL control reused across StylePanels for every image and video field
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, test, expect } from 'vitest';
|
||||
import { ButtonLink } from './ButtonLink';
|
||||
|
||||
const toHtml = (ButtonLink as any).toHtml;
|
||||
|
||||
describe('ButtonLink.toHtml href sanitization (attacker-controlled `href` prop)', () => {
|
||||
test('a javascript: URL is neutralized', () => {
|
||||
const { html } = toHtml({ href: 'javascript:alert(1)', text: 'Click' }, '');
|
||||
expect(html).not.toContain('javascript:alert');
|
||||
});
|
||||
|
||||
test('a quote-breakout href does not escape the href attribute', () => {
|
||||
const malicious = '"><script>alert(1)</script>';
|
||||
const { html } = toHtml({ href: malicious, text: 'Click' }, '');
|
||||
expect(html).not.toContain('<script>alert(1)</script>');
|
||||
});
|
||||
|
||||
test('a normal href still renders correctly', () => {
|
||||
const { html } = toHtml({ href: 'https://example.com', text: 'Click' }, '');
|
||||
expect(html).toContain('href="https://example.com"');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ButtonLink.toHtml target (boolean-gated, not raw interpolation)', () => {
|
||||
test('an attribute-breakout value for target does not reach the output raw', () => {
|
||||
const malicious = '_blank" onmouseover="alert(1)' as any;
|
||||
const { html } = toHtml({ href: '#', text: 'x', target: malicious }, '');
|
||||
expect(html).not.toContain('onmouseover');
|
||||
});
|
||||
|
||||
test('target="_blank" still adds rel=noopener noreferrer', () => {
|
||||
const { html } = toHtml({ href: '#', text: 'x', target: '_blank' }, '');
|
||||
expect(html).toContain('target="_blank"');
|
||||
expect(html).toContain('rel="noopener noreferrer"');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ButtonLink.toHtml text escaping (attacker-controlled `text` prop)', () => {
|
||||
test('a tag-breakout attempt in text is neutralized (no injected element)', () => {
|
||||
const { html } = toHtml({ href: '#', text: '</a><img src=x onerror=alert(1)>' }, '');
|
||||
expect(html).not.toContain('<img');
|
||||
expect(html).toContain('<img');
|
||||
});
|
||||
|
||||
test('ampersand is escaped for well-formed text content (consistency with escapeHtml)', () => {
|
||||
const { html } = toHtml({ href: '#', text: 'Tom & Jerry' }, '');
|
||||
expect(html).toContain('Tom & Jerry');
|
||||
});
|
||||
|
||||
test('a normal text value still renders unchanged', () => {
|
||||
const { html } = toHtml({ href: '#', text: 'Click Me' }, '');
|
||||
expect(html).toContain('>Click Me</a>');
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { CSSProperties } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeAttr, safeUrl } from '../../utils/escape';
|
||||
import { escapeHtml, escapeAttr, safeUrl } from '../../utils/escape';
|
||||
|
||||
interface ButtonLinkProps {
|
||||
text?: string;
|
||||
@@ -78,7 +78,7 @@ ButtonLink.craft = {
|
||||
textDecoration: 'none',
|
||||
...props.style,
|
||||
});
|
||||
const escapedText = (props.text || '').replace(/</g, '<').replace(/>/g, '>');
|
||||
const escapedText = escapeHtml(props.text || '');
|
||||
const targetAttr = props.target === '_blank' ? ' target="_blank" rel="noopener noreferrer"' : '';
|
||||
return {
|
||||
html: `<a href="${escapeAttr(safeUrl(props.href || '#'))}"${targetAttr}${styleStr ? ` style="${styleStr}"` : ''}>${escapedText}</a>`,
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, test, expect } from 'vitest';
|
||||
import { Divider } from './Divider';
|
||||
|
||||
const toHtml = (Divider as any).toHtml;
|
||||
|
||||
describe('Divider.toHtml normal rendering', () => {
|
||||
test('renders thickness/color into the border-top style', () => {
|
||||
const { html } = toHtml({ thickness: '2px', color: '#ff0000' }, '');
|
||||
expect(html).toContain('border-top:2px solid #ff0000');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Divider.toHtml XSS hardening (thickness/color into style=)', () => {
|
||||
test('a thickness value with an attribute-breakout string cannot escape style=""', () => {
|
||||
const malicious = '1px" onmouseover="alert(1)';
|
||||
const { html } = toHtml({ thickness: malicious as any, color: '#000' }, '');
|
||||
// The quote must not survive unescaped -- otherwise it closes style=""
|
||||
// early and "onmouseover" becomes a live, attacker-controlled attribute.
|
||||
expect(html).not.toMatch(/"\s+onmouseover="/);
|
||||
expect(html).not.toMatch(/style="[^"]*"[^>]*onmouseover/);
|
||||
});
|
||||
|
||||
test('a color value with a </style><script> breakout is neutralized', () => {
|
||||
const malicious = '#000</style><script>alert(1)</script>';
|
||||
const { html } = toHtml({ thickness: '1px', color: malicious as any }, '');
|
||||
expect(html).not.toContain('<script>alert(1)</script>');
|
||||
});
|
||||
|
||||
test('a non-string thickness (object) does not raw-splice into style=""', () => {
|
||||
const malicious = { toString: () => '1px" onmouseover="alert(1)' };
|
||||
const { html } = toHtml({ thickness: malicious as any, color: '#000' }, '');
|
||||
expect(html).not.toMatch(/"\s+onmouseover="/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import { describe, test, expect } from 'vitest';
|
||||
import { Footer } from './Footer';
|
||||
|
||||
const toHtml = (Footer as any).toHtml;
|
||||
|
||||
describe('Footer.toHtml text escaping (attacker-controlled `text` prop)', () => {
|
||||
test('a tag-breakout attempt in text is neutralized (no injected element)', () => {
|
||||
const { html } = toHtml({ text: '</footer><img src=x onerror=alert(1)>' }, '');
|
||||
expect(html).not.toContain('<img');
|
||||
expect(html).toContain('<img');
|
||||
});
|
||||
|
||||
test('ampersand is escaped for well-formed text content (consistency with escapeHtml)', () => {
|
||||
const { html } = toHtml({ text: 'Terms & Conditions' }, '');
|
||||
expect(html).toContain('Terms & Conditions');
|
||||
});
|
||||
|
||||
test('a normal copyright text value still renders unchanged', () => {
|
||||
const { html } = toHtml({ text: '© 2026 MySite. All rights reserved.' }, '');
|
||||
expect(html).toContain('© 2026 MySite. All rights reserved.');
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import React, { CSSProperties, useCallback, useRef, useEffect } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeHtml } from '../../utils/escape';
|
||||
|
||||
interface FooterProps {
|
||||
text?: string;
|
||||
@@ -107,6 +108,6 @@ Footer.craft = {
|
||||
textAlign: 'center',
|
||||
...props.style,
|
||||
});
|
||||
const escapedText = (props.text || '').replace(/</g, '<').replace(/>/g, '>');
|
||||
const escapedText = escapeHtml(props.text || '');
|
||||
return { html: `<footer${styleStr ? ` style="${styleStr}"` : ''}>${escapedText}</footer>` };
|
||||
};
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, test, expect } from 'vitest';
|
||||
import { Heading } from './Heading';
|
||||
|
||||
const toHtml = (Heading as any).toHtml;
|
||||
|
||||
describe('Heading.toHtml level allowlist (adversarial re-review, same class as C1)', () => {
|
||||
test('a malicious level value clamps to h2 -- no injected <img>, no broken-out tag', () => {
|
||||
const { html } = toHtml({ text: 'x', level: 'h2><img src=x onerror=alert(1)' }, '');
|
||||
expect(html).not.toContain('<img');
|
||||
expect(html).not.toContain('onerror');
|
||||
expect(html.startsWith('<h2')).toBe(true);
|
||||
expect(html.endsWith('</h2>')).toBe(true);
|
||||
});
|
||||
|
||||
test('a numeric out-of-range level (99) clamps to h2', () => {
|
||||
const { html } = toHtml({ text: 'x', level: 99 as any }, '');
|
||||
expect(html.startsWith('<h2')).toBe(true);
|
||||
expect(html.endsWith('</h2>')).toBe(true);
|
||||
});
|
||||
|
||||
test('a non-heading string level clamps to h2', () => {
|
||||
const { html } = toHtml({ text: 'x', level: 'script' as any }, '');
|
||||
expect(html.startsWith('<h2')).toBe(true);
|
||||
expect(html).not.toContain('<script');
|
||||
});
|
||||
|
||||
test('a normal valid level (h4) still emits <h4', () => {
|
||||
const { html } = toHtml({ text: 'x', level: 'h4' }, '');
|
||||
expect(html).toContain('<h4');
|
||||
expect(html).toContain('</h4>');
|
||||
});
|
||||
|
||||
test('all valid levels h1-h6 still work', () => {
|
||||
for (const level of ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']) {
|
||||
const { html } = toHtml({ text: 'x', level }, '');
|
||||
expect(html.startsWith(`<${level}`)).toBe(true);
|
||||
expect(html.endsWith(`</${level}>`)).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('Heading.toHtml text escaping (attacker-controlled `text` prop)', () => {
|
||||
test('a tag-breakout attempt in text is neutralized (no injected element)', () => {
|
||||
const { html } = toHtml({ text: '</h2><img src=x onerror=alert(1)>', level: 'h2' }, '');
|
||||
expect(html).not.toContain('<img');
|
||||
expect(html).toContain('<img');
|
||||
});
|
||||
|
||||
test('ampersand is escaped for well-formed text content (consistency with escapeHtml)', () => {
|
||||
const { html } = toHtml({ text: 'Fish & Chips', level: 'h2' }, '');
|
||||
expect(html).toContain('Fish & Chips');
|
||||
});
|
||||
|
||||
test('a normal text value still renders unchanged', () => {
|
||||
const { html } = toHtml({ text: 'Hello world', level: 'h2' }, '');
|
||||
expect(html).toBe('<h2>Hello world</h2>');
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,20 @@
|
||||
import React, { CSSProperties, useCallback, useRef, useEffect } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeHtml } from '../../utils/escape';
|
||||
|
||||
type HeadingLevel = 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6';
|
||||
|
||||
// `level` is settable via the AI `update_props` path and from deserialized
|
||||
// saved state -- neither type-checked at runtime -- and is interpolated
|
||||
// directly into the tag position (`React.createElement(level, ...)` /
|
||||
// `<${tag}` in `toHtml`). A malicious value like `h2><img src=x
|
||||
// onerror=alert(1)` (or a non-h1-6 string) must never reach that position
|
||||
// unchecked. Anything not in this allowlist clamps to `'h2'`.
|
||||
const ALLOWED_HEADING_LEVELS = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] as const;
|
||||
const sanitizeHeadingLevel = (level: unknown): HeadingLevel =>
|
||||
(ALLOWED_HEADING_LEVELS as readonly unknown[]).includes(level) ? (level as HeadingLevel) : 'h2';
|
||||
|
||||
interface HeadingProps {
|
||||
text?: string;
|
||||
level?: HeadingLevel;
|
||||
@@ -30,6 +41,7 @@ export const Heading: UserComponent<HeadingProps> = ({
|
||||
selected: node.events.selected,
|
||||
}));
|
||||
|
||||
const safeLevel = sanitizeHeadingLevel(level);
|
||||
const elRef = useRef<HTMLElement | null>(null);
|
||||
const editedTextRef = useRef<string | null>(null);
|
||||
|
||||
@@ -59,7 +71,7 @@ export const Heading: UserComponent<HeadingProps> = ({
|
||||
}
|
||||
}, [text, selected]);
|
||||
|
||||
return React.createElement(level, {
|
||||
return React.createElement(safeLevel, {
|
||||
ref: (ref: HTMLElement | null): void => {
|
||||
elRef.current = ref;
|
||||
if (ref) connect(drag(ref));
|
||||
@@ -98,8 +110,8 @@ Heading.craft = {
|
||||
};
|
||||
|
||||
(Heading as any).toHtml = (props: HeadingProps, _childrenHtml: string) => {
|
||||
const tag = props.level || 'h2';
|
||||
const safeText = (props.text || '').replace(/</g, '<').replace(/>/g, '>');
|
||||
const tag = sanitizeHeadingLevel(props.level);
|
||||
const safeText = escapeHtml(props.text || '');
|
||||
const styleStr = cssPropsToString(props.style);
|
||||
return { html: `<${tag}${styleStr ? ` style="${styleStr}"` : ''}>${safeText}</${tag}>` };
|
||||
};
|
||||
|
||||
@@ -10,4 +10,16 @@ describe('HtmlBlock.toHtml sanitizes raw code (A4.1)', () => {
|
||||
expect(html).not.toContain('onclick');
|
||||
expect(html).toContain('<p>hi</p>');
|
||||
});
|
||||
|
||||
test('does not wrap output in an unsanitized element carrying the style prop raw', () => {
|
||||
// toHtml only ever returns the sanitized `code` blob -- there is no
|
||||
// wrapper <div style="..."> in the exported HTML, so a malicious
|
||||
// `style` prop (e.g. an attacker-controlled object with a breakout
|
||||
// toString()) has nothing to splice into.
|
||||
const malicious = { toString: () => 'color:red" onmouseover="alert(1)' } as any;
|
||||
const { html } = toHtml({ code: '<p>hi</p>', style: malicious }, '');
|
||||
expect(html).not.toMatch(/onmouseover/);
|
||||
expect(html).not.toMatch(/<div/);
|
||||
expect(html).toBe('<p>hi</p>');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { describe, test, expect } from 'vitest';
|
||||
import { Icon } from './Icon';
|
||||
|
||||
const toHtml = (Icon as any).toHtml;
|
||||
|
||||
describe('Icon.toHtml normal rendering', () => {
|
||||
test('renders icon class, size/color style, and link href', () => {
|
||||
const { html } = toHtml({ icon: 'fa-star', size: '32px', color: '#3b82f6', link: 'https://example.com' }, '');
|
||||
expect(html).toContain('class="fa fa-star"');
|
||||
expect(html).toContain('font-size:32px');
|
||||
expect(html).toContain('color:#3b82f6');
|
||||
expect(html).toContain('href="https://example.com"');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Icon.toHtml XSS hardening', () => {
|
||||
test('an icon name with an attribute-breakout string is escaped, not raw-concatenated', () => {
|
||||
const malicious = 'star"><script>alert(1)</script>';
|
||||
const { html } = toHtml({ icon: malicious as any }, '');
|
||||
expect(html).not.toContain('<script>alert(1)</script>');
|
||||
expect(html).not.toMatch(/class="fa star"><script>/);
|
||||
});
|
||||
|
||||
test('a size value with an attribute-breakout string cannot escape style=""', () => {
|
||||
const malicious = '24px" onerror="alert(1)';
|
||||
const { html } = toHtml({ size: malicious as any }, '');
|
||||
expect(html).not.toMatch(/"\s+onerror="/);
|
||||
});
|
||||
|
||||
test('a bgSize/bgColor breakout via background wrapper is neutralized', () => {
|
||||
const malicious = '56px" onmouseover="alert(1)';
|
||||
const { html } = toHtml({ bgShape: 'circle', bgColor: '#fff', bgSize: malicious as any }, '');
|
||||
expect(html).not.toMatch(/"\s+onmouseover="/);
|
||||
});
|
||||
|
||||
test('a javascript: link is neutralized to an empty href', () => {
|
||||
const { html } = toHtml({ link: 'javascript:alert(1)' }, '');
|
||||
expect(html).not.toContain('javascript:alert(1)');
|
||||
});
|
||||
|
||||
test('a link value with an attribute-breakout string cannot escape href=""', () => {
|
||||
const malicious = 'https://example.com" onclick="alert(1)';
|
||||
const { html } = toHtml({ link: malicious as any }, '');
|
||||
expect(html).not.toMatch(/"\s+onclick="/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import { describe, test, expect } from 'vitest';
|
||||
import { Logo } from './Logo';
|
||||
|
||||
/*
|
||||
* Regression coverage for Logo.toHtml -- audited during the toHtml
|
||||
* attribute-XSS sweep (see task-cssxss-brief.md) and found already fully
|
||||
* sanitized (href/src via escapeAttr(safeUrl()), alt/text via escapeAttr /
|
||||
* escapeHtml, imageWidth/fontSize/etc. routed through cssPropsToString which
|
||||
* sanitizes every value regardless of declared type). No fix was required;
|
||||
* these tests lock that behavior in against regressions.
|
||||
*/
|
||||
const toHtml = (Logo as any).toHtml;
|
||||
|
||||
describe('Logo.toHtml href sanitization (attacker-controlled `href` prop)', () => {
|
||||
test('a javascript: URL is neutralized', () => {
|
||||
const { html } = toHtml({ href: 'javascript:alert(1)' }, '');
|
||||
expect(html).not.toContain('javascript:alert');
|
||||
});
|
||||
|
||||
test('a quote-breakout href does not escape the anchor attribute', () => {
|
||||
const malicious = '"><script>alert(1)</script>';
|
||||
const { html } = toHtml({ href: malicious }, '');
|
||||
expect(html).not.toContain('<script>alert(1)</script>');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Logo.toHtml image src/alt sanitization (type="image")', () => {
|
||||
test('a javascript: imageSrc is neutralized', () => {
|
||||
const { html } = toHtml({ type: 'image', imageSrc: 'javascript:alert(1)', text: 'Logo' }, '');
|
||||
expect(html).not.toContain('javascript:alert');
|
||||
});
|
||||
|
||||
test('a quote-breakout alt (from `text`) does not escape the img attribute', () => {
|
||||
const malicious = '"><script>alert(1)</script>';
|
||||
const { html } = toHtml({ type: 'image', imageSrc: 'https://example.com/logo.png', text: malicious }, '');
|
||||
expect(html).not.toContain('<script>alert(1)</script>');
|
||||
});
|
||||
|
||||
test('a non-numeric imageWidth (attribute-breakout attempt) does not escape the style attribute', () => {
|
||||
const malicious = '1"><script>alert(1)</script>';
|
||||
const { html } = toHtml({ type: 'image', imageSrc: 'https://example.com/logo.png', imageWidth: malicious }, '');
|
||||
expect(html).not.toContain('<script>alert(1)</script>');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Logo.toHtml text-logo styling sanitization', () => {
|
||||
test('a quote-breakout color does not escape the span style attribute', () => {
|
||||
const malicious = 'red" onmouseover="alert(1)';
|
||||
const { html } = toHtml({ type: 'text', text: 'MySite', color: malicious }, '');
|
||||
// The raw `"` must never survive un-escaped inside the style attribute
|
||||
// value -- if it did, `onmouseover` would land as a REAL new HTML
|
||||
// attribute (breakout) rather than being inert CSS-value garbage inside
|
||||
// a properly-escaped style="...".
|
||||
expect(html).not.toMatch(/style="[^"]*"[^>]*onmouseover/);
|
||||
});
|
||||
|
||||
test('a normal logo renders as expected', () => {
|
||||
const { html } = toHtml({ type: 'text', text: 'MySite', href: '/' }, '');
|
||||
expect(html).toContain('href="/"');
|
||||
expect(html).toContain('MySite');
|
||||
});
|
||||
});
|
||||
@@ -30,3 +30,17 @@ describe('Menu.toHtml deterministic + unique scope ids (thread node id, no Math.
|
||||
expect(html1).toBe(html2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Menu.toHtml XSS hardening (linkHoverColor into <style>)', () => {
|
||||
test('a linkHoverColor value containing </style><script> is neutralized', () => {
|
||||
const malicious = '#fff}</style><script>alert(1)</script><style>{';
|
||||
const { html } = toHtml({ linkHoverColor: malicious }, '', 'node-xss');
|
||||
expect(html).not.toContain('</style><script');
|
||||
expect(html).not.toContain('<script>alert(1)</script>');
|
||||
});
|
||||
|
||||
test('a normal linkHoverColor still renders in the hover rule', () => {
|
||||
const { html } = toHtml({ linkHoverColor: '#ff0000' }, '', 'node-normal');
|
||||
expect(html).toMatch(/:hover\s*\{\s*color:\s*#ff0000/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { CSSProperties, useState } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeHtml, escapeAttr, safeUrl, scopeId } from '../../utils/escape';
|
||||
import { escapeHtml, escapeAttr, safeUrl, scopeId, cssValue } from '../../utils/escape';
|
||||
|
||||
/* ---------- Types ---------- */
|
||||
|
||||
@@ -125,14 +125,18 @@ Menu.craft = {
|
||||
/* ---------- HTML export ---------- */
|
||||
|
||||
(Menu as any).toHtml = (props: MenuProps, _childrenHtml: string, nodeId?: string) => {
|
||||
const linkCol = props.linkColor || '#3f3f46';
|
||||
const hoverCol = props.linkHoverColor || '#3b82f6';
|
||||
const ctaBg = props.ctaBgColor || '#3b82f6';
|
||||
const ctaText = props.ctaTextColor || '#ffffff';
|
||||
const gap = props.gap || '24px';
|
||||
// Sanitized once here -- linkCol/hoverCol/ctaBg/ctaText/gap/fSize are raw
|
||||
// string-interpolation sinks below (hoverCol goes into a <style> block,
|
||||
// the worst case: </style> breakout -> arbitrary <script>), see
|
||||
// task-cssxss-brief.md.
|
||||
const linkCol = cssValue(props.linkColor) || '#3f3f46';
|
||||
const hoverCol = cssValue(props.linkHoverColor) || '#3b82f6';
|
||||
const ctaBg = cssValue(props.ctaBgColor) || '#3b82f6';
|
||||
const ctaText = cssValue(props.ctaTextColor) || '#ffffff';
|
||||
const gap = cssValue(props.gap) || '24px';
|
||||
const orientation = props.orientation || 'horizontal';
|
||||
const alignment = props.alignment || 'right';
|
||||
const fSize = props.fontSize || '14px';
|
||||
const fSize = cssValue(props.fontSize) || '14px';
|
||||
|
||||
const justifyMap: Record<string, string> = { left: 'flex-start', center: 'center', right: 'flex-end' };
|
||||
|
||||
|
||||
@@ -26,3 +26,38 @@ describe('Navbar.toHtml hamburger accessibility (F2.3)', () => {
|
||||
expect(html).not.toContain('navbar-hamburger');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Navbar.toHtml XSS hardening (hoverColor/backgroundColor/ctaColor into <style>)', () => {
|
||||
test('a hoverColor value containing </style><script> is neutralized in the hover <style> block', () => {
|
||||
const malicious = '#fff}</style><script>alert(1)</script><style>{';
|
||||
const { html } = toHtml({ hoverColor: malicious }, '');
|
||||
expect(html).not.toContain('</style><script');
|
||||
expect(html).not.toContain('<script>alert(1)</script>');
|
||||
});
|
||||
|
||||
test('a backgroundColor value containing </style><script> is neutralized (mobile media-query rule)', () => {
|
||||
const malicious = '#fff}</style><script>alert(2)</script><style>{';
|
||||
const { html } = toHtml({ backgroundColor: malicious, showMobileMenu: true }, '');
|
||||
expect(html).not.toContain('</style><script');
|
||||
expect(html).not.toContain('<script>alert(2)</script>');
|
||||
});
|
||||
|
||||
test('a ctaColor value containing </style><script> is neutralized', () => {
|
||||
const malicious = '#fff}</style><script>alert(3)</script><style>{';
|
||||
const { html } = toHtml({ ctaColor: malicious }, '');
|
||||
expect(html).not.toContain('</style><script');
|
||||
expect(html).not.toContain('<script>alert(3)</script>');
|
||||
});
|
||||
|
||||
test('a textColor value containing a quote breakout does not escape the hamburger span style attribute', () => {
|
||||
const malicious = '#333" onmouseover="alert(1)';
|
||||
const { html } = toHtml({ textColor: malicious, showMobileMenu: true }, '');
|
||||
expect(html).not.toMatch(/style="[^"]*"[^>]*onmouseover/);
|
||||
});
|
||||
|
||||
test('normal colors still render correctly', () => {
|
||||
const { html } = toHtml({ hoverColor: '#ff0000', backgroundColor: '#123456', ctaColor: '#00ff00' }, '');
|
||||
expect(html).toMatch(/:hover\s*\{\s*color:\s*#ff0000/);
|
||||
expect(html).toContain('background-color:#123456');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,7 +2,7 @@ import React, { CSSProperties, useState } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { useSiteDesign } from '../../state/SiteDesignContext';
|
||||
import { escapeHtml, escapeAttr, safeUrl } from '../../utils/escape';
|
||||
import { escapeHtml, escapeAttr, safeUrl, cssValue } from '../../utils/escape';
|
||||
|
||||
/* ---------- Types ---------- */
|
||||
|
||||
@@ -211,12 +211,15 @@ Navbar.craft = {
|
||||
/* ---------- HTML export ---------- */
|
||||
|
||||
(Navbar as any).toHtml = (props: NavbarProps, _childrenHtml: string) => {
|
||||
const bgColor = props.backgroundColor || '#ffffff';
|
||||
const textCol = props.textColor || '#3f3f46';
|
||||
const hoverCol = props.hoverColor || '#3b82f6';
|
||||
const ctaCol = props.ctaColor || '#3b82f6';
|
||||
const ctaTextCol = props.ctaTextColor || '#ffffff';
|
||||
const pad = props.padding || '16px 24px';
|
||||
// Sanitized once here -- these are raw string-interpolation sinks below
|
||||
// (hoverCol/bgColor go into a <style> block, the worst case: </style>
|
||||
// breakout -> arbitrary <script>), see task-cssxss-brief.md.
|
||||
const bgColor = cssValue(props.backgroundColor) || '#ffffff';
|
||||
const textCol = cssValue(props.textColor) || '#3f3f46';
|
||||
const hoverCol = cssValue(props.hoverColor) || '#3b82f6';
|
||||
const ctaCol = cssValue(props.ctaColor) || '#3b82f6';
|
||||
const ctaTextCol = cssValue(props.ctaTextColor) || '#ffffff';
|
||||
const pad = cssValue(props.padding) || '16px 24px';
|
||||
const alignment = props.navAlignment || 'space-between';
|
||||
const sticky = props.isSticky;
|
||||
const mobile = props.showMobileMenu;
|
||||
|
||||
@@ -11,3 +11,22 @@ describe('SearchBar.toHtml decorative icons (F2.5)', () => {
|
||||
icons.forEach((tag: string) => expect(tag).toContain('aria-hidden="true"'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('SearchBar.toHtml XSS hardening (placeholder/buttonText/showButton)', () => {
|
||||
test('a placeholder value with an attribute-breakout string cannot escape placeholder=""', () => {
|
||||
const malicious = 'Search..." onmouseover="alert(1)';
|
||||
const { html } = toHtml({ placeholder: malicious }, '');
|
||||
expect(html).not.toMatch(/"\s+onmouseover="/);
|
||||
});
|
||||
|
||||
test('a buttonText value with a script tag is escaped as text content, not raw HTML', () => {
|
||||
const malicious = '<script>alert(1)</script>';
|
||||
const { html } = toHtml({ buttonText: malicious, showButton: true }, '');
|
||||
expect(html).not.toContain('<script>alert(1)</script>');
|
||||
});
|
||||
|
||||
test('a non-boolean showButton (string "false") still yields fixed, safe border-radius values', () => {
|
||||
const { html } = toHtml({ showButton: 'false' as any }, '');
|
||||
expect(html).toMatch(/border-radius:(8px 0 0 8px|8px)/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -14,3 +14,40 @@ describe('SocialLinks.toHtml accessibility (F2.5)', () => {
|
||||
expect(html).toMatch(/<i class="fa fa-twitter"[^>]*aria-hidden="true"/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('SocialLinks.toHtml XSS hardening (iconSize/iconColor/iconBgColor/gap into style=)', () => {
|
||||
test('an iconSize value with an attribute-breakout string cannot escape style=""', () => {
|
||||
const malicious = '20px" onmouseover="alert(1)';
|
||||
const { html } = toHtml({ links: [{ platform: 'facebook', url: '#' }], iconSize: malicious as any }, '');
|
||||
expect(html).not.toMatch(/"\s+onmouseover="/);
|
||||
});
|
||||
|
||||
test('an iconColor value with an attribute-breakout string cannot escape style=""', () => {
|
||||
const malicious = '#fff" onmouseover="alert(1)';
|
||||
const { html } = toHtml({ links: [{ platform: 'facebook', url: '#' }], iconColor: malicious as any }, '');
|
||||
expect(html).not.toMatch(/"\s+onmouseover="/);
|
||||
});
|
||||
|
||||
test('an iconBgColor value with an attribute-breakout string cannot escape style=""', () => {
|
||||
const malicious = '#374151" onmouseover="alert(1)';
|
||||
const { html } = toHtml({ links: [{ platform: 'facebook', url: '#' }], iconShape: 'circle', iconBgColor: malicious as any }, '');
|
||||
expect(html).not.toMatch(/"\s+onmouseover="/);
|
||||
});
|
||||
|
||||
test('a gap value with an attribute-breakout string cannot escape the wrapper style=""', () => {
|
||||
const malicious = '10px" onmouseover="alert(1)';
|
||||
const { html } = toHtml({ links: [{ platform: 'facebook', url: '#' }], gap: malicious as any }, '');
|
||||
expect(html).not.toMatch(/"\s+onmouseover="/);
|
||||
});
|
||||
|
||||
test('a malicious platform key does not produce a raw class-attribute breakout', () => {
|
||||
const malicious = 'x"><script>alert(1)</script>';
|
||||
const { html } = toHtml({ links: [{ platform: malicious, url: '#' }] }, '');
|
||||
expect(html).not.toContain('<script>alert(1)</script>');
|
||||
});
|
||||
|
||||
test('a link url with a javascript: scheme is neutralized', () => {
|
||||
const { html } = toHtml({ links: [{ platform: 'facebook', url: 'javascript:alert(1)' }] }, '');
|
||||
expect(html).not.toContain('javascript:alert(1)');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { CSSProperties } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeAttr, safeUrl } from '../../utils/escape';
|
||||
import { escapeAttr, safeUrl, cssValue } from '../../utils/escape';
|
||||
|
||||
interface SocialLink {
|
||||
platform: string;
|
||||
@@ -163,9 +163,10 @@ SocialLinks.craft = {
|
||||
|
||||
(SocialLinks as any).toHtml = (props: SocialLinksProps, _childrenHtml: string) => {
|
||||
const links = props.links || defaultLinks;
|
||||
const iconSize = props.iconSize || '20px';
|
||||
const iconColor = props.iconColor || '#ffffff';
|
||||
const iconBgColor = props.iconBgColor || '#374151';
|
||||
// Sanitized -- raw string-interpolation sinks in aStyle/getShapeStr below.
|
||||
const iconSize = cssValue(props.iconSize) || '20px';
|
||||
const iconColor = cssValue(props.iconColor) || '#ffffff';
|
||||
const iconBgColor = cssValue(props.iconBgColor) || '#374151';
|
||||
const iconShape = props.iconShape || 'circle';
|
||||
const gap = props.gap || '10px';
|
||||
const alignment = props.alignment || 'center';
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, test, expect } from 'vitest';
|
||||
import { Spacer } from './Spacer';
|
||||
|
||||
const toHtml = (Spacer as any).toHtml;
|
||||
|
||||
describe('Spacer.toHtml normal rendering', () => {
|
||||
test('renders height into the style attribute', () => {
|
||||
const { html } = toHtml({ height: '80px' }, '');
|
||||
expect(html).toContain('height:80px');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Spacer.toHtml XSS hardening (height into style=)', () => {
|
||||
test('a height value with an attribute-breakout string cannot escape style=""', () => {
|
||||
const malicious = '40px" onmouseover="alert(1)';
|
||||
const { html } = toHtml({ height: malicious as any }, '');
|
||||
expect(html).not.toMatch(/"\s+onmouseover="/);
|
||||
expect(html).not.toMatch(/style="[^"]*"[^>]*onmouseover/);
|
||||
});
|
||||
|
||||
test('a height value with a </style><script> breakout is neutralized', () => {
|
||||
const malicious = '40px</style><script>alert(1)</script>';
|
||||
const { html } = toHtml({ height: malicious as any }, '');
|
||||
expect(html).not.toContain('<script>alert(1)</script>');
|
||||
});
|
||||
});
|
||||
@@ -21,3 +21,57 @@ describe('StarRating.toHtml accessibility (F2.2)', () => {
|
||||
expect(html).toContain('aria-label="Rating: 2 out of 10"');
|
||||
});
|
||||
});
|
||||
|
||||
describe('StarRating.toHtml XSS hardening (filledColor/emptyColor/size into style=)', () => {
|
||||
test('a filledColor value containing a quote breakout is neutralized', () => {
|
||||
const malicious = '#f00" onmouseover="alert(1)';
|
||||
const { html } = toHtml({ rating: 3, maxStars: 5, filledColor: malicious }, '');
|
||||
expect(html).not.toMatch(/style="[^"]*"[^>]*onmouseover/);
|
||||
});
|
||||
|
||||
test('a size value containing </style><script> is neutralized', () => {
|
||||
const malicious = '24px</style><script>alert(1)</script>';
|
||||
const { html } = toHtml({ rating: 3, maxStars: 5, size: malicious }, '');
|
||||
expect(html).not.toContain('<script>alert(1)</script>');
|
||||
});
|
||||
|
||||
test('a normal filled color still renders', () => {
|
||||
const { html } = toHtml({ rating: 5, maxStars: 5, filledColor: '#ff9900' }, '');
|
||||
expect(html).toContain('color:#ff9900');
|
||||
});
|
||||
});
|
||||
|
||||
describe('StarRating.toHtml XSS hardening (rating/maxStars into aria-label, F2.2 CONFIRMED sink)', () => {
|
||||
test('a maxStars value with an attribute-breakout string is neutralized in aria-label', () => {
|
||||
const malicious = '5" onmouseover="alert(1)';
|
||||
const { html } = toHtml({ rating: 3, maxStars: malicious as any }, '');
|
||||
expect(html).not.toMatch(/onmouseover/);
|
||||
expect(html).not.toMatch(/aria-label="Rating: 3 out of 5" onmouseover/);
|
||||
});
|
||||
|
||||
test('a rating value with an attribute-breakout string is neutralized in aria-label', () => {
|
||||
const malicious = '4.5" onmouseover="alert(1)';
|
||||
const { html } = toHtml({ rating: malicious as any, maxStars: 5 }, '');
|
||||
expect(html).not.toMatch(/onmouseover/);
|
||||
});
|
||||
|
||||
test('a non-numeric maxStars does not blow up the star loop (no NaN glyph count, no huge output)', () => {
|
||||
const malicious = '5" onmouseover="alert(1)';
|
||||
const { html } = toHtml({ rating: 3, maxStars: malicious as any }, '');
|
||||
const glyphs = html.match(/<i class="fa fa-star"/g) || [];
|
||||
// Falls back to a sane default star count rather than looping 0 or NaN times.
|
||||
expect(glyphs.length).toBeGreaterThan(0);
|
||||
expect(glyphs.length).toBeLessThanOrEqual(50);
|
||||
});
|
||||
|
||||
test('an absurdly large maxStars is clamped to a sane maximum instead of looping unboundedly', () => {
|
||||
const { html } = toHtml({ rating: 3, maxStars: 1e9 as any }, '');
|
||||
const glyphs = html.match(/<i class="fa fa-star"/g) || [];
|
||||
expect(glyphs.length).toBeLessThanOrEqual(50);
|
||||
});
|
||||
|
||||
test('normal numeric rating/maxStars still render the expected aria-label', () => {
|
||||
const { html } = toHtml({ rating: 4.5, maxStars: 5 }, '');
|
||||
expect(html).toMatch(/<span role="img" aria-label="Rating: 4\.5 out of 5"/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import React, { CSSProperties } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { cssValue, escapeAttr } from '../../utils/escape';
|
||||
|
||||
interface StarRatingProps {
|
||||
rating?: number;
|
||||
@@ -97,11 +98,23 @@ StarRating.craft = {
|
||||
/* ---------- HTML export ---------- */
|
||||
|
||||
(StarRating as any).toHtml = (props: StarRatingProps, _childrenHtml: string) => {
|
||||
const rating = props.rating ?? 4.5;
|
||||
const maxStars = props.maxStars || 5;
|
||||
const size = props.size || '24px';
|
||||
const filledColor = props.filledColor || '#f59e0b';
|
||||
const emptyColor = props.emptyColor || '#d1d5db';
|
||||
// `rating`/`maxStars` are declared `number` in TS but arrive unchecked at
|
||||
// runtime (AI update_props only validates node_id; deserialized saved
|
||||
// state is untyped JSON) -- a string like `5" onmouseover="alert(1)`
|
||||
// breaks out of the aria-label attribute below, and an uncoerced/unclamped
|
||||
// maxStars can also blow up the star-glyph loop (NaN, absurd loop count,
|
||||
// or -- observed -- a RangeError from string concatenation overflow with
|
||||
// e.g. maxStars=1e9). Coerce to numbers with sane fallbacks/clamps first.
|
||||
const ratingRaw = Number(props.rating);
|
||||
const rating = Number.isFinite(ratingRaw) ? ratingRaw : 4.5;
|
||||
const maxStarsRaw = Number(props.maxStars);
|
||||
const maxStars = Number.isFinite(maxStarsRaw)
|
||||
? Math.min(Math.max(Math.trunc(maxStarsRaw), 0), 50)
|
||||
: 5;
|
||||
// Sanitized -- raw string-interpolation sinks in the star glyphs below.
|
||||
const size = cssValue(props.size) || '24px';
|
||||
const filledColor = cssValue(props.filledColor) || '#f59e0b';
|
||||
const emptyColor = cssValue(props.emptyColor) || '#d1d5db';
|
||||
const wrapperStyle = cssPropsToString({
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
@@ -123,7 +136,12 @@ StarRating.craft = {
|
||||
// The star glyphs convey nothing to assistive tech on their own -- wrap
|
||||
// in role="img" with a textual equivalent, and hide the decorative glyphs
|
||||
// themselves (aria-hidden above) so AT doesn't announce each icon.
|
||||
// Belt-and-suspenders: rating/maxStars are already coerced to numbers
|
||||
// above, but the assembled label is still run through escapeAttr() in
|
||||
// case a decimal/negative/Infinity edge case produces odd (though no
|
||||
// longer dangerous) text.
|
||||
const ariaLabel = escapeAttr(`Rating: ${rating} out of ${maxStars}`);
|
||||
return {
|
||||
html: `<span role="img" aria-label="Rating: ${rating} out of ${maxStars}"${wrapperStyle ? ` style="${wrapperStyle}"` : ''}>${starsHtml}</span>`,
|
||||
html: `<span role="img" aria-label="${ariaLabel}"${wrapperStyle ? ` style="${wrapperStyle}"` : ''}>${starsHtml}</span>`,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { describe, test, expect } from 'vitest';
|
||||
import { TextBlock } from './TextBlock';
|
||||
|
||||
const toHtml = (TextBlock as any).toHtml;
|
||||
|
||||
describe('TextBlock.toHtml text escaping (attacker-controlled `text` prop)', () => {
|
||||
test('a tag-breakout attempt in text is neutralized (no injected element)', () => {
|
||||
const { html } = toHtml({ text: '</p><img src=x onerror=alert(1)>' }, '');
|
||||
expect(html).not.toContain('<img');
|
||||
expect(html).toContain('<img');
|
||||
});
|
||||
|
||||
test('ampersand is escaped for well-formed text content (consistency with escapeHtml)', () => {
|
||||
const { html } = toHtml({ text: 'Tom & Jerry' }, '');
|
||||
expect(html).toContain('Tom & Jerry');
|
||||
});
|
||||
|
||||
test('a normal text value still renders unchanged', () => {
|
||||
const { html } = toHtml({ text: 'Hello world' }, '');
|
||||
expect(html).toBe('<p>Hello world</p>');
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import React, { CSSProperties, useCallback, useRef, useEffect } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeHtml } from '../../utils/escape';
|
||||
|
||||
interface TextBlockProps {
|
||||
text?: string;
|
||||
@@ -95,6 +96,6 @@ TextBlock.craft = {
|
||||
|
||||
(TextBlock as any).toHtml = (props: TextBlockProps, _childrenHtml: string) => {
|
||||
const styleStr = cssPropsToString(props.style);
|
||||
const escapedText = (props.text || '').replace(/</g, '<').replace(/>/g, '>');
|
||||
const escapedText = escapeHtml(props.text || '');
|
||||
return { html: `<p${styleStr ? ` style="${styleStr}"` : ''}>${escapedText}</p>` };
|
||||
};
|
||||
|
||||
@@ -110,3 +110,19 @@ describe('ContactForm.toHtml accessibility (F2.1)', () => {
|
||||
expect(ids1).toEqual(ids2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ContactForm.toHtml field type attribute sanitization', () => {
|
||||
test('malicious field.type cannot break out of the input attribute; falls back to type="text"', () => {
|
||||
const fields = [{ type: 'text"><img src=x onerror=alert(1)>' as any, label: 'Name', name: 'name', placeholder: 'Your name', required: false }];
|
||||
const { html } = toHtml({ fields }, '');
|
||||
expect(html).not.toContain('<img');
|
||||
expect(html).not.toContain('onerror=');
|
||||
expect(html).toContain('type="text"');
|
||||
});
|
||||
|
||||
test('legitimate email field type still passes through unchanged', () => {
|
||||
const fields = [{ type: 'email' as const, label: 'Email', name: 'email', placeholder: 'you@example.com', required: false }];
|
||||
const { html } = toHtml({ fields }, '');
|
||||
expect(html).toContain('type="email"');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,7 +2,7 @@ import React, { CSSProperties } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { relayFormWiring } from '../../utils/form-relay-wiring';
|
||||
import { escapeHtml, escapeAttr, slugId } from '../../utils/escape';
|
||||
import { escapeHtml, escapeAttr, slugId, cssValue, sanitizeInputType } from '../../utils/escape';
|
||||
|
||||
interface ContactFormField {
|
||||
type: 'text' | 'email' | 'tel' | 'textarea' | 'select';
|
||||
@@ -175,9 +175,11 @@ ContactForm.craft = {
|
||||
gap: '20px',
|
||||
...props.style,
|
||||
});
|
||||
const labelColor = props.labelColor || '#374151';
|
||||
const inputBg = props.inputBg || '#ffffff';
|
||||
const inputBorder = props.inputBorder || '#d1d5db';
|
||||
// Sanitized -- raw string-interpolation sinks in inputStyleStr/labelHtml
|
||||
// below.
|
||||
const labelColor = cssValue(props.labelColor) || '#374151';
|
||||
const inputBg = cssValue(props.inputBg) || '#ffffff';
|
||||
const inputBorder = cssValue(props.inputBorder) || '#d1d5db';
|
||||
const inputStyleStr = `width:100%;padding:10px 14px;font-size:14px;font-family:Inter,sans-serif;border:1px solid ${inputBorder};border-radius:6px;background-color:${inputBg};color:#1f2937;box-sizing:border-box;outline:none`;
|
||||
|
||||
const fieldsHtml = (props.fields || defaultFields).map((field, i) => {
|
||||
@@ -194,7 +196,7 @@ ContactForm.craft = {
|
||||
const opts = (field.options || []).map((o) => `<option value="${escapeAttr(o)}">${escapeHtml(o)}</option>`).join('');
|
||||
inputHtml = `<select id="${escapeAttr(fieldId)}" name="${escapeAttr(field.name)}" style="${inputStyleStr};cursor:pointer"${reqAttr}><option value="">${escapeHtml(field.placeholder || 'Select...')}</option>${opts}</select>`;
|
||||
} else {
|
||||
inputHtml = `<input id="${escapeAttr(fieldId)}" type="${field.type}" name="${escapeAttr(field.name)}" placeholder="${escapeAttr(field.placeholder)}" style="${inputStyleStr}"${reqAttr} />`;
|
||||
inputHtml = `<input id="${escapeAttr(fieldId)}" type="${sanitizeInputType(field.type)}" name="${escapeAttr(field.name)}" placeholder="${escapeAttr(field.placeholder)}" style="${inputStyleStr}"${reqAttr} />`;
|
||||
}
|
||||
return `<div style="display:flex;flex-direction:column;gap:6px">${labelHtml}${inputHtml}</div>`;
|
||||
}).join('\n ');
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, test, expect } from 'vitest';
|
||||
import { FormButton } from './FormButton';
|
||||
|
||||
const toHtml = (FormButton as any).toHtml;
|
||||
|
||||
describe('FormButton.toHtml', () => {
|
||||
test('normal text renders as-is', () => {
|
||||
const { html } = toHtml({ text: 'Send it' }, '');
|
||||
expect(html).toContain('>Send it<');
|
||||
expect(html).toContain('type="submit"');
|
||||
});
|
||||
|
||||
test('type="submit" is a hardcoded literal, not prop-driven', () => {
|
||||
const { html } = toHtml({ text: 'Submit' }, '');
|
||||
expect(html).toMatch(/<button type="submit"/);
|
||||
});
|
||||
|
||||
test('text content is escaped for <, >, &, and " (consistent with escapeHtml)', () => {
|
||||
const { html } = toHtml({ text: '<script>alert(1)</script> & "quoted"' }, '');
|
||||
expect(html).not.toContain('<script>');
|
||||
expect(html).toContain('<script>alert(1)</script>');
|
||||
expect(html).toContain('&');
|
||||
expect(html).toContain('"quoted"');
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import React, { CSSProperties } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeHtml } from '../../utils/escape';
|
||||
|
||||
interface FormButtonProps {
|
||||
text?: string;
|
||||
@@ -74,7 +75,7 @@ FormButton.craft = {
|
||||
cursor: 'pointer',
|
||||
...props.style,
|
||||
});
|
||||
const escapedText = (props.text || 'Submit').replace(/</g, '<').replace(/>/g, '>');
|
||||
const escapedText = escapeHtml(props.text || 'Submit');
|
||||
return {
|
||||
html: `<button type="submit"${styleStr ? ` style="${styleStr}"` : ''}>${escapedText}</button>`,
|
||||
};
|
||||
|
||||
@@ -39,3 +39,16 @@ describe('FormContainer.toHtml relay wiring', () => {
|
||||
expect(mid1).not.toBe(mid2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('FormContainer.toHtml method attribute sanitization', () => {
|
||||
test('malicious method value cannot break out of the attribute; falls back to POST', () => {
|
||||
const { html } = toHtml({ action: '/legacy', method: 'POST"><script>alert(1)</script>' }, '');
|
||||
expect(html).not.toContain('<script');
|
||||
expect(html).toContain('method="POST"');
|
||||
});
|
||||
|
||||
test('legitimate GET method still passes through unchanged (non-relay path)', () => {
|
||||
const { html } = toHtml({ action: '/legacy', method: 'GET' }, '');
|
||||
expect(html).toContain('method="GET"');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@ import { useNode, Element, UserComponent } from '@craftjs/core';
|
||||
import { Container } from '../layout/Container';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { relayFormWiring } from '../../utils/form-relay-wiring';
|
||||
import { sanitizeFormMethod } from '../../utils/escape';
|
||||
|
||||
interface FormContainerProps {
|
||||
action?: string;
|
||||
@@ -74,7 +75,7 @@ FormContainer.craft = {
|
||||
...props.style,
|
||||
});
|
||||
const { useRelay, marker, actionAttr, honeypot } = relayFormWiring(props.recipientEmail, props.thankYouUrl, props.action, nodeId);
|
||||
const method = useRelay ? 'POST' : (props.method || 'POST'); // relay requires POST
|
||||
const method = useRelay ? 'POST' : sanitizeFormMethod(props.method); // relay requires POST
|
||||
const body = honeypot + childrenHtml; // honeypot as first child
|
||||
return {
|
||||
html: `${marker}<form action="${actionAttr}" method="${method}"${styleStr ? ` style="${styleStr}"` : ''}>${body}</form>`,
|
||||
|
||||
@@ -58,3 +58,17 @@ describe('InputField.toHtml deterministic + unique ids (thread node id, resolves
|
||||
expect(id1).toBe(id2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('InputField.toHtml type attribute sanitization', () => {
|
||||
test('malicious type value cannot break out of the attribute; falls back to type="text"', () => {
|
||||
const { html } = toHtml({ label: 'Name', name: 'name', type: 'text" autofocus onfocus="alert(1)' as any }, '');
|
||||
expect(html).not.toContain('onfocus=');
|
||||
expect(html).not.toContain('autofocus');
|
||||
expect(html).toContain('type="text"');
|
||||
});
|
||||
|
||||
test('legitimate number type still passes through unchanged', () => {
|
||||
const { html } = toHtml({ label: 'Age', name: 'age', type: 'number' as const }, '');
|
||||
expect(html).toContain('type="number"');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { CSSProperties } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeHtml, escapeAttr, scopeId } from '../../utils/escape';
|
||||
import { escapeHtml, escapeAttr, scopeId, sanitizeInputType } from '../../utils/escape';
|
||||
|
||||
interface InputFieldProps {
|
||||
label?: string;
|
||||
@@ -111,7 +111,7 @@ InputField.craft = {
|
||||
return {
|
||||
html: `<div${wrapStyle ? ` style="${wrapStyle}"` : ''}>
|
||||
${labelHtml}
|
||||
<input id="${escapeAttr(fieldId)}" type="${props.type || 'text'}" name="${escapeAttr(props.name || 'field')}" placeholder="${escapeAttr(props.placeholder || '')}"${reqAttr}${ariaLabelAttr} style="padding:10px 12px;border:1px solid #d4d4d8;border-radius:6px;font-size:14px;color:#18181b;background-color:#ffffff;width:100%;box-sizing:border-box" />
|
||||
<input id="${escapeAttr(fieldId)}" type="${sanitizeInputType(props.type)}" name="${escapeAttr(props.name || 'field')}" placeholder="${escapeAttr(props.placeholder || '')}"${reqAttr}${ariaLabelAttr} style="padding:10px 12px;border:1px solid #d4d4d8;border-radius:6px;font-size:14px;color:#18181b;background-color:#ffffff;width:100%;box-sizing:border-box" />
|
||||
</div>`,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { describe, test, expect } from 'vitest';
|
||||
import { SubscribeForm } from './SubscribeForm';
|
||||
|
||||
const toHtml = (SubscribeForm as any).toHtml;
|
||||
|
||||
describe('SubscribeForm.toHtml hardcoded attributes stay hardcoded (no raw prop breakout)', () => {
|
||||
test('form method is always POST regardless of any injected props', () => {
|
||||
const { html } = toHtml({ heading: 'Join us', method: 'GET"><script>alert(1)</script>' } as any, '');
|
||||
expect(html).toContain('<form method="POST"');
|
||||
expect(html).not.toContain('<script');
|
||||
});
|
||||
|
||||
test('email input type is always "email" regardless of any injected props', () => {
|
||||
const { html } = toHtml({ type: 'text"><img src=x onerror=alert(1)>' } as any, '');
|
||||
expect(html).toContain('<input type="email"');
|
||||
expect(html).not.toContain('<img');
|
||||
expect(html).not.toContain('onerror=');
|
||||
});
|
||||
|
||||
test('layout enum only ever feeds one of two fixed literal style strings, never raw', () => {
|
||||
const { html: inlineHtml } = toHtml({ layout: 'inline' }, '');
|
||||
const { html: stackedHtml } = toHtml({ layout: 'stacked' }, '');
|
||||
expect(inlineHtml).toContain('flex-direction:row');
|
||||
expect(stackedHtml).toContain('flex-direction:column');
|
||||
});
|
||||
|
||||
test('malicious layout value cannot inject raw CSS/attribute breakout (falls through the isInline boolean check to the stacked literal)', () => {
|
||||
const { html } = toHtml({ layout: '"><script>alert(1)</script>' as any }, '');
|
||||
expect(html).not.toContain('<script');
|
||||
expect(html).toContain('flex-direction:column');
|
||||
});
|
||||
|
||||
test('normal render still produces expected structure', () => {
|
||||
const { html } = toHtml({ heading: 'Subscribe', placeholder: 'you@example.com', buttonText: 'Go' }, '');
|
||||
expect(html).toContain('Subscribe');
|
||||
expect(html).toContain('placeholder="you@example.com"');
|
||||
expect(html).toContain('>Go<');
|
||||
});
|
||||
});
|
||||
@@ -50,3 +50,16 @@ describe('TextareaField.toHtml deterministic + unique ids (thread node id, resol
|
||||
expect(id1).toBe(id2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('TextareaField.toHtml rows attribute sanitization', () => {
|
||||
test('malicious rows value cannot break out of the attribute; falls back to a numeric rows', () => {
|
||||
const { html } = toHtml({ label: 'Message', name: 'message', rows: '4"><script>alert(1)</script>' as any }, '');
|
||||
expect(html).not.toContain('<script');
|
||||
expect(html).toMatch(/rows="\d+"/);
|
||||
});
|
||||
|
||||
test('legitimate numeric rows still passes through unchanged', () => {
|
||||
const { html } = toHtml({ label: 'Message', name: 'message', rows: 8 }, '');
|
||||
expect(html).toContain('rows="8"');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -97,6 +97,11 @@ TextareaField.craft = {
|
||||
...props.style,
|
||||
});
|
||||
const reqAttr = props.required ? ' required' : '';
|
||||
// `rows` is declared as a TS `number` but arrives unchecked (AI update_props
|
||||
// path only validates node_id; deserialized saved-state JSON is untyped at
|
||||
// runtime), so a string like `4"><script>...` must be coerced to a real
|
||||
// number before interpolation, not trusted as already-numeric.
|
||||
const rows = Number(props.rows) || 4;
|
||||
// Deterministic AND unique id: scoped on the Craft node id so the
|
||||
// <label for> always matches the <textarea id> AND two TextareaField
|
||||
// instances that share the same (often default) `name` -- e.g. two
|
||||
@@ -113,7 +118,7 @@ TextareaField.craft = {
|
||||
return {
|
||||
html: `<div${wrapStyle ? ` style="${wrapStyle}"` : ''}>
|
||||
${labelHtml}
|
||||
<textarea id="${escapeAttr(fieldId)}" name="${escapeAttr(props.name || 'message')}" placeholder="${escapeAttr(props.placeholder || '')}" rows="${props.rows || 4}"${reqAttr}${ariaLabelAttr} style="padding:10px 12px;border:1px solid #d4d4d8;border-radius:6px;font-size:14px;color:#18181b;background-color:#ffffff;width:100%;box-sizing:border-box;resize:vertical;font-family:inherit"></textarea>
|
||||
<textarea id="${escapeAttr(fieldId)}" name="${escapeAttr(props.name || 'message')}" placeholder="${escapeAttr(props.placeholder || '')}" rows="${escapeAttr(String(rows))}"${reqAttr}${ariaLabelAttr} style="padding:10px 12px;border:1px solid #d4d4d8;border-radius:6px;font-size:14px;color:#18181b;background-color:#ffffff;width:100%;box-sizing:border-box;resize:vertical;font-family:inherit"></textarea>
|
||||
</div>`,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, test, expect } from 'vitest';
|
||||
import { BackgroundSection } from './BackgroundSection';
|
||||
|
||||
const toHtml = (BackgroundSection as any).toHtml;
|
||||
|
||||
describe('BackgroundSection.toHtml anchorId', () => {
|
||||
test('escapes a malicious anchorId (attribute breakout attempt)', () => {
|
||||
const { html } = toHtml({ anchorId: 'x" onmouseover="alert(1)' }, 'child');
|
||||
expect(html).not.toContain('onmouseover="alert(1)"');
|
||||
});
|
||||
|
||||
test('a normal anchorId still renders correctly', () => {
|
||||
const { html } = toHtml({ anchorId: 'my-bg-section' }, 'child');
|
||||
expect(html).toContain('id="my-bg-section"');
|
||||
});
|
||||
});
|
||||
|
||||
describe('BackgroundSection.toHtml style-value XSS hardening', () => {
|
||||
test('a malicious bgImage cannot break out of the outer style attribute via url(...)', () => {
|
||||
const malicious = 'javascript:alert(1)) foo{background:red}</style><script>alert(1)</script';
|
||||
const { html } = toHtml({ bgImage: malicious }, 'child');
|
||||
expect(html).not.toContain('<script>alert(1)</script>');
|
||||
expect(html).not.toContain('javascript:alert(1)');
|
||||
});
|
||||
|
||||
test('a malicious bgColor cannot break out of the outer style attribute', () => {
|
||||
const malicious = 'red" onmouseover="alert(1)';
|
||||
const { html } = toHtml({ bgColor: malicious }, 'child');
|
||||
expect(html).not.toContain('onmouseover="alert(1)"');
|
||||
});
|
||||
|
||||
test('a malicious overlayColor cannot break out of the overlay style attribute', () => {
|
||||
const malicious = 'red" onmouseover="alert(1)';
|
||||
const { html } = toHtml({ overlayColor: malicious }, 'child');
|
||||
expect(html).not.toContain('onmouseover="alert(1)"');
|
||||
});
|
||||
|
||||
test('a wrong-typed overlayOpacity (string, not number) cannot break out of the overlay style attribute', () => {
|
||||
const malicious = '0.4" onmouseover="alert(1)' as any;
|
||||
const { html } = toHtml({ overlayOpacity: malicious }, 'child');
|
||||
expect(html).not.toContain('onmouseover="alert(1)"');
|
||||
});
|
||||
|
||||
test('a malicious innerMaxWidth cannot break out of the inner style attribute', () => {
|
||||
const malicious = '1200px" onmouseover="alert(1)';
|
||||
const { html } = toHtml({ innerMaxWidth: malicious }, 'child');
|
||||
expect(html).not.toContain('onmouseover="alert(1)"');
|
||||
});
|
||||
|
||||
test('normal props still render correctly', () => {
|
||||
const { html } = toHtml({ bgImage: 'https://example.com/bg.jpg', bgColor: '#1e293b', overlayColor: '#000000', overlayOpacity: 0.4, innerMaxWidth: '1200px' }, 'child');
|
||||
expect(html).toContain("url('https://example.com/bg.jpg')");
|
||||
expect(html).toContain('background-color:#1e293b');
|
||||
expect(html).toContain('opacity:0.4');
|
||||
expect(html).toContain('max-width:1200px');
|
||||
expect(html).toContain('child');
|
||||
});
|
||||
});
|
||||
@@ -59,3 +59,24 @@ describe('ColumnLayout.toHtml deterministic + unique scope ids (thread node id,
|
||||
expect(html1).toBe(html2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ColumnLayout.toHtml XSS hardening (gap into <style>)', () => {
|
||||
test('a gap value containing </style><script> is neutralized in the <style>-context nth-child rule', () => {
|
||||
const malicious = '0px)}</style><script>alert(1)</script><style>{';
|
||||
const { html } = toHtml({ columns: 2, split: '50-50', gap: malicious }, '<div>A</div><div>B</div>', 'node-xss');
|
||||
expect(html).not.toContain('</style><script');
|
||||
expect(html).not.toContain('<script>alert(1)</script>');
|
||||
});
|
||||
|
||||
test('a gap value containing a quote/semicolon breakout is neutralized in the style attribute', () => {
|
||||
const malicious = '16px" onmouseover="alert(1)';
|
||||
const { html } = toHtml({ columns: 2, split: '50-50', gap: malicious }, '', 'node-xss2');
|
||||
expect(html).not.toMatch(/style="[^"]*"[^>]*onmouseover/);
|
||||
});
|
||||
|
||||
test('a normal gap value still renders correctly', () => {
|
||||
const { html } = toHtml({ columns: 2, split: '50-50', gap: '24px' }, '<div>A</div>', 'node-normal');
|
||||
expect(html).toContain('gap:24px');
|
||||
expect(html).toMatch(/calc\(50% - 24px\)/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,7 +2,7 @@ import React, { CSSProperties } from 'react';
|
||||
import { useNode, Element, UserComponent } from '@craftjs/core';
|
||||
import { Container } from './Container';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeAttr, scopeId } from '../../utils/escape';
|
||||
import { escapeAttr, scopeId, cssValue } from '../../utils/escape';
|
||||
|
||||
type SplitOption =
|
||||
| '100'
|
||||
@@ -117,7 +117,11 @@ ColumnLayout.craft = {
|
||||
(ColumnLayout as any).toHtml = (props: ColumnLayoutProps, childrenHtml: string, nodeId?: string) => {
|
||||
const columns = props.columns || 2;
|
||||
const split = props.split || '50-50';
|
||||
const gap = props.gap || '16px';
|
||||
// Sanitized once here so BOTH the raw <style> nth-child rule below AND the
|
||||
// cssPropsToString-built outerStyle get a safe value -- gap is a raw
|
||||
// string-interpolation sink into a <style> block (worst case: </style>
|
||||
// breakout -> arbitrary <script>), see task-cssxss-brief.md.
|
||||
const gap = cssValue(props.gap) || '16px';
|
||||
const widths = getWidths(split, columns);
|
||||
|
||||
const outerStyle = cssPropsToString({
|
||||
|
||||
@@ -33,3 +33,33 @@ describe('Container.toHtml cssId/cssClass', () => {
|
||||
expect(html).toContain('id="anchor-id"');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Container.toHtml tag allowlist (adversarial re-review, same class as C1)', () => {
|
||||
test('a malicious tag value falls back to div -- no injected <img>, no broken-out attrs', () => {
|
||||
const { html } = toHtml({ tag: 'div><img src=x onerror=alert(1)' }, 'child');
|
||||
expect(html).not.toContain('<img');
|
||||
expect(html).not.toContain('onerror');
|
||||
expect(html.startsWith('<div')).toBe(true);
|
||||
expect(html.endsWith('</div>')).toBe(true);
|
||||
});
|
||||
|
||||
test('a tag value outside the known-safe set falls back to div', () => {
|
||||
const { html } = toHtml({ tag: 'script' }, 'child');
|
||||
expect(html.startsWith('<div')).toBe(true);
|
||||
expect(html).not.toContain('<script');
|
||||
});
|
||||
|
||||
test('a valid tag (section) still emits <section', () => {
|
||||
const { html } = toHtml({ tag: 'section' }, 'child');
|
||||
expect(html).toContain('<section');
|
||||
expect(html).toContain('</section>');
|
||||
});
|
||||
|
||||
test('all other allowlisted tags still work', () => {
|
||||
for (const tag of ['div', 'article', 'header', 'footer', 'main']) {
|
||||
const { html } = toHtml({ tag }, 'child');
|
||||
expect(html.startsWith(`<${tag}`)).toBe(true);
|
||||
expect(html.endsWith(`</${tag}>`)).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,6 +3,19 @@ import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeAttr } from '../../utils/escape';
|
||||
|
||||
// The only tag names Container actually supports (matches the TS union
|
||||
// below and the `tag` default in `.craft.props`). `tag` is settable via the
|
||||
// AI `update_props` path and from deserialized saved state -- neither is
|
||||
// type-checked at runtime -- so a malicious value like
|
||||
// `div><img src=x onerror=alert(1)` must never reach the `<${tag}` template
|
||||
// position in `toHtml`/the live render. Anything not in this allowlist
|
||||
// falls back to `'div'`.
|
||||
const ALLOWED_CONTAINER_TAGS = ['div', 'section', 'article', 'header', 'footer', 'main'] as const;
|
||||
export type ContainerTag = (typeof ALLOWED_CONTAINER_TAGS)[number];
|
||||
|
||||
export const sanitizeContainerTag = (tag: unknown): ContainerTag =>
|
||||
(ALLOWED_CONTAINER_TAGS as readonly unknown[]).includes(tag) ? (tag as ContainerTag) : 'div';
|
||||
|
||||
interface ContainerProps {
|
||||
style?: CSSProperties;
|
||||
tag?: 'div' | 'section' | 'article' | 'header' | 'footer' | 'main';
|
||||
@@ -42,6 +55,7 @@ export const Container: UserComponent<ContainerProps> = ({
|
||||
}) => {
|
||||
const { connectors: { connect, drag } } = useNode();
|
||||
|
||||
const safeTag = sanitizeContainerTag(tag);
|
||||
const needsBoxedWrapper = contentWidth === 'boxed';
|
||||
const flexStyles = flexAlignFromTextAlign(style.textAlign);
|
||||
|
||||
@@ -58,7 +72,7 @@ export const Container: UserComponent<ContainerProps> = ({
|
||||
const idValue = cssId || anchorId || undefined;
|
||||
|
||||
const el = React.createElement(
|
||||
tag,
|
||||
safeTag,
|
||||
{
|
||||
ref: (ref: HTMLElement | null): void => { if (ref) connect(drag(ref)); },
|
||||
style: outerStyle,
|
||||
@@ -97,7 +111,7 @@ Container.craft = {
|
||||
/* ---------- HTML export ---------- */
|
||||
|
||||
(Container as any).toHtml = (props: ContainerProps, childrenHtml: string) => {
|
||||
const tag = props.tag || 'div';
|
||||
const tag = sanitizeContainerTag(props.tag);
|
||||
const isBoxed = props.contentWidth === 'boxed';
|
||||
const flexStyles = flexAlignFromTextAlign(props.style?.textAlign);
|
||||
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import { describe, test, expect } from 'vitest';
|
||||
import { Section } from './Section';
|
||||
|
||||
const toHtml = (Section as any).toHtml;
|
||||
|
||||
describe('Section.toHtml anchorId', () => {
|
||||
test('escapes a malicious anchorId (attribute breakout attempt)', () => {
|
||||
const { html } = toHtml({ anchorId: 'x" onmouseover="alert(1)' }, 'child');
|
||||
expect(html).not.toContain('onmouseover="alert(1)"');
|
||||
});
|
||||
|
||||
test('a normal anchorId still renders correctly', () => {
|
||||
const { html } = toHtml({ anchorId: 'my-section' }, 'child');
|
||||
expect(html).toContain('id="my-section"');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Section.toHtml childrenHtml passthrough', () => {
|
||||
test('children are preserved', () => {
|
||||
const { html } = toHtml({}, '<p>hello</p>');
|
||||
expect(html).toContain('<p>hello</p>');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Section.toHtml shape divider color/height XSS hardening', () => {
|
||||
test('a malicious topDividerColor cannot break out of the SVG style attribute', () => {
|
||||
const malicious = 'red" onmouseover="alert(1)';
|
||||
const { html } = toHtml({ topDivider: 'wave', topDividerColor: malicious }, '');
|
||||
expect(html).not.toContain('onmouseover="alert(1)"');
|
||||
});
|
||||
|
||||
test('a malicious topDividerColor cannot inject a </style><script> breakout', () => {
|
||||
const malicious = 'red</style><script>alert(1)</script>';
|
||||
const { html } = toHtml({ topDivider: 'wave', topDividerColor: malicious }, '');
|
||||
expect(html).not.toContain('<script>alert(1)</script>');
|
||||
});
|
||||
|
||||
test('a malicious bottomDividerHeight cannot break out of the wrapper style attribute', () => {
|
||||
const malicious = '50px" onmouseover="alert(1)';
|
||||
const { html } = toHtml({ bottomDivider: 'angle', bottomDividerHeight: malicious }, '');
|
||||
expect(html).not.toContain('onmouseover="alert(1)"');
|
||||
});
|
||||
|
||||
test('a normal divider color/height still renders correctly', () => {
|
||||
const { html } = toHtml({ topDivider: 'wave', topDividerColor: '#123456', topDividerHeight: '80px' }, '');
|
||||
expect(html).toContain('fill:#123456');
|
||||
expect(html).toContain('height:80px');
|
||||
});
|
||||
|
||||
test('divider shape "none" emits no divider markup', () => {
|
||||
const { html } = toHtml({ topDivider: 'none' }, 'child');
|
||||
expect(html).not.toContain('<svg');
|
||||
});
|
||||
|
||||
test('an unrecognized divider shape value emits no divider markup and no injected content', () => {
|
||||
const malicious = 'wave"><script>alert(1)</script>' as any;
|
||||
const { html } = toHtml({ topDivider: malicious }, 'child');
|
||||
expect(html).not.toContain('<script>alert(1)</script>');
|
||||
expect(html).not.toContain('<svg');
|
||||
});
|
||||
|
||||
test('a prototype-property-name divider shape (__proto__) does not leak [object Object]/function source into the SVG path', () => {
|
||||
const { html } = toHtml({ topDivider: '__proto__' as any }, 'child');
|
||||
expect(html).not.toContain('[object');
|
||||
expect(html).not.toContain('native code');
|
||||
expect(html).not.toContain('<svg');
|
||||
});
|
||||
|
||||
test('a prototype-property-name divider shape (toString) does not leak Object.prototype.toString source into the SVG path', () => {
|
||||
const { html } = toHtml({ topDivider: 'toString' as any }, 'child');
|
||||
expect(html).not.toContain('[object');
|
||||
expect(html).not.toContain('native code');
|
||||
expect(html).not.toContain('<svg');
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,7 @@ import React, { CSSProperties } from 'react';
|
||||
import { useNode, Element, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { Container } from './Container';
|
||||
import { escapeAttr } from '../../utils/escape';
|
||||
import { escapeAttr, cssValue } from '../../utils/escape';
|
||||
|
||||
/* ---------- Shape Divider SVG Paths ---------- */
|
||||
|
||||
@@ -38,7 +38,14 @@ const ShapeDivider: React.FC<{
|
||||
position: 'top' | 'bottom';
|
||||
}> = ({ shape, color, height, position }) => {
|
||||
if (!shape || shape === 'none') return null;
|
||||
const path = DIVIDER_PATHS[shape];
|
||||
// `shape` is attacker-controlled (AI update_props / deserialized state) and
|
||||
// not runtime-type-checked. A plain-object index lookup with a string key
|
||||
// like '__proto__', 'toString', or 'constructor' returns an INHERITED
|
||||
// Object.prototype value (not undefined), which would otherwise leak
|
||||
// "[object Object]" / a function's source text into the SVG `d` attribute
|
||||
// below. hasOwnProperty restricts the lookup to the real allowlisted keys.
|
||||
if (!Object.prototype.hasOwnProperty.call(DIVIDER_PATHS, shape)) return null;
|
||||
const path = DIVIDER_PATHS[shape as Exclude<DividerShape, 'none'>];
|
||||
if (!path) return null;
|
||||
|
||||
const isTop = position === 'top';
|
||||
@@ -162,12 +169,16 @@ function buildDividerHtml(
|
||||
position: 'top' | 'bottom',
|
||||
): string {
|
||||
if (!shape || shape === 'none') return '';
|
||||
const path = DIVIDER_PATHS[shape];
|
||||
// See the matching hasOwnProperty guard in <ShapeDivider> above -- same
|
||||
// prototype-pollution-shaped lookup, same fix.
|
||||
if (!Object.prototype.hasOwnProperty.call(DIVIDER_PATHS, shape)) return '';
|
||||
const path = DIVIDER_PATHS[shape as Exclude<DividerShape, 'none'>];
|
||||
if (!path) return '';
|
||||
|
||||
const isTop = position === 'top';
|
||||
const h = height || '50px';
|
||||
const c = color || '#ffffff';
|
||||
// Sanitized -- raw string-interpolation sink in the SVG `fill:${c}` below.
|
||||
const c = cssValue(color) || '#ffffff';
|
||||
|
||||
const wrapperStyle = cssPropsToString({
|
||||
position: 'absolute',
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, test, expect } from 'vitest';
|
||||
import { ImageBlock } from './ImageBlock';
|
||||
|
||||
const toHtml = (ImageBlock as any).toHtml;
|
||||
|
||||
describe('ImageBlock.toHtml src/alt XSS hardening', () => {
|
||||
test('a javascript: src never reaches the output', () => {
|
||||
const { html } = toHtml({ src: 'javascript:alert(1)' }, '');
|
||||
expect(html).not.toContain('javascript:');
|
||||
});
|
||||
|
||||
test('a malicious src cannot break out of the src attribute', () => {
|
||||
const malicious = 'https://example.com/x.jpg" onerror="alert(1)';
|
||||
const { html } = toHtml({ src: malicious }, '');
|
||||
expect(html).not.toContain('onerror="alert(1)"');
|
||||
});
|
||||
|
||||
test('a malicious alt cannot break out of the alt attribute', () => {
|
||||
const malicious = 'x" onerror="alert(1)';
|
||||
const { html } = toHtml({ src: 'https://example.com/x.jpg', alt: malicious }, '');
|
||||
expect(html).not.toContain('onerror="alert(1)"');
|
||||
});
|
||||
|
||||
test('a placeholder/empty src emits no output', () => {
|
||||
const { html } = toHtml({ src: '' }, '');
|
||||
expect(html).toBe('');
|
||||
});
|
||||
|
||||
test('a normal image still renders correctly', () => {
|
||||
const { html } = toHtml({ src: 'https://example.com/photo.jpg', alt: 'A photo' }, '');
|
||||
expect(html).toContain('src="https://example.com/photo.jpg"');
|
||||
expect(html).toContain('alt="A photo"');
|
||||
});
|
||||
});
|
||||
@@ -27,3 +27,41 @@ describe('MapEmbed.toHtml iframe src ampersand encoding (F-export review Minor)'
|
||||
expect(srcMatch![1]).not.toMatch(/&(?!amp;)/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('MapEmbed.toHtml address/zoom/height XSS hardening', () => {
|
||||
test('a malicious address cannot break out of the src or title attribute', () => {
|
||||
const malicious = 'X" onerror="alert(1)';
|
||||
const { html } = toHtml({ address: malicious }, '');
|
||||
expect(html).not.toContain('onerror="alert(1)"');
|
||||
});
|
||||
|
||||
test('a wrong-typed zoom (string with attribute-breakout chars) cannot break out of the src attribute', () => {
|
||||
const malicious = '14"><script>alert(1)</script>' as any;
|
||||
const { html } = toHtml({ address: 'X', zoom: malicious }, '');
|
||||
expect(html).not.toContain('<script>alert(1)</script>');
|
||||
expect(html).not.toContain('"><script');
|
||||
});
|
||||
|
||||
test('a wrong-typed zoom is coerced to a safe numeric value in the exported URL (defense in depth beyond escaping)', () => {
|
||||
const malicious = '14"><script>alert(1)</script>' as any;
|
||||
const { html } = toHtml({ address: 'X', zoom: malicious }, '');
|
||||
const srcMatch = html.match(/<iframe src="([^"]+)"/);
|
||||
expect(srcMatch).toBeTruthy();
|
||||
// Decode the entity-escaped src back to a plain string and confirm the
|
||||
// `z=` param is a bare, well-formed number -- not the raw attacker string.
|
||||
const decoded = srcMatch![1].replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');
|
||||
expect(decoded).toMatch(/[&?]z=\d+(&|$)/);
|
||||
});
|
||||
|
||||
test('a malicious height cannot break out of the iframe style attribute', () => {
|
||||
const malicious = '400px" onmouseover="alert(1)';
|
||||
const { html } = toHtml({ address: 'X', height: malicious }, '');
|
||||
expect(html).not.toContain('onmouseover="alert(1)"');
|
||||
});
|
||||
|
||||
test('a normal zoom/height still renders correctly', () => {
|
||||
const { html } = toHtml({ address: 'X', zoom: 10, height: '300px' }, '');
|
||||
expect(html).toContain('z=10');
|
||||
expect(html).toContain('height:300px');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -12,7 +12,15 @@ interface MapEmbedProps {
|
||||
|
||||
function buildMapUrl(address: string, zoom: number): string {
|
||||
const encoded = encodeURIComponent(address);
|
||||
return `https://maps.google.com/maps?q=${encoded}&z=${zoom}&output=embed`;
|
||||
// `zoom` is declared as `number` but is not runtime-type-checked (AI
|
||||
// update_props / deserialized state can hand us anything). The final src
|
||||
// string is still run through escapeAttr(safeUrl(...)) at the toHtml call
|
||||
// site, which already blocks attribute-breakout -- but Number-coercing
|
||||
// here too keeps the emitted URL a well-formed `z=<digits>` query param
|
||||
// instead of smuggling arbitrary attacker text into it.
|
||||
const z = Number(zoom);
|
||||
const safeZoom = Number.isFinite(z) ? z : 14;
|
||||
return `https://maps.google.com/maps?q=${encoded}&z=${safeZoom}&output=embed`;
|
||||
}
|
||||
|
||||
export const MapEmbed: UserComponent<MapEmbedProps> = ({
|
||||
|
||||
@@ -72,6 +72,38 @@ describe('VideoBlock.toHtml iframe accessibility (F2.4)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('VideoBlock.toHtml overlay/innerMaxWidth XSS hardening (background mode)', () => {
|
||||
test('a malicious overlayColor cannot break out of the overlay style attribute', () => {
|
||||
const malicious = 'red" onmouseover="alert(1)';
|
||||
const { html } = toHtml({ videoUrl: 'https://vimeo.com/123456789', isBackground: true, overlayColor: malicious }, '');
|
||||
expect(html).not.toContain('onmouseover="alert(1)"');
|
||||
});
|
||||
|
||||
test('a wrong-typed overlayOpacity (string, not number) cannot break out of the overlay style attribute', () => {
|
||||
const malicious = '50" onmouseover="alert(1)' as any;
|
||||
const { html } = toHtml({ videoUrl: 'https://vimeo.com/123456789', isBackground: true, overlayOpacity: malicious }, '');
|
||||
expect(html).not.toContain('onmouseover="alert(1)"');
|
||||
});
|
||||
|
||||
test('a malicious innerMaxWidth cannot break out of the inner style attribute', () => {
|
||||
const malicious = '1200px" onmouseover="alert(1)';
|
||||
const { html } = toHtml({ videoUrl: 'https://vimeo.com/123456789', isBackground: true, innerMaxWidth: malicious }, '');
|
||||
expect(html).not.toContain('onmouseover="alert(1)"');
|
||||
});
|
||||
|
||||
test('a malicious style.borderRadius cannot break out of the style attribute (normal mode, iframe wrapper)', () => {
|
||||
const malicious = { borderRadius: '8px" onmouseover="alert(1)' } as any;
|
||||
const { html } = toHtml({ videoUrl: 'https://vimeo.com/123456789', style: malicious }, '');
|
||||
expect(html).not.toContain('onmouseover="alert(1)"');
|
||||
});
|
||||
|
||||
test('a malicious style.borderRadius cannot break out of the style attribute (direct file <video>)', () => {
|
||||
const malicious = { borderRadius: '8px" onmouseover="alert(1)' } as any;
|
||||
const { html } = toHtml({ videoUrl: 'https://example.com/clip.mp4', style: malicious }, '');
|
||||
expect(html).not.toContain('onmouseover="alert(1)"');
|
||||
});
|
||||
});
|
||||
|
||||
describe('VideoBlock.toHtml iframe src ampersand encoding (F-export review Minor)', () => {
|
||||
test('embed params joined with literal & are HTML-entity-encoded in the emitted src attribute', () => {
|
||||
// autoplay+muted+controls=false forces buildEmbedParams to concatenate
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { CSSProperties, useState } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeHtml, escapeAttr } from '../../utils/escape';
|
||||
import { escapeHtml, escapeAttr, cssValue } from '../../utils/escape';
|
||||
|
||||
interface AccordionItem {
|
||||
title: string;
|
||||
@@ -151,10 +151,12 @@ Accordion.craft = {
|
||||
...props.style,
|
||||
});
|
||||
const idAttr = props.anchorId ? ` id="${escapeAttr(props.anchorId)}"` : '';
|
||||
const headerBg = props.headerBg || '#f8fafc';
|
||||
const headerColor = props.headerColor || '#18181b';
|
||||
const contentBg = props.contentBg || '#ffffff';
|
||||
const borderColor = props.borderColor || '#e2e8f0';
|
||||
// Sanitized -- raw string-interpolation sinks in the <details>/<summary>
|
||||
// style attributes below.
|
||||
const headerBg = cssValue(props.headerBg) || '#f8fafc';
|
||||
const headerColor = cssValue(props.headerColor) || '#18181b';
|
||||
const contentBg = cssValue(props.contentBg) || '#ffffff';
|
||||
const borderColor = cssValue(props.borderColor) || '#e2e8f0';
|
||||
const items = props.items || defaultItems;
|
||||
|
||||
const panels = items.map((item, i) => {
|
||||
|
||||
@@ -2,7 +2,7 @@ import React, { CSSProperties } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { CtaButton, normalizeCtas, ctaInlineStyle, ctasToHtml } from './_cta-helpers';
|
||||
import { escapeHtml, escapeAttr } from '../../utils/escape';
|
||||
import { escapeHtml, escapeAttr, cssValue } from '../../utils/escape';
|
||||
|
||||
interface CallToActionProps {
|
||||
heading?: string;
|
||||
@@ -144,7 +144,9 @@ CallToAction.craft = {
|
||||
(CallToAction as any).toHtml = (props: CallToActionProps, _childrenHtml: string) => {
|
||||
const bgType = props.bgType || 'gradient';
|
||||
const bgValue = props.bgValue || defaultGradient;
|
||||
const textColor = props.textColor || '#ffffff';
|
||||
// Sanitized -- raw string-interpolation sink in the heading/description
|
||||
// style attributes below.
|
||||
const textColor = cssValue(props.textColor) || '#ffffff';
|
||||
const buttonColor = props.buttonColor || '#ffffff';
|
||||
const isButtonDark = buttonColor === '#ffffff' || buttonColor === '#f8fafc';
|
||||
const buttonTextColor = isButtonDark ? '#18181b' : '#ffffff';
|
||||
|
||||
@@ -91,3 +91,42 @@ describe('ContentSlider.toHtml autoplay silences aria-live and is pausable (F-ex
|
||||
expect(html).not.toMatch(/visibilitychange/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ContentSlider.toHtml renders slide.imageSrc as a background-image (INT)', () => {
|
||||
test('a slide with imageSrc set exports a background-image referencing it', () => {
|
||||
const slidesWithImage = [
|
||||
{ type: 'image' as const, imageSrc: 'https://example.com/photo.jpg', heading: 'One' },
|
||||
];
|
||||
const { html } = toHtml({ slides: slidesWithImage }, '');
|
||||
expect(html).toContain("background-image:url('https://example.com/photo.jpg')");
|
||||
});
|
||||
|
||||
test('a slide with no imageSrc falls back to bgColor (no broken/empty background-image url)', () => {
|
||||
const slidesNoImage = [
|
||||
{ type: 'image' as const, imageSrc: '', heading: 'One', bgColor: '#123456' },
|
||||
];
|
||||
const { html } = toHtml({ slides: slidesNoImage }, '');
|
||||
expect(html).not.toContain('background-image:url(');
|
||||
expect(html).toContain('background-color:#123456');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ContentSlider.toHtml interval is NOT runtime-type-checked -- must be coerced before it reaches the inline <script> numeric context', () => {
|
||||
test('a malicious interval string cannot inject arbitrary JS into the autoplay setInterval call', () => {
|
||||
const malicious = '5000);alert(document.domain);//';
|
||||
const { html } = toHtml({ slides, autoplay: true, interval: malicious }, '');
|
||||
expect(html).not.toContain('alert(document.domain)');
|
||||
// the setInterval call must still be well-formed with a plain numeral delay
|
||||
expect(html).toMatch(/setInterval\(function\(\)\{show\(current\+1\);\},\d+\);/);
|
||||
});
|
||||
|
||||
test('a non-numeric interval falls back to a safe default delay', () => {
|
||||
const { html } = toHtml({ slides, autoplay: true, interval: 'not-a-number' }, '');
|
||||
expect(html).toMatch(/setInterval\(function\(\)\{show\(current\+1\);\},5000\);/);
|
||||
});
|
||||
|
||||
test('a normal numeric interval still renders as the exact configured delay', () => {
|
||||
const { html } = toHtml({ slides, autoplay: true, interval: 3000 }, '');
|
||||
expect(html).toMatch(/setInterval\(function\(\)\{show\(current\+1\);\},3000\);/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { CSSProperties, useState, useEffect, useRef, useCallback } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeHtml, escapeAttr, safeUrl, scopeId } from '../../utils/escape';
|
||||
import { escapeHtml, escapeAttr, safeUrl, scopeId, cssValue } from '../../utils/escape';
|
||||
|
||||
interface Slide {
|
||||
type: 'image' | 'content';
|
||||
@@ -250,11 +250,24 @@ ContentSlider.craft = {
|
||||
} = props;
|
||||
|
||||
const items = slides.length > 0 ? slides : defaultSlides;
|
||||
// Number() coercion: `interval` is declared `number` in TS but is NOT
|
||||
// type-checked at runtime -- it arrives raw via the AI `update_props`
|
||||
// path or a deserialized saved-state blob and is interpolated directly
|
||||
// into the inline <script>'s `setInterval(fn, ${interval})` call below as
|
||||
// a bare JS numeral (no quotes around it). A string like
|
||||
// `5000);alert(1);//` would previously close the setInterval() call and
|
||||
// splice arbitrary JS into the page's own <script> tag -- worse than an
|
||||
// HTML attribute breakout, since it runs unconditionally on page load.
|
||||
// Number() of anything non-numeric collapses safely to NaN, so we fall
|
||||
// back to the 5000ms default rather than ever interpolating a
|
||||
// non-numeral.
|
||||
const intervalNum = Number(interval);
|
||||
const safeInterval = Number.isFinite(intervalNum) && intervalNum > 0 ? intervalNum : 5000;
|
||||
// Deterministic AND unique id, scoped on the Craft node id, for this
|
||||
// slider's slide/dot element ids and inline-script globals -- so two
|
||||
// ContentSlider instances (e.g. both left at default slides) don't
|
||||
// collide and end up driving each other's rotation.
|
||||
const uid = scopeId(nodeId, JSON.stringify(items) + interval, 'cs');
|
||||
const uid = scopeId(nodeId, JSON.stringify(items) + safeInterval, 'cs');
|
||||
|
||||
const sectionStyle = cssPropsToString({
|
||||
position: 'relative',
|
||||
@@ -266,11 +279,14 @@ ContentSlider.craft = {
|
||||
|
||||
const slidesHtml = items.map((slide, i) => {
|
||||
const hasBgImage = slide.imageSrc;
|
||||
// Sanitized -- slide.bgColor is a per-slide raw string-interpolation
|
||||
// sink (a malicious value could break out of the style="..." attribute).
|
||||
const safeBgColor = cssValue(slide.bgColor) || '#3b82f6';
|
||||
const bgStyle = hasBgImage
|
||||
? `background-image:url('${escapeAttr(safeUrl(slide.imageSrc!))}');background-size:cover;background-position:center`
|
||||
: slide.bgColor?.startsWith('linear-gradient')
|
||||
? `background-image:${slide.bgColor}`
|
||||
: `background-color:${slide.bgColor || '#3b82f6'}`;
|
||||
? `background-image:${safeBgColor}`
|
||||
: `background-color:${safeBgColor}`;
|
||||
|
||||
const contentParts: string[] = [];
|
||||
if (slide.heading) {
|
||||
@@ -336,7 +352,7 @@ ContentSlider.craft = {
|
||||
window["${uid}_prev"]=function(){ markManualNav(); show(current-1); };
|
||||
${autoplayActive ? `
|
||||
var timer=null;
|
||||
function start(){ if(!timer && document.visibilityState!=="hidden"){ timer=setInterval(function(){show(current+1);},${interval}); } }
|
||||
function start(){ if(!timer && document.visibilityState!=="hidden"){ timer=setInterval(function(){show(current+1);},${safeInterval}); } }
|
||||
function stop(){ if(timer){ clearInterval(timer); timer=null; } }
|
||||
var root=document.getElementById(uid);
|
||||
if(root){
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { CSSProperties, useEffect, useState } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeHtml, escapeAttr, scopeId } from '../../utils/escape';
|
||||
import { escapeHtml, escapeAttr, scopeId, cssValue } from '../../utils/escape';
|
||||
|
||||
interface CountdownProps {
|
||||
targetDate?: string;
|
||||
@@ -154,10 +154,12 @@ Countdown.craft = {
|
||||
targetDate = DEFAULT_TARGET,
|
||||
heading = 'Coming Soon',
|
||||
style = {},
|
||||
digitColor = '#ffffff',
|
||||
labelColor = 'rgba(255,255,255,0.7)',
|
||||
bgColor = '#18181b',
|
||||
} = props;
|
||||
// Sanitized -- raw string-interpolation sinks in the heading/digit/label
|
||||
// style attributes below.
|
||||
const digitColor = cssValue(props.digitColor) || '#ffffff';
|
||||
const labelColor = cssValue(props.labelColor) || 'rgba(255,255,255,0.7)';
|
||||
|
||||
const sectionStyle = cssPropsToString({
|
||||
padding: '60px 20px',
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { CSSProperties } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeHtml, escapeAttr, safeUrl, scopeId } from '../../utils/escape';
|
||||
import { escapeHtml, escapeAttr, safeUrl, scopeId, cssValue } from '../../utils/escape';
|
||||
|
||||
interface GalleryImage {
|
||||
src: string;
|
||||
@@ -130,8 +130,14 @@ Gallery.craft = {
|
||||
...props.style,
|
||||
});
|
||||
const images = props.images || defaultImages;
|
||||
const columns = props.columns || 3;
|
||||
const gap = props.gap || '16px';
|
||||
// Number() coercion: `columns` is a raw string-interpolation sink into the
|
||||
// grid style attribute below (repeat(${columns},1fr)) -- a non-numeric
|
||||
// (e.g. hand-crafted/AI-generated tree) value would otherwise be able to
|
||||
// break out; Number() of anything non-numeric collapses safely to NaN.
|
||||
const columns = Number(props.columns) || 3;
|
||||
// Sanitized -- gap is a raw string-interpolation sink into the grid style
|
||||
// attribute below.
|
||||
const gap = cssValue(props.gap) || '16px';
|
||||
const lightbox = props.lightbox || false;
|
||||
|
||||
// Deterministic AND unique id, scoped on the Craft node id, for this
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, test, expect } from 'vitest';
|
||||
import { HeroSimple } from './HeroSimple';
|
||||
|
||||
const toHtml = (HeroSimple as any).toHtml;
|
||||
|
||||
describe('HeroSimple.toHtml textAlign enum sink (attacker-controlled prop, not enforced at runtime)', () => {
|
||||
test('malicious textAlign value cannot break out of the content div style attribute', () => {
|
||||
const { html } = toHtml({
|
||||
heading: 'Hi',
|
||||
subtitle: 'There',
|
||||
textAlign: 'center;"><script>alert(1)</script>',
|
||||
}, '');
|
||||
expect(html).not.toContain('<script>alert(1)</script>');
|
||||
expect(html).not.toContain('center;">');
|
||||
});
|
||||
|
||||
test('unrecognized textAlign value falls back to a safe default rather than being echoed raw', () => {
|
||||
const { html } = toHtml({ heading: 'Hi', subtitle: 'There', textAlign: 'not-a-real-value' as any }, '');
|
||||
expect(html).not.toContain('text-align:not-a-real-value');
|
||||
});
|
||||
|
||||
test('valid textAlign values are preserved', () => {
|
||||
const { html: left } = toHtml({ heading: 'Hi', subtitle: 'There', textAlign: 'left' }, '');
|
||||
expect(left).toContain('text-align:left');
|
||||
const { html: right } = toHtml({ heading: 'Hi', subtitle: 'There', textAlign: 'right' }, '');
|
||||
expect(right).toContain('text-align:right');
|
||||
});
|
||||
|
||||
test('normal default render is sane', () => {
|
||||
const { html } = toHtml({ heading: 'Welcome', subtitle: 'Sub text' }, '');
|
||||
expect(html).toContain('Welcome');
|
||||
expect(html).toContain('Sub text');
|
||||
expect(html).toContain('text-align:center');
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,7 @@ import React, { CSSProperties } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { CtaButton, normalizeCtas, ctaInlineStyle, ctasToHtml } from './_cta-helpers';
|
||||
import { escapeHtml, escapeAttr, safeUrl } from '../../utils/escape';
|
||||
import { escapeHtml, escapeAttr, safeUrl, cssValue } from '../../utils/escape';
|
||||
|
||||
interface HeroProps {
|
||||
heading?: string;
|
||||
@@ -220,7 +220,8 @@ HeroSimple.craft = {
|
||||
|
||||
let overlayHtml = '';
|
||||
if ((props.overlayOpacity || 0) > 0) {
|
||||
overlayHtml = `<div style="position:absolute;top:0;left:0;right:0;bottom:0;background-color:${props.overlayColor || '#000'};opacity:${(props.overlayOpacity || 0) / 100};z-index:1"></div>`;
|
||||
const overlayColor = cssValue(props.overlayColor) || '#000';
|
||||
overlayHtml = `<div style="position:absolute;top:0;left:0;right:0;bottom:0;background-color:${overlayColor};opacity:${(props.overlayOpacity || 0) / 100};z-index:1"></div>`;
|
||||
}
|
||||
|
||||
let videoHtml = '';
|
||||
@@ -228,7 +229,13 @@ HeroSimple.craft = {
|
||||
videoHtml = `<video src="${escapeAttr(safeUrl(props.bgVideo))}" autoplay muted loop playsinline style="position:absolute;top:0;left:0;width:100%;height:100%;object-fit:cover;z-index:0"></video>`;
|
||||
}
|
||||
|
||||
const textAlign = props.textAlign || 'center';
|
||||
// Allowlisted -- `textAlign` is declared as a 'left'|'center'|'right' union
|
||||
// but arrives unchecked via AI update_props / deserialized state; it is
|
||||
// interpolated raw into the content div's style attribute below, so any
|
||||
// other value must collapse to a known-safe default rather than being
|
||||
// echoed into the markup.
|
||||
const ALLOWED_TEXT_ALIGN = ['left', 'center', 'right'];
|
||||
const textAlign = ALLOWED_TEXT_ALIGN.includes(props.textAlign as string) ? (props.textAlign as string) : 'center';
|
||||
const justifyBtn = textAlign === 'center' ? 'center' : textAlign === 'right' ? 'flex-end' : 'flex-start';
|
||||
|
||||
const ctas = normalizeCtas(props);
|
||||
@@ -239,12 +246,13 @@ HeroSimple.craft = {
|
||||
});
|
||||
|
||||
const idAttr = props.anchorId ? ` id="${escapeAttr(props.anchorId)}"` : '';
|
||||
const heroTextColor = cssValue(props.textColor) || '#fff';
|
||||
return {
|
||||
html: `<section${idAttr} style="${sectionStyle}">
|
||||
${videoHtml}${overlayHtml}
|
||||
<div style="max-width:800px;width:100%;position:relative;z-index:2;text-align:${textAlign}">
|
||||
<h1 style="font-size:48px;font-weight:700;color:${props.textColor || '#fff'};margin-bottom:16px;line-height:1.2">${escapeHtml(props.heading || '')}</h1>
|
||||
<p style="font-size:20px;color:${props.textColor || '#fff'};opacity:0.85;margin-bottom:32px;line-height:1.6;white-space:pre-line">${escapeHtml(props.subtitle || '')}</p>
|
||||
<h1 style="font-size:48px;font-weight:700;color:${heroTextColor};margin-bottom:16px;line-height:1.2">${escapeHtml(props.heading || '')}</h1>
|
||||
<p style="font-size:20px;color:${heroTextColor};opacity:0.85;margin-bottom:32px;line-height:1.6;white-space:pre-line">${escapeHtml(props.subtitle || '')}</p>
|
||||
<div style="display:flex;gap:12px;justify-content:${justifyBtn};flex-wrap:wrap">${buttonsHtml}</div>
|
||||
</div>
|
||||
</section>`,
|
||||
|
||||
@@ -47,3 +47,29 @@ describe('NumberCounter.toHtml deterministic + unique scope ids (thread node id,
|
||||
expect(wrapId1).not.toBe(wrapId2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('NumberCounter.toHtml counter.number is NOT runtime-type-checked -- must be sanitized before it reaches data-target', () => {
|
||||
test('a malicious counter.number cannot break out of the data-target attribute to inject a <script> tag', () => {
|
||||
const malicious = [
|
||||
{ number: '150"><script>alert(1)</script>', suffix: '+', label: 'Evil' },
|
||||
];
|
||||
const { html } = toHtml({ counters: malicious }, '', 'node-nc-evil1');
|
||||
expect(html).not.toContain('<script>alert(1)</script>');
|
||||
expect(html).not.toContain('"><script>');
|
||||
});
|
||||
|
||||
test('a malicious counter.number cannot break out of the data-target attribute to inject an onmouseover handler', () => {
|
||||
const malicious = [
|
||||
{ number: '150" onmouseover="alert(1)', suffix: '+', label: 'Evil' },
|
||||
];
|
||||
const { html } = toHtml({ counters: malicious }, '', 'node-nc-evil2');
|
||||
expect(html).not.toContain('onmouseover=');
|
||||
expect(html).not.toMatch(/data-target="150" onmouseover/);
|
||||
});
|
||||
|
||||
test('normal numeric counter.number values still render as data-target="150"', () => {
|
||||
const normal = [{ number: 150, suffix: '+', label: 'Projects' }];
|
||||
const { html } = toHtml({ counters: normal }, '', 'node-nc-normal');
|
||||
expect(html).toContain('data-target="150"');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { CSSProperties } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeHtml, escapeAttr, scopeId } from '../../utils/escape';
|
||||
import { escapeHtml, escapeAttr, scopeId, cssValue } from '../../utils/escape';
|
||||
|
||||
interface Counter {
|
||||
number: number;
|
||||
@@ -112,12 +112,17 @@ NumberCounter.craft = {
|
||||
(NumberCounter as any).toHtml = (props: NumberCounterProps, _childrenHtml: string, nodeId?: string) => {
|
||||
const {
|
||||
counters = defaultCounters,
|
||||
columns = 4,
|
||||
numberColor = '#3b82f6',
|
||||
labelColor = '#6b7280',
|
||||
numberSize = '48px',
|
||||
style = {},
|
||||
} = props;
|
||||
// Number() coercion: `columns` is a raw string-interpolation sink into the
|
||||
// grid style attribute below (repeat(${columns},1fr)); Number() of
|
||||
// anything non-numeric collapses safely to NaN instead of breaking out.
|
||||
const columns = Number(props.columns) || 4;
|
||||
// Sanitized -- raw string-interpolation sinks in the counter/label spans
|
||||
// below.
|
||||
const numberColor = cssValue(props.numberColor) || '#3b82f6';
|
||||
const labelColor = cssValue(props.labelColor) || '#6b7280';
|
||||
const numberSize = cssValue(props.numberSize) || '48px';
|
||||
|
||||
const items = counters.length > 0 ? counters : defaultCounters;
|
||||
|
||||
@@ -135,8 +140,20 @@ NumberCounter.craft = {
|
||||
});
|
||||
|
||||
const countersHtml = items.map((counter, i) => {
|
||||
// Number() coercion + escapeAttr: `counter.number` is declared `number`
|
||||
// per-item inside an array prop, but is NOT type-checked at runtime --
|
||||
// it arrives raw via the AI `update_props` path or a deserialized
|
||||
// saved-state blob and was previously interpolated straight into this
|
||||
// data-target attribute, letting a string like `150"><script>...`
|
||||
// break out of the attribute and inject markup. Number() collapses any
|
||||
// non-numeric value safely to NaN (then 0), and escapeAttr is kept as
|
||||
// defense-in-depth in case Number()'s string coercion output ever
|
||||
// contains a stray character (it can't today, but the sink should never
|
||||
// rely solely on the coercion).
|
||||
const numberVal = Number(counter.number);
|
||||
const safeNumber = Number.isFinite(numberVal) ? numberVal : 0;
|
||||
return `<div style="display:flex;flex-direction:column;align-items:center;gap:8px">
|
||||
<span id="${uid}_n${i}" data-target="${counter.number}" data-suffix="${escapeAttr(counter.suffix)}" style="font-size:${numberSize};font-weight:700;color:${numberColor};line-height:1.1;font-family:Inter,sans-serif">0${escapeHtml(counter.suffix)}</span>
|
||||
<span id="${uid}_n${i}" data-target="${escapeAttr(String(safeNumber))}" data-suffix="${escapeAttr(counter.suffix)}" style="font-size:${numberSize};font-weight:700;color:${numberColor};line-height:1.1;font-family:Inter,sans-serif">0${escapeHtml(counter.suffix)}</span>
|
||||
<span style="font-size:15px;color:${labelColor};font-family:Inter,sans-serif;font-weight:500">${escapeHtml(counter.label)}</span>
|
||||
</div>`;
|
||||
}).join('\n ');
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { CSSProperties } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeHtml, escapeAttr, safeUrl } from '../../utils/escape';
|
||||
import { escapeHtml, escapeAttr, safeUrl, cssValue } from '../../utils/escape';
|
||||
|
||||
interface PricingPlan {
|
||||
name: string;
|
||||
@@ -225,7 +225,9 @@ PricingTable.craft = {
|
||||
});
|
||||
const idAttr = props.anchorId ? ` id="${escapeAttr(props.anchorId)}"` : '';
|
||||
const plans = props.plans || defaultPlans;
|
||||
const featuredBg = props.featuredBg || '#3b82f6';
|
||||
// Sanitized -- featuredBg is a raw string-interpolation sink below (drives
|
||||
// cardBg/btnBg/btnColor, all raw-interpolated into style="...").
|
||||
const featuredBg = cssValue(props.featuredBg) || '#3b82f6';
|
||||
|
||||
const cards = plans.map((plan) => {
|
||||
const cardBg = plan.isFeatured ? featuredBg : '#ffffff';
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { CSSProperties, useState } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeHtml, escapeAttr, scopeId } from '../../utils/escape';
|
||||
import { escapeHtml, escapeAttr, scopeId, cssValue } from '../../utils/escape';
|
||||
|
||||
interface TabItem {
|
||||
label: string;
|
||||
@@ -131,11 +131,15 @@ Tabs.craft = {
|
||||
});
|
||||
const idAttr = props.anchorId ? ` id="${escapeAttr(props.anchorId)}"` : '';
|
||||
const tabs = props.tabs || defaultTabs;
|
||||
const activeTabBg = props.activeTabBg || '#3b82f6';
|
||||
const activeTabColor = props.activeTabColor || '#ffffff';
|
||||
const inactiveTabBg = props.inactiveTabBg || '#f1f5f9';
|
||||
const inactiveTabColor = props.inactiveTabColor || '#64748b';
|
||||
const contentBg = props.contentBg || '#ffffff';
|
||||
// Sanitized -- raw string-interpolation sinks below, both into style="..."
|
||||
// attributes AND into an inline <script> as single-quoted JS string
|
||||
// literals (a stray `'` there breaks out of the JS string, not just CSS);
|
||||
// cssValue strips quotes too so it neutralizes both contexts at once.
|
||||
const activeTabBg = cssValue(props.activeTabBg) || '#3b82f6';
|
||||
const activeTabColor = cssValue(props.activeTabColor) || '#ffffff';
|
||||
const inactiveTabBg = cssValue(props.inactiveTabBg) || '#f1f5f9';
|
||||
const inactiveTabColor = cssValue(props.inactiveTabColor) || '#64748b';
|
||||
const contentBg = cssValue(props.contentBg) || '#ffffff';
|
||||
|
||||
// tabId scopes the functional wiring (onclick/getElementById) as well as
|
||||
// the ARIA tab<->panel linking ids. It must be BOTH deterministic (so
|
||||
|
||||
@@ -46,3 +46,28 @@ describe('Testimonials.toHtml decorative star icons (F2.5)', () => {
|
||||
stars.forEach((tag: string) => expect(tag).toContain('aria-hidden="true"'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('Testimonials.toHtml rating aria-label sink (attacker-controlled `rating`, typed number but unchecked)', () => {
|
||||
test('malicious rating value cannot break out of the star row aria-label attribute', () => {
|
||||
const malicious = [
|
||||
{ quote: 'Q', name: 'N', title: 'T', rating: '5"><script>alert(1)</script>' as any },
|
||||
];
|
||||
const { html } = toHtml({ testimonials: malicious, layout: 'grid' }, '');
|
||||
expect(html).not.toContain('<script>alert(1)</script>');
|
||||
expect(html).not.toContain('5"><script>');
|
||||
});
|
||||
|
||||
test('non-numeric rating falls back to a safe numeric value', () => {
|
||||
const malicious = [
|
||||
{ quote: 'Q', name: 'N', title: 'T', rating: 'not-a-number' as any },
|
||||
];
|
||||
const { html } = toHtml({ testimonials: malicious, layout: 'grid' }, '');
|
||||
expect(html).toMatch(/aria-label="Rating: 0 out of 5"/);
|
||||
});
|
||||
|
||||
test('normal numeric rating still renders correctly', () => {
|
||||
const { html } = toHtml({ testimonials, layout: 'grid' }, '');
|
||||
expect(html).toContain('aria-label="Rating: 5 out of 5"');
|
||||
expect(html).toContain('aria-label="Rating: 4 out of 5"');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { CSSProperties } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeHtml, escapeAttr } from '../../utils/escape';
|
||||
import { escapeHtml, escapeAttr, cssValue } from '../../utils/escape';
|
||||
|
||||
interface Testimonial {
|
||||
quote: string;
|
||||
@@ -41,10 +41,16 @@ function renderStars(count: number, color: string): React.ReactNode {
|
||||
}
|
||||
|
||||
function starsHtml(count: number, color: string): string {
|
||||
// `count` is `Testimonial.rating`, typed `number` but arrives unchecked via
|
||||
// AI update_props / deserialized state -- coerce to a real number before
|
||||
// it's interpolated into the aria-label attribute below (both the loop
|
||||
// comparison and the escapeAttr(String(...)) call are safe against any
|
||||
// non-numeric/garbage value).
|
||||
const safeCount = Number(count) || 0;
|
||||
const stars = [1, 2, 3, 4, 5].map((i) =>
|
||||
`<i class="fa ${i <= count ? 'fa-star' : 'fa-star-o'}" style="color:${color};font-size:14px" aria-hidden="true"></i>`
|
||||
`<i class="fa ${i <= safeCount ? 'fa-star' : 'fa-star-o'}" style="color:${color};font-size:14px" aria-hidden="true"></i>`
|
||||
).join('');
|
||||
return `<div style="display:flex;gap:2px;justify-content:center;margin-bottom:12px" role="img" aria-label="Rating: ${count} out of 5">${stars}</div>`;
|
||||
return `<div style="display:flex;gap:2px;justify-content:center;margin-bottom:12px" role="img" aria-label="${escapeAttr(`Rating: ${safeCount} out of 5`)}">${stars}</div>`;
|
||||
}
|
||||
|
||||
export const Testimonials: UserComponent<TestimonialsProps> = ({
|
||||
@@ -139,11 +145,16 @@ Testimonials.craft = {
|
||||
const {
|
||||
testimonials = defaultTestimonials,
|
||||
layout = 'grid',
|
||||
columns = 3,
|
||||
style = {},
|
||||
cardBg = '#f8fafc',
|
||||
starColor = '#f59e0b',
|
||||
} = props;
|
||||
// Number() coercion: `columns` is a raw string-interpolation sink into the
|
||||
// grid style attribute below (repeat(${columns},1fr)); Number() of
|
||||
// anything non-numeric collapses safely to NaN instead of breaking out.
|
||||
const columns = Number(props.columns) || 3;
|
||||
// Sanitized -- raw string-interpolation sinks below (cardCss / starsHtml
|
||||
// style attributes).
|
||||
const cardBg = cssValue(props.cardBg) || '#f8fafc';
|
||||
const starColor = cssValue(props.starColor) || '#f59e0b';
|
||||
|
||||
const items = testimonials.length > 0 ? testimonials : defaultTestimonials;
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { CSSProperties } from 'react';
|
||||
import { escapeHtml, escapeAttr, safeUrl } from '../../utils/escape';
|
||||
import { escapeHtml, escapeAttr, safeUrl, cssValue } from '../../utils/escape';
|
||||
|
||||
export type CtaVariant = 'primary' | 'outline' | 'ghost';
|
||||
|
||||
@@ -68,14 +68,21 @@ export function ctaInlineStyle(cta: CtaButton, defaults: CtaStyleDefaults): CSSP
|
||||
|
||||
export function ctaCssString(cta: CtaButton, defaults: CtaStyleDefaults): string {
|
||||
const variant = cta.variant || 'primary';
|
||||
// Sanitized -- these are raw string-interpolation sinks into style="...".
|
||||
// Callers pass user-controlled design-token colors (e.g. HeroSimple's
|
||||
// buttonBgColor/buttonTextColor/textColor) through CtaStyleDefaults, so
|
||||
// sanitize once here rather than at every call site.
|
||||
const outlineText = cssValue(defaults.outlineText) || '#000000';
|
||||
const primaryBg = cssValue(defaults.primaryBg) || '#000000';
|
||||
const primaryText = cssValue(defaults.primaryText) || '#ffffff';
|
||||
switch (variant) {
|
||||
case 'outline':
|
||||
return `display:inline-block;padding:14px 36px;background-color:transparent;color:${defaults.outlineText};text-decoration:none;border-radius:8px;font-weight:600;font-size:16px;border:2px solid ${defaults.outlineText}`;
|
||||
return `display:inline-block;padding:14px 36px;background-color:transparent;color:${outlineText};text-decoration:none;border-radius:8px;font-weight:600;font-size:16px;border:2px solid ${outlineText}`;
|
||||
case 'ghost':
|
||||
return `display:inline-block;padding:14px 24px;background-color:transparent;color:${defaults.outlineText};text-decoration:underline;border-radius:8px;font-weight:600;font-size:16px`;
|
||||
return `display:inline-block;padding:14px 24px;background-color:transparent;color:${outlineText};text-decoration:underline;border-radius:8px;font-weight:600;font-size:16px`;
|
||||
case 'primary':
|
||||
default:
|
||||
return `display:inline-block;padding:14px 36px;background-color:${defaults.primaryBg};color:${defaults.primaryText};text-decoration:none;border-radius:8px;font-weight:600;font-size:16px`;
|
||||
return `display:inline-block;padding:14px 36px;background-color:${primaryBg};color:${primaryText};text-decoration:none;border-radius:8px;font-weight:600;font-size:16px`;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, test, expect, afterEach } from 'vitest';
|
||||
import { getClipboardNodeId, setClipboardNodeId } from './clipboard';
|
||||
|
||||
describe('clipboard', () => {
|
||||
afterEach(() => {
|
||||
setClipboardNodeId(null);
|
||||
});
|
||||
|
||||
test('starts empty', () => {
|
||||
expect(getClipboardNodeId()).toBeNull();
|
||||
});
|
||||
|
||||
test('set then get returns the stored node id', () => {
|
||||
setClipboardNodeId('node-123');
|
||||
expect(getClipboardNodeId()).toBe('node-123');
|
||||
});
|
||||
|
||||
test('is a shared module-level store -- overwriting replaces the previous value', () => {
|
||||
setClipboardNodeId('first');
|
||||
setClipboardNodeId('second');
|
||||
expect(getClipboardNodeId()).toBe('second');
|
||||
});
|
||||
|
||||
test('can be cleared back to null', () => {
|
||||
setClipboardNodeId('node-123');
|
||||
setClipboardNodeId(null);
|
||||
expect(getClipboardNodeId()).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* Tiny shared clipboard for canvas node copy/paste.
|
||||
*
|
||||
* Both the context menu (right-click Copy/Paste) and the keyboard shortcuts
|
||||
* hook (Ctrl/Cmd+C / Ctrl/Cmd+V) read and write this single module-level
|
||||
* store, so copying a node via one entry point and pasting via the other
|
||||
* behaves consistently instead of each maintaining its own clipboard.
|
||||
*
|
||||
* Deliberately not React state -- nothing in the UI needs to re-render
|
||||
* reactively when the clipboard changes; consumers just read the current
|
||||
* value at the moment they need it (on paste, or when a menu opens).
|
||||
*/
|
||||
let clipboardNodeId: string | null = null;
|
||||
|
||||
/** Returns the id of the node currently on the clipboard, or null if empty. */
|
||||
export function getClipboardNodeId(): string | null {
|
||||
return clipboardNodeId;
|
||||
}
|
||||
|
||||
/** Sets (or clears, with `null`) the node id on the clipboard. */
|
||||
export function setClipboardNodeId(nodeId: string | null): void {
|
||||
clipboardNodeId = nodeId;
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import React from 'react';
|
||||
import { createRoot, Root } from 'react-dom/client';
|
||||
import { act } from 'react-dom/test-utils';
|
||||
import type { NodeTree, Node } from '@craftjs/core';
|
||||
import { useKeyboardShortcuts } from './useKeyboardShortcuts';
|
||||
import { getClipboardNodeId, setClipboardNodeId } from './clipboard';
|
||||
|
||||
/**
|
||||
* Regression coverage: Ctrl/Cmd+V must run the copied subtree through
|
||||
* `regenerateTreeIds` BEFORE handing it to `actions.addNodeTree`. Pasting
|
||||
* with the source node's ORIGINAL ids re-inserted them into the live Craft.js
|
||||
* node map, producing duplicate ids and corrupting the tree -- that bug is
|
||||
* exactly what this suite guards against. Also covers the sibling-parent /
|
||||
* ROOT-fallback targeting, the empty-clipboard no-op, and the existing
|
||||
* input-focus guard.
|
||||
*
|
||||
* Mock pattern mirrors PageContext.pure-updaters.test.tsx /
|
||||
* PageContext.slug.test.tsx: a fake `useEditor` exposing `query`/`actions`,
|
||||
* mounted via a bare consumer component, with REAL `keydown` events
|
||||
* dispatched on `document` (where useKeyboardShortcuts attaches its
|
||||
* listener) to exercise the actual handler rather than calling it directly.
|
||||
*
|
||||
* `regenerateTreeIds` itself is NOT mocked -- we partially mock
|
||||
* `../utils/craft-tree` to wrap the real implementation in a `vi.fn()` so we
|
||||
* can assert it was called, while still getting genuinely fresh ids back.
|
||||
*/
|
||||
|
||||
const addNodeTreeMock = vi.fn();
|
||||
let selectedIds: string[] = [];
|
||||
|
||||
function makeNode(id: string, parent: string | null, children: string[] = []): Node {
|
||||
return {
|
||||
id,
|
||||
data: {
|
||||
props: {},
|
||||
type: { resolvedName: 'Container' },
|
||||
name: 'Container',
|
||||
displayName: 'Container',
|
||||
isCanvas: false,
|
||||
parent,
|
||||
linkedNodes: {},
|
||||
nodes: children,
|
||||
hidden: false,
|
||||
},
|
||||
info: {},
|
||||
events: { selected: false, dragged: false, hovered: false },
|
||||
dom: null,
|
||||
related: {},
|
||||
rules: {},
|
||||
_hydrationTimestamp: 0,
|
||||
} as unknown as Node;
|
||||
}
|
||||
|
||||
// The tree `toNodeTree()` returns for the node that was Ctrl+C'd -- a root
|
||||
// with one child, so regeneration has more than one id to remap.
|
||||
const COPIED_TREE: NodeTree = {
|
||||
rootNodeId: 'copied-root-1',
|
||||
nodes: {
|
||||
'copied-root-1': makeNode('copied-root-1', null, ['copied-child-1']),
|
||||
'copied-child-1': makeNode('copied-child-1', 'copied-root-1'),
|
||||
},
|
||||
};
|
||||
|
||||
const nodeStore: Record<string, { data: { parent: string | null } }> = {
|
||||
'selected-1': { data: { parent: 'parent-container-1' } },
|
||||
ROOT: { data: { parent: null } },
|
||||
'copied-root-1': { data: { parent: 'wherever-it-originally-lived' } },
|
||||
};
|
||||
|
||||
function makeQueryNode(id: string) {
|
||||
return {
|
||||
get: () => nodeStore[id] ?? null,
|
||||
toNodeTree: () => {
|
||||
if (id !== 'copied-root-1') {
|
||||
throw new Error(`unexpected toNodeTree() call for "${id}"`);
|
||||
}
|
||||
return COPIED_TREE;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
vi.mock('@craftjs/core', () => ({
|
||||
useEditor: () => ({
|
||||
query: {
|
||||
getEvent: () => ({ all: () => selectedIds }),
|
||||
node: (id: string) => makeQueryNode(id),
|
||||
},
|
||||
actions: {
|
||||
addNodeTree: addNodeTreeMock,
|
||||
history: { undo: vi.fn(), redo: vi.fn() },
|
||||
delete: vi.fn(),
|
||||
clearEvents: vi.fn(),
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
// Partial mock: keep the real `regenerateTreeIds` implementation (so pasted
|
||||
// trees genuinely get fresh ids) but wrap it in a spy so we can assert the
|
||||
// handler actually calls it, rather than only inferring that from the
|
||||
// output.
|
||||
vi.mock('../utils/craft-tree', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../utils/craft-tree')>();
|
||||
return {
|
||||
...actual,
|
||||
regenerateTreeIds: vi.fn(actual.regenerateTreeIds),
|
||||
};
|
||||
});
|
||||
|
||||
import { regenerateTreeIds } from '../utils/craft-tree';
|
||||
const regenerateTreeIdsMock = vi.mocked(regenerateTreeIds);
|
||||
|
||||
let container: HTMLDivElement;
|
||||
let root: Root;
|
||||
|
||||
function render(ui: React.ReactElement) {
|
||||
container = document.createElement('div');
|
||||
document.body.appendChild(container);
|
||||
act(() => {
|
||||
root = createRoot(container);
|
||||
root.render(ui);
|
||||
});
|
||||
}
|
||||
|
||||
function unmount() {
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
container.remove();
|
||||
}
|
||||
|
||||
function pressKey(key: string, opts: Partial<KeyboardEventInit> = {}) {
|
||||
act(() => {
|
||||
document.dispatchEvent(
|
||||
new KeyboardEvent('keydown', { key, ctrlKey: true, bubbles: true, cancelable: true, ...opts }),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
const Consumer: React.FC = () => {
|
||||
useKeyboardShortcuts();
|
||||
return null;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
selectedIds = [];
|
||||
addNodeTreeMock.mockClear();
|
||||
regenerateTreeIdsMock.mockClear();
|
||||
setClipboardNodeId(null);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
setClipboardNodeId(null);
|
||||
if (root) unmount();
|
||||
});
|
||||
|
||||
describe('useKeyboardShortcuts: Ctrl/Cmd+C / Ctrl/Cmd+V', () => {
|
||||
test('Ctrl+C copies the selected node id to the clipboard', () => {
|
||||
render(<Consumer />);
|
||||
selectedIds = ['selected-1'];
|
||||
|
||||
pressKey('c');
|
||||
|
||||
expect(getClipboardNodeId()).toBe('selected-1');
|
||||
});
|
||||
|
||||
test('Ctrl+V pastes as a sibling of the selection (selected node`s data.parent) with FRESH ids', () => {
|
||||
render(<Consumer />);
|
||||
|
||||
selectedIds = ['copied-root-1'];
|
||||
pressKey('c');
|
||||
expect(getClipboardNodeId()).toBe('copied-root-1');
|
||||
|
||||
selectedIds = ['selected-1'];
|
||||
pressKey('v');
|
||||
|
||||
// regenerateTreeIds actually ran before the tree was handed to Craft.js.
|
||||
expect(regenerateTreeIdsMock).toHaveBeenCalledTimes(1);
|
||||
expect(regenerateTreeIdsMock).toHaveBeenCalledWith(COPIED_TREE);
|
||||
|
||||
expect(addNodeTreeMock).toHaveBeenCalledTimes(1);
|
||||
const [pastedTree, targetParent] = addNodeTreeMock.mock.calls[0];
|
||||
|
||||
// Sibling of the current selection: selected-1's data.parent.
|
||||
expect(targetParent).toBe('parent-container-1');
|
||||
|
||||
// The regression this guards: pasted ids must be fresh, never reuse the
|
||||
// ids the copied node already occupies in the live Craft.js tree.
|
||||
expect(pastedTree.rootNodeId).not.toBe(COPIED_TREE.rootNodeId);
|
||||
const originalIds = new Set(Object.keys(COPIED_TREE.nodes));
|
||||
const pastedIds = new Set(Object.keys(pastedTree.nodes));
|
||||
expect(pastedIds.size).toBe(originalIds.size);
|
||||
for (const id of pastedIds) {
|
||||
expect(originalIds.has(id)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
test('Ctrl+V with selection at ROOT falls back to ROOT as the insertion parent', () => {
|
||||
render(<Consumer />);
|
||||
|
||||
selectedIds = ['copied-root-1'];
|
||||
pressKey('c');
|
||||
|
||||
selectedIds = ['ROOT'];
|
||||
pressKey('v');
|
||||
|
||||
expect(addNodeTreeMock).toHaveBeenCalledTimes(1);
|
||||
const [, targetParent] = addNodeTreeMock.mock.calls[0];
|
||||
expect(targetParent).toBe('ROOT');
|
||||
});
|
||||
|
||||
test('Ctrl+V with an empty clipboard is a no-op', () => {
|
||||
render(<Consumer />);
|
||||
selectedIds = ['selected-1'];
|
||||
|
||||
pressKey('v');
|
||||
|
||||
expect(addNodeTreeMock).not.toHaveBeenCalled();
|
||||
expect(regenerateTreeIdsMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('shortcuts are ignored while focus is in an input element', () => {
|
||||
const input = document.createElement('input');
|
||||
document.body.appendChild(input);
|
||||
input.focus();
|
||||
expect(document.activeElement).toBe(input);
|
||||
|
||||
render(<Consumer />);
|
||||
selectedIds = ['selected-1'];
|
||||
|
||||
pressKey('c');
|
||||
expect(getClipboardNodeId()).toBeNull();
|
||||
|
||||
setClipboardNodeId('copied-root-1');
|
||||
pressKey('v');
|
||||
expect(addNodeTreeMock).not.toHaveBeenCalled();
|
||||
|
||||
input.remove();
|
||||
});
|
||||
|
||||
test('shortcuts are ignored while focus is in a contentEditable element', () => {
|
||||
// jsdom does not implement `HTMLElement.isContentEditable` (it always
|
||||
// reports false regardless of the contentEditable attribute -- a known
|
||||
// jsdom limitation), so a real contentEditable + focus() can't exercise
|
||||
// this branch of the guard. Stub `document.activeElement` directly with
|
||||
// a fake element that reports isContentEditable: true, matching what
|
||||
// the guard (`isInputFocused` in useKeyboardShortcuts.ts) actually reads.
|
||||
const fakeEditable = { tagName: 'DIV', isContentEditable: true } as unknown as Element;
|
||||
const activeElementSpy = vi.spyOn(document, 'activeElement', 'get').mockReturnValue(fakeEditable);
|
||||
|
||||
render(<Consumer />);
|
||||
selectedIds = ['selected-1'];
|
||||
|
||||
pressKey('c');
|
||||
expect(getClipboardNodeId()).toBeNull();
|
||||
|
||||
activeElementSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import { useEffect } from 'react';
|
||||
import { useEditor } from '@craftjs/core';
|
||||
import { findDeletableTarget } from '../utils/craft-helpers';
|
||||
import { regenerateTreeIds } from '../utils/craft-tree';
|
||||
import { getClipboardNodeId, setClipboardNodeId } from './clipboard';
|
||||
|
||||
function isInputFocused(): boolean {
|
||||
const el = document.activeElement;
|
||||
@@ -85,6 +86,45 @@ export function useKeyboardShortcuts() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Ctrl+C: copy selected node id to the shared clipboard
|
||||
if (ctrl && (e.key === 'c' || e.key === 'C')) {
|
||||
e.preventDefault();
|
||||
try {
|
||||
const selected = query.getEvent('selected').all();
|
||||
if (selected.length > 0 && selected[0] !== 'ROOT') {
|
||||
setClipboardNodeId(selected[0]);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Copy failed:', err);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Ctrl+V: paste the clipboard node as a sibling of the current selection
|
||||
if (ctrl && (e.key === 'v' || e.key === 'V')) {
|
||||
e.preventDefault();
|
||||
try {
|
||||
const sourceId = getClipboardNodeId();
|
||||
if (!sourceId || !query.node(sourceId).get()) return;
|
||||
|
||||
const selected = query.getEvent('selected').all();
|
||||
if (selected.length === 0) return;
|
||||
const selectedId = selected[0];
|
||||
|
||||
let targetParent = 'ROOT';
|
||||
if (selectedId !== 'ROOT') {
|
||||
const node = query.node(selectedId).get();
|
||||
targetParent = node?.data?.parent || 'ROOT';
|
||||
}
|
||||
|
||||
const tree = regenerateTreeIds(query.node(sourceId).toNodeTree());
|
||||
actions.addNodeTree(tree, targetParent);
|
||||
} catch (err) {
|
||||
console.error('Paste failed:', err);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Escape: deselect all
|
||||
if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
|
||||
@@ -87,4 +87,33 @@ describe('buildSavePayload', () => {
|
||||
expect(payload.header_craft_state).toBe('STALE_HEADER');
|
||||
expect(payload.footer_craft_state).toBe('STALE_FOOTER');
|
||||
});
|
||||
|
||||
test('I-1: activePageId matches no page (dangling, e.g. original Home deleted then reload reset it to "home") -- live serialize still lands in pages_craft_state[0] / index.html, not lost', () => {
|
||||
// pages[0] has id 'page_x' (the replacement landing page after the
|
||||
// original 'home' was deleted); activePageId is stuck at the stale
|
||||
// default 'home', which matches no entry in `pages`.
|
||||
const pageX: PageData = { id: 'page_x', name: 'Home', slug: 'index', craftState: 'STORED_X' };
|
||||
const p2: PageData = { id: 'p2', name: 'About', slug: 'about', craftState: 'STORED_ABOUT_2' };
|
||||
|
||||
const payload = buildSavePayload({
|
||||
siteId: 1,
|
||||
siteName: 'Test Site',
|
||||
liveCraftState: 'LIVE_EDIT',
|
||||
pages: [pageX, p2],
|
||||
headerPage,
|
||||
footerPage,
|
||||
activePageId: 'home',
|
||||
isEditingHeader: false,
|
||||
isEditingFooter: false,
|
||||
});
|
||||
|
||||
// The live edit must land in pages_craft_state[0] (index.html slot),
|
||||
// not be silently dropped to only the legacy top-level fields.
|
||||
expect(payload.pages_craft_state[0].craftState).toBe('LIVE_EDIT');
|
||||
expect(payload.pages[0].filename).toBe('index.html');
|
||||
// Top-level fields (legacy) should also reflect the live edit.
|
||||
expect(payload.craft_state).toBe('LIVE_EDIT');
|
||||
// The other page is untouched.
|
||||
expect(payload.pages_craft_state.find((p) => p.id === 'p2')?.craftState).toBe('STORED_ABOUT_2');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -49,6 +49,18 @@ export function buildSavePayload(input: BuildSavePayloadInput) {
|
||||
|
||||
const isPageActive = !isEditingHeader && !isEditingFooter;
|
||||
|
||||
// I-1 (data-loss): `activePageId` can go dangling -- e.g. the original
|
||||
// Home page (id 'home') is deleted, its replacement gets a fresh id
|
||||
// (`page_<ts>`), and a reload re-initializes `activePageId` back to the
|
||||
// hardcoded default `'home'` (see PageContext's `useState('home')`) before
|
||||
// `load()` has a chance to point it at the actually-restored page. If a
|
||||
// real page IS active but matches no entry in `pages`, treat `pages[0]`
|
||||
// (the landing page) as the active one so the live canvas serialization
|
||||
// still reaches the index.html page slot / `pages_craft_state[0]` instead
|
||||
// of only the legacy top-level `craft_state`/`html` fields.
|
||||
const activePageIndex = isPageActive ? pages.findIndex((p) => p.id === activePageId) : -1;
|
||||
const effectiveActivePageId = activePageIndex !== -1 ? activePageId : pages[0]?.id;
|
||||
|
||||
// Fresh header/footer state: the live canvas wins when that zone is the
|
||||
// one currently being edited; otherwise fall back to the last-committed
|
||||
// stored state (updated on zone switch by PageContext's saveCurrentState).
|
||||
@@ -115,7 +127,7 @@ export function buildSavePayload(input: BuildSavePayloadInput) {
|
||||
const filename = i === 0 ? 'index.html' : page.slug + '.html';
|
||||
let pageHtml = '';
|
||||
|
||||
if (isPageActive && page.id === activePageId) {
|
||||
if (isPageActive && page.id === effectiveActivePageId) {
|
||||
// Active page: use the current canvas HTML (already exported above)
|
||||
pageHtml = currentHtml;
|
||||
} else if (page.craftState) {
|
||||
@@ -146,7 +158,7 @@ export function buildSavePayload(input: BuildSavePayloadInput) {
|
||||
// reload the editor's clean-URL routing (.htaccess rewrite of /name →
|
||||
// name.html) lines up with the file we just wrote (index.html).
|
||||
slug: i === 0 ? 'index' : page.slug,
|
||||
craftState: (isPageActive && page.id === activePageId) ? liveCraftState : (page.craftState || null),
|
||||
craftState: (isPageActive && page.id === effectiveActivePageId) ? liveCraftState : (page.craftState || null),
|
||||
}));
|
||||
|
||||
return {
|
||||
@@ -177,6 +189,7 @@ export function useWhpApi() {
|
||||
setHeaderCraftState,
|
||||
setFooterCraftState,
|
||||
setPagesCraftState,
|
||||
setActivePageIdDirect,
|
||||
} = usePages();
|
||||
|
||||
const save = useCallback(async () => {
|
||||
@@ -271,10 +284,23 @@ export function useWhpApi() {
|
||||
console.warn('Failed to load page state:', e);
|
||||
}
|
||||
}
|
||||
|
||||
// I-1 (data-loss): point activePageId at the page we just loaded
|
||||
// into the canvas. Without this, activePageId stays at whatever it
|
||||
// was initialized to (the hardcoded default 'home'), which goes
|
||||
// dangling the moment the original Home page has been deleted and
|
||||
// replaced (its replacement gets a fresh `page_<ts>` id) -- the next
|
||||
// edit+save would then only reach the legacy top-level fields
|
||||
// instead of the actual page slot. Only do this when a real page is
|
||||
// being loaded, i.e. we're not currently mid-edit of the header/
|
||||
// footer zone (switching zones is handled separately by switchPage).
|
||||
if (!isEditingHeader && !isEditingFooter) {
|
||||
setActivePageIdDirect(firstPage.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
return data;
|
||||
}, [isWHP, whpConfig, actions, setHeaderCraftState, setFooterCraftState, setPagesCraftState]);
|
||||
}, [isWHP, whpConfig, actions, setHeaderCraftState, setFooterCraftState, setPagesCraftState, setActivePageIdDirect, isEditingHeader, isEditingFooter]);
|
||||
|
||||
const uploadAsset = useCallback(
|
||||
async (file: File) => {
|
||||
|
||||
@@ -4,6 +4,7 @@ import { findDeletableTarget } from '../../utils/craft-helpers';
|
||||
import { useSitesmithModal } from '../../state/SitesmithContext';
|
||||
import { buildSitesmithTarget } from '../../utils/sitesmith-target';
|
||||
import { regenerateTreeIds } from '../../utils/craft-tree';
|
||||
import { getClipboardNodeId, setClipboardNodeId } from '../../hooks/clipboard';
|
||||
|
||||
interface ContextMenuProps {
|
||||
visible: boolean;
|
||||
@@ -32,7 +33,6 @@ export const ContextMenu: React.FC<ContextMenuProps> = ({
|
||||
const { actions, query } = useEditor();
|
||||
const { open: openSitesmith } = useSitesmithModal();
|
||||
const menuRef = useRef<HTMLDivElement>(null);
|
||||
const clipboardRef = useRef<string | null>(null);
|
||||
|
||||
// Close on click outside
|
||||
useEffect(() => {
|
||||
@@ -80,7 +80,7 @@ export const ContextMenu: React.FC<ContextMenuProps> = ({
|
||||
const copyNode = useCallback(() => {
|
||||
if (!nodeId || nodeId === 'ROOT') return;
|
||||
try {
|
||||
clipboardRef.current = nodeId;
|
||||
setClipboardNodeId(nodeId);
|
||||
} catch (e) {
|
||||
console.error('Copy failed:', e);
|
||||
}
|
||||
@@ -88,7 +88,7 @@ export const ContextMenu: React.FC<ContextMenuProps> = ({
|
||||
}, [nodeId, onClose]);
|
||||
|
||||
const pasteNode = useCallback(() => {
|
||||
const sourceId = clipboardRef.current;
|
||||
const sourceId = getClipboardNodeId();
|
||||
if (!sourceId) {
|
||||
onClose();
|
||||
return;
|
||||
@@ -210,7 +210,7 @@ export const ContextMenu: React.FC<ContextMenuProps> = ({
|
||||
label: 'Paste',
|
||||
shortcut: 'Ctrl+V',
|
||||
action: pasteNode,
|
||||
disabled: !clipboardRef.current,
|
||||
disabled: !getClipboardNodeId(),
|
||||
dividerAfter: true,
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import React from 'react';
|
||||
import { useEditor } from '@craftjs/core';
|
||||
import { componentResolver } from '../../components/resolver';
|
||||
import { SiteDesignPanel } from './SiteDesignPanel';
|
||||
import { useSitesmithModal } from '../../state/SitesmithContext';
|
||||
import { buildSitesmithTarget } from '../../utils/sitesmith-target';
|
||||
@@ -31,27 +30,21 @@ import {
|
||||
================================================================ */
|
||||
|
||||
export const GuidedStyles: React.FC = () => {
|
||||
const resolverMap = componentResolver as Record<string, any>;
|
||||
const { open: openSitesmith } = useSitesmithModal();
|
||||
const { query } = useEditor();
|
||||
|
||||
const { selected, selectedType, nodeProps, resolvedName } = useEditor((state) => {
|
||||
const { selected, selectedType, nodeProps } = useEditor((state) => {
|
||||
const currentNodeId = state.events.selected
|
||||
? Array.from(state.events.selected)[0]
|
||||
: undefined;
|
||||
let selectedType: string | null = null;
|
||||
let nodeProps: Record<string, any> = {};
|
||||
let resolvedName: string | null = null;
|
||||
|
||||
if (currentNodeId) {
|
||||
const node = state.nodes[currentNodeId];
|
||||
if (node) {
|
||||
selectedType = node.data.displayName || node.data.name || null;
|
||||
nodeProps = node.data.props || {};
|
||||
const nodeType = node.data.type as any;
|
||||
if (nodeType && typeof nodeType === 'object' && nodeType.resolvedName) {
|
||||
resolvedName = nodeType.resolvedName;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,7 +52,6 @@ export const GuidedStyles: React.FC = () => {
|
||||
selected: currentNodeId || null,
|
||||
selectedType,
|
||||
nodeProps,
|
||||
resolvedName,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -75,8 +67,8 @@ export const GuidedStyles: React.FC = () => {
|
||||
const isButton = /^button$/i.test(typeName);
|
||||
const isImage = /^image$/i.test(typeName);
|
||||
const isBgSection = /^background section$/i.test(typeName);
|
||||
const isContainer = /^container$|^section$|^columns$|^header zone$|^footer zone$/i.test(typeName);
|
||||
const isHero = /hero/i.test(typeName);
|
||||
const isContainer = /^container$|^section$|^columns$/i.test(typeName);
|
||||
const isHero = /^hero/i.test(typeName);
|
||||
const isNav = /^menu$|^logo$|^navbar$|^footer$/i.test(typeName);
|
||||
const isMedia = /^video$|^gallery$|^map$|^content slider$/i.test(typeName);
|
||||
const isForm = /^form$|^input$|^textarea$|^subscribe|^contact form$|^submit button$|^search bar$/i.test(typeName);
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
import React from 'react';
|
||||
import { useEditor } from '@craftjs/core';
|
||||
import { CollapsibleSection, ArrayPropEditor, smallInputStyle } from './shared';
|
||||
|
||||
/* ---------- Shared array-item field editor ----------
|
||||
Extracted from SectionTypePanel and GenericPropsEditor, which both had a
|
||||
near-byte-identical per-item field renderer for generic array props
|
||||
(features/items/plans/testimonials/etc.). Infers an input type per field:
|
||||
boolean -> checkbox, number -> number, /color/ -> color swatch, long
|
||||
string -> textarea, else text. Fields are derived from Object.keys(items[0]).
|
||||
Callers keep their own special-casing (e.g. SectionTypePanel routes
|
||||
key === 'features' to FeaturesEditor instead of using this component). */
|
||||
export const ArrayItemFieldsEditor: React.FC<{ selectedId: string; propKey: string; items: any[] }> = ({
|
||||
selectedId, propKey, items,
|
||||
}) => {
|
||||
const { actions } = useEditor();
|
||||
const arrayItems = items;
|
||||
const sampleItem = arrayItems[0] || {};
|
||||
const itemFields = typeof sampleItem === 'object' && sampleItem !== null ? Object.keys(sampleItem) : [];
|
||||
|
||||
return (
|
||||
<CollapsibleSection title={propKey.replace(/([A-Z])/g, ' $1').trim()}>
|
||||
<ArrayPropEditor
|
||||
selectedId={selectedId}
|
||||
propKey={propKey}
|
||||
items={arrayItems}
|
||||
renderItem={(item: any, index: number) => {
|
||||
if (typeof item !== 'object' || item === null) {
|
||||
return (
|
||||
<input
|
||||
type="text"
|
||||
value={String(item)}
|
||||
onChange={(e) => {
|
||||
actions.setProp(selectedId, (props: any) => {
|
||||
const updated = [...(props[propKey] || [])];
|
||||
updated[index] = e.target.value;
|
||||
props[propKey] = updated;
|
||||
});
|
||||
}}
|
||||
style={smallInputStyle}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
|
||||
{itemFields.map((field) => {
|
||||
const fieldVal = item[field];
|
||||
if (typeof fieldVal === 'boolean') {
|
||||
return (
|
||||
<label key={field} style={{ fontSize: 10, color: '#71717a', display: 'flex', alignItems: 'center', gap: 4, cursor: 'pointer' }}>
|
||||
<input type="checkbox" checked={fieldVal} onChange={(e) => {
|
||||
actions.setProp(selectedId, (props: any) => {
|
||||
const updated = [...(props[propKey] || [])];
|
||||
updated[index] = { ...updated[index], [field]: e.target.checked };
|
||||
props[propKey] = updated;
|
||||
});
|
||||
}} />
|
||||
{field}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
if (typeof fieldVal === 'number') {
|
||||
return (
|
||||
<div key={field}>
|
||||
<label style={{ fontSize: 9, color: '#52525b', textTransform: 'capitalize' }}>{field}</label>
|
||||
<input type="number" value={fieldVal} onChange={(e) => {
|
||||
actions.setProp(selectedId, (props: any) => {
|
||||
const updated = [...(props[propKey] || [])];
|
||||
updated[index] = { ...updated[index], [field]: parseFloat(e.target.value) || 0 };
|
||||
props[propKey] = updated;
|
||||
});
|
||||
}} style={smallInputStyle} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
// color fields
|
||||
if (/color/i.test(field) && typeof fieldVal === 'string') {
|
||||
return (
|
||||
<div key={field} style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
|
||||
<label style={{ fontSize: 9, color: '#52525b', textTransform: 'capitalize', width: 50 }}>{field}</label>
|
||||
<input type="color" value={fieldVal || '#000000'} onChange={(e) => {
|
||||
actions.setProp(selectedId, (props: any) => {
|
||||
const updated = [...(props[propKey] || [])];
|
||||
updated[index] = { ...updated[index], [field]: e.target.value };
|
||||
props[propKey] = updated;
|
||||
});
|
||||
}} style={{ width: 24, height: 20, border: 'none', cursor: 'pointer', background: 'none', padding: 0 }} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
// long text
|
||||
const strVal = String(fieldVal ?? '');
|
||||
const isLongField = strVal.length > 50 || field === 'description' || field === 'text' || field === 'content';
|
||||
return (
|
||||
<div key={field}>
|
||||
<label style={{ fontSize: 9, color: '#52525b', textTransform: 'capitalize' }}>{field}</label>
|
||||
{isLongField ? (
|
||||
<textarea value={strVal} onChange={(e) => {
|
||||
actions.setProp(selectedId, (props: any) => {
|
||||
const updated = [...(props[propKey] || [])];
|
||||
updated[index] = { ...updated[index], [field]: e.target.value };
|
||||
props[propKey] = updated;
|
||||
});
|
||||
}} rows={2} style={{ ...smallInputStyle, resize: 'vertical' }} />
|
||||
) : (
|
||||
<input type="text" value={strVal} onChange={(e) => {
|
||||
actions.setProp(selectedId, (props: any) => {
|
||||
const updated = [...(props[propKey] || [])];
|
||||
updated[index] = { ...updated[index], [field]: e.target.value };
|
||||
props[propKey] = updated;
|
||||
});
|
||||
}} style={smallInputStyle} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}}
|
||||
emptyItem={typeof sampleItem === 'object' && sampleItem !== null
|
||||
? Object.fromEntries(itemFields.map((f) => [f, typeof sampleItem[f] === 'number' ? 0 : typeof sampleItem[f] === 'boolean' ? false : '']))
|
||||
: ''
|
||||
}
|
||||
/>
|
||||
</CollapsibleSection>
|
||||
);
|
||||
};
|
||||
@@ -1,5 +1,4 @@
|
||||
import React, { useCallback } from 'react';
|
||||
import { useEditor } from '@craftjs/core';
|
||||
import React from 'react';
|
||||
import {
|
||||
BG_COLORS,
|
||||
SPACING_PRESETS,
|
||||
@@ -15,22 +14,13 @@ import {
|
||||
labelStyle,
|
||||
inputStyle,
|
||||
sectionGap,
|
||||
useNodeProp,
|
||||
} from './shared';
|
||||
import { AssetPicker } from '../../../ui/AssetPicker';
|
||||
|
||||
/* ---------- BACKGROUND SECTION ---------- */
|
||||
export const BackgroundSectionStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
|
||||
const { actions } = useEditor();
|
||||
|
||||
const setProp = useCallback((key: string, value: any) => {
|
||||
actions.setProp(selectedId, (props: any) => { props[key] = value; });
|
||||
}, [actions, selectedId]);
|
||||
|
||||
const setPropStyle = useCallback((key: string, value: string) => {
|
||||
actions.setProp(selectedId, (props: any) => {
|
||||
props.style = { ...props.style, [key]: value };
|
||||
});
|
||||
}, [actions, selectedId]);
|
||||
const { setProp, setPropStyle } = useNodeProp(selectedId);
|
||||
|
||||
const style = nodeProps.style || {};
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
PresetButtonGrid,
|
||||
TextInputField,
|
||||
autoTextColor,
|
||||
useNodeProp,
|
||||
} from './shared';
|
||||
|
||||
/* ---------- BUTTON ---------- */
|
||||
@@ -19,14 +20,7 @@ export const ButtonStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodePr
|
||||
const { actions } = useEditor();
|
||||
const style: CSSProperties = nodeProps.style || {};
|
||||
|
||||
const setPropStyle = useCallback(
|
||||
(property: string, value: string) => {
|
||||
actions.setProp(selectedId, (props: any) => {
|
||||
props.style = { ...props.style, [property]: value };
|
||||
});
|
||||
},
|
||||
[actions, selectedId],
|
||||
);
|
||||
const { setPropStyle } = useNodeProp(selectedId);
|
||||
|
||||
const setButtonColor = useCallback(
|
||||
(bgColor: string) => {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import React, { useCallback, CSSProperties } from 'react';
|
||||
import { useEditor } from '@craftjs/core';
|
||||
import React, { CSSProperties } from 'react';
|
||||
import {
|
||||
BG_COLORS,
|
||||
SPACING_PRESETS,
|
||||
@@ -14,28 +13,14 @@ import {
|
||||
labelStyle,
|
||||
inputStyle,
|
||||
sectionGap,
|
||||
useNodeProp,
|
||||
} from './shared';
|
||||
|
||||
/* ---------- CONTAINER / SECTION ---------- */
|
||||
export const ContainerStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
|
||||
const { actions } = useEditor();
|
||||
const style: CSSProperties = nodeProps.style || {};
|
||||
|
||||
const setPropStyle = useCallback(
|
||||
(property: string, value: string) => {
|
||||
actions.setProp(selectedId, (props: any) => {
|
||||
props.style = { ...props.style, [property]: value };
|
||||
});
|
||||
},
|
||||
[actions, selectedId],
|
||||
);
|
||||
|
||||
const setProp = useCallback(
|
||||
(key: string, value: string) => {
|
||||
actions.setProp(selectedId, (props: any) => { props[key] = value; });
|
||||
},
|
||||
[actions, selectedId],
|
||||
);
|
||||
const { setProp, setPropStyle } = useNodeProp(selectedId);
|
||||
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import React, { useCallback } from 'react';
|
||||
import { useEditor } from '@craftjs/core';
|
||||
import React from 'react';
|
||||
import {
|
||||
BG_COLORS,
|
||||
SPACING_PRESETS,
|
||||
@@ -15,21 +14,12 @@ import {
|
||||
inputStyle,
|
||||
btnActiveStyle,
|
||||
sectionGap,
|
||||
useNodeProp,
|
||||
} from './shared';
|
||||
|
||||
/* ---------- FORM ---------- */
|
||||
export const FormStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
|
||||
const { actions } = useEditor();
|
||||
|
||||
const setProp = useCallback((key: string, value: any) => {
|
||||
actions.setProp(selectedId, (props: any) => { props[key] = value; });
|
||||
}, [actions, selectedId]);
|
||||
|
||||
const setPropStyle = useCallback((key: string, value: string) => {
|
||||
actions.setProp(selectedId, (props: any) => {
|
||||
props.style = { ...props.style, [key]: value };
|
||||
});
|
||||
}, [actions, selectedId]);
|
||||
const { setProp, setPropStyle } = useNodeProp(selectedId);
|
||||
|
||||
const style = nodeProps.style || {};
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import React, { useCallback } from 'react';
|
||||
import { useEditor } from '@craftjs/core';
|
||||
import React from 'react';
|
||||
import {
|
||||
TEXT_COLORS,
|
||||
BG_COLORS,
|
||||
@@ -12,30 +11,20 @@ import {
|
||||
PresetButtonGrid,
|
||||
CollapsibleSection,
|
||||
ColorPickerField,
|
||||
ArrayPropEditor,
|
||||
labelStyle,
|
||||
inputStyle,
|
||||
smallInputStyle,
|
||||
sectionGap,
|
||||
useNodeProp,
|
||||
} from './shared';
|
||||
import { ArrayItemFieldsEditor } from './ArrayItemFields';
|
||||
|
||||
/* ---------- SMART GENERIC PROPS EDITOR (Fallback) ---------- */
|
||||
export const GenericPropsEditor: React.FC<{ selectedId: string; nodeProps: Record<string, any>; typeName: string }> = ({
|
||||
selectedId, nodeProps, typeName,
|
||||
}) => {
|
||||
const { actions } = useEditor();
|
||||
|
||||
const SKIP_PROPS = new Set(['style', 'children', 'cssId', 'cssClass']);
|
||||
|
||||
const setPropValue = useCallback((key: string, value: any) => {
|
||||
actions.setProp(selectedId, (props: any) => { props[key] = value; });
|
||||
}, [actions, selectedId]);
|
||||
|
||||
const setStyleValue = useCallback((key: string, value: string) => {
|
||||
actions.setProp(selectedId, (props: any) => {
|
||||
props.style = { ...props.style, [key]: value };
|
||||
});
|
||||
}, [actions, selectedId]);
|
||||
const { setProp: setPropValue, setPropStyle: setStyleValue } = useNodeProp(selectedId);
|
||||
|
||||
// Categorize all props
|
||||
const allProps = Object.entries(nodeProps).filter(([key]) => !SKIP_PROPS.has(key));
|
||||
@@ -105,116 +94,9 @@ export const GenericPropsEditor: React.FC<{ selectedId: string; nodeProps: Recor
|
||||
)}
|
||||
|
||||
{/* Array props */}
|
||||
{arrayProps.map(([key, items]) => {
|
||||
const arrayItems = items as any[];
|
||||
const sampleItem = arrayItems[0] || {};
|
||||
const itemFields = typeof sampleItem === 'object' && sampleItem !== null ? Object.keys(sampleItem) : [];
|
||||
|
||||
return (
|
||||
<CollapsibleSection key={key} title={key.replace(/([A-Z])/g, ' $1').trim()}>
|
||||
<ArrayPropEditor
|
||||
selectedId={selectedId}
|
||||
propKey={key}
|
||||
items={arrayItems}
|
||||
renderItem={(item: any, index: number) => {
|
||||
if (typeof item !== 'object' || item === null) {
|
||||
return (
|
||||
<input
|
||||
type="text"
|
||||
value={String(item)}
|
||||
onChange={(e) => {
|
||||
actions.setProp(selectedId, (props: any) => {
|
||||
const updated = [...(props[key] || [])];
|
||||
updated[index] = e.target.value;
|
||||
props[key] = updated;
|
||||
});
|
||||
}}
|
||||
style={smallInputStyle}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
|
||||
{itemFields.map((field) => {
|
||||
const fieldVal = item[field];
|
||||
if (typeof fieldVal === 'boolean') {
|
||||
return (
|
||||
<label key={field} style={{ fontSize: 10, color: '#71717a', display: 'flex', alignItems: 'center', gap: 4, cursor: 'pointer' }}>
|
||||
<input type="checkbox" checked={fieldVal} onChange={(e) => {
|
||||
actions.setProp(selectedId, (props: any) => {
|
||||
const updated = [...(props[key] || [])];
|
||||
updated[index] = { ...updated[index], [field]: e.target.checked };
|
||||
props[key] = updated;
|
||||
});
|
||||
}} />
|
||||
{field}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
if (typeof fieldVal === 'number') {
|
||||
return (
|
||||
<div key={field}>
|
||||
<label style={{ fontSize: 9, color: '#52525b', textTransform: 'capitalize' }}>{field}</label>
|
||||
<input type="number" value={fieldVal} onChange={(e) => {
|
||||
actions.setProp(selectedId, (props: any) => {
|
||||
const updated = [...(props[key] || [])];
|
||||
updated[index] = { ...updated[index], [field]: parseFloat(e.target.value) || 0 };
|
||||
props[key] = updated;
|
||||
});
|
||||
}} style={smallInputStyle} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (/color/i.test(field) && typeof fieldVal === 'string') {
|
||||
return (
|
||||
<div key={field} style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
|
||||
<label style={{ fontSize: 9, color: '#52525b', textTransform: 'capitalize', width: 50 }}>{field}</label>
|
||||
<input type="color" value={fieldVal || '#000000'} onChange={(e) => {
|
||||
actions.setProp(selectedId, (props: any) => {
|
||||
const updated = [...(props[key] || [])];
|
||||
updated[index] = { ...updated[index], [field]: e.target.value };
|
||||
props[key] = updated;
|
||||
});
|
||||
}} style={{ width: 24, height: 20, border: 'none', cursor: 'pointer', background: 'none', padding: 0 }} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const strVal = String(fieldVal ?? '');
|
||||
const isLongField = strVal.length > 50 || field === 'description' || field === 'text' || field === 'content';
|
||||
return (
|
||||
<div key={field}>
|
||||
<label style={{ fontSize: 9, color: '#52525b', textTransform: 'capitalize' }}>{field}</label>
|
||||
{isLongField ? (
|
||||
<textarea value={strVal} onChange={(e) => {
|
||||
actions.setProp(selectedId, (props: any) => {
|
||||
const updated = [...(props[key] || [])];
|
||||
updated[index] = { ...updated[index], [field]: e.target.value };
|
||||
props[key] = updated;
|
||||
});
|
||||
}} rows={2} style={{ ...smallInputStyle, resize: 'vertical' }} />
|
||||
) : (
|
||||
<input type="text" value={strVal} onChange={(e) => {
|
||||
actions.setProp(selectedId, (props: any) => {
|
||||
const updated = [...(props[key] || [])];
|
||||
updated[index] = { ...updated[index], [field]: e.target.value };
|
||||
props[key] = updated;
|
||||
});
|
||||
}} style={smallInputStyle} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}}
|
||||
emptyItem={typeof sampleItem === 'object' && sampleItem !== null
|
||||
? Object.fromEntries(itemFields.map((f) => [f, typeof sampleItem[f] === 'number' ? 0 : typeof sampleItem[f] === 'boolean' ? false : '']))
|
||||
: ''
|
||||
}
|
||||
/>
|
||||
</CollapsibleSection>
|
||||
);
|
||||
})}
|
||||
{arrayProps.map(([key, items]) => (
|
||||
<ArrayItemFieldsEditor key={key} selectedId={selectedId} propKey={key} items={items as any[]} />
|
||||
))}
|
||||
|
||||
{/* Style controls */}
|
||||
<CollapsibleSection title="Style">
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import React, { useCallback } from 'react';
|
||||
import { useEditor } from '@craftjs/core';
|
||||
import React from 'react';
|
||||
import {
|
||||
StylePanelProps,
|
||||
CollapsibleSection,
|
||||
@@ -8,16 +7,13 @@ import {
|
||||
inputStyle,
|
||||
btnActiveStyle,
|
||||
sectionGap,
|
||||
useNodeProp,
|
||||
} from './shared';
|
||||
import { AssetPicker } from '../../../ui/AssetPicker';
|
||||
|
||||
/* ---------- HERO STYLE PANEL ---------- */
|
||||
export const HeroStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
|
||||
const { actions } = useEditor();
|
||||
|
||||
const setProp = useCallback((key: string, value: any) => {
|
||||
actions.setProp(selectedId, (props: any) => { props[key] = value; });
|
||||
}, [actions, selectedId]);
|
||||
const { setProp } = useNodeProp(selectedId);
|
||||
|
||||
const bgType = nodeProps.bgType || 'color';
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useCallback, CSSProperties } from 'react';
|
||||
import React, { CSSProperties } from 'react';
|
||||
import { useEditor } from '@craftjs/core';
|
||||
import {
|
||||
IMAGE_RADIUS_PRESETS,
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
SectionLabel,
|
||||
PresetButtonGrid,
|
||||
TextInputField,
|
||||
useNodeProp,
|
||||
} from './shared';
|
||||
import { AssetPicker } from '../../../ui/AssetPicker';
|
||||
|
||||
@@ -16,14 +17,7 @@ export const ImageStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodePro
|
||||
const { actions } = useEditor();
|
||||
const style: CSSProperties = nodeProps.style || {};
|
||||
|
||||
const setPropStyle = useCallback(
|
||||
(property: string, value: string) => {
|
||||
actions.setProp(selectedId, (props: any) => {
|
||||
props.style = { ...props.style, [property]: value };
|
||||
});
|
||||
},
|
||||
[actions, selectedId],
|
||||
);
|
||||
const { setPropStyle } = useNodeProp(selectedId);
|
||||
|
||||
const maxWidthPresets = [
|
||||
{ label: '25%', value: '25%' },
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import React from 'react';
|
||||
import { createRoot, Root } from 'react-dom/client';
|
||||
import { act } from 'react-dom/test-utils';
|
||||
|
||||
/* MediaStylePanel (via useNodeProp/ArrayPropEditor in ./shared) only needs
|
||||
useEditor from @craftjs/core. Mock it following the DOM-harness pattern
|
||||
used in Footer.editguard.test.tsx / AssetPicker.test.tsx (no
|
||||
@testing-library/react in this repo) so setProp calls can be observed
|
||||
without mounting a real <Editor> tree. */
|
||||
const setPropSpy = vi.fn((_id: string, updater: (p: any) => void) => {
|
||||
updater(lastProps);
|
||||
});
|
||||
let lastProps: any;
|
||||
|
||||
vi.mock('@craftjs/core', () => ({
|
||||
useEditor: () => ({ actions: { setProp: setPropSpy } }),
|
||||
}));
|
||||
|
||||
vi.mock('../../../utils/assets', () => ({
|
||||
uploadAsset: vi.fn(),
|
||||
listAssets: vi.fn(),
|
||||
}));
|
||||
|
||||
import { MediaStylePanel } from './MediaStylePanel';
|
||||
|
||||
let container: HTMLDivElement;
|
||||
let root: Root;
|
||||
|
||||
function render(ui: React.ReactElement) {
|
||||
container = document.createElement('div');
|
||||
document.body.appendChild(container);
|
||||
act(() => {
|
||||
root = createRoot(container);
|
||||
root.render(ui);
|
||||
});
|
||||
}
|
||||
|
||||
function unmount() {
|
||||
act(() => { root.unmount(); });
|
||||
container.remove();
|
||||
}
|
||||
|
||||
function q<T extends Element = Element>(testId: string): T | null {
|
||||
return container.querySelector(`[data-testid="${testId}"]`);
|
||||
}
|
||||
|
||||
function setValue(input: HTMLInputElement, value: string) {
|
||||
const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')!.set!;
|
||||
setter.call(input, value);
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
setPropSpy.mockClear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (container) unmount();
|
||||
});
|
||||
|
||||
/**
|
||||
* INT: ContentSlider (src/components/sections/ContentSlider.tsx) reads
|
||||
* `slide.imageSrc` in both render and toHtml, but the Slides array editor
|
||||
* here guarded on `item.image !== undefined` and wrote `image` via
|
||||
* AssetPicker's onChange -- a key that ContentSlider never reads. Default
|
||||
* slides (`imageSrc:''`, no `image` key) therefore showed NO image picker at
|
||||
* all (the guard was never true), and even a manually-added `image` value
|
||||
* was a silent no-op on export/render.
|
||||
*/
|
||||
describe('MediaStylePanel Slides editor uses imageSrc (INT)', () => {
|
||||
test('a slide shaped like defaultSlides (imageSrc present, no `image` key) renders the image AssetPicker', () => {
|
||||
lastProps = { slides: [{ type: 'image', imageSrc: '', heading: 'First Slide', text: '', bgColor: '' }] };
|
||||
render(<MediaStylePanel selectedId="cs-1" nodeProps={lastProps} />);
|
||||
|
||||
// Before the fix, the guard `item.image !== undefined` was false for
|
||||
// this default-shaped slide, so no AssetPicker rendered at all.
|
||||
expect(q('asset-picker-compact')).not.toBeNull();
|
||||
});
|
||||
|
||||
test('editing the slide image writes imageSrc (not image) via setProp', () => {
|
||||
lastProps = { slides: [{ type: 'image', imageSrc: '', heading: 'First Slide', text: '', bgColor: '' }] };
|
||||
render(<MediaStylePanel selectedId="cs-1" nodeProps={lastProps} />);
|
||||
|
||||
const urlInput = q<HTMLInputElement>('asset-picker-url-input')!;
|
||||
expect(urlInput).not.toBeNull();
|
||||
setValue(urlInput, 'https://example.com/slide.jpg');
|
||||
act(() => {
|
||||
urlInput.dispatchEvent(new FocusEvent('focusout', { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(setPropSpy).toHaveBeenCalled();
|
||||
const updatedSlide = lastProps.slides[0];
|
||||
expect(updatedSlide.imageSrc).toBe('https://example.com/slide.jpg');
|
||||
expect(updatedSlide.image).toBeUndefined();
|
||||
});
|
||||
|
||||
test('adding a new slide (emptyItem) includes imageSrc, matching defaultSlides shape', () => {
|
||||
lastProps = { slides: [] };
|
||||
render(<MediaStylePanel selectedId="cs-1" nodeProps={lastProps} />);
|
||||
|
||||
// The "+ Add Item" button for the Slides ArrayPropEditor.
|
||||
const addButtons = Array.from(container.querySelectorAll('button')).filter(
|
||||
(b) => b.textContent?.includes('Add Item'),
|
||||
);
|
||||
expect(addButtons.length).toBeGreaterThan(0);
|
||||
act(() => {
|
||||
addButtons[0].dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(setPropSpy).toHaveBeenCalled();
|
||||
expect(lastProps.slides).toHaveLength(1);
|
||||
expect(lastProps.slides[0]).toHaveProperty('imageSrc');
|
||||
expect(lastProps.slides[0].image).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useCallback } from 'react';
|
||||
import React from 'react';
|
||||
import { useEditor } from '@craftjs/core';
|
||||
import {
|
||||
BG_COLORS,
|
||||
@@ -17,22 +17,14 @@ import {
|
||||
inputStyle,
|
||||
smallInputStyle,
|
||||
sectionGap,
|
||||
useNodeProp,
|
||||
} from './shared';
|
||||
import { AssetPicker } from '../../../ui/AssetPicker';
|
||||
|
||||
/* ---------- MEDIA (Video / Gallery / Map / Slider) ---------- */
|
||||
export const MediaStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
|
||||
const { actions } = useEditor();
|
||||
|
||||
const setProp = useCallback((key: string, value: any) => {
|
||||
actions.setProp(selectedId, (props: any) => { props[key] = value; });
|
||||
}, [actions, selectedId]);
|
||||
|
||||
const setPropStyle = useCallback((key: string, value: string) => {
|
||||
actions.setProp(selectedId, (props: any) => {
|
||||
props.style = { ...props.style, [key]: value };
|
||||
});
|
||||
}, [actions, selectedId]);
|
||||
const { setProp, setPropStyle } = useNodeProp(selectedId);
|
||||
|
||||
const style = nodeProps.style || {};
|
||||
|
||||
@@ -153,14 +145,14 @@ export const MediaStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodePro
|
||||
});
|
||||
}} placeholder="Text" rows={2} style={{ ...smallInputStyle, resize: 'vertical' }} />
|
||||
)}
|
||||
{item.image !== undefined && (
|
||||
{item.imageSrc !== undefined && (
|
||||
<AssetPicker
|
||||
variant="compact"
|
||||
value={item.image || ''}
|
||||
value={item.imageSrc || ''}
|
||||
onChange={(url) => {
|
||||
actions.setProp(selectedId, (props: any) => {
|
||||
const updated = [...(props.slides || [])];
|
||||
updated[index] = { ...updated[index], image: url };
|
||||
updated[index] = { ...updated[index], imageSrc: url };
|
||||
props.slides = updated;
|
||||
});
|
||||
}}
|
||||
@@ -168,7 +160,7 @@ export const MediaStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodePro
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
emptyItem={{ heading: 'New Slide', text: '', image: '' }}
|
||||
emptyItem={{ type: 'image', imageSrc: '', heading: 'New Slide', text: '', bgColor: '' }}
|
||||
/>
|
||||
</CollapsibleSection>
|
||||
)}
|
||||
|
||||
@@ -15,22 +15,14 @@ import {
|
||||
inputStyle,
|
||||
smallInputStyle,
|
||||
sectionGap,
|
||||
useNodeProp,
|
||||
} from './shared';
|
||||
import { AssetPicker } from '../../../ui/AssetPicker';
|
||||
|
||||
/* ---------- NAV / MENU / LOGO ---------- */
|
||||
export const NavStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
|
||||
const { actions } = useEditor();
|
||||
|
||||
const setProp = useCallback((key: string, value: any) => {
|
||||
actions.setProp(selectedId, (props: any) => { props[key] = value; });
|
||||
}, [actions, selectedId]);
|
||||
|
||||
const setPropStyle = useCallback((key: string, value: string) => {
|
||||
actions.setProp(selectedId, (props: any) => {
|
||||
props.style = { ...props.style, [key]: value };
|
||||
});
|
||||
}, [actions, selectedId]);
|
||||
const { setProp, setPropStyle } = useNodeProp(selectedId);
|
||||
|
||||
const links: any[] = nodeProps.links || [];
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import React, { useCallback } from 'react';
|
||||
import { useEditor } from '@craftjs/core';
|
||||
import React from 'react';
|
||||
import {
|
||||
BG_COLORS,
|
||||
SPACING_PRESETS,
|
||||
@@ -12,27 +11,17 @@ import {
|
||||
PresetButtonGrid,
|
||||
CollapsibleSection,
|
||||
ColorPickerField,
|
||||
ArrayPropEditor,
|
||||
labelStyle,
|
||||
inputStyle,
|
||||
smallInputStyle,
|
||||
sectionGap,
|
||||
useNodeProp,
|
||||
} from './shared';
|
||||
import { FeaturesEditor } from './FeaturesEditor';
|
||||
import { ArrayItemFieldsEditor } from './ArrayItemFields';
|
||||
|
||||
/* ---------- SECTION-TYPE (Accordion, Tabs, Pricing, Testimonials, etc.) ---------- */
|
||||
export const SectionTypePanel: React.FC<StylePanelProps & { typeName: string }> = ({ selectedId, nodeProps, typeName }) => {
|
||||
const { actions } = useEditor();
|
||||
|
||||
const setProp = useCallback((key: string, value: any) => {
|
||||
actions.setProp(selectedId, (props: any) => { props[key] = value; });
|
||||
}, [actions, selectedId]);
|
||||
|
||||
const setPropStyle = useCallback((key: string, value: string) => {
|
||||
actions.setProp(selectedId, (props: any) => {
|
||||
props.style = { ...props.style, [key]: value };
|
||||
});
|
||||
}, [actions, selectedId]);
|
||||
const { setProp, setPropStyle } = useNodeProp(selectedId);
|
||||
|
||||
const style = nodeProps.style || {};
|
||||
|
||||
@@ -108,115 +97,8 @@ export const SectionTypePanel: React.FC<StylePanelProps & { typeName: string }>
|
||||
}
|
||||
const arrayItems = items as any[];
|
||||
if (arrayItems.length === 0 && typeof arrayItems[0] !== 'object') return null;
|
||||
const sampleItem = arrayItems[0] || {};
|
||||
const itemFields = typeof sampleItem === 'object' && sampleItem !== null ? Object.keys(sampleItem) : [];
|
||||
|
||||
return (
|
||||
<CollapsibleSection key={key} title={key.replace(/([A-Z])/g, ' $1').trim()}>
|
||||
<ArrayPropEditor
|
||||
selectedId={selectedId}
|
||||
propKey={key}
|
||||
items={arrayItems}
|
||||
renderItem={(item: any, index: number) => {
|
||||
if (typeof item !== 'object' || item === null) {
|
||||
return (
|
||||
<input
|
||||
type="text"
|
||||
value={String(item)}
|
||||
onChange={(e) => {
|
||||
actions.setProp(selectedId, (props: any) => {
|
||||
const updated = [...(props[key] || [])];
|
||||
updated[index] = e.target.value;
|
||||
props[key] = updated;
|
||||
});
|
||||
}}
|
||||
style={smallInputStyle}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
|
||||
{itemFields.map((field) => {
|
||||
const fieldVal = item[field];
|
||||
if (typeof fieldVal === 'boolean') {
|
||||
return (
|
||||
<label key={field} style={{ fontSize: 10, color: '#71717a', display: 'flex', alignItems: 'center', gap: 4, cursor: 'pointer' }}>
|
||||
<input type="checkbox" checked={fieldVal} onChange={(e) => {
|
||||
actions.setProp(selectedId, (props: any) => {
|
||||
const updated = [...(props[key] || [])];
|
||||
updated[index] = { ...updated[index], [field]: e.target.checked };
|
||||
props[key] = updated;
|
||||
});
|
||||
}} />
|
||||
{field}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
if (typeof fieldVal === 'number') {
|
||||
return (
|
||||
<div key={field}>
|
||||
<label style={{ fontSize: 9, color: '#52525b', textTransform: 'capitalize' }}>{field}</label>
|
||||
<input type="number" value={fieldVal} onChange={(e) => {
|
||||
actions.setProp(selectedId, (props: any) => {
|
||||
const updated = [...(props[key] || [])];
|
||||
updated[index] = { ...updated[index], [field]: parseFloat(e.target.value) || 0 };
|
||||
props[key] = updated;
|
||||
});
|
||||
}} style={smallInputStyle} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
// color fields
|
||||
if (/color/i.test(field) && typeof fieldVal === 'string') {
|
||||
return (
|
||||
<div key={field} style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
|
||||
<label style={{ fontSize: 9, color: '#52525b', textTransform: 'capitalize', width: 50 }}>{field}</label>
|
||||
<input type="color" value={fieldVal || '#000000'} onChange={(e) => {
|
||||
actions.setProp(selectedId, (props: any) => {
|
||||
const updated = [...(props[key] || [])];
|
||||
updated[index] = { ...updated[index], [field]: e.target.value };
|
||||
props[key] = updated;
|
||||
});
|
||||
}} style={{ width: 24, height: 20, border: 'none', cursor: 'pointer', background: 'none', padding: 0 }} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
// long text
|
||||
const strVal = String(fieldVal ?? '');
|
||||
const isLongField = strVal.length > 50 || field === 'description' || field === 'text' || field === 'content';
|
||||
return (
|
||||
<div key={field}>
|
||||
<label style={{ fontSize: 9, color: '#52525b', textTransform: 'capitalize' }}>{field}</label>
|
||||
{isLongField ? (
|
||||
<textarea value={strVal} onChange={(e) => {
|
||||
actions.setProp(selectedId, (props: any) => {
|
||||
const updated = [...(props[key] || [])];
|
||||
updated[index] = { ...updated[index], [field]: e.target.value };
|
||||
props[key] = updated;
|
||||
});
|
||||
}} rows={2} style={{ ...smallInputStyle, resize: 'vertical' }} />
|
||||
) : (
|
||||
<input type="text" value={strVal} onChange={(e) => {
|
||||
actions.setProp(selectedId, (props: any) => {
|
||||
const updated = [...(props[key] || [])];
|
||||
updated[index] = { ...updated[index], [field]: e.target.value };
|
||||
props[key] = updated;
|
||||
});
|
||||
}} style={smallInputStyle} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}}
|
||||
emptyItem={typeof sampleItem === 'object' && sampleItem !== null
|
||||
? Object.fromEntries(itemFields.map((f) => [f, typeof sampleItem[f] === 'number' ? 0 : typeof sampleItem[f] === 'boolean' ? false : '']))
|
||||
: ''
|
||||
}
|
||||
/>
|
||||
</CollapsibleSection>
|
||||
);
|
||||
return <ArrayItemFieldsEditor key={key} selectedId={selectedId} propKey={key} items={arrayItems} />;
|
||||
})}
|
||||
|
||||
{/* Style */}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useCallback } from 'react';
|
||||
import React from 'react';
|
||||
import { useEditor } from '@craftjs/core';
|
||||
import {
|
||||
BG_COLORS,
|
||||
@@ -16,21 +16,13 @@ import {
|
||||
smallInputStyle,
|
||||
btnActiveStyle,
|
||||
sectionGap,
|
||||
useNodeProp,
|
||||
} from './shared';
|
||||
|
||||
/* ---------- SOCIAL / ICON / STAR RATING ---------- */
|
||||
export const SocialStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
|
||||
const { actions } = useEditor();
|
||||
|
||||
const setProp = useCallback((key: string, value: any) => {
|
||||
actions.setProp(selectedId, (props: any) => { props[key] = value; });
|
||||
}, [actions, selectedId]);
|
||||
|
||||
const setPropStyle = useCallback((key: string, value: string) => {
|
||||
actions.setProp(selectedId, (props: any) => {
|
||||
props.style = { ...props.style, [key]: value };
|
||||
});
|
||||
}, [actions, selectedId]);
|
||||
const { setProp, setPropStyle } = useNodeProp(selectedId);
|
||||
|
||||
const style = nodeProps.style || {};
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import React, { useCallback, CSSProperties } from 'react';
|
||||
import { useEditor } from '@craftjs/core';
|
||||
import React, { CSSProperties } from 'react';
|
||||
import {
|
||||
TEXT_COLORS,
|
||||
FONT_FAMILIES,
|
||||
@@ -11,21 +10,14 @@ import {
|
||||
SectionLabel,
|
||||
ColorSwatchGrid,
|
||||
PresetButtonGrid,
|
||||
useNodeProp,
|
||||
} from './shared';
|
||||
|
||||
/* ---------- TEXT ---------- */
|
||||
export const TextStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
|
||||
const { actions } = useEditor();
|
||||
const style: CSSProperties = nodeProps.style || {};
|
||||
|
||||
const setPropStyle = useCallback(
|
||||
(property: string, value: string) => {
|
||||
actions.setProp(selectedId, (props: any) => {
|
||||
props.style = { ...props.style, [property]: value };
|
||||
});
|
||||
},
|
||||
[actions, selectedId],
|
||||
);
|
||||
const { setPropStyle } = useNodeProp(selectedId);
|
||||
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -288,6 +288,18 @@ export interface StylePanelProps {
|
||||
nodeProps: Record<string, any>;
|
||||
}
|
||||
|
||||
/* ---------- useNodeProp ----------
|
||||
Shared setProp/setPropStyle boilerplate repeated across many *StylePanel.tsx
|
||||
files. Only adopted where a panel's inline definitions were byte-equivalent
|
||||
to this (some panels use different param names or extra logic and keep
|
||||
their own local versions). */
|
||||
export function useNodeProp(selectedId: string) {
|
||||
const { actions } = useEditor();
|
||||
const setProp = useCallback((key: string, value: any) => actions.setProp(selectedId, (p: any) => { p[key] = value; }), [actions, selectedId]);
|
||||
const setPropStyle = useCallback((prop: string, value: string) => actions.setProp(selectedId, (p: any) => { p.style = { ...p.style, [prop]: value }; }), [actions, selectedId]);
|
||||
return { setProp, setPropStyle };
|
||||
}
|
||||
|
||||
/* ---------- Array Prop Editor (reusable for features, items, plans, etc.) ---------- */
|
||||
interface ArrayPropEditorProps {
|
||||
selectedId: string;
|
||||
|
||||
@@ -11,6 +11,7 @@ import { MessageList } from './MessageList';
|
||||
import { ChatInput } from './ChatInput';
|
||||
import { WorkingIndicator } from './WorkingIndicator';
|
||||
import { SitesmithResponse } from '../../types/sitesmith';
|
||||
import { Modal } from '../../ui/Modal';
|
||||
|
||||
interface Props {
|
||||
onClose: () => void;
|
||||
@@ -39,7 +40,6 @@ export const SitesmithModal: React.FC<Props> = ({ onClose, target }) => {
|
||||
|
||||
const canChat = summary && (summary.status === 'OK_BONUS' || summary.status === 'OK_MONTHLY');
|
||||
|
||||
const overlay: React.CSSProperties = { position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.8)', zIndex: 9000, display: 'flex', alignItems: 'center', justifyContent: 'center' };
|
||||
const panel: React.CSSProperties = { background: '#0f0f17', border: '1px solid #27272a', borderRadius: 12, width: 'min(720px, 90vw)', maxHeight: '90vh', display: 'flex', flexDirection: 'column' };
|
||||
const header: React.CSSProperties = { display: 'flex', alignItems: 'center', padding: '14px 18px', borderBottom: '1px solid #27272a', gap: 8 };
|
||||
const body: React.CSSProperties = { flex: 1, padding: '14px 18px', overflowY: 'auto', display: 'flex', flexDirection: 'column' };
|
||||
@@ -93,7 +93,14 @@ export const SitesmithModal: React.FC<Props> = ({ onClose, target }) => {
|
||||
};
|
||||
|
||||
return (
|
||||
<div role="dialog" aria-modal="true" style={overlay}>
|
||||
<Modal
|
||||
open
|
||||
onClose={onClose}
|
||||
closeOnEscape={false}
|
||||
closeOnBackdropClick={false}
|
||||
backdropStyle={{ backgroundColor: 'rgba(0,0,0,0.8)', zIndex: 9000 }}
|
||||
backdropProps={{ role: 'dialog', 'aria-modal': true }}
|
||||
>
|
||||
<div style={panel}>
|
||||
<div style={header}>
|
||||
<div style={{ fontWeight: 600, color: '#fff' }}>✨ Sitesmith</div>
|
||||
@@ -166,6 +173,6 @@ export const SitesmithModal: React.FC<Props> = ({ onClose, target }) => {
|
||||
onCancel={() => setPendingReplace(null)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import React, { useEffect } from 'react';
|
||||
import React from 'react';
|
||||
import { useSiteDesign } from '../../state/SiteDesignContext';
|
||||
import { Modal } from '../../ui/Modal';
|
||||
|
||||
interface HeadCodeModalProps {
|
||||
open: boolean;
|
||||
@@ -9,19 +10,8 @@ interface HeadCodeModalProps {
|
||||
export const HeadCodeModal: React.FC<HeadCodeModalProps> = ({ open, onClose }) => {
|
||||
const { design, updateDesign } = useSiteDesign();
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const handler = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') onClose();
|
||||
};
|
||||
window.addEventListener('keydown', handler);
|
||||
return () => window.removeEventListener('keydown', handler);
|
||||
}, [open, onClose]);
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
return (
|
||||
<div style={backdropStyle} onClick={onClose}>
|
||||
<Modal open={open} onClose={onClose}>
|
||||
<div style={modalStyle} onClick={(e) => e.stopPropagation()}>
|
||||
{/* Header */}
|
||||
<div style={modalHeaderStyle}>
|
||||
@@ -92,25 +82,12 @@ export const HeadCodeModal: React.FC<HeadCodeModalProps> = ({ open, onClose }) =
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
/* ---------- Styles ---------- */
|
||||
|
||||
const backdropStyle: React.CSSProperties = {
|
||||
position: 'fixed',
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.65)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
zIndex: 10000,
|
||||
};
|
||||
|
||||
const modalStyle: React.CSSProperties = {
|
||||
width: '90vw',
|
||||
maxWidth: 700,
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
} from '../../templates';
|
||||
import { componentResolver } from '../../components/resolver';
|
||||
import { clickableProps } from '../../utils/a11y';
|
||||
import { Modal } from '../../ui/Modal';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
@@ -60,18 +61,15 @@ export const TemplateModal: React.FC<TemplateModalProps> = ({ open, onClose }) =
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Close on Escape key
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const handler = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') {
|
||||
if (confirmTemplate) setConfirmTemplate(null);
|
||||
else onClose();
|
||||
}
|
||||
};
|
||||
document.addEventListener('keydown', handler);
|
||||
return () => document.removeEventListener('keydown', handler);
|
||||
}, [open, confirmTemplate, onClose]);
|
||||
// Escape / backdrop-click close the confirmation dialog first if it's open,
|
||||
// otherwise close the modal. Passed to <Modal> below, which handles the
|
||||
// Escape listener and the backdrop-click detection itself; the header's own
|
||||
// close button (X) below still uses the raw `onClose` prop directly, so it
|
||||
// always fully closes the modal even mid-confirmation (unchanged behavior).
|
||||
const handleModalClose = useCallback(() => {
|
||||
if (confirmTemplate) setConfirmTemplate(null);
|
||||
else onClose();
|
||||
}, [confirmTemplate, onClose]);
|
||||
|
||||
// Filter templates by category
|
||||
const filtered = useMemo(() => {
|
||||
@@ -236,24 +234,8 @@ export const TemplateModal: React.FC<TemplateModalProps> = ({ open, onClose }) =
|
||||
}
|
||||
}, [confirmTemplate, applyDesign, pages, addPage, switchPage, deletePage, updateDesign, addTemplateComponents, clearCanvas, applyHeaderFooter, wait, onClose]);
|
||||
|
||||
// Close on backdrop click
|
||||
const handleBackdropClick = useCallback(
|
||||
(e: React.MouseEvent) => {
|
||||
if (e.target === e.currentTarget) {
|
||||
if (confirmTemplate) {
|
||||
setConfirmTemplate(null);
|
||||
} else {
|
||||
onClose();
|
||||
}
|
||||
}
|
||||
},
|
||||
[confirmTemplate, onClose],
|
||||
);
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
return (
|
||||
<div style={backdropStyle} onClick={handleBackdropClick}>
|
||||
<Modal open={open} onClose={handleModalClose}>
|
||||
<div style={modalStyle}>
|
||||
{/* Header */}
|
||||
<div style={modalHeaderStyle}>
|
||||
@@ -377,7 +359,7 @@ export const TemplateModal: React.FC<TemplateModalProps> = ({ open, onClose }) =
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -473,19 +455,6 @@ const TemplateCard: React.FC<{
|
||||
// Styles
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const backdropStyle: React.CSSProperties = {
|
||||
position: 'fixed',
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.65)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
zIndex: 10000,
|
||||
};
|
||||
|
||||
const modalStyle: React.CSSProperties = {
|
||||
width: '90vw',
|
||||
maxWidth: 900,
|
||||
|
||||
@@ -121,6 +121,38 @@ describe('PageProvider slug dedupe', () => {
|
||||
unmount();
|
||||
});
|
||||
|
||||
test('M-4: a punctuation-only page name ("!!!") falls back to slug "page", never empty string', () => {
|
||||
let ctx: ReturnType<typeof usePages> | null = null;
|
||||
const Consumer: React.FC = () => {
|
||||
ctx = usePages();
|
||||
return null;
|
||||
};
|
||||
|
||||
render(
|
||||
<PageProvider>
|
||||
<Consumer />
|
||||
</PageProvider>,
|
||||
);
|
||||
|
||||
act(() => {
|
||||
ctx!.addPage('!!!', '');
|
||||
});
|
||||
|
||||
const added = ctx!.pages.find((p) => p.name === '!!!')!;
|
||||
expect(added.slug).toBe('page');
|
||||
expect(added.slug).not.toBe('');
|
||||
|
||||
// A second punctuation-only-named page dedupes to 'page-2', not ''.
|
||||
act(() => {
|
||||
ctx!.addPage('???', '');
|
||||
});
|
||||
const second = ctx!.pages.find((p) => p.name === '???')!;
|
||||
expect(second.slug).toBe('page-2');
|
||||
expect(second.slug).not.toBe('');
|
||||
|
||||
unmount();
|
||||
});
|
||||
|
||||
test('landing page slug always stays "index" even if renamed to collide', () => {
|
||||
let ctx: ReturnType<typeof usePages> | null = null;
|
||||
const Consumer: React.FC = () => {
|
||||
|
||||
@@ -96,12 +96,57 @@ describe('treeToCraftState resolvedName guard', () => {
|
||||
expect(parsed.ROOT.type.resolvedName).toBe('ColumnLayout');
|
||||
expect(parsed.ROOT.linkedNodes).toEqual({ 'col-0': 'a', 'col-1': 'b' });
|
||||
expect(parsed.ROOT.props.columns).toBe(2);
|
||||
// NB: the ROOT-aliasing step only reassigns `nodes[]` children's parent,
|
||||
// not `linkedNodes` children's — a pre-existing quirk (not introduced by
|
||||
// this refactor, and out of scope for E3) that leaves column children's
|
||||
// `parent` pointing at the tree's original (pre-alias) root id.
|
||||
expect(parsed['a'].parent).toBe('cols-1');
|
||||
expect(parsed['a'].isCanvas).toBe(true);
|
||||
// I-2: the ROOT-aliasing step must reparent linkedNodes children too, not
|
||||
// just nodes[] children. Before the fix, 'a'/'b'.parent stayed pointing
|
||||
// at the tree's original (pre-alias) root id ('cols-1'), which is then
|
||||
// `delete`d from the output -- a dangling parent reference that breaks
|
||||
// select/move/delete of those nodes in the Craft.js editor.
|
||||
expect(parsed['a'].parent).toBe('ROOT');
|
||||
expect(parsed['b'].parent).toBe('ROOT');
|
||||
expect(parsed['cols-1']).toBeUndefined();
|
||||
});
|
||||
|
||||
test('I-2: every child parent in the output tree references an id that exists (no dangling reference to the deleted old-root id) -- ColumnLayout root', () => {
|
||||
const tree: SerializedTreeNode = {
|
||||
type: { resolvedName: 'ColumnLayout' },
|
||||
props: { node_id: 'cols-1' },
|
||||
nodes: [
|
||||
{ type: { resolvedName: 'Heading' }, props: { node_id: 'a' }, nodes: [] },
|
||||
{ type: { resolvedName: 'Heading' }, props: { node_id: 'b' }, nodes: [] },
|
||||
],
|
||||
};
|
||||
const parsed = JSON.parse(treeToCraftState(tree));
|
||||
for (const id of Object.keys(parsed)) {
|
||||
const parent = parsed[id].parent;
|
||||
if (parent == null) continue;
|
||||
expect(parsed[parent]).toBeDefined();
|
||||
}
|
||||
});
|
||||
|
||||
test('I-2: a Section (SHELL_INNER) root reparents its section-inner linkedNode child to ROOT', () => {
|
||||
const tree: SerializedTreeNode = {
|
||||
type: { resolvedName: 'Section' },
|
||||
props: { node_id: 'sec-root' },
|
||||
nodes: [
|
||||
{ type: { resolvedName: 'Heading' }, props: { node_id: 'h-1', text: 'Hi' }, nodes: [] },
|
||||
],
|
||||
};
|
||||
const parsed = JSON.parse(treeToCraftState(tree));
|
||||
|
||||
const innerId = parsed.ROOT.linkedNodes['section-inner'];
|
||||
expect(innerId).toBeDefined();
|
||||
// The section-inner node itself is a linkedNodes child of the
|
||||
// (re-keyed) root -- its parent must point at 'ROOT', not the deleted
|
||||
// original root id 'sec-root'.
|
||||
expect(parsed[innerId].parent).toBe('ROOT');
|
||||
expect(parsed['sec-root']).toBeUndefined();
|
||||
// And every parent reference in the whole tree resolves to a real node.
|
||||
for (const id of Object.keys(parsed)) {
|
||||
const parent = parsed[id].parent;
|
||||
if (parent == null) continue;
|
||||
expect(parsed[parent]).toBeDefined();
|
||||
}
|
||||
});
|
||||
|
||||
test('style: [] normalizes to {} (regression)', () => {
|
||||
|
||||
@@ -21,6 +21,17 @@ interface PageContextValue {
|
||||
setHeaderCraftState: (craftState: string) => void;
|
||||
setFooterCraftState: (craftState: string) => void;
|
||||
setPagesCraftState: (pagesData: { id: string; name: string; slug: string; craftState: string | null }[]) => void;
|
||||
/**
|
||||
* Bookkeeping-only: point `activePageId` at an already-loaded page without
|
||||
* re-serializing/deserializing the canvas (the caller -- e.g. useWhpApi's
|
||||
* `load()` -- has already put the right state on the canvas itself). Used
|
||||
* to fix I-1: `activePageId` defaults to the hardcoded `'home'` and
|
||||
* `load()` never updated it, so after the original Home page was deleted
|
||||
* (its replacement gets a fresh `page_<ts>` id) and the app reloaded,
|
||||
* `activePageId` pointed at nothing in `pages`, and a subsequent edit+save
|
||||
* only reached the legacy top-level fields.
|
||||
*/
|
||||
setActivePageIdDirect: (pageId: string) => void;
|
||||
/** AI helpers — replace entire site or page with a new tree */
|
||||
replaceAllPages: (pages: { name: string; tree: SerializedTreeNode }[]) => void;
|
||||
replaceCurrentPage: (page: { name: string; tree: SerializedTreeNode }) => void;
|
||||
@@ -75,6 +86,16 @@ export function treeToCraftState(tree: SerializedTreeNode): string {
|
||||
for (const childId of nodes['ROOT'].nodes) {
|
||||
if (nodes[childId]) nodes[childId].parent = 'ROOT';
|
||||
}
|
||||
// I-2: linkedNodes children (e.g. ColumnLayout's col-0/col-1, or a
|
||||
// Section/BackgroundSection/FormContainer's SHELL_INNER wrapper) need
|
||||
// the same reparenting as nodes[] children above. Without this, a
|
||||
// ColumnLayout/SHELL_INNER-rooted AI `replace` leaves those children's
|
||||
// `parent` pointing at the OLD root id, which is then `delete`d --
|
||||
// producing a dangling parent reference that breaks select/move/delete
|
||||
// of those nodes in the Craft.js editor.
|
||||
for (const linkedId of Object.values(nodes['ROOT'].linkedNodes)) {
|
||||
if (nodes[linkedId]) nodes[linkedId].parent = 'ROOT';
|
||||
}
|
||||
}
|
||||
return JSON.stringify(nodes);
|
||||
}
|
||||
@@ -149,6 +170,7 @@ const PageContext = createContext<PageContextValue>({
|
||||
setHeaderCraftState: () => {},
|
||||
setFooterCraftState: () => {},
|
||||
setPagesCraftState: () => {},
|
||||
setActivePageIdDirect: () => {},
|
||||
replaceAllPages: () => {},
|
||||
replaceCurrentPage: () => {},
|
||||
setHeader: () => {},
|
||||
@@ -159,12 +181,17 @@ const PageContext = createContext<PageContextValue>({
|
||||
export const usePages = () => useContext(PageContext);
|
||||
|
||||
function slugify(name: string): string {
|
||||
return name
|
||||
const slug = name
|
||||
.toLowerCase()
|
||||
.trim()
|
||||
.replace(/[^a-z0-9\s-]/g, '')
|
||||
.replace(/\s+/g, '-')
|
||||
.replace(/-+/g, '-');
|
||||
// M-4: a punctuation-only name (e.g. "!!!") strips down to '' -- without a
|
||||
// fallback, buildSavePayload would write filename = '' + '.html' for that
|
||||
// page. uniqueSlug's existing dedupe logic then applies on top of this
|
||||
// fallback the same way it does for any other base ('page', 'page-2', ...).
|
||||
return slug || 'page';
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -385,6 +412,16 @@ export const PageProvider: React.FC<{ children: ReactNode }> = ({ children }) =>
|
||||
setFooterPage((prev) => ({ ...prev, craftState }));
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* Bookkeeping-only setter for `activePageId` -- see the doc comment on
|
||||
* `PageContextValue.setActivePageIdDirect`. Does NOT serialize/deserialize
|
||||
* the canvas; callers that need that should use `switchPage` instead.
|
||||
*/
|
||||
const setActivePageIdDirect = useCallback((pageId: string) => {
|
||||
setActivePageId(pageId);
|
||||
activePageIdRef.current = pageId;
|
||||
}, []);
|
||||
|
||||
/** Allow external code (e.g., load from API) to restore pages with craft states */
|
||||
const setPagesCraftState = useCallback((pagesData: { id: string; name: string; slug: string; craftState: string | null }[]) => {
|
||||
setPages(pagesData.map((p, i) => ({
|
||||
@@ -492,6 +529,7 @@ export const PageProvider: React.FC<{ children: ReactNode }> = ({ children }) =>
|
||||
setHeaderCraftState,
|
||||
setFooterCraftState,
|
||||
setPagesCraftState,
|
||||
setActivePageIdDirect,
|
||||
replaceAllPages,
|
||||
replaceCurrentPage,
|
||||
setHeader,
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import { describe, test, expect, vi, afterEach } from 'vitest';
|
||||
import React from 'react';
|
||||
import { createRoot, Root } from 'react-dom/client';
|
||||
import { act } from 'react-dom/test-utils';
|
||||
import { Modal } from './Modal';
|
||||
|
||||
/* ---------- DOM test harness (no @testing-library/react in this repo, see
|
||||
src/ui/AssetPicker.test.tsx for the same pattern: react-dom/client +
|
||||
react-dom/test-utils `act`, both transitive deps of react-dom already). ---------- */
|
||||
let container: HTMLDivElement;
|
||||
let root: Root;
|
||||
|
||||
function render(ui: React.ReactElement) {
|
||||
container = document.createElement('div');
|
||||
document.body.appendChild(container);
|
||||
act(() => {
|
||||
root = createRoot(container);
|
||||
root.render(ui);
|
||||
});
|
||||
}
|
||||
|
||||
function unmount() {
|
||||
act(() => { root.unmount(); });
|
||||
container.remove();
|
||||
}
|
||||
|
||||
function pressEscape() {
|
||||
act(() => {
|
||||
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
|
||||
});
|
||||
}
|
||||
|
||||
function click(el: Element | null) {
|
||||
if (!el) throw new Error('element not found');
|
||||
act(() => { (el as HTMLElement).dispatchEvent(new MouseEvent('click', { bubbles: true })); });
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
if (container) unmount();
|
||||
document.body.style.overflow = '';
|
||||
});
|
||||
|
||||
describe('Modal', () => {
|
||||
test('renders children when open', () => {
|
||||
render(<Modal open onClose={vi.fn()}><div data-testid="body">hello</div></Modal>);
|
||||
expect(container.querySelector('[data-testid="body"]')?.textContent).toBe('hello');
|
||||
});
|
||||
|
||||
test('renders nothing when closed', () => {
|
||||
render(<Modal open={false} onClose={vi.fn()}><div data-testid="body">hello</div></Modal>);
|
||||
expect(container.querySelector('[data-testid="body"]')).toBeNull();
|
||||
});
|
||||
|
||||
test('Escape calls onClose by default', () => {
|
||||
const onClose = vi.fn();
|
||||
render(<Modal open onClose={onClose}><div>body</div></Modal>);
|
||||
pressEscape();
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('Escape does not call onClose when closeOnEscape is false', () => {
|
||||
const onClose = vi.fn();
|
||||
render(<Modal open onClose={onClose} closeOnEscape={false}><div>body</div></Modal>);
|
||||
pressEscape();
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('clicking the backdrop calls onClose by default', () => {
|
||||
const onClose = vi.fn();
|
||||
render(<Modal open onClose={onClose}><div data-testid="body">body</div></Modal>);
|
||||
// The backdrop is the outermost rendered element.
|
||||
click(container.firstElementChild);
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('clicking inside the content does not call onClose', () => {
|
||||
const onClose = vi.fn();
|
||||
render(<Modal open onClose={onClose}><div data-testid="body">body</div></Modal>);
|
||||
click(container.querySelector('[data-testid="body"]'));
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('clicking the backdrop does not call onClose when closeOnBackdropClick is false', () => {
|
||||
const onClose = vi.fn();
|
||||
render(<Modal open onClose={onClose} closeOnBackdropClick={false}><div>body</div></Modal>);
|
||||
click(container.firstElementChild);
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('locks body scroll while open and restores it on close', () => {
|
||||
render(<Modal open onClose={vi.fn()}><div>body</div></Modal>);
|
||||
expect(document.body.style.overflow).toBe('hidden');
|
||||
act(() => { root.render(<Modal open={false} onClose={vi.fn()}><div>body</div></Modal>); });
|
||||
expect(document.body.style.overflow).toBe('');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
import React, { useEffect } from 'react';
|
||||
|
||||
export interface ModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
title?: string;
|
||||
children: React.ReactNode;
|
||||
width?: number | string;
|
||||
/** Override the backdrop's own inline styles (e.g. a different overlay
|
||||
* opacity/z-index). Merged on top of the shared defaults. */
|
||||
backdropStyle?: React.CSSProperties;
|
||||
/** Escape key closes the modal. Default true — set false to preserve a
|
||||
* modal that never handled Escape before this component existed. */
|
||||
closeOnEscape?: boolean;
|
||||
/** Clicking the backdrop (outside the modal content) closes the modal.
|
||||
* Default true — set false to preserve a modal that never handled
|
||||
* backdrop clicks before this component existed. */
|
||||
closeOnBackdropClick?: boolean;
|
||||
/** Extra attributes spread onto the backdrop div (e.g. role="dialog",
|
||||
* aria-modal) for a modal that previously set those directly. */
|
||||
backdropProps?: React.HTMLAttributes<HTMLDivElement>;
|
||||
}
|
||||
|
||||
const defaultBackdropStyle: React.CSSProperties = {
|
||||
position: 'fixed',
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.65)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
zIndex: 10000,
|
||||
};
|
||||
|
||||
/* ---------- Shared modal chrome ----------
|
||||
Backdrop + centered panel wrapper + Escape-to-close + scroll-lock, extracted
|
||||
from TemplateModal / HeadCodeModal / SitesmithModal (task E4.3). Each
|
||||
modal's own content — including its own header, close button, and panel
|
||||
styling (background, radius, shadow, dimensions) — stays in that modal's
|
||||
own file and is passed in as `children`, since those visuals differ across
|
||||
the three. `closeOnEscape` / `closeOnBackdropClick` default to true (the
|
||||
behavior TemplateModal and HeadCodeModal already had); SitesmithModal had
|
||||
neither before this extraction, so it opts out of both to keep its exact
|
||||
prior behavior. */
|
||||
export const Modal: React.FC<ModalProps> = ({
|
||||
open,
|
||||
onClose,
|
||||
title,
|
||||
children,
|
||||
width,
|
||||
backdropStyle,
|
||||
closeOnEscape = true,
|
||||
closeOnBackdropClick = true,
|
||||
backdropProps,
|
||||
}) => {
|
||||
useEffect(() => {
|
||||
if (!open || !closeOnEscape) return;
|
||||
const handler = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') onClose();
|
||||
};
|
||||
window.addEventListener('keydown', handler);
|
||||
return () => window.removeEventListener('keydown', handler);
|
||||
}, [open, closeOnEscape, onClose]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const prevOverflow = document.body.style.overflow;
|
||||
document.body.style.overflow = 'hidden';
|
||||
return () => {
|
||||
document.body.style.overflow = prevOverflow;
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
{...backdropProps}
|
||||
style={backdropStyle ? { ...defaultBackdropStyle, ...backdropStyle } : defaultBackdropStyle}
|
||||
onClick={(e) => {
|
||||
if (closeOnBackdropClick && e.target === e.currentTarget) onClose();
|
||||
}}
|
||||
>
|
||||
<div style={width !== undefined ? { width } : undefined}>
|
||||
{title !== undefined && (
|
||||
<div style={{ fontSize: 15, fontWeight: 600, marginBottom: 8 }}>{title}</div>
|
||||
)}
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, test, expect, vi } from 'vitest';
|
||||
import { sanitizeAiTree, __test } from './apply-ai-response';
|
||||
import type { SitesmithPatchOp } from '../types/sitesmith';
|
||||
|
||||
describe('findNodeIdByAiNodeId', () => {
|
||||
const query = {
|
||||
@@ -173,7 +174,7 @@ describe('applyPatch', () => {
|
||||
text: 'Old',
|
||||
style: { color: 'red', fontSize: '16px' },
|
||||
});
|
||||
const ops = [
|
||||
const ops: SitesmithPatchOp[] = [
|
||||
{
|
||||
op: 'update_props',
|
||||
node_id: 'ai-node-1',
|
||||
@@ -194,7 +195,7 @@ describe('applyPatch', () => {
|
||||
text: 'Old',
|
||||
style: { color: 'red', fontSize: '16px' },
|
||||
});
|
||||
const ops = [
|
||||
const ops: SitesmithPatchOp[] = [
|
||||
{
|
||||
op: 'update_props',
|
||||
node_id: 'ai-node-1',
|
||||
@@ -211,7 +212,7 @@ describe('applyPatch', () => {
|
||||
const { query, actions, propsById } = makeSingleNodeHarness('craft-1', 'ai-node-1', {
|
||||
style: { color: 'red', fontSize: '16px' },
|
||||
});
|
||||
const ops = [
|
||||
const ops: SitesmithPatchOp[] = [
|
||||
{ op: 'update_props', node_id: 'ai-node-1', props: { style: { color: 'blue' } } },
|
||||
];
|
||||
__test.applyPatch(actions, query, ops);
|
||||
@@ -221,7 +222,7 @@ describe('applyPatch', () => {
|
||||
test('an op with an unknown resolvedName tree is skipped without throwing; other ops in the batch still apply', () => {
|
||||
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
const { query, actions, propsById } = makeSingleNodeHarness('craft-1', 'ai-node-1', {});
|
||||
const ops = [
|
||||
const ops: SitesmithPatchOp[] = [
|
||||
{
|
||||
op: 'insert_after',
|
||||
node_id: 'ai-node-1',
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEditor } from '@craftjs/core';
|
||||
import type { NodeTree } from '@craftjs/core';
|
||||
import { usePages } from '../state/PageContext';
|
||||
import { SitesmithResponse, SerializedTreeNode } from '../types/sitesmith';
|
||||
import { SitesmithResponse, SerializedTreeNode, SitesmithPatchOp } from '../types/sitesmith';
|
||||
import { sanitizeAiTree, flattenTreeForCraft } from './craft-tree';
|
||||
|
||||
// Re-exported for existing callers/tests that import sanitizeAiTree from
|
||||
@@ -155,7 +155,7 @@ export function useApplyAiResponse() {
|
||||
function applyPatch(
|
||||
actions: any,
|
||||
query: any,
|
||||
ops: any[],
|
||||
ops: SitesmithPatchOp[],
|
||||
): { ok: boolean; message?: string } {
|
||||
for (const op of ops) {
|
||||
const id = findNodeIdByAiNodeId(query, op.node_id);
|
||||
@@ -237,7 +237,12 @@ function applyPatch(
|
||||
break;
|
||||
|
||||
default:
|
||||
console.warn('sitesmith patch: unknown op', (op as any).op);
|
||||
// Every SitesmithPatchOp variant is handled above, so `op` is typed
|
||||
// `never` here at compile time — but the AI response is untrusted
|
||||
// JSON (see useSitesmith.ts's `j: SendResult = await r.json()`), so
|
||||
// a malformed/unrecognized `op` field can still reach this branch at
|
||||
// runtime. Log the raw value rather than assuming a shape.
|
||||
console.warn('sitesmith patch: unknown op', op);
|
||||
}
|
||||
}
|
||||
return { ok: true };
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import { describe, test, expect } from 'vitest';
|
||||
import { cssValue } from './escape';
|
||||
|
||||
describe('cssValue', () => {
|
||||
test('neutralizes </style> breakout', () => {
|
||||
expect(cssValue('0px)}</style><script>alert(1)</script><style>{')).not.toContain('</style');
|
||||
expect(cssValue('0px)}</style><script>alert(1)</script><style>{')).not.toContain('<script');
|
||||
});
|
||||
|
||||
test('strips double quote (attribute breakout)', () => {
|
||||
expect(cssValue('red" onmouseover="alert(1)')).not.toContain('"');
|
||||
});
|
||||
|
||||
test('strips single quote', () => {
|
||||
expect(cssValue("red' onmouseover='alert(1)")).not.toContain("'");
|
||||
});
|
||||
|
||||
test('strips semicolon (declaration injection)', () => {
|
||||
expect(cssValue('red;background:url(javascript:alert(1))')).not.toContain(';');
|
||||
});
|
||||
|
||||
test('strips curly braces (rule injection)', () => {
|
||||
expect(cssValue('red}body{background:red')).not.toContain('{');
|
||||
expect(cssValue('red}body{background:red')).not.toContain('}');
|
||||
});
|
||||
|
||||
test('strips angle brackets', () => {
|
||||
expect(cssValue('<b>red</b>')).not.toContain('<');
|
||||
expect(cssValue('<b>red</b>')).not.toContain('>');
|
||||
});
|
||||
|
||||
test('strips backslash', () => {
|
||||
expect(cssValue('red\\3c script')).not.toContain('\\');
|
||||
});
|
||||
|
||||
test('neutralizes url( to block javascript: via background shorthand', () => {
|
||||
expect(cssValue("red;background:url(javascript:alert(1))")).not.toMatch(/url\s*\(/i);
|
||||
});
|
||||
|
||||
test('non-string input returns empty string', () => {
|
||||
expect(cssValue(undefined)).toBe('');
|
||||
expect(cssValue(null)).toBe('');
|
||||
expect(cssValue(123 as unknown)).toBe('');
|
||||
expect(cssValue({} as unknown)).toBe('');
|
||||
});
|
||||
|
||||
test('preserves hex colors', () => {
|
||||
expect(cssValue('#fff')).toBe('#fff');
|
||||
expect(cssValue('#3b82f6')).toBe('#3b82f6');
|
||||
});
|
||||
|
||||
test('preserves rgba()', () => {
|
||||
expect(cssValue('rgba(0,0,0,.5)')).toBe('rgba(0,0,0,.5)');
|
||||
});
|
||||
|
||||
test('preserves linear-gradient()', () => {
|
||||
expect(cssValue('linear-gradient(90deg,#aaa 0%,#bbb 100%)')).toBe('linear-gradient(90deg,#aaa 0%,#bbb 100%)');
|
||||
});
|
||||
|
||||
test('preserves calc()', () => {
|
||||
expect(cssValue('calc(50% - 8px)')).toBe('calc(50% - 8px)');
|
||||
});
|
||||
|
||||
test('preserves var()', () => {
|
||||
expect(cssValue('var(--x)')).toBe('var(--x)');
|
||||
});
|
||||
|
||||
test('preserves border shorthand', () => {
|
||||
expect(cssValue('1px solid #ccc')).toBe('1px solid #ccc');
|
||||
});
|
||||
|
||||
test('preserves px/%/em/rem sizes', () => {
|
||||
expect(cssValue('24px')).toBe('24px');
|
||||
expect(cssValue('50%')).toBe('50%');
|
||||
expect(cssValue('1.5em')).toBe('1.5em');
|
||||
expect(cssValue('2rem')).toBe('2rem');
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, test, expect } from 'vitest';
|
||||
import { escapeHtml, escapeAttr, safeUrl, stableHash, scopeId } from './escape';
|
||||
import { escapeHtml, escapeAttr, safeUrl, stableHash, scopeId, sanitizeFormMethod, sanitizeInputType } from './escape';
|
||||
|
||||
describe('escapeHtml', () => {
|
||||
test('escapes &, <, >, "', () => {
|
||||
@@ -140,3 +140,56 @@ describe('scopeId', () => {
|
||||
expect(scopeId('node-abc', 'seed', 'tabs')).toMatch(/^tabs_/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('sanitizeFormMethod', () => {
|
||||
test('allows GET and POST unchanged', () => {
|
||||
expect(sanitizeFormMethod('GET')).toBe('GET');
|
||||
expect(sanitizeFormMethod('POST')).toBe('POST');
|
||||
});
|
||||
|
||||
test('is case-insensitive and normalizes to uppercase', () => {
|
||||
expect(sanitizeFormMethod('get')).toBe('GET');
|
||||
expect(sanitizeFormMethod('post')).toBe('POST');
|
||||
expect(sanitizeFormMethod('PoSt')).toBe('POST');
|
||||
});
|
||||
|
||||
test('falls back to POST for anything not in the allowlist', () => {
|
||||
expect(sanitizeFormMethod('DELETE')).toBe('POST');
|
||||
expect(sanitizeFormMethod('')).toBe('POST');
|
||||
expect(sanitizeFormMethod(undefined as any)).toBe('POST');
|
||||
});
|
||||
|
||||
test('neutralizes an attribute-breakout injection instead of passing it through', () => {
|
||||
const malicious = 'POST"><script>alert(1)</script>';
|
||||
expect(sanitizeFormMethod(malicious)).toBe('POST');
|
||||
});
|
||||
|
||||
test('coerces non-string input safely', () => {
|
||||
expect(sanitizeFormMethod(123 as any)).toBe('POST');
|
||||
expect(sanitizeFormMethod(null as any)).toBe('POST');
|
||||
});
|
||||
});
|
||||
|
||||
describe('sanitizeInputType', () => {
|
||||
test('allows known-safe input types unchanged', () => {
|
||||
['text', 'email', 'tel', 'number', 'password', 'url', 'search', 'date', 'checkbox', 'radio', 'hidden'].forEach((t) => {
|
||||
expect(sanitizeInputType(t)).toBe(t);
|
||||
});
|
||||
});
|
||||
|
||||
test('falls back to text for anything not in the allowlist', () => {
|
||||
expect(sanitizeInputType('bogus')).toBe('text');
|
||||
expect(sanitizeInputType('')).toBe('text');
|
||||
expect(sanitizeInputType(undefined as any)).toBe('text');
|
||||
});
|
||||
|
||||
test('neutralizes an attribute-breakout injection instead of passing it through', () => {
|
||||
const malicious = 'text"><img src=x onerror=alert(1)>';
|
||||
expect(sanitizeInputType(malicious)).toBe('text');
|
||||
});
|
||||
|
||||
test('coerces non-string input safely', () => {
|
||||
expect(sanitizeInputType(123 as any)).toBe('text');
|
||||
expect(sanitizeInputType(null as any)).toBe('text');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -79,6 +79,30 @@ export function safeUrl(s: string): string {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Neutralizes CSS-context breakout for a single design-token value (color,
|
||||
* length, gradient, etc.) so it is safe to interpolate RAW into either CSS
|
||||
* context found in exported HTML:
|
||||
* - ATTRIBUTE context: `style="color:${v}"` -- a `"` or `'` closes the
|
||||
* attribute early; a `;` injects an extra declaration.
|
||||
* - ELEMENT context: `<style>.x{color:${v}}</style>` -- `<`, `>`, `{`, `}`
|
||||
* let a value close the rule / the `<style>` element itself and open a
|
||||
* `<script>`, which is the worst case (arbitrary script execution).
|
||||
* Strips the characters that can terminate a value, declaration, rule, or
|
||||
* the `<style>` element itself, and neutralizes `url(` so a background
|
||||
* shorthand can't smuggle a `javascript:` URL. None of hex colors,
|
||||
* `rgb()`/`rgba()`, `var(...)`, gradients, `calc(...)`, or `px`/`%`/`em`/
|
||||
* `rem` sizes contain any stripped character, so legitimate values pass
|
||||
* through unchanged. If a sink legitimately needs a background image URL,
|
||||
* route that value through `safeUrl` instead of `cssValue`.
|
||||
*/
|
||||
export function cssValue(v: unknown): string {
|
||||
if (typeof v !== 'string') return '';
|
||||
return v
|
||||
.replace(/[<>{};"'\\]/g, '')
|
||||
.replace(/url\s*\(/gi, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Derives a deterministic, HTML-id-safe slug from a field's `name`/`label`
|
||||
* for wiring `<label for>` to a matching `<input id>` in exported markup.
|
||||
@@ -130,3 +154,32 @@ export function scopeId(nodeId: string | undefined, fallbackSeed: string, prefix
|
||||
const slug = (nodeId || '').toString().toLowerCase().replace(/[^a-z0-9]+/g, '');
|
||||
return `${prefix}_${slug || stableHash(fallbackSeed)}`;
|
||||
}
|
||||
|
||||
// Shared enum allowlists for `toHtml` attribute sinks fed by props that are
|
||||
// declared as a TS union (e.g. `method?: 'GET' | 'POST'`) but are NOT
|
||||
// type-checked at runtime -- they arrive raw via the AI `update_props` path
|
||||
// (only `node_id` is validated there) or a deserialized saved-state blob.
|
||||
// Allowlisting -- rather than escaping -- is correct here because the only
|
||||
// legitimate values are the fixed set below; anything else is either an
|
||||
// honest mistake or an attribute-breakout attempt, and both collapse safely
|
||||
// to the same known-good default.
|
||||
|
||||
const ALLOWED_FORM_METHODS = ['GET', 'POST'] as const;
|
||||
|
||||
/** Allowlists a `<form method>` value, case-insensitively, falling back to 'POST'. */
|
||||
export function sanitizeFormMethod(m: unknown): 'GET' | 'POST' {
|
||||
const upper = (typeof m === 'string' ? m : '').trim().toUpperCase();
|
||||
return (ALLOWED_FORM_METHODS as readonly string[]).includes(upper) ? (upper as 'GET' | 'POST') : 'POST';
|
||||
}
|
||||
|
||||
const ALLOWED_INPUT_TYPES = [
|
||||
'text', 'email', 'tel', 'number', 'password', 'url', 'search',
|
||||
'date', 'time', 'datetime-local', 'month', 'week',
|
||||
'checkbox', 'radio', 'hidden', 'color', 'range', 'file',
|
||||
] as const;
|
||||
|
||||
/** Allowlists an `<input type>` value, falling back to 'text'. */
|
||||
export function sanitizeInputType(t: unknown): string {
|
||||
const value = typeof t === 'string' ? t : '';
|
||||
return (ALLOWED_INPUT_TYPES as readonly string[]).includes(value) ? value : 'text';
|
||||
}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { describe, test, expect } from 'vitest';
|
||||
import { exportBodyHtml } from './html-export';
|
||||
|
||||
/**
|
||||
* C2: buildDataAttrs (internal to html-export.ts) previously interpolated
|
||||
* `props.animation` / `props.animationDelay` directly into
|
||||
* `data-animation="${...}"` / `data-animation-delay="${...}"` with no
|
||||
* escaping. Runs for EVERY node (via renderNode -> buildDataAttrs ->
|
||||
* injectAttrs) and is reachable via AI `update_props` + deserialized saved
|
||||
* state. A malicious value like `x"><img src=y onerror=alert(1)>` breaks
|
||||
* out of the attribute and injects a live element.
|
||||
*/
|
||||
describe('buildDataAttrs escapes animation/animationDelay (C2)', () => {
|
||||
const makeState = (props: Record<string, unknown>) =>
|
||||
JSON.stringify({
|
||||
ROOT: {
|
||||
type: { resolvedName: 'Container' },
|
||||
isCanvas: true,
|
||||
props: { tag: 'div', style: {}, ...props },
|
||||
displayName: 'Container',
|
||||
custom: {},
|
||||
hidden: false,
|
||||
nodes: [],
|
||||
linkedNodes: {},
|
||||
},
|
||||
});
|
||||
|
||||
test('malicious animation value is escaped -- no raw breakout, no injected <img>', () => {
|
||||
const payload = 'x"><img src=y onerror=alert(1)>';
|
||||
const state = makeState({ animation: payload });
|
||||
const { html } = exportBodyHtml(state);
|
||||
|
||||
expect(html).not.toContain('<img src=y onerror=alert(1)>');
|
||||
expect(html).not.toMatch(/data-animation="x">/);
|
||||
// The attribute value must be escaped, so no raw `"` or `<` survives
|
||||
// inside the data-animation attribute region.
|
||||
expect(html).toContain('data-animation="x"><img src=y onerror=alert(1)>"');
|
||||
});
|
||||
|
||||
test('malicious animationDelay value is escaped -- no raw breakout', () => {
|
||||
const payload = 'x"><script>alert(1)</script>';
|
||||
const state = makeState({ animation: 'fade-in', animationDelay: payload });
|
||||
const { html } = exportBodyHtml(state);
|
||||
|
||||
expect(html).not.toContain('<script>alert(1)</script>');
|
||||
expect(html).toContain('data-animation-delay="x"><script>alert(1)</script>"');
|
||||
});
|
||||
|
||||
test('normal animation value still emits data-animation="fade-in" unchanged', () => {
|
||||
const state = makeState({ animation: 'fade-in' });
|
||||
const { html } = exportBodyHtml(state);
|
||||
expect(html).toContain('data-animation="fade-in"');
|
||||
});
|
||||
|
||||
test('normal animationDelay value still emits unchanged', () => {
|
||||
const state = makeState({ animation: 'fade-in', animationDelay: '0.5s' });
|
||||
const { html } = exportBodyHtml(state);
|
||||
expect(html).toContain('data-animation-delay="0.5s"');
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Adversarial re-review of C1: the `typeName === 'Container' || typeName ===
|
||||
* 'div'` fallback in renderNode (hit when a node's `resolvedName` isn't in
|
||||
* the component resolver, e.g. legacy/tampered saved state) interpolated
|
||||
* `props.tag` raw into `<${tag}` with no validation -- the same breakout
|
||||
* class as the fixed Container.toHtml bug, reachable via deserialized saved
|
||||
* state.
|
||||
*/
|
||||
describe('renderNode div-fallback allowlists props.tag', () => {
|
||||
const makeUnresolvedDivState = (tag: unknown) =>
|
||||
JSON.stringify({
|
||||
ROOT: {
|
||||
type: { resolvedName: 'div' }, // not in componentResolver -> hits the fallback branch
|
||||
isCanvas: true,
|
||||
props: { tag, style: {} },
|
||||
displayName: 'div',
|
||||
custom: {},
|
||||
hidden: false,
|
||||
nodes: [],
|
||||
linkedNodes: {},
|
||||
},
|
||||
});
|
||||
|
||||
test('a malicious tag value falls back to div -- no injected <img>', () => {
|
||||
const state = makeUnresolvedDivState('div><img src=x onerror=alert(1)');
|
||||
const { html } = exportBodyHtml(state);
|
||||
expect(html).not.toContain('<img');
|
||||
expect(html).not.toContain('onerror');
|
||||
expect(html.startsWith('<div')).toBe(true);
|
||||
});
|
||||
|
||||
test('a valid tag (section) still emits <section', () => {
|
||||
const state = makeUnresolvedDivState('section');
|
||||
const { html } = exportBodyHtml(state);
|
||||
expect(html).toContain('<section');
|
||||
expect(html).toContain('</section>');
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import { componentResolver } from '../components/resolver';
|
||||
import { cssPropsToString } from './style-helpers';
|
||||
import { escapeHtml } from './escape';
|
||||
import { escapeHtml, escapeAttr } from './escape';
|
||||
import { sanitizeContainerTag } from '../components/layout/Container';
|
||||
|
||||
export interface ExportOptions {
|
||||
title?: string;
|
||||
@@ -24,9 +25,9 @@ function buildDataAttrs(props: Record<string, any>): string {
|
||||
if (props.hideOnTablet) attrs += ' data-hide-tablet';
|
||||
if (props.hideOnMobile) attrs += ' data-hide-mobile';
|
||||
if (props.animation && props.animation !== 'none') {
|
||||
attrs += ` data-animation="${props.animation}"`;
|
||||
attrs += ` data-animation="${escapeAttr(String(props.animation))}"`;
|
||||
if (props.animationDelay && props.animationDelay !== '0') {
|
||||
attrs += ` data-animation-delay="${props.animationDelay}"`;
|
||||
attrs += ` data-animation-delay="${escapeAttr(String(props.animationDelay))}"`;
|
||||
}
|
||||
}
|
||||
return attrs;
|
||||
@@ -94,7 +95,11 @@ function renderNode(nodes: Record<string, any>, nodeId: string): { html: string
|
||||
// Fallback: wrap children in a div with inline styles
|
||||
if (typeName === 'Container' || typeName === 'div') {
|
||||
const styleStr = cssPropsToString(props.style);
|
||||
const tag = props.tag || 'div';
|
||||
// `props.tag` reaches this fallback the same way it reaches
|
||||
// `Container.toHtml` -- via AI `update_props` or deserialized saved
|
||||
// state, neither type-checked at runtime -- so it must be allowlisted
|
||||
// before hitting the `<${tag}` template position below.
|
||||
const tag = sanitizeContainerTag(props.tag);
|
||||
return {
|
||||
html: `<${tag}${dataAttrs}${styleStr ? ` style="${styleStr}"` : ''}>${allChildrenHtml}</${tag}>`,
|
||||
};
|
||||
|
||||
@@ -54,3 +54,102 @@ describe('cssPropsToString sanitizes emitted values (A5)', () => {
|
||||
expect(withoutEntities).not.toContain(';');
|
||||
});
|
||||
});
|
||||
|
||||
describe('cssPropsToString sanitizes emitted VALUES that are not strings (adversarial re-review of C1)', () => {
|
||||
test('an array value containing an attribute-breakout payload is neutralized', () => {
|
||||
const out = cssPropsToString({
|
||||
color: ['red', '"><img src=x onerror=alert(1)>'],
|
||||
} as any);
|
||||
// No raw `"` (would close style="...") and no raw `<`/`>` (defense in
|
||||
// depth) may survive -- they must come back as HTML entities, leaving
|
||||
// the payload as inert text rather than a live tag.
|
||||
expect(out).not.toMatch(/[<>"]/);
|
||||
expect(out).toContain('<img');
|
||||
expect(out).toContain('"');
|
||||
});
|
||||
|
||||
test('an object value containing an attribute-breakout payload is neutralized', () => {
|
||||
const out = cssPropsToString({
|
||||
color: { toString: () => '"><img src=x onerror=alert(1)>' },
|
||||
} as any);
|
||||
expect(out).not.toMatch(/[<>"]/);
|
||||
expect(out).toContain('<img');
|
||||
expect(out).toContain('"');
|
||||
});
|
||||
|
||||
test('a number value is emitted raw/unchanged', () => {
|
||||
const out = cssPropsToString({ zIndex: 5 } as any);
|
||||
expect(out).toBe('z-index:5');
|
||||
});
|
||||
|
||||
test('a normal string value still works after the fix', () => {
|
||||
const out = cssPropsToString({ color: 'red' } as any);
|
||||
expect(out).toBe('color:red');
|
||||
});
|
||||
});
|
||||
|
||||
describe('cssPropsToString sanitizes emitted KEYS (C1 -- style-object key breakout)', () => {
|
||||
test('a key containing a double-quote is dropped entirely, not emitted', () => {
|
||||
const out = cssPropsToString({
|
||||
color: 'red',
|
||||
'"><img src=x onerror=alert(1)>': '1',
|
||||
} as any);
|
||||
expect(out).not.toContain('"><img');
|
||||
expect(out).not.toContain('onerror');
|
||||
expect(out).toBe('color:red');
|
||||
});
|
||||
|
||||
test('a key containing > is dropped', () => {
|
||||
const out = cssPropsToString({ 'foo>bar': '1' } as any);
|
||||
expect(out).toBe('');
|
||||
});
|
||||
|
||||
test('a key containing < is dropped', () => {
|
||||
const out = cssPropsToString({ 'foo<bar': '1' } as any);
|
||||
expect(out).toBe('');
|
||||
});
|
||||
|
||||
test('a key containing a semicolon is dropped', () => {
|
||||
const out = cssPropsToString({ 'foo;bar': '1' } as any);
|
||||
expect(out).toBe('');
|
||||
});
|
||||
|
||||
test('a key containing a space is dropped', () => {
|
||||
const out = cssPropsToString({ 'foo bar': '1' } as any);
|
||||
expect(out).toBe('');
|
||||
});
|
||||
|
||||
test('legit simple key "color" is preserved', () => {
|
||||
const out = cssPropsToString({ color: 'red' } as any);
|
||||
expect(out).toBe('color:red');
|
||||
});
|
||||
|
||||
test('legit camelCase key backgroundColor -> background-color is preserved', () => {
|
||||
const out = cssPropsToString({ backgroundColor: 'blue' } as any);
|
||||
expect(out).toBe('background-color:blue');
|
||||
});
|
||||
|
||||
test('a CSS custom property key (--custom-prop) is preserved', () => {
|
||||
const out = cssPropsToString({ '--custom-prop': '10px' } as any);
|
||||
expect(out).toBe('--custom-prop:10px');
|
||||
});
|
||||
|
||||
test('a vendor-prefixed key (-webkit-...) is preserved', () => {
|
||||
const out = cssPropsToString({ WebkitBoxShadow: '0 0 1px red' } as any);
|
||||
expect(out).toBe('-webkit-box-shadow:0 0 1px red');
|
||||
});
|
||||
|
||||
test('a digits-only key is dropped', () => {
|
||||
const out = cssPropsToString({ '123': '1' } as any);
|
||||
expect(out).toBe('');
|
||||
});
|
||||
|
||||
test('other legit keys in the same object still emit even when a malicious key is dropped', () => {
|
||||
const out = cssPropsToString({
|
||||
color: 'red',
|
||||
'"><script>alert(1)</script>': 'x',
|
||||
backgroundColor: 'blue',
|
||||
} as any);
|
||||
expect(out).toBe('color:red;background-color:blue');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9,10 +9,16 @@ const URL_RE = /url\(\s*(['"]?)([\s\S]*?)\1\s*\)/gi;
|
||||
// Outside of a url(...) reference, a `;` is never legitimate (declarations
|
||||
// are separated by it) -- stray semicolons are how a breakout injects a
|
||||
// second property -- and a raw `"` would close the `style="..."` attribute
|
||||
// early. Inside url('...') the content has already been made safe via
|
||||
// escapeAttr(safeUrl(...)), including any `;` required by data-URI syntax
|
||||
// (`data:<mime>;base64,<payload>`), so this must never be applied there.
|
||||
const sanitizeBreakoutChars = (s: string): string => s.replace(/;/g, '').replace(/"/g, '"');
|
||||
// early. `<`/`>` are escaped too as defense-in-depth: they're inert inside a
|
||||
// properly quote-terminated `style="..."` attribute, but a value can reach
|
||||
// this function from a non-string source (array/object coerced via
|
||||
// `String(v)`, see `cssPropsToString` below) so we don't want to rely solely
|
||||
// on the outer quote holding. Inside url('...') the content has already been
|
||||
// made safe via escapeAttr(safeUrl(...)), including any `;` required by
|
||||
// data-URI syntax (`data:<mime>;base64,<payload>`), so this must never be
|
||||
// applied there.
|
||||
const sanitizeBreakoutChars = (s: string): string =>
|
||||
s.replace(/;/g, '').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');
|
||||
|
||||
/**
|
||||
* Sanitizes a single CSS declaration value so it can never terminate the
|
||||
@@ -43,11 +49,31 @@ function sanitizeCssValue(raw: string): string {
|
||||
return out;
|
||||
}
|
||||
|
||||
// A real CSS property name (`color`, `background-color`), vendor-prefixed
|
||||
// property (`-webkit-box-shadow`), or custom property (`--custom-prop`) --
|
||||
// nothing else. This is a KEY allowlist, not a value sanitizer: it exists
|
||||
// solely to stop a malicious style object KEY (e.g.
|
||||
// `'"><img src=x onerror=alert(1)>'`, reachable via AI `update_props` or
|
||||
// deserialized saved state, which spread arbitrary keys into `p.style`)
|
||||
// from being emitted unescaped into `style="${camelToKebab(k)}:${...}"` and
|
||||
// closing the attribute early. Legitimate keys never contain `"`, `>`, `<`,
|
||||
// `;`, whitespace, `{`, `}`, or digits-only, so this never rejects real CSS.
|
||||
const VALID_CSS_KEY_RE = /^-{0,2}[a-z][a-z-]*$/;
|
||||
|
||||
export function cssPropsToString(style: CSSProperties | undefined): string {
|
||||
if (!style) return '';
|
||||
return Object.entries(style)
|
||||
.filter(([, v]) => v !== undefined && v !== null && v !== '')
|
||||
.map(([k, v]) => `${camelToKebab(k)}:${typeof v === 'string' ? sanitizeCssValue(v) : v}`)
|
||||
.map(([k, v]) => [camelToKebab(k), v] as const)
|
||||
.filter(([k]) => VALID_CSS_KEY_RE.test(k))
|
||||
// Only a genuine `number` is safe to interpolate raw (numbers can never
|
||||
// contain a `"`/`<`/`>`/`;` breakout character). Every other type --
|
||||
// string, array, object, etc. -- must be coerced to a string and run
|
||||
// through `sanitizeCssValue`. Without this, a non-string value (e.g. an
|
||||
// array like `['red', '"><img src=x onerror=alert(1)>']`) skips
|
||||
// sanitization entirely and is template-coerced (`${v}`) raw into the
|
||||
// `style="..."` attribute, breaking out via the un-escaped `"`.
|
||||
.map(([k, v]) => `${k}:${typeof v === 'number' ? v : sanitizeCssValue(String(v))}`)
|
||||
.join(';');
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user