@capacitor/android 8.3.5 → 8.3.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -15,11 +15,24 @@
15
15
 
16
16
  -keep public class * extends com.getcapacitor.Plugin { *; }
17
17
 
18
+ # The annotation types are read at runtime via reflection. If they are not kept, R8 full mode
19
+ # treats them as never instantiated and optimizes the annotation cached in PluginHandle to null,
20
+ # even with -keepattributes *Annotation*.
21
+ -keep @interface com.getcapacitor.annotation.** { *; }
22
+ -keep @interface com.getcapacitor.PluginMethod { *; }
23
+
24
+ # Callback methods are found by reflection, including on non-public base classes.
25
+ -keepclassmembers class * extends com.getcapacitor.Plugin {
26
+ @com.getcapacitor.annotation.ActivityCallback <methods>;
27
+ @com.getcapacitor.annotation.PermissionCallback <methods>;
28
+ }
29
+
18
30
  # Rules for Capacitor v2 plugins and annotations
19
31
  # These are deprecated but can still be used with Capacitor for now
20
32
  -keep @com.getcapacitor.NativePlugin public class * {
21
33
  @com.getcapacitor.PluginMethod public <methods>;
22
34
  }
35
+ -keep @interface com.getcapacitor.NativePlugin { *; }
23
36
 
24
37
  # Rules for Cordova plugins
