Skip to content

Build your personal knowledge base with Trilium Notes

fix(mobile): let scripts POST to custom request handlers (regression of #11310)

Elian Dorancb11a2f5615d
diff --git a/apps/standalone/src/native-request-bridge.spec.ts b/apps/standalone/src/native-request-bridge.spec.ts
index 07ab4aec9e..dae11ac560 100644
--- a/apps/standalone/src/native-request-bridge.spec.ts
+++ b/apps/standalone/src/native-request-bridge.spec.ts
@@ -8,7 +8,7 @@ const mocks = vi.hoisted(() => ({
vi.mock("./local-bridge.js", () => ({
localFetch: (request: Request) => mocks.localFetch(request),
- isLocalApiRequest: (url: URL) => url.pathname.startsWith("/api/") || url.pathname.startsWith("/share/")
+ isLocalApiRequest: (url: URL) => ["/api/", "/share/", "/custom/"].some((prefix) => url.pathname.startsWith(prefix))
}));
interface Channel {
@@ -36,6 +36,7 @@ afterEach(() => {
delete bridgeWindow.webkit;
delete bridgeWindow.__triliumNativeRequest;
vi.restoreAllMocks();
+ vi.unstubAllGlobals();
});
/** Installs the bridge, forwards one request, and returns every message the page sent back. */
@@ -154,4 +155,31 @@ describe("installNativeRequestBridge", () => {
const rejected = await forward({ id: 7, url: "https://localhost/api/notes" });
expect(rejected).toEqual([{ type: "error", id: 7, message: "closed" }]);
});
+
+ it("sends a script's local POST to localFetch with its body, since the native side cannot read it", async () => {
+ const networkFetch = vi.fn(async () => new Response("POST cannot be answered natively", { status: 405 }));
+ vi.stubGlobal("fetch", networkFetch);
+ mocks.localFetch.mockResolvedValue(Response.json({ ok: true }));
+ installNativeRequestBridge();
+
+ const response = await window.fetch("/custom/srs?action=rate", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ noteId: "abc", quality: 3 })
+ });
+
+ expect(networkFetch).not.toHaveBeenCalled();
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual({ ok: true });
+ const request: Request = mocks.localFetch.mock.calls[0][0];
+ expect(request.method).toBe("POST");
+ expect(new URL(request.url).pathname).toBe("/custom/srs");
+ expect(await request.json()).toEqual({ noteId: "abc", quality: 3 });
+
+ await window.fetch("/custom/srs?action=getDue");
+ await window.fetch("https://example.com/custom/srs", { method: "POST", body: "x" });
+ await window.fetch("/assets/upload", { method: "POST", body: "x" });
+ expect(networkFetch).toHaveBeenCalledTimes(3);
+ expect(mocks.localFetch).toHaveBeenCalledTimes(1);
+ });
});
diff --git a/apps/standalone/src/native-request-bridge.ts b/apps/standalone/src/native-request-bridge.ts
index 674c42d451..35fcd578bb 100644
--- a/apps/standalone/src/native-request-bridge.ts
+++ b/apps/standalone/src/native-request-bridge.ts
@@ -18,7 +18,9 @@ import { toBase64 } from "./services/capacitor_download.js";
* - `{"type":"end","id"}` once the body is complete, or `{"type":"error","id","message"}`.
*
* Android's `shouldInterceptRequest` exposes no request body, so both platforms forward only GET
- * and HEAD; a request with a body goes through `standaloneApi.localFetch`.
+ * and HEAD. A local request with any other method goes through `standaloneApi.localFetch`: the
+ * client's `server.ts` calls it directly, and `window.fetch` is wrapped so a script's
+ * `fetch("/custom/…", { method: "POST" })` reaches it too.
*
* Returns whether a native channel was found; without one the page registers its service worker.
*/
@@ -33,6 +35,7 @@ export function installNativeRequestBridge(): boolean {
bridgeWindow.__triliumNativeRequest = (request) => {
void answer(channel, request);
};
+ routeLocalRequestBodiesToWorker();
// The native side holds every request it intercepted until this arrives.
channel.postMessage(JSON.stringify({ type: "ready" }));
return true;
@@ -104,6 +107,23 @@ async function answer(channel: RequestChannel, request: NativeRequest) {
}
}
+/**
+ * Wraps `window.fetch` so a same-origin local request with a method the native side does not
+ * forward goes to `localFetch()` with its body, as it did through the service worker.
+ */
+function routeLocalRequestBodiesToWorker() {
+ const networkFetch = window.fetch.bind(window);
+ window.fetch = (input, init) => {
+ const request = new Request(input, init);
+ const url = new URL(request.url);
+ if (request.method === "GET" || request.method === "HEAD"
+ || url.origin !== location.origin || !isLocalApiRequest(url)) {
+ return networkFetch(input, init);
+ }
+ return localFetch(request);
+ };
+}
+
/**
* Neither native response type carries a 3xx (`WebResourceResponse` rejects one, a
* `WKURLSchemeTask` cannot redirect), so a redirect (the share pages issue them) becomes a page