Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/safe-footnote-content.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@youversion/platform-core": patch
"@youversion/platform-react-ui": patch
---

Sanitized `data-verse-footnote-content` found in Bible HTML input with the same allowlist as passage markup, so planted footnote markup can no longer run script in the Bible reader. `transformBibleHtml` now removes input `data-footnote-key` attributes and `data-yv-*` attributes other than `data-yv-transformed`, and drops all SVG and MathML content. `FootnoteContentProps` now documents that `notes` and `verseHtml` must be sanitized HTML.
72 changes: 72 additions & 0 deletions packages/core/src/bible-html-transformer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,20 @@
import { describe, it, expect } from 'vitest';
import { transformBibleHtml, transformBibleHtmlForBrowser } from './bible-html-transformer';

function parse(html: string): Document {
return new DOMParser().parseFromString(html, 'text/html');
}

function toAttr(html: string): string {
return html.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;');
}

function footnoteContent(doc: Document, key: string): string | null | undefined {
return doc
.querySelector(`[data-verse-footnote="${key}"]`)
?.getAttribute('data-verse-footnote-content');
}

function createAdapters() {
return {
parseHtml: (html: string) => new DOMParser().parseFromString(html, 'text/html'),
Expand Down Expand Up @@ -445,6 +459,64 @@ describe('transformBibleHtml - sanitization', () => {
expect(result.html).toContain('data-custom="value"');
});

it('should sanitize planted footnote content and strip reserved attributes from raw and transformed input', () => {
const raw = `<div class="p" data-footnote-key="1" data-yv-sdk="" data-yv-shadow-host="" data-slot="keep"><span class="yv-v" v="1"></span>Text<span data-verse-footnote="1" data-verse-footnote-content="${toAttr('<img src=x onerror=alert(1)>Planted')}"></span></div>`;
const rawDoc = parse(transformBibleHtml(raw, createAdapters()).html);
const rawRoot = rawDoc.body.firstElementChild;

expect(footnoteContent(rawDoc, '1')).toBe('Planted');
expect(rawRoot?.hasAttribute('data-footnote-key')).toBe(false);
expect(rawRoot?.hasAttribute('data-yv-sdk')).toBe(false);
expect(rawRoot?.hasAttribute('data-yv-shadow-host')).toBe(false);
expect(rawRoot?.getAttribute('data-slot')).toBe('keep');
expect(rawRoot?.hasAttribute('data-yv-transformed')).toBe(true);

const plantedNote =
'<span class="ft" onclick="alert(1)" data-yv-transformed="" data-slot="n">Note</span><script>alert(1)</script><img src=x onerror=alert(1)><span data-verse-footnote="2" data-verse-footnote-content="x" data-footnote-key="2">Nested</span>';
const transformed = `<div data-yv-transformed=""><span class="yv-v" v="1">Text<span data-verse-footnote="1" data-verse-footnote-content="${toAttr(plantedNote)}"></span></span></div>`;
const transformedDoc = parse(transformBibleHtml(transformed, createAdapters()).html);

expect(footnoteContent(transformedDoc, '1')).toBe(
'<span class="ft" data-slot="n">Note</span><span>Nested</span>',
);
expect(transformedDoc.querySelectorAll('[data-verse-footnote]')).toHaveLength(1);
});

it('should block footnote content bypasses and stay stable when transformed again', () => {
const bypasses: Array<[payload: string, expected: string]> = [
['<svg><script>alert(1)</script></svg>Safe', 'Safe'],
['<math><mtext><img src=x onerror=alert(1)></mtext><mi>x</mi></math>Safe', 'Safe'],
['<span ONCLICK="alert(1)" OnMouseOver="alert(1)">Safe</span>', '<span>Safe</span>'],
['<span &#111;nclick="alert(1)">Safe</span>', '<span>Safe</span>'],
['&lt;img src=x onerror=alert(1)&gt;', '&lt;img src=x onerror=alert(1)&gt;'],
['<a href="javascript:alert(1)">Safe</a>', 'Safe'],
[
'<span class="ft" style="background:url(javascript:alert(1))" href="javascript:alert(1)" src="data:text/html,x">Safe</span>',
'<span class="ft">Safe</span>',
],
['<img src="data:image/svg+xml,<svg onload=alert(1)>">Safe', 'Safe'],
];

for (const [payload, expected] of bypasses) {
const html = `<div data-yv-transformed=""><span data-verse-footnote="1" data-verse-footnote-content="${toAttr(payload)}"></span></div>`;
const first = transformBibleHtml(html, createAdapters());
const second = transformBibleHtml(first.html, createAdapters());

expect(footnoteContent(parse(first.html), '1'), payload).toBe(expected);
expect(second.html, payload).toBe(first.html);
}

const genuine =
'<div class="p"><span class="yv-v" v="1"></span><span class="yv-vlbl">1</span>Text<span class="yv-n f"><span class="fr">1:1 </span><span class="ft">A <em>note</em> <span data-verse-footnote="9">n</span></span></span>.</div>';
const first = transformBibleHtml(genuine, createAdapters());
const second = transformBibleHtml(first.html, createAdapters());

expect(footnoteContent(parse(first.html), '1')).toBe(
'<span class="fr">1:1 </span><span class="ft">A <em>note</em> <span>n</span></span>',
);
expect(second.html).toBe(first.html);
});

it('should preserve dir attribute for RTL support', () => {
const html = '<div dir="rtl"><p class="p">Hebrew text</p></div>';
const result = transformBibleHtml(html, createAdapters());
Expand Down
144 changes: 99 additions & 45 deletions packages/core/src/bible-html-transformer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,49 +6,74 @@ const TRANSFORMED_ATTR = 'data-yv-transformed';

const NEEDS_SPACE_BEFORE = /^[^\s.,;:!?)}\]'"'»›]/;

const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';

const ALLOWED_TAGS = new Set([
'DIV',
'P',
'SPAN',
'SUP',
'SUB',
'EM',
'STRONG',
'I',
'B',
'SMALL',
'BR',
'SECTION',
'TABLE',
'THEAD',
'TBODY',
'TR',
'TD',
'TH',
'div',
'p',
'span',
'sup',
'sub',
'em',
'strong',
'i',
'b',
'small',
'br',
'section',
'table',
'thead',
'tbody',
'tr',
'td',
'th',
]);

const DROP_ENTIRELY_TAGS = new Set([
'SCRIPT',
'STYLE',
'IFRAME',
'OBJECT',
'EMBED',
'SVG',
'MATH',
'FORM',
'INPUT',
'BUTTON',
'TEXTAREA',
'SELECT',
'TEMPLATE',
'LINK',
'META',
'BASE',
'NOSCRIPT',
'script',
'style',
'iframe',
'object',
'embed',
'svg',
'math',
'form',
'input',
'button',
'textarea',
'select',
'template',
'link',
'meta',
'base',
'noscript',
]);

const ALLOWED_ATTRS = new Set(['class', 'v', 'colspan', 'rowspan', 'dir', 'usfm']);

const FOOTNOTE_ANCHOR_ATTR = 'data-verse-footnote';

const FOOTNOTE_CONTENT_ATTR = 'data-verse-footnote-content';

const FOOTNOTE_DATA_ATTRS = new Set([FOOTNOTE_ANCHOR_ATTR, FOOTNOTE_CONTENT_ATTR]);

type SanitizeMode = 'passage' | 'footnote';

// Other data-* attributes stay because consumers style and query them (for
// example data-slot), and they carry no behavior. SDK-internal names are
// reserved so a passage cannot plant them. The transformed marker stays so
// re-transforming output is idempotent; footnote content is re-sanitized as
// HTML instead of trusted, and cannot nest further footnote anchors.
function isAllowedDataAttr(name: string, mode: SanitizeMode): boolean {
if (!name.startsWith('data-')) return false;
if (name === FOOTNOTE_KEY_ATTR) return false;
if (name.startsWith('data-yv-') && name !== TRANSFORMED_ATTR) return false;
if (mode === 'footnote' && (FOOTNOTE_DATA_ATTRS.has(name) || name === TRANSFORMED_ATTR)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Change needed before approval: no test covers removing data-yv-transformed in footnote mode. When we deleted this check, all 50 tests still passed. Please add a test that fails without it (docs/testing.md).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 57569dd. The planted note in the first workflow test has data-yv-transformed="" on a nested span, and the test expects the exact value <span class="ft" data-slot="n">Note</span>…. If I remove || name === TRANSFORMED_ATTR, that test fails.

return false;
}
return true;
}

export type TextDirection = 'ltr' | 'rtl';

function topLevelElements(doc: Document): Element[] {
Expand All @@ -64,17 +89,16 @@ function resolveTextDirection(roots: Element[]): TextDirection | undefined {
return undefined;
}

function sanitizeBibleHtmlDocument(doc: Document): void {
const root = doc.body ?? doc.documentElement;
function sanitizeBibleHtmlTree(root: ParentNode, mode: SanitizeMode): void {
for (const el of Array.from(root.querySelectorAll('*'))) {
const tag = el.tagName;

if (DROP_ENTIRELY_TAGS.has(tag)) {
// SVG and MathML elements keep lowercase tag names and their own parsing
// rules, so anything outside the HTML namespace is dropped with its text.
if (el.namespaceURI !== HTML_NAMESPACE || DROP_ENTIRELY_TAGS.has(el.localName)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

praise: Checking the namespace closes the SVG/MathML mutation-XSS route. The old uppercase tag-name check missed those elements, because they keep lowercase tag names. <svg><style><img onerror> and <math><mtext><img onerror> both come out empty now.

el.remove();
continue;
}

if (!ALLOWED_TAGS.has(tag)) {
if (!ALLOWED_TAGS.has(el.localName)) {
el.replaceWith(...Array.from(el.childNodes));
continue;
}
Expand All @@ -86,13 +110,30 @@ function sanitizeBibleHtmlDocument(doc: Document): void {
continue;
}

if (!ALLOWED_ATTRS.has(name) && !name.startsWith('data-')) {
if (!ALLOWED_ATTRS.has(name) && !isAllowedDataAttr(name, mode)) {
el.removeAttribute(attr.name);
}
}

const footnoteContent = el.getAttribute(FOOTNOTE_CONTENT_ATTR);
if (footnoteContent !== null) {
el.setAttribute(
FOOTNOTE_CONTENT_ATTR,
sanitizeFootnoteHtml(footnoteContent, el.ownerDocument),
);
}
}
}

// Footnote content is rendered as HTML by consumers, so it must pass the same
// allowlist as passage markup. An inert template avoids a full parse per note.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

praise: Parsing each note in an inert <template> fixed the speed problem. The earlier head did a full document parse per note and took 226 ms to re-transform 150 footnotes; now it takes 22 ms. It also means a <body onload> inside a note can't attach to anything.

function sanitizeFootnoteHtml(html: string, doc: Document): string {
const template = doc.createElement('template');
template.innerHTML = html;
sanitizeBibleHtmlTree(template.content, 'footnote');
return template.innerHTML;
}

/**
* Options for transforming Bible HTML. Requires DOM adapter functions
* to parse and serialize HTML, making the transformer runtime-agnostic.
Expand All @@ -113,6 +154,12 @@ export type TransformBibleHtmlOptions = {
*
* Consumers can access verse context by walking up from a footnote anchor
* to `.closest('.yv-v[v]')`.
*
* Sanitization: `html` and every `data-verse-footnote-content` value pass the
* same tag and attribute allowlist, so both are safe to inject as HTML. Input
* `data-footnote-key` and `data-yv-*` attributes (except `data-yv-transformed`)
* are removed; footnote content also has no `data-verse-footnote`,
* `data-verse-footnote-content`, or `data-yv-transformed` attributes.
*/
export type TransformedBibleHtml = {
/** The transformed HTML with footnotes replaced by marker elements */
Expand Down Expand Up @@ -290,8 +337,8 @@ function replaceFootnotesWithAnchors(doc: Document, footnotes: Element[]): void
}

const anchor = doc.createElement('span');
anchor.setAttribute('data-verse-footnote', key);
anchor.setAttribute('data-verse-footnote-content', fn.innerHTML);
anchor.setAttribute(FOOTNOTE_ANCHOR_ATTR, key);
anchor.setAttribute(FOOTNOTE_CONTENT_ATTR, sanitizeFootnoteHtml(fn.innerHTML, doc));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

note: Cleaning genuine footnote HTML here also fixes a case where the output changed on each transform. A planted anchor inside a real yv-n f footnote used to survive the first transform and get removed by the second. Now two transforms give identical output in every probe case.

fn.replaceWith(anchor);
}
}
Expand Down Expand Up @@ -344,6 +391,13 @@ function fixIrregularTables(doc: Document): void {
* Verse context is available by walking up from a footnote anchor:
* `anchor.closest('.yv-v[v]')` returns the verse wrapper (null for intro footnotes).
*
* Sanitization: input is treated as untrusted. Disallowed tags, SVG/MathML,
* `on*` handlers, and non-allowlisted attributes are removed. Footnote content
* already present in input (`data-verse-footnote-content`) is sanitized the same
* way, so the output and its footnote content are safe to inject as HTML. Input
* `data-footnote-key` and `data-yv-*` attributes (except `data-yv-transformed`)
* are removed. Other `data-*` attributes are kept.
*
* @param html - The raw Bible HTML from the YouVersion API
* @param options - DOM adapter options for parsing and serializing HTML
* @returns The transformed HTML
Expand All @@ -366,7 +420,7 @@ export function transformBibleHtml(
): TransformedBibleHtml {
const doc = options.parseHtml(html);

sanitizeBibleHtmlDocument(doc);
sanitizeBibleHtmlTree(doc.body ?? doc.documentElement, 'passage');

// Only trust the marker when every top-level element carries it. A nested or
// partially-marked fragment (transformed HTML concatenated with raw HTML, or
Expand Down
18 changes: 17 additions & 1 deletion packages/ui/src/components/verse.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* @vitest-environment jsdom
*/
import { describe, it, expect, vi, afterEach } from 'vitest';
import { act, render as rtlRender, waitFor } from '@testing-library/react';
import { act, render as rtlRender, screen, waitFor, within } from '@testing-library/react';
import type { ReactElement } from 'react';
import { hydrateRoot } from 'react-dom/client';
import { renderToString } from 'react-dom/server';
Expand Down Expand Up @@ -367,6 +367,22 @@ describe('Verse.Html - Footnotes', () => {
});
});

it('should not render HTML planted in data-verse-footnote-content', async () => {
const plantedHtml =
'<div class="p"><span class="yv-v" v="1"></span><span class="yv-vlbl">1</span>Text<span data-verse-footnote="1" data-verse-footnote-content="&lt;img src=x onerror=alert(1)&gt;Planted"></span></div>';

render(<Verse.Html html={plantedHtml} renderNotes={true} />);

await userEvent.click(await screen.findByRole('button'));

const dialog = await screen.findByRole('dialog');
await waitFor(() => {
expect(within(dialog).getByText('Planted')).toBeInTheDocument();
});
expect(dialog.querySelector('img')).toBeNull();
expect(dialog.innerHTML).not.toContain('onerror');
});

it('should use alphabetic markers beyond z in the popover list', async () => {
const repeatedFootnotes = Array.from({ length: 27 }, () => {
return '<span class="yv-n f"><span class="fr">1:1 </span><span class="ft">Footnote text</span></span>';
Expand Down
11 changes: 9 additions & 2 deletions packages/ui/src/components/verse.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,13 @@ export type FootnoteData = {
reference?: string;
};

/**
* Props for {@link FootnoteContent}.
*
* Security: `notes` and `verseHtml` are injected as HTML without further
* sanitization. Pass only output from `transformBibleHtml` (or HTML that went
* through an equivalent allowlist sanitizer); never pass raw API or user HTML.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (non-blocking): The follow-up to this doc comment should also cover the footnote key. getVerseHtmlFromDom (L164) puts data-verse-footnote into `.yv-v[v="${verseNum}"]` without escaping. The key has to survive sanitizing, so a planted value reaches the selector. 1"] <img [x=" makes querySelectorAll throw, which breaks footnote collection for that render. 1"] .yv-v, [v=" makes the popover show the wrong verse. It can't run script, and the same bug exists on main. Fix it with CSS.escape(verseNum) or a /^[\w-]+$/ check where the key is read at L396.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. The follow-up will cover the footnote key as well: check it against /^[\w-]+$/ where it is read (L396), and CSS.escape it in getVerseHtmlFromDom. That way a planted key can't make querySelectorAll throw or point the popover at another verse. I'm keeping it out of this PR because the same bug exists on main and can't run script.

*/
export type FootnoteContentProps = FootnoteData & {
scriptureDirection?: TextDirection;
fontSize?: number;
Expand Down Expand Up @@ -95,7 +102,7 @@ function FootnoteContentImplementation({
<div
className="yv:mb-3 yv:font-serif yv:*:font-serif"
style={{ fontSize: fontSize ? `${fontSize}px` : '1.25rem' }}
// biome-ignore lint/security/noDangerouslySetInnerHtml: Bible footnote HTML comes from our YouVersion APIs and is safe
// Caller must pass sanitized HTML; see FootnoteContentProps.
dangerouslySetInnerHTML={{ __html: verseHtml }}
/>
</>
Expand All @@ -109,7 +116,7 @@ function FootnoteContentImplementation({
className="yv:flex yv:gap-2 yv:text-xs yv:border-b yv:border-solid yv:border-border yv:py-2"
>
<span>{marker}.</span>
{/** biome-ignore lint/security/noDangerouslySetInnerHtml: Bible footnote HTML comes from our YouVersion APIs and is safe */}
{/* Caller must pass sanitized HTML; see FootnoteContentProps. */}
<span data-slot="yv-bible-note" dangerouslySetInnerHTML={{ __html: note }} />
</li>
);
Expand Down
Loading