Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(open-knowledge): surface CSP-blocked requests in code-block preview (#1721)

Andrew Mikofalvy69a21df33dd4
diff --git a/.changeset/preview-csp-blocked-notice.md b/.changeset/preview-csp-blocked-notice.md
new file mode 100644
index 000000000..04fe8d3a2
--- /dev/null
+++ b/.changeset/preview-csp-blocked-notice.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge-app": patch
+---
+
+The `html preview` code block now surfaces a friendly, dismissible notice when its security policy blocks a network request, instead of silently rendering a broken embed. The preview iframe reports blocked requests (for example plain `http://` resources, or code that uses `eval`) back to the editor, which lists what was blocked and why. This is especially helpful inside the desktop preview, where the browser console is out of reach. The preview's Content Security Policy is unchanged.
diff --git a/packages/app/src/editor/components/PreviewBlockedNotice.dom.test.tsx b/packages/app/src/editor/components/PreviewBlockedNotice.dom.test.tsx
new file mode 100644
index 000000000..af8438947
--- /dev/null
+++ b/packages/app/src/editor/components/PreviewBlockedNotice.dom.test.tsx
@@ -0,0 +1,107 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { PreviewBlockedNotice } from './PreviewBlockedNotice';
+
+const DISMISS_NAME = 'Dismiss notice';
+
+describe('PreviewBlockedNotice', () => {
+ afterEach(() => {
+ cleanup();
+ });
+
+ test('announces itself as a status region', () => {
+ render(
+ <PreviewBlockedNotice
+ blocked={[{ directive: 'img-src', uri: 'http://insecure.example/tile.png' }]}
+ truncated={false}
+ onDismiss={() => {}}
+ />,
+ );
+ expect(screen.getByRole('status')).toBeDefined();
+ });
+
+ test('names the blocked request (uri + directive)', () => {
+ render(
+ <PreviewBlockedNotice
+ blocked={[{ directive: 'img-src', uri: 'http://insecure.example/tile.png' }]}
+ truncated={false}
+ onDismiss={() => {}}
+ />,
+ );
+ expect(screen.getByText('http://insecure.example/tile.png')).toBeDefined();
+ expect(screen.getByText('img-src')).toBeDefined();
+ });
+
+ test('renders (inline) when the blocked uri is empty', () => {
+ render(
+ <PreviewBlockedNotice
+ blocked={[{ directive: 'script-src', uri: '' }]}
+ truncated={false}
+ onDismiss={() => {}}
+ />,
+ );
+ expect(screen.getByText('(inline)')).toBeDefined();
+ });
+
+ test('singular heading for one blocked request', () => {
+ render(
+ <PreviewBlockedNotice
+ blocked={[{ directive: 'img-src', uri: 'http://a/1.png' }]}
+ truncated={false}
+ onDismiss={() => {}}
+ />,
+ );
+ expect(screen.getByText(/1 request blocked by the preview's security policy/)).toBeDefined();
+ });
+
+ test('plural heading for multiple blocked requests', () => {
+ render(
+ <PreviewBlockedNotice
+ blocked={[
+ { directive: 'img-src', uri: 'http://a/1.png' },
+ { directive: 'font-src', uri: 'http://a/f.woff' },
+ ]}
+ truncated={false}
+ onDismiss={() => {}}
+ />,
+ );
+ expect(screen.getByText(/2 requests blocked by the preview's security policy/)).toBeDefined();
+ });
+
+ test('a truncated report shows a floor count, not an exact total', () => {
+ render(
+ <PreviewBlockedNotice
+ blocked={[
+ { directive: 'img-src', uri: 'http://a/1.png' },
+ { directive: 'img-src', uri: 'http://a/2.png' },
+ ]}
+ truncated={true}
+ onDismiss={() => {}}
+ />,
+ );
+ expect(screen.getByText(/more than 2 requests were blocked/i)).toBeDefined();
+ });
+
+ test('flags display overflow when more were listed than shown', () => {
+ const blocked = Array.from({ length: 6 }, (_v, i) => ({
+ directive: 'img-src',
+ uri: `http://a/${i}.png`,
+ }));
+ render(<PreviewBlockedNotice blocked={blocked} truncated={false} onDismiss={() => {}} />);
+ expect(screen.getByText(/6 requests blocked by the preview's security policy/)).toBeDefined();
+ expect(screen.getByText(/more requests were blocked/i)).toBeDefined();
+ });
+
+ test('the dismiss control is wired to onDismiss', () => {
+ const onDismiss = mock(() => {});
+ render(
+ <PreviewBlockedNotice
+ blocked={[{ directive: 'img-src', uri: 'http://a/1.png' }]}
+ truncated={false}
+ onDismiss={onDismiss}
+ />,
+ );
+ fireEvent.click(screen.getByRole('button', { name: DISMISS_NAME }));
+ expect(onDismiss).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/app/src/editor/components/PreviewBlockedNotice.tsx b/packages/app/src/editor/components/PreviewBlockedNotice.tsx
new file mode 100644
index 000000000..72debfe5b
--- /dev/null
+++ b/packages/app/src/editor/components/PreviewBlockedNotice.tsx
@@ -0,0 +1,69 @@
+import { Plural, Trans, useLingui } from '@lingui/react/macro';
+import { ShieldAlert, X } from 'lucide-react';
+import type { PreviewBlockedRequest } from '../extensions/preview-iframe-header';
+
+export interface PreviewBlockedNoticeProps {
+ blocked: PreviewBlockedRequest[];
+ truncated: boolean;
+ onDismiss: () => void;
+}
+
+const VISIBLE_LIMIT = 4;
+
+export function PreviewBlockedNotice({ blocked, truncated, onDismiss }: PreviewBlockedNoticeProps) {
+ const { t } = useLingui();
+ const visible = blocked.slice(0, VISIBLE_LIMIT);
+ const undisplayed = !truncated && blocked.length > visible.length;
+
+ return (
+ <div
+ role="status"
+ className="ok-codeblock-preview-blocked mt-1.5 flex items-start gap-2 rounded-md border border-border bg-muted/40 px-3 py-2 text-xs text-muted-foreground"
+ contentEditable={false}
+ >
+ <ShieldAlert className="mt-0.5 size-3.5 shrink-0 text-amber-500" aria-hidden="true" />
+ <div className="min-w-0 flex-1">
+ <p className="font-medium text-foreground">
+ {truncated ? (
+ <Trans>
+ More than {blocked.length} requests were blocked by the preview's security policy
+ </Trans>
+ ) : (
+ <Plural
+ value={blocked.length}
+ one="# request blocked by the preview's security policy"
+ other="# requests blocked by the preview's security policy"
+ />
+ )}
+ </p>
+ <p className="mt-0.5">
+ <Trans>
+ The preview blocks resources that don't meet its security rules (for example plain
+ http:// URLs, or code that uses eval). The content above may render incompletely.
+ </Trans>
+ </p>
+ <ul className="mt-1 space-y-0.5">
+ {visible.map((b) => (
+ <li key={`${b.directive} ${b.uri}`} className="flex flex-wrap items-baseline gap-x-1.5">
+ <span className="break-all font-mono">{b.uri || t`(inline)`}</span>
+ <span className="text-muted-foreground/70">{b.directive}</span>
+ </li>
+ ))}
+ </ul>
+ {undisplayed ? (
+ <p className="mt-0.5 text-muted-foreground/70">
+ <Trans>More requests were blocked.</Trans>
+ </p>
+ ) : null}
+ </div>
+ <button
+ type="button"
+ className="-mr-1 -mt-0.5 shrink-0 rounded p-1.5 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ aria-label={t`Dismiss notice`}
+ onClick={onDismiss}
+ >
+ <X className="size-3.5" aria-hidden="true" />
+ </button>
+ </div>
+ );
+}
diff --git a/packages/app/src/editor/extensions/CodeBlockView.dom.test.tsx b/packages/app/src/editor/extensions/CodeBlockView.dom.test.tsx
index bb57b805b..37a3d5e0a 100644
--- a/packages/app/src/editor/extensions/CodeBlockView.dom.test.tsx
+++ b/packages/app/src/editor/extensions/CodeBlockView.dom.test.tsx
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, test } from 'bun:test';
import type { Config } from '@inkeep/open-knowledge-core';
-import { cleanup, fireEvent, render } from '@testing-library/react';
+import { act, cleanup, fireEvent, render } from '@testing-library/react';
import type { NodeViewProps } from '@tiptap/core';
import { ConfigContext, type ConfigContextValue } from '@/lib/config-context';
import { CodeBlockView } from './CodeBlockView';
@@ -95,3 +95,81 @@ describe('CodeBlockView edit-source modal language wiring', () => {
expect(sourceHost?.getAttribute('data-language')).toBe('html');
});
});
+
+describe('CodeBlockView CSP-violation notice wiring', () => {
+ afterEach(() => {
+ cleanup();
+ });
+
+ function renderPreview() {
+ const utils = render(
+ <ConfigContext value={makeConfigValue(null)}>
+ <CodeBlockView {...makeProps()} />
+ </ConfigContext>,
+ );
+ const iframe = utils.container.querySelector('iframe') as HTMLIFrameElement;
+ expect(iframe).toBeTruthy();
+ return { ...utils, iframe };
+ }
+
+ function cspReport(source: unknown) {
+ const evt = new Event('message');
+ Object.defineProperty(evt, 'source', { value: source, configurable: true });
+ Object.defineProperty(evt, 'data', {
+ value: {
+ okPreviewCspViolation: {
+ blocked: [{ directive: 'img-src', uri: 'http://insecure.example/tile.png' }],
+ truncated: false,
+ },
+ },
+ configurable: true,
+ });
+ return evt;
+ }
+
+ test('shows no notice before any CSP report arrives', () => {
+ const { container } = renderPreview();
+ expect(container.querySelector('[role="status"]')).toBeNull();
+ });
+
+ test('a CSP report from this iframe surfaces the blocked-request notice', () => {
+ const { iframe, container } = renderPreview();
+ act(() => {
+ window.dispatchEvent(cspReport(iframe.contentWindow));
+ });
+ const notice = container.querySelector('[role="status"]');
+ expect(notice).toBeTruthy();
+ expect(notice?.textContent).toContain('http://insecure.example/tile.png');
+ });
+
+ test('reloading the iframe clears the notice (re-evaluated policy)', () => {
+ const { iframe, container } = renderPreview();
+ act(() => {
+ window.dispatchEvent(cspReport(iframe.contentWindow));
+ });
+ expect(container.querySelector('[role="status"]')).toBeTruthy();
+ fireEvent.load(iframe);
+ expect(container.querySelector('[role="status"]')).toBeNull();
+ });
+
+ test('a report from a different window is ignored', () => {
+ const { container } = renderPreview();
+ act(() => {
+ window.dispatchEvent(cspReport(window));
+ });
+ expect(container.querySelector('[role="status"]')).toBeNull();
+ });
+
+ test('dismissing the notice removes it', () => {
+ const { iframe, container } = renderPreview();
+ act(() => {
+ window.dispatchEvent(cspReport(iframe.contentWindow));
+ });
+ const dismiss = container.querySelector(
+ 'button[aria-label="Dismiss notice"]',
+ ) as HTMLButtonElement | null;
+ expect(dismiss).toBeTruthy();
+ fireEvent.click(dismiss as HTMLButtonElement);
+ expect(container.querySelector('[role="status"]')).toBeNull();
+ });
+});
diff --git a/packages/app/src/editor/extensions/CodeBlockView.tsx b/packages/app/src/editor/extensions/CodeBlockView.tsx
index 1ca31c365..5877e8bd2 100644
--- a/packages/app/src/editor/extensions/CodeBlockView.tsx
+++ b/packages/app/src/editor/extensions/CodeBlockView.tsx
@@ -17,6 +17,7 @@ import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover
import { cn } from '@/lib/utils';
import { OPT_OUT_ATTR } from '../clipboard/index.ts';
import { CodePreviewEditModal } from '../components/CodePreviewEditModal';
+import { PreviewBlockedNotice } from '../components/PreviewBlockedNotice';
import { ResizeHandles } from '../components/ResizeHandles.tsx';
import { CODE_BLOCK_LANGUAGES, normalizeCodeLanguage } from './code-block-languages';
import {
@@ -34,7 +35,9 @@ import {
import {
buildPreviewIframeHeader,
buildPreviewThemeMessage,
+ type PreviewBlockedRequest,
type PreviewTheme,
+ parsePreviewCspViolationMessage,
parsePreviewHeightMessage,
} from './preview-iframe-header';
@@ -77,6 +80,10 @@ export function CodeBlockView({ node, updateAttributes, editor, getPos, selected
const previewWrapperRef = useRef<HTMLDivElement | null>(null);
const previewFrameRef = useRef<HTMLIFrameElement | null>(null);
const [autoHeight, setAutoHeight] = useState<number | null>(null);
+ const [blockedRequests, setBlockedRequests] = useState<{
+ blocked: PreviewBlockedRequest[];
+ truncated: boolean;
+ } | null>(null);
const { resolvedTheme } = useTheme();
const appTheme: PreviewTheme =
resolvedTheme === 'dark' || resolvedTheme === 'light' ? resolvedTheme : readAppTheme();
@@ -124,8 +131,14 @@ export function CodeBlockView({ node, updateAttributes, editor, getPos, selected
function onMessage(e: MessageEvent) {
if (e.source !== previewFrameRef.current?.contentWindow) return;
const reported = parsePreviewHeightMessage(e.data);
- if (reported === null) return;
- setAutoHeight((prev) => (prev !== null && Math.abs(prev - reported) <= 2 ? prev : reported));
+ if (reported !== null) {
+ setAutoHeight((prev) =>
+ prev !== null && Math.abs(prev - reported) <= 2 ? prev : reported,
+ );
+ return;
+ }
+ const violation = parsePreviewCspViolationMessage(e.data);
+ if (violation !== null) setBlockedRequests(violation);
}
window.addEventListener('message', onMessage);
return () => window.removeEventListener('message', onMessage);
@@ -223,6 +236,7 @@ export function CodeBlockView({ node, updateAttributes, editor, getPos, selected
srcDoc={buildPreviewIframeHeader(bakedTheme) + node.textContent}
className="ok-codeblock-preview-frame"
onLoad={() => {
+ setBlockedRequests(null);
previewFrameRef.current?.contentWindow?.postMessage(
buildPreviewThemeMessage(appTheme),
'*',
@@ -248,6 +262,14 @@ export function CodeBlockView({ node, updateAttributes, editor, getPos, selected
</div>
) : null}
+ {previewActive && blockedRequests ? (
+ <PreviewBlockedNotice
+ blocked={blockedRequests.blocked}
+ truncated={blockedRequests.truncated}
+ onDismiss={() => setBlockedRequests(null)}
+ />
+ ) : null}
+
{/* Title strip — rendered above the source whenever the fence carries
`title="…"` in its info-string (PRD-6819). Display-only here; the
editable surface is the title input inside the settings popover
diff --git a/packages/app/src/editor/extensions/preview-iframe-csp-violation.test.ts b/packages/app/src/editor/extensions/preview-iframe-csp-violation.test.ts
new file mode 100644
index 000000000..c2faa4ed7
--- /dev/null
+++ b/packages/app/src/editor/extensions/preview-iframe-csp-violation.test.ts
@@ -0,0 +1,191 @@
+import { describe, expect, mock, test } from 'bun:test';
+import {
+ buildPreviewIframeHeader,
+ PREVIEW_CSP_VIOLATION_SAMPLE_CAP,
+ parsePreviewCspViolationMessage,
+} from './preview-iframe-header';
+
+function evalBootstrap() {
+ const header = buildPreviewIframeHeader('light');
+ const script = header.match(/<script>([\s\S]*?)<\/script>/)?.[1] ?? '';
+ const listeners: Record<string, Array<(e: unknown) => void>> = {};
+ const addEventListener = (type: string, fn: (e: unknown) => void) => {
+ if (!listeners[type]) listeners[type] = [];
+ listeners[type].push(fn);
+ };
+ const postMessage = mock((_msg: unknown, _origin?: string) => {});
+ const documentStub = {
+ documentElement: { classList: { add() {}, remove() {} } },
+ readyState: 'complete',
+ addEventListener() {},
+ body: {},
+ };
+ new Function(
+ 'document',
+ 'parent',
+ 'window',
+ 'addEventListener',
+ 'setTimeout',
+ 'clearTimeout',
+ 'requestAnimationFrame',
+ 'cancelAnimationFrame',
+ 'getComputedStyle',
+ script,
+ )(
+ documentStub,
+ { postMessage },
+ {},
+ addEventListener,
+ setTimeout,
+ clearTimeout,
+ () => 0,
+ () => {},
+ () => ({ marginBottom: '0' }),
+ );
+ const dispatch = (e: {
+ violatedDirective?: string;
+ effectiveDirective?: string;
+ blockedURI?: string;
+ }) => {
+ for (const fn of listeners.securitypolicyviolation ?? []) fn(e);
+ };
+ return { dispatch, postMessage, listeners };
+}
+
+function latestCspReport(postMessage: ReturnType<typeof mock>) {
+ const calls = postMessage.mock.calls.filter(
+ (c) => parsePreviewCspViolationMessage(c[0]) !== null,
+ );
+ return calls.length > 0 ? parsePreviewCspViolationMessage(calls.at(-1)?.[0]) : null;
+}
+
+const DEBOUNCE_WAIT = 350;
+
+describe('buildPreviewIframeHeader — CSP-violation reporting (wiring)', () => {
+ const header = buildPreviewIframeHeader('light');
+
+ test('registers a securitypolicyviolation listener in the bootstrap', () => {
+ expect(header).toContain('securitypolicyviolation');
+ });
+
+ test('reports blocked requests under the okPreviewCspViolation key', () => {
+ expect(header).toContain('okPreviewCspViolation');
+ });
+
+ test('reads the blocked URI and the violated directive off the event', () => {
+ expect(header).toContain('blockedURI');
+ expect(header).toMatch(/effectiveDirective|violatedDirective/);
+ });
+});
+
+describe('buildPreviewIframeHeader — CSP-violation reporting (behavior)', () => {
+ test('a blocked request is posted to the parent with directive + uri', async () => {
+ const { dispatch, postMessage } = evalBootstrap();
+ dispatch({ violatedDirective: 'img-src', blockedURI: 'http://insecure.example/tile.png' });
+ await new Promise((r) => setTimeout(r, DEBOUNCE_WAIT));
+
+ const report = latestCspReport(postMessage);
+ expect(report).not.toBeNull();
+ expect(report?.blocked).toEqual([
+ { directive: 'img-src', uri: 'http://insecure.example/tile.png' },
+ ]);
+ expect(report?.truncated).toBe(false);
+ });
+
+ test('coalesces a burst of violations into a single deduped report', async () => {
+ const { dispatch, postMessage } = evalBootstrap();
+ dispatch({ violatedDirective: 'img-src', blockedURI: 'http://a/1.png' });
+ dispatch({ violatedDirective: 'img-src', blockedURI: 'http://a/1.png' });
+ dispatch({ violatedDirective: 'img-src', blockedURI: 'http://a/1.png' });
+ dispatch({ effectiveDirective: 'font-src', blockedURI: 'http://a/font.woff' });
+ await new Promise((r) => setTimeout(r, DEBOUNCE_WAIT));
+
+ const cspMessages = postMessage.mock.calls.filter(
+ (c) => parsePreviewCspViolationMessage(c[0]) !== null,
+ );
+ expect(cspMessages.length).toBe(1);
+
+ const report = latestCspReport(postMessage);
+ expect(report?.blocked).toEqual([
+ { directive: 'img-src', uri: 'http://a/1.png' },
+ { directive: 'font-src', uri: 'http://a/font.woff' },
+ ]);
+ });
+
+ test('bounds the report and flags truncation past the sample cap', async () => {
+ const { dispatch, postMessage } = evalBootstrap();
+ const n = PREVIEW_CSP_VIOLATION_SAMPLE_CAP + 5;
+ for (let i = 0; i < n; i++) {
+ dispatch({ violatedDirective: 'img-src', blockedURI: `http://a/${i}.png` });
+ }
+ await new Promise((r) => setTimeout(r, DEBOUNCE_WAIT));
+
+ const report = latestCspReport(postMessage);
+ expect(report?.blocked.length).toBe(PREVIEW_CSP_VIOLATION_SAMPLE_CAP);
+ expect(report?.truncated).toBe(true);
+ });
+
+ test('prefers effectiveDirective over the deprecated violatedDirective', async () => {
+ const { dispatch, postMessage } = evalBootstrap();
+ dispatch({
+ effectiveDirective: 'img-src',
+ violatedDirective: 'default-src',
+ blockedURI: 'http://a/x.png',
+ });
+ await new Promise((r) => setTimeout(r, DEBOUNCE_WAIT));
+ expect(latestCspReport(postMessage)?.blocked[0]?.directive).toBe('img-src');
+ });
+});
+
+describe('parsePreviewCspViolationMessage', () => {
+ test('reads a well-formed report', () => {
+ const msg = {
+ okPreviewCspViolation: {
+ blocked: [{ directive: 'img-src', uri: 'http://x/y.png' }],
+ truncated: false,
+ },
+ };
+ expect(parsePreviewCspViolationMessage(msg)).toEqual({
+ blocked: [{ directive: 'img-src', uri: 'http://x/y.png' }],
+ truncated: false,
+ });
+ });
+
+ test('passes the truncated flag through', () => {
+ const msg = {
+ okPreviewCspViolation: {
+ blocked: [{ directive: 'img-src', uri: 'http://x' }],
+ truncated: true,
+ },
+ };
+ expect(parsePreviewCspViolationMessage(msg)?.truncated).toBe(true);
+ });
+
+ test('filters entries that are not {directive,uri} string pairs', () => {
+ const msg = {
+ okPreviewCspViolation: {
+ blocked: [
+ { directive: 'img-src', uri: 'http://ok' },
+ { directive: 42, uri: 'http://bad' },
+ { directive: 'font-src' },
+ null,
+ 'nope',
+ ],
+ truncated: false,
+ },
+ };
+ expect(parsePreviewCspViolationMessage(msg)?.blocked).toEqual([
+ { directive: 'img-src', uri: 'http://ok' },
+ ]);
+ });
+
+ test('rejects non-violation payloads', () => {
+ expect(parsePreviewCspViolationMessage(null)).toBeNull();
+ expect(parsePreviewCspViolationMessage('blocked')).toBeNull();
+ expect(parsePreviewCspViolationMessage({ okPreviewHeight: 400 })).toBeNull();
+ expect(parsePreviewCspViolationMessage({ okPreviewCspViolation: null })).toBeNull();
+ expect(parsePreviewCspViolationMessage({ okPreviewCspViolation: {} })).toBeNull();
+ expect(parsePreviewCspViolationMessage({ okPreviewCspViolation: { blocked: 'x' } })).toBeNull();
+ expect(parsePreviewCspViolationMessage({ okPreviewCspViolation: { blocked: [] } })).toBeNull();
+ });
+});
diff --git a/packages/app/src/editor/extensions/preview-iframe-header.ts b/packages/app/src/editor/extensions/preview-iframe-header.ts
index 80d9a5b37..9814c3f73 100644
--- a/packages/app/src/editor/extensions/preview-iframe-header.ts
+++ b/packages/app/src/editor/extensions/preview-iframe-header.ts
@@ -20,6 +20,38 @@ export function parsePreviewHeightMessage(data: unknown): number | null {
return typeof h === 'number' && Number.isFinite(h) && h > 0 ? Math.ceil(h) : null;
}
+const PREVIEW_CSP_VIOLATION_MESSAGE_KEY = 'okPreviewCspViolation';
+
+/** One CSP-blocked request: the violated directive and the (browser-reported,
+ * possibly origin-truncated or `inline`/`eval`) URI it blocked. */
+export interface PreviewBlockedRequest {
+ directive: string;
+ uri: string;
+}
+
+export const PREVIEW_CSP_VIOLATION_SAMPLE_CAP = 20;
+
+export function parsePreviewCspViolationMessage(
+ data: unknown,
+): { blocked: PreviewBlockedRequest[]; truncated: boolean } | null {
+ if (typeof data !== 'object' || data === null) return null;
+ const payload = (data as Record<string, unknown>)[PREVIEW_CSP_VIOLATION_MESSAGE_KEY];
+ if (typeof payload !== 'object' || payload === null) return null;
+ const rawBlocked = (payload as Record<string, unknown>).blocked;
+ if (!Array.isArray(rawBlocked)) return null;
+ const blocked: PreviewBlockedRequest[] = [];
+ for (const item of rawBlocked) {
+ if (typeof item !== 'object' || item === null) continue;
+ const directive = (item as Record<string, unknown>).directive;
+ const uri = (item as Record<string, unknown>).uri;
+ if (typeof directive === 'string' && typeof uri === 'string') {
+ blocked.push({ directive, uri });
+ }
+ }
+ if (blocked.length === 0) return null;
+ return { blocked, truncated: (payload as Record<string, unknown>).truncated === true };
+}
+
const PREVIEW_SCROLLBAR_STYLE = `<style>
html, body { scrollbar-width: thin; scrollbar-color: rgba(115,115,115,0.4) transparent; }
html::-webkit-scrollbar, body::-webkit-scrollbar,
@@ -69,6 +101,17 @@ function previewBootstrapScript(theme: PreviewTheme): string {
`}` +
`if(document.readyState==='loading'){document.addEventListener('DOMContentLoaded',init);}` +
`else{init();}` +
+ `var cspSeen=new Set();var cspList=[];var cspTrunc=false;var cspTimer;` +
+ `function cspFlush(){parent.postMessage({${PREVIEW_CSP_VIOLATION_MESSAGE_KEY}:{blocked:cspList.slice(),truncated:cspTrunc}},'*');}` +
+ `addEventListener('securitypolicyviolation',function(e){` +
+ `if(cspTrunc)return;` +
+ `var dir=(e&&(e.effectiveDirective||e.violatedDirective))||'';` +
+ `var uri=(e&&e.blockedURI)||'';` +
+ `var k=dir+' '+uri;` +
+ `if(cspSeen.has(k))return;cspSeen.add(k);` +
+ `if(cspList.length<${PREVIEW_CSP_VIOLATION_SAMPLE_CAP}){cspList.push({directive:dir,uri:uri});}else{cspTrunc=true;}` +
+ `if(cspTimer){clearTimeout(cspTimer);}cspTimer=setTimeout(cspFlush,250);` +
+ `});` +
`})();</script>`
);
}
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index fc4255b5b..4feac0cc7 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -797,6 +797,16 @@
"QcpeeE": ["Navigate to ", ["docName"]],
"QqBQu1": ["Label <0>(visible link text)</0>"],
"QyioBP": ["Move up"],
+ "R0cyYB": [
+ [
+ "0",
+ "plural",
+ {
+ "one": ["#", " request blocked by the preview's security policy"],
+ "other": ["#", " requests blocked by the preview's security policy"]
+ }
+ ]
+ ],
"R0jJzV": ["Paste URL, owner/repo, or search your repos"],
"R3y75Z": ["Edit source"],
"R4RGjs": [
@@ -1068,6 +1078,7 @@
"_TDESN": ["Network error - ", ["kind"], " \"", ["createdPath"], "\" still exists on disk"],
"_TF8ep": ["Failed to render PDF"],
"_VRtd7": ["Couldn't send the selection — please try again."],
+ "_W-elG": ["(inline)"],
"_gkGSK": ["deleted template"],
"_qD6mn": ["Pick the folder where you've cloned it."],
"_rP3HI": [["minutes"], "m ago"],
@@ -1170,6 +1181,7 @@
"dURmlQ": ["\"frontmatter\" is a reserved property name"],
"dbhUX1": ["Hide this file"],
"dbtjJh": ["(opens in new tab)"],
+ "djc1l9": ["More than ", ["0"], " requests were blocked by the preview's security policy"],
"dprWmL": ["Anchor in this page"],
"dr1vFs": ["Replace all matches"],
"dw_dUJ": ["Failed to duplicate path"],
@@ -1483,6 +1495,7 @@
],
"oBXkm2": ["Delete code block"],
"oJl7eO": ["Unknown component: ", ["componentName"], " — source editable below"],
+ "oKBnk5": ["More requests were blocked."],
"oS1YpJ": ["Open the Project Navigator."],
"oXKEsy": ["Delete an adjacent wiki-link or tag chip."],
"ogAuyr": ["Back to document view"],
@@ -1755,6 +1768,9 @@
"y46m5r": ["The desktop app isn't responding. Refresh and try again."],
"y5FUYi": ["Suggestion menu open"],
"yCX4jp": [" Your selection could not be restored."],
+ "yEJ-sl": [
+ "The preview blocks resources that don't meet its security rules (for example plain http:// URLs, or code that uses eval). The content above may render incompletely."
+ ],
"yHikCO": ["Open CodeMirror's go-to-line prompt."],
"yKu_3Y": ["Restore"],
"yLq4w4": ["Separator"],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index 045864772..41faf8dbb 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -50,6 +50,10 @@ msgstr "\"frontmatter\" is a reserved property name"
msgid "(a worktree of {0})"
msgstr "(a worktree of {0})"
+#: src/editor/components/PreviewBlockedNotice.tsx
+msgid "(inline)"
+msgstr "(inline)"
+
#: src/components/CommandPalette.tsx
msgid "(missing)"
msgstr "(missing)"
@@ -85,6 +89,11 @@ msgstr "(user-level only)"
msgid "{0, plural, one {# doc} other {# docs}}"
msgstr "{0, plural, one {# doc} other {# docs}}"
+#. placeholder {0}: blocked.length
+#: src/editor/components/PreviewBlockedNotice.tsx
+msgid "{0, plural, one {# request blocked by the preview's security policy} other {# requests blocked by the preview's security policy}}"
+msgstr "{0, plural, one {# request blocked by the preview's security policy} other {# requests blocked by the preview's security policy}}"
+
#. placeholder {0}: item.count
#: src/editor/tag-suggestion/TagSuggestionMenu.tsx
msgid "{0, plural, one {# use} other {# uses}}"
@@ -1755,6 +1764,7 @@ msgid "Dismiss"
msgstr "Dismiss"
#: src/components/UpdateNotices.tsx
+#: src/editor/components/PreviewBlockedNotice.tsx
msgid "Dismiss notice"
msgstr "Dismiss notice"
@@ -3113,6 +3123,15 @@ msgstr "Modify the link target, anchor, and display label."
msgid "More"
msgstr "More"
+#: src/editor/components/PreviewBlockedNotice.tsx
+msgid "More requests were blocked."
+msgstr "More requests were blocked."
+
+#. placeholder {0}: blocked.length
+#: src/editor/components/PreviewBlockedNotice.tsx
+msgid "More than {0} requests were blocked by the preview's security policy"
+msgstr "More than {0} requests were blocked by the preview's security policy"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Move between table cells"
msgstr "Move between table cells"
@@ -5329,6 +5348,10 @@ msgstr "The folders and templates are in place; there's nothing left to scaffold
msgid "The formula <0>c = √(a² + b²)</0> renders inline."
msgstr "The formula <0>c = √(a² + b²)</0> renders inline."
+#: src/editor/components/PreviewBlockedNotice.tsx
+msgid "The preview blocks resources that don't meet its security rules (for example plain http:// URLs, or code that uses eval). The content above may render incompletely."
+msgstr "The preview blocks resources that don't meet its security rules (for example plain http:// URLs, or code that uses eval). The content above may render incompletely."
+
#: src/components/PropertyPanel.tsx
msgid "The properties block at the top of this doc has a formatting error. Switch to source mode to fix it."
msgstr "The properties block at the top of this doc has a formatting error. Switch to source mode to fix it."
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index 9fb928699..87b1a965e 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -797,6 +797,16 @@
"QcpeeE": ["Ńàvĩĝàţē ţō ", ["docName"]],
"QqBQu1": ["Ĺàƀēĺ <0>(vĩśĩƀĺē ĺĩńķ ţēxţ)</0>"],
"QyioBP": ["Ḿōvē ũƥ"],
+ "R0cyYB": [
+ [
+ "0",
+ "plural",
+ {
+ "one": ["#", " ŕēǫũēśţ ƀĺōćķēď ƀŷ ţĥē ƥŕēvĩēŵ'ś śēćũŕĩţŷ ƥōĺĩćŷ"],
+ "other": ["#", " ŕēǫũēśţś ƀĺōćķēď ƀŷ ţĥē ƥŕēvĩēŵ'ś śēćũŕĩţŷ ƥōĺĩćŷ"]
+ }
+ ]
+ ],
"R0jJzV": ["Ƥàśţē ŨŔĹ, ōŵńēŕ/ŕēƥō, ōŕ śēàŕćĥ ŷōũŕ ŕēƥōś"],
"R3y75Z": ["Ēďĩţ śōũŕćē"],
"R4RGjs": [
@@ -1068,6 +1078,7 @@
"_TDESN": ["Ńēţŵōŕķ ēŕŕōŕ - ", ["kind"], " \"", ["createdPath"], "\" śţĩĺĺ ēxĩśţś ōń ďĩśķ"],
"_TF8ep": ["Ƒàĩĺēď ţō ŕēńďēŕ ƤĎƑ"],
"_VRtd7": ["Ćōũĺďń'ţ śēńď ţĥē śēĺēćţĩōń — ƥĺēàśē ţŕŷ àĝàĩń."],
+ "_W-elG": ["(ĩńĺĩńē)"],
"_gkGSK": ["ďēĺēţēď ţēḿƥĺàţē"],
"_qD6mn": ["Ƥĩćķ ţĥē ƒōĺďēŕ ŵĥēŕē ŷōũ'vē ćĺōńēď ĩţ."],
"_rP3HI": [["minutes"], "ḿ àĝō"],
@@ -1170,6 +1181,7 @@
"dURmlQ": ["\"ƒŕōńţḿàţţēŕ\" ĩś à ŕēśēŕvēď ƥŕōƥēŕţŷ ńàḿē"],
"dbhUX1": ["Ĥĩďē ţĥĩś ƒĩĺē"],
"dbtjJh": ["(ōƥēńś ĩń ńēŵ ţàƀ)"],
+ "djc1l9": ["Ḿōŕē ţĥàń ", ["0"], " ŕēǫũēśţś ŵēŕē ƀĺōćķēď ƀŷ ţĥē ƥŕēvĩēŵ'ś śēćũŕĩţŷ ƥōĺĩćŷ"],
"dprWmL": ["Àńćĥōŕ ĩń ţĥĩś ƥàĝē"],
"dr1vFs": ["Ŕēƥĺàćē àĺĺ ḿàţćĥēś"],
"dw_dUJ": ["Ƒàĩĺēď ţō ďũƥĺĩćàţē ƥàţĥ"],
@@ -1483,6 +1495,7 @@
],
"oBXkm2": ["Ďēĺēţē ćōďē ƀĺōćķ"],
"oJl7eO": ["Ũńķńōŵń ćōḿƥōńēńţ: ", ["componentName"], " — śōũŕćē ēďĩţàƀĺē ƀēĺōŵ"],
+ "oKBnk5": ["Ḿōŕē ŕēǫũēśţś ŵēŕē ƀĺōćķēď."],
"oS1YpJ": ["Ōƥēń ţĥē ƤŕōĴēćţ Ńàvĩĝàţōŕ."],
"oXKEsy": ["Ďēĺēţē àń àďĴàćēńţ ŵĩķĩ-ĺĩńķ ōŕ ţàĝ ćĥĩƥ."],
"ogAuyr": ["ßàćķ ţō ďōćũḿēńţ vĩēŵ"],
@@ -1755,6 +1768,9 @@
"y46m5r": ["Ţĥē ďēśķţōƥ àƥƥ ĩśń'ţ ŕēśƥōńďĩńĝ. Ŕēƒŕēśĥ àńď ţŕŷ àĝàĩń."],
"y5FUYi": ["Śũĝĝēśţĩōń ḿēńũ ōƥēń"],
"yCX4jp": [" Ŷōũŕ śēĺēćţĩōń ćōũĺď ńōţ ƀē ŕēśţōŕēď."],
+ "yEJ-sl": [
+ "Ţĥē ƥŕēvĩēŵ ƀĺōćķś ŕēśōũŕćēś ţĥàţ ďōń'ţ ḿēēţ ĩţś śēćũŕĩţŷ ŕũĺēś (ƒōŕ ēxàḿƥĺē ƥĺàĩń ĥţţƥ:// ŨŔĹś, ōŕ ćōďē ţĥàţ ũśēś ēvàĺ). Ţĥē ćōńţēńţ àƀōvē ḿàŷ ŕēńďēŕ ĩńćōḿƥĺēţēĺŷ."
+ ],
"yHikCO": ["Ōƥēń ĆōďēḾĩŕŕōŕ'ś ĝō-ţō-ĺĩńē ƥŕōḿƥţ."],
"yKu_3Y": ["Ŕēśţōŕē"],
"yLq4w4": ["Śēƥàŕàţōŕ"],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index 2a7ed325f..78fce2596 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -50,6 +50,10 @@ msgstr ""
msgid "(a worktree of {0})"
msgstr ""
+#: src/editor/components/PreviewBlockedNotice.tsx
+msgid "(inline)"
+msgstr ""
+
#: src/components/CommandPalette.tsx
msgid "(missing)"
msgstr ""
@@ -85,6 +89,11 @@ msgstr ""
msgid "{0, plural, one {# doc} other {# docs}}"
msgstr ""
+#. placeholder {0}: blocked.length
+#: src/editor/components/PreviewBlockedNotice.tsx
+msgid "{0, plural, one {# request blocked by the preview's security policy} other {# requests blocked by the preview's security policy}}"
+msgstr ""
+
#. placeholder {0}: item.count
#: src/editor/tag-suggestion/TagSuggestionMenu.tsx
msgid "{0, plural, one {# use} other {# uses}}"
@@ -1750,6 +1759,7 @@ msgid "Dismiss"
msgstr ""
#: src/components/UpdateNotices.tsx
+#: src/editor/components/PreviewBlockedNotice.tsx
msgid "Dismiss notice"
msgstr ""
@@ -3108,6 +3118,15 @@ msgstr ""
msgid "More"
msgstr ""
+#: src/editor/components/PreviewBlockedNotice.tsx
+msgid "More requests were blocked."
+msgstr ""
+
+#. placeholder {0}: blocked.length
+#: src/editor/components/PreviewBlockedNotice.tsx
+msgid "More than {0} requests were blocked by the preview's security policy"
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Move between table cells"
msgstr ""
@@ -5324,6 +5343,10 @@ msgstr ""
msgid "The formula <0>c = √(a² + b²)</0> renders inline."
msgstr ""
+#: src/editor/components/PreviewBlockedNotice.tsx
+msgid "The preview blocks resources that don't meet its security rules (for example plain http:// URLs, or code that uses eval). The content above may render incompletely."
+msgstr ""
+
#: src/components/PropertyPanel.tsx
msgid "The properties block at the top of this doc has a formatting error. Switch to source mode to fix it."
msgstr ""