25
38
  -keep public class * extends org.apache.cordova.* {
@@ -7,16 +7,20 @@ package com.getcapacitor;
7
7
  import android.content.Context;
8
8
  import android.content.res.AssetManager;
9
9
  import android.net.Uri;
10
+ import android.os.Environment;
10
11
  import android.util.TypedValue;
11
12
  import java.io.File;
12
13
  import java.io.FileInputStream;
14
+ import java.io.FileNotFoundException;
13
15
  import java.io.IOException;
14
16
  import java.io.InputStream;
17
+ import java.util.ArrayList;
15
18
  import java.util.List;
16
19
 
17
20
  public class AndroidProtocolHandler {
18
21
 
19
22
  private Context context;
23
+ private List<File> appStorageRoots;
20
24
 
21
25
  public AndroidProtocolHandler(Context context) {
22
26
  this.context = context;
@@ -69,6 +73,125 @@ public class AndroidProtocolHandler {
69
73
  return new FileInputStream(localFile);
70
74
  }
71
75
 
76
+ /**
77
+ * Opens a file served from the base path the app is hosted from (see {@code setServerBasePath}).
78
+ * The request path is decoded by {@link Uri#getPath()}, so an encoded slash ({@code %2F}) can carry
79
+ * {@code ..} segments that the browser did not resolve. The resolved file must therefore sit inside
80
+ * the base path, or the request would read any file the app can read.
81
+ *
82
+ * @param basePath the directory the app is hosted from
83
+ * @param filePath the base path followed by the request path
84
+ * @throws FileNotFoundException if the resolved file is outside of the base path
85
+ */
86
+ public InputStream openBasePathFile(String basePath, String filePath) throws IOException {
87
+ String base = new File(basePath).getCanonicalPath();
88
+ File file = new File(filePath).getCanonicalFile();
89
+ String resolved = file.getPath();
90
+ if (!resolved.equals(base) && !resolved.startsWith(base.endsWith(File.separator) ? base : base + File.separator)) {
91
+ throw new FileNotFoundException("File is outside of the base path: " + filePath);
92
+ }
93
+ return new FileInputStream(file);
94
+ }
95
+
96
+ /**
97
+ * Opens a file whose location was chosen by a {@link RouteProcessor}. The processor may map requests
98
+ * outside the base path on purpose, so containment is not checked here. The request path is decoded
99
+ * by {@link Uri#getPath()}, so an encoded slash ({@code %2F}) can still carry {@code ..} segments that
100
+ * the browser did not resolve and that a processor would pass on; such requests are refused.
101
+ *
102
+ * @param requestPath the decoded request path
103
+ * @param processedPath the file path returned by the route processor
104
+ * @throws FileNotFoundException if the request path contains a parent-directory segment
105
+ */
106
+ public InputStream openRoutedFile(String requestPath, String processedPath) throws IOException {
107
+ for (String segment : requestPath.split("/")) {
108
+ if (segment.equals("..")) {
109
+ throw new FileNotFoundException("Parent-directory segment in request path: " + requestPath);
110
+ }
111
+ }
112
+ return openFile(processedPath);
113
+ }
114
+
115
+ /**
116
+ * Opens a file requested through the {@link Bridge#CAPACITOR_FILE_START} proxy route.
117
+ * Unlike {@link #openFile(String)}, the resolved path must sit inside the app's own storage or
118
+ * shared/external storage, so the route cannot expose app-private data (shared_prefs, databases)
119
+ * or system files such as /proc or /etc.
120
+ *
121
+ * @param filePath the request path, starting with {@link Bridge#CAPACITOR_FILE_START}
122
+ * @throws IOException if the file cannot be opened or its location is not allowed
123
+ */
124
+ public InputStream openProxiedFile(String filePath) throws IOException {
125
+ String realPath = filePath.startsWith(Bridge.CAPACITOR_FILE_START)
126
+ ? filePath.substring(Bridge.CAPACITOR_FILE_START.length())
127
+ : filePath;
128
+ // Canonicalizing resolves ".." segments and symlinks; open the resolved file so the checked path is the read one.
129
+ File canonicalFile = new File(realPath).getCanonicalFile();
130
+ if (!isInAllowedLocation(canonicalFile)) {
131
+ throw new IOException("Path is outside the locations served by the file proxy: " + realPath);
132
+ }
133
+ return new FileInputStream(canonicalFile);
134
+ }
135
+
136
+ private boolean isInAllowedLocation(File canonicalFile) throws IOException {
137
+ String path = canonicalFile.getPath();
138
+ for (File root : getAllowedRoots()) {
139
+ String rootPath = root.getCanonicalPath();
140
+ if (path.equals(rootPath) || path.startsWith(rootPath + File.separator)) {
141
+ return true;
142
+ }
143
+ }
144
+ return false;
145
+ }
146
+
147
+ @SuppressWarnings("deprecation")
148
+ /**
149
+ * The app's files and cache directories (Filesystem Data/Library/Cache, Camera temporary images). They do not
150
+ * change while the app runs, unlike the external storage roots, so they are looked up once.
151
+ */
152
+ private List<File> getAppStorageRoots() {
153
+ List<File> roots = appStorageRoots;
154
+ if (roots == null) {
155
+ roots = new ArrayList<>();
156
+ addIfNotNull(roots, context.getFilesDir());
157
+ addIfNotNull(roots, context.getCacheDir());
158
+ appStorageRoots = roots;
159
+ }
160
+ return roots;
161
+ }
162
+
163
+ private List<File> getAllowedRoots() {
164
+ List<File> roots = new ArrayList<>(getAppStorageRoots());
165
+ // Primary shared storage (Filesystem Documents/ExternalStorage, gallery and media picks)
166
+ addIfNotNull(roots, Environment.getExternalStorageDirectory());
167
+ // App-specific external dirs, and the root of every other volume (e.g. SD cards) they live on
168
+ List<File> externalDirs = new ArrayList<>();
169
+ for (File dir : context.getExternalFilesDirs(null)) {
170
+ externalDirs.add(dir);
171
+ }
172
+ for (File dir : context.getExternalCacheDirs()) {
173
+ externalDirs.add(dir);
174
+ }
175
+ for (File dir : externalDirs) {
176
+ if (dir == null) {
177
+ continue;
178
+ }
179
+ roots.add(dir);
180
+ String dirPath = dir.getPath();
181
+ int androidDirIndex = dirPath.indexOf("/Android/");
182
+ if (androidDirIndex > 0) {
183
+ roots.add(new File(dirPath.substring(0, androidDirIndex)));
184
+ }
185
+ }
186
+ return roots;
187
+ }
188
+
189
+ private static void addIfNotNull(List<File> roots, File dir) {
190
+ if (dir != null) {
191
+ roots.add(dir);
192
+ }
193
+ }
194
+
72
195
  public InputStream openContentUrl(Uri uri) throws IOException {
73
196
  Integer port = uri.getPort();
74
197
  String baseUrl = uri.getScheme() + "://" + uri.getHost();
@@ -80,7 +203,10 @@ public class AndroidProtocolHandler {
80
203
  InputStream stream = null;
81
204
  try {
82
205
  stream = context.getContentResolver().openInputStream(Uri.parse(realPath));
83
- } catch (SecurityException e) {
206
+ } catch (RuntimeException e) {
207
+ // The target provider runs in this process and may throw unchecked exceptions for a malformed or
208
+ // unknown path (e.g. FileProvider throws IllegalArgumentException, older versions
209
+ // StringIndexOutOfBoundsException). Left uncaught they crash the app, so report "not found" instead.
84
210
  Logger.error("Unable to open content URL: " + uri, e);
85
211
  }
86
212
  return stream;
@@ -386,10 +386,23 @@ public class Bridge {
386
386
  return 0;
387
387
  }
388
388
 
389
+ /**
390
+ * Whether the path targets the local file or content proxy routes.
391
+ */
392
+ static boolean isLocalFilePath(String path) {
393
+ return path != null && (path.startsWith(CAPACITOR_FILE_START) || path.startsWith(CAPACITOR_CONTENT_START));
394
+ }
395
+
396
+ /**
397
+ * Whether the path targets one of the internal proxy routes (file, content, http interceptor).
398
+ */
399
+ static boolean isInternalProxyPath(String path) {
400
+ return isLocalFilePath(path) || (path != null && path.startsWith(CAPACITOR_HTTP_INTERCEPTOR_START));
401
+ }
402
+
389
403
  public boolean launchIntent(Uri url) {
390
- // The proxy returns a remote body at the app origin, so block it before plugins can allow it.
391
- String path = url.getPath();
392
- if (path != null && path.startsWith(CAPACITOR_HTTP_INTERCEPTOR_START)) {
404
+ // The proxy routes return data at the app origin, so block navigating to them before plugins can allow it.
405
+ if (isInternalProxyPath(url.getPath())) {
393
406
  return true;
394
407
  }
395
408
 
@@ -25,6 +25,7 @@ import android.webkit.WebResourceRequest;
25
25
  import android.webkit.WebResourceResponse;
26
26
  import com.getcapacitor.plugin.util.CapacitorHttpUrlConnection;
27
27
  import com.getcapacitor.plugin.util.HttpRequestHandler;
28
+ import java.io.ByteArrayInputStream;
28
29
  import java.io.IOException;
29
30
  import java.io.InputStream;
30
31
  import java.net.HttpURLConnection;
@@ -184,10 +185,15 @@ public class WebViewLocalServer {
184
185
  public WebResourceResponse shouldInterceptRequest(WebResourceRequest request) {
185
186
  Uri loadingUrl = request.getUrl();
186
187
 
188
+ if (Bridge.isInternalProxyPath(loadingUrl.getPath()) && !isProxyRequestAllowed(request)) {
189
+ // Internal proxy routes are only for sub-resources requested at the app's own origin.
190
+ Logger.warn("Blocked request to internal proxy route: " + loadingUrl);
191
+ return buildBlockedResponse();
192
+ }
193
+
187
194
  if (null != loadingUrl.getPath() && loadingUrl.getPath().startsWith(Bridge.CAPACITOR_HTTP_INTERCEPTOR_START)) {
188
- // Only fetch/XHR should reach the proxy; a document would run remote content at the app origin.
189
195
  boolean httpEnabled = bridge.getConfig().getPluginConfiguration("CapacitorHttp").getBoolean("enabled", false);
190
- if (!httpEnabled || isDocumentRequest(request)) {
196
+ if (!httpEnabled) {
191
197
  return null;
192
198
  }
193
199
  Logger.debug("Handling CapacitorHttp request: " + loadingUrl);
@@ -215,6 +221,47 @@ public class WebViewLocalServer {
215
221
  }
216
222
  }
217
223
 
224
+ /**
225
+ * Internal proxy routes (file, content, http interceptor) return data at the app origin, so they must only
226
+ * serve sub-resource requests (img, media, fetch/XHR) made to the app's own origin. A document would run
227
+ * the returned content with the app's privileges, and a request to any other origin has no business here.
228
+ */
229
+ private boolean isProxyRequestAllowed(WebResourceRequest request) {
230
+ return isAppOrigin(request.getUrl()) && !isDocumentRequest(request);
231
+ }
232
+
233
+ private boolean isAppOrigin(Uri uri) {
234
+ String localUrl = bridge.getLocalUrl();
235
+ if (localUrl == null || uri.getScheme() == null || uri.getHost() == null) {
236
+ return false;
237
+ }
238
+ Uri appOrigin = Uri.parse(localUrl);
239
+ return (
240
+ uri.getScheme().equalsIgnoreCase(appOrigin.getScheme()) &&
241
+ uri.getHost().equalsIgnoreCase(appOrigin.getHost()) &&
242
+ getEffectivePort(uri) == getEffectivePort(appOrigin)
243
+ );
244
+ }
245
+
246
+ /**
247
+ * The WebView hands over request URLs without a default port, while the configured app URL may spell it out
248
+ * (e.g. server.url "http://host:80"), so a missing port is treated as the scheme's default.
249
+ */
250
+ private static int getEffectivePort(Uri uri) {
251
+ int port = uri.getPort();
252
+ if (port != -1) {
253
+ return port;
254
+ }
255
+ String scheme = uri.getScheme();
256
+ if ("https".equalsIgnoreCase(scheme)) {
257
+ return 443;
258
+ }
259
+ if ("http".equalsIgnoreCase(scheme)) {
260
+ return 80;
261
+ }
262
+ return -1;
263
+ }
264
+
218
265
  /** isForMainFrame() is false for an iframe and a fetch alike; only navigations send this header. */
219
266
  private boolean isDocumentRequest(WebResourceRequest request) {
220
267
  if (request.isForMainFrame()) {
@@ -234,8 +281,7 @@ public class WebViewLocalServer {
234
281
  }
235
282
 
236
283
  private boolean isLocalFile(Uri uri) {
237
- String path = uri.getPath();
238
- return path.startsWith(capacitorContentStart) || path.startsWith(capacitorFileStart);
284
+ return Bridge.isLocalFilePath(uri.getPath());
239
285
  }
240
286
 
241
287
  private boolean isErrorUrl(Uri uri) {
@@ -339,7 +385,9 @@ public class WebViewLocalServer {
339
385
  encoding = encodingParts[1].trim();
340
386
  }
341
387
  }
342
- } else {
388
+ } else if (!"Access-Control-Allow-Origin".equalsIgnoreCase(entry.getKey())) {
389
+ // The target's CORS grant is not forwarded: the request is made natively (with the app's cookies), so a
390
+ // grant meant for the target's own callers would let another origin read the response.
343
391
  responseHeaders.put(entry.getKey(), builder.toString());
344
392
  }
345
393
  }
@@ -362,6 +410,27 @@ public class WebViewLocalServer {
362
410
  return new WebResourceResponse(mimeType, encoding, responseCode, reasonPhrase, responseHeaders, inputStream);
363
411
  }
364
412
 
413
+ /**
414
+ * A fixed rejection for a blocked proxy route request. Returning null would let the WebView send the request
415
+ * to the network itself, which for a remote server.url puts the local path in a request to that server.
416
+ */
417
+ private WebResourceResponse buildBlockedResponse() {
418
+ Map<String, String> headers = new HashMap<>();
419
+ headers.put("Content-Security-Policy", "sandbox; frame-ancestors 'none'");
420
+ headers.put("Cache-Control", "no-store");
421
+ return new WebResourceResponse("text/plain", "UTF-8", 403, "Forbidden", headers, new ByteArrayInputStream(new byte[0]));
422
+ }
423
+
424
+ /**
425
+ * Files served through the file/content proxy routes are data, not pages. If anything ends up rendering one,
426
+ * the sandbox keeps it inert and off the app origin, and it cannot be framed.
427
+ */
428
+ void addProxyRouteSecurityHeaders(Uri uri, Map<String, String> responseHeaders) {
429
+ if (isLocalFile(uri)) {
430
+ responseHeaders.put("Content-Security-Policy", "sandbox; frame-ancestors 'none'");
431
+ }
432
+ }
433
+
365
434
  private WebResourceResponse handleLocalRequest(WebResourceRequest request, PathHandler handler) {
366
435
  String path = request.getUrl().getPath();
367
436
 
@@ -375,15 +444,22 @@ public class WebViewLocalServer {
375
444
  int statusCode = 206;
376
445
  try {
377
446
  int totalRange = responseStream.available();
378
- String[] parts = rangeString.split("=");
379
- String[] streamParts = parts[1].split("-");
380
- String fromRange = streamParts[0];
381
- int range = totalRange - 1;
382
- if (streamParts.length > 1) {
383
- range = Integer.parseInt(streamParts[1]);
447
+ if (totalRange == -1) {
448
+ // No stream (missing or refused file): not a partial response.
449
+ statusCode = 404;
450
+ addProxyRouteSecurityHeaders(request.getUrl(), tempResponseHeaders);
451
+ } else {
452
+ String[] parts = rangeString.split("=");
453
+ String[] streamParts = parts[1].split("-");
454
+ String fromRange = streamParts[0];
455
+ int range = totalRange - 1;
456
+ if (streamParts.length > 1) {
457
+ range = Integer.parseInt(streamParts[1]);
458
+ }
459
+ tempResponseHeaders.put("Accept-Ranges", "bytes");
460
+ tempResponseHeaders.put("Content-Range", "bytes " + fromRange + "-" + range + "/" + totalRange);
461
+ addProxyRouteSecurityHeaders(request.getUrl(), tempResponseHeaders);
384
462
  }
385
- tempResponseHeaders.put("Accept-Ranges", "bytes");
386
- tempResponseHeaders.put("Content-Range", "bytes " + fromRange + "-" + range + "/" + totalRange);
387
463
  } catch (IOException e) {
388
464
  statusCode = 404;
389
465
  }
@@ -401,12 +477,14 @@ public class WebViewLocalServer {
401
477
  InputStream responseStream = new LollipopLazyInputStream(handler, request);
402
478
  String mimeType = getMimeType(request.getUrl().getPath(), responseStream);
403
479
  int statusCode = getStatusCode(responseStream, handler.getStatusCode());
480
+ Map<String, String> localResponseHeaders = handler.buildDefaultResponseHeaders();
481
+ addProxyRouteSecurityHeaders(request.getUrl(), localResponseHeaders);
404
482
  return new WebResourceResponse(
405
483
  mimeType,
406
484
  handler.getEncoding(),
407
485
  statusCode,
408
486
  handler.getReasonPhrase(),
409
- handler.buildDefaultResponseHeaders(),
487
+ localResponseHeaders,
410
488
  responseStream
411
489
  );
412
490
  }
@@ -680,13 +758,14 @@ public class WebViewLocalServer {
680
758
  if (path.startsWith(capacitorContentStart)) {
681
759
  stream = protocolHandler.openContentUrl(url);
682
760
  } else if (path.startsWith(capacitorFileStart)) {
683
- stream = protocolHandler.openFile(path);
761
+ stream = protocolHandler.openProxiedFile(path);
684
762
  } else if (!isAsset) {
685
763
  if (routeProcessor == null) {
686
- path = basePath + url.getPath();
764
+ // The decoded path can contain ".." that must not leave the base path.
765
+ stream = protocolHandler.openBasePathFile(basePath, basePath + url.getPath());
766
+ } else {
767
+ stream = protocolHandler.openRoutedFile(url.getPath(), path);
687
768
  }
688
-
689
- stream = protocolHandler.openFile(path);
690
769
  } else if (ignoreAssetPath) {
691
770
  stream = protocolHandler.openAsset(path);
692
771
  } else {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capacitor/android",
3
- "version": "8.3.5",
3
+ "version": "8.3.7",
4
4
  "description": "Capacitor: Cross-platform apps with JavaScript and the web",
5
5
  "homepage": "https://capacitorjs.com",
6
6
  "author": "Ionic Team <hi@ionic.io> (https://ionic.io)",