Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
135 changes: 135 additions & 0 deletions apps/desktop/src/save-image.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
/*
Copyright 2026 New Vector Ltd.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should be your copyright, not that of the old name of our company


SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE files in the repository root for full details.
*/

import { expect, describe, it, beforeEach, vi, type Mock } from "vitest";
import { nativeImage, type Session } from "electron";
import fs from "node:fs";
import * as streamPromises from "node:stream/promises";

import { saveImageToFile, writeNativeImage } from "./save-image.js";

vi.mock("electron", () => ({
nativeImage: {
createFromDataURL: vi.fn(),
},
}));

vi.mock("node:fs", () => ({
default: {
createWriteStream: vi.fn(),
promises: {
writeFile: vi.fn(() => Promise.resolve()),
},
},
}));

vi.mock("node:stream/promises", () => ({
pipeline: vi.fn(() => Promise.resolve()),
}));

const createFromDataURL = vi.mocked(nativeImage.createFromDataURL);
const createWriteStream = vi.mocked(fs.createWriteStream);
const writeFile = vi.mocked(fs.promises.writeFile);
const pipeline = vi.mocked(streamPromises.pipeline);

/** A stub {@link NativeImage} exposing the encoder methods `writeNativeImage` selects between. */
function stubNativeImage(): { toPNG: Mock; toJPEG: Mock; toBitmap: Mock } {
return {
toPNG: vi.fn(() => Buffer.from("png")),
toJPEG: vi.fn(() => Buffer.from("jpeg")),
toBitmap: vi.fn(() => Buffer.from("bmp")),
};
}

/** A fake Electron {@link Session} exposing only the `fetch` method used by `saveImageToFile`. */
function fakeSession(fetchImpl: Mock): Session {
return { fetch: fetchImpl } as unknown as Session;
}

describe("save-image", () => {
beforeEach(() => {
vi.clearAllMocks();
createFromDataURL.mockReturnValue(stubNativeImage() as never);
createWriteStream.mockReturnValue({} as never);
});

describe("saveImageToFile", () => {
it("decodes a data: URL into a NativeImage and writes it without fetching", async () => {
const session = fakeSession(vi.fn());
const globalFetch = vi.spyOn(globalThis, "fetch");

await saveImageToFile("data:image/png;base64,AAAA", "/tmp/out.png", session);

expect(createFromDataURL).toHaveBeenCalledWith("data:image/png;base64,AAAA");
expect(writeFile).toHaveBeenCalledTimes(1);
expect(session.fetch).not.toHaveBeenCalled();
expect(globalFetch).not.toHaveBeenCalled();
});

it("fetches http(s) URLs through the injected session and pipes the body to disk", async () => {
const body = { kind: "stream" };
const fetchImpl = vi.fn(() => Promise.resolve({ ok: true, body }));
const session = fakeSession(fetchImpl);
const writeStream = { kind: "writeStream" };
createWriteStream.mockReturnValue(writeStream as never);
const globalFetch = vi.spyOn(globalThis, "fetch");

await saveImageToFile("https://hs.example/_matrix/media/v3/download/x/y", "/tmp/out.png", session);

// Regression assertion (#32362): the injected session fetch is used so the media-auth
// webRequest interceptors apply; the main-process global fetch must NOT be called.
expect(fetchImpl).toHaveBeenCalledWith("https://hs.example/_matrix/media/v3/download/x/y");
expect(globalFetch).not.toHaveBeenCalled();
expect(createWriteStream).toHaveBeenCalledWith("/tmp/out.png");
expect(pipeline).toHaveBeenCalledWith(body, writeStream);
});

it("throws when the session fetch responds with a non-ok status", async () => {
const fetchImpl = vi.fn(() => Promise.resolve({ ok: false, statusText: "Not Found" }));
const session = fakeSession(fetchImpl);

await expect(saveImageToFile("https://hs.example/image.png", "/tmp/out.png", session)).rejects.toThrow(
"unexpected response Not Found",
);
expect(pipeline).not.toHaveBeenCalled();
});

it("throws when the session fetch responds without a body", async () => {
const fetchImpl = vi.fn(() => Promise.resolve({ ok: true, body: null, statusText: "OK" }));
const session = fakeSession(fetchImpl);

await expect(saveImageToFile("https://hs.example/image.png", "/tmp/out.png", session)).rejects.toThrow(
"unexpected response has no body OK",
);
expect(pipeline).not.toHaveBeenCalled();
});
});

describe("writeNativeImage", () => {
it("encodes .jpg/.jpeg as JPEG", async () => {
const img = stubNativeImage();
await writeNativeImage("/tmp/out.jpg", img as never);
expect(img.toJPEG).toHaveBeenCalledWith(100);
expect(img.toPNG).not.toHaveBeenCalled();
expect(img.toBitmap).not.toHaveBeenCalled();
});

it("encodes .bmp as a bitmap", async () => {
const img = stubNativeImage();
await writeNativeImage("/tmp/out.bmp", img as never);
expect(img.toBitmap).toHaveBeenCalled();
expect(img.toPNG).not.toHaveBeenCalled();
});

it("encodes unknown extensions as PNG", async () => {
const img = stubNativeImage();
await writeNativeImage("/tmp/out.weird", img as never);
expect(img.toPNG).toHaveBeenCalled();
expect(img.toJPEG).not.toHaveBeenCalled();
});
});
});
52 changes: 52 additions & 0 deletions apps/desktop/src/save-image.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
Copyright 2026 New Vector Ltd.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ditto


SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE files in the repository root for full details.
*/

import { nativeImage, type NativeImage, type Session } from "electron";
import fs from "node:fs";
import { pipeline } from "node:stream/promises";

/**
* Writes an Electron {@link NativeImage} to disk, encoding it based on the target file extension.
* Falls back to PNG for unknown extensions.
*/
export function writeNativeImage(filePath: string, img: NativeImage): Promise<void> {
switch (filePath.split(".").pop()?.toLowerCase()) {
case "jpg":
case "jpeg":
return fs.promises.writeFile(filePath, img.toJPEG(100));
case "bmp":
return fs.promises.writeFile(filePath, img.toBitmap());
case "png":
default:
return fs.promises.writeFile(filePath, img.toPNG());
}
}

/**
* Saves an image to a file on disk.
*
* `data:` URLs are decoded directly into a {@link NativeImage}. Network (`http(s):`) URLs are
* fetched through the supplied Electron {@link Session} rather than Node's global `fetch`, so that
* the session's `webRequest` interceptors apply — in particular the authenticated-media handlers in
* `media-auth.ts` which rewrite the download URL and attach the `Authorization` header. Using the
* main-process global `fetch` bypasses those interceptors and fails with 401/404 on modern Synapse
* (authenticated media, MSC3916). See https://github.com/element-hq/element-web/issues/32362.
*
* @param url - the `data:` or `http(s):` URL of the image to save
* @param filePath - the destination path on disk
* @param session - the Electron session whose `webRequest` interceptors should apply to the fetch
*/
export async function saveImageToFile(url: string, filePath: string, session: Session): Promise<void> {
if (url.startsWith("data:")) {
await writeNativeImage(filePath, nativeImage.createFromDataURL(url));
} else {
const resp = await session.fetch(url);
if (!resp.ok) throw new Error(`unexpected response ${resp.statusText}`);
if (!resp.body) throw new Error(`unexpected response has no body ${resp.statusText}`);
await pipeline(resp.body, fs.createWriteStream(filePath));
}
}
27 changes: 2 additions & 25 deletions apps/desktop/src/webcontents-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,11 @@

import {
clipboard,
nativeImage,
Menu,
MenuItem,
shell,
dialog,
ipcMain,
type NativeImage,
type WebContents,
type ContextMenuParams,
type DownloadItem,
Expand All @@ -22,11 +20,10 @@
type Event,
} from "electron";
import url from "node:url";
import fs from "node:fs";
import { pipeline } from "node:stream/promises";
import path from "node:path";

import { _t } from "./language-helper.js";
import { saveImageToFile } from "./save-image.js";
import { getConfig } from "./config.js";

const MAILTO_PREFIX = "mailto:";
Expand Down Expand Up @@ -57,19 +54,6 @@
safeOpenURL(target);
}

function writeNativeImage(filePath: string, img: NativeImage): Promise<void> {
switch (filePath.split(".").pop()?.toLowerCase()) {
case "jpg":
case "jpeg":
return fs.promises.writeFile(filePath, img.toJPEG(100));
case "bmp":
return fs.promises.writeFile(filePath, img.toBitmap());
case "png":
default:
return fs.promises.writeFile(filePath, img.toPNG());
}
}

function onLinkContextMenu(ev: Event, params: ContextMenuParams, webContents: WebContents): void {
let url = params.linkURL || params.srcURL;

Expand Down Expand Up @@ -150,14 +134,7 @@
if (!filePath) return; // user cancelled dialog

try {
if (url.startsWith("data:")) {
await writeNativeImage(filePath, nativeImage.createFromDataURL(url));
} else {
const resp = await fetch(url);
if (!resp.ok) throw new Error(`unexpected response ${resp.statusText}`);
if (!resp.body) throw new Error(`unexpected response has no body ${resp.statusText}`);
await pipeline(resp.body, fs.createWriteStream(filePath));
}
await saveImageToFile(url, filePath, webContents.session);

Check warning on line 137 in apps/desktop/src/webcontents-handler.ts

View workflow job for this annotation

GitHub Actions / Tests

Uncovered Line

Line 137 is not covered by tests
} catch (err) {
console.error(err);
void dialog.showMessageBox({
Expand Down
Loading