mirror of
https://github.com/GopeedLab/gopeed.git
synced 2026-11-19 23:03:43 +00:00
commit
b88144c864
564 files changed
+71880
-39
No files matched your search
@@ -0,0 +1,2 @@
|
||||
# Keep upstream plugin sources recognizable and collapsed in GitHub reviews.
|
||||
ui/flutter/third_party/** linguist-vendored whitespace=-blank-at-eol,-blank-at-eof
|
||||
@@ -91,7 +91,8 @@ jobs:
|
||||
flutter-version: ${{ env.FLUTTER_VERSION }}
|
||||
- name: Test webview
|
||||
if: runner.os == 'Windows'
|
||||
run: go test -tags webview -v -count=1 -timeout 300s ./internal/webview/goprovider/
|
||||
# Repeat close/reopen coverage to catch browser shutdown races.
|
||||
run: go test -tags webview -v -count=3 -timeout 300s ./internal/webview/goprovider/
|
||||
env:
|
||||
CGO_ENABLED: 1
|
||||
- name: Test webview
|
||||
|
||||
@@ -4,13 +4,14 @@ go 1.25.4
|
||||
|
||||
require (
|
||||
codeberg.org/gruf/go-ffmpreg v0.6.23-0.20260827095416-df1836cb5be0
|
||||
github.com/GopeedLab/webview_go v0.0.0-20260423085439-7a2f88b6e9b5
|
||||
github.com/GopeedLab/webview_go v0.0.0-20260915010614-2567e492369a
|
||||
github.com/anacrolix/torrent v1.60.1-0.20251217073903-486bcbe758e0
|
||||
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5
|
||||
github.com/bodgit/sevenzip v1.6.1
|
||||
github.com/dop251/goja v0.0.0-20260106131823-651366fbe6e3
|
||||
github.com/dop251/goja_nodejs v0.0.0-20240728170619-29b559befffc
|
||||
github.com/go-git/go-git/v5 v5.8.1
|
||||
github.com/google/jsonschema-go v0.4.3
|
||||
github.com/gorilla/handlers v1.5.1
|
||||
github.com/gorilla/mux v1.8.0
|
||||
github.com/imroc/req/v3 v3.52.2
|
||||
@@ -40,7 +41,6 @@ require (
|
||||
github.com/felixge/fgprof v0.9.5 // indirect
|
||||
github.com/go-task/slim-sprig/v3 v3.0.0 // indirect
|
||||
github.com/google/go-cmp v0.7.0 // indirect
|
||||
github.com/google/jsonschema-go v0.4.3 // indirect
|
||||
github.com/hashicorp/errwrap v1.1.0 // indirect
|
||||
github.com/hashicorp/go-multierror v1.1.1 // indirect
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
|
||||
|
||||
@@ -25,8 +25,8 @@ filippo.io/edwards25519 v1.0.0-rc.1 h1:m0VOOB23frXZvAOK44usCgLWvtsxIoMCTBGJZlpmG
|
||||
filippo.io/edwards25519 v1.0.0-rc.1/go.mod h1:N1IkdkCkiLB6tki+MYJoSx2JTY9NUlxZE7eHn5EwJns=
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
|
||||
github.com/GopeedLab/webview_go v0.0.0-20260423085439-7a2f88b6e9b5 h1:86LVTaNDM/j/uTAD2HedkXNO9LIQlt642VAdbU/0D/M=
|
||||
github.com/GopeedLab/webview_go v0.0.0-20260423085439-7a2f88b6e9b5/go.mod h1:FvV19lu9rQ9NcbczN5y8pbWecURRRbWa8tbfFARBDa0=
|
||||
github.com/GopeedLab/webview_go v0.0.0-20260915010614-2567e492369a h1:Vzz+8aMVX9ZPPpkxgxa7mCorrAgdXCZL5EunOpOBvao=
|
||||
github.com/GopeedLab/webview_go v0.0.0-20260915010614-2567e492369a/go.mod h1:FvV19lu9rQ9NcbczN5y8pbWecURRRbWa8tbfFARBDa0=
|
||||
github.com/Masterminds/semver/v3 v3.2.1 h1:RN9w6+7QoMeJVGyfmbcgs28Br8cvmnucEXnY0rYXWg0=
|
||||
github.com/Masterminds/semver/v3 v3.2.1/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYrf8m9wsX0PNOMQ=
|
||||
github.com/Microsoft/go-winio v0.5.2/go.mod h1:WpS1mjBmmwHBEWmogvA2mj8546UReBk4v8QkMxJ6pZY=
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
# Extension browser host configuration
|
||||
|
||||
The downloader wraps each provider with the extension's stable identity before
|
||||
constructing the runtime. `OpenOptions.ProfileID`, `DataPath`, and `ProxyURL` are
|
||||
host-only fields. `parseOpenOptions` never reads them from extension JavaScript.
|
||||
The extension API is unchanged.
|
||||
|
||||
Profiles are persistent and shared across invocations/pages of the same extension.
|
||||
Different identities use different native stores. Go providers use a SHA-256-based
|
||||
path under `<StorageDir>/webview`; Apple RPC hosts use a stable UUID data store;
|
||||
Android uses a named WebView profile. Cookie operations select that same store,
|
||||
including `clearCookies`. Closing an execution closes its pages, not its profile.
|
||||
Uninstall closes the extension's pages, prevents its old runtimes from opening
|
||||
new pages, and removes its native profile before deleting the extension record.
|
||||
Cleanup failures abort uninstall and can be retried. Reinstallation starts with
|
||||
empty browser data; an ordinary extension update keeps the existing profile.
|
||||
Windows/Linux delete the profile directory; Apple removes the named WebKit store.
|
||||
Android cannot delete a profile already loaded by the current process: when
|
||||
DELETE_BROWSING_DATA is supported it clears all site data immediately, and records
|
||||
an empty-profile deletion in SharedPreferences for the next process start. A
|
||||
reinstallation may reuse that cleared profile and cancels the pending deletion.
|
||||
If the full-data clearing API is unavailable, uninstall fails with a restart
|
||||
instruction; the pending profile is deleted at startup before it can be loaded.
|
||||
No removal operation is exposed through extension JavaScript.
|
||||
|
||||
Existing shared browser data is not copied into every extension's new profile.
|
||||
|
||||
The downloader lazily owns one loopback forward proxy with HTTP and SOCKS5
|
||||
listeners. Windows/Linux/Android use HTTP; Apple uses SOCKS5 because its HTTP
|
||||
CONNECT configuration may bypass plain HTTP. The forwarder reads the current
|
||||
Gopeed proxy config for each new request/tunnel and supports direct, system,
|
||||
HTTP(S) upstream proxies with Basic authentication, and authenticated SOCKS5.
|
||||
Credentials remain in Go and are never sent over the WebView RPC.
|
||||
|
||||
Changes affect new requests/connections. Existing CONNECT/SOCKS tunnels keep their
|
||||
route until closed; opening another page in the same profile does not reset it.
|
||||
SOCKS carries host/port rather than a full URL: system proxy/PAC selection for
|
||||
Apple is host-based, with port 80 treated as HTTP and other ports as HTTPS.
|
||||
Path-dependent PAC rules cannot be reproduced from a SOCKS connection.
|
||||
|
||||
Apple requires macOS 14 / iOS 17. Android checks MULTI_PROFILE and PROXY_OVERRIDE.
|
||||
Unsupported hosts fail explicitly instead of silently sharing browser storage or
|
||||
ignoring the proxy.
|
||||
|
||||
## Validation
|
||||
|
||||
- `go test -race ./internal/webview/proxy ./pkg/download/engine/webview`
|
||||
- `go test ./pkg/download -run 'TestWebViewProfileBound|TestDownloader_ExtensionRuntimeWebView'`
|
||||
- Windows/Linux: `go test -tags webview -v ./internal/webview/goprovider` (Linux: run under `xvfb-run -a`).
|
||||
- macOS: start the normal Flutter app, then run `go test -tags webview -v ./internal/webview/rpcprovider` with its socket address. See `rpcprovider/README.md`.
|
||||
- In webview_go: `go test -tags webview_integration -v -count=1 .` (Linux: run under `xvfb-run -a`).
|
||||
|
||||
The shared provider contract covers HTTP/HTTPS proxy routing, concurrent pages,
|
||||
HttpOnly cookies, LocalStorage, IndexedDB, profile-scoped clearing, reopening,
|
||||
and removal without affecting another profile. HTTPS routing is checked with a
|
||||
rejecting upstream tunnel; no test-only certificate bypass is added to the app.
|
||||
Go proxy unit tests separately cover successful TLS forwarding and authentication.
|
||||
These cases run in the existing `test.yml` WebView jobs; existing mobile build jobs
|
||||
compile the Android/iOS bridge. No separate Flutter test application is required.
|
||||
@@ -0,0 +1,47 @@
|
||||
//go:build linux && cgo
|
||||
|
||||
package goprovider
|
||||
|
||||
/*
|
||||
#cgo pkg-config: gtk+-3.0
|
||||
#include <gtk/gtk.h>
|
||||
static void pumpGTK(void) {
|
||||
// Bound each batch so Go creation/removal requests cannot be starved.
|
||||
for (int i = 0; i < 64 && g_main_context_pending(NULL); ++i)
|
||||
g_main_context_iteration(NULL, FALSE);
|
||||
}
|
||||
*/
|
||||
import "C"
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var gtkThreadOnce sync.Once
|
||||
var gtkThreadTasks = make(chan func())
|
||||
|
||||
func RunMainThreadLoop(run func() int) int { return run() }
|
||||
|
||||
func postMainThreadTask(task func()) bool {
|
||||
gtkThreadOnce.Do(func() {
|
||||
go func() {
|
||||
runtime.LockOSThread()
|
||||
// WebKit must always use its original UI thread, including after
|
||||
// the last page closes. A page cannot stop this shared event loop.
|
||||
ticker := time.NewTicker(10 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case task := <-gtkThreadTasks:
|
||||
task()
|
||||
case <-ticker.C:
|
||||
}
|
||||
C.pumpGTK()
|
||||
}
|
||||
}()
|
||||
})
|
||||
gtkThreadTasks <- task
|
||||
return true
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//go:build !darwin
|
||||
//go:build !darwin && (!linux || !cgo)
|
||||
|
||||
package goprovider
|
||||
|
||||
|
||||
@@ -105,7 +105,15 @@ func (p *pageWrapper) start() error {
|
||||
defer runtimepkg.UnlockOSThread()
|
||||
|
||||
var w webview.WebView
|
||||
if p.opts.Headless {
|
||||
if p.opts.DataPath != "" {
|
||||
var err error
|
||||
w, err = webview.NewWithOptions(webview.Options{Debug: p.opts.Debug, Headless: p.opts.Headless, DataPath: p.opts.DataPath, ProxyURL: p.opts.ProxyURL})
|
||||
if err != nil {
|
||||
p.ready <- err
|
||||
close(p.done)
|
||||
return
|
||||
}
|
||||
} else if p.opts.Headless {
|
||||
w = webview.NewHeadless(p.opts.Debug)
|
||||
} else {
|
||||
w = webview.New(p.opts.Debug)
|
||||
@@ -127,12 +135,18 @@ func (p *pageWrapper) start() error {
|
||||
if err := w.Bind(p.callbackName, func(payload string) error {
|
||||
return p.handleCallback(payload)
|
||||
}); err != nil {
|
||||
w.Destroy()
|
||||
p.ready <- err
|
||||
close(p.done)
|
||||
return
|
||||
}
|
||||
|
||||
applyWindowOptions(w, p.opts)
|
||||
w.SetHtml(buildBootstrapHTML(p.callbackName, p.readyID))
|
||||
if runtimepkg.GOOS == "linux" {
|
||||
// All GTK pages share the process-wide event loop below.
|
||||
return
|
||||
}
|
||||
w.Run()
|
||||
w.Destroy()
|
||||
close(p.done)
|
||||
@@ -318,7 +332,12 @@ func (p *pageWrapper) Close() error {
|
||||
// the quit message lands on the correct queue.
|
||||
terminateDone := make(chan struct{})
|
||||
w.Dispatch(func() {
|
||||
w.Terminate()
|
||||
if runtimepkg.GOOS == "linux" {
|
||||
w.Destroy()
|
||||
close(p.done)
|
||||
} else {
|
||||
w.Terminate()
|
||||
}
|
||||
close(terminateDone)
|
||||
})
|
||||
<-terminateDone
|
||||
@@ -610,3 +629,12 @@ func firstNonEmpty(values ...string) string {
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (p *Provider) RemoveProfile(profileID, dataPath string) error {
|
||||
done := make(chan error, 1)
|
||||
run := func() { done <- webview.RemoveProfile(dataPath) }
|
||||
if !postMainThreadTask(run) {
|
||||
run()
|
||||
}
|
||||
return <-done
|
||||
}
|
||||
@@ -13,3 +13,5 @@ func TestProviderContract(t *testing.T) {
|
||||
CookieDomainMode: integrationtest.CookieDomainModeRequired,
|
||||
})
|
||||
}
|
||||
|
||||
func TestProviderProfiles(t *testing.T) { integrationtest.RunProfileContract(t, New()) }
|
||||
@@ -1,10 +1,14 @@
|
||||
package integrationtest
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
webviewproxy "github.com/GopeedLab/gopeed/internal/webview/proxy"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -219,7 +223,19 @@ func openTestPage(t *testing.T, provider enginewebview.Provider, opts enginewebv
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
runtime := enginewebview.NewRuntime(provider, true)
|
||||
proxy, err := webviewproxy.New(nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { proxy.Close() })
|
||||
path := filepath.Join(t.TempDir(), "profile")
|
||||
sum := sha256.Sum256([]byte(path))
|
||||
profileID := fmt.Sprintf("%x-%x-%x-%x-%x", sum[:4], sum[4:6], sum[6:8], sum[8:10], sum[10:16])
|
||||
proxyURL := proxy.URL()
|
||||
if runtime.GOOS == "darwin" {
|
||||
proxyURL = proxy.SOCKSURL()
|
||||
}
|
||||
runtime := enginewebview.NewRuntime(&configuredOpener{provider: provider, profileID: profileID, dataPath: path, proxyURL: proxyURL}, true)
|
||||
page, err := runtime.Open(map[string]any{
|
||||
"headless": opts.Headless,
|
||||
"debug": opts.Debug,
|
||||
@@ -232,7 +248,14 @@ func openTestPage(t *testing.T, provider enginewebview.Provider, opts enginewebv
|
||||
t.Fatalf("failed to open webview: %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_ = runtime.Close()
|
||||
if err := runtime.Close(); err != nil {
|
||||
t.Errorf("close contract page: %v", err)
|
||||
}
|
||||
if remover, ok := provider.(enginewebview.ProfileRemover); ok {
|
||||
if err := remover.RemoveProfile(profileID, path); err != nil {
|
||||
t.Errorf("remove contract profile: %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return page, server, server.URL
|
||||
@@ -380,3 +403,15 @@ func hasCookie(cookies []enginewebview.Cookie, name string, value string) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type configuredOpener struct {
|
||||
provider enginewebview.Provider
|
||||
profileID, dataPath, proxyURL string
|
||||
}
|
||||
|
||||
func (o *configuredOpener) Open(opts enginewebview.OpenOptions) (enginewebview.Page, error) {
|
||||
opts.ProfileID = o.profileID
|
||||
opts.DataPath = o.dataPath
|
||||
opts.ProxyURL = o.proxyURL
|
||||
return o.provider.Open(opts)
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
package integrationtest
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
webviewproxy "github.com/GopeedLab/gopeed/internal/webview/proxy"
|
||||
webview "github.com/GopeedLab/gopeed/pkg/download/engine/webview"
|
||||
)
|
||||
|
||||
// RunProfileContract exercises the same host API through both native and RPC
|
||||
// providers. It never bypasses the host bridge with direct Flutter plugin calls.
|
||||
func RunProfileContract(t *testing.T, provider webview.Provider) {
|
||||
t.Helper()
|
||||
waitForProviderAvailable(t, provider, defaultAvailabilityTimeout)
|
||||
remover, ok := provider.(webview.ProfileRemover)
|
||||
if !ok {
|
||||
t.Fatal("provider does not implement host profile removal")
|
||||
}
|
||||
proxyURL, secureHits := profileProxy(t)
|
||||
a := newContractProfile(t, provider, remover, proxyURL)
|
||||
b := newContractProfile(t, provider, remover, proxyURL)
|
||||
first := a.open(t)
|
||||
assertProfileValue(t, first, `async () => { localStorage.setItem('owner','a'); return 'a'; }`, "a")
|
||||
assertProfileValue(t, first, profileDatabaseScript(true), "saved")
|
||||
if err := first.SetCookie(webview.Cookie{Name: "session", Value: "a", Domain: "profiles.invalid", Path: "/", HTTPOnly: true, Expires: time.Now().Add(time.Hour)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second := b.open(t)
|
||||
assertProfileValue(t, second, `() => localStorage.getItem('owner')`, nil)
|
||||
assertProfileValue(t, second, profileDatabaseScript(false), nil)
|
||||
assertProfileCookies(t, second, "", "new profile B")
|
||||
assertProfileValue(t, second, `() => { localStorage.setItem('owner','b'); return 'b'; }`, "b")
|
||||
if err := second.SetCookie(webview.Cookie{Name: "session", Value: "b", Domain: "profiles.invalid", Path: "/", HTTPOnly: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
shared := a.open(t)
|
||||
assertProfileValue(t, shared, `() => localStorage.getItem('owner')`, "a")
|
||||
assertProfileValue(t, shared, profileDatabaseScript(false), "saved")
|
||||
assertProfileCookies(t, shared, "a", "shared profile A")
|
||||
storedCookies, err := shared.GetCookies()
|
||||
if err != nil || len(storedCookies) != 1 || storedCookies[0].Expires.Before(time.Now()) {
|
||||
t.Fatalf("persistent cookie lost its expiration: %#v, error %v", storedCookies, err)
|
||||
}
|
||||
assertProfileValue(t, shared, `() => document.cookie`, "") // HttpOnly stays hidden.
|
||||
if err := second.ClearCookies(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertProfileCookies(t, first, "a", "clearing B leaves A intact")
|
||||
if err := second.SetCookie(webview.Cookie{Name: "session", Value: "b", Domain: "profiles.invalid", Path: "/", HTTPOnly: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a.close(t)
|
||||
reopened := a.open(t)
|
||||
assertProfileValue(t, reopened, `() => localStorage.getItem('owner')`, "a")
|
||||
assertProfileValue(t, reopened, profileDatabaseScript(false), "saved")
|
||||
assertProfileCookies(t, reopened, "a", "reopened profile A")
|
||||
// Include a session cookie immediately before deletion to catch stale
|
||||
// in-process CookieStore caches when the same profile is recreated.
|
||||
if err := reopened.SetCookie(webview.Cookie{Name: "session", Value: "remove-me", Domain: "profiles.invalid", Path: "/", HTTPOnly: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a.close(t)
|
||||
a.remove(t)
|
||||
a.remove(t) // Retrying a successful uninstall is harmless.
|
||||
reinstalled := a.open(t)
|
||||
assertProfileValue(t, reinstalled, `() => localStorage.getItem('owner')`, nil)
|
||||
assertProfileValue(t, reinstalled, profileDatabaseScript(false), nil)
|
||||
assertProfileCookies(t, reinstalled, "", "reinstalled profile A")
|
||||
assertProfileValue(t, second, `() => localStorage.getItem('owner')`, "b")
|
||||
assertProfileCookies(t, second, "b", "B after removing A")
|
||||
// Refuse the HTTPS tunnel deliberately. Seeing it at our proxy proves HTTPS
|
||||
// routing without adding a certificate-validation bypass to the test host.
|
||||
// WebView2 may commit its built-in error page and report navigation as
|
||||
// complete. The invariant here is that the HTTPS tunnel reaches the proxy.
|
||||
_ = reinstalled.Goto("https://profiles.invalid/", webview.GotoOptions{TimeoutMS: 5000})
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for secureHits.Load() == 0 && time.Now().Before(deadline) {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if secureHits.Load() == 0 {
|
||||
t.Fatal("HTTPS bypassed the host proxy")
|
||||
}
|
||||
}
|
||||
|
||||
type contractProfile struct {
|
||||
provider webview.Provider
|
||||
remover webview.ProfileRemover
|
||||
options webview.OpenOptions
|
||||
pages []webview.Page
|
||||
}
|
||||
|
||||
func newContractProfile(t *testing.T, provider webview.Provider, remover webview.ProfileRemover, proxyURL string) *contractProfile {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "profile")
|
||||
hash := sha256.Sum256([]byte(path))
|
||||
id := fmt.Sprintf("%x-%x-%x-%x-%x", hash[:4], hash[4:6], hash[6:8], hash[8:10], hash[10:16])
|
||||
p := &contractProfile{provider: provider, remover: remover, options: webview.OpenOptions{ProfileID: id, DataPath: path, ProxyURL: proxyURL, Headless: true, Title: "Gopeed profile contract"}}
|
||||
t.Cleanup(func() { p.close(t); p.remove(t) })
|
||||
return p
|
||||
}
|
||||
func (p *contractProfile) open(t *testing.T) webview.Page {
|
||||
t.Helper()
|
||||
page, err := p.provider.Open(p.options)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p.pages = append(p.pages, page)
|
||||
if err := page.Goto("http://profiles.invalid/", webview.GotoOptions{TimeoutMS: 10000}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return page
|
||||
}
|
||||
func (p *contractProfile) close(t *testing.T) {
|
||||
t.Helper()
|
||||
for _, page := range p.pages {
|
||||
if err := page.Close(); err != nil {
|
||||
t.Errorf("close profile page: %v", err)
|
||||
}
|
||||
}
|
||||
p.pages = nil
|
||||
}
|
||||
func (p *contractProfile) remove(t *testing.T) {
|
||||
t.Helper()
|
||||
if err := p.remover.RemoveProfile(p.options.ProfileID, p.options.DataPath); err != nil {
|
||||
t.Errorf("remove profile: %v", err)
|
||||
}
|
||||
}
|
||||
func assertProfileValue(t *testing.T, page webview.Page, script string, want any) {
|
||||
t.Helper()
|
||||
got, err := page.Execute(script)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("script %s: got %#v, want %#v", script, got, want)
|
||||
}
|
||||
}
|
||||
func assertProfileCookies(t *testing.T, page webview.Page, want, stage string) {
|
||||
t.Helper()
|
||||
// Native cookie managers propagate updates across browser processes
|
||||
// asynchronously. Wait for the expected state rather than assuming the
|
||||
// first IPC read already includes the preceding write.
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for {
|
||||
cookies, err := page.GetCookies()
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", stage, err)
|
||||
}
|
||||
matches := len(cookies) == 0 && want == "" || len(cookies) == 1 && want != "" && cookies[0].Name == "session" && cookies[0].Value == want && cookies[0].HTTPOnly
|
||||
if matches {
|
||||
return
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("%s: cookies %#v, want %q", stage, cookies, want)
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
func profileDatabaseScript(write bool) string {
|
||||
operation := "store.get('owner')"
|
||||
if write {
|
||||
operation = "store.put('saved','owner')"
|
||||
}
|
||||
return fmt.Sprintf(`async () => await new Promise((resolve,reject)=>{
|
||||
const request=indexedDB.open('profile-contract',1);
|
||||
request.onupgradeneeded=()=>request.result.createObjectStore('state');
|
||||
request.onerror=()=>reject(String(request.error));
|
||||
request.onsuccess=()=>{
|
||||
const db=request.result, tx=db.transaction('state','readwrite'), store=tx.objectStore('state');
|
||||
const op=%s; let value;
|
||||
op.onsuccess=()=>value=%s;
|
||||
tx.oncomplete=()=>{db.close();resolve(value===undefined?null:value)};
|
||||
tx.onerror=()=>{db.close();reject(String(tx.error))};
|
||||
};
|
||||
})`, operation, map[bool]string{true: "'saved'", false: "op.result"}[write])
|
||||
}
|
||||
|
||||
func profileProxy(t *testing.T) (string, *atomic.Int32) {
|
||||
t.Helper()
|
||||
origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
fmt.Fprint(w, "<!doctype html><title>Profile contract</title>")
|
||||
}))
|
||||
t.Cleanup(origin.Close)
|
||||
secureHits := &atomic.Int32{}
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodConnect {
|
||||
origin.Config.Handler.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
if r.Host == "profiles.invalid:443" {
|
||||
secureHits.Add(1)
|
||||
http.Error(w, "HTTPS routing fixture rejects tunnels", http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
if r.Host != "profiles.invalid:80" {
|
||||
http.Error(w, "unexpected target", http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
remote, err := net.DialTimeout("tcp", origin.Listener.Addr().String(), 5*time.Second)
|
||||
if err != nil {
|
||||
http.Error(w, "origin unavailable", http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
defer remote.Close()
|
||||
client, buffer, err := w.(http.Hijacker).Hijack()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer client.Close()
|
||||
if _, err := buffer.WriteString("HTTP/1.1 200 Connection Established\r\n\r\n"); err != nil {
|
||||
return
|
||||
}
|
||||
if err := buffer.Flush(); err != nil {
|
||||
return
|
||||
}
|
||||
go func() { io.Copy(remote, buffer); remote.Close() }()
|
||||
io.Copy(client, remote)
|
||||
}))
|
||||
t.Cleanup(upstream.Close)
|
||||
upstreamURL, err := url.Parse(upstream.URL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
proxy, err := webviewproxy.New(func(*http.Request) (*url.URL, error) { return upstreamURL, nil })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { proxy.Close() })
|
||||
if runtime.GOOS == "darwin" {
|
||||
return proxy.SOCKSURL(), secureHits
|
||||
}
|
||||
return proxy.URL(), secureHits
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
// Package proxy provides the host-owned WebView forward proxy. Browser engines
|
||||
// always use this endpoint; Gopeed decides the upstream route for each request.
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/armon/go-socks5"
|
||||
xproxy "golang.org/x/net/proxy"
|
||||
)
|
||||
|
||||
type Selector func(*http.Request) (*url.URL, error)
|
||||
|
||||
type Server struct {
|
||||
listener net.Listener
|
||||
socksListener net.Listener
|
||||
server *http.Server
|
||||
transport *http.Transport
|
||||
selectProxy Selector
|
||||
mu sync.Mutex
|
||||
connections map[io.Closer]struct{}
|
||||
closed bool
|
||||
}
|
||||
|
||||
func New(selectProxy Selector) (*Server, error) {
|
||||
if selectProxy == nil {
|
||||
selectProxy = func(*http.Request) (*url.URL, error) { return nil, nil }
|
||||
}
|
||||
listener, err := net.Listen("tcp4", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s := &Server{listener: listener, selectProxy: selectProxy, connections: make(map[io.Closer]struct{})}
|
||||
s.transport = &http.Transport{Proxy: selectProxy, DisableKeepAlives: true, TLSHandshakeTimeout: 15 * time.Second, ResponseHeaderTimeout: 30 * time.Second}
|
||||
s.server = &http.Server{Handler: s, ReadHeaderTimeout: 15 * time.Second}
|
||||
s.socksListener, err = net.Listen("tcp4", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
listener.Close()
|
||||
return nil, err
|
||||
}
|
||||
socks, err := socks5.New(&socks5.Config{Logger: log.New(io.Discard, "", 0), Resolver: unresolvedDNS{}, Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
_, port, _ := net.SplitHostPort(address)
|
||||
scheme := "https"
|
||||
if port == "80" {
|
||||
scheme = "http"
|
||||
}
|
||||
request := &http.Request{URL: &url.URL{Scheme: scheme, Host: address}, Header: make(http.Header)}
|
||||
upstream, err := selectProxy(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
timed, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
conn, err := dialTunnel(timed, address, upstream)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.track(conn)
|
||||
}})
|
||||
if err != nil {
|
||||
listener.Close()
|
||||
s.socksListener.Close()
|
||||
return nil, err
|
||||
}
|
||||
go s.server.Serve(listener)
|
||||
go socks.Serve(&trackedListener{Listener: s.socksListener, server: s})
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (s *Server) URL() string { return "http://" + s.listener.Addr().String() }
|
||||
|
||||
func (s *Server) SOCKSURL() string { return "socks5://" + s.socksListener.Addr().String() }
|
||||
|
||||
func (s *Server) Close() error {
|
||||
s.mu.Lock()
|
||||
s.closed = true
|
||||
connections := make([]io.Closer, 0, len(s.connections))
|
||||
for c := range s.connections {
|
||||
connections = append(connections, c)
|
||||
}
|
||||
s.mu.Unlock()
|
||||
for _, c := range connections {
|
||||
c.Close()
|
||||
}
|
||||
s.socksListener.Close()
|
||||
s.transport.CloseIdleConnections()
|
||||
return s.server.Close()
|
||||
}
|
||||
|
||||
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodConnect {
|
||||
s.connect(w, r)
|
||||
return
|
||||
}
|
||||
if !r.URL.IsAbs() || (r.URL.Scheme != "http" && r.URL.Scheme != "https") {
|
||||
http.Error(w, "absolute HTTP URL required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
out := r.Clone(r.Context())
|
||||
out.RequestURI = ""
|
||||
upgrade := out.Header.Get("Upgrade")
|
||||
stripHopHeaders(out.Header)
|
||||
if upgrade != "" {
|
||||
out.Header.Set("Connection", "Upgrade")
|
||||
out.Header.Set("Upgrade", upgrade)
|
||||
}
|
||||
resp, err := s.transport.RoundTrip(out)
|
||||
if err != nil {
|
||||
http.Error(w, "upstream request failed", http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode == http.StatusSwitchingProtocols {
|
||||
remote, ok := resp.Body.(io.ReadWriteCloser)
|
||||
if !ok {
|
||||
http.Error(w, "invalid upstream upgrade", 502)
|
||||
return
|
||||
}
|
||||
client, buffer, err := w.(http.Hijacker).Hijack()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer client.Close()
|
||||
resp.Body = nil
|
||||
if err := resp.Write(buffer); err != nil {
|
||||
return
|
||||
}
|
||||
if err := buffer.Flush(); err != nil {
|
||||
return
|
||||
}
|
||||
s.bridge(client, buffer, remote)
|
||||
return
|
||||
}
|
||||
stripHopHeaders(resp.Header)
|
||||
for k, v := range resp.Header {
|
||||
w.Header()[k] = v
|
||||
}
|
||||
w.WriteHeader(resp.StatusCode)
|
||||
io.Copy(w, resp.Body)
|
||||
}
|
||||
|
||||
func stripHopHeaders(h http.Header) {
|
||||
for _, key := range strings.Split(h.Get("Connection"), ",") {
|
||||
h.Del(strings.TrimSpace(key))
|
||||
}
|
||||
for _, key := range []string{"Connection", "Proxy-Connection", "Proxy-Authorization", "Proxy-Authenticate", "Keep-Alive", "TE", "Trailer", "Transfer-Encoding", "Upgrade"} {
|
||||
h.Del(key)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) connect(w http.ResponseWriter, r *http.Request) {
|
||||
if _, _, err := net.SplitHostPort(r.Host); err != nil {
|
||||
http.Error(w, "invalid tunnel destination", 400)
|
||||
return
|
||||
}
|
||||
target := r.Clone(r.Context())
|
||||
target.URL = &url.URL{Scheme: "https", Host: r.Host}
|
||||
upstream, err := s.selectProxy(target)
|
||||
if err != nil {
|
||||
http.Error(w, "proxy selection failed", 502)
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
defer cancel()
|
||||
remote, err := dialTunnel(ctx, r.Host, upstream)
|
||||
if err != nil {
|
||||
http.Error(w, "upstream connection failed", 502)
|
||||
return
|
||||
}
|
||||
defer remote.Close()
|
||||
client, buffer, err := w.(http.Hijacker).Hijack()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer client.Close()
|
||||
if _, err := buffer.WriteString("HTTP/1.1 200 Connection Established\r\n\r\n"); err != nil {
|
||||
return
|
||||
}
|
||||
if err := buffer.Flush(); err != nil {
|
||||
return
|
||||
}
|
||||
s.bridge(client, buffer, remote)
|
||||
}
|
||||
|
||||
func (s *Server) bridge(client net.Conn, buffer *bufio.ReadWriter, remote io.ReadWriteCloser) {
|
||||
s.mu.Lock()
|
||||
if s.closed {
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
s.connections[client] = struct{}{}
|
||||
s.connections[remote] = struct{}{}
|
||||
s.mu.Unlock()
|
||||
defer func() { s.mu.Lock(); delete(s.connections, client); delete(s.connections, remote); s.mu.Unlock() }()
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() { io.Copy(remote, buffer); remote.Close(); close(done) }()
|
||||
io.Copy(client, remote)
|
||||
client.Close()
|
||||
<-done
|
||||
}
|
||||
|
||||
type bufferedConn struct {
|
||||
net.Conn
|
||||
reader *bufio.Reader
|
||||
}
|
||||
|
||||
func (c *bufferedConn) Read(p []byte) (int, error) { return c.reader.Read(p) }
|
||||
|
||||
func dialTunnel(ctx context.Context, target string, upstream *url.URL) (net.Conn, error) {
|
||||
dialer := &net.Dialer{}
|
||||
if upstream == nil {
|
||||
return dialer.DialContext(ctx, "tcp", target)
|
||||
}
|
||||
if upstream.Scheme == "socks5" || upstream.Scheme == "socks5h" {
|
||||
u := *upstream
|
||||
u.Scheme = "socks5"
|
||||
d, err := xproxy.FromURL(&u, dialer)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return d.(xproxy.ContextDialer).DialContext(ctx, "tcp", target)
|
||||
}
|
||||
if upstream.Scheme != "http" && upstream.Scheme != "https" {
|
||||
return nil, errors.New("unsupported proxy scheme")
|
||||
}
|
||||
host := upstream.Host
|
||||
if upstream.Port() == "" {
|
||||
port := "80"
|
||||
if upstream.Scheme == "https" {
|
||||
port = "443"
|
||||
}
|
||||
host = net.JoinHostPort(upstream.Hostname(), port)
|
||||
}
|
||||
conn, err := dialer.DialContext(ctx, "tcp", host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ok := false
|
||||
defer func() {
|
||||
if !ok {
|
||||
conn.Close()
|
||||
}
|
||||
}()
|
||||
if deadline, exists := ctx.Deadline(); exists {
|
||||
conn.SetDeadline(deadline)
|
||||
}
|
||||
if upstream.Scheme == "https" {
|
||||
secure := tls.Client(conn, &tls.Config{ServerName: upstream.Hostname(), MinVersion: tls.VersionTLS12})
|
||||
if err := secure.HandshakeContext(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conn = secure
|
||||
}
|
||||
request := &http.Request{Method: http.MethodConnect, URL: &url.URL{Opaque: target}, Host: target, Header: make(http.Header)}
|
||||
if upstream.User != nil {
|
||||
password, _ := upstream.User.Password()
|
||||
request.Header.Set("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(upstream.User.Username()+":"+password)))
|
||||
}
|
||||
if err := request.Write(conn); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
reader := bufio.NewReader(conn)
|
||||
response, err := http.ReadResponse(reader, request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if response.StatusCode != 200 {
|
||||
response.Body.Close()
|
||||
return nil, fmt.Errorf("upstream CONNECT status %d", response.StatusCode)
|
||||
}
|
||||
conn.SetDeadline(time.Time{})
|
||||
ok = true
|
||||
return &bufferedConn{Conn: conn, reader: reader}, nil
|
||||
}
|
||||
|
||||
// Leave hostname resolution to the selected upstream (SOCKS remote DNS / CONNECT).
|
||||
type unresolvedDNS struct{}
|
||||
|
||||
func (unresolvedDNS) Resolve(ctx context.Context, name string) (context.Context, net.IP, error) {
|
||||
return ctx, nil, nil
|
||||
}
|
||||
|
||||
type trackedListener struct {
|
||||
net.Listener
|
||||
server *Server
|
||||
}
|
||||
|
||||
func (l *trackedListener) Accept() (net.Conn, error) {
|
||||
c, err := l.Listener.Accept()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return l.server.track(c)
|
||||
}
|
||||
|
||||
type trackedConn struct {
|
||||
net.Conn
|
||||
server *Server
|
||||
}
|
||||
|
||||
func (c *trackedConn) Close() error {
|
||||
err := c.Conn.Close()
|
||||
c.server.mu.Lock()
|
||||
delete(c.server.connections, c)
|
||||
c.server.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
func (s *Server) track(c net.Conn) (net.Conn, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.closed {
|
||||
c.Close()
|
||||
return nil, net.ErrClosed
|
||||
}
|
||||
tracked := &trackedConn{Conn: c, server: s}
|
||||
s.connections[tracked] = struct{}{}
|
||||
return tracked, nil
|
||||
}
|
||||
|
||||
func (c *trackedConn) CloseWrite() error { return closeWrite(c.Conn) }
|
||||
func (c *bufferedConn) CloseWrite() error { return closeWrite(c.Conn) }
|
||||
func closeWrite(c net.Conn) error {
|
||||
if writer, ok := c.(interface{ CloseWrite() error }); ok {
|
||||
return writer.CloseWrite()
|
||||
}
|
||||
return c.Close()
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/armon/go-socks5"
|
||||
)
|
||||
|
||||
func TestRejectedProxyRequests(t *testing.T) {
|
||||
secret := "upstream-password"
|
||||
for _, tc := range []struct {
|
||||
name, method, target string
|
||||
status int
|
||||
}{
|
||||
{"relative URL", "GET", "/relative", 400},
|
||||
{"unsupported URL", "GET", "ftp://example.com/file", 400},
|
||||
{"invalid CONNECT", "CONNECT", "example.com", 400},
|
||||
{"HTTP selection failure", "GET", "http://example.com/", 502},
|
||||
{"CONNECT selection failure", "CONNECT", "example.com:443", 502},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s := &Server{selectProxy: func(*http.Request) (*url.URL, error) { return nil, errors.New(secret) }}
|
||||
s.transport = &http.Transport{Proxy: s.selectProxy}
|
||||
defer s.transport.CloseIdleConnections()
|
||||
response := httptest.NewRecorder()
|
||||
s.ServeHTTP(response, httptest.NewRequest(tc.method, tc.target, nil))
|
||||
if response.Code != tc.status || strings.Contains(response.Body.String(), secret) {
|
||||
t.Fatalf("unexpected proxy rejection: %d %q", response.Code, response.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTunnelRejectsUnsafeUpstreams(t *testing.T) {
|
||||
rejected := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "authentication required", http.StatusProxyAuthRequired)
|
||||
}))
|
||||
defer rejected.Close()
|
||||
secure := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Error("untrusted TLS proxy received a request")
|
||||
}))
|
||||
defer secure.Close()
|
||||
for _, upstream := range []string{"ftp://127.0.0.1", rejected.URL, secure.URL} {
|
||||
t.Run(upstream, func(t *testing.T) {
|
||||
selected, err := url.Parse(upstream)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
conn, err := dialTunnel(ctx, "example.com:443", selected)
|
||||
if conn != nil {
|
||||
conn.Close()
|
||||
}
|
||||
if err == nil {
|
||||
t.Fatal("unsafe upstream unexpectedly accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoutesAndAuthentication(t *testing.T) {
|
||||
origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Proxy-Authorization") != "" {
|
||||
t.Error("proxy credentials leaked to origin")
|
||||
}
|
||||
w.Write([]byte("origin"))
|
||||
}))
|
||||
defer origin.Close()
|
||||
secure := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("secure")) }))
|
||||
defer secure.Close()
|
||||
upstream, err := New(func(*http.Request) (*url.URL, error) { return nil, nil })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer upstream.Close()
|
||||
var authenticated atomic.Int32
|
||||
authProxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Proxy-Authorization") != "Basic dXNlcjpwYXNz" {
|
||||
http.Error(w, "authentication required", 407)
|
||||
return
|
||||
}
|
||||
authenticated.Add(1)
|
||||
upstream.ServeHTTP(w, r)
|
||||
}))
|
||||
defer authProxy.Close()
|
||||
socks, err := socks5.New(&socks5.Config{Credentials: socks5.StaticCredentials{"user": "pass"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer listener.Close()
|
||||
go socks.Serve(listener)
|
||||
for _, route := range []string{"", authProxy.URL, "socks5://" + listener.Addr().String()} {
|
||||
t.Run(route, func(t *testing.T) {
|
||||
var selected *url.URL
|
||||
if route != "" {
|
||||
selected, _ = url.Parse(route)
|
||||
selected.User = url.UserPassword("user", "pass")
|
||||
}
|
||||
local, err := New(func(r *http.Request) (*url.URL, error) { return selected, nil })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer local.Close()
|
||||
proxyURL, _ := url.Parse(local.URL())
|
||||
transport := &http.Transport{Proxy: http.ProxyURL(proxyURL), TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}
|
||||
defer transport.CloseIdleConnections()
|
||||
client := &http.Client{Transport: transport, Timeout: 5 * time.Second}
|
||||
for _, test := range []struct{ url, want string }{{origin.URL, "origin"}, {secure.URL, "secure"}} {
|
||||
response, err := client.Get(test.url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body, _ := io.ReadAll(response.Body)
|
||||
response.Body.Close()
|
||||
if string(body) != test.want {
|
||||
t.Fatalf("got status %d, body %q", response.StatusCode, body)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
if authenticated.Load() != 2 {
|
||||
t.Fatalf("expected authenticated HTTP and CONNECT, got %d", authenticated.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoutingChangesAndFailureDoesNotBypassProxy(t *testing.T) {
|
||||
var hits atomic.Int32
|
||||
origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { hits.Add(1); w.Write([]byte("direct")) }))
|
||||
defer origin.Close()
|
||||
var useProxy atomic.Bool
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("proxied")) }))
|
||||
upstreamURL, _ := url.Parse(upstream.URL)
|
||||
local, err := New(func(*http.Request) (*url.URL, error) {
|
||||
if useProxy.Load() {
|
||||
return upstreamURL, nil
|
||||
}
|
||||
return nil, nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer local.Close()
|
||||
endpoint, _ := url.Parse(local.URL())
|
||||
transport := &http.Transport{Proxy: http.ProxyURL(endpoint)}
|
||||
defer transport.CloseIdleConnections()
|
||||
client := &http.Client{Transport: transport, Timeout: 3 * time.Second}
|
||||
for _, want := range []string{"direct", "proxied", "upstream request failed\n"} {
|
||||
resp, err := client.Get(origin.URL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
if string(body) != want {
|
||||
t.Fatalf("got %q want %q", body, want)
|
||||
}
|
||||
if want == "direct" {
|
||||
useProxy.Store(true)
|
||||
} else if want == "proxied" {
|
||||
upstream.Close()
|
||||
}
|
||||
}
|
||||
if hits.Load() != 1 {
|
||||
t.Fatal("failed proxy must not fall back to direct")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloseTerminatesTunnels(t *testing.T) {
|
||||
echo, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer echo.Close()
|
||||
go func() {
|
||||
c, e := echo.Accept()
|
||||
if e == nil {
|
||||
defer c.Close()
|
||||
io.Copy(c, c)
|
||||
}
|
||||
}()
|
||||
s, err := New(func(*http.Request) (*url.URL, error) { return nil, nil })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
endpoint, _ := url.Parse(s.URL())
|
||||
c, err := dialTunnel(context.Background(), echo.Addr().String(), endpoint)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
c.SetDeadline(time.Now().Add(3 * time.Second))
|
||||
c.Write([]byte("hello\n"))
|
||||
line, err := bufio.NewReader(c).ReadString('\n')
|
||||
if err != nil || line != "hello\n" {
|
||||
t.Fatalf("echo %q %v", line, err)
|
||||
}
|
||||
s.Close()
|
||||
if _, err := c.Read(make([]byte, 1)); err == nil {
|
||||
t.Fatal("tunnel stayed open")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSOCKSIngressPreservesRemoteDNS(t *testing.T) {
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != "CONNECT" || r.Host != "unresolved.invalid:80" {
|
||||
t.Errorf("lost destination: %s %s", r.Method, r.Host)
|
||||
}
|
||||
c, b, err := w.(http.Hijacker).Hijack()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer c.Close()
|
||||
b.WriteString("HTTP/1.1 200 Connection Established\r\n\r\n")
|
||||
b.Flush()
|
||||
request, err := http.ReadRequest(b.Reader)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
request.Body.Close()
|
||||
b.WriteString("HTTP/1.1 200 OK\r\nContent-Length: 7\r\nConnection: close\r\n\r\nproxied")
|
||||
b.Flush()
|
||||
}))
|
||||
defer upstream.Close()
|
||||
target, _ := url.Parse(upstream.URL)
|
||||
local, err := New(func(r *http.Request) (*url.URL, error) {
|
||||
if r.URL.Host != "unresolved.invalid:80" {
|
||||
t.Errorf("selector lost hostname: %s", r.URL)
|
||||
}
|
||||
return target, nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer local.Close()
|
||||
endpoint, _ := url.Parse(local.SOCKSURL())
|
||||
transport := &http.Transport{Proxy: http.ProxyURL(endpoint)}
|
||||
defer transport.CloseIdleConnections()
|
||||
client := &http.Client{Transport: transport, Timeout: 5 * time.Second}
|
||||
response, err := client.Get("http://unresolved.invalid/")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
body, _ := io.ReadAll(response.Body)
|
||||
if string(body) != "proxied" {
|
||||
t.Fatalf("unexpected body %q", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPUpgradeIsForwarded(t *testing.T) {
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Upgrade") != "fixture" {
|
||||
http.Error(w, "upgrade lost", 400)
|
||||
return
|
||||
}
|
||||
c, b, err := w.(http.Hijacker).Hijack()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer c.Close()
|
||||
b.WriteString("HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: fixture\r\n\r\n")
|
||||
b.Flush()
|
||||
line, err := b.ReadString('\n')
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
b.WriteString(line)
|
||||
b.Flush()
|
||||
}))
|
||||
defer upstream.Close()
|
||||
local, err := New(nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer local.Close()
|
||||
endpoint, _ := url.Parse(local.URL())
|
||||
c, err := net.Dial("tcp", endpoint.Host)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
c.SetDeadline(time.Now().Add(3 * time.Second))
|
||||
io.WriteString(c, "GET "+upstream.URL+"/ HTTP/1.1\r\nHost: fixture\r\nConnection: Upgrade\r\nUpgrade: fixture\r\n\r\n")
|
||||
reader := bufio.NewReader(c)
|
||||
response, err := http.ReadResponse(reader, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.StatusCode != 101 {
|
||||
t.Fatalf("upgrade failed: %s", response.Status)
|
||||
}
|
||||
io.WriteString(c, "hello\n")
|
||||
line, err := reader.ReadString('\n')
|
||||
if err != nil || line != "hello\n" {
|
||||
t.Fatalf("upgraded echo %q %v", line, err)
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
@@ -109,9 +110,14 @@ func (p *page) ClearCookies() error {
|
||||
}
|
||||
|
||||
func (p *page) Close() error {
|
||||
return p.client.Call(enginewebview.MethodPageClose, enginewebview.PageCloseParams{
|
||||
err := p.client.Call(enginewebview.MethodPageClose, enginewebview.PageCloseParams{
|
||||
PageID: p.id,
|
||||
}, nil)
|
||||
var rpcErr *enginewebview.RPCError
|
||||
if errors.As(err, &rpcErr) && rpcErr.Code == enginewebview.ErrorCodePageNotFound {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
@@ -193,3 +199,7 @@ func (c *Client) Call(method string, params any, result any) error {
|
||||
}
|
||||
return json.Unmarshal(body.Result, result)
|
||||
}
|
||||
|
||||
func (p *Provider) RemoveProfile(profileID, dataPath string) error {
|
||||
return p.client.Call(enginewebview.MethodProfileRemove, enginewebview.ProfileRemoveParams{ProfileID: profileID}, nil)
|
||||
}
|
||||
@@ -37,3 +37,8 @@ func defaultWebViewRPCAddress() string {
|
||||
}
|
||||
return filepath.Join(homeDir, "Library", "Application Support", "com.gopeed.gopeed", "gopeed_webview.sock")
|
||||
}
|
||||
|
||||
func TestProviderProfiles(t *testing.T) {
|
||||
provider := New(enginewebview.RPCConfig{Network: *webViewRPCNetwork, Address: *webViewRPCAddress, Token: *webViewRPCToken})
|
||||
integrationtest.RunProfileContract(t, provider)
|
||||
}
|
||||
@@ -184,3 +184,29 @@ func TestPageSetCookieParamsOmitsZeroExpires(t *testing.T) {
|
||||
t.Fatalf("expected expires in payload: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoveProfileUsesPrivateHostRPC(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var request struct {
|
||||
Method string `json:"method"`
|
||||
Params map[string]string `json:"params"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if request.Method != enginewebview.MethodProfileRemove || request.Params["profileId"] != "extension-profile" || len(request.Params) != 1 {
|
||||
t.Errorf("unexpected profile removal request: %+v", request)
|
||||
}
|
||||
if r.Header.Get("Authorization") != "Bearer secret" {
|
||||
t.Error("missing host authentication")
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write([]byte(`{"error":{"code":"PROFILE_REMOVE_FAILED","message":"store busy"}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
provider := New(enginewebview.RPCConfig{Network: "tcp", Address: strings.TrimPrefix(server.URL, "http://"), Token: "secret"})
|
||||
err := provider.(enginewebview.ProfileRemover).RemoveProfile("extension-profile", "/host-only/path")
|
||||
if err == nil || err.Error() != "store busy" {
|
||||
t.Fatalf("cleanup failure was lost: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
"github.com/GopeedLab/gopeed/internal/controller"
|
||||
"github.com/GopeedLab/gopeed/internal/fetcher"
|
||||
"github.com/GopeedLab/gopeed/internal/logger"
|
||||
webviewproxy "github.com/GopeedLab/gopeed/internal/webview/proxy"
|
||||
"github.com/GopeedLab/gopeed/pkg/base"
|
||||
"github.com/GopeedLab/gopeed/pkg/protocol/http"
|
||||
"github.com/GopeedLab/gopeed/pkg/util"
|
||||
@@ -97,8 +98,12 @@ type Progress struct {
|
||||
}
|
||||
|
||||
type Downloader struct {
|
||||
Logger *logger.Logger
|
||||
ExtensionLogger *logger.Logger
|
||||
webviewProfilesLock sync.Mutex
|
||||
webviewProfiles map[string]*extensionWebViewProfile
|
||||
webviewProxyLock sync.Mutex
|
||||
webviewProxy *webviewproxy.Server
|
||||
Logger *logger.Logger
|
||||
ExtensionLogger *logger.Logger
|
||||
|
||||
cfg *DownloaderConfig
|
||||
fetcherCache map[string]fetcher.Fetcher
|
||||
@@ -1114,6 +1119,11 @@ func (d *Downloader) doDelete(task *Task, force bool) (err error) {
|
||||
|
||||
func (d *Downloader) Close() error {
|
||||
d.closed.Store(true)
|
||||
d.webviewProxyLock.Lock()
|
||||
if d.webviewProxy != nil {
|
||||
_ = d.webviewProxy.Close()
|
||||
}
|
||||
d.webviewProxyLock.Unlock()
|
||||
|
||||
closeArr := []func() error{
|
||||
d.pauseAll,
|
||||
|
||||
@@ -5,6 +5,7 @@ import "encoding/json"
|
||||
const RPCEndpointPath = "/webview"
|
||||
|
||||
const (
|
||||
MethodProfileRemove = "profile.remove"
|
||||
MethodIsAvailable = "webview.isAvailable"
|
||||
MethodPageOpen = "page.open"
|
||||
MethodPageAddInitScript = "page.addInitScript"
|
||||
@@ -68,6 +69,9 @@ type IsAvailableResult struct {
|
||||
}
|
||||
|
||||
type PageOpenParams struct {
|
||||
ProfileID string `json:"profileId,omitempty"`
|
||||
DataPath string `json:"dataPath,omitempty"`
|
||||
ProxyURL string `json:"proxyUrl,omitempty"`
|
||||
Headless bool `json:"headless,omitempty"`
|
||||
Debug bool `json:"debug,omitempty"`
|
||||
Title string `json:"title,omitempty"`
|
||||
@@ -78,6 +82,9 @@ type PageOpenParams struct {
|
||||
|
||||
func NewPageOpenParams(opts OpenOptions) PageOpenParams {
|
||||
return PageOpenParams{
|
||||
ProfileID: opts.ProfileID,
|
||||
DataPath: opts.DataPath,
|
||||
ProxyURL: opts.ProxyURL,
|
||||
Headless: opts.Headless,
|
||||
Debug: opts.Debug,
|
||||
Title: opts.Title,
|
||||
@@ -141,3 +148,8 @@ type PageCloseParams struct {
|
||||
}
|
||||
|
||||
type EmptyResult struct{}
|
||||
|
||||
// ProfileRemoveParams belongs to the private host RPC.
|
||||
type ProfileRemoveParams struct {
|
||||
ProfileID string `json:"profileId"`
|
||||
}
|
||||
@@ -17,6 +17,11 @@ type Opener interface {
|
||||
Open(opts OpenOptions) (Page, error)
|
||||
}
|
||||
|
||||
// ProfileRemover is a host-only lifecycle operation, never exposed to extension JS.
|
||||
type ProfileRemover interface {
|
||||
RemoveProfile(profileID, dataPath string) error
|
||||
}
|
||||
|
||||
type Page interface {
|
||||
AddInitScript(script string) error
|
||||
Goto(url string, opts GotoOptions) error
|
||||
@@ -29,6 +34,10 @@ type Page interface {
|
||||
}
|
||||
|
||||
type OpenOptions struct {
|
||||
// Host-owned fields are never parsed from extension JavaScript options.
|
||||
ProfileID string
|
||||
DataPath string
|
||||
ProxyURL string
|
||||
Headless bool
|
||||
Debug bool
|
||||
Title string
|
||||
|
||||
@@ -336,3 +336,15 @@ func (p *fakePage) Close() error {
|
||||
p.closed = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestExtensionCannotSupplyHostProfileOrProxy(t *testing.T) {
|
||||
opener := &fakeOpener{page: &fakePage{}}
|
||||
runtime := NewRuntime(opener, true)
|
||||
_, err := runtime.Open(map[string]any{"profileId": "other-extension", "dataPath": "/tmp/other-profile", "proxyUrl": "http://example.com:1234", "ProfileID": "other"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if opener.opts.ProfileID != "" || opener.opts.DataPath != "" || opener.opts.ProxyURL != "" {
|
||||
t.Fatalf("extension controlled host settings: %+v", opener.opts)
|
||||
}
|
||||
}
|
||||
@@ -65,6 +65,7 @@ func (d *Downloader) InstallExtensionByFolder(path string, devMode bool) (*Exten
|
||||
|
||||
// if extension is not installed, add it to the list, otherwise update it
|
||||
installedExt := d.getExtension(ext.Identity)
|
||||
newInstallation := installedExt == nil
|
||||
if installedExt == nil {
|
||||
ext.CreatedAt = time.Now()
|
||||
ext.UpdatedAt = ext.CreatedAt
|
||||
@@ -76,6 +77,11 @@ func (d *Downloader) InstallExtensionByFolder(path string, devMode bool) (*Exten
|
||||
if err = d.storage.Put(bucketExtension, installedExt.Identity, installedExt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if newInstallation {
|
||||
d.webviewProfilesLock.Lock()
|
||||
delete(d.webviewProfiles, ext.Identity)
|
||||
d.webviewProfilesLock.Unlock()
|
||||
}
|
||||
return installedExt, nil
|
||||
}
|
||||
|
||||
@@ -144,6 +150,9 @@ func (d *Downloader) DeleteExtension(identity string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.removeExtensionWebViewProfile(identity); err != nil {
|
||||
return fmt.Errorf("remove extension WebView data: %w", err)
|
||||
}
|
||||
// remove from disk
|
||||
if !ext.DevMode {
|
||||
if err := os.RemoveAll(d.ExtensionPath(ext)); err != nil {
|
||||
@@ -365,7 +374,7 @@ func doTrigger[T any](d *Downloader, event ActivationEvent, req *base.Request, c
|
||||
engine, session := d.newExtensionEngine()
|
||||
defer session.CloseIfIdle()
|
||||
gopeed.Runtime = &InstanceRuntime{
|
||||
WebView: d.newExtensionWebViewRuntime(session),
|
||||
WebView: d.newExtensionWebViewRuntime(session, ext.buildIdentity()),
|
||||
}
|
||||
err = injectGopeed(engine.Runtime, gopeed)
|
||||
if err != nil {
|
||||
|
||||
@@ -30,7 +30,7 @@ func (d *Downloader) NewExtensionEngine(ext *Extension, settings map[string]any)
|
||||
identity: ext.buildIdentity(),
|
||||
},
|
||||
Runtime: &InstanceRuntime{
|
||||
WebView: d.newExtensionWebViewRuntime(session),
|
||||
WebView: d.newExtensionWebViewRuntime(session, ext.buildIdentity()),
|
||||
},
|
||||
}
|
||||
if err := injectGopeed(engine.Runtime, gopeed); err != nil {
|
||||
|
||||
@@ -135,13 +135,13 @@ func (d *Downloader) newExtensionEngine() (*engine.Engine, *engineSession) {
|
||||
return e, session
|
||||
}
|
||||
|
||||
func (d *Downloader) newExtensionWebViewRuntime(session *engineSession) *enginewebview.Runtime {
|
||||
func (d *Downloader) newExtensionWebViewRuntime(session *engineSession, identity string) *enginewebview.Runtime {
|
||||
var (
|
||||
opener enginewebview.Opener
|
||||
available bool
|
||||
)
|
||||
if provider := d.cfg.WebViewProvider; provider != nil && provider.IsAvailable() {
|
||||
opener = provider
|
||||
opener = &extensionWebViewOpener{downloader: d, provider: provider, identity: identity, profile: d.extensionWebViewProfile(identity)}
|
||||
available = true
|
||||
}
|
||||
runtime := enginewebview.NewRuntime(opener, available)
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
package download
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
"github.com/GopeedLab/gopeed/pkg/base"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
|
||||
webviewproxy "github.com/GopeedLab/gopeed/internal/webview/proxy"
|
||||
enginewebview "github.com/GopeedLab/gopeed/pkg/download/engine/webview"
|
||||
)
|
||||
|
||||
// extensionWebViewOpener binds browser state to the owning extension. Neither
|
||||
// identity, filesystem paths nor proxy settings are accepted from JavaScript.
|
||||
type extensionWebViewOpener struct {
|
||||
downloader *Downloader
|
||||
provider enginewebview.Provider
|
||||
identity string
|
||||
profile *extensionWebViewProfile
|
||||
}
|
||||
|
||||
func (o *extensionWebViewOpener) Open(opts enginewebview.OpenOptions) (enginewebview.Page, error) {
|
||||
if o.identity == "" {
|
||||
return nil, fmt.Errorf("webview extension identity is required")
|
||||
}
|
||||
profile := o.profile
|
||||
if profile == nil {
|
||||
profile = o.downloader.extensionWebViewProfile(o.identity)
|
||||
}
|
||||
profile.mu.Lock()
|
||||
defer profile.mu.Unlock()
|
||||
if profile.revoked {
|
||||
return nil, fmt.Errorf("extension WebView profile has been removed")
|
||||
}
|
||||
id, path, err := o.downloader.extensionWebViewLocation(o.identity)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
opts.ProfileID, opts.DataPath = id, path
|
||||
opts.ProxyURL, err = o.downloader.webviewProxyURL()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
page, err := o.provider.Open(opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tracked := &extensionWebViewPage{Page: page, profile: profile}
|
||||
profile.pages[tracked] = struct{}{}
|
||||
return tracked, nil
|
||||
}
|
||||
|
||||
func (d *Downloader) webviewProxyURL() (string, error) {
|
||||
d.webviewProxyLock.Lock()
|
||||
defer d.webviewProxyLock.Unlock()
|
||||
if d.closed.Load() {
|
||||
return "", fmt.Errorf("downloader is closed")
|
||||
}
|
||||
if d.webviewProxy == nil {
|
||||
server, err := webviewproxy.New(func(r *http.Request) (*url.URL, error) {
|
||||
if d.blob != nil && d.blob.IsURL(r.URL.String()) {
|
||||
return nil, nil
|
||||
}
|
||||
d.configLock.RLock()
|
||||
var cfg base.DownloaderProxyConfig
|
||||
if d.cfg.Proxy != nil {
|
||||
cfg = *d.cfg.Proxy
|
||||
}
|
||||
d.configLock.RUnlock()
|
||||
handler := cfg.ToHandler()
|
||||
if handler == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return handler(r)
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
d.webviewProxy = server
|
||||
}
|
||||
if runtime.GOOS == "darwin" || runtime.GOOS == "ios" {
|
||||
return d.webviewProxy.SOCKSURL(), nil
|
||||
}
|
||||
return d.webviewProxy.URL(), nil
|
||||
}
|
||||
|
||||
// A revoked profile is retained until a fresh installation. Existing runtimes
|
||||
// retain this object, so reinstalling cannot let an old runtime recreate data.
|
||||
type extensionWebViewProfile struct {
|
||||
mu sync.Mutex
|
||||
deleteMu sync.Mutex
|
||||
revoked bool
|
||||
pages map[*extensionWebViewPage]struct{}
|
||||
}
|
||||
|
||||
type extensionWebViewPage struct {
|
||||
enginewebview.Page
|
||||
profile *extensionWebViewProfile
|
||||
mu sync.Mutex
|
||||
closed bool
|
||||
}
|
||||
|
||||
func (p *extensionWebViewPage) Close() error {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if p.closed {
|
||||
return nil
|
||||
}
|
||||
if err := p.Page.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
p.closed = true
|
||||
p.profile.mu.Lock()
|
||||
delete(p.profile.pages, p)
|
||||
p.profile.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *Downloader) extensionWebViewProfile(identity string) *extensionWebViewProfile {
|
||||
d.webviewProfilesLock.Lock()
|
||||
defer d.webviewProfilesLock.Unlock()
|
||||
if d.webviewProfiles == nil {
|
||||
d.webviewProfiles = make(map[string]*extensionWebViewProfile)
|
||||
}
|
||||
profile := d.webviewProfiles[identity]
|
||||
if profile == nil {
|
||||
profile = &extensionWebViewProfile{pages: make(map[*extensionWebViewPage]struct{})}
|
||||
d.webviewProfiles[identity] = profile
|
||||
}
|
||||
return profile
|
||||
}
|
||||
|
||||
func (d *Downloader) extensionWebViewLocation(identity string) (string, string, error) {
|
||||
if identity == "" {
|
||||
return "", "", fmt.Errorf("webview extension identity is required")
|
||||
}
|
||||
sum := sha256.Sum256([]byte(identity))
|
||||
id := fmt.Sprintf("%x-%x-%x-%x-%x", sum[:4], sum[4:6], sum[6:8], sum[8:10], sum[10:16])
|
||||
path, err := filepath.Abs(filepath.Join(d.cfg.StorageDir, "webview", fmt.Sprintf("%x", sum[:])))
|
||||
return id, path, err
|
||||
}
|
||||
|
||||
func (d *Downloader) removeExtensionWebViewProfile(identity string) error {
|
||||
profile := d.extensionWebViewProfile(identity)
|
||||
profile.deleteMu.Lock()
|
||||
defer profile.deleteMu.Unlock()
|
||||
profile.mu.Lock()
|
||||
profile.revoked = true
|
||||
pages := make([]*extensionWebViewPage, 0, len(profile.pages))
|
||||
for page := range profile.pages {
|
||||
pages = append(pages, page)
|
||||
}
|
||||
profile.mu.Unlock()
|
||||
for _, page := range pages {
|
||||
if err := page.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
id, path, err := d.extensionWebViewLocation(identity)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if provider := d.cfg.WebViewProvider; provider != nil {
|
||||
remover, ok := provider.(enginewebview.ProfileRemover)
|
||||
if !ok {
|
||||
// An unavailable backend cannot have created a profile this run.
|
||||
// Still fail if a persisted native profile directory exists.
|
||||
_, statErr := os.Stat(path)
|
||||
if provider.IsAvailable() || len(pages) != 0 || !os.IsNotExist(statErr) {
|
||||
return fmt.Errorf("WebView provider does not support profile removal")
|
||||
}
|
||||
} else if err := remover.RemoveProfile(id, path); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return os.RemoveAll(path)
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package download
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/GopeedLab/gopeed/pkg/base"
|
||||
enginewebview "github.com/GopeedLab/gopeed/pkg/download/engine/webview"
|
||||
)
|
||||
|
||||
type profileCaptureProvider struct{ options []enginewebview.OpenOptions }
|
||||
|
||||
func (*profileCaptureProvider) IsAvailable() bool { return true }
|
||||
func (p *profileCaptureProvider) Open(opts enginewebview.OpenOptions) (enginewebview.Page, error) {
|
||||
p.options = append(p.options, opts)
|
||||
return fakeRuntimeWebViewPage{}, nil
|
||||
}
|
||||
|
||||
func TestWebViewProfileBoundToExtension(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
d := &Downloader{cfg: &DownloaderConfig{StorageDir: root, DownloaderStoreConfig: &base.DownloaderStoreConfig{}}, configLock: &sync.RWMutex{}}
|
||||
t.Cleanup(func() {
|
||||
if d.webviewProxy != nil {
|
||||
d.webviewProxy.Close()
|
||||
}
|
||||
})
|
||||
provider := &profileCaptureProvider{}
|
||||
for _, id := range []string{"extension-a", "extension-b", "extension-a", "../../escape"} {
|
||||
opener := &extensionWebViewOpener{downloader: d, provider: provider, identity: id}
|
||||
_, err := opener.Open(enginewebview.OpenOptions{ProfileID: "forged", DataPath: "/tmp/forged", ProxyURL: "http://wrong:80"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
a, b, reopen := provider.options[0], provider.options[1], provider.options[2]
|
||||
if a.ProfileID == b.ProfileID || a.DataPath == b.DataPath {
|
||||
t.Fatal("different extensions shared browser storage")
|
||||
}
|
||||
if a.ProfileID != reopen.ProfileID || a.DataPath != reopen.DataPath {
|
||||
t.Fatal("same extension lost profile identity")
|
||||
}
|
||||
for _, opts := range provider.options {
|
||||
if filepath.Dir(opts.DataPath) != filepath.Join(root, "webview") {
|
||||
t.Fatalf("profile escaped storage root: %s", opts.DataPath)
|
||||
}
|
||||
if opts.ProxyURL != d.webviewProxy.URL() && opts.ProxyURL != d.webviewProxy.SOCKSURL() {
|
||||
t.Fatal("host proxy was overridden")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package download
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/GopeedLab/gopeed/pkg/base"
|
||||
webview "github.com/GopeedLab/gopeed/pkg/download/engine/webview"
|
||||
)
|
||||
|
||||
type removalProvider struct {
|
||||
pages map[string][]*removalPage
|
||||
removed []string
|
||||
failure error
|
||||
entered chan struct{}
|
||||
resume chan struct{}
|
||||
}
|
||||
type removalPage struct {
|
||||
fakeRuntimeWebViewPage
|
||||
closed bool
|
||||
}
|
||||
|
||||
func (p *removalPage) Close() error { p.closed = true; return nil }
|
||||
func (p *removalProvider) IsAvailable() bool { return true }
|
||||
func (p *removalProvider) Open(opts webview.OpenOptions) (webview.Page, error) {
|
||||
if p.entered != nil {
|
||||
close(p.entered)
|
||||
<-p.resume
|
||||
}
|
||||
if p.pages == nil {
|
||||
p.pages = make(map[string][]*removalPage)
|
||||
}
|
||||
page := &removalPage{}
|
||||
p.pages[opts.ProfileID] = append(p.pages[opts.ProfileID], page)
|
||||
return page, nil
|
||||
}
|
||||
func (p *removalProvider) RemoveProfile(id, path string) error {
|
||||
for _, page := range p.pages[id] {
|
||||
if !page.closed {
|
||||
return errors.New("profile removed before closing pages")
|
||||
}
|
||||
}
|
||||
if p.failure != nil {
|
||||
return p.failure
|
||||
}
|
||||
p.removed = append(p.removed, id)
|
||||
return nil
|
||||
}
|
||||
func removalDownloader(t *testing.T, provider *removalProvider) *Downloader {
|
||||
t.Helper()
|
||||
storage := NewMemStorage()
|
||||
if err := storage.Setup([]string{bucketExtension, bucketExtensionStorage}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d := &Downloader{cfg: &DownloaderConfig{StorageDir: t.TempDir(), DownloaderStoreConfig: &base.DownloaderStoreConfig{}, WebViewProvider: provider}, storage: storage, configLock: &sync.RWMutex{}}
|
||||
t.Cleanup(func() {
|
||||
if d.webviewProxy != nil {
|
||||
d.webviewProxy.Close()
|
||||
}
|
||||
})
|
||||
return d
|
||||
}
|
||||
func profileSentinel(t *testing.T, d *Downloader, id string) string {
|
||||
t.Helper()
|
||||
_, path, err := d.extensionWebViewLocation(id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.MkdirAll(path, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sentinel := filepath.Join(path, "cookies.sqlite")
|
||||
if err := os.WriteFile(sentinel, []byte("private browser state"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return sentinel
|
||||
}
|
||||
func TestDeleteExtensionRemovesWebViewData(t *testing.T) {
|
||||
provider := &removalProvider{}
|
||||
d := removalDownloader(t, provider)
|
||||
ext, err := d.InstallExtensionByFolder("testdata/extensions/basic", true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
identity := ext.Identity
|
||||
opener := &extensionWebViewOpener{downloader: d, provider: provider, identity: identity, profile: d.extensionWebViewProfile(identity)}
|
||||
for i := 0; i < 2; i++ {
|
||||
if _, err := opener.Open(webview.OpenOptions{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
sentinel := profileSentinel(t, d, identity)
|
||||
other := profileSentinel(t, d, "other-extension")
|
||||
// Updating the installation keeps both its profile object and stored data.
|
||||
if _, err := d.InstallExtensionByFolder("testdata/extensions/basic", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(sentinel); err != nil {
|
||||
t.Fatal("upgrade removed browser data", err)
|
||||
}
|
||||
if err := d.DeleteExtension(identity); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(sentinel); !os.IsNotExist(err) {
|
||||
t.Fatalf("browser data retained: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(other); err != nil {
|
||||
t.Fatal("other extension data was removed", err)
|
||||
}
|
||||
if _, err := os.Stat(ext.DevPath); err != nil {
|
||||
t.Fatal("dev source was removed", err)
|
||||
}
|
||||
if len(provider.removed) != 1 {
|
||||
t.Fatal("native profile was not removed")
|
||||
}
|
||||
if _, err := opener.Open(webview.OpenOptions{}); err == nil {
|
||||
t.Fatal("old runtime recreated removed profile")
|
||||
}
|
||||
if _, err := d.InstallExtensionByFolder("testdata/extensions/basic", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fresh := &extensionWebViewOpener{downloader: d, provider: provider, identity: identity, profile: d.extensionWebViewProfile(identity)}
|
||||
if _, err := fresh.Open(webview.OpenOptions{}); err != nil {
|
||||
t.Fatal("reinstall could not open profile", err)
|
||||
}
|
||||
if _, err := opener.Open(webview.OpenOptions{}); err == nil {
|
||||
t.Fatal("reinstall reactivated old runtime")
|
||||
}
|
||||
}
|
||||
func TestDeleteExtensionProfileFailureIsRetryable(t *testing.T) {
|
||||
provider := &removalProvider{failure: errors.New("native store busy")}
|
||||
d := removalDownloader(t, provider)
|
||||
ext, err := d.InstallExtensionByFolder("testdata/extensions/basic", true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sentinel := profileSentinel(t, d, ext.Identity)
|
||||
if err := d.DeleteExtension(ext.Identity); err == nil {
|
||||
t.Fatal("cleanup failure was swallowed")
|
||||
}
|
||||
if _, err := d.GetExtension(ext.Identity); err != nil {
|
||||
t.Fatal("extension removed before cleanup completed")
|
||||
}
|
||||
if _, err := os.Stat(sentinel); err != nil {
|
||||
t.Fatal("profile path removed before native cleanup completed")
|
||||
}
|
||||
provider.failure = nil
|
||||
if err := d.DeleteExtension(ext.Identity); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := d.GetExtension(ext.Identity); !errors.Is(err, ErrExtensionNotFound) {
|
||||
t.Fatal("extension was not uninstalled")
|
||||
}
|
||||
}
|
||||
func TestRemoveProfileWaitsForOpeningPage(t *testing.T) {
|
||||
provider := &removalProvider{entered: make(chan struct{}), resume: make(chan struct{})}
|
||||
d := removalDownloader(t, provider)
|
||||
opener := &extensionWebViewOpener{downloader: d, provider: provider, identity: "race", profile: d.extensionWebViewProfile("race")}
|
||||
opened := make(chan error, 1)
|
||||
go func() { _, err := opener.Open(webview.OpenOptions{}); opened <- err }()
|
||||
<-provider.entered
|
||||
removed := make(chan error, 1)
|
||||
go func() { removed <- d.removeExtensionWebViewProfile("race") }()
|
||||
close(provider.resume)
|
||||
if err := <-opened; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := <-removed; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(provider.removed) != 1 {
|
||||
t.Fatal("profile not removed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUninstallWithoutAvailableWebView(t *testing.T) {
|
||||
d := removalDownloader(t, &removalProvider{})
|
||||
d.cfg.WebViewProvider = webview.NewUnavailableProvider()
|
||||
ext, err := d.InstallExtensionByFolder("testdata/extensions/basic", true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := d.DeleteExtension(ext.Identity); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -29,3 +29,7 @@ linter:
|
||||
|
||||
formatter:
|
||||
page_width: 120
|
||||
|
||||
analyzer:
|
||||
exclude:
|
||||
- third_party/**
|
||||
@@ -0,0 +1,66 @@
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
|
||||
|
||||
// Private host/plugin bridge. These settings never originate from extension JS.
|
||||
class WebViewProfileSettings extends InAppWebViewSettings {
|
||||
WebViewProfileSettings({required this.profileId, required bool debug, super.userAgent})
|
||||
: super(javaScriptEnabled: true, transparentBackground: true, isInspectable: debug);
|
||||
|
||||
final String profileId;
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toMap() => {...super.toMap(), 'gopeedProfileId': profileId};
|
||||
}
|
||||
|
||||
class WebViewProfile {
|
||||
WebViewProfile(this.id);
|
||||
|
||||
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});
|
||||
}
|
||||
|
||||
Future<dynamic> _call(String method, Map<String, dynamic> arguments) =>
|
||||
_channel.invokeMethod(method, {...arguments, 'gopeedProfileId': id});
|
||||
|
||||
Future<List<Cookie>> getCookies({required WebUri url}) async {
|
||||
final values = await _call('getCookies', {'url': url.toString()}) as List? ?? [];
|
||||
return values.map((value) => Cookie.fromMap(Map<String, dynamic>.from(value as Map))!).toList();
|
||||
}
|
||||
|
||||
Future<void> setCookie({
|
||||
required WebUri url,
|
||||
required String name,
|
||||
required String value,
|
||||
String? domain,
|
||||
String path = '/',
|
||||
int? expiresDate,
|
||||
bool isSecure = false,
|
||||
bool isHttpOnly = false,
|
||||
}) async {
|
||||
await _call('setCookie', {
|
||||
'url': url.toString(),
|
||||
'name': name,
|
||||
'value': value,
|
||||
'domain': domain,
|
||||
'path': path,
|
||||
'expiresDate': expiresDate?.toString(),
|
||||
'isSecure': isSecure,
|
||||
'isHttpOnly': isHttpOnly,
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> deleteCookie({required WebUri url, required String name, String? domain, String path = '/'}) async {
|
||||
await _call('deleteCookie', {'url': url.toString(), 'name': name, 'domain': domain, 'path': path});
|
||||
}
|
||||
|
||||
Future<void> deleteAllCookies() async {
|
||||
await _call('deleteAllCookies', {});
|
||||
}
|
||||
}
|
||||
@@ -3,12 +3,14 @@ import 'dart:collection';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
|
||||
|
||||
import '../../core/common/start_config.dart';
|
||||
import '../../util/log_util.dart';
|
||||
import '../../util/util.dart';
|
||||
import 'server.dart';
|
||||
import 'webview_profile.dart';
|
||||
|
||||
String buildWebViewExecuteScript({
|
||||
required String channelName,
|
||||
@@ -73,7 +75,6 @@ class WebViewRpcService {
|
||||
|
||||
final Map<String, WebViewRpcPageSession> _pagesById = {};
|
||||
final Completer<void> _overlayReady = Completer<void>();
|
||||
late final CookieManager _cookieManager = CookieManager.instance();
|
||||
|
||||
RpcServerHandle? _server;
|
||||
int _pageSeq = 0;
|
||||
@@ -129,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':
|
||||
@@ -162,10 +166,12 @@ class WebViewRpcService {
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> _openPage(Map<String, dynamic> params) async {
|
||||
final profile = WebViewProfile(_string(params, 'profileId'));
|
||||
await profile.prepare(_string(params, 'proxyUrl'));
|
||||
final pageId = 'page-${++_pageSeq}';
|
||||
final session = WebViewRpcPageSession(
|
||||
pageId: pageId,
|
||||
cookieManager: _cookieManager,
|
||||
cookieManager: profile,
|
||||
headless: params['headless'] as bool? ?? false,
|
||||
debug: params['debug'] as bool? ?? false,
|
||||
title: params['title'] as String? ?? '',
|
||||
@@ -185,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) {
|
||||
@@ -271,6 +286,9 @@ class WebViewRpcService {
|
||||
if (error is WebViewRpcException) {
|
||||
return {'code': error.code, 'message': error.message};
|
||||
}
|
||||
if (error is PlatformException && error.code == 'UNAVAILABLE') {
|
||||
return {'code': error.code, 'message': error.message ?? 'WebView is unavailable'};
|
||||
}
|
||||
final code = switch (method) {
|
||||
'page.goto' => 'NAVIGATION_FAILED',
|
||||
'page.execute' => 'EVALUATION_FAILED',
|
||||
@@ -293,7 +311,7 @@ class WebViewRpcPageSession {
|
||||
});
|
||||
|
||||
final String pageId;
|
||||
final CookieManager cookieManager;
|
||||
final WebViewProfile cookieManager;
|
||||
final bool headless;
|
||||
final bool debug;
|
||||
final String title;
|
||||
@@ -449,6 +467,8 @@ class WebViewRpcPageSession {
|
||||
'path': cookie.path ?? '/',
|
||||
'secure': cookie.isSecure,
|
||||
'httpOnly': cookie.isHttpOnly,
|
||||
if (cookie.expiresDate != null)
|
||||
'expires': DateTime.fromMillisecondsSinceEpoch(cookie.expiresDate!, isUtc: true).toIso8601String(),
|
||||
};
|
||||
})
|
||||
.toList(growable: false);
|
||||
@@ -523,10 +543,9 @@ class WebViewRpcPageSession {
|
||||
);
|
||||
}
|
||||
|
||||
InAppWebViewSettings get _settings => InAppWebViewSettings(
|
||||
javaScriptEnabled: true,
|
||||
transparentBackground: true,
|
||||
isInspectable: debug,
|
||||
InAppWebViewSettings get _settings => WebViewProfileSettings(
|
||||
profileId: cookieManager.id,
|
||||
debug: debug,
|
||||
userAgent: userAgent.isNotEmpty ? userAgent : null,
|
||||
);
|
||||
|
||||
|
||||
@@ -2,6 +2,11 @@
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>NSAppTransportSecurity</key>
|
||||
<dict>
|
||||
<key>NSAllowsArbitraryLoadsInWebContent</key>
|
||||
<true/>
|
||||
</dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
|
||||
+12
-15
@@ -463,12 +463,11 @@ packages:
|
||||
source: hosted
|
||||
version: "6.1.5"
|
||||
flutter_inappwebview_android:
|
||||
dependency: transitive
|
||||
dependency: "direct overridden"
|
||||
description:
|
||||
name: flutter_inappwebview_android
|
||||
sha256: "62557c15a5c2db5d195cb3892aab74fcaec266d7b86d59a6f0027abd672cddba"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
path: "third_party/flutter_inappwebview_android"
|
||||
relative: true
|
||||
source: path
|
||||
version: "1.1.3"
|
||||
flutter_inappwebview_internal_annotations:
|
||||
dependency: transitive
|
||||
@@ -479,20 +478,18 @@ packages:
|
||||
source: hosted
|
||||
version: "1.3.0"
|
||||
flutter_inappwebview_ios:
|
||||
dependency: transitive
|
||||
dependency: "direct overridden"
|
||||
description:
|
||||
name: flutter_inappwebview_ios
|
||||
sha256: "5818cf9b26cf0cbb0f62ff50772217d41ea8d3d9cc00279c45f8aabaa1b4025d"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
path: "third_party/flutter_inappwebview_ios"
|
||||
relative: true
|
||||
source: path
|
||||
version: "1.1.2"
|
||||
flutter_inappwebview_macos:
|
||||
dependency: transitive
|
||||
dependency: "direct overridden"
|
||||
description:
|
||||
name: flutter_inappwebview_macos
|
||||
sha256: c1fbb86af1a3738e3541364d7d1866315ffb0468a1a77e34198c9be571287da1
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
path: "third_party/flutter_inappwebview_macos"
|
||||
relative: true
|
||||
source: path
|
||||
version: "1.1.2"
|
||||
flutter_inappwebview_platform_interface:
|
||||
dependency: transitive
|
||||
|
||||
@@ -86,6 +86,13 @@ dependencies:
|
||||
go_router: ^16.2.1
|
||||
|
||||
dependency_overrides:
|
||||
# Host-only native WebView profile/proxy bridge.
|
||||
flutter_inappwebview_macos:
|
||||
path: third_party/flutter_inappwebview_macos
|
||||
flutter_inappwebview_ios:
|
||||
path: third_party/flutter_inappwebview_ios
|
||||
flutter_inappwebview_android:
|
||||
path: third_party/flutter_inappwebview_android
|
||||
# Prevent a native Windows crash when the push notification service is unavailable.
|
||||
# Keep this fork until https://github.com/MaikuB/flutter_local_notifications/pull/2813 is merged and released.
|
||||
flutter_local_notifications:
|
||||
|
||||
Vendored
+38
@@ -0,0 +1,38 @@
|
||||
# Native WebView host bridge
|
||||
|
||||
Vendored unmodified Dart facades and native sources from pub.dev:
|
||||
|
||||
- flutter_inappwebview_macos 1.1.2
|
||||
- flutter_inappwebview_ios 1.1.2
|
||||
- flutter_inappwebview_android 1.1.3
|
||||
|
||||
Each package retains its upstream license. Versions and original archive hashes
|
||||
are available in the parent commit's pubspec.lock.
|
||||
|
||||
Local native changes are limited to:
|
||||
|
||||
- `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`
|
||||
setting and attach the profile before navigation.
|
||||
- `MyCookieManager`: route cookie operations to the requested profile, capturing
|
||||
the store per operation so asynchronous calls cannot cross profiles.
|
||||
- macOS `InAppWebView`: resign input focus before disposing a view so AppKit
|
||||
cannot retain its profile through the responder chain after closing the page.
|
||||
|
||||
`lib/app/rpc/webview_profile.dart` uses the existing plugin method channel and
|
||||
serializes these internal settings. No extension JavaScript API is added.
|
||||
|
||||
Apple requires macOS 14 / iOS 17 for named persistent stores and proxy settings.
|
||||
Android requires `MULTI_PROFILE` and `PROXY_OVERRIDE`; unsupported runtimes return
|
||||
an explicit unavailable error rather than opening a shared, unproxied browser.
|
||||
|
||||
When updating upstream, refresh these three packages, reapply the above changes,
|
||||
and run the shared Go provider integration tests against the normal Flutter app
|
||||
on a native Apple host (see `internal/webview/rpcprovider/README.md`). 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.
|
||||
@@ -0,0 +1,103 @@
|
||||
## 1.1.3
|
||||
|
||||
- Updated flutter_inappwebview_platform_interface version to ^1.3.0
|
||||
|
||||
## 1.1.2
|
||||
|
||||
- Removed webview/plugin_scripts_js/ConsoleLogJS.java file, use native WebChromeClient.onConsoleMessage instead
|
||||
|
||||
## 1.1.1
|
||||
|
||||
- Updated flutter_inappwebview_platform_interface version to ^1.2.0
|
||||
|
||||
## 1.1.0+4
|
||||
|
||||
- Updated flutter_inappwebview_platform_interface version
|
||||
|
||||
## 1.1.0+3
|
||||
|
||||
- Fixed compilation error
|
||||
|
||||
## 1.1.0+2
|
||||
|
||||
- Updated pubspec.yaml
|
||||
|
||||
## 1.1.0+1
|
||||
|
||||
- Downgraded androidx.appcompat:appcompat:1.7.0 to androidx.appcompat:appcompat:1.6.1
|
||||
- Added `-dontwarn android.window.BackEvent` proguard rule
|
||||
|
||||
## 1.1.0
|
||||
|
||||
- Updated androidx.webkit:webkit:1.8.0 to androidx.webkit:webkit:1.12.0
|
||||
- Updated androidx.browser:browser:1.6.0 to androidx.browser:browser:1.8.0
|
||||
- Updates minimum supported SDK version to Flutter 3.24/Dart 3.5.
|
||||
- Removed unsupported WebViewFeature.SUPPRESS_ERROR_PAGE
|
||||
- Merged "Remove references to deprecated v1 Android embedding" [#2176](https://github.com/pichillilorenzo/flutter_inappwebview/pull/2176) (thanks to [gmackall](https://github.com/gmackall))
|
||||
|
||||
## 1.0.13
|
||||
|
||||
- Fixed "Android emulator using API 34 fails to draw on resume sometimes" [#1981](https://github.com/pichillilorenzo/flutter_inappwebview/issues/1981)
|
||||
|
||||
## 1.0.12
|
||||
|
||||
- Updated `flutter_inappwebview_platform_interface` version dependency to `^1.0.10`
|
||||
|
||||
## 1.0.11
|
||||
|
||||
- Updated `flutter_inappwebview_platform_interface` version dependency to `^1.0.9`
|
||||
- Fix typos (thanks to [michalsrutek](https://github.com/michalsrutek))
|
||||
|
||||
## 1.0.10
|
||||
|
||||
- Updated `flutter_inappwebview_platform_interface` version dependency to `^1.0.8`
|
||||
- Implemented `PlatformCustomPathHandler` class
|
||||
|
||||
## 1.0.9
|
||||
|
||||
- Updated `flutter_inappwebview_platform_interface` version dependency to `^1.0.7`
|
||||
- Fixed "Cloudflare Turnstile failure" [#1738](https://github.com/pichillilorenzo/flutter_inappwebview/issues/1738)
|
||||
- Fixed `InAppWebViewController.callAsyncJavaScript` issue when the last line of the `functionBody` parameter includes a code comment
|
||||
|
||||
## 1.0.8
|
||||
|
||||
- Implemented `InAppWebViewSettings.interceptOnlyAsyncAjaxRequests`
|
||||
- Implemented `PlatformInAppWebViewController.clearFormData` method
|
||||
- Implemented `PlatformCookieManager.removeSessionCookies` method
|
||||
- Updated `useShouldInterceptAjaxRequest` automatic infer logic
|
||||
- Updated `CookieManager` methods return value
|
||||
|
||||
## 1.0.7
|
||||
|
||||
- Merged "Fixed error in InterceptAjaxRequestJS 'Failed to set responseType property'" [#1904](https://github.com/pichillilorenzo/flutter_inappwebview/pull/1904) (thanks to [EArminjon](https://github.com/EArminjon))
|
||||
- Fixed shouldInterceptAjaxRequest javascript code when overriding XMLHttpRequest.open method parameters
|
||||
|
||||
## 1.0.6
|
||||
|
||||
- Fixed "getFavicons: _TypeError: type '_Map<String, dynamic>' is not a subtype of type 'Iterable<dynamic>'" [#1897](https://github.com/pichillilorenzo/flutter_inappwebview/issues/1897)
|
||||
- Fixed "onClosed not considering back navigation or up button / close button in ChromeSafariBrowser when using noHistory: true" [#1882](https://github.com/pichillilorenzo/flutter_inappwebview/issues/1882)
|
||||
|
||||
## 1.0.5
|
||||
|
||||
- Call `super.dispose();` on `InAppBrowser` and `ChromeSafari` implementations
|
||||
|
||||
## 1.0.4
|
||||
|
||||
- Throw platform exception when ProcessGlobalConfig.apply throws an error on the native side to be able to catch it on Flutter side
|
||||
|
||||
## 1.0.3
|
||||
|
||||
- Updated `ContentBlockerHandler` CSS_DISPLAY_NONE action type and `JavaScriptBridgeJS.JAVASCRIPT_BRIDGE_JS_SOURCE` javascript implementation code
|
||||
|
||||
## 1.0.2
|
||||
|
||||
- Updated `flutter_inappwebview_platform_interface` version dependency to `1.0.2`
|
||||
- Fixed "Crash when starting ChromeSafariBrowser on Android java.lang.NoSuchMethodError: No virtual method isEngagementSignalsApiAvailable" [#1881](https://github.com/pichillilorenzo/flutter_inappwebview/issues/1881)
|
||||
|
||||
## 1.0.1
|
||||
|
||||
- Updated README
|
||||
|
||||
## 1.0.0
|
||||
|
||||
Initial release.
|
||||
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2023 Lorenzo Pichilli
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,13 @@
|
||||
# flutter\_inappwebview\_android
|
||||
|
||||
The Android WebView implementation of [`flutter_inappwebview`](https://pub.dev/packages/flutter_inappwebview).
|
||||
|
||||
## Usage
|
||||
|
||||
This package is [endorsed](https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin),
|
||||
which means you can simply use `flutter_inappwebview`
|
||||
normally. This package will be automatically included in your app when you do,
|
||||
so you do not need to add it to your `pubspec.yaml`.
|
||||
|
||||
However, if you `import` this package to use any of its APIs directly, you
|
||||
should add it to your `pubspec.yaml` as usual.
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
group 'com.pichillilorenzo.flutter_inappwebview_android'
|
||||
version '1.0-SNAPSHOT'
|
||||
|
||||
buildscript {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
classpath 'com.android.tools.build:gradle:8.0.1'
|
||||
}
|
||||
}
|
||||
|
||||
rootProject.allprojects {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
}
|
||||
|
||||
apply plugin: 'com.android.library'
|
||||
|
||||
android {
|
||||
// Conditional for compatibility with AGP <4.2.
|
||||
if (project.android.hasProperty("namespace")) {
|
||||
namespace 'com.pichillilorenzo.flutter_inappwebview_android'
|
||||
}
|
||||
compileSdk 34
|
||||
|
||||
defaultConfig {
|
||||
minSdkVersion 21
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
|
||||
vectorDrawables.useSupportLibrary = true
|
||||
consumerProguardFiles 'proguard-rules.pro'
|
||||
}
|
||||
lintOptions {
|
||||
disable 'InvalidPackage'
|
||||
}
|
||||
buildTypes {
|
||||
debug {
|
||||
minifyEnabled false
|
||||
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
|
||||
}
|
||||
release {
|
||||
minifyEnabled true
|
||||
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
|
||||
}
|
||||
}
|
||||
dependencies {
|
||||
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'
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
org.gradle.jvmargs=-Xmx1536M
|
||||
android.useAndroidX=true
|
||||
android.enableJetifier=true
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
# WebView
|
||||
-keepattributes *JavascriptInterface*
|
||||
-keepclassmembers class * {
|
||||
@android.webkit.JavascriptInterface <methods>;
|
||||
}
|
||||
-keepclassmembers class * extends android.webkit.WebViewClient {
|
||||
public void *(android.webkit.WebView, java.lang.String, android.graphics.Bitmap);
|
||||
public boolean *(android.webkit.WebView, java.lang.String);
|
||||
public void *(android.webkit.webView, jav.lang.String);
|
||||
}
|
||||
-keepclassmembers class com.pichillilorenzo.flutter_inappwebview_android$JavaScriptBridgeInterface {
|
||||
<fields>;
|
||||
<methods>;
|
||||
public *;
|
||||
private *;
|
||||
}
|
||||
-keep class com.pichillilorenzo.flutter_inappwebview_android.** { *; }
|
||||
|
||||
-dontwarn android.window.BackEvent
|
||||
+1
@@ -0,0 +1 @@
|
||||
rootProject.name = 'flutter_inappwebview_android'
|
||||
Vendored
Executable
+43
@@ -0,0 +1,43 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="com.pichillilorenzo.flutter_inappwebview_android">
|
||||
<application>
|
||||
<activity
|
||||
android:theme="@style/AppTheme"
|
||||
android:exported="false"
|
||||
android:name="com.pichillilorenzo.flutter_inappwebview_android.in_app_browser.InAppBrowserActivity"
|
||||
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density" />
|
||||
<activity
|
||||
android:theme="@style/ThemeTransparent"
|
||||
android:exported="false"
|
||||
android:name="com.pichillilorenzo.flutter_inappwebview_android.chrome_custom_tabs.ChromeCustomTabsActivity" />
|
||||
<activity
|
||||
android:theme="@style/ThemeTransparent"
|
||||
android:exported="false"
|
||||
android:name="com.pichillilorenzo.flutter_inappwebview_android.chrome_custom_tabs.TrustedWebActivity" />
|
||||
<activity
|
||||
android:theme="@style/ThemeTransparent"
|
||||
android:exported="false"
|
||||
android:name="com.pichillilorenzo.flutter_inappwebview_android.chrome_custom_tabs.ChromeCustomTabsActivitySingleInstance"
|
||||
android:launchMode="singleInstance"/>
|
||||
<activity
|
||||
android:theme="@style/ThemeTransparent"
|
||||
android:exported="false"
|
||||
android:name="com.pichillilorenzo.flutter_inappwebview_android.chrome_custom_tabs.TrustedWebActivitySingleInstance"
|
||||
android:launchMode="singleInstance"/>
|
||||
<receiver
|
||||
android:name="com.pichillilorenzo.flutter_inappwebview_android.chrome_custom_tabs.ActionBroadcastReceiver"
|
||||
android:enabled="true"
|
||||
android:exported="false" />
|
||||
<meta-data
|
||||
android:name="io.flutter.embedded_views_preview"
|
||||
android:value="true" />
|
||||
</application>
|
||||
|
||||
<queries>
|
||||
<intent>
|
||||
<action android:name=
|
||||
"android.support.customtabs.action.CustomTabsService" />
|
||||
</intent>
|
||||
</queries>
|
||||
</manifest>
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
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;
|
||||
import androidx.webkit.WebViewFeature;
|
||||
import io.flutter.plugin.common.MethodCall;
|
||||
import io.flutter.plugin.common.MethodChannel;
|
||||
|
||||
// Internal host bridge: profile creation and proxy completion precede navigation.
|
||||
public final class GopeedProfiles {
|
||||
private static final java.util.Map<android.webkit.WebView, String> views = new java.util.IdentityHashMap<>();
|
||||
|
||||
public static void viewCreated(android.webkit.WebView view, String id) { views.put(view, id); }
|
||||
public static void viewDestroyed(android.webkit.WebView view) { views.remove(view); }
|
||||
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) {
|
||||
waitForViews(call, result, 100);
|
||||
}
|
||||
|
||||
private static void waitForViews(MethodCall call, MethodChannel.Result result, int attempts) {
|
||||
String id = call.argument("gopeedProfileId");
|
||||
if (views.containsValue(id)) {
|
||||
if (attempts <= 0) {
|
||||
result.error("PROFILE_REMOVE_FAILED", "WebView pages have not finished closing", null);
|
||||
return;
|
||||
}
|
||||
// The plugin destroys WebViews asynchronously after about:blank loads.
|
||||
// Wait for actual native destruction, not just Dart widget disposal.
|
||||
new android.os.Handler(android.os.Looper.getMainLooper()).postDelayed(
|
||||
() -> waitForViews(call, result, attempts - 1), 100);
|
||||
return;
|
||||
}
|
||||
removeData(call, result);
|
||||
}
|
||||
|
||||
private static void removeData(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<>();
|
||||
static void prepare(MethodCall call, MethodChannel.Result result) {
|
||||
if (!WebViewFeature.isFeatureSupported(WebViewFeature.MULTI_PROFILE) ||
|
||||
!WebViewFeature.isFeatureSupported(WebViewFeature.PROXY_OVERRIDE)) {
|
||||
result.error("UNAVAILABLE", "Android WebView does not support isolated profiles and proxy override", null);
|
||||
return;
|
||||
}
|
||||
String id = call.argument("gopeedProfileId");
|
||||
String proxy = call.argument("proxyUrl");
|
||||
try {
|
||||
java.util.UUID.fromString(id);
|
||||
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) {
|
||||
if (proxy.equals(pendingProxy)) pending.add(result);
|
||||
else result.error("UNAVAILABLE", "A different WebView proxy is being configured", null);
|
||||
return;
|
||||
}
|
||||
pendingProxy = proxy;
|
||||
pending.add(result);
|
||||
ProxyConfig config = new ProxyConfig.Builder().addProxyRule(proxy).removeImplicitRules().build();
|
||||
ProxyController.getInstance().setProxyOverride(config, task -> new android.os.Handler(android.os.Looper.getMainLooper()).post(task), () -> {
|
||||
appliedProxy = proxy;
|
||||
pendingProxy = null;
|
||||
java.util.List<MethodChannel.Result> completed = new java.util.ArrayList<>(pending);
|
||||
pending.clear();
|
||||
for (MethodChannel.Result callback : completed) callback.success(true);
|
||||
});
|
||||
} catch (RuntimeException e) {
|
||||
if (pendingProxy != null && pending.contains(result)) {
|
||||
pendingProxy = null;
|
||||
java.util.List<MethodChannel.Result> failed = new java.util.ArrayList<>(pending);
|
||||
pending.clear();
|
||||
for (MethodChannel.Result callback : failed) callback.error("UNAVAILABLE", "Unable to configure WebView profile and proxy", null);
|
||||
} else result.error("UNAVAILABLE", "Unable to configure WebView profile and proxy", null);
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
Executable
+11
@@ -0,0 +1,11 @@
|
||||
package com.pichillilorenzo.flutter_inappwebview_android;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public interface ISettings<T> {
|
||||
@NonNull ISettings<T> parse(@NonNull Map<String, Object> settings);
|
||||
@NonNull Map<String, Object> toMap();
|
||||
@NonNull Map<String, Object> getRealSettings(@NonNull T obj);
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.pichillilorenzo.flutter_inappwebview_android;
|
||||
|
||||
import androidx.core.content.FileProvider;
|
||||
|
||||
public class InAppWebViewFileProvider extends FileProvider {
|
||||
|
||||
public static final String fileProviderAuthorityExtension = "flutter_inappwebview_android.fileprovider";
|
||||
|
||||
}
|
||||
Vendored
Executable
+225
@@ -0,0 +1,225 @@
|
||||
package com.pichillilorenzo.flutter_inappwebview_android;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.Context;
|
||||
import android.os.Build;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.pichillilorenzo.flutter_inappwebview_android.chrome_custom_tabs.ChromeSafariBrowserManager;
|
||||
import com.pichillilorenzo.flutter_inappwebview_android.chrome_custom_tabs.NoHistoryCustomTabsActivityCallbacks;
|
||||
import com.pichillilorenzo.flutter_inappwebview_android.credential_database.CredentialDatabaseHandler;
|
||||
import com.pichillilorenzo.flutter_inappwebview_android.headless_in_app_webview.HeadlessInAppWebViewManager;
|
||||
import com.pichillilorenzo.flutter_inappwebview_android.in_app_browser.InAppBrowserManager;
|
||||
import com.pichillilorenzo.flutter_inappwebview_android.print_job.PrintJobManager;
|
||||
import com.pichillilorenzo.flutter_inappwebview_android.process_global_config.ProcessGlobalConfigManager;
|
||||
import com.pichillilorenzo.flutter_inappwebview_android.proxy.ProxyManager;
|
||||
import com.pichillilorenzo.flutter_inappwebview_android.service_worker.ServiceWorkerManager;
|
||||
import com.pichillilorenzo.flutter_inappwebview_android.tracing.TracingControllerManager;
|
||||
import com.pichillilorenzo.flutter_inappwebview_android.webview.FlutterWebViewFactory;
|
||||
import com.pichillilorenzo.flutter_inappwebview_android.webview.InAppWebViewManager;
|
||||
|
||||
import io.flutter.embedding.engine.plugins.FlutterPlugin;
|
||||
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
|
||||
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
|
||||
import io.flutter.plugin.common.BinaryMessenger;
|
||||
import io.flutter.plugin.platform.PlatformViewRegistry;
|
||||
import io.flutter.embedding.android.FlutterView;
|
||||
|
||||
public class InAppWebViewFlutterPlugin implements FlutterPlugin, ActivityAware {
|
||||
|
||||
protected static final String LOG_TAG = "InAppWebViewFlutterPL";
|
||||
|
||||
@Nullable
|
||||
public PlatformUtil platformUtil;
|
||||
@Nullable
|
||||
public InAppBrowserManager inAppBrowserManager;
|
||||
@Nullable
|
||||
public HeadlessInAppWebViewManager headlessInAppWebViewManager;
|
||||
@Nullable
|
||||
public ChromeSafariBrowserManager chromeSafariBrowserManager;
|
||||
@Nullable
|
||||
public NoHistoryCustomTabsActivityCallbacks noHistoryCustomTabsActivityCallbacks;
|
||||
@Nullable
|
||||
public InAppWebViewManager inAppWebViewManager;
|
||||
@Nullable
|
||||
public MyCookieManager myCookieManager;
|
||||
@Nullable
|
||||
public CredentialDatabaseHandler credentialDatabaseHandler;
|
||||
@Nullable
|
||||
public MyWebStorage myWebStorage;
|
||||
@Nullable
|
||||
public ServiceWorkerManager serviceWorkerManager;
|
||||
@Nullable
|
||||
public WebViewFeatureManager webViewFeatureManager;
|
||||
@Nullable
|
||||
public ProxyManager proxyManager;
|
||||
@Nullable
|
||||
public PrintJobManager printJobManager;
|
||||
@Nullable
|
||||
public TracingControllerManager tracingControllerManager;
|
||||
@Nullable
|
||||
public ProcessGlobalConfigManager processGlobalConfigManager;
|
||||
public FlutterWebViewFactory flutterWebViewFactory;
|
||||
public Context applicationContext;
|
||||
public BinaryMessenger messenger;
|
||||
public FlutterPlugin.FlutterAssets flutterAssets;
|
||||
@Nullable
|
||||
public ActivityPluginBinding activityPluginBinding;
|
||||
@Nullable
|
||||
public Activity activity;
|
||||
public FlutterView flutterView;
|
||||
|
||||
public InAppWebViewFlutterPlugin() {}
|
||||
|
||||
@Override
|
||||
public void onAttachedToEngine(FlutterPluginBinding binding) {
|
||||
this.flutterAssets = binding.getFlutterAssets();
|
||||
|
||||
// Shared.activity could be null or not.
|
||||
// It depends on who is called first between onAttachedToEngine event and onAttachedToActivity event.
|
||||
//
|
||||
// See https://github.com/pichillilorenzo/flutter_inappwebview/issues/390#issuecomment-647039084
|
||||
onAttachedToEngine(
|
||||
binding.getApplicationContext(), binding.getBinaryMessenger(), this.activity, binding.getPlatformViewRegistry(), null);
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
inAppBrowserManager = new InAppBrowserManager(this);
|
||||
headlessInAppWebViewManager = new HeadlessInAppWebViewManager(this);
|
||||
chromeSafariBrowserManager = new ChromeSafariBrowserManager(this);
|
||||
noHistoryCustomTabsActivityCallbacks = new NoHistoryCustomTabsActivityCallbacks(this);
|
||||
flutterWebViewFactory = new FlutterWebViewFactory(this);
|
||||
platformViewRegistry.registerViewFactory(
|
||||
FlutterWebViewFactory.VIEW_TYPE_ID, flutterWebViewFactory);
|
||||
|
||||
platformUtil = new PlatformUtil(this);
|
||||
inAppWebViewManager = new InAppWebViewManager(this);
|
||||
myCookieManager = new MyCookieManager(this);
|
||||
myWebStorage = new MyWebStorage(this);
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
|
||||
serviceWorkerManager = new ServiceWorkerManager(this);
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
credentialDatabaseHandler = new CredentialDatabaseHandler(this);
|
||||
}
|
||||
webViewFeatureManager = new WebViewFeatureManager(this);
|
||||
proxyManager = new ProxyManager(this);
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
|
||||
printJobManager = new PrintJobManager(this);
|
||||
}
|
||||
tracingControllerManager = new TracingControllerManager(this);
|
||||
processGlobalConfigManager = new ProcessGlobalConfigManager(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
|
||||
if (platformUtil != null) {
|
||||
platformUtil.dispose();
|
||||
platformUtil = null;
|
||||
}
|
||||
if (inAppBrowserManager != null) {
|
||||
inAppBrowserManager.dispose();
|
||||
inAppBrowserManager = null;
|
||||
}
|
||||
if (headlessInAppWebViewManager != null) {
|
||||
headlessInAppWebViewManager.dispose();
|
||||
headlessInAppWebViewManager = null;
|
||||
}
|
||||
if (chromeSafariBrowserManager != null) {
|
||||
chromeSafariBrowserManager.dispose();
|
||||
chromeSafariBrowserManager = null;
|
||||
}
|
||||
if (noHistoryCustomTabsActivityCallbacks != null) {
|
||||
noHistoryCustomTabsActivityCallbacks.dispose();
|
||||
noHistoryCustomTabsActivityCallbacks = null;
|
||||
}
|
||||
if (myCookieManager != null) {
|
||||
myCookieManager.dispose();
|
||||
myCookieManager = null;
|
||||
}
|
||||
if (myWebStorage != null) {
|
||||
myWebStorage.dispose();
|
||||
myWebStorage = null;
|
||||
}
|
||||
if (credentialDatabaseHandler != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
credentialDatabaseHandler.dispose();
|
||||
credentialDatabaseHandler = null;
|
||||
}
|
||||
if (inAppWebViewManager != null) {
|
||||
inAppWebViewManager.dispose();
|
||||
inAppWebViewManager = null;
|
||||
}
|
||||
if (serviceWorkerManager != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
|
||||
serviceWorkerManager.dispose();
|
||||
serviceWorkerManager = null;
|
||||
}
|
||||
if (webViewFeatureManager != null) {
|
||||
webViewFeatureManager.dispose();
|
||||
webViewFeatureManager = null;
|
||||
}
|
||||
if (proxyManager != null) {
|
||||
proxyManager.dispose();
|
||||
proxyManager = null;
|
||||
}
|
||||
if (printJobManager != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
|
||||
printJobManager.dispose();
|
||||
printJobManager = null;
|
||||
}
|
||||
if (tracingControllerManager != null) {
|
||||
tracingControllerManager.dispose();
|
||||
tracingControllerManager = null;
|
||||
}
|
||||
if (processGlobalConfigManager != null) {
|
||||
processGlobalConfigManager.dispose();
|
||||
processGlobalConfigManager = null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAttachedToActivity(ActivityPluginBinding activityPluginBinding) {
|
||||
this.activityPluginBinding = activityPluginBinding;
|
||||
this.activity = activityPluginBinding.getActivity();
|
||||
|
||||
if (noHistoryCustomTabsActivityCallbacks != null) {
|
||||
this.activity.getApplication().registerActivityLifecycleCallbacks(noHistoryCustomTabsActivityCallbacks.activityLifecycleCallbacks);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDetachedFromActivityForConfigChanges() {
|
||||
if (activity != null && noHistoryCustomTabsActivityCallbacks != null) {
|
||||
this.activity.getApplication().unregisterActivityLifecycleCallbacks(noHistoryCustomTabsActivityCallbacks.activityLifecycleCallbacks);
|
||||
}
|
||||
|
||||
activityPluginBinding = null;
|
||||
activity = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onReattachedToActivityForConfigChanges(ActivityPluginBinding activityPluginBinding) {
|
||||
this.activityPluginBinding = activityPluginBinding;
|
||||
this.activity = activityPluginBinding.getActivity();
|
||||
|
||||
if (noHistoryCustomTabsActivityCallbacks != null) {
|
||||
this.activity.getApplication().registerActivityLifecycleCallbacks(noHistoryCustomTabsActivityCallbacks.activityLifecycleCallbacks);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDetachedFromActivity() {
|
||||
if (activity != null && noHistoryCustomTabsActivityCallbacks != null) {
|
||||
this.activity.getApplication().unregisterActivityLifecycleCallbacks(noHistoryCustomTabsActivityCallbacks.activityLifecycleCallbacks);
|
||||
}
|
||||
|
||||
activityPluginBinding = null;
|
||||
activity = null;
|
||||
}
|
||||
}
|
||||
Vendored
Executable
+456
@@ -0,0 +1,456 @@
|
||||
package com.pichillilorenzo.flutter_inappwebview_android;
|
||||
|
||||
import android.os.Build;
|
||||
import android.util.Log;
|
||||
import android.webkit.CookieManager;
|
||||
import android.webkit.CookieSyncManager;
|
||||
import android.webkit.ValueCallback;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.webkit.CookieManagerCompat;
|
||||
import androidx.webkit.WebViewFeature;
|
||||
|
||||
import com.pichillilorenzo.flutter_inappwebview_android.types.ChannelDelegateImpl;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import io.flutter.plugin.common.MethodCall;
|
||||
import io.flutter.plugin.common.MethodChannel;
|
||||
|
||||
public class MyCookieManager extends ChannelDelegateImpl {
|
||||
protected static final String LOG_TAG = "MyCookieManager";
|
||||
public static final String METHOD_CHANNEL_NAME = "com.pichillilorenzo/flutter_inappwebview_cookiemanager";
|
||||
@Nullable
|
||||
public static CookieManager cookieManager;
|
||||
private CookieManager selectedCookieManager;
|
||||
@Nullable
|
||||
public InAppWebViewFlutterPlugin plugin;
|
||||
|
||||
public MyCookieManager(@NonNull final InAppWebViewFlutterPlugin plugin) {
|
||||
super(new MethodChannel(plugin.messenger, METHOD_CHANNEL_NAME));
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
public static void init() {
|
||||
if (cookieManager == null) {
|
||||
cookieManager = getCookieManager();
|
||||
}
|
||||
}
|
||||
|
||||
@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;
|
||||
}
|
||||
String profileID = call.argument("gopeedProfileId");
|
||||
if (profileID != null && !profileID.isEmpty()) {
|
||||
if (!androidx.webkit.WebViewFeature.isFeatureSupported(androidx.webkit.WebViewFeature.MULTI_PROFILE) ||
|
||||
androidx.webkit.ProfileStore.getInstance().getProfile(profileID) == null) {
|
||||
result.error("UNAVAILABLE", "WebView profile is not initialized", null);
|
||||
return;
|
||||
}
|
||||
selectedCookieManager = androidx.webkit.ProfileStore.getInstance().getProfile(profileID).getCookieManager();
|
||||
}
|
||||
init();
|
||||
try {
|
||||
switch (call.method) {
|
||||
case "setCookie":
|
||||
{
|
||||
String url = (String) call.argument("url");
|
||||
String name = (String) call.argument("name");
|
||||
String value = (String) call.argument("value");
|
||||
String domain = (String) call.argument("domain");
|
||||
String path = (String) call.argument("path");
|
||||
String expiresDateString = (String) call.argument("expiresDate");
|
||||
Long expiresDate = (expiresDateString != null ? new Long(expiresDateString) : null);
|
||||
Integer maxAge = (Integer) call.argument("maxAge");
|
||||
Boolean isSecure = (Boolean) call.argument("isSecure");
|
||||
Boolean isHttpOnly = (Boolean) call.argument("isHttpOnly");
|
||||
String sameSite = (String) call.argument("sameSite");
|
||||
setCookie(url,
|
||||
name,
|
||||
value,
|
||||
domain,
|
||||
path,
|
||||
expiresDate,
|
||||
maxAge,
|
||||
isSecure,
|
||||
isHttpOnly,
|
||||
sameSite,
|
||||
result);
|
||||
}
|
||||
break;
|
||||
case "getCookies":
|
||||
result.success(getCookies((String) call.argument("url")));
|
||||
break;
|
||||
case "deleteCookie":
|
||||
{
|
||||
String url = (String) call.argument("url");
|
||||
String name = (String) call.argument("name");
|
||||
String domain = (String) call.argument("domain");
|
||||
String path = (String) call.argument("path");
|
||||
deleteCookie(url, name, domain, path, result);
|
||||
}
|
||||
break;
|
||||
case "deleteCookies":
|
||||
{
|
||||
String url = (String) call.argument("url");
|
||||
String domain = (String) call.argument("domain");
|
||||
String path = (String) call.argument("path");
|
||||
deleteCookies(url, domain, path, result);
|
||||
}
|
||||
break;
|
||||
case "deleteAllCookies":
|
||||
deleteAllCookies(result);
|
||||
break;
|
||||
case "removeSessionCookies":
|
||||
removeSessionCookies(result);
|
||||
break;
|
||||
default:
|
||||
result.notImplemented();
|
||||
}
|
||||
} finally { selectedCookieManager = null; }
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiating CookieManager will load the Chromium task taking a 100ish ms so we do it lazily
|
||||
* to make sure it's done on a background thread as needed.
|
||||
*
|
||||
* https://github.com/facebook/react-native/blob/1903f6680d9750e244d97c3cd4a9f755a9a47c61/ReactAndroid/src/main/java/com/facebook/react/modules/network/ForwardingCookieHandler.java#L132
|
||||
*/
|
||||
static private @Nullable CookieManager getCookieManager() {
|
||||
if (cookieManager == null) {
|
||||
try {
|
||||
cookieManager = CookieManager.getInstance();
|
||||
} catch (IllegalArgumentException ex) {
|
||||
// https://bugs.chromium.org/p/chromium/issues/detail?id=559720
|
||||
return null;
|
||||
} catch (Exception exception) {
|
||||
String message = exception.getMessage();
|
||||
// We cannot catch MissingWebViewPackageException as it is in a private / system API
|
||||
// class. This validates the exception's message to ensure we are only handling this
|
||||
// specific exception.
|
||||
// https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/webkit/WebViewFactory.java#348
|
||||
if (message != null
|
||||
&& exception
|
||||
.getClass()
|
||||
.getCanonicalName()
|
||||
.equals("android.webkit.WebViewFactory.MissingWebViewPackageException")) {
|
||||
return null;
|
||||
} else {
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return cookieManager;
|
||||
}
|
||||
|
||||
public void setCookie(String url,
|
||||
String name,
|
||||
String value,
|
||||
String domain,
|
||||
String path,
|
||||
Long expiresDate,
|
||||
Integer maxAge,
|
||||
Boolean isSecure,
|
||||
Boolean isHttpOnly,
|
||||
String sameSite,
|
||||
final MethodChannel.Result result) {
|
||||
final CookieManager cookieManager = selectedCookieManager != null ? selectedCookieManager : getCookieManager();
|
||||
if (cookieManager == null) {
|
||||
result.success(false);
|
||||
return;
|
||||
}
|
||||
|
||||
String cookieValue = name + "=" + value + "; Path=" + path;
|
||||
|
||||
if (domain != null)
|
||||
cookieValue += "; Domain=" + domain;
|
||||
|
||||
if (expiresDate != null)
|
||||
cookieValue += "; Expires=" + getCookieExpirationDate(expiresDate);
|
||||
|
||||
if (maxAge != null)
|
||||
cookieValue += "; Max-Age=" + maxAge.toString();
|
||||
|
||||
if (isSecure != null && isSecure)
|
||||
cookieValue += "; Secure";
|
||||
|
||||
if (isHttpOnly != null && isHttpOnly)
|
||||
cookieValue += "; HttpOnly";
|
||||
|
||||
if (sameSite != null)
|
||||
cookieValue += "; SameSite=" + sameSite;
|
||||
|
||||
cookieValue += ";";
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
|
||||
cookieManager.setCookie(url, cookieValue, new ValueCallback<Boolean>() {
|
||||
@Override
|
||||
public void onReceiveValue(Boolean successful) {
|
||||
result.success(successful);
|
||||
}
|
||||
});
|
||||
cookieManager.flush();
|
||||
}
|
||||
else if (plugin != null) {
|
||||
CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(plugin.applicationContext);
|
||||
cookieSyncMngr.startSync();
|
||||
cookieManager.setCookie(url, cookieValue);
|
||||
cookieSyncMngr.stopSync();
|
||||
cookieSyncMngr.sync();
|
||||
result.success(true);
|
||||
} else {
|
||||
cookieManager.setCookie(url, cookieValue);
|
||||
result.success(true);
|
||||
}
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> getCookies(final String url) {
|
||||
|
||||
final List<Map<String, Object>> cookieListMap = new ArrayList<>();
|
||||
|
||||
final CookieManager cookieManager = selectedCookieManager != null ? selectedCookieManager : getCookieManager();
|
||||
if (cookieManager == null) return cookieListMap;
|
||||
|
||||
List<String> cookies = new ArrayList<>();
|
||||
if (WebViewFeature.isFeatureSupported(WebViewFeature.GET_COOKIE_INFO)) {
|
||||
cookies = CookieManagerCompat.getCookieInfo(cookieManager, url);
|
||||
} else {
|
||||
String cookiesString = cookieManager.getCookie(url);
|
||||
if (cookiesString != null) {
|
||||
cookies = Arrays.asList(cookiesString.split(";"));
|
||||
}
|
||||
}
|
||||
|
||||
for (String cookie : cookies) {
|
||||
String[] cookieParams = cookie.split(";");
|
||||
if (cookieParams.length == 0) continue;
|
||||
|
||||
String[] nameValue = cookieParams[0].split("=", 2);
|
||||
String name = nameValue[0].trim();
|
||||
String value = (nameValue.length > 1) ? nameValue[1].trim() : "";
|
||||
|
||||
Map<String, Object> cookieMap = new HashMap<>();
|
||||
cookieMap.put("name", name);
|
||||
cookieMap.put("value", value);
|
||||
cookieMap.put("expiresDate", null);
|
||||
cookieMap.put("isSessionOnly", null);
|
||||
cookieMap.put("domain", null);
|
||||
cookieMap.put("sameSite", null);
|
||||
cookieMap.put("isSecure", null);
|
||||
cookieMap.put("isHttpOnly", null);
|
||||
cookieMap.put("path", null);
|
||||
|
||||
if (WebViewFeature.isFeatureSupported(WebViewFeature.GET_COOKIE_INFO)) {
|
||||
cookieMap.put("isSecure", false);
|
||||
cookieMap.put("isHttpOnly", false);
|
||||
|
||||
for (int i = 1; i < cookieParams.length; i++) {
|
||||
String[] cookieParamNameValue = cookieParams[i].split("=", 2);
|
||||
String cookieParamName = cookieParamNameValue[0].trim();
|
||||
String cookieParamValue = (cookieParamNameValue.length > 1) ? cookieParamNameValue[1].trim() : "";
|
||||
|
||||
if (cookieParamName.equalsIgnoreCase("Expires")) {
|
||||
try {
|
||||
final SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss z", Locale.US);
|
||||
Date expiryDate = sdf.parse(cookieParamValue);
|
||||
if (expiryDate != null) {
|
||||
cookieMap.put("expiresDate", expiryDate.getTime());
|
||||
}
|
||||
} catch (ParseException e) {
|
||||
Log.e(LOG_TAG, "", e);
|
||||
}
|
||||
} else if (cookieParamName.equalsIgnoreCase("Max-Age")) {
|
||||
try {
|
||||
long maxAge = Long.parseLong(cookieParamValue);
|
||||
cookieMap.put("expiresDate", System.currentTimeMillis() + maxAge);
|
||||
} catch (NumberFormatException e) {
|
||||
Log.e(LOG_TAG, "", e);
|
||||
}
|
||||
} else if (cookieParamName.equalsIgnoreCase("Domain")) {
|
||||
cookieMap.put("domain", cookieParamValue);
|
||||
} else if (cookieParamName.equalsIgnoreCase("SameSite")) {
|
||||
cookieMap.put("sameSite", cookieParamValue);
|
||||
} else if (cookieParamName.equalsIgnoreCase("Secure")) {
|
||||
cookieMap.put("isSecure", true);
|
||||
} else if (cookieParamName.equalsIgnoreCase("HttpOnly")) {
|
||||
cookieMap.put("isHttpOnly", true);
|
||||
} else if (cookieParamName.equalsIgnoreCase("Path")) {
|
||||
cookieMap.put("path", cookieParamValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cookieListMap.add(cookieMap);
|
||||
}
|
||||
return cookieListMap;
|
||||
|
||||
}
|
||||
|
||||
public void deleteCookie(String url, String name, String domain, String path, final MethodChannel.Result result) {
|
||||
final CookieManager cookieManager = selectedCookieManager != null ? selectedCookieManager : getCookieManager();
|
||||
if (cookieManager == null) {
|
||||
result.success(false);
|
||||
return;
|
||||
}
|
||||
|
||||
String cookieValue = name + "=; Path=" + path + "; Max-Age=-1";
|
||||
|
||||
if (domain != null)
|
||||
cookieValue += "; Domain=" + domain;
|
||||
|
||||
cookieValue += ";";
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
|
||||
cookieManager.setCookie(url, cookieValue, new ValueCallback<Boolean>() {
|
||||
@Override
|
||||
public void onReceiveValue(Boolean successful) {
|
||||
result.success(successful);
|
||||
}
|
||||
});
|
||||
cookieManager.flush();
|
||||
}
|
||||
else if (plugin != null) {
|
||||
CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(plugin.applicationContext);
|
||||
cookieSyncMngr.startSync();
|
||||
cookieManager.setCookie(url, cookieValue);
|
||||
cookieSyncMngr.stopSync();
|
||||
cookieSyncMngr.sync();
|
||||
result.success(true);
|
||||
} else {
|
||||
cookieManager.setCookie(url, cookieValue);
|
||||
result.success(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void deleteCookies(String url, String domain, String path, final MethodChannel.Result result) {
|
||||
final CookieManager cookieManager = selectedCookieManager != null ? selectedCookieManager : getCookieManager();
|
||||
if (cookieManager == null) {
|
||||
result.success(false);
|
||||
return;
|
||||
}
|
||||
|
||||
CookieSyncManager cookieSyncMngr = null;
|
||||
|
||||
String cookiesString = cookieManager.getCookie(url);
|
||||
if (cookiesString != null) {
|
||||
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP && plugin != null) {
|
||||
cookieSyncMngr = CookieSyncManager.createInstance(plugin.applicationContext);
|
||||
cookieSyncMngr.startSync();
|
||||
}
|
||||
|
||||
String[] cookies = cookiesString.split(";");
|
||||
for (String cookie : cookies) {
|
||||
String[] nameValue = cookie.split("=", 2);
|
||||
String name = nameValue[0].trim();
|
||||
|
||||
String cookieValue = name + "=; Path=" + path + "; Max-Age=-1";
|
||||
|
||||
if (domain != null)
|
||||
cookieValue += "; Domain=" + domain;
|
||||
|
||||
cookieValue += ";";
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
|
||||
cookieManager.setCookie(url, cookieValue, null);
|
||||
else
|
||||
cookieManager.setCookie(url, cookieValue);
|
||||
}
|
||||
|
||||
if (cookieSyncMngr != null) {
|
||||
cookieSyncMngr.stopSync();
|
||||
cookieSyncMngr.sync();
|
||||
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
|
||||
cookieManager.flush();
|
||||
}
|
||||
result.success(true);
|
||||
}
|
||||
|
||||
public void deleteAllCookies(final MethodChannel.Result result) {
|
||||
final CookieManager cookieManager = selectedCookieManager != null ? selectedCookieManager : getCookieManager();
|
||||
if (cookieManager == null) {
|
||||
result.success(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
|
||||
cookieManager.removeAllCookies(new ValueCallback<Boolean>() {
|
||||
@Override
|
||||
public void onReceiveValue(Boolean successful) {
|
||||
result.success(successful);
|
||||
}
|
||||
});
|
||||
cookieManager.flush();
|
||||
}
|
||||
else if (plugin != null) {
|
||||
CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(plugin.applicationContext);
|
||||
cookieSyncMngr.startSync();
|
||||
cookieManager.removeAllCookie();
|
||||
cookieSyncMngr.stopSync();
|
||||
cookieSyncMngr.sync();
|
||||
result.success(true);
|
||||
} else {
|
||||
cookieManager.removeAllCookie();
|
||||
result.success(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void removeSessionCookies(final MethodChannel.Result result) {
|
||||
final CookieManager cookieManager = selectedCookieManager != null ? selectedCookieManager : getCookieManager();
|
||||
if (cookieManager == null) {
|
||||
result.success(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
|
||||
cookieManager.removeSessionCookies(new ValueCallback<Boolean>() {
|
||||
@Override
|
||||
public void onReceiveValue(Boolean successful) {
|
||||
result.success(successful);
|
||||
}
|
||||
});
|
||||
cookieManager.flush();
|
||||
}
|
||||
else if (plugin != null) {
|
||||
CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(plugin.applicationContext);
|
||||
cookieSyncMngr.startSync();
|
||||
cookieManager.removeSessionCookie();
|
||||
cookieSyncMngr.stopSync();
|
||||
cookieSyncMngr.sync();
|
||||
result.success(true);
|
||||
} else {
|
||||
cookieManager.removeSessionCookie();
|
||||
result.success(true);
|
||||
}
|
||||
}
|
||||
|
||||
public static String getCookieExpirationDate(Long timestamp) {
|
||||
final SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss z", Locale.US);
|
||||
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
|
||||
return sdf.format(new Date(timestamp));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void dispose() {
|
||||
super.dispose();
|
||||
plugin = null;
|
||||
}
|
||||
}
|
||||
Vendored
Executable
+138
@@ -0,0 +1,138 @@
|
||||
package com.pichillilorenzo.flutter_inappwebview_android;
|
||||
|
||||
import android.webkit.ValueCallback;
|
||||
import android.webkit.WebStorage;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.pichillilorenzo.flutter_inappwebview_android.types.ChannelDelegateImpl;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import io.flutter.plugin.common.MethodCall;
|
||||
import io.flutter.plugin.common.MethodChannel;
|
||||
|
||||
public class MyWebStorage extends ChannelDelegateImpl {
|
||||
protected static final String LOG_TAG = "MyWebStorage";
|
||||
public static final String METHOD_CHANNEL_NAME = "com.pichillilorenzo/flutter_inappwebview_webstoragemanager";
|
||||
|
||||
@Nullable
|
||||
public static WebStorage webStorageManager;
|
||||
@Nullable
|
||||
public InAppWebViewFlutterPlugin plugin;
|
||||
|
||||
public MyWebStorage(@NonNull final InAppWebViewFlutterPlugin plugin) {
|
||||
super(new MethodChannel(plugin.messenger, METHOD_CHANNEL_NAME));
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
public static void init() {
|
||||
if (webStorageManager == null) {
|
||||
webStorageManager = WebStorage.getInstance();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
|
||||
init();
|
||||
|
||||
switch (call.method) {
|
||||
case "getOrigins":
|
||||
getOrigins(result);
|
||||
break;
|
||||
case "deleteAllData":
|
||||
if (webStorageManager != null) {
|
||||
webStorageManager.deleteAllData();
|
||||
result.success(true);
|
||||
} else {
|
||||
result.success(false);
|
||||
}
|
||||
break;
|
||||
case "deleteOrigin":
|
||||
{
|
||||
if (webStorageManager != null) {
|
||||
String origin = (String) call.argument("origin");
|
||||
webStorageManager.deleteOrigin(origin);
|
||||
result.success(true);
|
||||
} else {
|
||||
result.success(false);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case "getQuotaForOrigin":
|
||||
{
|
||||
String origin = (String) call.argument("origin");
|
||||
getQuotaForOrigin(origin, result);
|
||||
}
|
||||
break;
|
||||
case "getUsageForOrigin":
|
||||
{
|
||||
String origin = (String) call.argument("origin");
|
||||
getUsageForOrigin(origin, result);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
result.notImplemented();
|
||||
}
|
||||
}
|
||||
|
||||
public void getOrigins(final MethodChannel.Result result) {
|
||||
if (webStorageManager == null) {
|
||||
result.success(new ArrayList<>());
|
||||
return;
|
||||
}
|
||||
webStorageManager.getOrigins(new ValueCallback<Map>() {
|
||||
@Override
|
||||
public void onReceiveValue(Map value) {
|
||||
List<Map<String, Object>> origins = new ArrayList<>();
|
||||
for(Object key : value.keySet()) {
|
||||
WebStorage.Origin originObj = (WebStorage.Origin) value.get(key);
|
||||
|
||||
Map<String, Object> originInfo = new HashMap<>();
|
||||
originInfo.put("origin", originObj.getOrigin());
|
||||
originInfo.put("quota", originObj.getQuota());
|
||||
originInfo.put("usage", originObj.getUsage());
|
||||
|
||||
origins.add(originInfo);
|
||||
}
|
||||
result.success(origins);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void getQuotaForOrigin(String origin, final MethodChannel.Result result) {
|
||||
if (webStorageManager == null) {
|
||||
result.success(0);
|
||||
return;
|
||||
}
|
||||
webStorageManager.getQuotaForOrigin(origin, new ValueCallback<Long>() {
|
||||
@Override
|
||||
public void onReceiveValue(Long value) {
|
||||
result.success(value);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void getUsageForOrigin(String origin, final MethodChannel.Result result) {
|
||||
if (webStorageManager == null) {
|
||||
result.success(0);
|
||||
return;
|
||||
}
|
||||
webStorageManager.getUsageForOrigin(origin, new ValueCallback<Long>() {
|
||||
@Override
|
||||
public void onReceiveValue(Long value) {
|
||||
result.success(value);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void dispose() {
|
||||
super.dispose();
|
||||
plugin = null;
|
||||
}
|
||||
}
|
||||
Vendored
Executable
+73
@@ -0,0 +1,73 @@
|
||||
package com.pichillilorenzo.flutter_inappwebview_android;
|
||||
|
||||
import android.os.Build;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.pichillilorenzo.flutter_inappwebview_android.types.ChannelDelegateImpl;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.Locale;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import io.flutter.plugin.common.MethodCall;
|
||||
import io.flutter.plugin.common.MethodChannel;
|
||||
|
||||
public class PlatformUtil extends ChannelDelegateImpl {
|
||||
protected static final String LOG_TAG = "PlatformUtil";
|
||||
public static final String METHOD_CHANNEL_NAME = "com.pichillilorenzo/flutter_inappwebview_platformutil";
|
||||
|
||||
@Nullable
|
||||
public InAppWebViewFlutterPlugin plugin;
|
||||
|
||||
public PlatformUtil(final InAppWebViewFlutterPlugin plugin) {
|
||||
super(new MethodChannel(plugin.messenger, METHOD_CHANNEL_NAME));
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMethodCall(@NonNull MethodCall call, @NonNull final MethodChannel.Result result) {
|
||||
switch (call.method) {
|
||||
case "getSystemVersion":
|
||||
result.success(String.valueOf(Build.VERSION.SDK_INT));
|
||||
break;
|
||||
case "formatDate":
|
||||
long date = (long) call.argument("date");
|
||||
String format = (String) call.argument("format");
|
||||
Locale locale = PlatformUtil.getLocaleFromString((String) call.argument("locale"));
|
||||
String timezone = (String) call.argument("timezone");
|
||||
if (timezone == null) {
|
||||
timezone = "UTC";
|
||||
}
|
||||
result.success(PlatformUtil.formatDate(date, format, locale, TimeZone.getTimeZone(timezone)));
|
||||
break;
|
||||
default:
|
||||
result.notImplemented();
|
||||
}
|
||||
}
|
||||
|
||||
public static Locale getLocaleFromString(@Nullable String locale) {
|
||||
if (locale == null) {
|
||||
return Locale.US;
|
||||
}
|
||||
String[] localeSplit = locale.split("_");
|
||||
String language = localeSplit[0];
|
||||
String country = localeSplit.length > 1 ? localeSplit[1] : "";
|
||||
String variant = localeSplit.length > 2 ? localeSplit[2] : "";
|
||||
return new Locale(language, country, variant);
|
||||
}
|
||||
|
||||
public static String formatDate(long date, String format, Locale locale, TimeZone timezone) {
|
||||
final SimpleDateFormat sdf = new SimpleDateFormat(format, locale);
|
||||
sdf.setTimeZone(timezone);
|
||||
return sdf.format(new Date(date));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void dispose() {
|
||||
super.dispose();
|
||||
plugin = null;
|
||||
}
|
||||
}
|
||||
Vendored
Executable
+386
@@ -0,0 +1,386 @@
|
||||
package com.pichillilorenzo.flutter_inappwebview_android;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.res.AssetManager;
|
||||
import android.graphics.BitmapFactory;
|
||||
import android.graphics.Insets;
|
||||
import android.graphics.Rect;
|
||||
import android.graphics.drawable.BitmapDrawable;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.net.http.SslCertificate;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.text.TextUtils;
|
||||
import android.util.DisplayMetrics;
|
||||
import android.util.Log;
|
||||
import android.view.WindowInsets;
|
||||
import android.view.WindowManager;
|
||||
import android.view.WindowMetrics;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.annotation.RequiresApi;
|
||||
|
||||
import com.pichillilorenzo.flutter_inappwebview_android.types.Size2D;
|
||||
import com.pichillilorenzo.flutter_inappwebview_android.types.SyncBaseCallbackResultImpl;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.Inet6Address;
|
||||
import java.net.InetAddress;
|
||||
import java.net.URL;
|
||||
import java.net.UnknownHostException;
|
||||
import java.security.Key;
|
||||
import java.security.KeyStore;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.cert.Certificate;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.security.cert.CertificateFactory;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.Enumeration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import javax.net.ssl.SSLHandshakeException;
|
||||
|
||||
import io.flutter.plugin.common.MethodChannel;
|
||||
|
||||
public class Util {
|
||||
|
||||
static final String LOG_TAG = "Util";
|
||||
public static final String ANDROID_ASSET_URL = "file:///android_asset/";
|
||||
|
||||
private Util() {}
|
||||
|
||||
public static String getUrlAsset(InAppWebViewFlutterPlugin plugin, String assetFilePath) throws IOException {
|
||||
String key = plugin.flutterAssets.getAssetFilePathByName(assetFilePath);
|
||||
InputStream is = null;
|
||||
IOException e = null;
|
||||
|
||||
try {
|
||||
is = getFileAsset(plugin, assetFilePath);
|
||||
} catch (IOException ex) {
|
||||
e = ex;
|
||||
} finally {
|
||||
if (is != null) {
|
||||
try {
|
||||
is.close();
|
||||
} catch (IOException ex) {
|
||||
e = ex;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (e != null) {
|
||||
throw e;
|
||||
}
|
||||
|
||||
return ANDROID_ASSET_URL + key;
|
||||
}
|
||||
|
||||
public static InputStream getFileAsset(InAppWebViewFlutterPlugin plugin, String assetFilePath) throws IOException {
|
||||
String key = plugin.flutterAssets.getAssetFilePathByName(assetFilePath);
|
||||
AssetManager mg = plugin.applicationContext.getResources().getAssets();
|
||||
return mg.open(key);
|
||||
}
|
||||
|
||||
public static <T> T invokeMethodAndWaitResult(final @NonNull MethodChannel channel,
|
||||
final @NonNull String method, final @Nullable Object arguments,
|
||||
final @NonNull SyncBaseCallbackResultImpl<T> callback) throws InterruptedException {
|
||||
Handler handler = new Handler(Looper.getMainLooper());
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
channel.invokeMethod(method, arguments, callback);
|
||||
}
|
||||
});
|
||||
callback.latch.await();
|
||||
return callback.result;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static PrivateKeyAndCertificates loadPrivateKeyAndCertificate(@NonNull InAppWebViewFlutterPlugin plugin,
|
||||
@NonNull String certificatePath,
|
||||
@Nullable String certificatePassword,
|
||||
@NonNull String keyStoreType) {
|
||||
PrivateKeyAndCertificates privateKeyAndCertificates = null;
|
||||
InputStream certificateFileStream = null;
|
||||
|
||||
try {
|
||||
certificateFileStream = getFileAsset(plugin, certificatePath);
|
||||
} catch (IOException ignored) {}
|
||||
|
||||
try {
|
||||
if (certificateFileStream == null) {
|
||||
certificateFileStream = new FileInputStream(certificatePath);
|
||||
}
|
||||
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
|
||||
keyStore.load(certificateFileStream, (certificatePassword != null ? certificatePassword : "").toCharArray());
|
||||
|
||||
Enumeration<String> aliases = keyStore.aliases();
|
||||
String alias = aliases.nextElement();
|
||||
|
||||
Key key = keyStore.getKey(alias, (certificatePassword != null ? certificatePassword : "").toCharArray());
|
||||
if (key instanceof PrivateKey) {
|
||||
PrivateKey privateKey = (PrivateKey)key;
|
||||
Certificate cert = keyStore.getCertificate(alias);
|
||||
X509Certificate[] certificates = new X509Certificate[1];
|
||||
certificates[0] = (X509Certificate)cert;
|
||||
privateKeyAndCertificates = new PrivateKeyAndCertificates(privateKey, certificates);
|
||||
}
|
||||
certificateFileStream.close();
|
||||
} catch (Exception e) {
|
||||
Log.e(LOG_TAG, "", e);
|
||||
} finally {
|
||||
if (certificateFileStream != null) {
|
||||
try {
|
||||
certificateFileStream.close();
|
||||
} catch (IOException ex) {
|
||||
Log.e(LOG_TAG, "", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return privateKeyAndCertificates;
|
||||
}
|
||||
|
||||
public static class PrivateKeyAndCertificates {
|
||||
|
||||
public X509Certificate[] certificates;
|
||||
public PrivateKey privateKey;
|
||||
|
||||
public PrivateKeyAndCertificates(PrivateKey privateKey, X509Certificate[] certificates) {
|
||||
this.privateKey = privateKey;
|
||||
this.certificates = certificates;
|
||||
}
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static HttpURLConnection makeHttpRequest(String urlString, String method, @Nullable Map<String, String> headers) {
|
||||
HttpURLConnection urlConnection = null;
|
||||
try {
|
||||
URL url = new URL(urlString);
|
||||
urlConnection = (HttpURLConnection) url.openConnection();
|
||||
urlConnection.setRequestMethod(method);
|
||||
if (headers != null) {
|
||||
for (Map.Entry<String, String> header : headers.entrySet()) {
|
||||
urlConnection.setRequestProperty(header.getKey(), header.getValue());
|
||||
}
|
||||
}
|
||||
urlConnection.setConnectTimeout(15000); // 15 seconds
|
||||
urlConnection.setReadTimeout(15000); // 15 seconds
|
||||
urlConnection.setDoInput(true);
|
||||
urlConnection.setInstanceFollowRedirects(true);
|
||||
if ("GET".equalsIgnoreCase(method)) {
|
||||
urlConnection.setDoOutput(false);
|
||||
}
|
||||
urlConnection.connect();
|
||||
return urlConnection;
|
||||
}
|
||||
catch (Exception e) {
|
||||
if (!(e instanceof SSLHandshakeException)) {
|
||||
Log.e(LOG_TAG, "", e);
|
||||
}
|
||||
if (urlConnection != null) {
|
||||
urlConnection.disconnect();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* SslCertificate class does not has a public getter for the underlying
|
||||
* X509Certificate, we can only do this by hack. This only works for Android 4.0+
|
||||
* https://groups.google.com/forum/#!topic/android-developers/eAPJ6b7mrmg
|
||||
*/
|
||||
public static X509Certificate getX509CertFromSslCertHack(SslCertificate sslCert) {
|
||||
X509Certificate x509Certificate = null;
|
||||
|
||||
Bundle bundle = SslCertificate.saveState(sslCert);
|
||||
byte[] bytes = bundle.getByteArray("x509-certificate");
|
||||
|
||||
if (bytes == null) {
|
||||
x509Certificate = null;
|
||||
} else {
|
||||
try {
|
||||
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
|
||||
Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
|
||||
x509Certificate = (X509Certificate) cert;
|
||||
} catch (CertificateException e) {
|
||||
x509Certificate = null;
|
||||
}
|
||||
}
|
||||
|
||||
return x509Certificate;
|
||||
}
|
||||
|
||||
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
|
||||
public static String JSONStringify(@Nullable Object value) {
|
||||
if (value == null) {
|
||||
return "null";
|
||||
}
|
||||
if (value instanceof Map) {
|
||||
return new JSONObject((Map<String, Object>) value).toString();
|
||||
} else if (value instanceof List) {
|
||||
return new JSONArray((List<Object>) value).toString();
|
||||
} else if (value instanceof String) {
|
||||
return JSONObject.quote((String) value);
|
||||
} else {
|
||||
return JSONObject.wrap(value).toString();
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean objEquals(@Nullable Object a, @Nullable Object b) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
|
||||
return Objects.equals(a, b);
|
||||
}
|
||||
return (a == b) || (a != null && a.equals(b));
|
||||
}
|
||||
|
||||
public static String replaceAll(String s, String oldString, String newString) {
|
||||
return TextUtils.join(newString, s.split(Pattern.quote(oldString)));
|
||||
}
|
||||
|
||||
public static void log(String tag, String message) {
|
||||
// Split by line, then ensure each line can fit into Log's maximum length.
|
||||
for (int i = 0, length = message.length(); i < length; i++) {
|
||||
int newline = message.indexOf('\n', i);
|
||||
newline = newline != -1 ? newline : length;
|
||||
do {
|
||||
int end = Math.min(newline, i + 4000);
|
||||
Log.d(tag, message.substring(i, end));
|
||||
i = end;
|
||||
} while (i < newline);
|
||||
}
|
||||
}
|
||||
|
||||
public static float getPixelDensity(Context context) {
|
||||
return context.getResources().getDisplayMetrics().density;
|
||||
}
|
||||
|
||||
public static Size2D getFullscreenSize(Context context) {
|
||||
Size2D fullscreenSize = new Size2D(-1, -1);
|
||||
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
|
||||
if (wm != null) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
final WindowMetrics metrics = wm.getCurrentWindowMetrics();
|
||||
// Gets all excluding insets
|
||||
final WindowInsets windowInsets = metrics.getWindowInsets();
|
||||
Insets insets = windowInsets.getInsetsIgnoringVisibility(WindowInsets.Type.navigationBars()
|
||||
| WindowInsets.Type.displayCutout());
|
||||
int insetsWidth = insets.right + insets.left;
|
||||
int insetsHeight = insets.top + insets.bottom;
|
||||
final Rect bounds = metrics.getBounds();
|
||||
fullscreenSize.setWidth(bounds.width() - insetsWidth);
|
||||
fullscreenSize.setHeight(bounds.height() - insetsHeight);
|
||||
} else {
|
||||
DisplayMetrics displayMetrics = new DisplayMetrics();
|
||||
wm.getDefaultDisplay().getMetrics(displayMetrics);
|
||||
fullscreenSize.setWidth(displayMetrics.widthPixels);
|
||||
fullscreenSize.setHeight(displayMetrics.heightPixels);
|
||||
}
|
||||
}
|
||||
return fullscreenSize;
|
||||
}
|
||||
|
||||
public static boolean isClass(String className) {
|
||||
try {
|
||||
Class.forName(className);
|
||||
return true;
|
||||
} catch (ClassNotFoundException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isIPv6(String address) {
|
||||
try {
|
||||
Inet6Address.getByName(address);
|
||||
} catch (UnknownHostException e) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static String normalizeIPv6(String address) throws Exception {
|
||||
if (!Util.isIPv6(address)) {
|
||||
throw new Exception("Invalid address: " + address);
|
||||
}
|
||||
return InetAddress.getByName(address).getCanonicalHostName();
|
||||
}
|
||||
|
||||
public static <T> T getOrDefault(Map<String, Object> map, String key, T defaultValue) {
|
||||
return map.containsKey(key) ? (T) map.get(key) : defaultValue;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static byte[] readAllBytes(@Nullable InputStream inputStream) {
|
||||
if (inputStream == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
final int bufLen = 4 * 0x400; // 4KB
|
||||
byte[] buf = new byte[bufLen];
|
||||
int readLen;
|
||||
IOException exception = null;
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
byte[] data = null;
|
||||
|
||||
try {
|
||||
while ((readLen = inputStream.read(buf, 0, bufLen)) != -1)
|
||||
outputStream.write(buf, 0, readLen);
|
||||
|
||||
data = outputStream.toByteArray();
|
||||
} catch (IOException e) {
|
||||
exception = e;
|
||||
} finally {
|
||||
try {
|
||||
inputStream.close();
|
||||
} catch (IOException e) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && exception != null) {
|
||||
exception.addSuppressed(e);
|
||||
}
|
||||
}
|
||||
try {
|
||||
outputStream.close();
|
||||
} catch (IOException e) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && exception != null) {
|
||||
exception.addSuppressed(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static <O> Object invokeMethodIfExists(final O o, final String methodName, Object... args) {
|
||||
Method[] methods = o.getClass().getMethods();
|
||||
for (Method method : methods) {
|
||||
if (method.getName().equals(methodName)) {
|
||||
try {
|
||||
return method.invoke(o, args);
|
||||
} catch (IllegalAccessException e) {
|
||||
return null;
|
||||
} catch (InvocationTargetException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Drawable drawableFromBytes(Context context, byte[] data) {
|
||||
return new BitmapDrawable(context.getResources(), BitmapFactory.decodeByteArray(data, 0, data.length));
|
||||
}
|
||||
}
|
||||
Vendored
Executable
+47
@@ -0,0 +1,47 @@
|
||||
package com.pichillilorenzo.flutter_inappwebview_android;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.webkit.WebViewFeature;
|
||||
|
||||
import com.pichillilorenzo.flutter_inappwebview_android.types.ChannelDelegateImpl;
|
||||
|
||||
import io.flutter.plugin.common.MethodCall;
|
||||
import io.flutter.plugin.common.MethodChannel;
|
||||
|
||||
public class WebViewFeatureManager extends ChannelDelegateImpl {
|
||||
protected static final String LOG_TAG = "WebViewFeatureManager";
|
||||
public static final String METHOD_CHANNEL_NAME = "com.pichillilorenzo/flutter_inappwebview_webviewfeature";
|
||||
|
||||
@Nullable
|
||||
public InAppWebViewFlutterPlugin plugin;
|
||||
|
||||
public WebViewFeatureManager(@NonNull final InAppWebViewFlutterPlugin plugin) {
|
||||
super(new MethodChannel(plugin.messenger, METHOD_CHANNEL_NAME));
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
|
||||
switch (call.method) {
|
||||
case "isFeatureSupported":
|
||||
String feature = (String) call.argument("feature");
|
||||
result.success(WebViewFeature.isFeatureSupported(feature));
|
||||
break;
|
||||
case "isStartupFeatureSupported":
|
||||
if (plugin != null && plugin.activity != null) {
|
||||
String startupFeature = (String) call.argument("startupFeature");
|
||||
result.success(WebViewFeature.isStartupFeatureSupported(plugin.activity, startupFeature));
|
||||
}
|
||||
break;
|
||||
default:
|
||||
result.notImplemented();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void dispose() {
|
||||
super.dispose();
|
||||
plugin = null;
|
||||
}
|
||||
}
|
||||
Loaded 50 of 564 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user