Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: offer a per-canvas network grant when the offline CSP blocks a preview (#8262)
Nilaya43c81d529fc
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex c3945b0c13e..094ccf8b26c 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -2241,11 +2241,24 @@ _ARTIFACT_PREVIEW_FRAME_HTML = """<!doctype html>installStorageFallback("localStorage");installStorageFallback("sessionStorage");};+ // Stamp the load this frame was served for. A report still in flight+ // when the canvas is swapped would otherwise be read as the new one's.+ const loadVersion = new URLSearchParams(location.search).get("v") || "";+ const reportBlocked = (event) => {+ parent.postMessage({+ type: "unsloth:artifact-blocked",+ blockedURI: event.blockedURI || "",+ effectiveDirective: event.effectiveDirective || "",+ v: loadVersion,+ }, "*");+ };const render = (html) => {installStorageFallbacks();document.open();document.write(html);document.close();+ // document.open() drops listeners bound before it, so rebind here.+ document.addEventListener("securitypolicyviolation", reportBlocked, true);};installStorageFallbacks();window.addEventListener("message", (event) => {diff --git a/studio/backend/tests/test_artifact_preview_frame_csp.py b/studio/backend/tests/test_artifact_preview_frame_csp.pyindex 9ede57ecba9..81b1278b9e6 100644--- a/studio/backend/tests/test_artifact_preview_frame_csp.py+++ b/studio/backend/tests/test_artifact_preview_frame_csp.py@@ -44,3 +44,81 @@ def test_the_sandbox_holds_in_both_variants():assert "base-uri 'none';" in cspassert "form-action 'none';" in cspassert "frame-ancestors 'self'" in csp+++def test_the_shell_reports_blocked_resources():+ shell = inf_mod._ARTIFACT_PREVIEW_FRAME_HTML+ assert '"unsloth:artifact-blocked"' in shell+ # document.close() drops listeners bound before it, so binding earlier+ # reports nothing and the banner never appears.+ write, listen = (+ shell.index("document.close();"),+ shell.index('document.addEventListener("securitypolicyviolation"'),+ )+ assert write < listen+++def test_blocked_reports_carry_the_load_they_came_from():+ # event.source survives the swap navigation, so without the stamp a report+ # from the outgoing canvas reads as the incoming one's and prompts a grant+ # for a canvas that never hit the CSP. Read once at load, not per report,+ # so a rewritten document cannot forge a different one.+ shell = inf_mod._ARTIFACT_PREVIEW_FRAME_HTML+ assert 'get("v")' in shell+ assert "v: loadVersion," in shell+ read, report = (+ shell.index("const loadVersion"),+ shell.index("const reportBlocked"),+ )+ assert read < report+++def _directives(csp: str) -> dict:+ out = {}+ for part in csp.split(";"):+ part = part.strip()+ if not part:+ continue+ name, _, value = part.partition(" ")+ out[name] = value.strip()+ return out+++def test_the_shell_reports_which_directive_was_violated():+ # Without it the banner cannot tell a blocked CDN script from an object-src+ # violation, and offers a grant that cannot fix the latter.+ shell = inf_mod._ARTIFACT_PREVIEW_FRAME_HTML+ assert "effectiveDirective: event.effectiveDirective" in shell+++def test_the_grant_widens_everything_but_the_locked_directives():+ # Pins GRANT_CANNOT_FIX in html-frame.tsx: lock a fourth directive down in+ # both policies and this fails, rather than the banner silently starting to+ # prompt for something the grant cannot fix.+ strict = _directives(inf_mod._ARTIFACT_PREVIEW_FRAME_STRICT_CSP)+ network = _directives(inf_mod._ARTIFACT_PREVIEW_FRAME_NETWORK_CSP)+ unchanged = {+ name for name, value in strict.items() if name in network and network[name] == value+ }+ # frame-ancestors and sandbox are not resource loads, so they never report.+ assert unchanged == {"object-src", "base-uri", "form-action", "frame-ancestors", "sandbox"}+ for locked in ("object-src", "base-uri", "form-action"):+ assert network[locked] == "'none'"+++def test_the_permissive_policy_widens_every_hostless_scheme_but_one():+ # Pins GRANT_CANNOT_FIX_SCHEME in html-frame.tsx. A non-HTTP(S) violation+ # reports a bare scheme, so the banner may only offer the grant where the+ # permissive policy actually allows that scheme for that directive. Verified+ # in Chromium: a data: Worker reports worker-src/data under both policies.+ network = _directives(inf_mod._ARTIFACT_PREVIEW_FRAME_NETWORK_CSP)+ # Locked or not a resource load, so they never reach the scheme check.+ skip = {"object-src", "base-uri", "form-action", "frame-ancestors", "sandbox"}+ gaps = {+ name: scheme+ for name, value in network.items()+ if name not in skip+ for scheme in ("data:", "blob:")+ if scheme not in value.split()+ }+ assert gaps == {"worker-src": "data:"}diff --git a/studio/frontend/src/features/chat/artifacts/html-frame.tsx b/studio/frontend/src/features/chat/artifacts/html-frame.tsxindex d0e41768aee..f50ebca421b 100644--- a/studio/frontend/src/features/chat/artifacts/html-frame.tsx+++ b/studio/frontend/src/features/chat/artifacts/html-frame.tsx@@ -3,6 +3,8 @@"use client";+import { Button } from "@/components/ui/button";+import { useT } from "@/i18n";import { apiUrl } from "@/lib/api-base";import { cn } from "@/lib/utils";import { useCallback, useEffect, useMemo, useRef, useState } from "react";@@ -11,6 +13,63 @@ import { hashArtifactCode } from "./types";const HTML_FRAME_DEFAULT_HEIGHT = 400;const HTML_FRAME_MAX_HEIGHT = 900;+const BLOCKED_HOSTS_SHOWN = 3;+// Entries are per URL, not per host, so a page pulling a whole CDN directory+// counts each file. Still far above what a real one trips.+const BLOCKED_URIS_TRACKED = 100;+// A report carries the full URL, so this is generous next to a real one, and it+// bounds both the stored string and the host derived from it.+const BLOCKED_URI_MAX_CHARS = 2048;++// The only directives the network CSP leaves at 'none'. Kept in step by+// test_the_grant_widens_everything_but_the_locked_directives, which fails if+// the two policies stop differing exactly outside this set.+const GRANT_CANNOT_FIX = new Set(["object-src", "base-uri", "form-action"]);++// A hostless blockedURI is a bare scheme, and the permissive policy widens every+// one of them but this: its worker-src is `http: https: blob:`, with no data:,+// so a data: Worker stays blocked after the grant. Kept in step by+// test_the_permissive_policy_widens_every_hostless_scheme_but_one.+const GRANT_CANNOT_FIX_SCHEME: Record<string, string> = { "worker-src": "data" };++type BlockedState = { code: string; uris: string[]; hosts: string[] };++const NOTHING_BLOCKED: BlockedState = { code: "", uris: [], hosts: [] };++// Reports from before a swap belong to the old canvas, so start over rather+// than append. The cap is checked BEFORE the duplicate scan, so past it a+// canvas posting unique URIs cannot make the parent rescan every stored string;+// returning `current` unchanged lets React bail out of the re-render too.+function appendBlocked(+ current: BlockedState,+ code: string,+ uri: string,+ host: string,+): BlockedState {+ const mine = current.code === code ? current : { code, uris: [], hosts: [] };+ if (mine.uris.length >= BLOCKED_URIS_TRACKED || mine.uris.includes(uri)) {+ return mine === current ? current : mine;+ }+ return {+ code,+ uris: [...mine.uris, uri],+ hosts: mine.hosts.includes(host) ? mine.hosts : [...mine.hosts, host],+ };+}++// A non-HTTP(S) violation reports a bare token ("eval", "blob"), which the+// permissive CSP widens too. Dropping those left the canvas blank with no+// prompt, so label them with the token itself.+const BLOCKED_KEYWORD = /^[a-z-]+$/;++function blockedHost(uri: string): string | null {+ if (BLOCKED_KEYWORD.test(uri)) return uri;+ try {+ return new URL(uri).host || null;+ } catch {+ return null;+ }+}export type ArtifactViewMode = "preview" | "source";export const ARTIFACT_VIEW_MODES: readonly ArtifactViewMode[] = [@@ -41,21 +100,42 @@ export function ArtifactHtmlFrame({className?: string;fill?: boolean;}) {+ const t = useT();const iframeRef = useRef<HTMLIFrameElement>(null);- // Every canvas honors this, fence or tool. Off by default, and the only gate.+ // Every canvas honors this, fence or tool. Off by default; the standing half+ // of the gate, alongside the per-canvas grant below.const networkAccessEnabled = useChatRuntimeStore((state) => state.allowArtifactNetworkAccess,);const [height, setHeight] = useState(HTML_FRAME_DEFAULT_HEIGHT);+ // Carries the code it was reported for, so a canvas swapped in place cannot+ // inherit the previous one's banner. Clearing it from the [src] effect ran a+ // render too late, and that stale render is the one carrying the button.+ const [blocked, setBlocked] = useState<BlockedState>({+ code,+ uris: [],+ hosts: [],+ });+ const blockedForCanvas = blocked.code === code ? blocked : NOTHING_BLOCKED;+ // Granted by the banner button alone, and only for the code on screen when it+ // was clicked; nothing the canvas sends may set it, or a blocked page could+ // talk its way onto the network. Compared during render rather than reset in+ // an effect, which runs after the DOM is updated and so would let the first+ // render carrying new code reuse the previous canvas' allow_network=1.+ const [grantedCode, setGrantedCode] = useState<string | null>(null);+ const grantedForCanvas = grantedCode === code;+ const networkAllowed = networkAccessEnabled || grantedForCanvas;const artifactHtml = useMemo(() => buildArtifactSrcDoc(code), [code]);+ // Identifies this load to the frame, which stamps its blocked reports with it.+ const codeVersion = useMemo(() => hashArtifactCode(code), [code]);const src = useMemo(() => {- const query = new URLSearchParams({ v: hashArtifactCode(code) });+ const query = new URLSearchParams({ v: codeVersion });// Never put the auth token in the URL: in-frame code can read location.href.- if (networkAccessEnabled) {+ if (networkAllowed) {query.set("allow_network", "1");}return apiUrl(`/api/inference/artifact-preview-frame?${query.toString()}`);- }, [networkAccessEnabled, code]);+ }, [networkAllowed, codeVersion]);// Feed only parent-initiated loads, so a self-navigated frame can't self-upgrade.const pendingPostRef = useRef(false);useEffect(() => {@@ -76,6 +156,32 @@ export function ArtifactHtmlFrame({const handler = (event: MessageEvent) => {if (event.source !== iframeRef.current?.contentWindow) return;if (event.origin !== "null") return;+ if (event.data?.type === "unsloth:artifact-blocked") {+ // event.source survives the swap navigation, so without the frame's+ // stamp a report from the outgoing canvas would be tagged with the+ // incoming code and prompt a grant for a canvas that never hit the CSP.+ if (event.data.v !== codeVersion) return;+ const uri = event.data.blockedURI;+ // A report carries the full URL, and the canvas can post these directly+ // rather than going through the CSP. The entry cap bounds how many are+ // kept but not their size, so a handful could park megabytes otherwise.+ if (typeof uri !== "string" || uri.length > BLOCKED_URI_MAX_CHARS) {+ return;+ }+ // The grant cannot fix these three, and prompting anyway widens the+ // policy for nothing, then hides the banner because the grant is on,+ // leaving a broken canvas and no way back to the prompt.+ if (GRANT_CANNOT_FIX.has(event.data.effectiveDirective)) return;+ // Same dead end one scheme down: the grant widens worker-src to blob:+ // but not data:, so a data: Worker reports under both policies.+ if (GRANT_CANNOT_FIX_SCHEME[event.data.effectiveDirective] === uri) {+ return;+ }+ const host = blockedHost(uri);+ if (!host) return;+ setBlocked((current) => appendBlocked(current, code, uri, host));+ return;+ }if (typeof event.data?.chatArtifactHeight !== "number") return;setHeight(Math.min(@@ -86,18 +192,50 @@ export function ArtifactHtmlFrame({};window.addEventListener("message", handler);return () => window.removeEventListener("message", handler);- }, [postArtifactHtml]);+ // `code`/`codeVersion` are listed so the handler always closes over the+ // canvas on screen, rather than relying on postArtifactHtml changing.+ }, [postArtifactHtml, code, codeVersion]);++ const showBlockedBanner = !networkAllowed && blockedForCanvas.uris.length > 0;+ const shownHosts = blockedForCanvas.hosts+ .slice(0, BLOCKED_HOSTS_SHOWN)+ .join(", ");+ const blockedFrom =+ blockedForCanvas.hosts.length > BLOCKED_HOSTS_SHOWN+ ? `${shownHosts}…`+ : shownHosts;return (- <iframe- ref={iframeRef}- src={src}- sandbox="allow-scripts"- referrerPolicy="no-referrer"- onLoad={postArtifactHtml}- className={cn("block w-full border-0 bg-background", className)}- style={{ height: fill ? "100%" : height }}- title={title}- />+ <div className={cn("relative", fill ? "h-full" : undefined)}>+ <iframe+ ref={iframeRef}+ src={src}+ sandbox="allow-scripts"+ referrerPolicy="no-referrer"+ onLoad={postArtifactHtml}+ className={cn("block w-full border-0 bg-background", className)}+ style={{ height: fill ? "100%" : height }}+ title={title}+ />+ {showBlockedBanner ? (+ <div className="absolute inset-x-0 bottom-0 flex flex-wrap items-center justify-between gap-2 border-t bg-background/95 px-3 py-2 text-xs backdrop-blur">+ <span className="text-muted-foreground">+ {t(+ blockedForCanvas.uris.length === 1+ ? "settings.chat.artifacts.blockedBanner"+ : "settings.chat.artifacts.blockedBannerPlural",+ { count: blockedForCanvas.uris.length, hosts: blockedFrom },+ )}+ </span>+ <Button+ size="sm"+ variant="outline"+ onClick={() => setGrantedCode(code)}+ >+ {t("settings.chat.artifacts.blockedBannerAction")}+ </Button>+ </div>+ ) : null}+ </div>);}diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex 6af97686066..012443f7326 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -898,6 +898,9 @@ export const ar = {allowNetworkAccess: "السماح بوصول Canvas إلى الشبكة",allowNetworkAccessDescription:"اسمح لمعاينات Canvas بتحميل النصوص البرمجية والأنماط والخطوط والوسائط وموارد الشبكة من شبكات CDN. أبقِه معطّلاً للمعاينات دون اتصال بالكامل.",+ blockedBanner: "تم حظر {count} مورد خارجي من {hosts}.",+ blockedBannerPlural: "تم حظر {count} موارد خارجية من {hosts}.",+ blockedBannerAction: "السماح لهذا الـ Canvas",},data: "البيانات",exportHistory: "تصدير سجل المحادثات",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex 63de4631956..8f05c2231ec 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -931,6 +931,9 @@ export const de = {allowNetworkAccess: "Netzwerkzugriff für Canvas erlauben",allowNetworkAccessDescription:"Erlaubt Canvas-Vorschauen, Skripte, Stile, Schriftarten, Medien und Netzwerkressourcen von CDNs zu laden. Für vollständig offline nutzbare Vorschauen deaktiviert lassen.",+ blockedBanner: "{count} externe Ressource von {hosts} blockiert.",+ blockedBannerPlural: "{count} externe Ressourcen von {hosts} blockiert.",+ blockedBannerAction: "Für dieses Canvas erlauben",},data: "Daten",exportHistory: "Chatverlauf exportieren",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 15e4eecce68..478fedc2ebf 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -891,6 +891,9 @@ export const en = {allowNetworkAccess: "Allow canvas network access",allowNetworkAccessDescription:"Let canvas previews load scripts, styles, fonts, media, and network resources from CDNs. Keep off for fully offline previews.",+ blockedBanner: "Blocked {count} external resource from {hosts}.",+ blockedBannerPlural: "Blocked {count} external resources from {hosts}.",+ blockedBannerAction: "Allow for this canvas",},data: "Data",exportHistory: "Export chat history",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex c804a06237d..8fd68b9c3cf 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -922,6 +922,9 @@ export const es = {allowNetworkAccess: "Permitir acceso de red en Canvas",allowNetworkAccessDescription:"Permite que las vistas previas de Canvas carguen scripts, estilos, fuentes, medios y recursos de red desde CDNs. Mantenlo desactivado para vistas previas totalmente sin conexión.",+ blockedBanner: "Se bloqueó {count} recurso externo de {hosts}.",+ blockedBannerPlural: "Se bloquearon {count} recursos externos de {hosts}.",+ blockedBannerAction: "Permitir en este Canvas",},data: "Datos",exportHistory: "Exportar historial de chat",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex 64c6393f983..e965a830a31 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -928,6 +928,9 @@ export const fr = {allowNetworkAccess: "Autoriser l'accès réseau du canvas",allowNetworkAccessDescription:"Permettre aux aperçus Canvas de charger des scripts, des styles, des polices, des médias et d'autres ressources depuis des CDN. Laissez cette option désactivée pour des aperçus entièrement hors ligne.",+ blockedBanner: "{count} ressource externe bloquée depuis {hosts}.",+ blockedBannerPlural: "{count} ressources externes bloquées depuis {hosts}.",+ blockedBannerAction: "Autoriser pour ce Canvas",},data: "Données",exportHistory: "Exporter l'historique des discussions",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 02168000a1c..9f2effeb5c8 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -904,6 +904,9 @@ export const hi = {allowNetworkAccess: "canvas नेटवर्क एक्सेस की अनुमति दें",allowNetworkAccessDescription:"canvas पूर्वावलोकन को CDN से स्क्रिप्ट, स्टाइल, फ़ॉन्ट, मीडिया, और नेटवर्क संसाधन लोड करने दें। पूरी तरह ऑफ़लाइन पूर्वावलोकन के लिए बंद रखें।",+ blockedBanner: "{hosts} से {count} बाहरी संसाधन अवरुद्ध किया गया।",+ blockedBannerPlural: "{hosts} से {count} बाहरी संसाधन अवरुद्ध किए गए।",+ blockedBannerAction: "इस Canvas के लिए अनुमति दें",},data: "डेटा",exportHistory: "चैट इतिहास एक्सपोर्ट करें",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex 2e1c412fba6..bc1aac5934b 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -898,6 +898,9 @@ export const it = {allowNetworkAccess: "Consenti a Canvas di accedere alla rete",allowNetworkAccessDescription:"Consenti alle anteprime di Canvas di caricare script, stili, font, contenuti multimediali e risorse di rete dalle CDN. Lascia l'opzione disattivata per anteprime completamente offline.",+ blockedBanner: "Bloccata {count} risorsa esterna da {hosts}.",+ blockedBannerPlural: "Bloccate {count} risorse esterne da {hosts}.",+ blockedBannerAction: "Consenti per questo Canvas",},data: "Dati",exportHistory: "Esporta la cronologia delle chat",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex 97bda39a814..9a1fd6b9a54 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -884,6 +884,9 @@ export const ja = {"Canvas モードでは完全な HTML を自動的に折りたたみます。Canvas がオフのときも、コードフェンスで囲まれた HTML ドキュメントを折りたたむには、この設定をオンにします。",allowNetworkAccess: "Canvas のネットワークアクセスを許可",allowNetworkAccessDescription: "CanvasのプレビューがCDNからスクリプト、スタイル、フォント、メディア、ネットワークリソースを読み込むことを許可します。完全にオフラインでプレビューする場合はオフのままにしてください。",+ blockedBanner: "{hosts} からの外部リソース {count} 件をブロックしました。",+ blockedBannerPlural: "{hosts} からの外部リソース {count} 件をブロックしました。",+ blockedBannerAction: "この Canvas で許可",},data: "データ",exportHistory: "チャット履歴をエクスポート",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex 89051d7dfcd..dbef42db5c9 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -896,6 +896,9 @@ export const ko = {allowNetworkAccess: "Canvas 네트워크 접근 허용",allowNetworkAccessDescription:"Canvas 미리보기가 CDN에서 스크립트, 스타일, 폰트, 미디어 및 네트워크 리소스를 불러올 수 있게 합니다. 완전한 오프라인 미리보기를 위해서는 꺼 두세요.",+ blockedBanner: "{hosts}의 외부 리소스 {count}개를 차단했습니다.",+ blockedBannerPlural: "{hosts}의 외부 리소스 {count}개를 차단했습니다.",+ blockedBannerAction: "이 Canvas에서 허용",},data: "데이터",exportHistory: "채팅 기록 내보내기",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex 96cefd9cdf2..d2bf9282409 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -910,6 +910,9 @@ export const ptBR = {allowNetworkAccess: "Permitir acesso à rede no canvas",allowNetworkAccessDescription:"Permite que as pré-visualizações do canvas carreguem scripts, estilos, fontes, mídia e recursos de rede de CDNs. Mantenha desativado para pré-visualizações totalmente offline.",+ blockedBanner: "{count} recurso externo de {hosts} bloqueado.",+ blockedBannerPlural: "{count} recursos externos de {hosts} bloqueados.",+ blockedBannerAction: "Permitir neste Canvas",},data: "Dados",exportHistory: "Exportar histórico de chat",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 4a2ac3a13e0..33084f4dab4 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -908,6 +908,9 @@ export const ru = {allowNetworkAccess: "Разрешить сетевой доступ Canvas",allowNetworkAccessDescription:"Позволяет предпросмотрам Canvas загружать скрипты, стили, шрифты, медиа и сетевые ресурсы из CDN. Оставьте выключенным для полностью офлайн-предпросмотров.",+ blockedBanner: "Заблокирован {count} внешний ресурс с {hosts}.",+ blockedBannerPlural: "Заблокировано внешних ресурсов: {count} с {hosts}.",+ blockedBannerAction: "Разрешить для этого Canvas",},data: "Данные",exportHistory: "Экспортировать историю чатов",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex cfe84b9af3b..f89306ac45b 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -873,6 +873,9 @@ export const zhCN = {allowNetworkAccess: "允许 Canvas 访问网络",allowNetworkAccessDescription:"允许 Canvas 预览从 CDN 加载脚本、样式、字体、媒体和网络资源。若需完全离线预览请保持关闭。",+ blockedBanner: "已阻止来自 {hosts} 的 {count} 个外部资源。",+ blockedBannerPlural: "已阻止来自 {hosts} 的 {count} 个外部资源。",+ blockedBannerAction: "允许此 Canvas",},data: "数据",exportHistory: "导出聊天记录",diff --git a/studio/frontend/tests/artifact-frame-network-access.test.ts b/studio/frontend/tests/artifact-frame-network-access.test.tsindex de9cafa2cfb..ee754d19fe4 100644--- a/studio/frontend/tests/artifact-frame-network-access.test.ts+++ b/studio/frontend/tests/artifact-frame-network-access.test.ts@@ -43,8 +43,7 @@ function readFrameOpeningTags(): string[] {// The bug: a fenced html block is source "fence", so gating on "tool" left every// fenced canvas on the strict CSP and a CDN import (three.js) silently died.-// Every call site is checked, so a source-gated one cannot hide behind an-// ungated one that happens to be visited later.+// Every call site is checked, so a source-gated one cannot hide behind another.test("no canvas preview is gated on the artifact source", () => {const tags = readFrameOpeningTags();assert.ok(@@ -77,12 +76,287 @@ function readAllowNetworkGuards(): string[] {return conditions;}-// The permissive CSP is opt-in, and that setting is the whole gate. Asserting the-// condition exactly is the point: a second operand is how the gate gets defeated-// (an || that short-circuits past it, or a source check smuggled back in), and-// there is no legitimate reason for one here.-test("the permissive CSP is gated on the user's network setting alone", () => {+// These two operands are the whole gate: the persistent setting, or a grant the+// user clicked for this canvas. Asserting the condition exactly is the point,+// since a third operand is how the gate gets defeated.+test("the permissive CSP is gated on the setting or a per-canvas grant", () => {const conditions = readAllowNetworkGuards();assert.equal(conditions.length, 1, "expected exactly one allow_network guard");- assert.equal(conditions[0], "networkAccessEnabled");+ assert.equal(conditions[0], "networkAllowed");+});++test("the gate is exactly the setting or the per-canvas grant", () => {+ assert.equal(+ readConst("networkAllowed"),+ "networkAccessEnabled || grantedForCanvas",+ );+});++/** Initializer of a `const` declared in the frame, by name. */+function readConst(name: string): string {+ const source = sourceFile(FRAME);+ let text: string | undefined;+ const visit = (node: ts.Node): void => {+ if (+ ts.isVariableDeclaration(node) &&+ node.name.getText() === name &&+ node.initializer+ ) {+ text = node.initializer.getText();+ }+ node.forEachChild(visit);+ };+ source.forEachChild(visit);+ assert.ok(text, `${name} not found in the frame`);+ return text;+}++// The banner's only call to action is the grant, so one that survives it prompts+// for something already on. The blocked list stays in the condition too, or+// every offline canvas gets a banner.+test("the blocked banner is hidden once network access is on", () => {+ const condition = readConst("showBlockedBanner");+ assert.match(condition, /!networkAllowed/);+ assert.match(condition, /blockedForCanvas\.uris\.length > 0/);+});++// The button grants network to the CURRENT code, so a banner left over from a+// swapped-out canvas is a grant for one that reported nothing. Derived during+// render: the [src] effect that used to clear it ran a render too late, and+// that stale render is the one carrying the button.+test("the blocked banner is tied to the canvas that reported it", () => {+ assert.equal(+ readConst("blockedForCanvas"),+ "blocked.code === code ? blocked : NOTHING_BLOCKED",+ );+});++// The old clear was a wholesale `setBlocked({...})` in the [src] effect, a+// render too late. Every write goes through an updater that carries the code+// forward, so no reset can reintroduce the stale-banner window.+test("no write resets the blocked list wholesale", () => {+ const source = sourceFile(FRAME);+ const args: ts.Node[] = [];+ const visit = (node: ts.Node): void => {+ if (+ ts.isCallExpression(node) &&+ node.expression.getText() === "setBlocked" &&+ node.arguments[0]+ ) {+ args.push(node.arguments[0]);+ }+ node.forEachChild(visit);+ };+ source.forEachChild(visit);+ assert.ok(args.length > 0, "setBlocked is never called");+ for (const argument of args) {+ assert.ok(+ ts.isArrowFunction(argument) || ts.isFunctionExpression(argument),+ "setBlocked must take an updater, not a replacement object",+ );+ }+});++const GRANT_SETTER = /\bsetGranted\w*\(/;++/** Arguments of every `setGrantedCode(...)` call, with the enclosing JSX handler. */+function readGrantCalls(): { argument: string; handler: string | null }[] {+ const source = sourceFile(FRAME);+ const calls: { argument: string; handler: string | null }[] = [];+ const visit = (node: ts.Node): void => {+ if (+ ts.isCallExpression(node) &&+ node.expression.getText() === "setGrantedCode"+ ) {+ let handler: string | null = null;+ for (let at: ts.Node = node; at.parent; at = at.parent) {+ if (ts.isJsxAttribute(at.parent)) {+ handler = at.parent.name.getText();+ break;+ }+ }+ calls.push({ argument: node.arguments[0]?.getText() ?? "", handler });+ }+ node.forEachChild(visit);+ };+ source.forEachChild(visit);+ return calls;+}++// The canvas is what reports being blocked, so the grant must never be reachable+// from that path or a page could post its way onto the network. Only a JSX click+// handler may grant, and it stores the code it was clicked for.+test("only a click can grant the per-canvas exception", () => {+ const calls = readGrantCalls();+ assert.ok(calls.length > 0, "setGrantedCode is never called");+ for (const { argument, handler } of calls) {+ assert.equal(argument, "code", "the grant stores the current code");+ assert.equal(handler, "onClick", "the grant must come from a click handler");+ }+});++// A new canvas is new untrusted code, so the grant must not carry over. The tie+// has to be compared during render: an effect resetting it on [code] runs after+// React updated the DOM, so canvas B's first render still had A's grant.+test("the per-canvas grant is tied to the code it was granted for", () => {+ assert.equal(readConst("grantedForCanvas"), "grantedCode === code");+});++test("no effect resets the grant, which would leave a stale render", () => {+ const source = sourceFile(FRAME);+ let resetInEffect = false;+ const visit = (node: ts.Node): void => {+ if (+ ts.isCallExpression(node) &&+ node.expression.getText() === "useEffect" &&+ GRANT_SETTER.test(node.arguments[0]?.getText() ?? "")+ ) {+ resetInEffect = true;+ }+ node.forEachChild(visit);+ };+ source.forEachChild(visit);+ assert.ok(!resetInEffect, "the grant must not be reset from an effect");+});++const DIRECTIVE_FILTER =+ /GRANT_CANNOT_FIX\.has\(event\.data\.effectiveDirective\)/;+const SCHEME_FILTER =+ /GRANT_CANNOT_FIX_SCHEME\[event\.data\.effectiveDirective\] === uri/;+const URI_LENGTH_GUARD = /uri\.length > BLOCKED_URI_MAX_CHARS/;+const URI_CAP = /\buris\.length >= BLOCKED_URIS_TRACKED/;+const URI_DUPLICATE = /\buris\.includes\(uri\)/;+const BAILS_OUT = /\bcurrent\b/;++/** Body of a function declared in the frame, by name. */+function readFunctionBody(name: string): string {+ const source = sourceFile(FRAME);+ let text: string | undefined;+ const visit = (node: ts.Node): void => {+ if (+ ts.isFunctionDeclaration(node) &&+ node.name?.getText() === name &&+ node.body+ ) {+ text = node.body.getText();+ }+ node.forEachChild(visit);+ };+ source.forEachChild(visit);+ if (!text) throw new Error(`${name} not found in the frame`);+ return text;+}++// event.source survives the swap navigation and the handler closes over the NEW+// code, so an in-flight report from the outgoing canvas would be stored as the+// incoming one's. The frame stamps each report with the load it came from.+test("blocked reports from a stale frame load are rejected", () => {+ const source = sourceFile(FRAME);+ let guarded = false;+ const visit = (node: ts.Node): void => {+ if (+ ts.isIfStatement(node) &&+ /event\.data\.v !== codeVersion/.test(node.expression.getText()) &&+ node.thenStatement.getText().includes("return")+ ) {+ guarded = true;+ }+ node.forEachChild(visit);+ };+ source.forEachChild(visit);+ assert.ok(guarded, "reports are not matched against the current load");+});++// The entry cap bounds how many reports are kept, not how big each one is, and+// the canvas can post these directly rather than going through the CSP. Without+// this a handful parks megabytes of parent state; it bounds the host too, which+// is derived from the URI.+test("oversized blocked URIs are dropped before anything is stored", () => {+ const source = sourceFile(FRAME);+ let bounded = false;+ const visit = (node: ts.Node): void => {+ if (+ ts.isIfStatement(node) &&+ URI_LENGTH_GUARD.test(node.expression.getText()) &&+ node.thenStatement.getText().includes("return")+ ) {+ bounded = true;+ }+ node.forEachChild(visit);+ };+ source.forEachChild(visit);+ assert.ok(bounded, "an oversized blockedURI is not rejected");+});++// A non-HTTP(S) violation reports a bare token, not a URL: eval() reports+// "eval" and a blob Worker reports "blob" (verified in Chromium). new URL() has+// no host for either, so they were dropped and a canvas broken only by those+// stayed blank, even though the permissive CSP widens both.+test("a hostless blocked URI still reaches the banner", () => {+ assert.match(readFunctionBody("blockedHost"), /BLOCKED_KEYWORD\.test\(uri\)/);+ assert.equal(readConst("BLOCKED_KEYWORD"), "/^[a-z-]+$/");+});++// ...but only where the grant widens that scheme for that directive. The+// permissive worker-src is `http: https: blob:`, so a data: Worker reports under+// both policies (verified in Chromium) and the grant is a dead end: it widens+// the policy for nothing, then hides the banner because networkAllowed is true.+test("the grant is not offered for a scheme it cannot widen", () => {+ assert.equal(+ readConst("GRANT_CANNOT_FIX_SCHEME"),+ '{ "worker-src": "data" }',+ );+ const source = sourceFile(FRAME);+ let filtered = false;+ const visit = (node: ts.Node): void => {+ if (+ ts.isIfStatement(node) &&+ SCHEME_FILTER.test(node.expression.getText()) &&+ node.thenStatement.getText().includes("return")+ ) {+ filtered = true;+ }+ node.forEachChild(visit);+ };+ source.forEachChild(visit);+ assert.ok(filtered, "reports are not filtered by blocked scheme");+});++// These three stay at 'none' in the permissive policy, so the grant cannot fix+// them and prompting widens the policy for nothing. The backend counterpart+// asserts they are exactly what the two policies agree on, so the set cannot+// drift.+test("the grant is not offered for directives it cannot fix", () => {+ assert.equal(+ readConst("GRANT_CANNOT_FIX"),+ 'new Set(["object-src", "base-uri", "form-action"])',+ );+ const source = sourceFile(FRAME);+ let filtered = false;+ const visit = (node: ts.Node): void => {+ if (+ ts.isIfStatement(node) &&+ DIRECTIVE_FILTER.test(node.expression.getText()) &&+ node.thenStatement.getText().includes("return")+ ) {+ filtered = true;+ }+ node.forEachChild(visit);+ };+ source.forEachChild(visit);+ assert.ok(filtered, "reports are not filtered by effective directive");+});++// The canvas picks the blocked URIs, so an uncapped list is memory growth and a+// parent re-render per message, both driven from inside the sandbox. The cap is+// checked BEFORE the duplicate scan so past it the work is O(1) too.+test("blocked-resource state is capped against the untrusted canvas", () => {+ const updater = readFunctionBody("appendBlocked");+ assert.match(updater, URI_CAP);+ assert.match(updater, URI_DUPLICATE);+ assert.ok(+ updater.search(URI_CAP) < updater.search(URI_DUPLICATE),+ "the cap must be checked before the duplicate scan",+ );+ assert.match(updater, BAILS_OUT);});