# Rich Text & Embedded Blocks

> How OvertCMS Core parses, canonicalizes, secures, and projects rich_html fields using WHATWG HTML5 parsing, <cms-block> structured components, and targeted bodyPatches.

OvertCMS Core stores rich editorial content in `rich_html` fields as **canonical semantic HTML5**—never proprietary editor JSON ASTs—parsed and validated on every write using Go's WHATWG-compliant HTML5 parser (`golang.org/x/net/html`).

This gives clients clean, zero-transform semantic HTML, lets LLMs author naturally without brittle proprietary JSON node trees, and enforces airtight XSS protection at the storage boundary.

## Semantic HTML5 Allowlist

### Allowed Elements

| Category | Permitted Tags | Notes |
| :--- | :--- | :--- |
| **Headings** | `h1`, `h2`, `h3`, `h4`, `h5`, `h6` | `h1` can be blocked via `constraints.disallowH1: true`. |
| **Block prose** | `p`, `blockquote`, `footer`, `hr`, `pre` | `footer` is allowed **only** inside `blockquote`. |
| **Lists** | `ul`, `ol`, `li` | Checklists (`ul[data-checklist]`, `li[data-checked]`) require `allowChecklists: true`. |
| **Tables** | `table`, `caption`, `thead`, `tbody`, `tfoot`, `tr`, `th`, `td` | `colspan`/`rowspan` must be positive integers; `th[scope]` must be `row`, `col`, `rowgroup`, or `colgroup`. |
| **Media** | `figure`, `figcaption`, `img`, `audio`, `video`, `source` | Gated by `allowInlineMedia` (default `true`). `source` is allowed **only** inside `audio` or `video`. |
| **Embeds** | `iframe` | Disabled by default (`allowEmbeds: false`). Requires allowlisted HTTPS `src` and empty body. |
| **Inline marks** | `strong`, `em`, `u`, `s`, `mark`, `sup`, `sub`, `code`, `a`, `br`, `time` | `code[class]` is allowed **only** inside `pre` and must match `^language-[a-zA-Z0-9_+-]+$`. |
| **Structured blocks** | `<cms-block>` | Must reference an allowlisted Component via `type` and valid JSON in `data-props`. |

### Allowed Attributes

Every attribute not explicitly listed below is rejected (in `strict` mode) or stripped with a warning (in `sanitize` mode). Event handlers (`on*`), inline `style`, and foreign XML/SVG/MathML namespaces are **always forbidden**:

| Tag | Allowed Attributes |
| :--- | :--- |
| `a` | `href` (`http:`, `https:`, `mailto:`, `tel:`, `#anchor`, or root-relative `/path`), `title`, `rel` |
| `img` | `src`, `alt`, `title`, `width`, `height`, `data-asset-id` |
| `audio` | `controls` |
| `video` | `controls`, `poster` |
| `source` | `src`, `type` |
| `iframe` | `src` (HTTPS allowlisted host only), `title`, `width`, `height`, `allowfullscreen` |
| `code` | `class` (inside `pre` only, matching `language-*`) |
| `ul` | `data-checklist` (`""`, `"true"`, `"false"`, when `allowChecklists: true`) |
| `ol` | `start` (integer) |
| `li` | `data-checked` (`"true"` or `"false"`, when `allowChecklists: true`) |
| `th` | `colspan`, `rowspan`, `scope` |
| `td` | `colspan`, `rowspan` |
| `time` | `datetime` |
| `cms-block` | `type`, `data-props` |

### Default `iframe` Embed Host Allowlist

When `allowEmbeds: true`, `iframe[src]` must be `https://` without userinfo, have no child fallback content, and match the allowlist:
- `youtube.com`, `www.youtube.com`, `youtu.be`
- `player.vimeo.com`
- `open.spotify.com`
- `www.loom.com`
- `codepen.io`
- `datawrapper.dwcdn.net`

---

## Security Defenses & Strictness Modes

### `strict` (Default) vs. `sanitize`

- **`strict` (default)**: Any forbidden tag (`script`, `style`, `svg`, `math`, `form`, `input`, `textarea`, `button`, `object`, `embed`), disallowed attribute, HTML comment, disallowed block/mark, or unsafe URL fails the write with a `422 validation_error` containing exact field diagnostics. Ideal for AI agents and APIs so issues are fixed rather than silently mutated.
- **`sanitize`**: Drops entire subtrees of dangerous tags (`script`, `style`, `svg`, `math`, `object`, `embed`, `noscript`, `template`, `form`, `input`, `iframe` with bad `src`, etc.), unwraps benign unknown wrapper tags (like `div`/`span`) while keeping their text, strips disallowed attributes and comments, and returns non-fatal `warnings` alongside the canonical HTML.

### URL Obfuscation & Placeholder Link Guards

