: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(desktop): mobile scripted HTML artifact previews (#79505)
Tom Owers06e51660dc66
diff --git a/products/desktop/apps/mobile/src/features/tasks/components/ArtifactPreview.test.tsx b/products/desktop/apps/mobile/src/features/tasks/components/ArtifactPreview.test.tsxnew file mode 100644index 000000000000..74b909f31fd9--- /dev/null+++ b/products/desktop/apps/mobile/src/features/tasks/components/ArtifactPreview.test.tsx@@ -0,0 +1,195 @@+import type { TaskRunArtifact } from "@posthog/shared";+import { createElement } from "react";+import WebView from "react-native-webview";+import { act, create } from "react-test-renderer";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { ArtifactPreview } from "./ArtifactPreview";++const mockPreview = vi.fn();+const mockQuery = vi.fn();+const mockOpenExternalUrl = vi.hoisted(() => vi.fn());++vi.mock("../hooks/useCloudAttachmentPreview", () => ({+ useCloudAttachmentPreview: () => mockPreview(),+}));++vi.mock("@tanstack/react-query", () => ({+ useQuery: () => mockQuery(),+}));++vi.mock("react-native-webview", () => ({+ default: (props: Record<string, unknown>) => createElement("WebView", props),+}));++vi.mock("@/features/mcp/sandbox/mcpAppCsp", () => ({+ applyCspToHtml: (html: string) => `csp:${html}`,+}));++vi.mock("@/features/chat", () => ({+ MarkdownText: (props: Record<string, unknown>) =>+ createElement("MarkdownText", props),+}));++vi.mock("@/lib/openExternalUrl", () => ({+ openExternalUrl: mockOpenExternalUrl,+}));++vi.mock("@/lib/theme", () => ({+ useThemeColors: () => ({+ gray: { 9: "#999", 11: "#555", 12: "#111" },+ accent: { 9: "#f54d00" },+ }),+}));++// The global react-native mock renders Modal through a DOM portal that is a+// no-op under the node test env, so its children never mount. Substitute plain+// host elements for the components the preview uses so the body is inspectable.+vi.mock("react-native", () => {+ const host = (name: string) => (props: Record<string, unknown>) =>+ createElement(name, props);+ return {+ ActivityIndicator: host("ActivityIndicator"),+ Image: host("Image"),+ Modal: host("Modal"),+ Pressable: host("Pressable"),+ ScrollView: host("ScrollView"),+ Text: host("Text"),+ View: host("View"),+ };+});++function mount() {+ mockPreview.mockReturnValue({+ data: "https://s3.example/report.html",+ isLoading: false,+ });+ mockQuery.mockReturnValue({+ data: "<h1>hello</h1>",+ isLoading: false,+ isError: false,+ });+ let renderer: ReturnType<typeof create> | null = null;+ act(() => {+ renderer = create(+ createElement(ArtifactPreview, {+ taskId: "t1",+ runId: "r1",+ artifact: {+ id: "a1",+ name: "report.html",+ type: "output",+ } as TaskRunArtifact,+ onClose: vi.fn(),+ }),+ );+ });+ if (!renderer) throw new Error("Renderer not created");+ return renderer as ReturnType<typeof create>;+}++function webViews(renderer: ReturnType<typeof create>) {+ return renderer.root.findAll((node) => node.type === WebView);+}++describe("ArtifactPreview", () => {+ beforeEach(() => {+ mockOpenExternalUrl.mockClear();+ });++ it("runs HTML artifacts with scripts enabled and the CSP applied", () => {+ const renderer = mount();+ const rendered = webViews(renderer);+ expect(rendered).toHaveLength(1);+ expect(rendered[0].props.javaScriptEnabled).toBe(true);+ expect(rendered[0].props.setSupportMultipleWindows).toBe(false);+ const { html } = rendered[0].props.source;+ expect(html.startsWith("csp:")).toBe(true);+ expect(html).toContain("<h1>hello</h1>");+ // The media capture guard runs ahead of the artifact's own markup, since+ // mediaCapturePermissionGrantType below is an iOS-only prop.+ expect(html.indexOf("mediaDevices")).toBeLessThan(+ html.indexOf("<h1>hello</h1>"),+ );+ });++ it("keeps the sandbox sealed around the enabled scripts", () => {+ const webView = webViews(mount())[0].props;+ expect(webView.allowFileAccess).toBe(false);+ expect(webView.allowFileAccessFromFileURLs).toBe(false);+ expect(webView.allowUniversalAccessFromFileURLs).toBe(false);+ expect(webView.geolocationEnabled).toBe(false);+ expect(webView.mediaCapturePermissionGrantType).toBe("deny");+ // No bridge back into the app.+ expect(webView.onMessage).toBeUndefined();+ expect(webView.injectedJavaScript).toBeUndefined();+ });++ it("only lets the artifact's own document load in place", () => {+ const webView = webViews(mount())[0].props;+ expect(+ webView.onShouldStartLoadWithRequest({+ url: "about:blank",+ navigationType: "other",+ }),+ ).toBe(true);+ });++ it("denies navigation that is not a tapped web link", () => {+ const webView = webViews(mount())[0].props;+ for (const url of [+ "tel:+15550100",+ "sms:+15550100",+ "mailto:[email protected]",+ "itms-apps://apps.apple.com/app/id1",+ "myapp://do-thing",+ "data:text/html,<script></script>",+ "file:///etc/passwd",+ "https://evil.example",+ ]) {+ expect(+ webView.onShouldStartLoadWithRequest({ url, navigationType: "other" }),+ ).toBe(false);+ }+ // A non-web scheme is dropped even when it comes from a tap.+ expect(+ webView.onShouldStartLoadWithRequest({+ url: "myapp://do-thing",+ navigationType: "click",+ }),+ ).toBe(false);+ expect(mockOpenExternalUrl).not.toHaveBeenCalled();+ });++ it("opens a tapped web link externally instead of navigating", () => {+ const webView = webViews(mount())[0].props;+ expect(+ webView.onShouldStartLoadWithRequest({+ url: "https://posthog.com",+ navigationType: "click",+ }),+ ).toBe(false);+ expect(mockOpenExternalUrl).toHaveBeenCalledWith("https://posthog.com");+ });++ it("stops the preview by unmounting the web content and restarts it", () => {+ const renderer = mount();+ expect(webViews(renderer)).toHaveLength(1);++ const stop = renderer.root.findByProps({+ accessibilityLabel: "Stop preview",+ });+ act(() => {+ stop.props.onPress();+ });+ expect(webViews(renderer)).toHaveLength(0);+ expect(JSON.stringify(renderer.toJSON())).toContain("Preview stopped");++ const restart = renderer.root.findByProps({+ accessibilityLabel: "Restart preview",+ });+ act(() => {+ restart.props.onPress();+ });+ expect(webViews(renderer)).toHaveLength(1);+ });+});diff --git a/products/desktop/apps/mobile/src/features/tasks/components/ArtifactPreview.tsx b/products/desktop/apps/mobile/src/features/tasks/components/ArtifactPreview.tsxindex 1eeb2c8165c0..82d98f1bac99 100644--- a/products/desktop/apps/mobile/src/features/tasks/components/ArtifactPreview.tsx+++ b/products/desktop/apps/mobile/src/features/tasks/components/ArtifactPreview.tsx@@ -1,6 +1,13 @@import type { TaskRunArtifact } from "@posthog/shared";import { useQuery } from "@tanstack/react-query";-import { ArrowSquareOut, Warning, X } from "phosphor-react-native";+import {+ ArrowSquareOut,+ ArrowsClockwise,+ Stop,+ Warning,+ X,+} from "phosphor-react-native";+import { useMemo, useState } from "react";import {ActivityIndicator,Image,@@ -17,6 +24,10 @@ import { applyCspToHtml } from "@/features/mcp/sandbox/mcpAppCsp";import { openExternalUrl } from "@/lib/openExternalUrl";import { useThemeColors } from "@/lib/theme";import { useCloudAttachmentPreview } from "../hooks/useCloudAttachmentPreview";+import {+ denyMediaCapture,+ removeAutomaticRedirects,+} from "../utils/artifactHtml";import { artifactPreviewKind } from "../utils/artifactPreview";interface ArtifactPreviewProps {@@ -36,6 +47,7 @@ export function ArtifactPreview({const themeColors = useThemeColors();const name = artifact.name ?? "artifact";const kind = artifactPreviewKind(name);+ const [stopped, setStopped] = useState(false);const { data: url, isLoading: urlLoading } = useCloudAttachmentPreview(taskId,@@ -62,6 +74,20 @@ export function ArtifactPreview({});const loading = urlLoading || (needsText && textLoading);+ const htmlControlsVisible =+ kind === "html" && !!url && !textError && !loading;+ const previewControl = stopped+ ? {+ label: "Restart preview",+ Icon: ArrowsClockwise,+ onPress: () => setStopped(false),+ }+ : { label: "Stop preview", Icon: Stop, onPress: () => setStopped(true) };+ const html = useMemo(+ () =>+ applyCspToHtml(denyMediaCapture(removeAutomaticRedirects(text ?? ""))),+ [text],+ );return (<Modal@@ -78,6 +104,16 @@ export function ArtifactPreview({>{name}</Text>+ {htmlControlsVisible ? (+ <Pressable+ onPress={previewControl.onPress}+ hitSlop={8}+ className="active:opacity-60"+ accessibilityLabel={previewControl.label}+ >+ <previewControl.Icon size={20} color={themeColors.gray[12]} />+ </Pressable>+ ) : null}{url ? (<PressableonPress={() => openExternalUrl(url)}@@ -121,27 +157,48 @@ export function ArtifactPreview({><MarkdownText content={text ?? ""} disableRemoteImages /></ScrollView>+ ) : stopped ? (+ <PreviewStopped />) : (+ // Untrusted agent scripts run in the WebView's isolated web-content+ // process; keep it sealed. Do not add onMessage or injectedJavaScript+ // (a bridge back into the app). The rest of the props deny file and+ // device access, and the CSP applied above denies the network.+ // Two props below are iOS-only, and Android is covered elsewhere:+ // onFileDownload (Android keeps the library's own DownloadListener,+ // so downloads there are suppressed by the navigation gate rejecting+ // the http(s) request first) and mediaCapturePermissionGrantType+ // (denyMediaCapture strips the getUserMedia entry points out of the+ // document instead).<WebVieworiginWhitelist={["*"]}- source={{ html: applyCspToHtml(text ?? "") }}- // Untrusted agent output: no scripts, and the sandbox never- // navigates to a remote page. Only a genuine tap ("click") opens- // externally — automatic redirects (e.g. a <meta http-equiv=- // "refresh">) are dropped so previewing a file can't silently- // launch an attacker URL. The injected CSP blocks remote resource- // loads on top of that.- javaScriptEnabled={false}+ source={{ html }}+ javaScriptEnabledsetSupportMultipleWindows={false}+ allowFileAccess={false}+ allowFileAccessFromFileURLs={false}+ allowUniversalAccessFromFileURLs={false}+ geolocationEnabled={false}+ mediaPlaybackRequiresUserAction+ mediaCapturePermissionGrantType="deny"+ onFileDownload={() => {}}onShouldStartLoadWithRequest={(req) => {+ // Allowlist, so the boundary fails closed: with scripts enabled+ // an artifact can set location.href to any scheme without a+ // gesture, and tel:/sms:/mailto:/deep links hand off to another+ // app. source={{ html }} loads against the about:blank base URL,+ // which is the only navigation allowed to happen in place.+ if (req.url === "about:blank") return true;+ // A link activation leaves the preview and opens in the system+ // browser instead; everything else is dropped.if (- req.url.startsWith("http://") ||- req.url.startsWith("https://")+ req.navigationType === "click" &&+ (req.url.startsWith("http://") ||+ req.url.startsWith("https://"))) {- if (req.navigationType === "click") openExternalUrl(req.url);- return false;+ openExternalUrl(req.url);}- return true;+ return false;}}style={{ flex: 1, backgroundColor: "#fff" }}/>@@ -152,6 +209,16 @@ export function ArtifactPreview({);}+function PreviewStopped() {+ return (+ <View className="flex-1 items-center justify-center px-8">+ <Text className="text-center text-[14px] text-gray-11">+ Preview stopped. Restart it to run the HTML again.+ </Text>+ </View>+ );+}+function Unsupported({url,onShare,diff --git a/products/desktop/apps/mobile/src/features/tasks/utils/artifactHtml.test.ts b/products/desktop/apps/mobile/src/features/tasks/utils/artifactHtml.test.tsnew file mode 100644index 000000000000..ce8bef4a1727--- /dev/null+++ b/products/desktop/apps/mobile/src/features/tasks/utils/artifactHtml.test.ts@@ -0,0 +1,115 @@+import { describe, expect, it } from "vitest";+import { denyMediaCapture, removeAutomaticRedirects } from "./artifactHtml";++describe("removeAutomaticRedirects", () => {+ it.each([+ ['<meta http-equiv="refresh" content="0;url=https://evil.example">'],+ ['<META HTTP-EQUIV="REFRESH" CONTENT="5">'],+ ["<meta http-equiv='refresh' content='0'>"],+ ['<meta content="0;url=/next" http-equiv="refresh">'],+ ['<meta http-equiv = "refresh" content="0">'],+ ["<meta http-equiv=refresh content=0>"],+ ['<meta http-equiv="refresh" content="0"/>'],+ // A quoted ">" does not end the tag for an HTML tokenizer, so it must not+ // end it for this helper either.+ ['<meta title=">" http-equiv="refresh" content="0;url=/evil">'],+ ])("strips the auto-refresh meta %#", (meta) => {+ const html = `<!doctype html><html><head>${meta}<title>t</title></head><body><script>ok()</script></body></html>`;+ const result = removeAutomaticRedirects(html);+ expect(result.toLowerCase()).not.toContain("http-equiv");+ expect(result).toContain("<title>t</title>");+ expect(result).toContain("<script>ok()</script>");+ });++ it.each([+ ['<meta charset="utf-8">'],+ ['<meta http-equiv="content-type" content="text/html; charset=utf-8">'],+ ['<meta name="viewport" content="width=device-width, initial-scale=1">'],+ // http-equiv is read as an attribute, not matched as loose tag text, so a+ // value that merely mentions it is left alone.+ ['<meta name="note" content="http-equiv=refresh">'],+ ])("keeps non-refresh markup untouched %#", (meta) => {+ const html = `<!doctype html><head>${meta}</head>`;+ expect(removeAutomaticRedirects(html)).toBe(html);+ });++ it("strips every auto-refresh meta in the document", () => {+ const refresh = '<meta http-equiv="refresh" content="0">';+ const html = `<head><meta charset="utf-8">${refresh}${refresh}</head>`;+ expect(removeAutomaticRedirects(html)).toBe(+ '<head><meta charset="utf-8"></head>',+ );+ });+});++describe("denyMediaCapture", () => {+ // The guard is the whole output when there is no artifact markup to wrap.+ const guardScript = () => {+ const guard = denyMediaCapture("");+ return guard.slice("<script>".length, guard.length - "</script>".length);+ };++ it("runs the guard ahead of the artifact's own markup", () => {+ const result = denyMediaCapture("<body><script>ok()</script></body>");+ expect(result.indexOf("mediaDevices")).toBeLessThan(+ result.indexOf("<body>"),+ );+ });++ it("keeps the doctype first so the document stays out of quirks mode", () => {+ const result = denyMediaCapture("<!doctype html><html></html>");+ expect(result.startsWith("<!doctype html><script>")).toBe(true);+ expect(result.endsWith("<html></html>")).toBe(true);+ });++ it("removes the media capture entry points beyond recovery", () => {+ const fakeNavigator: Record<string, unknown> = {+ mediaDevices: { getUserMedia: () => undefined },+ getUserMedia: () => undefined,+ webkitGetUserMedia: () => undefined,+ mozGetUserMedia: () => undefined,+ };+ new Function("navigator", guardScript())(fakeNavigator);++ for (const key of [+ "mediaDevices",+ "getUserMedia",+ "webkitGetUserMedia",+ "mozGetUserMedia",+ ]) {+ expect(fakeNavigator[key]).toBeUndefined();+ // Non-writable and non-configurable, so artifact scripts cannot put the+ // API back once the guard has run.+ const descriptor = Object.getOwnPropertyDescriptor(fakeNavigator, key);+ expect(descriptor?.writable).toBe(false);+ expect(descriptor?.configurable).toBe(false);+ }+ });++ it("does not throw when an entry point is already missing", () => {+ const fakeNavigator: Record<string, unknown> = {};+ expect(() =>+ new Function("navigator", guardScript())(fakeNavigator),+ ).not.toThrow();+ expect(fakeNavigator.mediaDevices).toBeUndefined();+ });++ // Records the limitation documented in artifactHtml.ts as something the+ // suite states rather than a claim in a comment: the guard reaches one+ // realm's navigator, so a script that builds a fresh realm (an about:blank+ // iframe, which frame-src 'none' does not cover) finds an unpatched one+ // there. Closing that needs a native WebChromeClient denying+ // onPermissionRequest, not a bigger script.+ it("only covers the realm it runs in", () => {+ const topRealmNavigator: Record<string, unknown> = {+ mediaDevices: { getUserMedia: () => undefined },+ };+ const freshRealmNavigator: Record<string, unknown> = {+ mediaDevices: { getUserMedia: () => undefined },+ };+ new Function("navigator", guardScript())(topRealmNavigator);++ expect(topRealmNavigator.mediaDevices).toBeUndefined();+ expect(freshRealmNavigator.mediaDevices).toBeDefined();+ });+});diff --git a/products/desktop/apps/mobile/src/features/tasks/utils/artifactHtml.ts b/products/desktop/apps/mobile/src/features/tasks/utils/artifactHtml.tsnew file mode 100644index 000000000000..9a3f6f9eb017--- /dev/null+++ b/products/desktop/apps/mobile/src/features/tasks/utils/artifactHtml.ts@@ -0,0 +1,106 @@+// Mobile has no DOMParser, so this removes the meta tag at the string level+// rather than reusing the desktop DOM-based removal. The scan is attribute+// aware — a quoted ">" inside an attribute value does not end the tag, and+// http-equiv is read as a parsed attribute rather than matched as loose text —+// so it agrees with what an HTML tokenizer sees.++// Returns the index just past the ">" that closes the tag opened at `from`,+// skipping over quoted attribute values.+function tagEnd(html: string, from: number): number {+ let index = from;+ while (index < html.length) {+ const char = html[index];+ if (char === '"' || char === "'") {+ const closingQuote = html.indexOf(char, index + 1);+ // An unterminated quote swallows the rest of the document, exactly as a+ // tokenizer stuck in the attribute-value state would.+ if (closingQuote === -1) return html.length;+ index = closingQuote + 1;+ continue;+ }+ if (char === ">") return index + 1;+ index += 1;+ }+ return html.length;+}++const META_TAG = /<meta\b/gi;+const ATTRIBUTE = /([^\s/>=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]*)))?/g;++function isRefreshMeta(tag: string): boolean {+ ATTRIBUTE.lastIndex = "<meta".length;+ let attribute = ATTRIBUTE.exec(tag);+ while (attribute !== null) {+ const name = attribute[1].toLowerCase();+ const value = attribute[2] ?? attribute[3] ?? attribute[4] ?? "";+ if (name === "http-equiv" && value.trim().toLowerCase() === "refresh") {+ return true;+ }+ attribute = ATTRIBUTE.exec(tag);+ }+ return false;+}++export function removeAutomaticRedirects(html: string): string {+ META_TAG.lastIndex = 0;+ let kept = "";+ let copiedUpTo = 0;+ let stripped = false;+ let match = META_TAG.exec(html);+ while (match !== null) {+ const end = tagEnd(html, match.index + match[0].length);+ if (isRefreshMeta(html.slice(match.index, end))) {+ kept += html.slice(copiedUpTo, match.index);+ copiedUpTo = end;+ stripped = true;+ }+ META_TAG.lastIndex = end;+ match = META_TAG.exec(html);+ }+ return stripped ? kept + html.slice(copiedUpTo) : html;+}++// mediaCapturePermissionGrantType is an iOS-only prop. On Android+// react-native-webview's WebChromeClient grants a getUserMedia request whenever+// the host app already holds CAMERA or RECORD_AUDIO, which this app does for QR+// sign-in and voice input — so an artifact could otherwise reach the camera or+// microphone. Removing the entry points from the document is the only lever+// available without patching the library's native WebChromeClient, so treat it+// as defence in depth: a script that builds a fresh realm (an about:blank+// iframe, which frame-src 'none' does not cover) can still find an unpatched+// navigator. That gap cannot be closed from script — patching+// HTMLIFrameElement's contentWindow getter still leaves window[0], an+// unconfigurable WindowProxy index. Closing it properly means a native+// WebChromeClient whose onPermissionRequest denies RESOURCE_VIDEO_CAPTURE and+// RESOURCE_AUDIO_CAPTURE, i.e. a patch to react-native-webview, which affects+// every WebView in the app and so needs its own change.+const MEDIA_CAPTURE_GUARD = `<script>(function () {+ var hide = function (target, key) {+ try {+ Object.defineProperty(target, key, {+ value: undefined,+ writable: false,+ configurable: false,+ });+ } catch (error) {}+ };+ hide(navigator, "mediaDevices");+ hide(navigator, "getUserMedia");+ hide(navigator, "webkitGetUserMedia");+ hide(navigator, "mozGetUserMedia");+})();</script>`;++// Inserted after the doctype, which must stay first or the document drops into+// quirks mode. The parser hoists the script into <head>, ahead of the+// artifact's own markup, so it runs before any of the artifact's scripts.+export function denyMediaCapture(html: string): string {+ const doctype = html.match(/^\s*<!doctype[^>]*>/i);+ if (doctype) {+ return (+ html.slice(0, doctype[0].length) ++ MEDIA_CAPTURE_GUARD ++ html.slice(doctype[0].length)+ );+ }+ return MEDIA_CAPTURE_GUARD + html;+}