Skip to content

Build your personal knowledge base with Trilium Notes

perf(sync): stream mobile pull responses through a native WebView proxy

Elian Doran33f860197af8
diff --git a/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/MainActivity.java b/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/MainActivity.java
index 3e60011cbc..930d7c568a 100644
--- a/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/MainActivity.java
+++ b/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/MainActivity.java
@@ -19,7 +19,11 @@ public class MainActivity extends BridgeActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
+ // Custom plugins must be registered before super.onCreate() initializes the bridge.
+ registerPlugin(TriliumHttp.class);
super.onCreate(savedInstanceState);
+ // Streaming HTTP proxy for the sync worker (see TriliumWebViewClient).
+ getBridge().setWebViewClient(new TriliumWebViewClient(getBridge()));
enableEdgeToEdge();
forwardInsetsToWebView();
applySystemBarsAppearance();
diff --git a/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/TriliumHttp.java b/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/TriliumHttp.java
new file mode 100644
index 0000000000..1fa7141db4
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/TriliumHttp.java
@@ -0,0 +1,151 @@
+package org.triliumnotes.trilium;
+
+import android.text.TextUtils;
+import android.util.Base64;
+
+import com.getcapacitor.JSObject;
+import com.getcapacitor.Plugin;
+import com.getcapacitor.PluginCall;
+import com.getcapacitor.PluginMethod;
+import com.getcapacitor.annotation.CapacitorPlugin;
+import com.getcapacitor.plugin.util.CapacitorHttpUrlConnection;
+
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+/**
+ * Minimal HTTP plugin used by the sync worker instead of CapacitorHttp.
+ *
+ * CapacitorHttp force-parses any response whose Content-Type is application/json into an
+ * org.json object tree and then re-serializes it into the bridge message ("backward
+ * compatibility" branch in HttpRequestHandler.readData), ignoring the requested
+ * responseType. For multi-megabyte sync pull responses that costs two full JSON passes and
+ * hundreds of thousands of short-lived Java objects per request — measured at ~60% of a CPU
+ * core for the duration of an initial sync. This plugin performs the same request via
+ * CapacitorHttpUrlConnection but always returns the body as a single string (or base64 for
+ * binary), leaving JSON parsing to the web worker that actually consumes it.
+ */
+@CapacitorPlugin(name = "TriliumHttp")
+public class TriliumHttp extends Plugin {
+
+ private static final int CONNECT_TIMEOUT_MS = 30_000;
+ // The JS side enforces its own (configurable) sync timeout; this is only a backstop so a
+ // dead connection cannot pin a native thread forever.
+ private static final int READ_TIMEOUT_MS = 600_000;
+
+ private ExecutorService executor;
+
+ @Override
+ public void load() {
+ executor = Executors.newCachedThreadPool();
+ super.load();
+ }
+
+ @Override
+ protected void handleOnDestroy() {
+ super.handleOnDestroy();
+ if (executor != null) {
+ executor.shutdownNow();
+ }
+ }
+
+ @PluginMethod
+ public void request(final PluginCall call) {
+ if (executor == null || executor.isShutdown()) {
+ call.reject("Failed to execute request - TriliumHttp plugin was shut down");
+ return;
+ }
+
+ executor.submit(() -> {
+ try {
+ call.resolve(doRequest(call));
+ } catch (Exception e) {
+ call.reject(e.getLocalizedMessage(), e.getClass().getSimpleName(), e);
+ }
+ });
+ }
+
+ private JSObject doRequest(PluginCall call) throws Exception {
+ String urlString = call.getString("url");
+ if (urlString == null) {
+ throw new IllegalArgumentException("url is required");
+ }
+ String method = call.getString("method", "GET").toUpperCase();
+ JSObject headers = call.getObject("headers", new JSObject());
+ String body = call.getString("data");
+ String responseType = call.getString("responseType", "text");
+
+ URL url = new URL(urlString);
+ CapacitorHttpUrlConnection connection = new CapacitorHttpUrlConnection((HttpURLConnection) url.openConnection());
+
+ try {
+ connection.setAllowUserInteraction(false);
+ connection.setRequestMethod(method);
+ connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
+ connection.setReadTimeout(READ_TIMEOUT_MS);
+ connection.setRequestHeaders(headers);
+ connection.setSSLSocketFactory(getBridge());
+
+ if (body != null && !"GET".equals(method) && !"HEAD".equals(method)) {
+ connection.setDoOutput(true);
+ try (OutputStream os = connection.getHttpConnection().getOutputStream()) {
+ os.write(body.getBytes(StandardCharsets.UTF_8));
+ }
+ }
+
+ connection.connect();
+
+ int status = connection.getResponseCode();
+
+ JSObject responseHeaders = new JSObject();
+ for (Map.Entry<String, List<String>> entry : connection.getHttpConnection().getHeaderFields().entrySet()) {
+ // The status line arrives as a header with a null key — skip it.
+ if (entry.getKey() != null) {
+ responseHeaders.put(entry.getKey(), TextUtils.join(", ", entry.getValue()));
+ }
+ }
+
+ InputStream stream = connection.getErrorStream();
+ if (stream == null) {
+ stream = connection.getInputStream();
+ }
+
+ String data;
+ if (stream == null) {
+ data = "";
+ } else if ("arraybuffer".equals(responseType) || "blob".equals(responseType)) {
+ data = Base64.encodeToString(readFully(stream), Base64.NO_WRAP);
+ } else {
+ data = new String(readFully(stream), StandardCharsets.UTF_8);
+ }
+
+ JSObject result = new JSObject();
+ result.put("status", status);
+ result.put("headers", responseHeaders);
+ result.put("data", data);
+ return result;
+ } finally {
+ connection.disconnect();
+ }
+ }
+
+ private static byte[] readFully(InputStream stream) throws Exception {
+ try (InputStream in = stream) {
+ ByteArrayOutputStream out = new ByteArrayOutputStream(64 * 1024);
+ byte[] buffer = new byte[64 * 1024];
+ int read;
+ while ((read = in.read(buffer)) != -1) {
+ out.write(buffer, 0, read);
+ }
+ return out.toByteArray();
+ }
+ }
+}
diff --git a/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/TriliumWebViewClient.java b/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/TriliumWebViewClient.java
new file mode 100644
index 0000000000..69e77a75c5
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/TriliumWebViewClient.java
@@ -0,0 +1,214 @@
+package org.triliumnotes.trilium;
+
+import android.net.Uri;
+import android.text.TextUtils;
+import android.util.Log;
+import android.webkit.WebResourceRequest;
+import android.webkit.WebResourceResponse;
+import android.webkit.WebView;
+
+import com.getcapacitor.Bridge;
+import com.getcapacitor.BridgeWebViewClient;
+
+import java.io.ByteArrayInputStream;
+import java.io.FilterInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+/**
+ * WebViewClient that adds a streaming same-origin HTTP proxy for the sync worker.
+ *
+ * A plugin-based transport (TriliumHttp/CapacitorHttp) has to hold the entire response body
+ * in Java as a string, escape it into the bridge message envelope and copy it across the
+ * JS bridge — measured at ~60% of a CPU core and ~2 MB/s throughput for the duration of an
+ * initial sync. Here the page instead fetch()es a same-origin URL under
+ * {@code /_trilium_native_http/}, this client forwards it to the real sync server and hands
+ * the response back as a raw InputStream, so the WebView's network stack streams the body
+ * into the page with no full-body Java string, no envelope and no bridge copy. Being
+ * same-origin from the page's point of view, no CORS applies on either leg.
+ *
+ * Protocol (see capacitor_http_handler.ts for the JS side):
+ * <ul>
+ * <li>{@code GET /_trilium_native_http/ping} — availability probe, answers with the
+ * {@code x-trilium-native-http} marker header.</li>
+ * <li>{@code GET /_trilium_native_http/fetch?url=<encoded>} — proxies to the target URL.
+ * Only GET/HEAD: shouldInterceptRequest does not expose request bodies.</li>
+ * <li>Request headers are only forwarded when tunneled as {@code x-trilium-h-<name>} —
+ * fetch() cannot set forbidden headers such as Cookie, and this also keeps
+ * WebView-generated headers (User-Agent, sec-*, ...) off the sync connection.</li>
+ * <li>Upstream {@code Set-Cookie} is re-exposed as {@code x-trilium-set-cookie}, since
+ * fetch() cannot read it and the WebView's cookie store must not adopt sync-server
+ * session cookies for the app origin.</li>
+ * <li>Failures inside the proxy itself answer 502 with {@code x-trilium-proxy-error}.</li>
+ * </ul>
+ */
+public class TriliumWebViewClient extends BridgeWebViewClient {
+
+ private static final String TAG = "TriliumHttpProxy";
+ private static final String INTERCEPT_PREFIX = "/_trilium_native_http/";
+ private static final String HEADER_TUNNEL_PREFIX = "x-trilium-h-";
+ private static final String MARKER_HEADER = "x-trilium-native-http";
+
+ private static final int CONNECT_TIMEOUT_MS = 30_000;
+ // The JS side enforces its own (configurable) sync timeout; this is only a backstop so a
+ // dead connection cannot pin a WebView IO thread forever.
+ private static final int READ_TIMEOUT_MS = 600_000;
+
+ public TriliumWebViewClient(Bridge bridge) {
+ super(bridge);
+ }
+
+ @Override
+ public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
+ Uri uri = request.getUrl();
+ String path = uri.getPath();
+ if (path == null || !path.startsWith(INTERCEPT_PREFIX)) {
+ return super.shouldInterceptRequest(view, request);
+ }
+
+ String action = path.substring(INTERCEPT_PREFIX.length());
+ if ("ping".equals(action)) {
+ return syntheticResponse(200, "OK", "pong", null);
+ }
+ if (!"fetch".equals(action)) {
+ return errorResponse("Unknown proxy action: " + action);
+ }
+
+ try {
+ return proxyRequest(request, uri);
+ } catch (Exception e) {
+ Log.w(TAG, "Proxy request failed: " + e);
+ return errorResponse(e.getClass().getSimpleName() + ": " + e.getMessage());
+ }
+ }
+
+ private WebResourceResponse proxyRequest(WebResourceRequest request, Uri uri) throws IOException {
+ String target = uri.getQueryParameter("url");
+ if (target == null || target.isEmpty()) {
+ return errorResponse("Missing url query parameter");
+ }
+ String method = request.getMethod() == null ? "GET" : request.getMethod().toUpperCase(Locale.ROOT);
+ if (!"GET".equals(method) && !"HEAD".equals(method)) {
+ return errorResponse("Only GET/HEAD can be proxied, got " + method);
+ }
+
+ final HttpURLConnection connection = (HttpURLConnection) new URL(target).openConnection();
+ boolean handedOff = false;
+ try {
+ connection.setRequestMethod(method);
+ connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
+ connection.setReadTimeout(READ_TIMEOUT_MS);
+ connection.setUseCaches(false);
+ connection.setInstanceFollowRedirects(true);
+
+ for (Map.Entry<String, String> entry : request.getRequestHeaders().entrySet()) {
+ String name = entry.getKey();
+ if (name != null && name.toLowerCase(Locale.ROOT).startsWith(HEADER_TUNNEL_PREFIX)) {
+ connection.setRequestProperty(name.substring(HEADER_TUNNEL_PREFIX.length()), entry.getValue());
+ }
+ }
+ // No explicit Accept-Encoding: Android's HttpURLConnection then negotiates gzip
+ // itself and transparently inflates the stream, dropping Content-Encoding and
+ // Content-Length from the header fields it reports.
+
+ int status = connection.getResponseCode();
+ if (status >= 300 && status < 400) {
+ // WebResourceResponse rejects 3xx status codes. Same-protocol redirects were
+ // already followed by the connection, so this should not happen in practice.
+ return errorResponse("Upstream replied with unfollowed redirect " + status
+ + " to " + connection.getHeaderField("Location"));
+ }
+ String reason = connection.getResponseMessage();
+ if (reason == null || reason.isEmpty()) {
+ // HTTP/2 has no reason phrase, but WebResourceResponse requires a non-empty one.
+ reason = "Status " + status;
+ }
+
+ Map<String, String> responseHeaders = new HashMap<>();
+ for (Map.Entry<String, List<String>> entry : connection.getHeaderFields().entrySet()) {
+ String name = entry.getKey();
+ if (name == null) {
+ continue; // the status line arrives as a header with a null key
+ }
+ String value = TextUtils.join(", ", entry.getValue());
+ switch (name.toLowerCase(Locale.ROOT)) {
+ case "set-cookie":
+ responseHeaders.put("x-trilium-set-cookie", value);
+ break;
+ case "content-encoding":
+ case "transfer-encoding":
+ case "content-length":
+ // The stream handed to the WebView is already decoded, so these
+ // no longer describe it.
+ break;
+ default:
+ responseHeaders.put(name, value);
+ }
+ }
+
+ String mimeType = "application/octet-stream";
+ String encoding = "utf-8";
+ String contentType = connection.getContentType();
+ if (contentType != null) {
+ String[] parts = contentType.split(";");
+ mimeType = parts[0].trim();
+ for (int i = 1; i < parts.length; i++) {
+ String part = parts[i].trim();
+ if (part.toLowerCase(Locale.ROOT).startsWith("charset=")) {
+ encoding = part.substring("charset=".length()).trim();
+ }
+ }
+ }
+
+ InputStream stream = status >= 400 ? connection.getErrorStream() : connection.getInputStream();
+ if (stream == null) {
+ stream = new ByteArrayInputStream(new byte[0]);
+ }
+ // The WebView reads and closes the stream on its own IO threads, well after this
+ // method returns — tie the connection's lifetime to the stream's.
+ InputStream disconnectingStream = new FilterInputStream(stream) {
+ @Override
+ public void close() throws IOException {
+ try {
+ super.close();
+ } finally {
+ connection.disconnect();
+ }
+ }
+ };
+ handedOff = true;
+ return new WebResourceResponse(mimeType, encoding, status, reason, responseHeaders, disconnectingStream);
+ } finally {
+ if (!handedOff) {
+ connection.disconnect();
+ }
+ }
+ }
+
+ /** A response produced by the proxy itself rather than by the upstream server. */
+ private static WebResourceResponse syntheticResponse(int status, String reason, String body, String errorMessage) {
+ Map<String, String> headers = new HashMap<>();
+ headers.put(MARKER_HEADER, "1");
+ if (errorMessage != null) {
+ headers.put("x-trilium-proxy-error", sanitizeHeaderValue(errorMessage));
+ }
+ return new WebResourceResponse("text/plain", "utf-8", status, reason,
+ headers, new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8)));
+ }
+
+ private static WebResourceResponse errorResponse(String message) {
+ return syntheticResponse(502, "Proxy Error", message, message);
+ }
+
+ /** Exception messages can contain characters that are not valid in a header value. */
+ private static String sanitizeHeaderValue(String value) {
+ return value.replaceAll("[^\\x20-\\x7e]", " ");
+ }
+}
diff --git a/apps/standalone/src/services/capacitor_http_handler.spec.ts b/apps/standalone/src/services/capacitor_http_handler.spec.ts
index d5015816a1..5836432057 100644
--- a/apps/standalone/src/services/capacitor_http_handler.spec.ts
+++ b/apps/standalone/src/services/capacitor_http_handler.spec.ts
@@ -1,37 +1,107 @@
import { afterEach, describe, expect, it, vi } from "vitest";
-import { capacitorHttpHandler } from "./capacitor_http_handler.js";
+import { capacitorHttpHandler, resetNativeProxyProbeForTests } from "./capacitor_http_handler.js";
interface CapacitorWindow {
Capacitor?: unknown;
}
-function installCapacitor(request: ReturnType<typeof vi.fn>) {
+type RequestMock = ReturnType<typeof vi.fn>;
+
+/**
+ * Models the real bridge: `Plugins` only contains JS-registered plugins (CapacitorHttp is
+ * registered by @capacitor/core itself), while native-only plugins are announced via
+ * `PluginHeaders` and must be materialized through `registerPlugin()`, which also stores
+ * the proxy in `Plugins`.
+ */
+function installCapacitor({ triliumHttp, capacitorHttp, platform }: { triliumHttp?: RequestMock; capacitorHttp?: RequestMock; platform?: string }) {
+ const plugins: Record<string, { request: RequestMock }> = {};
+ if (capacitorHttp) {
+ plugins.CapacitorHttp = { request: capacitorHttp };
+ }
+
+ const registerPlugin = vi.fn((name: string) => {
+ if (name === "TriliumHttp" && triliumHttp) {
+ plugins.TriliumHttp = { request: triliumHttp };
+ return plugins.TriliumHttp;
+ }
+ return undefined;
+ });
+
(window as unknown as CapacitorWindow).Capacitor = {
- Plugins: { CapacitorHttp: { request } }
+ Plugins: plugins,
+ PluginHeaders: triliumHttp ? [{ name: "TriliumHttp", methods: [{ name: "request" }] }] : [],
+ registerPlugin,
+ ...(platform ? { getPlatform: () => platform } : {})
};
+
+ return { registerPlugin };
+}
+
+/** The minimal Response surface the handler touches, with fetch()'s lowercase header keys. */
+function fakeResponse({ status = 200, headers = {}, body = "" }: { status?: number; headers?: Record<string, string>; body?: string }): Response {
+ const map = new Map(Object.entries(headers).map(([key, value]) => [key.toLowerCase(), value]));
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ headers: {
+ get: (key: string) => map.get(key.toLowerCase()) ?? null,
+ forEach: (callback: (value: string, key: string) => void) => map.forEach(callback)
+ },
+ text: () => Promise.resolve(body)
+ } as unknown as Response;
}
describe("capacitorHttpHandler", () => {
afterEach(() => {
delete (window as unknown as CapacitorWindow).Capacitor;
+ resetNativeProxyProbeForTests();
+ vi.unstubAllGlobals();
vi.restoreAllMocks();
});
- it("throws when the CapacitorHttp plugin is unavailable", async () => {
+ it("throws when no native HTTP plugin is available", async () => {
await expect(
capacitorHttpHandler({ method: "GET", url: "https://x", headers: {} })
- ).rejects.toThrow("CapacitorHttp plugin is not available");
+ ).rejects.toThrow("No native HTTP plugin is available");
+ });
+
+ it("materializes TriliumHttp via registerPlugin when the native bridge announces it", async () => {
+ const triliumHttp = vi.fn().mockResolvedValue({ status: 200, headers: {}, data: "via trilium" });
+ const capacitorHttp = vi.fn().mockResolvedValue({ status: 200, headers: {}, data: "via capacitor" });
+ const { registerPlugin } = installCapacitor({ triliumHttp, capacitorHttp });
+
+ const result = await capacitorHttpHandler({ method: "GET", url: "https://x", headers: {} });
+
+ expect(result.body).toBe("via trilium");
+ expect(registerPlugin).toHaveBeenCalledWith("TriliumHttp");
+ expect(capacitorHttp).not.toHaveBeenCalled();
+
+ // Second call reuses the proxy stored in Plugins instead of re-registering
+ await capacitorHttpHandler({ method: "GET", url: "https://x", headers: {} });
+ expect(registerPlugin).toHaveBeenCalledOnce();
+ expect(triliumHttp).toHaveBeenCalledTimes(2);
+ });
+
+ it("falls back to CapacitorHttp when the native binary lacks TriliumHttp", async () => {
+ const capacitorHttp = vi.fn().mockResolvedValue({ status: 200, headers: {}, data: "via capacitor" });
+ const { registerPlugin } = installCapacitor({ capacitorHttp });
+
+ const result = await capacitorHttpHandler({ method: "GET", url: "https://x", headers: {} });
+
+ expect(result.body).toBe("via capacitor");
+ // Never registers a plugin the native side did not announce — the proxy would throw.
+ expect(registerPlugin).not.toHaveBeenCalled();
});
it("requests the raw text response and passes a JSON string through unchanged (no re-parse/re-stringify)", async () => {
const rawJson = '{"ok":true}';
- const request = vi.fn().mockResolvedValue({
+ const triliumHttp = vi.fn().mockResolvedValue({
status: 200,
headers: { "Content-Type": "application/json", "X-Custom": "v" },
data: rawJson
});
- installCapacitor(request);
+ installCapacitor({ triliumHttp });
const result = await capacitorHttpHandler({
method: "POST",
@@ -40,7 +110,7 @@ describe("capacitorHttpHandler", () => {
body: "{}"
});
- expect(request).toHaveBeenCalledWith({
+ expect(triliumHttp).toHaveBeenCalledWith({
method: "POST",
url: "https://api/test",
headers: { Authorization: "token" },
@@ -53,25 +123,25 @@ describe("capacitorHttpHandler", () => {
expect(result.body).toBe(rawJson);
});
- it("still serializes object response data as a defensive fallback", async () => {
- const request = vi.fn().mockResolvedValue({ status: 200, headers: {}, data: { ok: true } });
- installCapacitor(request);
+ it("still serializes object response data (CapacitorHttp fallback pre-parses JSON)", async () => {
+ const capacitorHttp = vi.fn().mockResolvedValue({ status: 200, headers: {}, data: { ok: true } });
+ installCapacitor({ capacitorHttp });
const result = await capacitorHttpHandler({ method: "GET", url: "https://x", headers: {} });
expect(result.body).toBe(JSON.stringify({ ok: true }));
});
it("passes string response data through unchanged", async () => {
- const request = vi.fn().mockResolvedValue({ status: 201, headers: {}, data: "plain text" });
- installCapacitor(request);
+ const triliumHttp = vi.fn().mockResolvedValue({ status: 201, headers: {}, data: "plain text" });
+ installCapacitor({ triliumHttp });
const result = await capacitorHttpHandler({ method: "GET", url: "https://x", headers: {} });
expect(result.body).toBe("plain text");
});
it("passes arraybuffer responses through as the raw base64 string", async () => {
- const request = vi.fn().mockResolvedValue({ status: 200, headers: {}, data: "QUJD" });
- installCapacitor(request);
+ const triliumHttp = vi.fn().mockResolvedValue({ status: 200, headers: {}, data: "QUJD" });
+ installCapacitor({ triliumHttp });
const result = await capacitorHttpHandler({
method: "GET",
@@ -81,4 +151,103 @@ describe("capacitorHttpHandler", () => {
});
expect(result.body).toBe("QUJD");
});
+
+ describe("native streaming proxy", () => {
+ it("streams GET text requests through the proxy with tunneled headers, probing only once", async () => {
+ const triliumHttp = vi.fn();
+ installCapacitor({ triliumHttp, platform: "android" });
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(fakeResponse({ headers: { "x-trilium-native-http": "1" }, body: "pong" }))
+ .mockResolvedValueOnce(fakeResponse({
+ headers: { "Content-Type": "application/json", "x-trilium-set-cookie": "sid=next" },
+ body: '{"ok":true}'
+ }))
+ .mockResolvedValueOnce(fakeResponse({ body: "second" }));
+ vi.stubGlobal("fetch", fetchMock);
+
+ const url = "https://sync.example.com/api/sync/changed?lastEntityChangeId=5";
+ const result = await capacitorHttpHandler({
+ method: "GET",
+ url,
+ headers: { Cookie: "sid=current", pageCount: "1" }
+ });
+
+ expect(fetchMock).toHaveBeenNthCalledWith(1, "/_trilium_native_http/ping", { cache: "no-store" });
+ expect(fetchMock).toHaveBeenNthCalledWith(2,
+ `/_trilium_native_http/fetch?url=${encodeURIComponent(url)}`,
+ {
+ method: "GET",
+ headers: { "x-trilium-h-Cookie": "sid=current", "x-trilium-h-pageCount": "1" },
+ cache: "no-store"
+ });
+ expect(result.status).toBe(200);
+ expect(result.body).toBe('{"ok":true}');
+ // Set-Cookie is unreadable through fetch(), so it arrives renamed and is mapped back.
+ expect(result.headers["set-cookie"]).toBe("sid=next");
+ expect(result.headers["x-trilium-set-cookie"]).toBeUndefined();
+ expect(triliumHttp).not.toHaveBeenCalled();
+
+ // The availability probe is cached — a second request goes straight to /fetch.
+ await capacitorHttpHandler({ method: "GET", url, headers: {} });
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ });
+
+ it("keeps POSTs and binary requests on the plugin transport", async () => {
+ const triliumHttp = vi.fn().mockResolvedValue({ status: 200, headers: {}, data: "ok" });
+ installCapacitor({ triliumHttp, platform: "android" });
+ const fetchMock = vi.fn();
+ vi.stubGlobal("fetch", fetchMock);
+
+ await capacitorHttpHandler({ method: "POST", url: "https://x", headers: {}, body: "{}" });
+ await capacitorHttpHandler({ method: "GET", url: "https://x/image", headers: {}, responseType: "arraybuffer" });
+
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(triliumHttp).toHaveBeenCalledTimes(2);
+ });
+
+ it("does not probe the proxy off Android", async () => {
+ const triliumHttp = vi.fn().mockResolvedValue({ status: 200, headers: {}, data: "ok" });
+ installCapacitor({ triliumHttp, platform: "ios" });
+ const fetchMock = vi.fn();
+ vi.stubGlobal("fetch", fetchMock);
+
+ await capacitorHttpHandler({ method: "GET", url: "https://x", headers: {} });
+
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(triliumHttp).toHaveBeenCalledOnce();
+ });
+
+ it("uses the plugin transport when the ping is not answered by the interceptor (stale APK)", async () => {
+ const triliumHttp = vi.fn().mockResolvedValue({ status: 200, headers: {}, data: "ok" });
+ installCapacitor({ triliumHttp, platform: "android" });
+ // An older APK serves the path from the asset server — no marker header.
+ const fetchMock = vi.fn().mockResolvedValue(fakeResponse({ status: 404, body: "not found" }));
+ vi.stubGlobal("fetch", fetchMock);
+
+ await capacitorHttpHandler({ method: "GET", url: "https://x", headers: {} });
+ await capacitorHttpHandler({ method: "GET", url: "https://x", headers: {} });
+
+ // The failed probe is cached too — pinged once, never fetched through the proxy.
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(triliumHttp).toHaveBeenCalledTimes(2);
+ });
+
+ it("falls back to the plugin transport when the proxy reports an internal error", async () => {
+ const triliumHttp = vi.fn().mockResolvedValue({ status: 200, headers: {}, data: "via plugin" });
+ installCapacitor({ triliumHttp, platform: "android" });
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(fakeResponse({ headers: { "x-trilium-native-http": "1" }, body: "pong" }))
+ .mockResolvedValueOnce(fakeResponse({
+ status: 502,
+ headers: { "x-trilium-native-http": "1", "x-trilium-proxy-error": "SocketTimeoutException: timed out" }
+ }));
+ vi.stubGlobal("fetch", fetchMock);
+
+ const result = await capacitorHttpHandler({ method: "GET", url: "https://x", headers: {} });
+
+ expect(result.body).toBe("via plugin");
+ expect(warnSpy).toHaveBeenCalledOnce();
+ });
+ });
});
diff --git a/apps/standalone/src/services/capacitor_http_handler.ts b/apps/standalone/src/services/capacitor_http_handler.ts
index f4efd22b08..5d196e7170 100644
--- a/apps/standalone/src/services/capacitor_http_handler.ts
+++ b/apps/standalone/src/services/capacitor_http_handler.ts
@@ -1,6 +1,6 @@
import type { NativeHttpHandler } from "../local-bridge.js";
-// Access CapacitorHttp via the global Capacitor bridge rather than importing
+// Access plugins via the global Capacitor bridge rather than importing
// from "@capacitor/core" — bare module specifiers don't resolve in the
// browser's native ES module loader.
interface CapacitorHttpResponse {
@@ -9,37 +9,164 @@ interface CapacitorHttpResponse {
data: unknown;
}
-function getCapacitorHttp() {
+interface HttpPlugin {
+ request(opts: {
+ method: string;
+ url: string;
+ headers: Record<string, string>;
+ data?: string;
+ responseType?: string;
+ }): Promise<CapacitorHttpResponse>;
+}
+
+function getHttpPlugin(): HttpPlugin {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const cap = (window as any).Capacitor;
- if (!cap?.Plugins?.CapacitorHttp) {
- throw new Error("CapacitorHttp plugin is not available");
+
+ // Prefer the app's own TriliumHttp plugin: it always returns the body as a plain string.
+ // CapacitorHttp force-parses application/json responses into a Java object tree and
+ // re-serializes them into the bridge message regardless of the requested responseType
+ // (the "backward compatibility" branch in HttpRequestHandler.readData), which costs two
+ // full JSON passes per multi-megabyte sync response.
+ //
+ // Capacitor.Plugins only contains plugins that were registered from the JS side, so a
+ // native-only plugin like TriliumHttp does not appear there on its own — it has to be
+ // looked up via registerPlugin(), and only when the native bridge actually announced it
+ // in PluginHeaders (otherwise proxy method calls would throw "not implemented").
+ // registerPlugin() also stores the proxy in Capacitor.Plugins, so the first branch acts
+ // as the cache on subsequent calls. The CapacitorHttp fallback keeps things working if
+ // the JS bundle is ever newer than the installed native binary.
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const hasTriliumHttp = cap?.PluginHeaders?.some((header: any) => header?.name === "TriliumHttp");
+ const plugin = cap?.Plugins?.TriliumHttp
+ ?? (hasTriliumHttp ? cap.registerPlugin("TriliumHttp") : null)
+ ?? cap?.Plugins?.CapacitorHttp;
+
+ if (!plugin) {
+ throw new Error("No native HTTP plugin is available");
+ }
+
+ return plugin as HttpPlugin;
+}
+
+// Streaming same-origin proxy (Android only): the native side answers fetch()es under
+// this path prefix from WebViewClient.shouldInterceptRequest and streams the upstream
+// body straight into the WebView — no plugin-bridge envelope, no full-body Java string,
+// no base64 (see TriliumWebViewClient.java). Because the page-visible request is
+// same-origin, no CORS check applies; the cross-origin hop happens natively, exactly as
+// it does on the plugin transports.
+const NATIVE_PROXY_PREFIX = "/_trilium_native_http/";
+const HEADER_TUNNEL_PREFIX = "x-trilium-h-";
+
+let nativeProxyProbe: Promise<boolean> | null = null;
+
+// A failed probe is retried after a while: right after an app update the previous
+// service worker can still own the page's fetches (and swallow the probe) until the
+// updated one calls clients.claim(), so "unavailable" may be a temporary condition.
+const PROBE_RETRY_MS = 15_000;
+
+function isNativeProxyAvailable(): Promise<boolean> {
+ nativeProxyProbe ??= probeNativeProxy().then((available) => {
+ if (!available) {
+ setTimeout(() => {
+ nativeProxyProbe = null;
+ }, PROBE_RETRY_MS);
+ }
+ return available;
+ });
+ return nativeProxyProbe;
+}
+
+function probeNativeProxy(): Promise<boolean> {
+ return (async () => {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const cap = (window as any).Capacitor;
+ if (cap?.getPlatform?.() !== "android") {
+ // iOS has no equivalent hook for https URLs — it stays on the plugin transport.
+ return false;
+ }
+ try {
+ const response = await fetch(`${NATIVE_PROXY_PREFIX}ping`, { cache: "no-store" });
+ // The marker header proves the interceptor answered — on an APK older than this
+ // bundle the request falls through to the asset server instead.
+ return response.ok && response.headers.get("x-trilium-native-http") === "1";
+ } catch {
+ return false;
+ }
+ })();
+}
+
+/** Test-only: clears the cached availability probe. */
+export function resetNativeProxyProbeForTests() {
+ nativeProxyProbe = null;
+}
+
+type NativeHttpRequest = Parameters<NativeHttpHandler>[0];
+
+function canUseNativeProxy(request: NativeHttpRequest): boolean {
+ const method = request.method.toUpperCase();
+ // shouldInterceptRequest cannot read request bodies, and binary responses would have
+ // to be re-encoded as base64 for the bridge protocol — those stay on the plugin path.
+ return (method === "GET" || method === "HEAD")
+ && !request.body
+ && (request.responseType ?? "text") === "text";
+}
+
+async function nativeProxyFetch(request: NativeHttpRequest): ReturnType<NativeHttpHandler> {
+ // fetch() refuses forbidden header names such as Cookie, so every header rides under
+ // a tunnel prefix that the interceptor strips before forwarding upstream. This also
+ // means WebView-generated headers are never forwarded — only what the worker asked for.
+ const tunneledHeaders: Record<string, string> = {};
+ for (const [key, value] of Object.entries(request.headers)) {
+ tunneledHeaders[HEADER_TUNNEL_PREFIX + key] = value;
}
- return cap.Plugins.CapacitorHttp as {
- request(opts: {
- method: string;
- url: string;
- headers: Record<string, string>;
- data?: string;
- responseType?: string;
- }): Promise<CapacitorHttpResponse>;
- };
+
+ const response = await fetch(`${NATIVE_PROXY_PREFIX}fetch?url=${encodeURIComponent(request.url)}`, {
+ method: request.method,
+ headers: tunneledHeaders,
+ cache: "no-store"
+ });
+
+ const proxyError = response.headers.get("x-trilium-proxy-error");
+ if (proxyError) {
+ throw new Error(`Native HTTP proxy failed: ${proxyError}`);
+ }
+
+ // Header keys from fetch() are already lowercase.
+ const headers: Record<string, string> = {};
+ response.headers.forEach((value, key) => {
+ headers[key] = value;
+ });
+ // fetch() cannot read Set-Cookie, so the interceptor re-exposes it under a safe name;
+ // map it back for the worker's cookie jar.
+ const setCookie = headers["x-trilium-set-cookie"];
+ if (setCookie) {
+ headers["set-cookie"] = setCookie;
+ delete headers["x-trilium-set-cookie"];
+ }
+
+ return { status: response.status, headers, body: await response.text() };
}
/**
- * Native HTTP handler that uses Capacitor's native networking layer.
+ * Native HTTP handler that uses the app's native networking layer.
*
* This bypasses the WebView's fetch — no CORS preflight, no SameSite cookie
* restrictions, and plain HTTP targets work from an HTTPS WebView origin.
*/
export const capacitorHttpHandler: NativeHttpHandler = async (request) => {
- // Ask for the raw response as text rather than CapacitorHttp's default JSON auto-parsing. The
- // worker (BridgedRequestProvider) parses the body itself, so letting the plugin parse it to an
- // object only for us to JSON.stringify it straight back is a wasted parse + serialize of the
- // entire body — doubling main-thread peak memory on a large sync response (e.g. one carrying a
- // big blob), which shares the mobile process heap with the sync worker.
+ if (canUseNativeProxy(request) && await isNativeProxyAvailable()) {
+ try {
+ return await nativeProxyFetch(request);
+ } catch (e) {
+ // Idempotent GET — retrying once over the plugin transport is safe and keeps
+ // sync alive if the proxy misbehaves in ways the availability probe missed.
+ console.warn("Native HTTP proxy failed, falling back to the plugin transport", e);
+ }
+ }
+
const responseType = request.responseType ?? "text";
- const response = await getCapacitorHttp().request({
+ const response = await getHttpPlugin().request({
method: request.method,
url: request.url,
headers: request.headers,
@@ -55,9 +182,12 @@ export const capacitorHttpHandler: NativeHttpHandler = async (request) => {
let body: string;
if (request.responseType === "arraybuffer") {
- // Capacitor returns binary data as a base64 string — pass it through directly
+ // Both plugins return binary data as a base64 string — pass it through directly
body = String(response.data);
} else {
+ // TriliumHttp always returns a string. On the CapacitorHttp fallback, JSON responses
+ // arrive pre-parsed as an object (see above) and have to be re-serialized for the
+ // worker, which parses the body itself.
body = typeof response.data === "string"
? response.data
: JSON.stringify(response.data);
diff --git a/apps/standalone/src/sw.spec.ts b/apps/standalone/src/sw.spec.ts
index 197799010c..85572a1a4f 100644
--- a/apps/standalone/src/sw.spec.ts
+++ b/apps/standalone/src/sw.spec.ts
@@ -101,6 +101,15 @@ describe("fetch routing", () => {
expect(event._response).toBeUndefined();
});
+ it("lets native-proxy requests fall through to the network stack untouched", async () => {
+ const handlers = await loadSw();
+ const event = fetchEvent(`${origin}/_trilium_native_http/ping`);
+ handlers.fetch(event);
+ // No respondWith: only the WebView's own network path reaches shouldInterceptRequest.
+ expect(event._response).toBeUndefined();
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
it("routes local-first prefixes to the client bridge", async () => {
const handlers = await loadSw();
const event = fetchEvent(`${origin}/api/notes`);
diff --git a/apps/standalone/src/sw.ts b/apps/standalone/src/sw.ts
index dde5c4268e..48fb617882 100644
--- a/apps/standalone/src/sw.ts
+++ b/apps/standalone/src/sw.ts
@@ -179,6 +179,12 @@ self.addEventListener("fetch", (event) => {
// Only handle same-origin
if (url.origin !== self.location.origin) return;
+ // Native streaming HTTP proxy (Capacitor Android): these must reach the WebView's
+ // network stack untouched so WebViewClient.shouldInterceptRequest can answer them —
+ // a respondWith() (even a fetch() pass-through) would re-issue them from the service
+ // worker, which the interceptor never sees. See capacitor_http_handler.ts.
+ if (url.pathname.startsWith("/_trilium_native_http/")) return;
+
// API-ish: local-first via bridge (must be checked before navigate handling,
// because export triggers a navigation to an /api/ URL)
if (isLocalFirst(url)) {