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
20 changes: 20 additions & 0 deletions src/utils/sanitize.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { describe, expect, test } from 'vitest';
import { sanitizeHtml } from './sanitize';

describe('sanitizeHtml iframe handling', () => {
test('strips non-YouTube iframe', () => {
const html = '<iframe src="https://evil.com"></iframe>';
const result = sanitizeHtml(html);
expect(result).not.toContain('iframe');
});

test('allows YouTube nocookie iframe with allowfullscreen', () => {
const html =
'<iframe src="https://www.youtube-nocookie.com/embed/abc" allowfullscreen></iframe>';
const result = sanitizeHtml(html);
// src should remain
expect(result).toContain('src="https://www.youtube-nocookie.com/embed/abc"');
// allowfullscreen should be present (may be normalized)
expect(result).toMatch(/allowfullscreen(?:="")?/);
});
});
31 changes: 30 additions & 1 deletion src/utils/sanitize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,42 @@ if (typeof window !== 'undefined' && !_hookRegistered) {
// new URL() throws for relative URLs — allow them (they stay on the same origin)
}
});

DOMPurify.addHook('afterSanitizeAttributes', (node) => {
if (node.tagName === 'IFRAME') {
const src = node.getAttribute('src');
if (src === null) return;
let allowed = false;
try {
const parsed = new URL(src);
// Only allow YouTube nocookie domain
if (
SAFE_URL_SCHEMES.includes(parsed.protocol) &&
parsed.hostname.endsWith('youtube-nocookie.com')
) {
allowed = true;
}
} catch {
// Invalid URL – not allowed
}
if (!allowed) {
node.removeAttribute('src');
node.removeAttribute('allowfullscreen');
return;
}
// Preserve allowfullscreen if present on allowed iframe
if (node.hasAttribute('allowfullscreen')) {
node.setAttribute('allowfullscreen', '');
}
}
});
}

export const sanitizeHtml = (html: string): string => {
if (typeof window === 'undefined') return html;
return DOMPurify.sanitize(html, {
ADD_TAGS: ['iframe'],
ADD_ATTR: ['allowfullscreen', 'frameborder', 'data-youtube-video'],
ADD_ATTR: ['frameborder', 'src', 'allowfullscreen'],
});
};

Expand Down
Loading