mirror of
https://github.com/GopeedLab/gopeed.git
synced 2026-11-16 21:33:41 +00:00
Remove extension WebView data during uninstall
This commit is contained in:
1 parent
c47b735fc4
commit
d642ae5018
25 files changed
+609
-19
No files matched your search
@@ -18,6 +18,10 @@ class WebViewProfile {
|
||||
final String id;
|
||||
static const _channel = MethodChannel('com.pichillilorenzo/flutter_inappwebview_cookiemanager');
|
||||
|
||||
Future<void> remove() async {
|
||||
await _call('gopeed.removeProfile', {});
|
||||
}
|
||||
|
||||
Future<void> prepare(String proxyUrl) async {
|
||||
await _call('gopeed.prepareProfile', {'proxyUrl': proxyUrl});
|
||||
}
|
||||
|
||||
@@ -130,6 +130,9 @@ class WebViewRpcService {
|
||||
switch (method) {
|
||||
case 'webview.isAvailable':
|
||||
return {'available': true};
|
||||
case 'profile.remove':
|
||||
await _removeProfile(_string(params, 'profileId'));
|
||||
return {};
|
||||
case 'page.open':
|
||||
return _openPage(params);
|
||||
case 'page.addInitScript':
|
||||
@@ -188,6 +191,15 @@ class WebViewRpcService {
|
||||
return {'pageId': pageId};
|
||||
}
|
||||
|
||||
Future<void> _removeProfile(String id) async {
|
||||
for (final page in _pagesById.values.where((page) => page.cookieManager.id == id).toList()) {
|
||||
await _closePage(page.pageId);
|
||||
}
|
||||
// Let visible platform views unmount before releasing their native store.
|
||||
await WidgetsBinding.instance.endOfFrame;
|
||||
await WebViewProfile(id).remove();
|
||||
}
|
||||
|
||||
WebViewRpcPageSession _page(Map<String, dynamic> params) {
|
||||
final page = _pagesById[_pageId(params)];
|
||||
if (page == null) {
|
||||
|
||||
Vendored
+5
-1
@@ -11,7 +11,7 @@ are available in the parent commit's pubspec.lock.
|
||||
|
||||
Local native changes are limited to:
|
||||
|
||||
- `GopeedProfiles`: prepare a persistent profile and apply the internal loopback
|
||||
- `GopeedProfiles`: remove profiles on uninstall and prepare a persistent profile and apply the internal loopback
|
||||
proxy before creating a WebView. Apple uses SOCKS5 to cover HTTP as well as HTTPS;
|
||||
Android uses the application-wide HTTP proxy override completion callback.
|
||||
- `InAppWebViewSettings` and `InAppWebView`: read the host-only `gopeedProfileId`
|
||||
@@ -29,3 +29,7 @@ an explicit unavailable error rather than opening a shared, unproxied browser.
|
||||
When updating upstream, refresh these three packages, reapply the above changes,
|
||||
and run `tool/webview_profile_check.dart` on a native Apple host. Do not patch the
|
||||
user's pub cache: dependency_overrides selects these tracked sources reproducibly.
|
||||
|
||||
Android uses AndroidX WebKit 1.13.0 for profile-scoped full browsing-data deletion.
|
||||
Loaded profile shells are queued durably for deletion before WebViews initialize
|
||||
at the next process start. No global cookie/cache clearing is used for uninstall.
|
||||
@@ -29,7 +29,7 @@ android {
|
||||
compileSdk 34
|
||||
|
||||
defaultConfig {
|
||||
minSdkVersion 19
|
||||
minSdkVersion 21
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
|
||||
vectorDrawables.useSupportLibrary = true
|
||||
@@ -49,7 +49,7 @@ android {
|
||||
}
|
||||
}
|
||||
dependencies {
|
||||
implementation 'androidx.webkit:webkit:1.12.0'
|
||||
implementation 'androidx.webkit:webkit:1.13.0'
|
||||
implementation 'androidx.browser:browser:1.8.0'
|
||||
implementation 'androidx.appcompat:appcompat:1.6.1'
|
||||
implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
|
||||
|
||||
+83
@@ -1,6 +1,12 @@
|
||||
package com.pichillilorenzo.flutter_inappwebview_android;
|
||||
|
||||
import android.net.Uri;
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import androidx.webkit.Profile;
|
||||
import androidx.webkit.WebStorageCompat;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import androidx.webkit.ProfileStore;
|
||||
import androidx.webkit.ProxyConfig;
|
||||
import androidx.webkit.ProxyController;
|
||||
@@ -10,6 +16,76 @@ import io.flutter.plugin.common.MethodChannel;
|
||||
|
||||
// Internal host bridge: profile creation and proxy completion precede navigation.
|
||||
final class GopeedProfiles {
|
||||
private static SharedPreferences preferences;
|
||||
private static final Set<String> cleared = new HashSet<>();
|
||||
private static final String DELETIONS = "pendingDeletions";
|
||||
|
||||
static void initialize(Context context) {
|
||||
if (preferences != null) return;
|
||||
preferences = context.getSharedPreferences("gopeed_webview_profiles", Context.MODE_PRIVATE);
|
||||
if (!WebViewFeature.isFeatureSupported(WebViewFeature.MULTI_PROFILE)) return;
|
||||
for (String id : deletions()) {
|
||||
try {
|
||||
// Do this before getProfile/getOrCreateProfile load any profile.
|
||||
ProfileStore.getInstance().deleteProfile(id);
|
||||
setPending(id, false);
|
||||
} catch (RuntimeException ignored) {
|
||||
// Keep the durable entry and reject use until removal succeeds.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Set<String> deletions() {
|
||||
return new HashSet<>(preferences.getStringSet(DELETIONS, new HashSet<>()));
|
||||
}
|
||||
|
||||
private static void setPending(String id, boolean pending) {
|
||||
Set<String> ids = deletions();
|
||||
if (pending) ids.add(id); else ids.remove(id);
|
||||
if (!preferences.edit().putStringSet(DELETIONS, ids).commit())
|
||||
throw new IllegalStateException("Unable to persist WebView profile removal");
|
||||
}
|
||||
|
||||
static void remove(MethodCall call, MethodChannel.Result result) {
|
||||
if (!WebViewFeature.isFeatureSupported(WebViewFeature.MULTI_PROFILE)) {
|
||||
result.error("UNAVAILABLE", "Android WebView profile removal is unavailable", null);
|
||||
return;
|
||||
}
|
||||
String id = call.argument("gopeedProfileId");
|
||||
try {
|
||||
java.util.UUID.fromString(id);
|
||||
setPending(id, true);
|
||||
try {
|
||||
ProfileStore.getInstance().deleteProfile(id);
|
||||
setPending(id, false);
|
||||
cleared.remove(id);
|
||||
result.success(true);
|
||||
return;
|
||||
} catch (IllegalStateException loadedProfile) {
|
||||
// Android forbids deleting a profile loaded in this process, even
|
||||
// after every WebView has been destroyed. Clear all its data now;
|
||||
// remove the empty profile at the next process start.
|
||||
}
|
||||
if (!WebViewFeature.isFeatureSupported(WebViewFeature.DELETE_BROWSING_DATA)) {
|
||||
result.error("PROFILE_REMOVE_FAILED", "Restart Gopeed to finish removing WebView profile data", null);
|
||||
return;
|
||||
}
|
||||
Profile profile = ProfileStore.getInstance().getProfile(id);
|
||||
if (profile == null) {
|
||||
setPending(id, false);
|
||||
result.success(true);
|
||||
return;
|
||||
}
|
||||
profile.getGeolocationPermissions().clearAll();
|
||||
WebStorageCompat.deleteBrowsingData(profile.getWebStorage(), () -> {
|
||||
cleared.add(id);
|
||||
result.success(true);
|
||||
});
|
||||
} catch (RuntimeException e) {
|
||||
result.error("PROFILE_REMOVE_FAILED", "Unable to remove WebView profile data", null);
|
||||
}
|
||||
}
|
||||
|
||||
private static String appliedProxy;
|
||||
private static String pendingProxy;
|
||||
private static final java.util.List<MethodChannel.Result> pending = new java.util.ArrayList<>();
|
||||
@@ -26,6 +102,13 @@ final class GopeedProfiles {
|
||||
Uri uri = Uri.parse(proxy);
|
||||
if (!"http".equals(uri.getScheme()) || !"127.0.0.1".equals(uri.getHost()) || uri.getPort() <= 0)
|
||||
throw new IllegalArgumentException("Invalid host proxy configuration");
|
||||
if (deletions().contains(id)) {
|
||||
if (!cleared.contains(id)) throw new IllegalStateException("Profile removal requires restart");
|
||||
// Reinstallation may reuse the now-empty profile. Do not delete its
|
||||
// new data on the next start.
|
||||
setPending(id, false);
|
||||
cleared.remove(id);
|
||||
}
|
||||
ProfileStore.getInstance().getOrCreateProfile(id);
|
||||
if (proxy.equals(appliedProxy)) { result.success(true); return; }
|
||||
if (pendingProxy != null) {
|
||||
|
||||
+1
@@ -87,6 +87,7 @@ public class InAppWebViewFlutterPlugin implements FlutterPlugin, ActivityAware {
|
||||
|
||||
private void onAttachedToEngine(Context applicationContext, BinaryMessenger messenger, Activity activity, PlatformViewRegistry platformViewRegistry, FlutterView flutterView) {
|
||||
this.applicationContext = applicationContext;
|
||||
GopeedProfiles.initialize(applicationContext);
|
||||
this.activity = activity;
|
||||
this.messenger = messenger;
|
||||
this.flutterView = flutterView;
|
||||
|
||||
+4
@@ -49,6 +49,10 @@ public class MyCookieManager extends ChannelDelegateImpl {
|
||||
|
||||
@Override
|
||||
public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
|
||||
if (call.method.equals("gopeed.removeProfile")) {
|
||||
GopeedProfiles.remove(call, result);
|
||||
return;
|
||||
}
|
||||
if (call.method.equals("gopeed.prepareProfile")) {
|
||||
GopeedProfiles.prepare(call, result);
|
||||
return;
|
||||
|
||||
+39
@@ -32,4 +32,43 @@ final class GopeedProfiles {
|
||||
proxyURLs[identifier] = proxyURL
|
||||
result(true)
|
||||
}
|
||||
static func remove(arguments: NSDictionary?, result: @escaping FlutterResult) {
|
||||
guard let identifier = arguments?["gopeedProfileId"] as? String,
|
||||
let uuid = UUID(uuidString: identifier) else {
|
||||
result(FlutterError(code: "INVALID_REQUEST", message: "Invalid WebView profile identifier", details: nil))
|
||||
return
|
||||
}
|
||||
guard #available(macOS 14.0, iOS 17.0, *) else {
|
||||
// Named stores could not have been created on these OS versions.
|
||||
result(true)
|
||||
return
|
||||
}
|
||||
// Deleting a named store alone can leave in-process cookie caches.
|
||||
// Clear every website data type before releasing/removing the store.
|
||||
let store = stores[identifier] ?? WKWebsiteDataStore(forIdentifier: uuid)
|
||||
store.removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), modifiedSince: Date.distantPast) {
|
||||
stores.removeValue(forKey: identifier)
|
||||
proxyURLs.removeValue(forKey: identifier)
|
||||
removeStore(uuid, attempts: 100, result: result)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 14.0, iOS 17.0, *)
|
||||
private static func removeStore(_ uuid: UUID, attempts: Int, result: @escaping FlutterResult) {
|
||||
WKWebsiteDataStore.remove(forIdentifier: uuid) { error in
|
||||
if error != nil && attempts > 1 {
|
||||
// Network-process references can outlive platform-view disposal.
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
|
||||
removeStore(uuid, attempts: attempts - 1, result: result)
|
||||
}
|
||||
return
|
||||
}
|
||||
if let error = error {
|
||||
result(FlutterError(code: "PROFILE_REMOVE_FAILED", message: error.localizedDescription, details: nil))
|
||||
} else {
|
||||
result(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+4
@@ -22,6 +22,10 @@ public class MyCookieManager: ChannelDelegate {
|
||||
|
||||
public override func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
|
||||
let arguments = call.arguments as? NSDictionary
|
||||
if call.method == "gopeed.removeProfile" {
|
||||
GopeedProfiles.remove(arguments: arguments, result: result)
|
||||
return
|
||||
}
|
||||
if call.method == "gopeed.prepareProfile" {
|
||||
GopeedProfiles.prepare(arguments: arguments, result: result)
|
||||
return
|
||||
|
||||
+39
@@ -32,4 +32,43 @@ final class GopeedProfiles {
|
||||
proxyURLs[identifier] = proxyURL
|
||||
result(true)
|
||||
}
|
||||
static func remove(arguments: NSDictionary?, result: @escaping FlutterResult) {
|
||||
guard let identifier = arguments?["gopeedProfileId"] as? String,
|
||||
let uuid = UUID(uuidString: identifier) else {
|
||||
result(FlutterError(code: "INVALID_REQUEST", message: "Invalid WebView profile identifier", details: nil))
|
||||
return
|
||||
}
|
||||
guard #available(macOS 14.0, iOS 17.0, *) else {
|
||||
// Named stores could not have been created on these OS versions.
|
||||
result(true)
|
||||
return
|
||||
}
|
||||
// Deleting a named store alone can leave in-process cookie caches.
|
||||
// Clear every website data type before releasing/removing the store.
|
||||
let store = stores[identifier] ?? WKWebsiteDataStore(forIdentifier: uuid)
|
||||
store.removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), modifiedSince: Date.distantPast) {
|
||||
stores.removeValue(forKey: identifier)
|
||||
proxyURLs.removeValue(forKey: identifier)
|
||||
removeStore(uuid, attempts: 100, result: result)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 14.0, iOS 17.0, *)
|
||||
private static func removeStore(_ uuid: UUID, attempts: Int, result: @escaping FlutterResult) {
|
||||
WKWebsiteDataStore.remove(forIdentifier: uuid) { error in
|
||||
if error != nil && attempts > 1 {
|
||||
// Network-process references can outlive platform-view disposal.
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
|
||||
removeStore(uuid, attempts: attempts - 1, result: result)
|
||||
}
|
||||
return
|
||||
}
|
||||
if let error = error {
|
||||
result(FlutterError(code: "PROFILE_REMOVE_FAILED", message: error.localizedDescription, details: nil))
|
||||
} else {
|
||||
result(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+4
@@ -22,6 +22,10 @@ public class MyCookieManager: ChannelDelegate {
|
||||
|
||||
public override func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
|
||||
let arguments = call.arguments as? NSDictionary
|
||||
if call.method == "gopeed.removeProfile" {
|
||||
GopeedProfiles.remove(arguments: arguments, result: result)
|
||||
return
|
||||
}
|
||||
if call.method == "gopeed.prepareProfile" {
|
||||
GopeedProfiles.prepare(arguments: arguments, result: result)
|
||||
return
|
||||
|
||||
@@ -11,7 +11,9 @@ Future<void> main() async {
|
||||
runApp(const MaterialApp(home: SizedBox()));
|
||||
try {
|
||||
await checkProfiles();
|
||||
stdout.writeln('PASS: native proxy, concurrent profiles, cookies, LocalStorage, IndexedDB and reopening');
|
||||
stdout.writeln(
|
||||
'PASS: native proxy, concurrent profiles, cookies, LocalStorage, IndexedDB, reopening and profile deletion',
|
||||
);
|
||||
exit(0);
|
||||
} catch (error, stack) {
|
||||
stderr.writeln('FAIL: $error\n$stack');
|
||||
@@ -190,11 +192,27 @@ Future<void> checkProfiles() async {
|
||||
expectValue((await a.getCookies(url: target)).single.isHttpOnly, true);
|
||||
await a.deleteCookie(url: target, name: 'session', domain: 'profiles.invalid');
|
||||
expectValue((await a.getCookies(url: target)).length, 0);
|
||||
for (final page in pages) {
|
||||
await page.dispose();
|
||||
}
|
||||
pages.clear();
|
||||
final untouched = await open(b);
|
||||
await js(untouched, "localStorage.setItem('owner','other')");
|
||||
await a.setCookie(url: target, name: 'delete-me', value: 'secret', isHttpOnly: true);
|
||||
await a.remove();
|
||||
await a.remove(); // Uninstall retries must be safe.
|
||||
final reinstalled = await open(a);
|
||||
expectValue(await js(reinstalled, "localStorage.getItem('owner')"), null);
|
||||
expectValue(await database(reinstalled, false), null);
|
||||
expectValue((await a.getCookies(url: target)).length, 0);
|
||||
expectValue(await js(untouched, "localStorage.getItem('owner')"), 'other');
|
||||
if (proxyHits == 0) throw StateError('Browser bypassed proxy');
|
||||
} finally {
|
||||
for (final page in pages) {
|
||||
await page.dispose();
|
||||
}
|
||||
await a.remove();
|
||||
await b.remove();
|
||||
await proxy.close();
|
||||
await plainOrigin.close(force: true);
|
||||
await origin.close(force: true);
|
||||
|
||||
Reference in new issue
Block a user