Skip to content
TypeScript

fix(web): copy and save images embedded as data URLs (#23621)

Kayzelb0aa468aa18c
diff --git a/apps/web/src/components/media/mediaContent.test.ts b/apps/web/src/components/media/mediaContent.test.ts
new file mode 100644
index 00000000000..fb95a7e0eac
--- /dev/null
+++ b/apps/web/src/components/media/mediaContent.test.ts
@@ -0,0 +1,57 @@
+import { expect, it, vi } from "vite-plus/test";
+
+import { readMediaPng } from "./mediaContent";
+
+const PNG_BYTES = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
+
+it("copies a data URL image without fetching it", async () => {
+ // The desktop renderer's connect-src rejects data: URLs the way fetch rejects a CORS failure.
+ using fetch = vi.spyOn(globalThis, "fetch").mockRejectedValue(new TypeError("Failed to fetch"));
+ const src = `data:image/png;base64,${btoa(String.fromCharCode(...PNG_BYTES))}`;
+
+ const png = await readMediaPng(src);
+
+ expect(fetch).not.toHaveBeenCalled();
+ expect(png.type).toBe("image/png");
+ expect([...new Uint8Array(await png.arrayBuffer())]).toEqual(PNG_BYTES);
+});
+
+it("decodes percent-escaped bytes in a non-base64 data URL", async () => {
+ const escaped = PNG_BYTES.map((byte) => `%${byte.toString(16).padStart(2, "0")}`).join("");
+ const src = `data:image/png,${escaped}`;
+
+ const png = await readMediaPng(src);
+
+ expect([...new Uint8Array(await png.arrayBuffer())]).toEqual(PNG_BYTES);
+});
+
+it("accepts any case in the scheme and base64 marker, and escapes in base64", async () => {
+ const base64 = btoa(String.fromCharCode(...PNG_BYTES)).replaceAll("=", "%3D");
+
+ const png = await readMediaPng(`DATA:image/png;BASE64,${base64}`);
+
+ expect([...new Uint8Array(await png.arrayBuffer())]).toEqual(PNG_BYTES);
+});
+
+it("ignores the URL fragment when decoding a data URL", async () => {
+ const src = `data:image/png;base64,${btoa(String.fromCharCode(...PNG_BYTES))}#preview`;
+
+ const png = await readMediaPng(src);
+
+ expect([...new Uint8Array(await png.arrayBuffer())]).toEqual(PNG_BYTES);
+});
+
+it.each(["data:image/png;base64,%%%", "data:image/png"])(
+ "reports malformed inline media: %s",
+ async (src) => {
+ await expect(readMediaPng(src)).rejects.toThrow("This inline media could not be decoded.");
+ },
+);
+
+it("keeps remote media on the fetch path", async () => {
+ const png = new Blob([new Uint8Array(PNG_BYTES)], { type: "image/png" });
+ using fetch = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(png));
+
+ expect(await readMediaPng("https://example.com/image.png")).toEqual(png);
+ expect(fetch).toHaveBeenCalledWith("https://example.com/image.png");
+});
diff --git a/apps/web/src/components/media/mediaContent.ts b/apps/web/src/components/media/mediaContent.ts
index 7c3128ca28e..4b1edab6a3d 100644
--- a/apps/web/src/components/media/mediaContent.ts
+++ b/apps/web/src/components/media/mediaContent.ts
@@ -6,7 +6,42 @@ export function resolveProtocolRelativeMediaUrl(src: string): string {
return `${protocol}${src}`;
}
+// Data URL escapes are raw bytes, not UTF-8, so `%89` must stay one byte.
+function decodePercentBytes(payload: string) {
+ const encoder = new TextEncoder();
+ return Uint8Array.from(
+ payload
+ .split(/(%[0-9a-f]{2})/i)
+ .flatMap((part) =>
+ /^%[0-9a-f]{2}$/i.test(part)
+ ? [Number.parseInt(part.slice(1), 16)]
+ : [...encoder.encode(part)],
+ ),
+ );
+}
+
+/** Decodes inline media locally; desktop connect-src omits `data:`, so fetch() cannot read it. */
+function readDataUrlBlob(src: string): Blob {
+ // A fragment is never part of the payload; a literal `#` in data must be escaped as `%23`.
+ const url = src.split("#", 1)[0] ?? src;
+ const comma = url.indexOf(",");
+ const [mimeType = "", ...parameters] = url.slice("data:".length, comma).split(";");
+ const payload = url.slice(comma + 1);
+ try {
+ if (comma < 0) throw new Error("Missing data URL payload.");
+ const isBase64 = parameters.some((parameter) => parameter.trim().toLowerCase() === "base64");
+ // Base64 text is ASCII, so any escape that is not valid UTF-8 is malformed anyway.
+ const bytes = isBase64
+ ? Uint8Array.from(atob(decodeURIComponent(payload)), (char) => char.charCodeAt(0))
+ : decodePercentBytes(payload);
+ return new Blob([bytes], { type: mimeType || "text/plain" });
+ } catch (cause) {
+ throw new Error("This inline media could not be decoded.", { cause });
+ }
+}
+
async function readMediaBlob(src: string): Promise<Blob> {
+ if (/^data:/i.test(src)) return readDataUrlBlob(src);
let response: Response;
try {
response = await fetch(src);