Skip to content

Build your personal knowledge base with Trilium Notes

test(mobile): unit-test the Android request bridge and sync proxy on the JVM

Elian Doran7d767cf84ae5
diff --git a/.claude/skills/developing-capacitor-mobile/SKILL.md b/.claude/skills/developing-capacitor-mobile/SKILL.md
index 6509b38e83..f3a9c11fb2 100644
--- a/.claude/skills/developing-capacitor-mobile/SKILL.md
+++ b/.claude/skills/developing-capacitor-mobile/SKILL.md
@@ -13,8 +13,11 @@ Key files:
apps/mobile/capacitor.config.json # appId org.triliumnotes.trilium, androidScheme https, hostname localhost, plugins
apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/
MainActivity.java # installs TriliumRequestBridge, TriliumWebViewClient, TriliumFileSink; edge-to-edge + insets, system bars
- TriliumRequestBridge.java # answers local API requests from the page's worker in place of a service worker (Android only)
- TriliumWebViewClient.java # routes local API requests to TriliumRequestBridge; streaming HTTP proxy for the sync worker
+ TriliumRequestBridge.java # Android adapter for LocalRequestBroker: message listener, evaluateJavascript, page reloads
+ LocalRequestBroker.java # local API request logic in place of a service worker; no Android classes, unit-tested
+ NativeHttpProxy.java # the sync worker's streaming HTTP proxy; no Android classes, unit-tested
+ InterceptedResponse.java # Android-free form of WebResourceResponse, returned by both
+ TriliumWebViewClient.java # routes requests to TriliumRequestBridge and NativeHttpProxy, builds the WebResourceResponse
TriliumFileSink.java # binary file-write channel (WebMessageListener + ArrayBuffer, Android only)
apps/mobile/ios/App/App/ViewController.swift # keyboard handling: pins outer scroll, drives --tn-keyboard-gap
apps/standalone/src/main.ts # boot: registers native HTTP handler if `Capacitor` in window; iOS interceptors or Android request bridge
@@ -175,7 +178,7 @@ pnpm --filter @triliumnext/mobile open:android # Android Studio
pnpm --filter @triliumnext/mobile run:ios | open:ios # Xcode (macOS)
```
-CI: `mobile.yml` (pull requests) builds a debug APK via `.github/actions/build-mobile` and an unsigned iOS **Simulator** `.app` on macOS; `nightly.yml` calls the same action with `nightly: "true"` for the signed `assembleRelease` build under the `.nightly` app id. Neither runs unit tests — those live in the standalone suite.
+CI: `mobile.yml` (pull requests) builds a debug APK via `.github/actions/build-mobile` and an unsigned iOS **Simulator** `.app` on macOS; `nightly.yml` calls the same action with `nightly: "true"` for the signed `assembleRelease` build under the `.nightly` app id. The action runs the Android JVM unit tests before assembling, and `mobile.yml` uploads their JaCoCo report to Codecov under the `mobile` flag; the JS unit tests live in the standalone suite.
**Debugging on a device:** a *release*-type build (what `nightly.yml` produces) suppresses WebView
console→logcat forwarding, so anything logged from JS is invisible to `adb logcat` and log-based
@@ -196,4 +199,19 @@ pnpm --filter standalone test android-request-bridge # Android request bridge:
pnpm --filter standalone test main # boot wiring (native handler, iOS interceptors, Android bridge instead of the SW)
```
-Simulate the platform in a spec by stubbing `location.protocol` / `window.Capacitor` (`getPlatform`, `isNativePlatform`, `Plugins.CapacitorHttp`) — see the existing specs for the fixtures. Native Java/Swift has no test harness in the repo; keep logic there minimal and mirror the protocol on the JS side where it is testable.
+Simulate the platform in a spec by stubbing `location.protocol` / `window.Capacitor` (`getPlatform`, `isNativePlatform`, `Plugins.CapacitorHttp`) — see the existing specs for the fixtures.
+
+The Android Java has JVM unit tests (JUnit 4) under `apps/mobile/android/app/src/test/`:
+
+```bash
+cd apps/mobile/android
+./gradlew testDebugUnitTest # needs a JDK 21 and ANDROID_HOME
+./gradlew testDebugUnitTest createDebugUnitTestCoverageReport # + app/build/reports/coverage/test/debug/
+```
+
+The project needs `cap sync android` (or `cap update android`) once first, for the generated `capacitor-cordova-android-plugins/`.
+
+- **Only Android-free classes are testable.** Unit tests compile against `android.jar`, whose classes (`Uri`, `Handler`, `Log`, `Base64`, `WebResourceResponse`) are stubs that throw "Method not mocked". Logic therefore lives in classes that import none of them (`LocalRequestBroker`, `NativeHttpProxy`, `InterceptedResponse`), with the WebView, the main thread, base64 and logging passed in; the `Trilium*` classes are thin adapters with no tests. Keep new native logic on the same side of that line.
+- **`org.json` comes from a `testImplementation` dependency**, since `android.jar`'s copy is a stub too. **`com.sun.net.httpserver` is not on the test classpath**, so `NativeHttpProxyTest` serves canned responses from a `ServerSocket` (`StubServer`).
+- **`minSdk` is 24**: `String.join` and `java.util.Base64` need API 26, so production code avoids them; tests can use them.
+- Swift has no harness in the repo; keep logic there minimal and mirror the protocol on the JS side, where it is testable.
diff --git a/.github/actions/build-mobile/action.yml b/.github/actions/build-mobile/action.yml
index 6d838ec900..52b4cfe89b 100644
--- a/.github/actions/build-mobile/action.yml
+++ b/.github/actions/build-mobile/action.yml
@@ -85,6 +85,11 @@ runs:
echo "TRILIUM_ANDROID_VERSION_NAME=nightly-$(date -u +%Y%m%d)"
} >> "$GITHUB_ENV"
+ - name: Run Android unit tests
+ shell: bash
+ working-directory: apps/mobile/android
+ run: ./gradlew testDebugUnitTest createDebugUnitTestCoverageReport --no-daemon
+
- name: Assemble APK
shell: bash
working-directory: apps/mobile/android
diff --git a/.github/workflows/mobile.yml b/.github/workflows/mobile.yml
index ade7bc2160..06c613b73a 100644
--- a/.github/workflows/mobile.yml
+++ b/.github/workflows/mobile.yml
@@ -30,6 +30,14 @@ jobs:
- name: Build mobile APK
uses: ./.github/actions/build-mobile
+ - name: Upload Android coverage to Codecov
+ uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1
+ with:
+ files: apps/mobile/android/app/build/reports/coverage/test/debug/report.xml
+ flags: mobile
+ disable_search: true
+ fail_ci_if_error: false
+
build_ios:
name: Build iOS App
# iOS builds require Xcode, which is only available on macOS runners.
diff --git a/apps/mobile/android/app/build.gradle b/apps/mobile/android/app/build.gradle
index c15695c09f..c653dbc0d6 100644
--- a/apps/mobile/android/app/build.gradle
+++ b/apps/mobile/android/app/build.gradle
@@ -45,6 +45,8 @@ android {
// ever conflicting with a nightly or stable install.
applicationIdSuffix ".debug"
manifestPlaceholders = [appName: "Trilium Debug"]
+ // createDebugUnitTestCoverageReport writes the JaCoCo report CI uploads to Codecov.
+ enableUnitTestCoverage true
}
release {
minifyEnabled false
@@ -71,6 +73,8 @@ dependencies {
implementation "androidx.webkit:webkit:$androidxWebkitVersion"
implementation project(':capacitor-android')
testImplementation "junit:junit:$junitVersion"
+ // android.jar's org.json is a stub that throws in JVM unit tests; this is the real library.
+ testImplementation "org.json:json:20250517"
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
implementation project(':capacitor-cordova-android-plugins')
diff --git a/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/InterceptedResponse.java b/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/InterceptedResponse.java
new file mode 100644
index 0000000000..5f0d04050f
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/InterceptedResponse.java
@@ -0,0 +1,65 @@
+package org.triliumnotes.trilium;
+
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.Locale;
+import java.util.Map;
+
+/**
+ * The parts of a {@code WebResourceResponse}, held without Android classes so that
+ * {@link LocalRequestBroker} and {@link NativeHttpProxy} run in plain JVM unit tests.
+ * {@code TriliumWebViewClient} turns it into the real response.
+ */
+final class InterceptedResponse {
+
+ final int status;
+ final String reasonPhrase;
+ final String mimeType;
+ /** Null when the response names no charset. */
+ final String encoding;
+ final Map<String, String> headers;
+ final InputStream body;
+
+ InterceptedResponse(int status, String reasonPhrase, String contentType,
+ Map<String, String> headers, InputStream body) {
+ this.status = status;
+ this.reasonPhrase = reasonPhrase;
+ this.headers = headers;
+ this.body = body;
+
+ String mime = "application/octet-stream";
+ String charset = null;
+ if (contentType != null) {
+ String[] parts = contentType.split(";");
+ if (!parts[0].trim().isEmpty()) {
+ mime = parts[0].trim();
+ }
+ for (int i = 1; i < parts.length; i++) {
+ String part = parts[i].trim();
+ if (part.toLowerCase(Locale.ROOT).startsWith("charset=")) {
+ charset = part.substring("charset=".length()).trim();
+ }
+ }
+ }
+ this.mimeType = mime;
+ this.encoding = charset;
+ }
+
+ /** A plain-text response with the message as its body and in {@code errorHeader}, if given. */
+ static InterceptedResponse text(int status, String reasonPhrase, String message,
+ Map<String, String> headers, String errorHeader) {
+ Map<String, String> allHeaders = new HashMap<>(headers);
+ if (errorHeader != null) {
+ allHeaders.put(errorHeader, sanitizeHeaderValue(message));
+ }
+ return new InterceptedResponse(status, reasonPhrase, "text/plain; charset=utf-8", allHeaders,
+ new ByteArrayInputStream(message.getBytes(StandardCharsets.UTF_8)));
+ }
+
+ /** Exception messages can contain characters that are not valid in a header value. */
+ static String sanitizeHeaderValue(String value) {
+ return value.replaceAll("[^\\x20-\\x7e]", " ");
+ }
+}
diff --git a/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/LocalRequestBroker.java b/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/LocalRequestBroker.java
new file mode 100644
index 0000000000..4ef676279b
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/LocalRequestBroker.java
@@ -0,0 +1,397 @@
+package org.triliumnotes.trilium;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executor;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Consumer;
+import java.util.function.Function;
+
+/**
+ * Tracks the local API requests {@link TriliumRequestBridge} forwards to the page, from dispatch
+ * until the page's reply completes them. Holds no Android classes, so it runs in plain JVM unit
+ * tests; the bridge supplies the WebView, the main thread and base64 decoding.
+ *
+ * <p>{@link #handle} runs on a WebView IO thread: it hands the request to the page through
+ * {@code window.__triliumNativeRequest()} and blocks until the head of the reply arrives. The
+ * body then streams through a {@link ChunkStream}. The page's messages arrive through
+ * {@link #onMessage} and {@link #onFrame}; the protocol is described in
+ * {@code apps/standalone/src/android-request-bridge.ts}.
+ *
+ * <p>Requests that arrive before the page sends {@code ready} are queued, and
+ * {@link #onPageStarted} fails whatever the previous page left unanswered.
+ */
+final class LocalRequestBroker {
+
+ /** The page the requests are forwarded to. */
+ interface Page {
+ /**
+ * Runs the script in the page, on the main thread, and reports whether it returned
+ * {@code true}.
+ */
+ void evaluate(String script, Consumer<Boolean> accepted);
+ }
+
+ /** Must match {@code isLocalApiRequest()} in {@code apps/standalone/src/local-bridge.ts}. */
+ private static final String[] LOCAL_PREFIXES = { "/bootstrap", "/api/", "/sync/", "/search/", "/custom/" };
+
+ static final String ERROR_HEADER = "x-trilium-bridge-error";
+
+ private static final int FRAME_HEADER_SIZE = 4;
+
+ private final Page page;
+ private final Executor mainThread;
+ private final Function<String, byte[]> base64Decoder;
+ private final Consumer<String> warn;
+ private final long headTimeoutMs;
+ private final boolean binaryChunks;
+
+ private final AtomicInteger nextId = new AtomicInteger();
+ private final Map<Integer, PendingRequest> pending = new ConcurrentHashMap<>();
+
+ /** Guards {@link #pageReady} and {@link #queuedIds}. */
+ private final Object readyLock = new Object();
+ private boolean pageReady;
+ private final List<Integer> queuedIds = new ArrayList<>();
+
+ /**
+ * @param binaryChunks whether the WebView carries ArrayBuffer messages; the page sends base64
+ * chunks otherwise.
+ */
+ LocalRequestBroker(Page page, Executor mainThread, Function<String, byte[]> base64Decoder,
+ Consumer<String> warn, long headTimeoutMs, boolean binaryChunks) {
+ this.page = page;
+ this.mainThread = mainThread;
+ this.base64Decoder = base64Decoder;
+ this.warn = warn;
+ this.headTimeoutMs = headTimeoutMs;
+ this.binaryChunks = binaryChunks;
+ }
+
+ /** Whether the path belongs to the local worker rather than to the app's static files. */
+ static boolean isLocalPath(String path) {
+ if (path == null) {
+ return false;
+ }
+ if (path.equals("/share") || (path.startsWith("/share/") && !path.startsWith("/share/assets/"))) {
+ return true;
+ }
+ for (String prefix : LOCAL_PREFIXES) {
+ if (path.startsWith(prefix)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /** Answers a local API request. Blocks the calling thread until the page replies. */
+ InterceptedResponse handle(String method, String url, Map<String, String> headers) {
+ String normalizedMethod = method == null ? "GET" : method.toUpperCase(Locale.ROOT);
+ if (!"GET".equals(normalizedMethod) && !"HEAD".equals(normalizedMethod)) {
+ // shouldInterceptRequest exposes no request body; the page sends these through
+ // standaloneApi.localFetch instead.
+ return error(405, "Method Not Allowed",
+ normalizedMethod + " cannot be answered natively: the request body is not available");
+ }
+
+ int id = nextId.incrementAndGet();
+ PendingRequest request = new PendingRequest();
+ try {
+ JSONObject payload = new JSONObject()
+ .put("id", id)
+ .put("method", normalizedMethod)
+ .put("url", url)
+ .put("headers", new JSONObject(headers))
+ .put("binary", binaryChunks);
+ String json = escapeLineSeparators(payload.toString());
+ request.script =
+ "window.__triliumNativeRequest ? (window.__triliumNativeRequest(" + json + "), true) : false";
+ } catch (JSONException e) {
+ return error(500, "Internal Error", "Cannot encode the request: " + e.getMessage());
+ }
+
+ pending.put(id, request);
+ synchronized (readyLock) {
+ if (pageReady) {
+ mainThread.execute(() -> dispatch(id, request));
+ } else {
+ queuedIds.add(id);
+ }
+ }
+
+ try {
+ if (!request.headReceived.await(headTimeoutMs, TimeUnit.MILLISECONDS)) {
+ pending.remove(id);
+ return error(504, "Gateway Timeout", "The local worker did not answer in time");
+ }
+ } catch (InterruptedException e) {
+ pending.remove(id);
+ Thread.currentThread().interrupt();
+ return error(503, "Service Unavailable", "Interrupted while waiting for the local worker");
+ }
+
+ if (request.headError != null) {
+ return error(502, "Bad Gateway", request.headError);
+ }
+ if (request.status < 100 || request.status > 599 || (request.status >= 300 && request.status < 400)) {
+ // WebResourceResponse rejects these; the page turns redirects into a 200 already.
+ return error(502, "Bad Gateway", "The local worker answered with status " + request.status);
+ }
+
+ Map<String, String> responseHeaders = new HashMap<>();
+ String contentType = null;
+ for (Map.Entry<String, String> header : request.headers.entrySet()) {
+ String name = header.getKey().toLowerCase(Locale.ROOT);
+ if ("content-length".equals(name) || "content-encoding".equals(name)) {
+ // The stream carries exactly the decoded bytes the page sent.
+ continue;
+ }
+ if ("content-type".equals(name)) {
+ contentType = header.getValue();
+ }
+ responseHeaders.put(header.getKey(), header.getValue());
+ }
+ return new InterceptedResponse(request.status, reasonPhrase(request.status), contentType,
+ responseHeaders, request.body);
+ }
+
+ /** Fails every request the previous page left unanswered; the new page has to announce itself. */
+ void onPageStarted() {
+ synchronized (readyLock) {
+ pageReady = false;
+ queuedIds.clear();
+ }
+ Iterator<PendingRequest> iterator = pending.values().iterator();
+ while (iterator.hasNext()) {
+ iterator.next().fail("The page reloaded before answering");
+ iterator.remove();
+ }
+ }
+
+ /** A JSON message from the page. Runs on the main thread. */
+ void onMessage(String message) {
+ try {
+ JSONObject parsed = new JSONObject(message);
+ String type = parsed.getString("type");
+ if ("ready".equals(type)) {
+ onPageReady();
+ return;
+ }
+
+ int id = parsed.getInt("id");
+ PendingRequest request = pending.get(id);
+ if (request == null) {
+ return;
+ }
+ switch (type) {
+ case "head":
+ request.receiveHead(parsed.getInt("status"), toHeaderMap(parsed.optJSONObject("headers")));
+ break;
+ case "chunk":
+ request.body.append(base64Decoder.apply(parsed.getString("data")));
+ break;
+ case "end":
+ pending.remove(id);
+ request.body.finish();
+ break;
+ case "error":
+ pending.remove(id);
+ request.fail(parsed.optString("message", "The local request failed"));
+ break;
+ default:
+ warn.accept("Unknown message type: " + type);
+ }
+ } catch (JSONException e) {
+ warn.accept("Malformed message from the page: " + e.getMessage());
+ }
+ }
+
+ /** A binary body chunk from the page: a 4-byte big-endian request id, then the bytes. */
+ void onFrame(byte[] frame) {
+ if (frame.length < FRAME_HEADER_SIZE) {
+ warn.accept("Body frame too short to carry a request id");
+ return;
+ }
+ PendingRequest request = pending.get(ByteBuffer.wrap(frame).getInt());
+ if (request != null) {
+ request.body.append(Arrays.copyOfRange(frame, FRAME_HEADER_SIZE, frame.length));
+ }
+ }
+
+ private void onPageReady() {
+ List<Integer> ids;
+ synchronized (readyLock) {
+ pageReady = true;
+ ids = new ArrayList<>(queuedIds);
+ queuedIds.clear();
+ }
+ for (int id : ids) {
+ PendingRequest request = pending.get(id);
+ if (request != null) {
+ dispatch(id, request);
+ }
+ }
+ }
+
+ private void dispatch(int id, PendingRequest request) {
+ page.evaluate(request.script, accepted -> {
+ if (!accepted) {
+ PendingRequest rejected = pending.remove(id);
+ if (rejected != null) {
+ rejected.fail("The page has no request handler");
+ }
+ }
+ });
+ }
+
+ private InterceptedResponse error(int status, String reason, String message) {
+ warn.accept(message);
+ return InterceptedResponse.text(status, reason, message, new HashMap<>(), ERROR_HEADER);
+ }
+
+ /**
+ * U+2028 and U+2029 are valid in JSON strings but end a line in JavaScript source, and
+ * Android's {@code org.json} leaves them unescaped.
+ */
+ static String escapeLineSeparators(String json) {
+ return json.replace("\u2028", "\\u2028").replace("\u2029", "\\u2029");
+ }
+
+ /** WebResourceResponse requires a non-empty reason phrase. */
+ static String reasonPhrase(int status) {
+ switch (status) {
+ case 200: return "OK";
+ case 201: return "Created";
+ case 204: return "No Content";
+ case 206: return "Partial Content";
+ case 400: return "Bad Request";
+ case 401: return "Unauthorized";
+ case 403: return "Forbidden";
+ case 404: return "Not Found";
+ case 500: return "Internal Server Error";
+ case 503: return "Service Unavailable";
+ default: return "Status " + status;
+ }
+ }
+
+ private static Map<String, String> toHeaderMap(JSONObject json) {
+ Map<String, String> headers = new HashMap<>();
+ if (json == null) {
+ return headers;
+ }
+ Iterator<String> names = json.keys();
+ while (names.hasNext()) {
+ String name = names.next();
+ headers.put(name, json.optString(name));
+ }
+ return headers;
+ }
+
+ /** One forwarded request, from dispatch until the page sends {@code end} or {@code error}. */
+ private static final class PendingRequest {
+ final CountDownLatch headReceived = new CountDownLatch(1);
+ final ChunkStream body = new ChunkStream();
+ String script;
+ volatile int status;
+ volatile Map<String, String> headers;
+ volatile String headError;
+
+ void receiveHead(int status, Map<String, String> headers) {
+ this.status = status;
+ this.headers = headers;
+ headReceived.countDown();
+ }
+
+ void fail(String message) {
+ if (headReceived.getCount() > 0) {
+ headError = message;
+ headReceived.countDown();
+ }
+ body.fail(message);
+ }
+ }
+
+ /** The response body as the page sends it: a queue of chunks the WebView drains. */
+ static final class ChunkStream extends InputStream {
+ private static final byte[] END = new byte[0];
+
+ private final LinkedBlockingQueue<byte[]> chunks = new LinkedBlockingQueue<>();
+ private volatile String error;
+ private byte[] current;
+ private int position;
+ private boolean finished;
+
+ void append(byte[] chunk) {
+ if (chunk.length > 0) {
+ chunks.add(chunk);
+ }
+ }
+
+ void finish() {
+ chunks.add(END);
+ }
+
+ void fail(String message) {
+ error = message;
+ chunks.add(END);
+ }
+
+ @Override
+ public int read() throws IOException {
+ byte[] single = new byte[1];
+ int read = read(single, 0, 1);
+ return read == -1 ? -1 : single[0] & 0xff;
+ }
+
+ @Override
+ public int read(byte[] buffer, int offset, int length) throws IOException {
+ if (length == 0) {
+ return 0;
+ }
+ while (current == null || position >= current.length) {
+ if (finished) {
+ return -1;
+ }
+ try {
+ current = chunks.take();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IOException("Interrupted while reading the local response", e);
+ }
+ position = 0;
+ if (current == END) {
+ finished = true;
+ if (error != null) {
+ throw new IOException(error);
+ }
+ return -1;
+ }
+ }
+ int count = Math.min(length, current.length - position);
+ System.arraycopy(current, position, buffer, offset, count);
+ position += count;
+ return count;
+ }
+
+ @Override
+ public void close() {
+ chunks.clear();
+ finished = true;
+ }
+ }
+}
diff --git a/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/NativeHttpProxy.java b/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/NativeHttpProxy.java
new file mode 100644
index 0000000000..d485b3fa04
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/NativeHttpProxy.java
@@ -0,0 +1,199 @@
+package org.triliumnotes.trilium;
+
+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.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+
+/**
+ * Streaming same-origin HTTP proxy for the sync worker, served by {@code TriliumWebViewClient}.
+ *
+ * <p>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 {@link #PREFIX}, this
+ * proxy 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.
+ *
+ * <p>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>
+ *
+ * <p>Holds no Android classes, so it runs in plain JVM unit tests.
+ */
+final class NativeHttpProxy {
+
+ static final String PREFIX = "/_trilium_native_http/";
+ static final String MARKER_HEADER = "x-trilium-native-http";
+ static final String ERROR_HEADER = "x-trilium-proxy-error";
+ private static final String HEADER_TUNNEL_PREFIX = "x-trilium-h-";
+
+ private final Consumer<String> warn;
+ private final int connectTimeoutMs;
+ private final int readTimeoutMs;
+
+ NativeHttpProxy(Consumer<String> warn, int connectTimeoutMs, int readTimeoutMs) {
+ this.warn = warn;
+ this.connectTimeoutMs = connectTimeoutMs;
+ this.readTimeoutMs = readTimeoutMs;
+ }
+
+ static boolean isProxyPath(String path) {
+ return path != null && path.startsWith(PREFIX);
+ }
+
+ /**
+ * Answers a request under {@link #PREFIX}.
+ *
+ * @param target the {@code url} query parameter, or null when absent.
+ */
+ InterceptedResponse handle(String path, String method, String target, Map<String, String> requestHeaders) {
+ String action = path.substring(PREFIX.length());
+ if ("ping".equals(action)) {
+ return synthetic(200, "OK", "pong", null);
+ }
+ if (!"fetch".equals(action)) {
+ return error("Unknown proxy action: " + action);
+ }
+
+ try {
+ return proxy(method, target, requestHeaders);
+ } catch (Exception e) {
+ return error(e.getClass().getSimpleName() + ": " + e.getMessage());
+ }
+ }
+
+ private InterceptedResponse proxy(String method, String target, Map<String, String> requestHeaders)
+ throws IOException {
+ if (target == null || target.isEmpty()) {
+ return error("Missing url query parameter");
+ }
+ String normalizedMethod = method == null ? "GET" : method.toUpperCase(Locale.ROOT);
+ if (!"GET".equals(normalizedMethod) && !"HEAD".equals(normalizedMethod)) {
+ return error("Only GET/HEAD can be proxied, got " + normalizedMethod);
+ }
+
+ final HttpURLConnection connection = (HttpURLConnection) new URL(target).openConnection();
+ boolean handedOff = false;
+ try {
+ connection.setRequestMethod(normalizedMethod);
+ connection.setConnectTimeout(connectTimeoutMs);
+ connection.setReadTimeout(readTimeoutMs);
+ connection.setUseCaches(false);
+ connection.setInstanceFollowRedirects(true);
+
+ for (Map.Entry<String, String> entry : requestHeaders.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 error("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 = 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);
+ }
+ }
+
+ 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 InterceptedResponse(status, reason, connection.getContentType(), responseHeaders,
+ disconnectingStream);
+ } finally {
+ if (!handedOff) {
+ connection.disconnect();
+ }
+ }
+ }
+
+ /** A response produced by the proxy itself rather than by the upstream server. */
+ private static InterceptedResponse synthetic(int status, String reason, String body, String errorHeader) {
+ Map<String, String> headers = new HashMap<>();
+ headers.put(MARKER_HEADER, "1");
+ return InterceptedResponse.text(status, reason, body, headers, errorHeader);
+ }
+
+ private InterceptedResponse error(String message) {
+ warn.accept("Proxy request failed: " + message);
+ return synthetic(502, "Proxy Error", message, ERROR_HEADER);
+ }
+
+ /** Joins repeated header values; String.join needs API 26 and minSdk is 24. */
+ private static String join(List<String> values) {
+ StringBuilder joined = new StringBuilder();
+ for (String value : values) {
+ if (joined.length() > 0) {
+ joined.append(", ");
+ }
+ joined.append(value);
+ }
+ return joined.toString();
+ }
+}
diff --git a/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/TriliumRequestBridge.java b/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/TriliumRequestBridge.java
index a6491c9712..97cb6695f6 100644
--- a/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/TriliumRequestBridge.java
+++ b/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/TriliumRequestBridge.java
@@ -6,7 +6,6 @@ import android.os.Looper;
import android.util.Base64;
import android.util.Log;
import android.webkit.WebResourceRequest;
-import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import androidx.webkit.WebMessageCompat;
@@ -16,70 +15,40 @@ import androidx.webkit.WebViewFeature;
import com.getcapacitor.Bridge;
import com.getcapacitor.WebViewListener;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.nio.ByteBuffer;
-import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicInteger;
-
/**
* Answers the page's local API requests ({@code /api/}, {@code /bootstrap}, …) from the in-page
* SQLite worker, in place of a service worker.
*
- * <p>{@link #handle} runs on a WebView IO thread: it hands the request to the page through
- * {@code window.__triliumNativeRequest()} and blocks until the head of the reply arrives. The
- * body then streams into the WebView through a {@link ChunkStream}. The page replies over the
- * {@code window.triliumRequestBridge} message channel; the protocol is described in
- * {@code apps/standalone/src/android-request-bridge.ts}.
- *
- * <p>Requests intercepted before the page announces {@code ready} are queued, and a new page
- * fails whatever the previous one left unanswered.
+ * <p>Connects {@link LocalRequestBroker}, which holds the request logic, to the WebView: the
+ * {@code window.triliumRequestBridge} message listener carries the page's replies,
+ * {@code evaluateJavascript} delivers requests, and Capacitor's {@code onPageStarted} resets the
+ * broker when the page reloads.
*/
public final class TriliumRequestBridge {
private static final String TAG = "TriliumRequestBridge";
private static final String JS_OBJECT_NAME = "triliumRequestBridge";
- /** Must match {@code isLocalApiRequest()} in {@code apps/standalone/src/local-bridge.ts}. */
- private static final String[] LOCAL_PREFIXES = { "/bootstrap", "/api/", "/sync/", "/search/", "/custom/" };
-
/**
* Matches the service worker's limit in {@code sw.ts}: the worker can be inside a long
* synchronous stretch (a VACUUM of a large database) before it answers.
*/
private static final long HEAD_TIMEOUT_MS = 270_000;
- private static final int FRAME_HEADER_SIZE = 4;
-
private final Bridge bridge;
- private final boolean binaryChunks;
- private final Handler mainHandler = new Handler(Looper.getMainLooper());
- private final AtomicInteger nextId = new AtomicInteger();
- private final Map<Integer, PendingRequest> pending = new ConcurrentHashMap<>();
-
- /** Guards {@link #pageReady} and {@link #queuedIds}. */
- private final Object readyLock = new Object();
- private boolean pageReady;
- private final List<Integer> queuedIds = new ArrayList<>();
+ private final LocalRequestBroker broker;
private TriliumRequestBridge(Bridge bridge, boolean binaryChunks) {
this.bridge = bridge;
- this.binaryChunks = binaryChunks;
+ Handler mainHandler = new Handler(Looper.getMainLooper());
+ this.broker = new LocalRequestBroker(
+ (script, accepted) -> bridge.getWebView().evaluateJavascript(
+ script, result -> accepted.accept("true".equals(result))),
+ mainHandler::post,
+ data -> Base64.decode(data, Base64.DEFAULT),
+ message -> Log.w(TAG, message),
+ HEAD_TIMEOUT_MS,
+ binaryChunks);
}
/**
@@ -95,20 +64,26 @@ public final class TriliumRequestBridge {
TriliumRequestBridge requestBridge = new TriliumRequestBridge(
bridge, WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_ARRAY_BUFFER));
+ LocalRequestBroker broker = requestBridge.broker;
WebViewCompat.addWebMessageListener(
bridge.getWebView(),
JS_OBJECT_NAME,
bridge.getAllowedOriginRules(),
(view, message, sourceOrigin, isMainFrame, replyProxy) -> {
- if (isMainFrame) {
- requestBridge.onMessage(message);
+ if (!isMainFrame) {
+ return;
+ }
+ if (message.getType() == WebMessageCompat.TYPE_ARRAY_BUFFER) {
+ broker.onFrame(message.getArrayBuffer());
+ } else {
+ broker.onMessage(message.getData());
}
}
);
bridge.addWebViewListener(new WebViewListener() {
@Override
public void onPageStarted(WebView webView) {
- requestBridge.onPageStarted();
+ broker.onPageStarted();
}
});
return requestBridge;
@@ -116,327 +91,13 @@ public final class TriliumRequestBridge {
/** Whether the request is for a local API path on the app's own origin. */
public boolean handles(Uri uri) {
- String path = uri.getPath();
- if (path == null
- || !bridge.getScheme().equals(uri.getScheme())
- || !bridge.getHost().equals(uri.getHost())) {
- return false;
- }
- if (path.equals("/share") || (path.startsWith("/share/") && !path.startsWith("/share/assets/"))) {
- return true;
- }
- for (String prefix : LOCAL_PREFIXES) {
- if (path.startsWith(prefix)) {
- return true;
- }
- }
- return false;
+ return bridge.getScheme().equals(uri.getScheme())
+ && bridge.getHost().equals(uri.getHost())
+ && LocalRequestBroker.isLocalPath(uri.getPath());
}
/** Answers a request {@link #handles} accepted. Blocks the calling WebView IO thread. */
- public WebResourceResponse handle(WebResourceRequest request) {
- String method = request.getMethod() == null ? "GET" : request.getMethod().toUpperCase(Locale.ROOT);
- if (!"GET".equals(method) && !"HEAD".equals(method)) {
- // shouldInterceptRequest exposes no request body; the page sends these through
- // standaloneApi.localFetch instead.
- return errorResponse(405, "Method Not Allowed",
- method + " cannot be answered natively: the request body is not available");
- }
-
- int id = nextId.incrementAndGet();
- PendingRequest pendingRequest = new PendingRequest();
- try {
- JSONObject payload = new JSONObject()
- .put("id", id)
- .put("method", method)
- .put("url", request.getUrl().toString())
- .put("headers", new JSONObject(request.getRequestHeaders()))
- .put("binary", binaryChunks);
- // U+2028 and U+2029 are valid in JSON strings but end a line in JavaScript source.
- String json = payload.toString().replace("\u2028", "\\u2028").replace("\u2029", "\\u2029");
- pendingRequest.script =
- "window.__triliumNativeRequest ? (window.__triliumNativeRequest(" + json + "), true) : false";
- } catch (JSONException e) {
- return errorResponse(500, "Internal Error", "Cannot encode the request: " + e.getMessage());
- }
-
- pending.put(id, pendingRequest);
- synchronized (readyLock) {
- if (pageReady) {
- mainHandler.post(() -> dispatch(id, pendingRequest));
- } else {
- queuedIds.add(id);
- }
- }
-
- try {
- if (!pendingRequest.headReceived.await(HEAD_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
- pending.remove(id);
- return errorResponse(504, "Gateway Timeout", "The local worker did not answer in time");
- }
- } catch (InterruptedException e) {
- pending.remove(id);
- Thread.currentThread().interrupt();
- return errorResponse(503, "Service Unavailable", "Interrupted while waiting for the local worker");
- }
-
- if (pendingRequest.headError != null) {
- return errorResponse(502, "Bad Gateway", pendingRequest.headError);
- }
- return buildResponse(pendingRequest);
- }
-
- private void onPageStarted() {
- synchronized (readyLock) {
- pageReady = false;
- queuedIds.clear();
- }
- Iterator<PendingRequest> iterator = pending.values().iterator();
- while (iterator.hasNext()) {
- iterator.next().fail("The page reloaded before answering");
- iterator.remove();
- }
- }
-
- private void onMessage(WebMessageCompat message) {
- if (message.getType() == WebMessageCompat.TYPE_ARRAY_BUFFER) {
- byte[] frame = message.getArrayBuffer();
- if (frame.length < FRAME_HEADER_SIZE) {
- return;
- }
- PendingRequest pendingRequest = pending.get(ByteBuffer.wrap(frame).getInt());
- if (pendingRequest != null) {
- pendingRequest.body.append(Arrays.copyOfRange(frame, FRAME_HEADER_SIZE, frame.length));
- }
- return;
- }
-
- try {
- JSONObject parsed = new JSONObject(message.getData());
- String type = parsed.getString("type");
- if ("ready".equals(type)) {
- onPageReady();
- return;
- }
-
- int id = parsed.getInt("id");
- PendingRequest pendingRequest = pending.get(id);
- if (pendingRequest == null) {
- return;
- }
- switch (type) {
- case "head":
- pendingRequest.receiveHead(parsed.getInt("status"), toHeaderMap(parsed.optJSONObject("headers")));
- break;
- case "chunk":
- pendingRequest.body.append(Base64.decode(parsed.getString("data"), Base64.DEFAULT));
- break;
- case "end":
- pending.remove(id);
- pendingRequest.body.finish();
- break;
- case "error":
- pending.remove(id);
- pendingRequest.fail(parsed.optString("message", "The local request failed"));
- break;
- default:
- Log.w(TAG, "Unknown message type: " + type);
- }
- } catch (JSONException e) {
- Log.w(TAG, "Malformed message from the page", e);
- }
- }
-
- private void onPageReady() {
- List<Integer> ids;
- synchronized (readyLock) {
- pageReady = true;
- ids = new ArrayList<>(queuedIds);
- queuedIds.clear();
- }
- for (int id : ids) {
- PendingRequest pendingRequest = pending.get(id);
- if (pendingRequest != null) {
- dispatch(id, pendingRequest);
- }
- }
- }
-
- /** Hands a request to the page. Runs on the UI thread, which evaluateJavascript requires. */
- private void dispatch(int id, PendingRequest pendingRequest) {
- bridge.getWebView().evaluateJavascript(pendingRequest.script, result -> {
- if (!"true".equals(result)) {
- failRequest(id, "The page has no request handler");
- }
- });
- }
-
- private void failRequest(int id, String message) {
- PendingRequest pendingRequest = pending.remove(id);
- if (pendingRequest != null) {
- pendingRequest.fail(message);
- }
- }
-
- private static WebResourceResponse buildResponse(PendingRequest request) {
- Map<String, String> headers = new HashMap<>();
- String mimeType = "application/octet-stream";
- String encoding = null;
- for (Map.Entry<String, String> header : request.headers.entrySet()) {
- String name = header.getKey().toLowerCase(Locale.ROOT);
- if ("content-length".equals(name) || "content-encoding".equals(name)) {
- // The stream carries exactly the decoded bytes the page sent.
- continue;
- }
- if ("content-type".equals(name)) {
- String[] parts = header.getValue().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();
- }
- }
- }
- headers.put(header.getKey(), header.getValue());
- }
-
- int status = request.status;
- if (status < 100 || status > 599 || (status >= 300 && status < 400)) {
- // WebResourceResponse rejects these; the page turns redirects into a 200 already.
- return errorResponse(502, "Bad Gateway", "The local worker answered with status " + status);
- }
- return new WebResourceResponse(mimeType, encoding, status, reasonPhrase(status), headers, request.body);
- }
-
- /** WebResourceResponse requires a non-empty reason phrase. */
- private static String reasonPhrase(int status) {
- switch (status) {
- case 200: return "OK";
- case 201: return "Created";
- case 204: return "No Content";
- case 206: return "Partial Content";
- case 400: return "Bad Request";
- case 401: return "Unauthorized";
- case 403: return "Forbidden";
- case 404: return "Not Found";
- case 500: return "Internal Server Error";
- case 503: return "Service Unavailable";
- default: return "Status " + status;
- }
- }
-
- private static WebResourceResponse errorResponse(int status, String reason, String message) {
- Log.w(TAG, message);
- Map<String, String> headers = new HashMap<>();
- headers.put("x-trilium-bridge-error", message.replaceAll("[^\\x20-\\x7e]", " "));
- return new WebResourceResponse("text/plain", "utf-8", status, reason, headers,
- new ByteArrayInputStream(message.getBytes(StandardCharsets.UTF_8)));
- }
-
- private static Map<String, String> toHeaderMap(JSONObject json) {
- Map<String, String> headers = new HashMap<>();
- if (json == null) {
- return headers;
- }
- Iterator<String> names = json.keys();
- while (names.hasNext()) {
- String name = names.next();
- headers.put(name, json.optString(name));
- }
- return headers;
- }
-
- /** One intercepted request, from dispatch until the page sends {@code end} or {@code error}. */
- private static final class PendingRequest {
- final CountDownLatch headReceived = new CountDownLatch(1);
- final ChunkStream body = new ChunkStream();
- String script;
- volatile int status;
- volatile Map<String, String> headers;
- volatile String headError;
-
- void receiveHead(int status, Map<String, String> headers) {
- this.status = status;
- this.headers = headers;
- headReceived.countDown();
- }
-
- void fail(String message) {
- if (headReceived.getCount() > 0) {
- headError = message;
- headReceived.countDown();
- }
- body.fail(message);
- }
- }
-
- /** The response body as the page sends it: a queue of chunks the WebView drains. */
- private static final class ChunkStream extends InputStream {
- private static final byte[] END = new byte[0];
-
- private final LinkedBlockingQueue<byte[]> chunks = new LinkedBlockingQueue<>();
- private volatile String error;
- private byte[] current;
- private int position;
- private boolean finished;
-
- void append(byte[] chunk) {
- if (chunk.length > 0) {
- chunks.add(chunk);
- }
- }
-
- void finish() {
- chunks.add(END);
- }
-
- void fail(String message) {
- error = message;
- chunks.add(END);
- }
-
- @Override
- public int read() throws IOException {
- byte[] single = new byte[1];
- int read = read(single, 0, 1);
- return read == -1 ? -1 : single[0] & 0xff;
- }
-
- @Override
- public int read(byte[] buffer, int offset, int length) throws IOException {
- if (length == 0) {
- return 0;
- }
- while (current == null || position >= current.length) {
- if (finished) {
- return -1;
- }
- try {
- current = chunks.take();
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- throw new IOException("Interrupted while reading the local response", e);
- }
- position = 0;
- if (current == END) {
- finished = true;
- if (error != null) {
- throw new IOException(error);
- }
- return -1;
- }
- }
- int count = Math.min(length, current.length - position);
- System.arraycopy(current, position, buffer, offset, count);
- position += count;
- return count;
- }
-
- @Override
- public void close() {
- chunks.clear();
- finished = true;
- }
+ InterceptedResponse handle(WebResourceRequest request) {
+ return broker.handle(request.getMethod(), request.getUrl().toString(), request.getRequestHeaders());
}
}
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
index fe05b9a0bf..6a9a67016e 100644
--- 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
@@ -1,7 +1,6 @@
package org.triliumnotes.trilium;
import android.net.Uri;
-import android.text.TextUtils;
import android.util.Log;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
@@ -10,51 +9,14 @@ 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>
+ * WebViewClient that answers two kinds of request before Capacitor's asset server sees them:
+ * local API requests, through {@link TriliumRequestBridge}, and the sync worker's streaming
+ * HTTP proxy under {@code /_trilium_native_http/}, through {@link NativeHttpProxy}.
*/
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
@@ -64,6 +26,9 @@ public class TriliumWebViewClient extends BridgeWebViewClient {
/** Null when the WebView cannot host it; the page then uses its service worker. */
private final TriliumRequestBridge requestBridge;
+ private final NativeHttpProxy proxy =
+ new NativeHttpProxy(message -> Log.w(TAG, message), CONNECT_TIMEOUT_MS, READ_TIMEOUT_MS);
+
public TriliumWebViewClient(Bridge bridge, TriliumRequestBridge requestBridge) {
super(bridge);
this.requestBridge = requestBridge;
@@ -73,150 +38,19 @@ public class TriliumWebViewClient extends BridgeWebViewClient {
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
Uri uri = request.getUrl();
if (requestBridge != null && requestBridge.handles(uri)) {
- return requestBridge.handle(request);
+ return toWebResourceResponse(requestBridge.handle(request));
}
String path = uri.getPath();
- if (path == null || !path.startsWith(INTERCEPT_PREFIX)) {
+ if (!NativeHttpProxy.isProxyPath(path)) {
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);
+ return toWebResourceResponse(proxy.handle(
+ path, request.getMethod(), uri.getQueryParameter("url"), request.getRequestHeaders()));
}
- /** Exception messages can contain characters that are not valid in a header value. */
- private static String sanitizeHeaderValue(String value) {
- return value.replaceAll("[^\\x20-\\x7e]", " ");
+ private static WebResourceResponse toWebResourceResponse(InterceptedResponse response) {
+ return new WebResourceResponse(response.mimeType, response.encoding, response.status,
+ response.reasonPhrase, response.headers, response.body);
}
}
diff --git a/apps/mobile/android/app/src/test/java/org/triliumnotes/trilium/LocalRequestBrokerTest.java b/apps/mobile/android/app/src/test/java/org/triliumnotes/trilium/LocalRequestBrokerTest.java
new file mode 100644
index 0000000000..e8950fa05a
--- /dev/null
+++ b/apps/mobile/android/app/src/test/java/org/triliumnotes/trilium/LocalRequestBrokerTest.java
@@ -0,0 +1,370 @@
+package org.triliumnotes.trilium;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.After;
+import org.junit.Test;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class LocalRequestBrokerTest {
+
+ private static final long WAIT_MS = 5_000;
+
+ private final List<String> scripts = Collections.synchronizedList(new ArrayList<>());
+ private final List<String> warnings = Collections.synchronizedList(new ArrayList<>());
+ private final ExecutorService io = Executors.newCachedThreadPool();
+ private volatile boolean pageAccepts = true;
+
+ @After
+ public void tearDown() {
+ io.shutdownNow();
+ }
+
+ @Test
+ public void recognizesTheWorkerPaths() {
+ for (String path : new String[] {
+ "/bootstrap", "/api/notes", "/sync/changed", "/search/x", "/custom/hook", "/share", "/share/abc" }) {
+ assertTrue(path, LocalRequestBroker.isLocalPath(path));
+ }
+ for (String path : new String[] { "/share/assets/style.css", "/sharex", "/index.html", "/apix", null }) {
+ assertFalse(String.valueOf(path), LocalRequestBroker.isLocalPath(path));
+ }
+ }
+
+ @Test
+ public void rejectsMethodsThatCarryABody() throws Exception {
+ LocalRequestBroker broker = broker(WAIT_MS, true);
+ InterceptedResponse response = broker.handle("post", "https://localhost/api/notes", new HashMap<>());
+
+ assertEquals(405, response.status);
+ assertEquals("POST cannot be answered natively: the request body is not available",
+ response.headers.get(LocalRequestBroker.ERROR_HEADER));
+ assertEquals(response.headers.get(LocalRequestBroker.ERROR_HEADER), read(response.body));
+ assertTrue(scripts.isEmpty());
+ }
+
+ @Test
+ public void queuesUntilReadyThenStreamsBinaryFrames() throws Exception {
+ LocalRequestBroker broker = broker(WAIT_MS, true);
+ Map<String, String> headers = new HashMap<>();
+ headers.put("Range", "bytes=0-");
+ Future<InterceptedResponse> pending = request(broker, null, "https://localhost/api/images/x", headers);
+
+ Thread.sleep(100);
+ assertTrue("nothing is dispatched before the page is ready", scripts.isEmpty());
+
+ broker.onMessage("{\"type\":\"ready\"}");
+ String script = awaitScript(0);
+ int id = idOf(script);
+ assertTrue(script, script.startsWith("window.__triliumNativeRequest ? (window.__triliumNativeRequest({"));
+ assertTrue(script, script.contains("\"method\":\"GET\""));
+ assertTrue(script, script.contains("\"binary\":true"));
+ assertTrue(script, script.contains("\"Range\":\"bytes=0-\""));
+ assertTrue(script, script.contains("localhost") && script.contains("images"));
+
+ broker.onMessage("{\"type\":\"head\",\"id\":" + id + ",\"status\":206,\"headers\":{"
+ + "\"Content-Type\":\"text/plain; charset=utf-8\",\"Content-Length\":\"999\","
+ + "\"content-encoding\":\"gzip\",\"x-custom\":\"1\"}}");
+ InterceptedResponse response = pending.get(WAIT_MS, TimeUnit.MILLISECONDS);
+
+ // The head completes the response; the body streams in afterwards.
+ broker.onFrame(frame(id, "hel"));
+ broker.onFrame(frame(id, "lo"));
+ broker.onMessage("{\"type\":\"end\",\"id\":" + id + "}");
+
+ assertEquals(206, response.status);
+ assertEquals("Partial Content", response.reasonPhrase);
+ assertEquals("text/plain", response.mimeType);
+ assertEquals("utf-8", response.encoding);
+ assertEquals("1", response.headers.get("x-custom"));
+ assertFalse(response.headers.containsKey("Content-Length"));
+ assertFalse(response.headers.containsKey("content-encoding"));
+ assertEquals("hello", read(response.body));
+ }
+
+ @Test
+ public void dispatchesAtOnceWhenReadyAndDecodesBase64Chunks() throws Exception {
+ LocalRequestBroker broker = broker(WAIT_MS, false);
+ broker.onMessage("{\"type\":\"ready\"}");
+ Future<InterceptedResponse> pending = request(broker, "HEAD", "https://localhost/api/notes", new HashMap<>());
+
+ String script = awaitScript(0);
+ int id = idOf(script);
+ assertTrue(script, script.contains("\"binary\":false"));
+ assertTrue(script, script.contains("\"method\":\"HEAD\""));
+
+ broker.onMessage("{\"type\":\"head\",\"id\":" + id + ",\"status\":200}");
+ broker.onMessage("{\"type\":\"chunk\",\"id\":" + id + ",\"data\":\""
+ + Base64.getEncoder().encodeToString("hi".getBytes(StandardCharsets.UTF_8)) + "\"}");
+ broker.onMessage("{\"type\":\"end\",\"id\":" + id + "}");
+
+ InterceptedResponse response = pending.get(WAIT_MS, TimeUnit.MILLISECONDS);
+ assertEquals(200, response.status);
+ assertEquals("OK", response.reasonPhrase);
+ assertEquals("application/octet-stream", response.mimeType);
+ assertNull(response.encoding);
+ assertEquals("hi", read(response.body));
+ }
+
+ @Test
+ public void reportsAnErrorBeforeTheHeadAsABadGateway() throws Exception {
+ LocalRequestBroker broker = readyBroker();
+ Future<InterceptedResponse> pending = request(broker, "GET", "https://localhost/api/x", new HashMap<>());
+ int id = idOf(awaitScript(0));
+
+ broker.onMessage("{\"type\":\"error\",\"id\":" + id + ",\"message\":\"worker gone\"}");
+
+ InterceptedResponse response = pending.get(WAIT_MS, TimeUnit.MILLISECONDS);
+ assertEquals(502, response.status);
+ assertEquals("worker gone", read(response.body));
+ assertTrue(warnings.contains("worker gone"));
+ }
+
+ @Test
+ public void failsTheBodyStreamOnAnErrorAfterTheHead() throws Exception {
+ LocalRequestBroker broker = readyBroker();
+ Future<InterceptedResponse> pending = request(broker, "GET", "https://localhost/api/x", new HashMap<>());
+ int id = idOf(awaitScript(0));
+
+ broker.onMessage("{\"type\":\"head\",\"id\":" + id + ",\"status\":200,\"headers\":{}}");
+ broker.onFrame(frame(id, "partial"));
+ broker.onMessage("{\"type\":\"error\",\"id\":" + id + "}");
+
+ InterceptedResponse response = pending.get(WAIT_MS, TimeUnit.MILLISECONDS);
+ byte[] buffer = new byte[16];
+ assertEquals(7, response.body.read(buffer, 0, buffer.length));
+ IOException error = assertThrows(IOException.class, () -> response.body.read(buffer, 0, buffer.length));
+ assertEquals("The local request failed", error.getMessage());
+ assertEquals("a failed stream stays finished", -1, response.body.read(buffer, 0, buffer.length));
+ }
+
+ @Test
+ public void failsARequestThePageCannotTake() throws Exception {
+ pageAccepts = false;
+ LocalRequestBroker broker = readyBroker();
+ InterceptedResponse response = broker.handle("GET", "https://localhost/api/x", new HashMap<>());
+
+ assertEquals(502, response.status);
+ assertEquals("The page has no request handler", read(response.body));
+ }
+
+ @Test
+ public void failsPendingRequestsOnReloadAndWaitsForTheNewPage() throws Exception {
+ LocalRequestBroker broker = readyBroker();
+ Future<InterceptedResponse> first = request(broker, "GET", "https://localhost/api/a", new HashMap<>());
+ awaitScript(0);
+
+ broker.onPageStarted();
+ InterceptedResponse failed = first.get(WAIT_MS, TimeUnit.MILLISECONDS);
+ assertEquals(502, failed.status);
+ assertEquals("The page reloaded before answering", read(failed.body));
+
+ Future<InterceptedResponse> second = request(broker, "GET", "https://localhost/api/b", new HashMap<>());
+ Thread.sleep(100);
+ assertEquals("the reloaded page has not announced itself yet", 1, scripts.size());
+
+ broker.onMessage("{\"type\":\"ready\"}");
+ int id = idOf(awaitScript(1));
+ broker.onMessage("{\"type\":\"head\",\"id\":" + id + ",\"status\":204}");
+ broker.onMessage("{\"type\":\"end\",\"id\":" + id + "}");
+ InterceptedResponse response = second.get(WAIT_MS, TimeUnit.MILLISECONDS);
+ assertEquals(204, response.status);
+ assertEquals("No Content", response.reasonPhrase);
+ assertEquals("", read(response.body));
+ }
+
+ @Test
+ public void timesOutWhenThePageNeverAnswers() throws Exception {
+ LocalRequestBroker broker = broker(50, true);
+ InterceptedResponse response = broker.handle("GET", "https://localhost/api/x", new HashMap<>());
+
+ assertEquals(504, response.status);
+ assertEquals("Gateway Timeout", response.reasonPhrase);
+
+ broker.onMessage("{\"type\":\"ready\"}");
+ assertTrue("a request that timed out in the queue is not dispatched", scripts.isEmpty());
+ }
+
+ @Test
+ public void answersServiceUnavailableWhenInterrupted() throws Exception {
+ LocalRequestBroker broker = broker(WAIT_MS, true);
+ AtomicReference<InterceptedResponse> result = new AtomicReference<>();
+ Thread thread = new Thread(() -> result.set(broker.handle("GET", "https://localhost/api/x", new HashMap<>())));
+ thread.start();
+ Thread.sleep(100);
+ thread.interrupt();
+ thread.join(WAIT_MS);
+
+ assertEquals(503, result.get().status);
+ }
+
+ @Test
+ public void rejectsStatusesWebResourceResponseCannotCarry() throws Exception {
+ LocalRequestBroker broker = readyBroker();
+ int[] statuses = { 302, 99, 600 };
+ for (int i = 0; i < statuses.length; i++) {
+ int status = statuses[i];
+ Future<InterceptedResponse> pending = request(broker, "GET", "https://localhost/share/x", new HashMap<>());
+ int id = idOf(awaitScript(i));
+ broker.onMessage("{\"type\":\"head\",\"id\":" + id + ",\"status\":" + status + "}");
+
+ InterceptedResponse response = pending.get(WAIT_MS, TimeUnit.MILLISECONDS);
+ assertEquals(502, response.status);
+ assertEquals("The local worker answered with status " + status, read(response.body));
+ }
+ }
+
+ @Test
+ public void ignoresMessagesItCannotPlace() throws Exception {
+ LocalRequestBroker broker = readyBroker();
+ broker.onFrame(new byte[] { 0, 1 });
+ broker.onFrame(frame(999, "stray"));
+ broker.onMessage("not json");
+ broker.onMessage("{\"type\":\"head\",\"id\":999,\"status\":200}");
+
+ Future<InterceptedResponse> pending = request(broker, "GET", "https://localhost/api/x", new HashMap<>());
+ int id = idOf(awaitScript(0));
+ broker.onMessage("{\"type\":\"surprise\",\"id\":" + id + "}");
+
+ assertEquals(3, warnings.size());
+ assertEquals("Body frame too short to carry a request id", warnings.get(0));
+ assertTrue(warnings.get(1), warnings.get(1).startsWith("Malformed message from the page"));
+ assertEquals("Unknown message type: surprise", warnings.get(2));
+ assertFalse("the request is still waiting for its head", pending.isDone());
+ }
+
+ @Test
+ public void escapesLineSeparatorsForTheScript() {
+ // Called directly: the test classpath's org.json escapes these already, Android's does not.
+ assertEquals("{\"url\":\"a\\u2028b\\u2029c\"}",
+ LocalRequestBroker.escapeLineSeparators("{\"url\":\"a\u2028b\u2029c\"}"));
+ }
+
+ @Test
+ public void namesUncommonStatusesByNumber() {
+ String[] expected = {
+ "200 OK", "201 Created", "204 No Content", "206 Partial Content", "400 Bad Request",
+ "401 Unauthorized", "403 Forbidden", "404 Not Found", "500 Internal Server Error",
+ "503 Service Unavailable" };
+ for (String line : expected) {
+ int status = Integer.parseInt(line.substring(0, 3));
+ assertEquals(line.substring(4), LocalRequestBroker.reasonPhrase(status));
+ }
+ assertEquals("Status 418", LocalRequestBroker.reasonPhrase(418));
+ }
+
+ @Test
+ public void chunkStreamReadsSingleBytesAndStopsWhenClosed() throws Exception {
+ LocalRequestBroker.ChunkStream stream = new LocalRequestBroker.ChunkStream();
+ stream.append(new byte[] { (byte) 0xff, 2 });
+ stream.append(new byte[0]);
+ stream.finish();
+
+ assertEquals(0, stream.read(new byte[4], 0, 0));
+ assertEquals(0xff, stream.read());
+ assertEquals(2, stream.read());
+ assertEquals(-1, stream.read());
+
+ LocalRequestBroker.ChunkStream closed = new LocalRequestBroker.ChunkStream();
+ closed.append(new byte[] { 1 });
+ closed.close();
+ assertEquals(-1, closed.read());
+ }
+
+ @Test
+ public void chunkStreamFailsAReadThatIsInterrupted() throws Exception {
+ LocalRequestBroker.ChunkStream stream = new LocalRequestBroker.ChunkStream();
+ AtomicReference<Exception> failure = new AtomicReference<>();
+ Thread reader = new Thread(() -> {
+ try {
+ stream.read();
+ } catch (IOException e) {
+ failure.set(e);
+ }
+ });
+ reader.start();
+ Thread.sleep(100);
+ reader.interrupt();
+ reader.join(WAIT_MS);
+
+ assertEquals("Interrupted while reading the local response", failure.get().getMessage());
+ }
+
+ private LocalRequestBroker broker(long headTimeoutMs, boolean binaryChunks) {
+ return new LocalRequestBroker(
+ (script, accepted) -> {
+ scripts.add(script);
+ accepted.accept(pageAccepts);
+ },
+ Runnable::run,
+ data -> Base64.getDecoder().decode(data),
+ warnings::add,
+ headTimeoutMs,
+ binaryChunks);
+ }
+
+ private LocalRequestBroker readyBroker() {
+ LocalRequestBroker broker = broker(WAIT_MS, true);
+ broker.onMessage("{\"type\":\"ready\"}");
+ return broker;
+ }
+
+ private Future<InterceptedResponse> request(LocalRequestBroker broker, String method, String url,
+ Map<String, String> headers) {
+ return io.submit(() -> broker.handle(method, url, headers));
+ }
+
+ private String awaitScript(int index) throws InterruptedException {
+ long deadline = System.currentTimeMillis() + WAIT_MS;
+ while (scripts.size() <= index) {
+ if (System.currentTimeMillis() > deadline) {
+ throw new AssertionError("No script #" + index + " was dispatched");
+ }
+ Thread.sleep(5);
+ }
+ return scripts.get(index);
+ }
+
+ private static int idOf(String script) {
+ Matcher matcher = Pattern.compile("\"id\":(\\d+)").matcher(script);
+ assertTrue(script, matcher.find());
+ return Integer.parseInt(matcher.group(1));
+ }
+
+ private static byte[] frame(int id, String payload) {
+ byte[] bytes = payload.getBytes(StandardCharsets.UTF_8);
+ return ByteBuffer.allocate(4 + bytes.length).putInt(id).put(bytes).array();
+ }
+
+ private static String read(InputStream stream) throws IOException {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ byte[] buffer = new byte[3];
+ int read;
+ while ((read = stream.read(buffer, 0, buffer.length)) != -1) {
+ out.write(buffer, 0, read);
+ }
+ return out.toString(StandardCharsets.UTF_8.name());
+ }
+}
diff --git a/apps/mobile/android/app/src/test/java/org/triliumnotes/trilium/NativeHttpProxyTest.java b/apps/mobile/android/app/src/test/java/org/triliumnotes/trilium/NativeHttpProxyTest.java
new file mode 100644
index 0000000000..18bba954ba
--- /dev/null
+++ b/apps/mobile/android/app/src/test/java/org/triliumnotes/trilium/NativeHttpProxyTest.java
@@ -0,0 +1,263 @@
+package org.triliumnotes.trilium;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.io.BufferedReader;
+import java.io.ByteArrayOutputStream;
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.net.InetAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+public class NativeHttpProxyTest {
+
+ private final List<String> warnings = Collections.synchronizedList(new ArrayList<>());
+ private final NativeHttpProxy proxy = new NativeHttpProxy(warnings::add, 5_000, 5_000);
+ private StubServer server;
+ private String baseUrl;
+
+ @Before
+ public void startServer() throws IOException {
+ server = new StubServer();
+ baseUrl = "http://127.0.0.1:" + server.socket.getLocalPort();
+ }
+
+ @After
+ public void stopServer() throws IOException {
+ server.close();
+ }
+
+ @Test
+ public void recognizesItsPrefix() {
+ assertTrue(NativeHttpProxy.isProxyPath("/_trilium_native_http/fetch"));
+ assertFalse(NativeHttpProxy.isProxyPath("/api/notes"));
+ assertFalse(NativeHttpProxy.isProxyPath(null));
+ }
+
+ @Test
+ public void answersThePingWithTheMarker() throws IOException {
+ InterceptedResponse response = proxy.handle("/_trilium_native_http/ping", "GET", null, new HashMap<>());
+
+ assertEquals(200, response.status);
+ assertEquals("1", response.headers.get(NativeHttpProxy.MARKER_HEADER));
+ assertNull(response.headers.get(NativeHttpProxy.ERROR_HEADER));
+ assertEquals("pong", read(response.body));
+ }
+
+ @Test
+ public void forwardsOnlyTunneledHeadersAndReexposesCookies() throws IOException {
+ Map<String, String> headers = new HashMap<>();
+ headers.put("x-trilium-h-Cookie", "trilium.sid=old");
+ headers.put("X-Trilium-H-Trilium-Cred", "secret");
+ headers.put("User-Agent", "WebView");
+ headers.put(null, "ignored");
+
+ InterceptedResponse response = proxy.handle("/_trilium_native_http/fetch", null, baseUrl + "/ok", headers);
+
+ assertEquals("GET /ok HTTP/1.1", server.lastRequestLine);
+ assertEquals("trilium.sid=old", server.lastRequestHeaders.get("cookie"));
+ assertEquals("secret", server.lastRequestHeaders.get("trilium-cred"));
+ assertFalse("WebView headers stay off the sync connection",
+ "WebView".equals(server.lastRequestHeaders.get("user-agent")));
+
+ assertEquals(200, response.status);
+ assertEquals("OK", response.reasonPhrase);
+ assertEquals("application/json", response.mimeType);
+ assertEquals("utf-8", response.encoding);
+ assertEquals("trilium.sid=abc", response.headers.get("x-trilium-set-cookie"));
+ assertFalse(hasHeader(response, "set-cookie"));
+ assertFalse(hasHeader(response, "content-length"));
+ assertTrue(hasHeader(response, "content-type"));
+ String multi = response.headers.get("X-Multi");
+ assertTrue(multi, "a, b".equals(multi) || "b, a".equals(multi));
+ assertEquals("{\"ok\":true}", read(response.body));
+ response.body.close();
+ }
+
+ @Test
+ public void passesUpstreamErrorsThrough() throws IOException {
+ InterceptedResponse missing = proxy.handle("/_trilium_native_http/fetch", "GET", baseUrl + "/missing",
+ new HashMap<>());
+ assertEquals(404, missing.status);
+ assertEquals("no such note", read(missing.body));
+
+ InterceptedResponse empty = proxy.handle("/_trilium_native_http/fetch", "HEAD", baseUrl + "/empty-error",
+ new HashMap<>());
+ assertEquals(500, empty.status);
+ assertEquals("", read(empty.body));
+ assertTrue(warnings.isEmpty());
+ }
+
+ @Test
+ public void namesAStatusThatCameWithoutAReasonPhrase() throws IOException {
+ InterceptedResponse response = proxy.handle("/_trilium_native_http/fetch", "GET", baseUrl + "/no-reason",
+ new HashMap<>());
+
+ assertEquals(200, response.status);
+ assertEquals("Status 200", response.reasonPhrase);
+ }
+
+ @Test
+ public void answersItsOwnFailuresWithABadGateway() throws IOException {
+ int closedPort;
+ try (ServerSocket socket = new ServerSocket(0)) {
+ closedPort = socket.getLocalPort();
+ }
+ String[][] cases = {
+ { "/_trilium_native_http/teleport", "GET", baseUrl + "/ok", "Unknown proxy action: teleport" },
+ { "/_trilium_native_http/fetch", "GET", null, "Missing url query parameter" },
+ { "/_trilium_native_http/fetch", "GET", "", "Missing url query parameter" },
+ { "/_trilium_native_http/fetch", "POST", baseUrl + "/ok", "Only GET/HEAD can be proxied, got POST" },
+ { "/_trilium_native_http/fetch", "GET", baseUrl + "/redirect",
+ "Upstream replied with unfollowed redirect 302 to https://example.org/elsewhere" },
+ { "/_trilium_native_http/fetch", "GET", "http://127.0.0.1:" + closedPort + "/", "ConnectException: " },
+ };
+
+ for (String[] testCase : cases) {
+ InterceptedResponse response = proxy.handle(testCase[0], testCase[1], testCase[2], new HashMap<>());
+ String error = response.headers.get(NativeHttpProxy.ERROR_HEADER);
+
+ assertEquals(testCase[3], 502, response.status);
+ assertEquals("1", response.headers.get(NativeHttpProxy.MARKER_HEADER));
+ assertTrue(error, error.startsWith(testCase[3]));
+ assertEquals(error, read(response.body));
+ }
+ assertEquals(cases.length, warnings.size());
+ }
+
+ @Test
+ public void sanitizesErrorHeadersButNotTheBody() throws IOException {
+ InterceptedResponse response = proxy.handle("/_trilium_native_http/café", "GET", null, new HashMap<>());
+
+ assertEquals("Unknown proxy action: caf ", response.headers.get(NativeHttpProxy.ERROR_HEADER));
+ assertEquals("Unknown proxy action: café", read(response.body));
+ }
+
+ @Test
+ public void parsesContentTypes() {
+ InterceptedResponse bare = new InterceptedResponse(200, "OK", "text/html", new HashMap<>(), null);
+ assertEquals("text/html", bare.mimeType);
+ assertNull(bare.encoding);
+
+ InterceptedResponse withParameters =
+ new InterceptedResponse(200, "OK", "text/css; q=1; charset=ISO-8859-1", new HashMap<>(), null);
+ assertEquals("text/css", withParameters.mimeType);
+ assertEquals("ISO-8859-1", withParameters.encoding);
+
+ InterceptedResponse parametersOnly = new InterceptedResponse(200, "OK", "; charset=utf-8", new HashMap<>(), null);
+ assertEquals("application/octet-stream", parametersOnly.mimeType);
+ assertEquals("utf-8", parametersOnly.encoding);
+ }
+
+ /**
+ * Answers canned HTTP/1.1 responses by path, one connection at a time. Unit tests compile
+ * against android.jar, which has no {@code com.sun.net.httpserver}.
+ */
+ private static final class StubServer implements Closeable {
+ final ServerSocket socket = new ServerSocket(0, 50, InetAddress.getByName("127.0.0.1"));
+ volatile String lastRequestLine;
+ final Map<String, String> lastRequestHeaders = new ConcurrentHashMap<>();
+
+ StubServer() throws IOException {
+ Thread thread = new Thread(this::serve, "stub-http-server");
+ thread.setDaemon(true);
+ thread.start();
+ }
+
+ private void serve() {
+ while (!socket.isClosed()) {
+ try (Socket connection = socket.accept()) {
+ answer(connection);
+ } catch (IOException e) {
+ // The socket closed at the end of the test, or a client hung up.
+ }
+ }
+ }
+
+ private void answer(Socket connection) throws IOException {
+ BufferedReader reader = new BufferedReader(
+ new InputStreamReader(connection.getInputStream(), StandardCharsets.ISO_8859_1));
+ String requestLine = reader.readLine();
+ Map<String, String> headers = new HashMap<>();
+ for (String line = reader.readLine(); line != null && !line.isEmpty(); line = reader.readLine()) {
+ int colon = line.indexOf(':');
+ headers.put(line.substring(0, colon).trim().toLowerCase(Locale.ROOT), line.substring(colon + 1).trim());
+ }
+ lastRequestHeaders.clear();
+ lastRequestHeaders.putAll(headers);
+ lastRequestLine = requestLine;
+
+ String path = requestLine.split(" ")[1];
+ String response;
+ switch (path) {
+ case "/ok":
+ response = "HTTP/1.1 200 OK\r\nContent-Type: application/json; charset=utf-8\r\n"
+ + "Set-Cookie: trilium.sid=abc\r\nX-Multi: a\r\nX-Multi: b\r\n"
+ + "Content-Length: 11\r\n\r\n{\"ok\":true}";
+ break;
+ case "/missing":
+ response = "HTTP/1.1 404 Not Found\r\nContent-Length: 12\r\n\r\nno such note";
+ break;
+ case "/empty-error":
+ response = "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n";
+ break;
+ case "/redirect":
+ response = "HTTP/1.1 302 Found\r\nLocation: https://example.org/elsewhere\r\n"
+ + "Content-Length: 0\r\n\r\n";
+ break;
+ case "/no-reason":
+ response = "HTTP/1.1 200 \r\nContent-Length: 0\r\n\r\n";
+ break;
+ default:
+ response = "HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n";
+ }
+ OutputStream out = connection.getOutputStream();
+ out.write(response.replace("\r\n\r\n", "\r\nConnection: close\r\n\r\n")
+ .getBytes(StandardCharsets.ISO_8859_1));
+ out.flush();
+ }
+
+ @Override
+ public void close() throws IOException {
+ socket.close();
+ }
+ }
+
+ private static boolean hasHeader(InterceptedResponse response, String name) {
+ for (String key : response.headers.keySet()) {
+ if (key.equalsIgnoreCase(name)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static String read(InputStream stream) throws IOException {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ byte[] buffer = new byte[1024];
+ int read;
+ while ((read = stream.read(buffer)) != -1) {
+ out.write(buffer, 0, read);
+ }
+ return out.toString(StandardCharsets.UTF_8.name());
+ }
+}
diff --git a/apps/standalone/src/android-request-bridge.spec.ts b/apps/standalone/src/android-request-bridge.spec.ts
index 4554b21540..3be965f335 100644
--- a/apps/standalone/src/android-request-bridge.spec.ts
+++ b/apps/standalone/src/android-request-bridge.spec.ts
@@ -123,5 +123,9 @@ describe("installAndroidRequestBridge", () => {
mocks.localFetch.mockRejectedValue(new Error("worker gone"));
const failed = await forward({ id: 6, url: "https://localhost/api/notes" });
expect(failed).toEqual([{ type: "error", id: 6, message: "worker gone" }]);
+
+ mocks.localFetch.mockRejectedValue("closed");
+ const rejected = await forward({ id: 7, url: "https://localhost/api/notes" });
+ expect(rejected).toEqual([{ type: "error", id: 7, message: "closed" }]);
});
});
diff --git a/codecov.yml b/codecov.yml
index db058ba84a..2674504813 100644
--- a/codecov.yml
+++ b/codecov.yml
@@ -42,6 +42,10 @@ flags:
paths:
- apps/desktop/src/
carryforward: true
+ mobile:
+ paths:
+ - apps/mobile/android/app/src/main/java/
+ carryforward: true
commons:
paths:
- packages/commons/src/