- **Scheme obfuscation defense**: Strips ASCII control characters and whitespace before checking URLs so payloads like `java\tscript:alert(1)`, `data:`, `vbscript:`, or backslash tricks are unconditionally caught.
- **LLM placeholder link guard**: Outside `<pre><code>` blocks, `<a href>` rejects common LLM placeholders—such as `#`, `TBD`, `TODO`, `[insert link]`, `{{url}}`, `example.com`, `example.org`, `example.net`, and `placeholder.*`—with `placeholder_link_detected` in **both** `strict` and `sanitize` modes.

---

## Structured Components with `<cms-block>`

Embed strongly typed, schema-validated Components anywhere inside a `rich_html` document using empty `<cms-block>` elements:

```html
<h2>Deployment Checklist</h2>
<p>Before going live, verify your master secret key.</p>
<cms-block type="callout" data-props='{"tone":"warning","title":"Master Key Required","body":"Set OVERTCMS_SECRET_KEY to at least 32 bytes."}'></cms-block>
```

**Rules enforced on every `<cms-block>`:**
1. The `type` slug must be listed in the field's `constraints.allowedComponents` and exist on the site.
2. Only `type` and `data-props` attributes are allowed; `<cms-block>` must contain **no child elements or non-whitespace text** (`cms_block_non_empty_body`).
3. `data-props` is decoded strictly as a single JSON object, scanned for prototype-pollution keys (`__proto__`, `constructor`, `prototype`), and validated against the Component's `fields` schema (including nested references, media assets, and `aiWritable` checks).
4. Normalized props are re-serialized into deterministic canonical JSON inside `data-props`.
5. Maximum `<cms-block>` nesting depth is **4** (`maxCMSBlockDepth`).
6. Any `reference` or media field inside a `<cms-block>` is automatically indexed into `entry_references` and `entry_media_refs`!

---

## Automatic Inline Image Sideloading

When an entry's `rich_html` field contains an external `<img src="https://...">` **without** a `data-asset-id` attribute:

- On create, update, publish, or schedule (skipped during `dryRun`), OvertCMS Core automatically fetches the image through the SSRF-hardened `SafeFetcher` (up to **20** external inline images per entry), sniffs magic bytes, deduplicates by SHA-256, stores it in your media driver, and rewrites the `<img>` tag with `data-asset-id="<assetId>"` and your canonical media/CDN `src` URL.
- If the request is authenticated with an API key, sideloaded bytes are charged against that key's `dailyMediaBytesCap`.

---

## Targeted Body Patching (`bodyPatches`)

Rather than having an AI agent regenerate and resend a 5,000-word HTML article to fix one paragraph, `PATCH` requests accept `bodyPatches` keyed by field name. Patches run sequentially against the current `draftData` HTML and then pass through `CanonicalizeHTML`:

```json
{
  "expectedVersion": 2,
  "bodyPatches": {
    "body": [
      {
        "op": "replace_exact",
        "oldHtml": "<p>PostgreSQL 15 is supported.</p>",
        "newHtml": "<p>PostgreSQL 16 is supported.</p>"
      },
      {
        "op": "append_after",
        "anchorHtml": "<h2>Prerequisites</h2>",
        "insertHtml": "<p>Make sure Go 1.23 or newer is installed.</p>"
      },
      {
        "op": "prepend_before",
        "anchorHtml": "<h2>Next Steps</h2>",
        "insertHtml": "<p>You are now ready to deploy.</p>"
      }
    ]
  }
}
```

### Exact Single-Match Safety

Every patch operation (`replace_exact`, `append_after`, `prepend_before`) enforces an **exact match count of 1**:
- **0 matches** -> `422 patch_target_not_found`
- **2+ matches** -> `422 patch_target_ambiguous` (caller must provide a more specific snippet)

This eliminates silent mis-edits and makes automated editing deterministic and retry-safe.

---

## Derived HTML Projections (`?include=...`)

On the Delivery Plane, request derived read-only metadata for every `rich_html` field via `?include=plainText,wordCount,headings,readingTime`:

```bash
GET /delivery/v1/posts/hello-overtcms?include=plainText,wordCount,headings,readingTime
```

```json
{
  "id": "0193a8b2-...",
  "slug": "hello-overtcms",
  "data": { "title": "Hello OvertCMS Core", "body": "<h2>Welcome</h2><p>...</p>" },
  "projections": {
    "body": {
      "plainText": "Welcome\nPublished from the Agent Plane with strict HTML5 validation.",
      "wordCount": 11,
      "readingTime": 1,
      "headings": [
        { "level": 2, "id": "welcome", "text": "Welcome" }
      ]
    }
  }
}
```

- **Unicode & CJK word counting**: Counts Latin/alphanumeric words (preserving internal apostrophes/hyphens like `don't` and `well-known`) and counts each CJK Han/Hiragana/Katakana character as one word.
- **Reading time**: Computed as `ceil(wordCount / 225)` minutes (`(wordCount + 224) / 225`).
- **Heading outline**: Extracts `h1`–`h6` in document order, strips NFD diacritics (e.g. `café` -> `cafe`), and automatically deduplicates repeated slugs (`setup`, `setup-2`, `setup-3`).
- `<cms-block>`, `iframe`, `script`, and `style` elements are excluded from prose projections.
