forked from Blendman974/faceclaw
Fixes to EvenHub webview handling
This commit is contained in:
1 parent
f4751ad480
commit
60595d7321
21 files changed
+1001
-142
No files matched your search
@@ -1,32 +1,100 @@
|
||||
package com.faceclaw.app
|
||||
|
||||
import android.net.Uri
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.webkit.JavascriptInterface
|
||||
import android.util.Log
|
||||
import android.webkit.WebView
|
||||
import androidx.webkit.JavaScriptReplyProxy
|
||||
import androidx.webkit.WebMessageCompat
|
||||
import androidx.webkit.WebViewCompat
|
||||
import androidx.webkit.WebViewFeature
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONException
|
||||
|
||||
/**
|
||||
* The object injected into a hosted EvenHub app's WebView as
|
||||
* window.__faceclawEvenHub. The document-start shim (served inline by
|
||||
* FaceclawEvenHubWebViewClient) wraps it in a promise-returning
|
||||
* window.flutter_inappwebview.callHandler, which is what the EvenHub SDK
|
||||
* actually talks to.
|
||||
* The host end of a hosted EvenHub app's bridge: window.__faceclawEvenHubPort,
|
||||
* a WebMessageListener object that WebView injects only into frames from the
|
||||
* app's own origin. Sites the app navigates to, and other-origin iframes it
|
||||
* embeds, never see it, and messages from the app's own subframes are dropped,
|
||||
* so only the app's main document reaches the host (its SDK storage, sensors,
|
||||
* glasses display and the Faceclaw extensions, API keys included). This
|
||||
* replaced an addJavascriptInterface object, which WebView exposes to every
|
||||
* frame of every page.
|
||||
*
|
||||
* JavascriptInterface methods run on a WebView-internal thread; everything
|
||||
* is bounced to the main thread before touching the NativeScript listener.
|
||||
* The transport script (webview.ts) wraps the port as window.__faceclawEvenHub,
|
||||
* whose postMessage(name, argsJson, id) and wakeTimers() the stock bridge shim
|
||||
* and the extensions call. Messages are JSON arrays: ["call", name, argsJson,
|
||||
* id] or ["wake"].
|
||||
*/
|
||||
class FaceclawEvenHubJsBridge(private val listener: FaceclawEvenHubListener) {
|
||||
class FaceclawEvenHubJsBridge private constructor(
|
||||
private val listener: FaceclawEvenHubListener
|
||||
) : WebViewCompat.WebMessageListener {
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
|
||||
@JavascriptInterface
|
||||
fun postMessage(handlerName: String?, argsJson: String?, callId: Int) {
|
||||
mainHandler.post {
|
||||
listener.onEvenAppMessage(handlerName, argsJson, callId)
|
||||
override fun onPostMessage(
|
||||
view: WebView,
|
||||
message: WebMessageCompat,
|
||||
sourceOrigin: Uri,
|
||||
isMainFrame: Boolean,
|
||||
replyProxy: JavaScriptReplyProxy
|
||||
) {
|
||||
if (!isMainFrame) return
|
||||
val parts = try {
|
||||
JSONArray(message.data ?: return)
|
||||
} catch (e: JSONException) {
|
||||
return
|
||||
}
|
||||
when (parts.optString(0)) {
|
||||
"call" -> {
|
||||
val name = parts.optString(1)
|
||||
val argsJson = parts.optString(2)
|
||||
val callId = parts.optInt(3)
|
||||
mainHandler.post { listener.onEvenAppMessage(name, argsJson, callId) }
|
||||
}
|
||||
// The page's timer shim has work due before the host's next tick.
|
||||
"wake" -> FaceclawEvenHubWebViewHost.getInstance().wakeTimers()
|
||||
}
|
||||
}
|
||||
|
||||
/** The page's timer shim has work due before the host's next tick. */
|
||||
@JavascriptInterface
|
||||
fun wakeTimers() {
|
||||
FaceclawEvenHubWebViewHost.getInstance().wakeTimers()
|
||||
companion object {
|
||||
private const val TAG = "FaceclawEvenHub"
|
||||
private const val OBJECT_NAME = "__faceclawEvenHubPort"
|
||||
|
||||
/**
|
||||
* The origin rule matching exactly [url]'s origin (default port elided),
|
||||
* or null when it isn't an http(s) URL with a host.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun originRule(url: String): String? {
|
||||
val uri = Uri.parse(url)
|
||||
val scheme = uri.scheme?.lowercase()
|
||||
val host = uri.host?.lowercase()
|
||||
if ((scheme != "http" && scheme != "https") || host.isNullOrEmpty()) return null
|
||||
val defaultPort = if (scheme == "https") 443 else 80
|
||||
return if (uri.port == -1 || uri.port == defaultPort) "$scheme://$host" else "$scheme://$host:${uri.port}"
|
||||
}
|
||||
|
||||
/**
|
||||
* Expose the bridge to [webView]'s frames from [originRule]. Must run
|
||||
* before the WebView loads anything.
|
||||
*
|
||||
* @return null on success, else why the bridge could not be installed.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun install(webView: WebView, originRule: String, listener: FaceclawEvenHubListener): String? {
|
||||
if (!WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) {
|
||||
Log.w(TAG, "WebMessageListener unsupported; not exposing the EvenHub bridge")
|
||||
return "This Android System WebView is too old to run EvenHub apps safely. Update it, then reopen the app."
|
||||
}
|
||||
return try {
|
||||
WebViewCompat.addWebMessageListener(webView, OBJECT_NAME, setOf(originRule), FaceclawEvenHubJsBridge(listener))
|
||||
null
|
||||
} catch (e: IllegalArgumentException) {
|
||||
Log.w(TAG, "bridge origin rule rejected: $originRule", e)
|
||||
"The app's address ($originRule) can't be used as a web origin."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.faceclaw.app
|
||||
|
||||
import android.util.Log
|
||||
import android.webkit.WebView
|
||||
import androidx.webkit.ProfileStore
|
||||
import androidx.webkit.WebViewCompat
|
||||
import androidx.webkit.WebViewFeature
|
||||
|
||||
import java.security.MessageDigest
|
||||
|
||||
/**
|
||||
* Gives each EvenHub package its own WebView profile, so one app's browser
|
||||
* storage (cookies, localStorage, IndexedDB, caches, service workers) is out of
|
||||
* reach of every other app. That includes the storage of third-party sites an
|
||||
* app navigates to, such as a sign-in provider's session cookies, which in the
|
||||
* shared default profile any other app's WebView could reuse. The per-app fake
|
||||
* origins alone don't cover that, and `*.evenhub.invalid` hosts share a site,
|
||||
* so domain cookies would cross between packaged apps too.
|
||||
*
|
||||
* The profile persists across launches, and is shared by every instance of the
|
||||
* same package, like the iOS per-package WKWebsiteDataStore.
|
||||
*/
|
||||
class FaceclawEvenHubProfile private constructor() {
|
||||
companion object {
|
||||
private const val TAG = "FaceclawEvenHub"
|
||||
|
||||
/** Stable per package; the hash input matches the iOS data-store identifier's. */
|
||||
@JvmStatic
|
||||
fun nameFor(packageId: String): String {
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
.digest("com.faceclaw.ehpk:$packageId".toByteArray(Charsets.UTF_8))
|
||||
return "evenhub-" + digest.take(16).joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Put a new WebView in [packageId]'s profile. Must run on the main thread
|
||||
* before anything else is done with the WebView.
|
||||
*
|
||||
* @return false when the WebView provider lacks multi-profile support,
|
||||
* leaving the WebView in the shared default profile.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun apply(webView: WebView, packageId: String): Boolean {
|
||||
if (!WebViewFeature.isFeatureSupported(WebViewFeature.MULTI_PROFILE)) {
|
||||
Log.w(TAG, "multi-profile WebView unsupported; $packageId shares the default profile")
|
||||
return false
|
||||
}
|
||||
val name = nameFor(packageId)
|
||||
ProfileStore.getInstance().getOrCreateProfile(name)
|
||||
WebViewCompat.setProfile(webView, name)
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package com.faceclaw.app
|
||||
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.webkit.RenderProcessGoneDetail
|
||||
import android.webkit.WebResourceRequest
|
||||
import android.webkit.WebResourceResponse
|
||||
import android.webkit.WebView
|
||||
@@ -33,6 +34,11 @@ import java.nio.charset.StandardCharsets
|
||||
* The shim is registered as a document-start script instead
|
||||
* (FaceclawEvenHubDocumentStart); injectOnPageStarted is the fallback for
|
||||
* WebView versions that lack that API.
|
||||
*
|
||||
* An app can crash its renderer, or the system can kill it for memory. Unless
|
||||
* every WebView that renderer served handles that, WebView aborts the whole
|
||||
* process, taking Faceclaw down with it; so onRenderProcessGone retires the
|
||||
* affected WebView and reports it instead.
|
||||
*/
|
||||
class FaceclawEvenHubWebViewClient(
|
||||
private val rootDir: String?,
|
||||
@@ -93,6 +99,15 @@ class FaceclawEvenHubWebViewClient(
|
||||
}
|
||||
}
|
||||
|
||||
override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean {
|
||||
// Called on the main thread for each WebView the renderer served. This
|
||||
// one can't be used again: drop it, and the app shows as failed.
|
||||
Log.w(TAG, "renderer gone (crashed=${detail.didCrash()}) for $host")
|
||||
FaceclawEvenHubWebViewHost.getInstance().detach(view)
|
||||
listener.onRenderProcessGone(detail.didCrash())
|
||||
return true
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "FaceclawEvenHub"
|
||||
|
||||
|
||||
@@ -59,8 +59,8 @@ import java.util.HashMap
|
||||
* requestAnimationFrame) with JS queues fired by window.__fcTick(), and this
|
||||
* host ticks those on the main thread regardless of screen state. The tick
|
||||
* returns when the page next has work, so an idle page isn't evaluated at
|
||||
* 60Hz; work scheduled between ticks wakes the host through
|
||||
* FaceclawEvenHubJsBridge.wakeTimers. The main Looper keeps running under the
|
||||
* 60Hz; work scheduled between ticks wakes the host through the bridge's
|
||||
* "wake" message (FaceclawEvenHubJsBridge). The main Looper keeps running under the
|
||||
* foreground service, so the tick survives the screen turning off. (Matches the
|
||||
* official Even app's approach.)
|
||||
*
|
||||
@@ -105,8 +105,12 @@ class FaceclawEvenHubWebViewHost {
|
||||
* the page wakes it. It also re-ticks after IDLE_POLL_MS regardless, so a
|
||||
* lost evaluateJavascript callback (e.g. mid-navigation) or a page whose
|
||||
* wake didn't reach us stalls its timers for at most that long.
|
||||
*
|
||||
* The tick only runs in the app's own documents ([appCheck], a JS
|
||||
* expression): after a navigation the WebView may show another site.
|
||||
*/
|
||||
private inner class Ticker(private val web: WebView) : Runnable {
|
||||
private inner class Ticker(private val web: WebView, appCheck: String) : Runnable {
|
||||
private val tickJs = "if ($appCheck) { $TICK_JS }"
|
||||
private var inFlight = false
|
||||
private var wakePending = false
|
||||
private var stopped = false
|
||||
@@ -114,7 +118,7 @@ class FaceclawEvenHubWebViewHost {
|
||||
override fun run() {
|
||||
if (stopped) return
|
||||
inFlight = true
|
||||
web.evaluateJavascript(TICK_JS) { result -> onTicked(result) }
|
||||
web.evaluateJavascript(tickJs) { result -> onTicked(result) }
|
||||
schedule(IDLE_POLL_MS)
|
||||
}
|
||||
|
||||
@@ -278,8 +282,11 @@ class FaceclawEvenHubWebViewHost {
|
||||
(web.context as? MutableContextWrapper)?.baseContext = activity
|
||||
}
|
||||
|
||||
/** Add a WebView to the host, full-size and rendering, hidden behind the UI. */
|
||||
fun attach(activity: Activity, web: WebView) {
|
||||
/**
|
||||
* Add a WebView to the host, full-size and rendering, hidden behind the UI.
|
||||
* [appCheck] is a JS expression that is true only in the app's own documents.
|
||||
*/
|
||||
fun attach(activity: Activity, web: WebView, appCheck: String) {
|
||||
ensureOverlay(activity)
|
||||
rebaseContext(web, activity)
|
||||
web.visibility = View.VISIBLE
|
||||
@@ -301,7 +308,7 @@ class FaceclawEvenHubWebViewHost {
|
||||
}
|
||||
if (!webViews.contains(web)) webViews.add(web)
|
||||
if (!tickers.containsKey(web)) {
|
||||
val ticker = Ticker(web)
|
||||
val ticker = Ticker(web, appCheck)
|
||||
tickers[web] = ticker
|
||||
mainHandler.postDelayed(ticker, TICK_MS)
|
||||
}
|
||||
@@ -348,9 +355,9 @@ class FaceclawEvenHubWebViewHost {
|
||||
return shown
|
||||
}
|
||||
|
||||
/** Remove and destroy a WebView (its app is closing). */
|
||||
/** Remove and destroy a WebView (its app is closing, or its renderer is gone). Idempotent. */
|
||||
fun detach(web: WebView) {
|
||||
webViews.remove(web)
|
||||
if (!webViews.remove(web)) return
|
||||
tickers.remove(web)?.stop()
|
||||
stack?.removeView(web)
|
||||
web.destroy()
|
||||
|
||||
@@ -3,7 +3,7 @@ TARGETED_DEVICE_FAMILY = 1;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
|
||||
// Set IOS_TEAM_ID in build_paths.sh (or pass --teamId) to choose the signing team.
|
||||
OTHER_LDFLAGS = $(inherited) -framework CoreBluetooth -framework CoreLocation -framework CoreText -framework Speech -framework AVFoundation -framework WebKit -framework UniformTypeIdentifiers -framework ImageIO -framework EventKit
|
||||
OTHER_LDFLAGS = $(inherited) -framework CoreBluetooth -framework CoreLocation -framework CoreText -framework Speech -framework AVFoundation -framework WebKit -framework SafariServices -framework UniformTypeIdentifiers -framework ImageIO -framework EventKit
|
||||
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
#import <WebKit/WebKit.h>
|
||||
|
||||
/** One local or URL EvenHub runtime, retained by its TS session until its window closes. */
|
||||
@interface FaceclawEvenHubWebView : NSObject <WKScriptMessageHandler, WKNavigationDelegate, WKURLSchemeHandler>
|
||||
@interface FaceclawEvenHubWebView : NSObject <WKScriptMessageHandler, WKNavigationDelegate, WKUIDelegate, WKURLSchemeHandler>
|
||||
@property(nonatomic, copy) void (^eventHandler)(NSString *json);
|
||||
@property(nonatomic, copy) NSString *packageIdentifier;
|
||||
- (void)start:(NSString *)directory entrypoint:(NSString *)entrypoint script:(NSString *)script;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#import "FaceclawEvenHubWebView.h"
|
||||
#import <UIKit/UIKit.h>
|
||||
#import <SafariServices/SafariServices.h>
|
||||
#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
|
||||
#import <CommonCrypto/CommonDigest.h>
|
||||
|
||||
@@ -7,19 +8,49 @@
|
||||
@property(nonatomic) WKWebView *webView;
|
||||
@property(nonatomic) UIView *host;
|
||||
@property(nonatomic) UIButton *back;
|
||||
@property(nonatomic) UIButton *returnButton;
|
||||
@property(nonatomic) NSTimer *timer;
|
||||
@property(nonatomic) NSString *directory;
|
||||
@property(nonatomic) NSURL *remoteURL;
|
||||
@property(nonatomic) NSString *script;
|
||||
/** The app's start page. Only documents from its origin get the bridge. */
|
||||
@property(nonatomic) NSURL *startURL;
|
||||
/** The redirect_uri of a sign-in the app started; the provider's reply is finished inside the app. */
|
||||
@property(nonatomic) NSURL *returnURL;
|
||||
/** The main frame shows a page outside the app's origin (a sign-in page, a followed link). */
|
||||
@property(nonatomic) BOOL away;
|
||||
@property(nonatomic) BOOL committed;
|
||||
@property(nonatomic) BOOL ticking;
|
||||
@property(nonatomic) BOOL destroyed;
|
||||
@end
|
||||
|
||||
static NSInteger FCDefaultPort(NSString *scheme) {
|
||||
scheme = scheme.lowercaseString;
|
||||
return [scheme isEqual:@"https"] ? 443 : [scheme isEqual:@"http"] ? 80 : 0;
|
||||
}
|
||||
static BOOL FCIsWebURL(NSURL *url) {
|
||||
NSString *scheme = url.scheme.lowercaseString;
|
||||
return [scheme isEqual:@"http"] || [scheme isEqual:@"https"];
|
||||
}
|
||||
static BOOL FCSameOrigin(NSURL *origin, NSString *scheme, NSString *host, NSInteger port) {
|
||||
return origin && host.length && [scheme.lowercaseString isEqual:origin.scheme.lowercaseString] &&
|
||||
[host.lowercaseString isEqual:origin.host.lowercaseString] &&
|
||||
(port ?: FCDefaultPort(scheme)) == (origin.port.integerValue ?: FCDefaultPort(origin.scheme));
|
||||
}
|
||||
/** A newer navigation replaced this one, or the policy below cancelled it; the current page is unaffected. */
|
||||
static BOOL FCIsInterruption(NSError *error) {
|
||||
return ([error.domain isEqual:NSURLErrorDomain] && error.code == NSURLErrorCancelled) ||
|
||||
([error.domain isEqual:@"WebKitErrorDomain"] && error.code == 102); // FrameLoadInterruptedByPolicyChange
|
||||
}
|
||||
|
||||
@implementation FaceclawEvenHubWebView
|
||||
- (void)emit:(NSDictionary *)event {
|
||||
if (!_eventHandler || _destroyed) return;
|
||||
NSData *data = [NSJSONSerialization dataWithJSONObject:event options:0 error:nil];
|
||||
if (data) _eventHandler([[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
|
||||
}
|
||||
- (void)notice:(NSString *)message {
|
||||
[self emit:@{@"kind": @"notice", @"message": message.length > 4000 ? [message substringToIndex:4000] : message}];
|
||||
}
|
||||
- (void)start:(NSString *)directory entrypoint:(NSString *)entrypoint script:(NSString *)script {
|
||||
_directory = directory.stringByStandardizingPath.stringByResolvingSymlinksInPath;
|
||||
NSURLComponents *url = [NSURLComponents new];
|
||||
@@ -28,14 +59,14 @@
|
||||
}
|
||||
- (void)startURL:(NSString *)url script:(NSString *)script {
|
||||
NSURL *target = [NSURL URLWithString:url];
|
||||
if (!target.host.length || ![@[@"http", @"https"] containsObject:target.scheme.lowercaseString] || target.user || target.password) {
|
||||
if (!target.host.length || !FCIsWebURL(target) || target.user || target.password) {
|
||||
[self emit:@{@"kind": @"error", @"message": @"Invalid app URL."}]; return;
|
||||
}
|
||||
_remoteURL = target;
|
||||
[self startRequest:target script:script];
|
||||
}
|
||||
- (void)startRequest:(NSURL *)url script:(NSString *)script {
|
||||
if (_destroyed) return;
|
||||
_startURL = url; _script = script;
|
||||
WKWebViewConfiguration *config = [WKWebViewConfiguration new];
|
||||
// Isolate browser storage by package, retaining it across closing/reopening.
|
||||
// SDK storage also persists independently through the shared TS session.
|
||||
@@ -49,10 +80,9 @@
|
||||
}
|
||||
[config setURLSchemeHandler:self forURLScheme:@"faceclaw-ehpk"];
|
||||
[config.userContentController addScriptMessageHandler:self name:@"faceclaw"];
|
||||
[config.userContentController addUserScript:[[WKUserScript alloc] initWithSource:script
|
||||
injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES]];
|
||||
[self installScript:config.userContentController];
|
||||
_webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
|
||||
_webView.navigationDelegate = self;
|
||||
_webView.navigationDelegate = self; _webView.UIDelegate = self;
|
||||
_webView.accessibilityIdentifier = @"evenhub-webview";
|
||||
UIWindow *window = nil;
|
||||
for (UIScene *scene in UIApplication.sharedApplication.connectedScenes) {
|
||||
@@ -73,13 +103,21 @@
|
||||
[_back setTitle:@"Back to Faceclaw" forState:UIControlStateNormal];
|
||||
_back.accessibilityIdentifier = @"evenhub-back";
|
||||
[_back addTarget:self action:@selector(hideOnPhone) forControlEvents:UIControlEventTouchUpInside];
|
||||
[_host addSubview:_back]; _back.translatesAutoresizingMaskIntoConstraints = NO;
|
||||
// Shown only while the page is outside the app, e.g. an abandoned sign-in.
|
||||
_returnButton = [UIButton buttonWithType:UIButtonTypeSystem];
|
||||
[_returnButton setTitle:@"Return to app" forState:UIControlStateNormal];
|
||||
_returnButton.accessibilityIdentifier = @"evenhub-return";
|
||||
_returnButton.hidden = YES;
|
||||
[_returnButton addTarget:self action:@selector(returnToApp) forControlEvents:UIControlEventTouchUpInside];
|
||||
UIStackView *bar = [[UIStackView alloc] initWithArrangedSubviews:@[_back, _returnButton]];
|
||||
bar.distribution = UIStackViewDistributionFillEqually;
|
||||
[_host addSubview:bar]; bar.translatesAutoresizingMaskIntoConstraints = NO;
|
||||
[NSLayoutConstraint activateConstraints:@[
|
||||
[_back.topAnchor constraintEqualToAnchor:_host.safeAreaLayoutGuide.topAnchor],
|
||||
[_back.leadingAnchor constraintEqualToAnchor:_host.leadingAnchor],
|
||||
[_back.trailingAnchor constraintEqualToAnchor:_host.trailingAnchor],
|
||||
[_back.heightAnchor constraintEqualToConstant:44],
|
||||
[_webView.topAnchor constraintEqualToAnchor:_back.bottomAnchor],
|
||||
[bar.topAnchor constraintEqualToAnchor:_host.safeAreaLayoutGuide.topAnchor],
|
||||
[bar.leadingAnchor constraintEqualToAnchor:_host.leadingAnchor],
|
||||
[bar.trailingAnchor constraintEqualToAnchor:_host.trailingAnchor],
|
||||
[bar.heightAnchor constraintEqualToConstant:44],
|
||||
[_webView.topAnchor constraintEqualToAnchor:bar.bottomAnchor],
|
||||
[_webView.leadingAnchor constraintEqualToAnchor:_host.leadingAnchor],
|
||||
[_webView.trailingAnchor constraintEqualToAnchor:_host.trailingAnchor],
|
||||
[_webView.bottomAnchor constraintEqualToAnchor:_host.safeAreaLayoutGuide.bottomAnchor]
|
||||
@@ -92,7 +130,7 @@
|
||||
__weak typeof(self) weakSelf = self;
|
||||
_timer = [NSTimer timerWithTimeInterval:1.0 / 60 repeats:YES block:^(NSTimer *timer) {
|
||||
typeof(self) strongSelf = weakSelf;
|
||||
if (!strongSelf || strongSelf.destroyed || strongSelf.ticking) return;
|
||||
if (!strongSelf || strongSelf.destroyed || strongSelf.ticking || strongSelf.away) return;
|
||||
strongSelf.ticking = YES;
|
||||
[strongSelf.webView evaluateJavaScript:@"window.__fcTimerTick && window.__fcTimerTick(); window.__fcRafTick && window.__fcRafTick();" completionHandler:^(id result, NSError *error) {
|
||||
weakSelf.ticking = NO;
|
||||
@@ -101,8 +139,18 @@
|
||||
[NSRunLoop.mainRunLoop addTimer:_timer forMode:NSRunLoopCommonModes];
|
||||
[_webView loadRequest:[NSURLRequest requestWithURL:url]];
|
||||
}
|
||||
/** The bridge scripts run only in the app's own documents, never in pages it navigates to. */
|
||||
- (void)installScript:(WKUserContentController *)controller {
|
||||
NSData *start = [NSJSONSerialization dataWithJSONObject:_startURL.absoluteString options:NSJSONWritingFragmentsAllowed error:nil];
|
||||
NSString *source = [NSString stringWithFormat:@"if ((function (app) { return app.protocol === location.protocol && app.host === location.host; })(new URL(%@))) {\n%@\n}",
|
||||
[[NSString alloc] initWithData:start encoding:NSUTF8StringEncoding], _script];
|
||||
[controller removeAllUserScripts];
|
||||
[controller addUserScript:[[WKUserScript alloc] initWithSource:source
|
||||
injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES]];
|
||||
}
|
||||
- (void)evaluate:(NSString *)script {
|
||||
if (!_destroyed) [_webView evaluateJavaScript:script completionHandler:nil];
|
||||
// Host messages are for the app's documents; a page it navigated to must not receive them.
|
||||
if (!_destroyed && !_away) [_webView evaluateJavaScript:script completionHandler:nil];
|
||||
}
|
||||
- (void)showOnPhone {
|
||||
if (_destroyed) return;
|
||||
@@ -112,51 +160,152 @@
|
||||
[_host endEditing:YES]; [_host.superview sendSubviewToBack:_host]; _host.userInteractionEnabled = NO; _host.accessibilityElementsHidden = YES;
|
||||
[self emit:@{@"kind": @"hidden"}];
|
||||
}
|
||||
- (void)returnToApp {
|
||||
if (_destroyed) return;
|
||||
_returnURL = nil; [_webView loadRequest:[NSURLRequest requestWithURL:_startURL]];
|
||||
}
|
||||
- (void)destroy {
|
||||
if (_destroyed) return;
|
||||
_destroyed = YES; [_timer invalidate]; _timer = nil;
|
||||
[_webView stopLoading]; _webView.navigationDelegate = nil;
|
||||
[_webView stopLoading]; _webView.navigationDelegate = nil; _webView.UIDelegate = nil;
|
||||
[_webView.configuration.userContentController removeScriptMessageHandlerForName:@"faceclaw"];
|
||||
[_webView.configuration.userContentController removeAllUserScripts];
|
||||
[_host removeFromSuperview]; _host = nil; _back = nil; _webView = nil; _eventHandler = nil;
|
||||
[_host removeFromSuperview]; _host = nil; _back = nil; _returnButton = nil; _webView = nil; _eventHandler = nil;
|
||||
}
|
||||
- (BOOL)allowsURL:(NSURL *)url {
|
||||
if (!_remoteURL) return [url.scheme isEqual:@"faceclaw-ehpk"] && [url.host isEqual:@"app"];
|
||||
NSNumber *port = url.port ?: @([url.scheme.lowercaseString isEqual:@"https"] ? 443 : 80);
|
||||
NSNumber *remotePort = _remoteURL.port ?: @([_remoteURL.scheme.lowercaseString isEqual:@"https"] ? 443 : 80);
|
||||
return [url.scheme.lowercaseString isEqual:_remoteURL.scheme.lowercaseString] &&
|
||||
[url.host.lowercaseString isEqual:_remoteURL.host.lowercaseString] && [port isEqual:remotePort];
|
||||
- (BOOL)isAppURL:(NSURL *)url {
|
||||
return FCSameOrigin(_startURL, url.scheme, url.host, url.port.integerValue);
|
||||
}
|
||||
- (BOOL)isAppFrame:(WKFrameInfo *)frame {
|
||||
WKSecurityOrigin *origin = frame.securityOrigin;
|
||||
return frame.isMainFrame && FCSameOrigin(_startURL, origin.protocol, origin.host, origin.port);
|
||||
}
|
||||
/** An OAuth authorization request names where the provider replies. */
|
||||
- (void)rememberReturnURLFrom:(NSURL *)url {
|
||||
for (NSURLQueryItem *item in [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO].queryItems) {
|
||||
NSURL *target = [item.name isEqual:@"redirect_uri"] && item.value ? [NSURL URLWithString:item.value] : nil;
|
||||
// A redirect_uri on the app's own origin needs no help: the app handles it itself.
|
||||
if (FCIsWebURL(target) && target.host.length && ![self isAppURL:target]) _returnURL = target;
|
||||
}
|
||||
}
|
||||
- (BOOL)isReturnURL:(NSURL *)url {
|
||||
// NSURL.path drops a trailing slash, so ".../callback/" and ".../callback" match.
|
||||
NSString *path = url.path.length ? url.path : @"/", *returnPath = _returnURL.path.length ? _returnURL.path : @"/";
|
||||
return FCSameOrigin(_returnURL, url.scheme, url.host, url.port.integerValue) && [path isEqual:returnPath];
|
||||
}
|
||||
/** The app's start page carrying the provider's reply (its query and fragment). */
|
||||
- (void)loadAppWithResultOf:(NSURL *)url {
|
||||
NSURLComponents *result = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
|
||||
NSURLComponents *app = [NSURLComponents componentsWithURL:_startURL resolvingAgainstBaseURL:NO];
|
||||
if (result.percentEncodedQuery.length) app.percentEncodedQuery = app.percentEncodedQuery.length ?
|
||||
[NSString stringWithFormat:@"%@&%@", app.percentEncodedQuery, result.percentEncodedQuery] : result.percentEncodedQuery;
|
||||
if (result.percentEncodedFragment) app.percentEncodedFragment = result.percentEncodedFragment;
|
||||
NSURL *target = app.URL;
|
||||
_returnURL = nil;
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
if (!self.destroyed) [self.webView loadRequest:[NSURLRequest requestWithURL:target]];
|
||||
});
|
||||
}
|
||||
- (void)userContentController:(WKUserContentController *)controller didReceiveScriptMessage:(WKScriptMessage *)message {
|
||||
// Subframes and navigated third-party documents never receive host access.
|
||||
NSURL *url = message.frameInfo.request.URL;
|
||||
if (!message.frameInfo.isMainFrame || ![self allowsURL:url]) return;
|
||||
// Only the app's own main frame gets host access: not subframes, nor pages the app navigated to.
|
||||
if (![self isAppFrame:message.frameInfo]) return;
|
||||
if ([message.body isKindOfClass:NSDictionary.class]) [self emit:message.body];
|
||||
}
|
||||
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)action decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
|
||||
NSURL *url = action.request.URL;
|
||||
BOOL allowed = [self allowsURL:url] && action.targetFrame.isMainFrame;
|
||||
if (!allowed && action.targetFrame.isMainFrame)
|
||||
[self emit:@{@"kind": @"error", @"message": @"Navigation outside the app origin is blocked. Open the destination as a separate app URL."}];
|
||||
decisionHandler(allowed ? WKNavigationActionPolicyAllow : WKNavigationActionPolicyCancel);
|
||||
NSString *scheme = url.scheme.lowercaseString;
|
||||
// A new window (target=_blank, window.open): createWebView below opens it outside the app.
|
||||
if (!action.targetFrame) { decisionHandler(WKNavigationActionPolicyAllow); return; }
|
||||
// Subframes load as in a browser; they never get the bridge.
|
||||
if (!action.targetFrame.isMainFrame) {
|
||||
BOOL allowed = FCIsWebURL(url) || [self isAppURL:url] || [@[@"about", @"data", @"blob"] containsObject:scheme];
|
||||
decisionHandler(allowed ? WKNavigationActionPolicyAllow : WKNavigationActionPolicyCancel); return;
|
||||
}
|
||||
if ([self isAppURL:url]) { _returnURL = nil; decisionHandler(WKNavigationActionPolicyAllow); return; }
|
||||
if (FCIsWebURL(url) && !_committed && !_directory.length) {
|
||||
// The app URL redirected before anything loaded: the app lives where it lands. The
|
||||
// script update reaches the web process ahead of the policy reply.
|
||||
_startURL = url; [self installScript:webView.configuration.userContentController];
|
||||
decisionHandler(WKNavigationActionPolicyAllow); return;
|
||||
}
|
||||
if (_returnURL && [self isReturnURL:url]) {
|
||||
// A sign-in provider replying: finish in the app rather than at the page the redirect_uri names.
|
||||
decisionHandler(WKNavigationActionPolicyCancel); [self loadAppWithResultOf:url]; return;
|
||||
}
|
||||
if (!FCIsWebURL(url)) {
|
||||
[self notice:[NSString stringWithFormat:@"Blocked navigation to a %@: URL.", scheme ?: @"schemeless"]];
|
||||
decisionHandler(WKNavigationActionPolicyCancel); return;
|
||||
}
|
||||
// Leaving the app's origin. Such pages never get the bridge; "Return to app" leads back.
|
||||
if ([self isAppFrame:action.sourceFrame]) [self rememberReturnURLFrom:url];
|
||||
decisionHandler(WKNavigationActionPolicyAllow);
|
||||
}
|
||||
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
|
||||
_committed = YES; _away = ![self isAppURL:webView.URL]; _returnButton.hidden = !_away;
|
||||
}
|
||||
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
|
||||
[self emit:@{@"kind": @"loaded"}];
|
||||
if (!_away) [self emit:@{@"kind": @"loaded"}];
|
||||
}
|
||||
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
|
||||
[self emit:@{@"kind": @"error", @"message": error.localizedDescription}];
|
||||
if (!FCIsInterruption(error)) [self emit:@{@"kind": @"error", @"message": error.localizedDescription}];
|
||||
}
|
||||
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
|
||||
[self emit:@{@"kind": @"error", @"message": error.localizedDescription}];
|
||||
if (!FCIsInterruption(error)) [self emit:@{@"kind": @"error", @"message": error.localizedDescription}];
|
||||
}
|
||||
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
|
||||
[self emit:@{@"kind": @"error", @"message": @"The app's web process ended. Close and reopen the app."}];
|
||||
[self emit:@{@"kind": @"error", @"fatal": @YES, @"message": @"The app's web process ended. Close and reopen the app."}];
|
||||
}
|
||||
/** What to present over, only while the app's phone UI is shown and not mid-transition. */
|
||||
- (UIViewController *)presenter {
|
||||
if (_destroyed || !_host.userInteractionEnabled) return nil;
|
||||
UIViewController *controller = _host.window.rootViewController;
|
||||
while (controller.presentedViewController) controller = controller.presentedViewController;
|
||||
return controller.transitionCoordinator ? nil : controller;
|
||||
}
|
||||
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)action windowFeatures:(WKWindowFeatures *)windowFeatures {
|
||||
NSURL *url = action.request.URL;
|
||||
UIViewController *presenter = FCIsWebURL(url) ? [self presenter] : nil;
|
||||
if (presenter) [presenter presentViewController:[[SFSafariViewController alloc] initWithURL:url] animated:YES completion:nil];
|
||||
else [self notice:[NSString stringWithFormat:@"Did not open a window for a %@: URL.", url.scheme ?: @"schemeless"]];
|
||||
return nil;
|
||||
}
|
||||
// JavaScript dialogs. WebKit requires each completion handler to run exactly once, so a
|
||||
// dialog that cannot be shown (the app is hidden) completes at once with its default.
|
||||
- (UIAlertController *)dialog:(NSString *)message {
|
||||
if ([self presenter]) return [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
|
||||
[self notice:[@"Dialog while hidden: " stringByAppendingString:message ?: @""]];
|
||||
return nil;
|
||||
}
|
||||
- (BOOL)presentDialog:(UIAlertController *)alert {
|
||||
if (!alert) return NO;
|
||||
[[self presenter] presentViewController:alert animated:YES completion:nil];
|
||||
return alert.presentingViewController != nil;
|
||||
}
|
||||
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
|
||||
UIAlertController *alert = [self dialog:message];
|
||||
[alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { completionHandler(); }]];
|
||||
if (![self presentDialog:alert]) completionHandler();
|
||||
}
|
||||
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
|
||||
UIAlertController *alert = [self dialog:message];
|
||||
[alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { completionHandler(NO); }]];
|
||||
[alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { completionHandler(YES); }]];
|
||||
if (![self presentDialog:alert]) completionHandler(NO);
|
||||
}
|
||||
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString *))completionHandler {
|
||||
UIAlertController *alert = [self dialog:prompt];
|
||||
[alert addTextFieldWithConfigurationHandler:^(UITextField *field) { field.text = defaultText; }];
|
||||
__weak UIAlertController *weakAlert = alert;
|
||||
[alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { completionHandler(nil); }]];
|
||||
[alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
|
||||
completionHandler(weakAlert.textFields.firstObject.text ?: @"");
|
||||
}]];
|
||||
if (![self presentDialog:alert]) completionHandler(nil);
|
||||
}
|
||||
- (void)webView:(WKWebView *)webView startURLSchemeTask:(id<WKURLSchemeTask>)task {
|
||||
NSURL *url = task.request.URL;
|
||||
NSString *relative = [url.path stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"/"]];
|
||||
NSString *file = [[_directory stringByAppendingPathComponent:relative] stringByStandardizingPath].stringByResolvingSymlinksInPath;
|
||||
BOOL allowed = !_destroyed && _directory.length && !_remoteURL && [url.host isEqual:@"app"] &&
|
||||
BOOL allowed = !_destroyed && _directory.length && [url.host isEqual:@"app"] &&
|
||||
[file hasPrefix:[_directory stringByAppendingString:@"/"]];
|
||||
NSData *data = allowed ? [NSData dataWithContentsOfFile:file options:NSDataReadingMappedIfSafe error:nil] : nil;
|
||||
NSString *ext = file.pathExtension.lowercaseString;
|
||||
|
||||
Reference in new issue
Block a user