#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Send in-memory copies of every upload from Safari (#8802)
Anthony Stirling24ef9b8b88e1
diff --git a/frontend/src/editor/core/services/apiClient.ts b/frontend/src/editor/core/services/apiClient.tsindex 8c19f0113a..04a8ff2186 100644--- a/frontend/src/editor/core/services/apiClient.ts+++ b/frontend/src/editor/core/services/apiClient.ts@@ -2,6 +2,7 @@ import axios from "axios";import { handleHttpError } from "@editor/services/httpErrorHandler";import { setupApiInterceptors } from "@editor/services/apiClientSetup";import { getApiBaseUrl } from "@editor/services/apiClientConfig";+import { installInMemoryUploads } from "@editor/utils/inMemoryUpload";// Create axios instance with default configconst apiClient = axios.create({@@ -12,6 +13,7 @@ const apiClient = axios.create({// Setup interceptors (core does nothing, proprietary adds JWT auth)setupApiInterceptors(apiClient);+installInMemoryUploads(apiClient);// ---------- Install error interceptor ----------apiClient.interceptors.response.use(diff --git a/frontend/src/editor/core/utils/inMemoryUpload.test.ts b/frontend/src/editor/core/utils/inMemoryUpload.test.tsnew file mode 100644index 0000000000..ea754d03e2--- /dev/null+++ b/frontend/src/editor/core/utils/inMemoryUpload.test.ts@@ -0,0 +1,189 @@+// @vitest-environment node+import { afterEach, describe, expect, it, vi } from "vitest";+import axios, {+ AxiosHeaders,+ isCancel,+ type InternalAxiosRequestConfig,+} from "axios";+import {+ copyBudgetBytes,+ inMemoryFormData,+ installInMemoryUploads,+ uploadSafeFormData,+ uploadsNeedInMemoryFiles,+} from "@editor/utils/inMemoryUpload";++const SAFARI =+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Safari/605.1.15";+const CHROME =+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36";++function pdfForm(): { form: FormData; file: File } {+ const file = new File(["%PDF-1.7"], "a.pdf", { type: "application/pdf" });+ const form = new FormData();+ form.append("fileInput", file);+ form.append("angle", "90");+ return { form, file };+}++afterEach(() => {+ vi.unstubAllGlobals();+});++describe("uploadsNeedInMemoryFiles", () => {+ it.each([+ ["Safari", SAFARI, true],+ [+ "DuckDuckGo on macOS",+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Safari/605.1.15 Ddg/26.0",+ true,+ ],+ [+ "Chrome on iOS",+ "Mozilla/5.0 (iPhone; CPU iPhone OS 26_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/141.0 Mobile/15E148 Safari/604.1",+ true,+ ],+ ["Chrome", CHROME, false],+ [+ "Edge",+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36 Edg/141.0.0.0",+ false,+ ],+ [+ "Firefox",+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 15.0; rv:144.0) Gecko/20100101 Firefox/144.0",+ false,+ ],+ ])("%s → %s", (_browser, userAgent, expected) => {+ expect(uploadsNeedInMemoryFiles(userAgent)).toBe(expected);+ });+});++describe("copyBudgetBytes", () => {+ it("allows less on touch devices, where iOS kills tabs sooner", () => {+ expect(copyBudgetBytes(5)).toBeLessThan(copyBudgetBytes(0));+ });+});++describe("inMemoryFormData", () => {+ it("keeps every field and copies each file with its name and type", async () => {+ const { form, file } = pdfForm();+ const copy = await inMemoryFormData(form, 1024);+ const copied = copy.get("fileInput") as File;+ expect(copy.get("angle")).toBe("90");+ expect(copied).not.toBe(file);+ expect(copied.name).toBe("a.pdf");+ expect(copied.type).toBe("application/pdf");+ expect(await copied.text()).toBe("%PDF-1.7");+ });++ it("re-wraps files past the budget instead of copying them", async () => {+ const small = new File(["1234"], "small.pdf");+ const large = new File(["12345678"], "large.pdf", {+ type: "application/pdf",+ });+ const form = new FormData();+ form.append("fileInput", small);+ form.append("fileInput", large);+ const [copiedSmall, wrappedLarge] = (+ await inMemoryFormData(form, 10)+ ).getAll("fileInput") as File[];+ expect(await copiedSmall.text()).toBe("1234");+ expect(wrappedLarge).not.toBe(large);+ expect(wrappedLarge.name).toBe("large.pdf");+ expect(wrappedLarge.type).toBe("application/pdf");+ expect(await wrappedLarge.text()).toBe("12345678");+ });+});++describe("uploadSafeFormData", () => {+ it("returns the same form outside WebKit", async () => {+ vi.stubGlobal("navigator", { userAgent: CHROME, maxTouchPoints: 0 });+ const { form } = pdfForm();+ expect(await uploadSafeFormData(form)).toBe(form);+ });++ it("returns a copy in WebKit", async () => {+ vi.stubGlobal("navigator", { userAgent: SAFARI, maxTouchPoints: 0 });+ const { form, file } = pdfForm();+ const sent = await uploadSafeFormData(form);+ expect(sent).not.toBe(form);+ expect(sent.get("fileInput")).not.toBe(file);+ });+});++describe("installInMemoryUploads", () => {+ function fakeClient() {+ const use = vi.fn();+ return { client: { interceptors: { request: { use } } }, use };+ }++ it("installs nothing outside WebKit", () => {+ vi.stubGlobal("navigator", { userAgent: CHROME, maxTouchPoints: 0 });+ const { client, use } = fakeClient();+ installInMemoryUploads(client as never);+ expect(use).not.toHaveBeenCalled();+ });++ it("copies FormData bodies and leaves every other body alone in WebKit", async () => {+ vi.stubGlobal("navigator", { userAgent: SAFARI, maxTouchPoints: 0 });+ const { client, use } = fakeClient();+ installInMemoryUploads(client as never);+ const interceptor = use.mock.calls[0][0] as (+ config: InternalAxiosRequestConfig,+ ) => Promise<InternalAxiosRequestConfig>;++ const { form, file } = pdfForm();+ const sent = await interceptor({+ data: form,+ } as InternalAxiosRequestConfig);+ expect((sent.data as FormData).get("fileInput")).not.toBe(file);++ const json = { data: { a: 1 } } as InternalAxiosRequestConfig;+ expect(await interceptor(json)).toBe(json);+ });++ function safariInterceptor() {+ vi.stubGlobal("navigator", { userAgent: SAFARI, maxTouchPoints: 0 });+ const { client, use } = fakeClient();+ installInMemoryUploads(client as never);+ return use.mock.calls[0][0] as (+ config: InternalAxiosRequestConfig,+ ) => Promise<InternalAxiosRequestConfig>;+ }++ it("sends a retried request's copy as it is instead of copying it again", async () => {+ const interceptor = safariInterceptor();+ const sent = await interceptor({+ data: pdfForm().form,+ } as InternalAxiosRequestConfig);+ const retried = await interceptor(sent);+ expect(retried.data).toBe(sent.data);+ });++ it("rejects as cancelled without copying once the request's signal aborts", async () => {+ const interceptor = safariInterceptor();+ const controller = new AbortController();+ controller.abort();+ const { form, file } = pdfForm();+ const read = vi.spyOn(file, "arrayBuffer");+ const error = await interceptor({+ data: form,+ signal: controller.signal,+ headers: new AxiosHeaders(),+ }).catch((e: unknown) => e);+ expect(isCancel(error)).toBe(true);+ expect(read).not.toHaveBeenCalled();+ });++ it("rejects as cancelled once the request's cancel token fires", async () => {+ const interceptor = safariInterceptor();+ const source = axios.CancelToken.source();+ source.cancel();+ const error = await interceptor({+ data: pdfForm().form,+ cancelToken: source.token,+ } as InternalAxiosRequestConfig).catch((e: unknown) => e);+ expect(isCancel(error)).toBe(true);+ });+});diff --git a/frontend/src/editor/core/utils/inMemoryUpload.ts b/frontend/src/editor/core/utils/inMemoryUpload.tsnew file mode 100644index 0000000000..b420d9d335--- /dev/null+++ b/frontend/src/editor/core/utils/inMemoryUpload.ts@@ -0,0 +1,123 @@+import {+ CanceledError,+ type AxiosInstance,+ type InternalAxiosRequestConfig,+} from "axios";++/**+ * Works around WebKit sending a File as an empty request body (Content-Length: 0), which the+ * backend reports as "unexpected EOF in PREAMBLE". It hits files restored from IndexedDB and+ * files picked from disk alike, in Safari and in every browser built on WebKit: DuckDuckGo on+ * macOS and all iOS browsers. An in-memory copy of the bytes always uploads. Fixed upstream in+ * WebKit 323318@main (https://bugs.webkit.org/show_bug.cgi?id=319985); harmless once fixed,+ * since a copy is an ordinary in-memory file.+ */++const DESKTOP_COPY_BUDGET_BYTES = 512 * 1024 * 1024;+// iOS kills a tab well short of 1 GB on many devices, and the copy sits beside the original.+const TOUCH_COPY_BUDGET_BYTES = 192 * 1024 * 1024;++const inMemoryCopies = new WeakSet<FormData>();++export function uploadsNeedInMemoryFiles(userAgent: string): boolean {+ return /AppleWebKit/.test(userAgent) && !/Chrome\//.test(userAgent);+}++/** iPadOS reports a desktop Safari user agent, so touch support is what tells it apart. */+export function copyBudgetBytes(maxTouchPoints: number): number {+ return maxTouchPoints > 1+ ? TOUCH_COPY_BUDGET_BYTES+ : DESKTOP_COPY_BUDGET_BYTES;+}++/**+ * A copy of `form` with files read into memory, in entry order, until their combined size would+ * pass `budgetBytes`. Files past the budget are re-wrapped instead of copied: the WebKit bug+ * thread reports a fresh File over the same bytes uploading correctly, which costs no memory but+ * has not been confirmed here. String fields are kept as they are.+ */+export async function inMemoryFormData(+ form: FormData,+ budgetBytes: number,+ throwIfCancelled: () => void = () => {},+): Promise<FormData> {+ const copy = new FormData();+ let remaining = budgetBytes;+ for (const [key, value] of form.entries()) {+ throwIfCancelled();+ if (typeof value === "string") {+ copy.append(key, value);+ continue;+ }+ const options = { type: value.type, lastModified: value.lastModified };+ if (value.size > remaining) {+ copy.append(+ key,+ new File([value.slice(0, value.size, value.type)], value.name, options),+ );+ continue;+ }+ remaining -= value.size;+ copy.append(+ key,+ new File([await value.arrayBuffer()], value.name, options),+ );+ }+ throwIfCancelled();+ inMemoryCopies.add(copy);+ return copy;+}++function thisBrowserNeedsInMemoryFiles(): boolean {+ return (+ typeof navigator !== "undefined" &&+ uploadsNeedInMemoryFiles(navigator.userAgent)+ );+}++function inMemoryFormDataForThisDevice(+ form: FormData,+ throwIfCancelled?: () => void,+): Promise<FormData> {+ return inMemoryFormData(+ form,+ copyBudgetBytes(navigator.maxTouchPoints ?? 0),+ throwIfCancelled,+ );+}++function throwIfRequestCancelled(config: InternalAxiosRequestConfig): void {+ config.cancelToken?.throwIfRequested();+ if (config.signal?.aborted) throw new CanceledError(undefined, config);+}++/**+ * The form to send from this browser: `form` itself outside WebKit, otherwise its in-memory copy.+ * For uploads that bypass the API clients, such as a raw `fetch`.+ */+export async function uploadSafeFormData(form: FormData): Promise<FormData> {+ return thisBrowserNeedsInMemoryFiles()+ ? inMemoryFormDataForThisDevice(form)+ : form;+}++/**+ * Makes every FormData request `client` sends upload-safe. Installs nothing outside WebKit, so+ * other browsers keep streaming the original file. Install it last: axios runs the most recently+ * added request interceptor first, so the copy is in place before auth or any other interceptor.+ */+export function installInMemoryUploads(+ client: Pick<AxiosInstance, "interceptors">,+): void {+ if (!thisBrowserNeedsInMemoryFiles()) return;+ client.interceptors.request.use(async (config) =>+ config.data instanceof FormData && !inMemoryCopies.has(config.data)+ ? {+ ...config,+ data: await inMemoryFormDataForThisDevice(config.data, () =>+ throwIfRequestCancelled(config),+ ),+ }+ : config,+ );+}diff --git a/frontend/src/editor/proprietary/components/chat/ChatContext.tsx b/frontend/src/editor/proprietary/components/chat/ChatContext.tsxindex de00606393..3fbe648d4d 100644--- a/frontend/src/editor/proprietary/components/chat/ChatContext.tsx+++ b/frontend/src/editor/proprietary/components/chat/ChatContext.tsx@@ -28,6 +28,7 @@ import {type StirlingFileStub,} from "@editor/types/fileContext";import type { ToolOperation } from "@editor/types/file";+import { uploadSafeFormData } from "@editor/utils/inMemoryUpload";export enum ChatRole {USER = "user",@@ -589,7 +590,7 @@ export function ChatProvider({ children }: { children: ReactNode }) {`${await getAiBaseUrl()}/api/v1/ai/orchestrate/stream`,{method: "POST",- body: formData,+ body: await uploadSafeFormData(formData),headers: await getAuthHeaders(),credentials: "include",signal: controller.signal,diff --git a/frontend/src/editor/proprietary/components/workflow/ParticipantView.tsx b/frontend/src/editor/proprietary/components/workflow/ParticipantView.tsxindex 5da919b4a1..e8d32a7bdb 100644--- a/frontend/src/editor/proprietary/components/workflow/ParticipantView.tsx+++ b/frontend/src/editor/proprietary/components/workflow/ParticipantView.tsx@@ -17,6 +17,7 @@ import { useParticipantSession } from "@editor/hooks/workflow/useParticipantSessimport { Icon } from "@editor/ui/Icon";import { PrivateContent } from "@editor/components/shared/PrivateContent";import { privateContentClassName } from "@editor/components/shared/privateContentClassName";+import { uploadSafeFormData } from "@editor/utils/inMemoryUpload";interface ParticipantViewProps {token: string;}@@ -85,7 +86,7 @@ const ParticipantView: React.FC<ParticipantViewProps> = ({ token }) => {"/api/v1/workflow/participant/validate-certificate",{method: "POST",- body: formData,+ body: await uploadSafeFormData(formData),},);const data = await res.json();diff --git a/frontend/src/editor/saas/services/apiClient.ts b/frontend/src/editor/saas/services/apiClient.tsindex f29d9b220f..ee3da91d01 100644--- a/frontend/src/editor/saas/services/apiClient.ts+++ b/frontend/src/editor/saas/services/apiClient.ts@@ -8,6 +8,7 @@ import {} from "@editor/services/paygErrorInterceptor";import { redirectToLogin } from "@editor/auth/redirectToLogin";import { getBrowserId } from "@editor/utils/browserIdentifier";+import { installInMemoryUploads } from "@editor/utils/inMemoryUpload";// Helper: decode base64url JWT payload safelyfunction decodeJwtPayload(token: string): Record<string, unknown> | null {@@ -93,6 +94,8 @@ apiClient.interceptors.request.use(},);+installInMemoryUploads(apiClient);+// Endpoints whose 401s must never trigger the hard redirect to /login. Prefix// matching covers the whole public surface (/api/v1/config/* and /api/v1/info/*// are permitAll on the backend), and crucially includes background pings like