Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(canvas): allow declared origins to serve resources (#89943)

Peter Kirkham98b156ebaff3
diff --git a/products/canvas/backend/contract.py b/products/canvas/backend/contract.py
index 6b187fe6ebec..a4ee185710a9 100644
--- a/products/canvas/backend/contract.py
+++ b/products/canvas/backend/contract.py
@@ -28,7 +28,7 @@ MAX_COMPONENT_HEIGHT = 40
# other character is rejected because urlsplit keeps CSP delimiters such as ";"
# and spaces inside the netloc, so an origin like "example.com; img-src evil.net"
# would otherwise reach the hostname unchanged and inject an extra directive when
-# spliced into the artifact's connect-src.
+# spliced into the artifact's resource directives.
_DNS_NAME_LABEL = r"(?!-)[a-z0-9-]{1,63}(?<!-)"
_DNS_NAME_RE = re.compile(rf"{_DNS_NAME_LABEL}(?:\.{_DNS_NAME_LABEL})*\.?")
@@ -50,7 +50,7 @@ def allowed_import_specifiers() -> frozenset[str]:
def _is_public_network_host(hostname: str) -> bool:
"""Reject hosts that point at the viewer's machine or private network.
- Declared origins go straight into the viewer's connect-src, so a loopback or
+ Declared origins go straight into the viewer's CSP, so a loopback or
private origin would let a published canvas probe services on the viewer's
machine or LAN. Literal IPs must be globally routable; names must be dotted
public DNS names outside the reserved local suffixes. Rebinding a public
@@ -107,8 +107,20 @@ def canonical_network_origin(origin: Any) -> str | None:
def artifact_csp(network_origins: list[str] | None = None) -> str:
csp = platform_contract()["csp"]
safe_origins = [canonical for origin in network_origins or [] if (canonical := canonical_network_origin(origin))]
- connect_sources = " ".join(safe_origins) or "'none'"
- return csp.replace("connect-src 'none'", f"connect-src {connect_sources}")
+ if not safe_origins:
+ return csp
+ sources = " ".join(safe_origins)
+ replacements = {
+ "connect-src 'none'": f"connect-src {sources}",
+ "style-src 'self' 'unsafe-inline'": f"style-src 'self' 'unsafe-inline' {sources}",
+ "img-src 'self' data: blob:": f"img-src 'self' data: blob: {sources}",
+ "font-src 'self' data:": f"font-src 'self' data: {sources}",
+ "media-src 'self' data: blob:": f"media-src 'self' data: blob: {sources}",
+ "frame-src 'none'": f"frame-src {sources}",
+ }
+ for directive, replacement in replacements.items():
+ csp = csp.replace(directive, replacement)
+ return csp
def contract_limits() -> dict[str, int]:
diff --git a/products/canvas/backend/source.py b/products/canvas/backend/source.py
index 0d84f7387eee..de9435eb49a1 100644
--- a/products/canvas/backend/source.py
+++ b/products/canvas/backend/source.py
@@ -13,6 +13,7 @@ can be exercised without a database and shared with the build worker.
import re
import json
from typing import Any
+from urllib.parse import urlsplit
import jsonschema
@@ -102,15 +103,32 @@ _NETWORK_PATTERNS: list[tuple[re.Pattern[str], str, str]] = [
(
re.compile(r"\bfetch\s*\("),
"network_fetch",
- "fetch() is blocked by the canvas sandbox — use the `ph` data bridge instead",
+ "fetch() requires every destination in capabilities.network.origins — prefer the `ph` data bridge for PostHog data",
),
(
re.compile(r"\bXMLHttpRequest\b"),
"network_xhr",
- "XMLHttpRequest is blocked by the canvas sandbox — use the `ph` data bridge instead",
+ "XMLHttpRequest requires every destination in capabilities.network.origins — prefer the `ph` data bridge for PostHog data",
),
]
+_FETCH_LITERAL_URL_RE = re.compile(r"\bfetch\s*\(\s*([\"'`])(https://[^\"'`]+)\1")
+# `object` and `embed` are left out on purpose: the artifact CSP keeps
+# `object-src 'none'`, so a declared origin cannot make them load. Matching
+# them would block publish with a remedy that does nothing.
+_RESOURCE_TAG_RE = re.compile(
+ r"<(?:img|audio|video|source|track|iframe)\b[^>]*?"
+ r"\b(?:src|poster)\s*=\s*(?:\{\s*)?([\"'`])(https://[^\"'`]+)\1",
+ re.IGNORECASE,
+)
+_SRCSET_TAG_RE = re.compile(r"<(?:img|source)\b[^>]*?\bsrcset\s*=\s*(?:\{\s*)?([\"'`])([^\"'`]+)\1", re.IGNORECASE)
+_SRCSET_URL_RE = re.compile(r"https://[^\s,]+")
+_LINK_TAG_RE = re.compile(r"<link\b[^>]*>", re.IGNORECASE)
+_REL_STYLESHEET_RE = re.compile(r"\brel\s*=\s*([\"'])stylesheet\1", re.IGNORECASE)
+_HREF_LITERAL_URL_RE = re.compile(r"\bhref\s*=\s*(?:\{\s*)?([\"'])(https://[^\"']+)\1", re.IGNORECASE)
+_CSS_URL_RE = re.compile(r"\burl\(\s*([\"']?)(https://[^\"')\s]+)\1\s*\)", re.IGNORECASE)
+_CSS_IMPORT_RE = re.compile(r"@import\s+([\"'])(https://[^\"']+)\1", re.IGNORECASE)
+
# `ph` bridge calls checked against the project's declared capabilities. The
# host enforces capabilities at runtime, so an undeclared call would build fine
# and then die in view mode — validating here turns that into a diagnostic the
@@ -226,6 +244,58 @@ def _validate_network_origin(origin: Any) -> str | None:
return None
+def _network_origin_from_url(url: str) -> str | None:
+ try:
+ parsed = urlsplit(url)
+ port = parsed.port
+ except ValueError:
+ return None
+ if parsed.scheme != "https" or not parsed.hostname:
+ return None
+ hostname = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
+ candidate = f"https://{hostname}" + (f":{port}" if port is not None else "")
+ return canonical_network_origin(candidate)
+
+
+def _literal_external_urls(content: str) -> list[tuple[str, int]]:
+ urls: list[tuple[str, int]] = []
+ for pattern in (_FETCH_LITERAL_URL_RE, _RESOURCE_TAG_RE, _CSS_URL_RE, _CSS_IMPORT_RE):
+ urls.extend((match.group(2), match.start(2)) for match in pattern.finditer(content))
+ for srcset in _SRCSET_TAG_RE.finditer(content):
+ urls.extend(
+ (match.group(0), srcset.start(2) + match.start()) for match in _SRCSET_URL_RE.finditer(srcset.group(2))
+ )
+ for tag in _LINK_TAG_RE.finditer(content):
+ if _REL_STYLESHEET_RE.search(tag.group(0)) is None:
+ continue
+ href = _HREF_LITERAL_URL_RE.search(tag.group(0))
+ if href is not None:
+ urls.append((href.group(2), tag.start() + href.start(2)))
+ return urls
+
+
+def _validate_network_capabilities(path: str, content: str, declared_origins: set[str]) -> list[dict[str, Any]]:
+ diagnostics: list[dict[str, Any]] = []
+ seen: set[str] = set()
+ for url, position in _literal_external_urls(content):
+ origin = _network_origin_from_url(url)
+ if origin is None or origin in seen:
+ continue
+ seen.add(origin)
+ if origin not in declared_origins:
+ diagnostics.append(
+ diagnostic(
+ "error",
+ "capability_missing_network_origin",
+ f'External resource requires "{origin}" in capabilities.network.origins — '
+ "the canvas sandbox blocks undeclared origins at runtime",
+ path=path,
+ line=_line_of(content, position),
+ )
+ )
+ return diagnostics
+
+
def _validate_code_file(path: str, code: str) -> list[dict[str, Any]]:
diagnostics: list[dict[str, Any]] = []
@@ -570,7 +640,8 @@ def validate_source_project(project: dict[str, Any], *, kind: str = "freeform")
assets = project.get("assets") or {}
if project.get("entryHtml") not in files:
diagnostics.append(diagnostic("error", "missing_entry", "entryHtml must name a file present in files"))
- network_origins = ((project.get("capabilities") or {}).get("network") or {}).get("origins") or []
+ capabilities = project.get("capabilities") or {}
+ network_origins = (capabilities.get("network") or {}).get("origins") or []
for origin in network_origins:
problem = _validate_network_origin(origin)
if problem is not None:
@@ -661,11 +732,15 @@ def validate_source_project(project: dict[str, Any], *, kind: str = "freeform")
)
)
- capabilities = project.get("capabilities") or {}
+ declared_network_origins = {
+ canonical for origin in network_origins if (canonical := canonical_network_origin(origin)) is not None
+ }
for path, content in files.items():
- if not path.endswith(_CODE_EXTENSIONS) or not isinstance(content, str):
+ if not isinstance(content, str):
continue
- diagnostics.extend(_validate_code_file(path, content))
- diagnostics.extend(_validate_capabilities(path, content, capabilities))
+ diagnostics.extend(_validate_network_capabilities(path, content, declared_network_origins))
+ if path.endswith(_CODE_EXTENSIONS):
+ diagnostics.extend(_validate_code_file(path, content))
+ diagnostics.extend(_validate_capabilities(path, content, capabilities))
return diagnostics
diff --git a/products/canvas/backend/tests/test_artifact_tokens.py b/products/canvas/backend/tests/test_artifact_tokens.py
index 70ead677096e..6e4766d5b5b9 100644
--- a/products/canvas/backend/tests/test_artifact_tokens.py
+++ b/products/canvas/backend/tests/test_artifact_tokens.py
@@ -80,6 +80,9 @@ class TestCanvasArtifactTokens(SimpleTestCase):
self.assertEqual(response["X-Content-Type-Options"], "nosniff")
self.assertEqual(response["Content-Security-Policy"].split(";")[0], "sandbox allow-scripts")
self.assertIn("connect-src https://api.example.com", response["Content-Security-Policy"])
+ self.assertIn("style-src 'self' 'unsafe-inline' https://api.example.com", response["Content-Security-Policy"])
+ self.assertIn("img-src 'self' data: blob: https://api.example.com", response["Content-Security-Policy"])
+ self.assertIn("frame-src https://api.example.com", response["Content-Security-Policy"])
self.assertNotIn("evil.example.net", response["Content-Security-Policy"])
with self.assertRaises(Http404):
canvas_artifact(RequestFactory().get("/"), token or "", "source.ts")
diff --git a/products/canvas/backend/tests/test_artifacts.py b/products/canvas/backend/tests/test_artifacts.py
index c360b35162aa..a913d9a4e055 100644
--- a/products/canvas/backend/tests/test_artifacts.py
+++ b/products/canvas/backend/tests/test_artifacts.py
@@ -62,6 +62,12 @@ class TestCanvasArtifacts(APIBaseTest):
assert response["ETag"] == f'"{self.content_hash}"'
assert response["Content-Security-Policy"].startswith("sandbox allow-scripts; default-src 'none'")
assert "connect-src https://api.example.com" in response["Content-Security-Policy"]
+ assert "style-src 'self' 'unsafe-inline' https://api.example.com" in response["Content-Security-Policy"]
+ assert "img-src 'self' data: blob: https://api.example.com" in response["Content-Security-Policy"]
+ assert "font-src 'self' data: https://api.example.com" in response["Content-Security-Policy"]
+ assert "media-src 'self' data: blob: https://api.example.com" in response["Content-Security-Policy"]
+ assert "frame-src https://api.example.com" in response["Content-Security-Policy"]
+ assert "script-src 'self' https://api.example.com" not in response["Content-Security-Policy"]
assert response["Cache-Control"] == "private, max-age=31536000, immutable"
# The sandboxed iframe's opaque origin fetches module scripts in CORS
# mode; without this the entry bundle is blocked and the canvas
diff --git a/products/canvas/backend/tests/test_cloud_builder.py b/products/canvas/backend/tests/test_cloud_builder.py
index 969b34707e9d..920e93b3d63b 100644
--- a/products/canvas/backend/tests/test_cloud_builder.py
+++ b/products/canvas/backend/tests/test_cloud_builder.py
@@ -171,6 +171,50 @@ class TestCanvasCloudBuilder(SimpleTestCase):
self.assertEqual(process.returncode, 0, process.stderr or process.stdout)
+ def test_runtime_bounds_csp_violation_telemetry_to_one_per_directive(self) -> None:
+ # Blocked subresources fire securitypolicyviolation before the port
+ # connects, so each violation shares the 256-slot pre-connect queue with
+ # data requests. A canvas that misses one origin can render many blocked
+ # resources; without a bound the burst fills the queue and a later
+ # ph.query is dropped and dies on its 30s timeout. Reporting each
+ # directive once keeps the queue open for the request.
+ result = run_cloud_builder(self._project('document.body.textContent = "Hello"'))
+
+ runtime = next(file["content"] for file in result["files"] if file["path"] == "assets/canvas-runtime.js")
+ harness = "\n".join(
+ [
+ "const listeners = {};",
+ "const timers = new Map();",
+ "let timerId = 0;",
+ "globalThis.window = globalThis;",
+ "globalThis.parent = {};",
+ 'globalThis.document = { readyState: "complete", body: {}, head: { appendChild: () => {} }, addEventListener: () => {}, createElement: () => ({}) };',
+ 'globalThis.location = { hash: "" };',
+ "globalThis.MutationObserver = class { observe() {} };",
+ "globalThis.addEventListener = (type, fn) => { (listeners[type] ||= []).push(fn); };",
+ "globalThis.setTimeout = (fn) => { timers.set(++timerId, fn); return timerId; };",
+ "globalThis.clearTimeout = (id) => { timers.delete(id); };",
+ runtime,
+ "const received = [];",
+ "const port = { postMessage: (m) => received.push(m), addEventListener: () => {}, start: () => {} };",
+ # A burst larger than the 256-slot queue across two directives.
+ 'for (let i = 0; i < 300; i++) for (const fn of listeners.securitypolicyviolation) fn({ effectiveDirective: i % 2 ? "img-src" : "font-src" });',
+ # The data request issued after the burst must still fit the queue.
+ 'window.ph.query("SELECT 1");',
+ 'for (const fn of listeners.message) fn({ source: parent, data: { channel: "posthog-canvas", type: "connect" }, ports: [port] });',
+ 'const cspErrors = received.filter((m) => m.type === "error" && m.message.startsWith("SecurityPolicyViolationError:"));',
+ 'if (cspErrors.length !== 2) { console.error("expected one error per directive, got " + cspErrors.length); process.exit(1); }',
+ "const directives = new Set(cspErrors.map((m) => m.message));",
+ 'if (directives.size !== 2) { console.error("directives were not deduplicated"); process.exit(1); }',
+ 'if (!received.some((m) => m.type === "data-request" && m.payload.hogql === "SELECT 1")) { console.error("data request was dropped by the violation burst"); process.exit(1); }',
+ "process.exit(0);",
+ ]
+ )
+
+ process = subprocess.run([node_executable()], input=harness, capture_output=True, text=True, timeout=60)
+
+ self.assertEqual(process.returncode, 0, process.stderr or process.stdout)
+
def test_runtime_rejects_pre_connect_action_invocations(self) -> None:
# Reads queue until the port connects, but a write queued during module
# initialization would fire on connect as the viewer — an on-open task
@@ -440,6 +484,42 @@ bridge.port1.close();
self.assertEqual(manifest["capabilities"], project["capabilities"])
html = next(file["content"] for file in files if file["path"] == "index.html")
self.assertIn("connect-src https://api.example.com", html)
+ self.assertIn("style-src 'self' 'unsafe-inline' https://api.example.com", html)
+ self.assertIn("img-src 'self' data: blob: https://api.example.com", html)
+ self.assertIn("font-src 'self' data: https://api.example.com", html)
+ self.assertIn("media-src 'self' data: blob: https://api.example.com", html)
+ self.assertIn("frame-src https://api.example.com", html)
+ self.assertNotIn("script-src 'self' https://api.example.com", html)
+
+ def test_preserves_declared_remote_stylesheet_links(self) -> None:
+ project = self._project('document.body.textContent = "Hello"')
+ project["files"]["index.html"] = (
+ '<head><link rel="stylesheet" href="https://styles.example.com/theme.css" /></head>'
+ '<div id="root"></div><script type="module" src="/src/main.ts"></script>'
+ )
+ project["capabilities"] = {
+ "posthog": {"insights": [], "inlineQueries": False, "captureEvents": []},
+ "network": {"origins": ["https://styles.example.com"]},
+ }
+
+ files, _, diagnostics = validate_builder_output(run_cloud_builder(project))
+
+ self.assertEqual(diagnostics, [])
+ html = next(file["content"] for file in files if file["path"] == "index.html")
+ # A declared remote stylesheet is not a local build entry, so it stays in
+ # the HTML and loads at runtime under the widened style-src CSP, instead
+ # of failing the build with entry_not_found.
+ self.assertIn('href="https://styles.example.com/theme.css"', html)
+ self.assertIn("style-src 'self' 'unsafe-inline' https://styles.example.com", html)
+
+ def test_runtime_reports_csp_violations_without_blocked_urls(self) -> None:
+ result = run_cloud_builder(self._project('document.body.textContent = "Hello"'))
+
+ runtime = next(file["content"] for file in result["files"] if file["path"] == "assets/canvas-runtime.js")
+ self.assertIn('addEventListener("securitypolicyviolation"', runtime)
+ self.assertIn("SecurityPolicyViolationError", runtime)
+ self.assertIn("effectiveDirective", runtime)
+ self.assertNotIn("blockedURI", runtime)
def test_rejects_unbounded_capabilities(self) -> None:
project = self._project("")
diff --git a/products/canvas/backend/tests/test_source.py b/products/canvas/backend/tests/test_source.py
index bc028917fbd1..0624e1561878 100644
--- a/products/canvas/backend/tests/test_source.py
+++ b/products/canvas/backend/tests/test_source.py
@@ -186,20 +186,107 @@ class TestCanvasSourceAdapter(SimpleTestCase):
self.assertNotIn("capability_missing_state", [d["code"] for d in diagnostics])
def test_direct_network_calls_warn_but_stay_publishable(self):
- # fetch() is blocked by the sandbox CSP, not by publish — a comment or
- # string mentioning it must not brick a canvas, so it's a warning.
- candidate = project(files={CANVAS_COMPONENT_PATH: CODE + 'fetch("/api/x");'})
+ candidate = project(files={CANVAS_COMPONENT_PATH: CODE + "fetch(dynamicUrl);"})
diagnostics = validate_source_project(candidate)
self.assertFalse(has_errors(diagnostics))
self.assertIn("network_fetch", [d["code"] for d in diagnostics])
+ @parameterized.expand(
+ [
+ ("fetch", 'fetch("https://api.example.com/v1/data");', CANVAS_COMPONENT_PATH, "https://api.example.com"),
+ (
+ "fetch_template_literal",
+ "fetch(`https://api.example.com/v1/${reportId}`);",
+ CANVAS_COMPONENT_PATH,
+ "https://api.example.com",
+ ),
+ (
+ "image",
+ '<img src="https://images.example.com/chart.png" />',
+ CANVAS_COMPONENT_PATH,
+ "https://images.example.com",
+ ),
+ (
+ "image_srcset",
+ '<img srcSet="/chart-small.png 1x, https://images.example.com/chart-large.png 2x" />',
+ CANVAS_COMPONENT_PATH,
+ "https://images.example.com",
+ ),
+ (
+ "stylesheet",
+ '<link rel="stylesheet" href="https://styles.example.com/theme.css" />',
+ CANVAS_ENTRY_HTML,
+ "https://styles.example.com",
+ ),
+ (
+ "css_url",
+ '.hero { background-image: url("https://images.example.com/hero.png"); }',
+ "src/theme.css",
+ "https://images.example.com",
+ ),
+ (
+ "css_import",
+ '@import url("https://styles.example.com/base.css");',
+ "src/theme.css",
+ "https://styles.example.com",
+ ),
+ ]
+ )
+ def test_literal_external_resources_require_declared_origin(self, _name, snippet, path, expected_origin):
+ candidate = project(files={CANVAS_COMPONENT_PATH: CODE, path: snippet})
+
+ diagnostics = validate_source_project(candidate)
+
+ entry = next(d for d in diagnostics if d["code"] == "capability_missing_network_origin")
+ self.assertIn(f'"{expected_origin}" in capabilities.network.origins', entry["message"])
+ self.assertEqual(entry["path"], path)
+
+ def test_declared_origin_covers_literal_external_resources(self):
+ candidate = project(
+ files={CANVAS_COMPONENT_PATH: CODE + 'fetch("https://api.example.com/v1/data");'},
+ capabilities={"network": {"origins": ["https://api.example.com"]}},
+ )
+
+ diagnostics = validate_source_project(candidate)
+
+ self.assertNotIn("capability_missing_network_origin", [entry["code"] for entry in diagnostics])
+
+ @parameterized.expand(
+ [
+ ("anchor", '<a href="https://posthog.com/docs">Docs</a>'),
+ ("open_external", 'ph.openExternal("https://app.posthog.com/insights/abc");'),
+ ]
+ )
+ def test_navigation_urls_do_not_require_network_origin(self, _name, snippet):
+ candidate = project(files={CANVAS_COMPONENT_PATH: CODE + snippet})
+
+ diagnostics = validate_source_project(candidate)
+
+ self.assertNotIn("capability_missing_network_origin", [entry["code"] for entry in diagnostics])
+
+ @parameterized.expand(
+ [
+ ("object", '<object data="https://cdn.example.com/report.pdf"></object>'),
+ ("embed", '<embed src="https://cdn.example.com/report.pdf" />'),
+ ]
+ )
+ def test_object_and_embed_do_not_require_network_origin(self, _name, snippet):
+ # The artifact CSP keeps object-src 'none', so a declared origin cannot
+ # make these load. Flagging them would block publish with a remedy that
+ # does nothing.
+ candidate = project(files={CANVAS_COMPONENT_PATH: CODE + snippet})
+
+ diagnostics = validate_source_project(candidate)
+
+ self.assertNotIn("capability_missing_network_origin", [entry["code"] for entry in diagnostics])
+
@parameterized.expand(
[
("http", "http://api.example.com"),
("path", "https://api.example.com/v1"),
("credentials", "https://user:[email protected]"),
("wildcard", "https://*.example.com"),
- # Origins land in the viewer's connect-src, so private and local
+ # Origins land in the viewer's CSP, so private and local
# destinations would let a canvas probe the viewer's machine or LAN.
("loopback_ipv4", "https://127.0.0.1:8443"),
("private_ipv4", "https://192.168.1.1"),
@@ -219,7 +306,7 @@ class TestCanvasSourceAdapter(SimpleTestCase):
("ipv4_hex_label", "https://1.2.3.0x10"),
("ipv6_scope_id", "https://[fe80::1%eth0]"),
("ipv6_global_scope_id", "https://[2606:4700:4700::1111%foo; img-src evil.example]"),
- # A delimiter in the hostname would break out of the connect-src it is
+ # A delimiter in the hostname would break out of the directive it is
# spliced into. This form carries no wildcard, so only the hostname
# charset check rejects it.
("csp_directive_injection", "https://example.com; img-src evil.example.net"),
diff --git a/products/canvas/packages/canvas_builder/build.mjs b/products/canvas/packages/canvas_builder/build.mjs
index 101cb5377508..83bbc9806020 100644
--- a/products/canvas/packages/canvas_builder/build.mjs
+++ b/products/canvas/packages/canvas_builder/build.mjs
@@ -27,7 +27,7 @@ const runtimePath = 'assets/canvas-runtime.js'
// event, which fires after the app's module scripts have already run, so any
// ph.* call issued during mount lands before the port exists. Those messages
// queue (bounded, in case the host never connects) and flush on connect.
-const runtime = `(()=>{const channel="posthog-canvas",pending=new Map,queued=[];let sequence=0,port;const post=(message)=>{const payload={channel,...message};if(port){port.postMessage(payload)}else if(queued.length<256){queued.push(payload)}};const call=(method,payload)=>new Promise((resolve,reject)=>{if(!port&&(method==="actionInvoke"||method==="agentRequest")){reject(new Error("Canvas actions require a user action"));return}const id=String(++sequence);const timer=setTimeout(()=>{pending.delete(id);const queuedIndex=queued.findIndex((message)=>message.type==="data-request"&&message.id===id);if(queuedIndex>-1)queued.splice(queuedIndex,1);reject(new Error("Canvas request timed out"));},30000);pending.set(id,{resolve,reject,timer});post({type:"data-request",id,method,payload});});const applyTheme=(theme)=>{if(theme!=="dark"&&theme!=="light")return;const dark=theme==="dark";document.documentElement.classList.toggle("dark",dark);document.documentElement.style.colorScheme=dark?"dark":"light";};const fragmentParams=new URLSearchParams(location.hash.slice(1));applyTheme(fragmentParams.get("theme"));let config={};try{const rawConfig=fragmentParams.get("config");if(rawConfig)config=Object.freeze(JSON.parse(rawConfig))}catch{config={}};const receive=(event)=>{if(event.data?.channel!==channel)return;if(event.data.type==="set-theme"){applyTheme(event.data.theme);return}if(event.data.type!=="data-response")return;const request=pending.get(event.data.id);if(!request)return;pending.delete(event.data.id);clearTimeout(request.timer);event.data.ok?request.resolve(event.data.result):request.reject(new Error(event.data.error??"Canvas request failed"));};const capture=(event,properties,distinctId)=>{const normalized=properties??{};let serialized;try{serialized=JSON.stringify(normalized)}catch{throw new Error("Canvas capture properties must be serializable")};if(typeof serialized!=="string"||serialized.length>16384)throw new Error("Canvas capture properties are too large");return call("capture",{event,properties:normalized,distinctId})};const openExternal=(value)=>{const url=new URL(value);if(url.protocol!=="https:"||!(url.hostname==="posthog.com"||url.hostname.endsWith(".posthog.com")))throw new Error("Canvas external URL is not allowed");post({type:"open-external",url:url.href})};window.ph={config,loadInsight:(shortId,options)=>call("loadInsight",{shortId,dateRange:options?.dateRange,variables:options?.variables,refresh:options?.refresh}),query:(query,params,options)=>call("query",typeof query==="string"?{hogql:query,params:params??{},refresh:options?.refresh}:{query,params:params??{},refresh:options?.refresh}),capture,openExternal,agent:{request:(prompt)=>call("agentRequest",{prompt})},state:{get:(key,opts)=>call("stateGet",{key,scope:opts?.scope||"user"}),set:(key,value,opts)=>call("stateSet",{key,value:value===undefined?null:value,scope:opts?.scope||"user"}),list:(opts)=>call("stateList",{scope:opts?.scope})},actions:{invoke:(verb,payload)=>call("actionInvoke",{verb,payload:payload??{}})}};addEventListener("message",(event)=>{if(port||event.source!==parent||event.data?.channel!==channel||event.data?.type!=="connect"||!event.ports[0])return;port=event.ports[0];port.addEventListener("message",receive);port.start();while(queued.length)port.postMessage(queued.shift());if(document.readyState!=="loading")post({type:"ready"});if(document.readyState==="complete")post({type:"rendered"});});addEventListener("error",(event)=>post({type:"error",message:event.message||"Canvas runtime error",stack:event.error?.stack}));addEventListener("unhandledrejection",(event)=>post({type:"error",message:event.reason instanceof Error?event.reason.message:String(event.reason),stack:event.reason instanceof Error?event.reason.stack:undefined}));addEventListener("DOMContentLoaded",()=>post({type:"ready"}));addEventListener("load",()=>post({type:"rendered"}));})();`
+const runtime = `(()=>{const channel="posthog-canvas",pending=new Map,queued=[];let sequence=0,port;const post=(message)=>{const payload={channel,...message};if(port){port.postMessage(payload)}else if(queued.length<256){queued.push(payload)}};const call=(method,payload)=>new Promise((resolve,reject)=>{if(!port&&(method==="actionInvoke"||method==="agentRequest")){reject(new Error("Canvas actions require a user action"));return}const id=String(++sequence);const timer=setTimeout(()=>{pending.delete(id);const queuedIndex=queued.findIndex((message)=>message.type==="data-request"&&message.id===id);if(queuedIndex>-1)queued.splice(queuedIndex,1);reject(new Error("Canvas request timed out"));},30000);pending.set(id,{resolve,reject,timer});post({type:"data-request",id,method,payload});});const applyTheme=(theme)=>{if(theme!=="dark"&&theme!=="light")return;const dark=theme==="dark";document.documentElement.classList.toggle("dark",dark);document.documentElement.style.colorScheme=dark?"dark":"light";};const fragmentParams=new URLSearchParams(location.hash.slice(1));applyTheme(fragmentParams.get("theme"));let config={};try{const rawConfig=fragmentParams.get("config");if(rawConfig)config=Object.freeze(JSON.parse(rawConfig))}catch{config={}};const receive=(event)=>{if(event.data?.channel!==channel)return;if(event.data.type==="set-theme"){applyTheme(event.data.theme);return}if(event.data.type!=="data-response")return;const request=pending.get(event.data.id);if(!request)return;pending.delete(event.data.id);clearTimeout(request.timer);event.data.ok?request.resolve(event.data.result):request.reject(new Error(event.data.error??"Canvas request failed"));};const capture=(event,properties,distinctId)=>{const normalized=properties??{};let serialized;try{serialized=JSON.stringify(normalized)}catch{throw new Error("Canvas capture properties must be serializable")};if(typeof serialized!=="string"||serialized.length>16384)throw new Error("Canvas capture properties are too large");return call("capture",{event,properties:normalized,distinctId})};const openExternal=(value)=>{const url=new URL(value);if(url.protocol!=="https:"||!(url.hostname==="posthog.com"||url.hostname.endsWith(".posthog.com")))throw new Error("Canvas external URL is not allowed");post({type:"open-external",url:url.href})};window.ph={config,loadInsight:(shortId,options)=>call("loadInsight",{shortId,dateRange:options?.dateRange,variables:options?.variables,refresh:options?.refresh}),query:(query,params,options)=>call("query",typeof query==="string"?{hogql:query,params:params??{},refresh:options?.refresh}:{query,params:params??{},refresh:options?.refresh}),capture,openExternal,agent:{request:(prompt)=>call("agentRequest",{prompt})},state:{get:(key,opts)=>call("stateGet",{key,scope:opts?.scope||"user"}),set:(key,value,opts)=>call("stateSet",{key,value:value===undefined?null:value,scope:opts?.scope||"user"}),list:(opts)=>call("stateList",{scope:opts?.scope})},actions:{invoke:(verb,payload)=>call("actionInvoke",{verb,payload:payload??{}})}};addEventListener("message",(event)=>{if(port||event.source!==parent||event.data?.channel!==channel||event.data?.type!=="connect"||!event.ports[0])return;port=event.ports[0];port.addEventListener("message",receive);port.start();while(queued.length)port.postMessage(queued.shift());if(document.readyState!=="loading")post({type:"ready"});if(document.readyState==="complete")post({type:"rendered"});});addEventListener("error",(event)=>post({type:"error",message:event.message||"Canvas runtime error",stack:event.error?.stack}));addEventListener("unhandledrejection",(event)=>post({type:"error",message:event.reason instanceof Error?event.reason.message:String(event.reason),stack:event.reason instanceof Error?event.reason.stack:undefined}));const cspSeen=new Set();addEventListener("securitypolicyviolation",(event)=>{const directive=event.effectiveDirective||"unknown";if(cspSeen.has(directive))return;cspSeen.add(directive);post({type:"error",message:"SecurityPolicyViolationError: "+directive})});addEventListener("DOMContentLoaded",()=>post({type:"ready"}));addEventListener("load",()=>post({type:"rendered"}));})();`
// A published canvas runs the runtime baked into its artifact by this builder,
// while an unpublished one runs the desktop's sandbox document — two copies of
// the same selection behavior. The pair below is ported from the desktop's
@@ -240,7 +240,15 @@ function entryReferences(html) {
}
if (tag[1].toLowerCase() === 'script' && attributes.type === 'module' && attributes.src) {
references.push([attributes.src, 'js'])
- } else if (tag[1].toLowerCase() === 'link' && attributes.rel === 'stylesheet' && attributes.href) {
+ } else if (
+ tag[1].toLowerCase() === 'link' &&
+ attributes.rel === 'stylesheet' &&
+ attributes.href &&
+ !/^https:\/\//i.test(attributes.href)
+ ) {
+ // A remote HTTPS stylesheet is not a local build entry, so it stays
+ // in the emitted HTML and loads at runtime under the declared-origin
+ // style-src CSP. Only local stylesheets are bundled here.
references.push([attributes.href, 'css'])
}
}
@@ -534,8 +542,16 @@ async function buildCanvas(project) {
files.push(artifact(cssPath, platformCss))
files.push(artifact(runtimePath, `${runtime}\n${selectionRuntime}\n${highlightRuntime}\n${keyboardRuntime}`))
const networkOrigins = project.capabilities?.network?.origins ?? []
- const connectSources = networkOrigins.length ? networkOrigins.join(' ') : "'none'"
- const projectCsp = csp.replace("connect-src 'none'", `connect-src ${connectSources}`)
+ const externalSources = networkOrigins.join(' ')
+ const projectCsp = externalSources
+ ? csp
+ .replace("connect-src 'none'", `connect-src ${externalSources}`)
+ .replace("style-src 'self' 'unsafe-inline'", `style-src 'self' 'unsafe-inline' ${externalSources}`)
+ .replace("img-src 'self' data: blob:", `img-src 'self' data: blob: ${externalSources}`)
+ .replace("font-src 'self' data:", `font-src 'self' data: ${externalSources}`)
+ .replace("media-src 'self' data: blob:", `media-src 'self' data: blob: ${externalSources}`)
+ .replace("frame-src 'none'", `frame-src ${externalSources}`)
+ : csp
const head = `<meta http-equiv="Content-Security-Policy" content="${projectCsp}" /><link rel="stylesheet" href="./${cssPath}" /><script src="./${runtimePath}"></script>`
html = html.includes('<head>') ? html.replace('<head>', `<head>${head}`) : `${head}${html}`
files.unshift(artifact(project.entryHtml, html))
diff --git a/products/canvas/packages/canvas_builder/manifest.json b/products/canvas/packages/canvas_builder/manifest.json
index 73f6a2eed87f..7f3bedfd593b 100644
--- a/products/canvas/packages/canvas_builder/manifest.json
+++ b/products/canvas/packages/canvas_builder/manifest.json
@@ -54,7 +54,7 @@
"react-markdown",
"papaparse"
],
- "csp": "sandbox allow-scripts; default-src 'none'; base-uri 'none'; object-src 'none'; form-action 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'none'; img-src 'self' data: blob:; font-src 'self' data:; media-src 'self' data: blob:; worker-src 'self' blob:",
+ "csp": "sandbox allow-scripts; default-src 'none'; base-uri 'none'; object-src 'none'; form-action 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'none'; img-src 'self' data: blob:; font-src 'self' data:; media-src 'self' data: blob:; frame-src 'none'; worker-src 'self' blob:",
"limits": {
"maxSourceFiles": 64,
"maxSourceFileBytes": 524288,
diff --git a/products/canvas/skills/building-html-canvases/SKILL.md b/products/canvas/skills/building-html-canvases/SKILL.md
index d4c2c63aeb4b..b6ff60d13773 100644
--- a/products/canvas/skills/building-html-canvases/SKILL.md
+++ b/products/canvas/skills/building-html-canvases/SKILL.md
@@ -53,9 +53,10 @@ build pipeline's dependency admission ships.
## Rules that still apply
-- No `fetch()`/`XMLHttpRequest`, no `<script>` tags, no dynamic `import()`, no remote assets —
- the sandbox blocks them. PostHog data comes only through the `ph` bridge (see the
- `querying-canvas-data` skill), including `ph.capture` for interaction analytics.
+- PostHog data comes only through the `ph` bridge (see `querying-canvas-data`), including
+ `ph.capture` for interaction analytics. Other requests and external styles, images, fonts, media,
+ or frames require their exact public HTTPS origins in `capabilities.network.origins` and work only
+ after publishing. Remote scripts and dynamic imports remain blocked.
- A document that states PostHog numbers must make each one verifiable: an insight-backed number
links its saved insight through `ph.openExternal` (URL from the `generate-app-url` MCP tool,
from a click); an ad-hoc `ph.query` number discloses the exact query that ran in a `<details>`
diff --git a/products/canvas/skills/building-react-quill-canvases/SKILL.md b/products/canvas/skills/building-react-quill-canvases/SKILL.md
index 2c6d17a15925..77344b66a49d 100644
--- a/products/canvas/skills/building-react-quill-canvases/SKILL.md
+++ b/products/canvas/skills/building-react-quill-canvases/SKILL.md
@@ -26,9 +26,10 @@ also admits ten optional libraries for specialized work. Read
[references/platform-libraries.md](references/platform-libraries.md) before choosing one.
Other bare imports, dynamic `import()`, `require()`, `<script>` tags, and remote code fail
-validation. Direct `fetch()` requires an exact HTTPS origin in `capabilities.network.origins`,
-and works only in the **published** canvas — the edit-mode preview blocks all direct network
-access regardless of declaration, so verify origin-fetching code after publishing, not in preview.
+validation. Direct network requests and external images, fonts, media, or frames require an exact
+HTTPS origin in `capabilities.network.origins`. They work only in the **published** canvas — the
+edit-mode preview blocks direct network access regardless of declaration. Stylesheets from declared
+origins are allowed; remote scripts remain blocked, so bundle code with the canvas.
## Quill component rules
diff --git a/products/canvas/skills/building-react-quill-canvases/references/platform-libraries.md b/products/canvas/skills/building-react-quill-canvases/references/platform-libraries.md
index 1a9f6fcb5ad9..6e97932d7fa5 100644
--- a/products/canvas/skills/building-react-quill-canvases/references/platform-libraries.md
+++ b/products/canvas/skills/building-react-quill-canvases/references/platform-libraries.md
@@ -30,7 +30,8 @@ keep the dependency map returned by `canvas-source-retrieve` unchanged.
HTML from untrusted content.
- Papa Parse processes text already available to the canvas. Loading a remote CSV still requires its
exact HTTPS origin in `capabilities.network.origins` (published canvases only — the edit-mode
- preview blocks direct network access regardless of declaration).
+ preview blocks direct network access regardless of declaration). The same declaration is required
+ for external stylesheets, images, fonts, media, and frames.
- Three.js owns its `<canvas>` element. React can own the surrounding Quill application shell.
The standard imports remain `react`, `react-dom`, `react-dom/client`, `@posthog/quill`, `recharts`,
diff --git a/products/canvas/skills/querying-canvas-data/SKILL.md b/products/canvas/skills/querying-canvas-data/SKILL.md
index f2edcc1406e9..3fc71c97c149 100644
--- a/products/canvas/skills/querying-canvas-data/SKILL.md
+++ b/products/canvas/skills/querying-canvas-data/SKILL.md
@@ -13,9 +13,10 @@ description: >
The global `ph` object (injected by the host — never imported, never initialized) is the only way
a canvas talks to PostHog. Credentials stay in the host; `fetch()`, posthog-js, and hand-rolled
-clients cannot reach PostHog from the sandbox. The one sanctioned use of `fetch()` is a non-PostHog
-origin declared in `capabilities.network.origins`, and only in the published canvas — the
-edit-mode preview blocks all direct network access.
+clients cannot reach PostHog from the sandbox. External requests and resources require a non-PostHog
+origin declared in `capabilities.network.origins`, and work only in the published canvas — the
+edit-mode preview blocks all direct network access. This includes external stylesheets; remote
+scripts remain blocked.
## Data hierarchy — back every metric with a saved insight
diff --git a/products/canvas/skills/validating-and-publishing-canvases/SKILL.md b/products/canvas/skills/validating-and-publishing-canvases/SKILL.md
index 533120d7e26d..7127d0e090fe 100644
--- a/products/canvas/skills/validating-and-publishing-canvases/SKILL.md
+++ b/products/canvas/skills/validating-and-publishing-canvases/SKILL.md
@@ -39,15 +39,23 @@ then dies in the rendered canvas. Declare:
- `capabilities.posthog.captureEvents` — every event name it passes to `ph.capture`.
- `capabilities.posthog.inlineQueries: true` — when it calls `ph.query` at all.
- `capabilities.posthog.agentRequests: true` — when it calls `ph.agent.request`.
-- `capabilities.network.origins` — each exact HTTPS origin used by `fetch` or `XMLHttpRequest`.
+- `capabilities.network.origins` — each exact HTTPS origin used by `fetch`, `XMLHttpRequest`, or an
+ external stylesheet, image, font, media file, or frame. Remote scripts remain blocked.
Do not include paths, credentials, queries, fragments, or wildcards. The host must be public:
loopback and private IPs, single-label names like `intranet`, and the `.local`, `.localhost`,
`.internal`, and `.home.arpa` suffixes are all rejected, so a local dev host such as
`https://localhost:8010` fails validation with an `invalid_network_origin` error. Data sent to a
declared origin leaves PostHog and appears in the capability review before promotion.
-Validation rejects undeclared literal calls (`capability_missing_*` diagnostics) so you can fix
-them before publishing; dynamic ids it can only warn about, so keep the declarations complete.
+Before validation, inventory every literal external URL in every source file. Classify navigation
+links and `ph.openExternal()` URLs as navigation; they do not need a network origin. For every
+request or resource URL, declare its scheme + host + optional port only. Include every origin a
+request redirects to and every secondary origin a stylesheet references for fonts or images.
+Never infer that one CDN hostname covers another.
+
+Validation rejects undeclared literal calls and resource URLs (`capability_missing_*` diagnostics)
+so you can fix them before publishing. Dynamic URLs and redirect destinations cannot be inferred,
+so the inventory is still required even when validation is clean.
## Validate until clean
@@ -59,7 +67,8 @@ Diagnostics carry `severity`, a stable `code`, a `message`, and (for file-specif
(bare imports are limited to the dependencies returned in the source project),
`forbidden_dynamic_import` / `forbidden_require` / `forbidden_inline_script`,
`invalid_path`, `capability_missing_insight` / `capability_missing_capture_event` /
- `capability_missing_inline_queries` / `capability_missing_agent_requests`,
+ `capability_missing_inline_queries` / `capability_missing_agent_requests` /
+ `capability_missing_network_origin`,
`dependency_not_admitted` / `dependency_version_mismatch`, and path/size violations.
- `warning` diagnostics don't block, but heed them: `network_fetch` / `network_xhr` mean the code
reaches for the network directly. Declare the exact HTTPS origin or use the `ph` bridge.
diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.ts
index ea967e77a67a..20b355d5cee3 100644
--- a/products/desktop/packages/shared/src/analytics-events.ts
+++ b/products/desktop/packages/shared/src/analytics-events.ts
@@ -1120,6 +1120,8 @@ export interface CanvasRuntimeErrorProperties {
* source fragments, query results, or secrets that must not cross into analytics.
*/
error_type: string;
+ /** CSP directive only; blocked URLs never cross into analytics. */
+ csp_directive?: string;
}
export type ContextActionType = "save_version" | "generate_started" | "discard";
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx
index 1fa092f78577..3cba1a0c6803 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx
@@ -100,6 +100,7 @@ import { CanvasPermissionDialog } from "./CanvasPermissionDialog";
import { CanvasSelectionCommentAction } from "./CanvasSelectionCommentAction";
import { CanvasSidePanel } from "./CanvasSidePanel";
import { canvasCommentTaskId } from "./canvasCommentTask";
+import { canvasRuntimeErrorAnalytics } from "./canvasRuntimeError";
import { canvasSidePanelVisibility } from "./canvasSidePanelVisibility";
import {
canvasVersionNavigation,
@@ -118,15 +119,6 @@ import { usePinnedArtifact } from "./usePinnedArtifact";
// history), and an edit composer. Generation runs as a dedicated task; while
// one is in flight the empty canvas shows a "Generating…" state with the run's
// chat panel open by default (in view mode too), so the work is watchable.
-// The canvas runtime error string is user/agent-authored and can carry source
-// fragments, query results, or secrets. Reduce it to the leading error class name
-// (e.g. "TypeError") for analytics, so no interpolated content crosses the boundary.
-function canvasErrorType(message: string): string {
- return (
- message.match(/^([A-Z][A-Za-z0-9]*(?:Error|Exception))\b/)?.[1] ?? "unknown"
- );
-}
-
// One toast per outcome: only new_run actually starts a run — signaled hands
// the prompt to a run already in progress, and already_queued means an
// identical request beat this one, so "Agent run started" would misreport both.
@@ -679,10 +671,10 @@ export function FreeformCanvasView({
(message: string) => {
if (message !== lastRuntimeErrorRef.current) {
lastRuntimeErrorRef.current = message;
- const errorType = canvasErrorType(message);
+ const analytics = canvasRuntimeErrorAnalytics(message);
track(ANALYTICS_EVENTS.CANVAS_RUNTIME_ERROR, {
...canvasTrackProps,
- error_type: errorType,
+ ...analytics,
});
// File the error in the authoring task's thread so its agent hears
// about it — the class name only; the full message stays client-side.
@@ -690,7 +682,7 @@ export function FreeformCanvasView({
reportRuntimeError({
id: dashboardId,
buildId: canvasTrackProps.build_id,
- errorType,
+ errorType: analytics.error_type,
});
}
}
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/canvasRuntimeError.test.ts b/products/desktop/packages/ui/src/features/canvas/freeform/canvasRuntimeError.test.ts
new file mode 100644
index 000000000000..c1f7b5015eee
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/canvasRuntimeError.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from "vitest";
+import { canvasRuntimeErrorAnalytics } from "./canvasRuntimeError";
+
+describe("canvasRuntimeErrorAnalytics", () => {
+ it("captures only the CSP directive", () => {
+ expect(
+ canvasRuntimeErrorAnalytics("SecurityPolicyViolationError: img-src"),
+ ).toEqual({
+ error_type: "SecurityPolicyViolationError",
+ csp_directive: "img-src",
+ });
+ });
+
+ it("does not capture arbitrary runtime messages", () => {
+ expect(
+ canvasRuntimeErrorAnalytics(
+ "TypeError: request failed with [email protected]",
+ ),
+ ).toEqual({ error_type: "TypeError" });
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/canvasRuntimeError.ts b/products/desktop/packages/ui/src/features/canvas/freeform/canvasRuntimeError.ts
new file mode 100644
index 000000000000..a91438f840f1
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/canvasRuntimeError.ts
@@ -0,0 +1,16 @@
+import type { CanvasRuntimeErrorProperties } from "@posthog/shared/analytics-events";
+
+export function canvasRuntimeErrorAnalytics(
+ message: string,
+): Pick<CanvasRuntimeErrorProperties, "error_type" | "csp_directive"> {
+ const errorType =
+ message.match(/^([A-Z][A-Za-z0-9]*(?:Error|Exception))\b/)?.[1] ??
+ "unknown";
+ const cspDirective = message.match(
+ /^SecurityPolicyViolationError: ([a-z][a-z-]{0,63})$/,
+ )?.[1];
+ return {
+ error_type: errorType,
+ ...(cspDirective ? { csp_directive: cspDirective } : {}),
+ };
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/grid/ComponentFrame.tsx b/products/desktop/packages/ui/src/features/canvas/grid/ComponentFrame.tsx
index a864329f12c1..dea10b04f703 100644
--- a/products/desktop/packages/ui/src/features/canvas/grid/ComponentFrame.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/grid/ComponentFrame.tsx
@@ -5,10 +5,13 @@ import {
} from "@posthog/core/canvas/gridLayoutSchemas";
import { Button, Spinner, Text } from "@posthog/quill";
import type { CanvasCapabilities } from "@posthog/shared";
+import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";
import { useCanvasBuilds } from "@posthog/ui/features/canvas/hooks/useCanvasBuilds";
+import { track } from "@posthog/ui/shell/analytics";
import { useQueryClient } from "@tanstack/react-query";
-import { useCallback, useMemo } from "react";
+import { useCallback, useMemo, useRef } from "react";
import { BuiltCanvas } from "../freeform/BuiltCanvas";
+import { canvasRuntimeErrorAnalytics } from "../freeform/canvasRuntimeError";
import { handleFreeformDataRequest } from "../freeform/freeformDataBridge";
import { usePinnedArtifact } from "../freeform/usePinnedArtifact";
@@ -58,6 +61,23 @@ export function ComponentFrame({ placement }: { placement: GridPlacement }) {
() => (placement.config as Record<string, unknown> | null) ?? undefined,
[placement.config],
);
+ const lastRuntimeErrorRef = useRef<string | null>(null);
+ const onError = useCallback(
+ (message: string) => {
+ if (message === lastRuntimeErrorRef.current) return;
+ lastRuntimeErrorRef.current = message;
+ track(ANALYTICS_EVENTS.CANVAS_RUNTIME_ERROR, {
+ dashboard_id: componentId,
+ build_id: artifact?.buildId,
+ ...canvasRuntimeErrorAnalytics(message),
+ });
+ },
+ [artifact?.buildId, componentId],
+ );
+ const onArtifactReady = useCallback(() => {
+ lastRuntimeErrorRef.current = null;
+ onReady();
+ }, [onReady]);
if (!artifact) {
// The lifecycle loaded and the pinned version has no artifact in it: build
@@ -128,8 +148,9 @@ export function ComponentFrame({ placement }: { placement: GridPlacement }) {
capabilities={capabilities}
config={config}
onDataRequest={onDataRequest}
- onReady={onReady}
- onRendered={onReady}
+ onError={onError}
+ onReady={onArtifactReady}
+ onRendered={onArtifactReady}
/>
);
}