-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Fetch authenticated media through the session for "Save image as" #33997
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
hayaksi1
wants to merge
1
commit into
element-hq:develop
Choose a base branch
from
hayaksi1:pr/desktop-save-image-authed
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+189
−25
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| /* | ||
| Copyright 2026 New Vector Ltd. | ||
|
|
||
| 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(); | ||
| }); | ||
| }); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| /* | ||
| Copyright 2026 New Vector Ltd. | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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)); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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