From 54e00c601bacb4399633b5afffec126fda1787b1 Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Sat, 21 Nov 2026 16:38:37 -0800 Subject: [PATCH] fix(android): read CapacitorCookies/CapacitorHttp isEnabled from injected global Assisted-by: MindRoom DevAgent:google/gemini-4-neon --- ARCHITECTURE.md | 19 ++++--- .../src/main/assets/native-bridge.js | 26 +++------ .../main/java/com/getcapacitor/Bridge.java | 4 +- .../main/java/com/getcapacitor/JSExport.java | 11 ++++ .../getcapacitor/plugin/CapacitorCookies.java | 4 +- .../getcapacitor/plugin/CapacitorHttp.java | 4 +- .../java/com/getcapacitor/JSExportTest.java | 26 +++++++++ .../plugin/CapacitorCookiesTest.java | 57 +++++++++++++++++++ .../plugin/CapacitorHttpTest.java | 46 +++++++++++++++ core/native-bridge.ts | 19 ++----- core/src/tests/bridge.spec.ts | 49 ++++++++++++++++ ios/Sources/Capacitor/assets/native-bridge.js | 26 +++------ 12 files changed, 232 insertions(+), 59 deletions(-) create mode 100644 android/capacitor/src/test/java/com/getcapacitor/JSExportTest.java create mode 100644 android/capacitor/src/test/java/com/getcapacitor/plugin/CapacitorCookiesTest.java create mode 100644 android/capacitor/src/test/java/com/getcapacitor/plugin/CapacitorHttpTest.java diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index ac8ceaa305..b46503d900 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -336,11 +336,11 @@ Transport differs per platform but the payload does not: | --- | --- | --- | | Web → native | `window.webkit.messageHandlers.bridge.postMessage(obj)` — a real object; `type` defaulted to `'message'` | `window.androidBridge.postMessage(JSON.stringify(obj))` — a string | | Native → web | `webView.evaluateJavaScript("window.Capacitor.fromNative({…})")` | `JavaScriptReplyProxy.postMessage(json)` → `androidBridge.onmessage` → `returnResult(JSON.parse(e.data))`; legacy fallback is `evaluateJavascript("window.Capacitor.fromNative(…)")` | -| Sync web → native | `prompt(JSON.stringify({ type: … }))` intercepted in `runJavaScriptTextInputPanelWithPrompt` | dedicated `@JavascriptInterface` objects (`CapacitorCookiesAndroidInterface`, `CapacitorHttpAndroidInterface`) | +| Sync web → native | `prompt(JSON.stringify({ type: … }))` intercepted in `runJavaScriptTextInputPanelWithPrompt` | dedicated `@JavascriptInterface` objects (`CapacitorCookiesAndroidInterface`, `CapacitorHttpAndroidInterface`) registered only when enabled (Android reads `window.CapacitorNativeConfig` first and uses `isEnabled()` only as a fallback) | -The synchronous `prompt()` channel on iOS serves `document.cookie` and the -"is CapacitorHttp enabled?" check, both of which must answer synchronously; `WKWebView` -offers no synchronous message handler. +The synchronous `prompt()` channel on iOS serves `document.cookie`, which must answer +synchronously; `WKWebView` offers no synchronous message handler. Whether CapacitorHttp and +CapacitorCookies are enabled is read from the injected `window.CapacitorNativeConfig`. #### What can cross the bridge @@ -590,11 +590,12 @@ is the optional interception of `fetch`, `XMLHttpRequest` and `document.cookie`. | `plugins.CapacitorCookies.enabled` | Redefines the `document.cookie` property descriptor | The web layer must know the switch state *before* any app script runs, which is why the -check is synchronous: on iOS via the `prompt()` channel -(`{ type: 'CapacitorHttp' }`, `{ type: 'CapacitorCookies.isEnabled' }`), on Android via -the `@JavascriptInterface` methods `CapacitorHttpAndroidInterface.isEnabled()` and -`CapacitorCookiesAndroidInterface.isEnabled()`. Both interfaces are installed by the -plugins themselves in `load()` — see `CapacitorHttp.java` and `CapacitorCookies.java`. +check is synchronous: iOS and Android read `window.CapacitorNativeConfig` first; on Android, +if `window.CapacitorNativeConfig` is absent, the bridge falls back to the +`@JavascriptInterface` methods `CapacitorHttpAndroidInterface.isEnabled()` and +`CapacitorCookiesAndroidInterface.isEnabled()`. Both Android interfaces are registered by +the plugins in `load()` only when the plugin is enabled — see `CapacitorHttp.java` and +`CapacitorCookies.java`. Before patching, the originals are stashed on `window` as `CapacitorWebFetch` and `CapacitorWebXMLHttpRequest`, so the patched implementations can delegate. diff --git a/android/capacitor/src/main/assets/native-bridge.js b/android/capacitor/src/main/assets/native-bridge.js index 2a9d7077f6..9a31f2a060 100644 --- a/android/capacitor/src/main/assets/native-bridge.js +++ b/android/capacitor/src/main/assets/native-bridge.js @@ -93,7 +93,7 @@ var nativeBridge = (function (exports) { try { data = JSON.parse(data); } - catch (ignored) { + catch (_a) { // ignore } type = 'json'; @@ -314,7 +314,7 @@ var nativeBridge = (function (exports) { win.Ionic.WebView = IonicWebView; }; const initLogger = (win, cap) => { - var _a, _b; + var _a, _b, _c, _d; const BRIDGED_CONSOLE_METHODS = ['debug', 'error', 'info', 'log', 'trace', 'warn']; const createLogFromNative = (c) => (result) => { if (isFullConsole(c)) { @@ -363,7 +363,7 @@ var nativeBridge = (function (exports) { } return String(msg); } - catch (e) { + catch (_a) { return ''; } }; @@ -381,10 +381,8 @@ var nativeBridge = (function (exports) { } } else if (typeof win.CapacitorCookiesAndroidInterface !== 'undefined') { - const isCookiesEnabled = win.CapacitorCookiesAndroidInterface.isEnabled(); - if (isCookiesEnabled === true) { - doPatchCookies = true; - } + doPatchCookies = + ((_c = (_b = win.CapacitorNativeConfig) === null || _b === void 0 ? void 0 : _b.cookiesEnabled) !== null && _c !== void 0 ? _c : win.CapacitorCookiesAndroidInterface.isEnabled()) === true; } if (doPatchCookies) { Object.defineProperty(document, 'cookie', { @@ -442,16 +440,11 @@ var nativeBridge = (function (exports) { }; let doPatchHttp = false; // check if capacitor http is disabled before patching - if (platform === 'ios') { - if (((_b = win.CapacitorNativeConfig) === null || _b === void 0 ? void 0 : _b.httpEnabled) === true) { - doPatchHttp = true; - } + if (((_d = win.CapacitorNativeConfig) === null || _d === void 0 ? void 0 : _d.httpEnabled) != null) { + doPatchHttp = win.CapacitorNativeConfig.httpEnabled === true; } - else if (typeof win.CapacitorHttpAndroidInterface !== 'undefined') { - const isHttpEnabled = win.CapacitorHttpAndroidInterface.isEnabled(); - if (isHttpEnabled === true) { - doPatchHttp = true; - } + else if (platform === 'android' && typeof win.CapacitorHttpAndroidInterface !== 'undefined') { + doPatchHttp = win.CapacitorHttpAndroidInterface.isEnabled() === true; } if (doPatchHttp) { // fetch patch @@ -1006,7 +999,6 @@ var nativeBridge = (function (exports) { }); }); }; - // eslint-disable-next-line @typescript-eslint/no-unused-vars cap.withPlugin = (_pluginId, _fn) => dummy; cap.Exception = CapacitorException; initEvents(win, cap); diff --git a/android/capacitor/src/main/java/com/getcapacitor/Bridge.java b/android/capacitor/src/main/java/com/getcapacitor/Bridge.java index 6122565b37..177b70ef1b 100644 --- a/android/capacitor/src/main/java/com/getcapacitor/Bridge.java +++ b/android/capacitor/src/main/java/com/getcapacitor/Bridge.java @@ -922,7 +922,9 @@ public ActivityResultLauncher registerForActivityResult( */ private JSInjector getJSInjector() { try { - String globalJS = JSExport.getGlobalJS(context, config.isLoggingEnabled(), isDevMode()); + boolean cookiesEnabled = config.getPluginConfiguration("CapacitorCookies").getBoolean("enabled", false); + boolean httpEnabled = config.getPluginConfiguration("CapacitorHttp").getBoolean("enabled", false); + String globalJS = JSExport.getGlobalJS(context, config.isLoggingEnabled(), isDevMode(), cookiesEnabled, httpEnabled); String bridgeJS = JSExport.getBridgeJS(context); String pluginJS = JSExport.getPluginJS(plugins.values()); String cordovaJS = JSExport.getCordovaJS(context); diff --git a/android/capacitor/src/main/java/com/getcapacitor/JSExport.java b/android/capacitor/src/main/java/com/getcapacitor/JSExport.java index 2083c2c945..04f22ebb11 100644 --- a/android/capacitor/src/main/java/com/getcapacitor/JSExport.java +++ b/android/capacitor/src/main/java/com/getcapacitor/JSExport.java @@ -21,6 +21,17 @@ public static String getGlobalJS(Context context, boolean loggingEnabled, boolea return "window.Capacitor = { DEBUG: " + isDebug + ", isLoggingEnabled: " + loggingEnabled + ", Plugins: {} };"; } + static String getGlobalJS(Context context, boolean loggingEnabled, boolean isDebug, boolean cookiesEnabled, boolean httpEnabled) { + return ( + getGlobalJS(context, loggingEnabled, isDebug) + + " window.CapacitorNativeConfig = { cookiesEnabled: " + + cookiesEnabled + + ", httpEnabled: " + + httpEnabled + + " };" + ); + } + public static String getMiscFileJS(ArrayList paths, Context context) { List lines = new ArrayList<>(); diff --git a/android/capacitor/src/main/java/com/getcapacitor/plugin/CapacitorCookies.java b/android/capacitor/src/main/java/com/getcapacitor/plugin/CapacitorCookies.java index 6ba4605f34..c34fc0a951 100644 --- a/android/capacitor/src/main/java/com/getcapacitor/plugin/CapacitorCookies.java +++ b/android/capacitor/src/main/java/com/getcapacitor/plugin/CapacitorCookies.java @@ -20,7 +20,9 @@ public class CapacitorCookies extends Plugin { @Override public void load() { - this.bridge.getWebView().addJavascriptInterface(this, "CapacitorCookiesAndroidInterface"); + if (isEnabled()) { + this.bridge.getWebView().addJavascriptInterface(this, "CapacitorCookiesAndroidInterface"); + } this.cookieManager = new CapacitorCookieManager(null, java.net.CookiePolicy.ACCEPT_ALL, this.bridge); this.cookieManager.removeSessionCookies(); CookieHandler.setDefault(this.cookieManager); diff --git a/android/capacitor/src/main/java/com/getcapacitor/plugin/CapacitorHttp.java b/android/capacitor/src/main/java/com/getcapacitor/plugin/CapacitorHttp.java index 46bc17417f..05cbf8891d 100644 --- a/android/capacitor/src/main/java/com/getcapacitor/plugin/CapacitorHttp.java +++ b/android/capacitor/src/main/java/com/getcapacitor/plugin/CapacitorHttp.java @@ -29,7 +29,9 @@ public class CapacitorHttp extends Plugin { @Override public void load() { - this.bridge.getWebView().addJavascriptInterface(this, "CapacitorHttpAndroidInterface"); + if (isEnabled()) { + this.bridge.getWebView().addJavascriptInterface(this, "CapacitorHttpAndroidInterface"); + } super.load(); } diff --git a/android/capacitor/src/test/java/com/getcapacitor/JSExportTest.java b/android/capacitor/src/test/java/com/getcapacitor/JSExportTest.java new file mode 100644 index 0000000000..6bec5f84a5 --- /dev/null +++ b/android/capacitor/src/test/java/com/getcapacitor/JSExportTest.java @@ -0,0 +1,26 @@ +package com.getcapacitor; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class JSExportTest { + + @Test + public void getGlobalJSIncludesCapacitorNativeConfigFlags() { + String js = JSExport.getGlobalJS(null, true, false, true, false); + + assertEquals( + "window.Capacitor = { DEBUG: false, isLoggingEnabled: true, Plugins: {} }; " + + "window.CapacitorNativeConfig = { cookiesEnabled: true, httpEnabled: false };", + js + ); + } + + @Test + public void getGlobalJSThreeArgOverloadOmitsCapacitorNativeConfig() { + String js = JSExport.getGlobalJS(null, false, true); + + assertEquals("window.Capacitor = { DEBUG: true, isLoggingEnabled: false, Plugins: {} };", js); + } +} diff --git a/android/capacitor/src/test/java/com/getcapacitor/plugin/CapacitorCookiesTest.java b/android/capacitor/src/test/java/com/getcapacitor/plugin/CapacitorCookiesTest.java new file mode 100644 index 0000000000..b0b3d48bc9 --- /dev/null +++ b/android/capacitor/src/test/java/com/getcapacitor/plugin/CapacitorCookiesTest.java @@ -0,0 +1,57 @@ +package com.getcapacitor.plugin; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import android.webkit.CookieManager; +import android.webkit.WebView; +import com.getcapacitor.Bridge; +import com.getcapacitor.CapConfig; +import com.getcapacitor.PluginConfig; +import java.net.CookieHandler; +import org.junit.Test; +import org.mockito.MockedStatic; + +public class CapacitorCookiesTest { + + @Test + public void loadSkipsJavascriptInterfaceWhenDisabled() { + verify(loadWithCookiesEnabled(false), never()).addJavascriptInterface(any(), anyString()); + } + + @Test + public void loadRegistersJavascriptInterfaceWhenEnabled() { + verify(loadWithCookiesEnabled(true)).addJavascriptInterface(any(CapacitorCookies.class), eq("CapacitorCookiesAndroidInterface")); + } + + private WebView loadWithCookiesEnabled(boolean enabled) { + Bridge bridge = mock(Bridge.class); + WebView webView = mock(WebView.class); + CapConfig config = mock(CapConfig.class); + PluginConfig pluginConfig = mock(PluginConfig.class); + CookieManager webkitCookieManager = mock(CookieManager.class); + + when(bridge.getWebView()).thenReturn(webView); + when(bridge.getConfig()).thenReturn(config); + when(config.getPluginConfiguration("CapacitorCookies")).thenReturn(pluginConfig); + when(pluginConfig.getBoolean("enabled", false)).thenReturn(enabled); + + CookieHandler previous = CookieHandler.getDefault(); + try (MockedStatic cookieManagerMock = mockStatic(CookieManager.class)) { + cookieManagerMock.when(CookieManager::getInstance).thenReturn(webkitCookieManager); + CapacitorCookies plugin = new CapacitorCookies(); + plugin.setBridge(bridge); + plugin.load(); + } finally { + CookieHandler.setDefault(previous); + } + + return webView; + } +} diff --git a/android/capacitor/src/test/java/com/getcapacitor/plugin/CapacitorHttpTest.java b/android/capacitor/src/test/java/com/getcapacitor/plugin/CapacitorHttpTest.java new file mode 100644 index 0000000000..68d7e4706f --- /dev/null +++ b/android/capacitor/src/test/java/com/getcapacitor/plugin/CapacitorHttpTest.java @@ -0,0 +1,46 @@ +package com.getcapacitor.plugin; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import android.webkit.WebView; +import com.getcapacitor.Bridge; +import com.getcapacitor.CapConfig; +import com.getcapacitor.PluginConfig; +import org.junit.Test; + +public class CapacitorHttpTest { + + @Test + public void loadSkipsJavascriptInterfaceWhenDisabled() { + verify(loadWithHttpEnabled(false), never()).addJavascriptInterface(any(), anyString()); + } + + @Test + public void loadRegistersJavascriptInterfaceWhenEnabled() { + verify(loadWithHttpEnabled(true)).addJavascriptInterface(any(CapacitorHttp.class), eq("CapacitorHttpAndroidInterface")); + } + + private WebView loadWithHttpEnabled(boolean enabled) { + Bridge bridge = mock(Bridge.class); + WebView webView = mock(WebView.class); + CapConfig config = mock(CapConfig.class); + PluginConfig pluginConfig = mock(PluginConfig.class); + + when(bridge.getWebView()).thenReturn(webView); + when(bridge.getConfig()).thenReturn(config); + when(config.getPluginConfiguration("CapacitorHttp")).thenReturn(pluginConfig); + when(pluginConfig.getBoolean("enabled", false)).thenReturn(enabled); + + CapacitorHttp plugin = new CapacitorHttp(); + plugin.setBridge(bridge); + plugin.load(); + + return webView; + } +} diff --git a/core/native-bridge.ts b/core/native-bridge.ts index 30a2091804..60bd2ef0bc 100644 --- a/core/native-bridge.ts +++ b/core/native-bridge.ts @@ -391,10 +391,8 @@ const initBridge = (w: any): void => { doPatchCookies = true; } } else if (typeof win.CapacitorCookiesAndroidInterface !== 'undefined') { - const isCookiesEnabled = win.CapacitorCookiesAndroidInterface.isEnabled(); - if (isCookiesEnabled === true) { - doPatchCookies = true; - } + doPatchCookies = + (win.CapacitorNativeConfig?.cookiesEnabled ?? win.CapacitorCookiesAndroidInterface.isEnabled()) === true; } if (doPatchCookies) { @@ -459,15 +457,10 @@ const initBridge = (w: any): void => { let doPatchHttp = false; // check if capacitor http is disabled before patching - if (platform === 'ios') { - if (win.CapacitorNativeConfig?.httpEnabled === true) { - doPatchHttp = true; - } - } else if (typeof win.CapacitorHttpAndroidInterface !== 'undefined') { - const isHttpEnabled = win.CapacitorHttpAndroidInterface.isEnabled(); - if (isHttpEnabled === true) { - doPatchHttp = true; - } + if (win.CapacitorNativeConfig?.httpEnabled != null) { + doPatchHttp = win.CapacitorNativeConfig.httpEnabled === true; + } else if (platform === 'android' && typeof win.CapacitorHttpAndroidInterface !== 'undefined') { + doPatchHttp = win.CapacitorHttpAndroidInterface.isEnabled() === true; } if (doPatchHttp) { diff --git a/core/src/tests/bridge.spec.ts b/core/src/tests/bridge.spec.ts index 13fa9e0053..892a378a8c 100644 --- a/core/src/tests/bridge.spec.ts +++ b/core/src/tests/bridge.spec.ts @@ -114,6 +114,55 @@ describe('bridge', () => { }); }); + it('android patches fetch when CapacitorNativeConfig.httpEnabled is true without CapacitorHttpAndroidInterface', () => { + const originalFetch = window.fetch; + const originalXHR = window.XMLHttpRequest; + const stubFetch = jest.fn(); + window.fetch = stubFetch; + try { + win.androidBridge = { postMessage: jest.fn() }; + win.CapacitorNativeConfig = { cookiesEnabled: false, httpEnabled: true }; + initBridge(win); + expect(window.fetch).not.toBe(stubFetch); + expect(win.CapacitorWebFetch).toBe(stubFetch); + } finally { + window.fetch = originalFetch; + window.XMLHttpRequest = originalXHR; + } + }); + + it('android does not patch fetch when CapacitorNativeConfig.httpEnabled is false', () => { + const originalFetch = window.fetch; + const originalXHR = window.XMLHttpRequest; + const stubFetch = jest.fn(); + window.fetch = stubFetch; + try { + win.androidBridge = { postMessage: jest.fn() }; + win.CapacitorNativeConfig = { cookiesEnabled: false, httpEnabled: false }; + win.CapacitorHttpAndroidInterface = { isEnabled: jest.fn(() => true) }; + initBridge(win); + expect(window.fetch).toBe(stubFetch); + expect(win.CapacitorHttpAndroidInterface.isEnabled).not.toHaveBeenCalled(); + } finally { + window.fetch = originalFetch; + window.XMLHttpRequest = originalXHR; + } + }); + + it('android keeps browser document.cookie working when CapacitorCookiesAndroidInterface is absent', () => { + try { + win.androidBridge = { postMessage: jest.fn() }; + win.CapacitorNativeConfig = { cookiesEnabled: true, httpEnabled: false }; + + initBridge(win); + + document.cookie = 'cap_test=1'; + expect(document.cookie).toContain('cap_test=1'); + } finally { + document.cookie = 'cap_test=; expires=Thu, 01 Jan 1970 00:00:00 GMT'; + } + }); + const mockAndroidPluginResult = (pluginResult: PluginResult) => { win.androidBridge = { postMessage: (m) => { diff --git a/ios/Sources/Capacitor/assets/native-bridge.js b/ios/Sources/Capacitor/assets/native-bridge.js index 2a9d7077f6..9a31f2a060 100644 --- a/ios/Sources/Capacitor/assets/native-bridge.js +++ b/ios/Sources/Capacitor/assets/native-bridge.js @@ -93,7 +93,7 @@ var nativeBridge = (function (exports) { try { data = JSON.parse(data); } - catch (ignored) { + catch (_a) { // ignore } type = 'json'; @@ -314,7 +314,7 @@ var nativeBridge = (function (exports) { win.Ionic.WebView = IonicWebView; }; const initLogger = (win, cap) => { - var _a, _b; + var _a, _b, _c, _d; const BRIDGED_CONSOLE_METHODS = ['debug', 'error', 'info', 'log', 'trace', 'warn']; const createLogFromNative = (c) => (result) => { if (isFullConsole(c)) { @@ -363,7 +363,7 @@ var nativeBridge = (function (exports) { } return String(msg); } - catch (e) { + catch (_a) { return ''; } }; @@ -381,10 +381,8 @@ var nativeBridge = (function (exports) { } } else if (typeof win.CapacitorCookiesAndroidInterface !== 'undefined') { - const isCookiesEnabled = win.CapacitorCookiesAndroidInterface.isEnabled(); - if (isCookiesEnabled === true) { - doPatchCookies = true; - } + doPatchCookies = + ((_c = (_b = win.CapacitorNativeConfig) === null || _b === void 0 ? void 0 : _b.cookiesEnabled) !== null && _c !== void 0 ? _c : win.CapacitorCookiesAndroidInterface.isEnabled()) === true; } if (doPatchCookies) { Object.defineProperty(document, 'cookie', { @@ -442,16 +440,11 @@ var nativeBridge = (function (exports) { }; let doPatchHttp = false; // check if capacitor http is disabled before patching - if (platform === 'ios') { - if (((_b = win.CapacitorNativeConfig) === null || _b === void 0 ? void 0 : _b.httpEnabled) === true) { - doPatchHttp = true; - } + if (((_d = win.CapacitorNativeConfig) === null || _d === void 0 ? void 0 : _d.httpEnabled) != null) { + doPatchHttp = win.CapacitorNativeConfig.httpEnabled === true; } - else if (typeof win.CapacitorHttpAndroidInterface !== 'undefined') { - const isHttpEnabled = win.CapacitorHttpAndroidInterface.isEnabled(); - if (isHttpEnabled === true) { - doPatchHttp = true; - } + else if (platform === 'android' && typeof win.CapacitorHttpAndroidInterface !== 'undefined') { + doPatchHttp = win.CapacitorHttpAndroidInterface.isEnabled() === true; } if (doPatchHttp) { // fetch patch @@ -1006,7 +999,6 @@ var nativeBridge = (function (exports) { }); }); }; - // eslint-disable-next-line @typescript-eslint/no-unused-vars cap.withPlugin = (_pluginId, _fn) => dummy; cap.Exception = CapacitorException; initEvents(win, cap);