Fixes to EvenHub webview handling

This commit is contained in:
James Babcock committed 2026-10-16 18:22:35 -07:00
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()
+1 -1
View File
@@ -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;
+183 -34
View File
@@ -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;
+3
View File
@@ -19,6 +19,9 @@
* iOS: Add missing EvenHub icons on the phone home screen
* Fix a bug where album art and track display could get out of sync if you advance twice quickly
* Fix a bug where EvenHub searches with spaces in the search term would fail
* Crashes in a webview renderer can no longer take down the rest of the app
* EvenHub app localstorage is now partitioned by app
* Fix issues that would prevent sign-in to EvenHub apps that rely on cross-domain navigation
## 0.8.3 - 2026-10-10
+16 -3
View File
@@ -487,13 +487,21 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
this.webViewHandle = handle;
}
webViewFailed(message: string): void {
/**
* A WebView load failed. Once the app has loaded, a failed or blocked
* navigation leaves its page running, so only a failure before then (or one
* the host marks `fatal`) replaces the glasses window with the error.
*/
webViewFailed(message: string, fatal = false): void {
if (this.closed) return;
this.loadError = message; this.log(`evenhub: ${message}`); this.windowHooks?.requestRender();
this.log(`evenhub: ${message}`);
if (this.launchContextPushed && !fatal) return;
this.loadError = message; this.windowHooks?.requestRender();
}
/** The WebView finished loading the app: push the one-shot launch context. */
webViewLoaded(): void {
if (this.loadError) { this.loadError = ''; this.windowHooks?.requestRender(); }
if (this.launchContextPushed) return;
this.launchContextPushed = true;
// Launched to drive the glasses (from the on-glasses file browser), so
@@ -1018,7 +1026,12 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
}
private storageKey(key: string): string {
return `evenhub:${this.manifest.packageId}:ls:${key}`;
// The package ID must end at the first ':' so that no other package can
// reach this one's keys (manifest IDs are unvalidated: package "a" asking
// for key "b:ls:c" must not read package "a:ls:b"'s "c"). IDs containing
// ':' or '%' are encoded, so they can't collide with the plain IDs either.
const id = this.manifest.packageId;
return `evenhub:${/[:%]/.test(id) ? encodeURIComponent(id) : id}:ls:${key}`;
}
// ----- pushes (host -> web) -----
+3 -2
View File
@@ -32,9 +32,10 @@ export function createEvenHubWebView(session: EvenHubSession): EvenHubWebView {
if (event.kind === 'call' && typeof event.name === 'string' && typeof event.args === 'string' && Number.isSafeInteger(event.id))
session.handleBridgeCall(event.name, event.args, event.id)
else if (event.kind === 'loaded') session.webViewLoaded()
else if (event.kind === 'error') session.webViewFailed(String(event.message))
else if (event.kind === 'error') session.webViewFailed(String(event.message), event.fatal === true)
else if (event.kind === 'hidden') { const close = onClose; onClose = null; close?.() }
else if (event.kind === 'console') console.log(`[evenhub:${session.manifest.name}] ${event.message}`)
// 'notice': host-side events such as a blocked navigation, logged with the app's console.
else if (event.kind === 'console' || event.kind === 'notice') console.log(`[evenhub:${session.manifest.name}] ${event.message}`)
} catch (error) { console.warn(`EvenHub bridge: ${error}`) }
}
// Defer loading until manager.ts has attached the session/window handles.
+68 -18
View File
@@ -15,6 +15,11 @@
* the offline serving entirely and loads that URL from the network; the shim
* is registered as a document-start script instead of being spliced into the
* served HTML.
*
* The app can navigate its WebView to other sites, so host access is tied to
* the app's origin: the bridge port is injected only into the app's own frames
* (FaceclawEvenHubJsBridge), and every script the host runs in the WebView is
* guarded by an origin check.
*/
import { Application, Utils } from "@nativescript/core";
import { EVENHUB_BRIDGE_INJECT_SCRIPT, buildFaceclawExtensionsScript, type EvenHubSession } from "./session";
@@ -34,19 +39,40 @@ export type EvenHubWebView = {
native: unknown;
};
/** A distinct (fake, intercepted) https origin per app isolates web storage. */
function originHost(session: EvenHubSession): string {
const safe = session.manifest.packageId.toLowerCase().replace(/[^a-z0-9.-]/g, "-");
return `${safe}.evenhub.invalid`;
/**
* Wraps the bridge port (window.__faceclawEvenHubPort, which WebView injects
* only into the app's own frames) as the window.__faceclawEvenHub interface
* the bridge shim and the extensions call.
*/
export const ANDROID_EVENHUB_TRANSPORT_SCRIPT = `
(function () {
var port = window.__faceclawEvenHubPort;
if (!port || window.__faceclawEvenHub) return;
window.__faceclawEvenHub = {
postMessage: function (name, args, id) { port.postMessage(JSON.stringify(['call', String(name), String(args), id])); },
wakeTimers: function () { port.postMessage('["wake"]'); }
};
})();
`;
/** A JS expression that is true only in a document from `startUrl`'s origin. */
export function appOriginCheck(startUrl: string): string {
return `(function (app) { return app.protocol === location.protocol && app.host === location.host; })(new URL(${JSON.stringify(startUrl)}))`;
}
/** `js`, run only when the WebView's document is from `startUrl`'s origin. */
export function guardToAppOrigin(startUrl: string, js: string): string {
return `if (${appOriginCheck(startUrl)}) {\n${js}\n}`;
}
/**
* The allowed-origin rule for a remote app's document-start script: the
* loaded URL's own origin, so the shim isn't handed to third-party frames.
* A distinct (fake, intercepted) https origin per app. The per-app profile is
* what keeps storage apart; without one, this still separates origin-scoped
* storage, though not cookies scoped to the shared evenhub.invalid domain.
*/
function originRule(url: string): string {
const match = /^(https?:\/\/[^/?#]+)/i.exec(url);
return match ? match[1]! : "*";
function originHost(session: EvenHubSession): string {
const safe = session.manifest.packageId.toLowerCase().replace(/[^a-z0-9.-]/g, "-");
return `${safe}.evenhub.invalid`;
}
/**
@@ -59,12 +85,20 @@ export function createEvenHubWebView(session: EvenHubSession): EvenHubWebView {
// A mutable wrapper, so the host can re-point the WebView at a recreated
// activity (see FaceclawEvenHubWebViewHost).
const webView = new com.faceclaw.app.FaceclawEvenHubWebView(new android.content.MutableContextWrapper(context));
// The app's own WebView profile, so its browser storage (and that of sites it
// navigates to) is separate from every other app's. This must come before
// any other use of the WebView.
if (!com.faceclaw.app.FaceclawEvenHubProfile.apply(webView, session.manifest.packageId)) {
console.warn(`evenhub: this WebView can't separate profiles; ${session.manifest.packageId} shares browser storage with other apps`);
}
const settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDomStorageEnabled(true);
settings.setAllowFileAccess(false);
settings.setMediaPlaybackRequiresUserGesture(false);
// Set once the renderer is gone: the WebView is destroyed and must not be used.
let gone = false;
const listener = new com.faceclaw.app.FaceclawEvenHubListener({
onEvenAppMessage: (handlerName: string, argsJson: string, callId: number) => {
session.handleBridgeCall(String(handlerName), String(argsJson), Number(callId));
@@ -72,17 +106,31 @@ export function createEvenHubWebView(session: EvenHubSession): EvenHubWebView {
onPageFinished: () => {
session.webViewLoaded();
},
onRenderProcessGone: (crashed: boolean) => {
gone = true;
session.webViewFailed(crashed
? "The app's web page crashed. Close and reopen the app."
: "Android stopped the app's web page to free memory. Close and reopen the app.", true);
},
});
const remoteUrl = session.remoteUrl;
// Remote apps load from their own server, so nothing is intercepted and the
// fake per-app origin is unused.
const host = remoteUrl ? "" : originHost(session);
// Stock bridge shim first, then the Faceclaw extensions global (both at
// document-start, before any app JS).
const injectScript = EVENHUB_BRIDGE_INJECT_SCRIPT + buildFaceclawExtensionsScript(`Faceclaw/${FACECLAW_VERSION}`);
const documentStartInstalled = remoteUrl
? com.faceclaw.app.FaceclawEvenHubDocumentStart.install(webView, injectScript, originRule(remoteUrl)) === true
const startUrl = remoteUrl || `https://${host}/${session.manifest.entrypoint}`;
const originRule: string | null = com.faceclaw.app.FaceclawEvenHubJsBridge.originRule(startUrl);
const appCheck = appOriginCheck(startUrl);
const guarded = (js: string) => guardToAppOrigin(startUrl, js);
// The transport, the stock bridge shim, then the Faceclaw extensions global
// (all at document-start, before any app JS).
const injectScript = guarded(ANDROID_EVENHUB_TRANSPORT_SCRIPT + EVENHUB_BRIDGE_INJECT_SCRIPT +
buildFaceclawExtensionsScript(`Faceclaw/${FACECLAW_VERSION}`));
const bridgeError: string | null = originRule
? com.faceclaw.app.FaceclawEvenHubJsBridge.install(webView, originRule, listener)
: `Not a web address: ${startUrl}`;
const documentStartInstalled = remoteUrl && originRule
? com.faceclaw.app.FaceclawEvenHubDocumentStart.install(webView, injectScript, originRule) === true
: false;
webView.setWebViewClient(
new com.faceclaw.app.FaceclawEvenHubWebViewClient(
@@ -95,20 +143,22 @@ export function createEvenHubWebView(session: EvenHubSession): EvenHubWebView {
listener,
),
);
webView.addJavascriptInterface(new com.faceclaw.app.FaceclawEvenHubJsBridge(listener), "__faceclawEvenHub");
// Surface the app's console in logcat (tag FaceclawEvenHubConsole).
webView.setWebChromeClient(new com.faceclaw.app.FaceclawEvenHubChromeClient());
const nativeHost = com.faceclaw.app.FaceclawEvenHubWebViewHost.getInstance();
nativeHost.attach(activity, webView);
webView.loadUrl(remoteUrl || `https://${host}/${session.manifest.entrypoint}`);
nativeHost.attach(activity, webView, appCheck);
// Without the bridge the app could only hang waiting for it.
if (bridgeError) session.webViewFailed(String(bridgeError), true);
else webView.loadUrl(startUrl);
return {
native: webView,
evaluateJs: (js: string) => {
if (gone) return;
try {
webView.evaluateJavascript(js, null);
webView.evaluateJavascript(guarded(js), null);
} catch (error) {
console.warn(`evenhub evaluateJs failed: ${error}`);
}
@@ -15,4 +15,10 @@ interface FaceclawEvenHubListener {
/** The WebView finished loading the app's page. */
fun onPageFinished(url: String?): Unit
/**
* The WebView's renderer process is gone: it [crashed], or the system killed it to reclaim
* memory. The WebView has already been detached and destroyed, so the app's page is lost.
*/
fun onRenderProcessGone(crashed: Boolean): Unit
}
+11
View File
@@ -37,3 +37,14 @@ intervals and animation callbacks still fire, and cancelled timers stay cancelle
A short UIKit background task keeps the test process running without glasses.
This covers the ticker's background behavior; sustained execution with BLE and a
locked physical phone still requires device testing.
The native Android EvenHub probe runs on a booted emulator or attached device:
node tests/android-evenhub-native.cjs [adb-serial]
It compiles the production EvenHub WebView classes into an isolated APK (with the
Kotlin compiler and AndroidX artifacts a prior `./build.sh` cached), installs it,
and checks per-package WebView profiles, that the bridge reaches only the app's
own main frame (not its iframes or pages it navigates to), that host scripts and
timer ticks stay out of other sites, and that a renderer crash leaves the process
running.
+169
View File
@@ -0,0 +1,169 @@
// Run the production Android EvenHub WebView classes in an isolated probe APK on
// an emulator or device, no glasses: node tests/android-evenhub-native.cjs [adb-serial]
// Checks the per-package profiles, the origin-locked bridge and the renderer-crash
// handling against a real WebView. Needs ANDROID_HOME, a JDK, and a prior ./build.sh
// (for the cached Kotlin compiler and AndroidX artifacts).
const http = require('node:http');
const { execFileSync } = require('node:child_process');
const fs = require('node:fs'), path = require('node:path'), os = require('node:os');
const { loader } = require('./helpers/load-typescript.cjs');
const { newestArtifact, kotlinCompiler } = require('./helpers/kotlin-compiler.cjs');
const root = path.resolve(__dirname, '..');
const sdk = process.env.ANDROID_HOME || path.join(os.homedir(), 'Library/Android/sdk');
const newest = dir => fs.readdirSync(dir).filter(name => /^\d/.test(name)).sort((a, b) => a.localeCompare(b, undefined, { numeric: true })).at(-1);
const buildTools = path.join(sdk, 'build-tools', newest(path.join(sdk, 'build-tools')));
const androidJar = path.join(sdk, 'platforms', fs.readdirSync(path.join(sdk, 'platforms')).filter(name => /^android-\d+$/.test(name))
.sort((a, b) => a.localeCompare(b, undefined, { numeric: true })).at(-1), 'android.jar');
const javaBin = process.env.JAVA_HOME ? path.join(process.env.JAVA_HOME, 'bin') : '';
const env = { ...process.env, PATH: [javaBin, process.env.PATH].filter(Boolean).join(path.delimiter) };
const run = (file, args, options = {}) => execFileSync(file, args, { cwd: root, env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], ...options });
const serial = process.argv[2] || run('adb', ['devices']).split('\n').slice(1).map(line => line.split('\t')).find(([, state]) => state === 'device')?.[0];
if (!serial) throw new Error('No adb device or emulator is attached.');
const adb = (...args) => run('adb', ['-s', serial, ...args]);
const work = fs.mkdtempSync(path.join(os.tmpdir(), 'faceclaw-android-evenhub-probe-'));
// The scripts webview.ts builds, from the production sources.
const session = fs.readFileSync(path.join(root, 'app/apps/evenhub/session.ts'), 'utf8');
const shim = session.match(/export const EVENHUB_BRIDGE_INJECT_SCRIPT = `([\s\S]*?)`;/)[1];
const webview = loader({}, { '@nativescript/core': {}, './session': {}, '../../version': {} })('app/apps/evenhub/webview.ts');
const reports = [];
const server = http.createServer((request, response) => {
const url = new URL(request.url, 'http://probe');
const page = body => { response.setHeader('Content-Type', 'text/html'); response.end(`<!doctype html><html><head></head><body>${body}</body></html>`); };
if (url.pathname === '/report') { reports.push(url.search.slice(1)); response.end(); return; }
if (url.pathname === '/cookie') { reports.push(`cookie:${url.searchParams.get('app')}=${/\bthird=A\b/.test(request.headers.cookie ?? '')}`); page('cookie'); return; }
// A cross-origin iframe inside the app, and a third-party page the app navigates to.
if (url.pathname === '/xframe') { page(`<script>new Image().src = '/report?xframe=' + typeof window.__faceclawEvenHubPort + ',' + typeof window.__faceclawEvenHub</script>`); return; }
if (url.pathname === '/third') {
page(`<script>
var port = window.__faceclawEvenHubPort;
new Image().src = '/report?third=' + typeof port + ',' + typeof window.__faceclawEvenHub + ',' + typeof window.flutter_inappwebview;
if (port) port.postMessage(JSON.stringify(['call', 'probe', '["UNTRUSTED"]', 0]));
document.cookie = 'third=A; max-age=3600';
window.__fcTick = function () { new Image().src = '/report?tick=leak'; return 16; };
</script>`);
return;
}
if (url.pathname === '/remote/') { page(`<script>flutter_inappwebview.callHandler('probe', 'remote')</script>`); return; }
response.writeHead(404); response.end();
});
server.listen(0, '127.0.0.1', async () => {
try {
const port = server.address().port;
adb('reverse', `tcp:${port}`, `tcp:${port}`);
const third = `http://127.0.0.1:${port}`;
const start = { A: 'https://probe.a.evenhub.invalid/index.html', B: 'https://probe.b.evenhub.invalid/index.html',
A2: 'https://probe.a.evenhub.invalid/index.html', R: `http://localhost:${port}/remote/` };
const assets = path.join(work, 'assets'), dist = path.join(assets, 'dist');
fs.mkdirSync(dist, { recursive: true });
const checks = {};
for (const [tag, url] of Object.entries(start)) {
checks[tag] = webview.appOriginCheck(url);
fs.writeFileSync(path.join(assets, `inject-${tag}.js`), webview.guardToAppOrigin(url, webview.ANDROID_EVENHUB_TRANSPORT_SCRIPT + shim));
}
fs.writeFileSync(path.join(assets, 'config.json'), JSON.stringify({ third, start, checks }));
fs.writeFileSync(path.join(dist, 'index.html'), `<!doctype html><html><head><title>probe</title></head><body><script>
var call = function (name) { return flutter_inappwebview.callHandler('probe', name); };
call('early').then(function () { return call('resolved'); });
var same = document.createElement('iframe'); same.src = '/frame.html'; document.body.appendChild(same);
var cross = document.createElement('iframe'); cross.src = '${third}/xframe'; document.body.appendChild(cross);
</script></body></html>`);
// The app's own subframe: it gets the port, but the host ignores subframes.
fs.writeFileSync(path.join(dist, 'frame.html'), `<!doctype html><html><head></head><body><script>
new Image().src = '${third}/report?sameframe=' + typeof window.__faceclawEvenHubPort;
flutter_inappwebview.callHandler('probe', 'FRAME');
</script></body></html>`);
// Link the manifest, assets and androidx.core's resources (generating its R
// class, as Gradle would), compile the production classes with the probe,
// then dex, package and sign.
const compiler = kotlinCompiler();
if (!compiler) throw new Error('Kotlin compiler not in the Gradle cache; run ./build.sh once.');
const aar = (group, artifact) => {
const file = newestArtifact(group, artifact, 'aar');
if (!file) throw new Error(`${group}:${artifact} not in the Gradle cache; run ./build.sh once.`);
const out = path.join(work, artifact);
run('unzip', ['-q', '-o', file, 'classes.jar', 'res/*', '-d', out]);
return out;
};
const webkit = aar('androidx.webkit', 'webkit'), core = aar('androidx.core', 'core');
const libraries = [path.join(webkit, 'classes.jar'), path.join(core, 'classes.jar'),
newestArtifact('androidx.collection', 'collection-jvm'), newestArtifact('androidx.annotation', 'annotation-jvm'),
newestArtifact('org.jspecify', 'jspecify')];
if (libraries.some(file => !file)) throw new Error('AndroidX artifacts missing from the Gradle cache; run ./build.sh once.');
fs.writeFileSync(path.join(work, 'AndroidManifest.xml'), `<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.faceclaw.evenhubprobe">
<uses-permission android:name="android.permission.INTERNET"/>
<application android:label="EvenHubProbe" android:usesCleartextTraffic="true">
<activity android:name=".ProbeActivity" android:exported="true"/>
</application>
</manifest>`);
const aapt2 = path.join(buildTools, 'aapt2'), coreResources = path.join(work, 'core-res.zip'), generated = path.join(work, 'gen');
run(aapt2, ['compile', '--dir', path.join(core, 'res'), '-o', coreResources]);
const unsigned = path.join(work, 'unsigned.apk'), aligned = path.join(work, 'aligned.apk'), signed = path.join(work, 'probe.apk');
run(aapt2, ['link', '-o', unsigned, '-I', androidJar, '--manifest', path.join(work, 'AndroidManifest.xml'), '-A', assets,
'-R', coreResources, '--auto-add-overlay', '--extra-packages', 'androidx.core', '--java', generated,
'--min-sdk-version', '24', '--target-sdk-version', '35']);
const app = 'App_Resources/Android/src/main/java/com/faceclaw/app';
const shared = 'native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app';
fs.writeFileSync(path.join(work, 'Platform.kt'), 'package com.faceclaw.app\n' +
'fun fileExists(path: String): Boolean = java.io.File(path).exists()\n' +
'internal fun readFileData(path: String): ByteArray = java.io.File(path).readBytes()\n');
const classes = path.join(work, 'classes');
run('java', ['-cp', compiler.classpath, 'org.jetbrains.kotlin.cli.jvm.K2JVMCompiler', '-no-stdlib', '-no-reflect', '-nowarn',
'-cp', [androidJar, ...libraries, compiler.stdlib].join(path.delimiter), '-d', classes,
...['WebView', 'WebViewClient', 'WebViewHost', 'JsBridge', 'Profile', 'DocumentStart', 'ChromeClient'].map(name => `${app}/FaceclawEvenHub${name}.kt`),
`${shared}/callbacks/FaceclawEvenHubListener.kt`, `${shared}/evenhub/EvenHubAssetServer.kt`,
path.join(work, 'Platform.kt'), 'tests/native/AndroidEvenHubProbe.kt'], { maxBuffer: 64 << 20 });
const rSources = run('find', [generated, '-name', 'R.java']).trim().split('\n');
run('javac', ['-nowarn', '-cp', androidJar, '-d', classes, ...rSources]);
const dex = path.join(work, 'dex');
fs.mkdirSync(dex);
run('jar', ['cf', path.join(work, 'probe.jar'), '-C', classes, '.']);
run(path.join(buildTools, 'd8'), ['--min-api', '24', '--lib', androidJar, '--output', dex,
path.join(work, 'probe.jar'), compiler.stdlib, ...libraries], { maxBuffer: 64 << 20 });
run('zip', ['-j', unsigned, ...fs.readdirSync(dex).map(name => path.join(dex, name))]);
run(path.join(buildTools, 'zipalign'), ['-p', '-f', '4', unsigned, aligned]);
run(path.join(buildTools, 'apksigner'), ['sign', '--ks', path.join(os.homedir(), '.android/debug.keystore'), '--ks-pass', 'pass:android',
'--key-pass', 'pass:android', '--ks-key-alias', 'androiddebugkey', '--out', signed, aligned]);
try { adb('uninstall', 'com.faceclaw.evenhubprobe'); } catch { /* not installed */ }
adb('install', '-t', signed);
adb('logcat', '-c');
adb('shell', 'am', 'start', '-W', '-n', 'com.faceclaw.evenhubprobe/.ProbeActivity');
let result = null;
const deadline = Date.now() + 40000;
while (!result) {
if (Date.now() > deadline) throw new Error(`Probe timed out (did the process die?); artifacts: ${work}\n${adb('logcat', '-d', '-b', 'crash')}`);
await new Promise(resolve => setTimeout(resolve, 500));
const line = adb('logcat', '-d', '-s', 'EHPROBE:I').split('\n').find(text => text.includes('RESULT '));
if (line) result = JSON.parse(line.slice(line.indexOf('RESULT ') + 7));
}
const seen = new Set(result.seen);
const alive = adb('shell', 'pidof', 'com.faceclaw.evenhubprobe').trim() !== '';
const failures = [];
const expect = (ok, what) => { if (!ok) failures.push(what); };
for (const tag of Object.keys(start)) expect(seen.has(`${tag}:profile=true`), `${tag} has its own profile`);
for (const name of ['A:early', 'A:resolved', 'B:early', 'A2:early', 'R:remote']) expect(seen.has(name), `bridge round trip ${name}`);
expect(![...seen].some(name => name.endsWith(':bridge-error')), 'bridge installs');
expect(!seen.has('A:FRAME'), 'the app\'s subframe is ignored');
expect(!seen.has('A:UNTRUSTED'), 'the third-party page cannot post to the host');
expect(reports.includes('third=undefined,undefined,undefined'), 'the third-party page gets no port, bridge or shim');
expect(reports.length && reports.filter(r => r.startsWith('xframe=')).every(r => r === 'xframe=undefined,undefined'), 'cross-origin iframes get no port or bridge');
expect(!reports.includes('eval=leak'), 'host scripts do not run in the third-party page');
expect(!reports.includes('tick=leak'), 'host ticks do not run in the third-party page');
expect(reports.includes('cookie:B=false'), 'another package cannot see A\'s third-party cookie');
expect(reports.includes('cookie:A2=true'), 'A\'s profile keeps its cookie');
expect(seen.has('R:gone'), 'the crashed renderer is reported');
expect(alive, 'the process survives the renderer crash');
console.log(JSON.stringify({ work, serial, seen: [...seen], reports, alive, failures }));
if (failures.length) process.exitCode = 1;
} catch (error) {
console.error(error.stderr?.toString() || '', error); process.exitCode = 1;
} finally {
try { adb('reverse', '--remove-all'); } catch { /* best effort */ }
server.closeAllConnections(); server.close();
}
});
+89
View File
@@ -0,0 +1,89 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const vm = require('node:vm');
const { loader } = require('./helpers/load-typescript.cjs');
// Loads webview.ts against recording doubles of the Android/Kotlin classes.
function androidWebView({ remoteUrl = '', bridgeError = null } = {}) {
const calls = [], evaluated = [];
let listener, attachedCheck;
const ignore = new Proxy({}, { get: () => () => {} });
class WebView {
constructor() { calls.push('construct'); }
getSettings() { calls.push('settings'); return ignore; }
setWebViewClient() {} setWebChromeClient() {}
addJavascriptInterface() { calls.push('addJavascriptInterface'); }
evaluateJavascript(js) { evaluated.push(js); }
loadUrl(url) { calls.push(`load ${url}`); }
}
const app = {
FaceclawEvenHubWebView: WebView,
FaceclawEvenHubProfile: { apply: (web, packageId) => { calls.push(`profile ${packageId}`); return web instanceof WebView; } },
FaceclawEvenHubListener: class { constructor(impl) { listener = impl; } },
FaceclawEvenHubJsBridge: {
originRule: url => /^https?:\/\/[^/]+/.exec(url)[0],
install: (_web, rule) => { calls.push(`bridge ${rule}`); return bridgeError; },
},
FaceclawEvenHubWebViewClient: class {}, FaceclawEvenHubChromeClient: class {},
FaceclawEvenHubDocumentStart: { install: (_web, _script, rule) => { calls.push(`document-start ${rule}`); return true; } },
FaceclawEvenHubWebViewHost: { getInstance: () => ({ attach(_activity, _web, check) { attachedCheck = check; }, detach() { calls.push('detach'); } }) },
};
const load = loader({ com: { faceclaw: { app } }, android: { content: { MutableContextWrapper: class {} } }, java: {} }, {
'@nativescript/core': { Application: { android: { foregroundActivity: {} } }, Utils: {} },
'./session': { EVENHUB_BRIDGE_INJECT_SCRIPT: '', buildFaceclawExtensionsScript: () => '' }, '../../version': { FACECLAW_VERSION: 'test' },
});
const failures = [];
const session = { manifest: { packageId: 'com.example.app', entrypoint: 'index.html', name: 'Example' }, distDir: '/dist', remoteUrl,
webViewFailed: (message, fatal) => failures.push([message, fatal]), webViewLoaded() {}, handleBridgeCall() {} };
const api = load('app/apps/evenhub/webview.ts');
const handle = api.createEvenHubWebView(session);
return { api, calls, evaluated, failures, handle, listener: () => listener, attachedCheck: () => attachedCheck };
}
// Runs a host-evaluated script in a document at `href`, as WebView would.
function runIn(href, script, globals = {}) {
const context = vm.createContext({ URL, location: new URL(href), JSON, String, ...globals });
context.window = context;
return { result: vm.runInContext(script, context), context };
}
test('Android EvenHub WebViews join their package profile, then get an origin-locked bridge', () => {
const h = androidWebView();
assert.deepEqual(h.calls, ['construct', 'profile com.example.app', 'settings',
'bridge https://com.example.app.evenhub.invalid', 'load https://com.example.app.evenhub.invalid/index.html']);
const remote = androidWebView({ remoteUrl: 'http://192.168.1.5:5173/app/' });
assert.ok(remote.calls.includes('bridge http://192.168.1.5:5173'));
assert.ok(remote.calls.includes('document-start http://192.168.1.5:5173'));
});
test('Android EvenHub host scripts only run in the app\'s own documents', () => {
const h = androidWebView();
h.handle.evaluateJs('window.ran = true');
assert.equal(runIn('https://com.example.app.evenhub.invalid/index.html?code=1', h.evaluated[0]).context.ran, true);
assert.equal(runIn('https://accounts.example.com/authorize', h.evaluated[0]).context.ran, undefined);
// The ticker's guard is the same check.
assert.equal(runIn('https://com.example.app.evenhub.invalid/', `if (${h.attachedCheck()}) { 5 }`).result, 5);
assert.equal(runIn('http://com.example.app.evenhub.invalid/', `if (${h.attachedCheck()}) { 5 }`).result, undefined);
});
test('Android EvenHub transport wraps the bridge port, and is inert without it', () => {
const posted = [];
const port = { postMessage: message => posted.push(JSON.parse(message)) };
const { api } = androidWebView();
const { context } = runIn('https://com.example.app.evenhub.invalid/', api.ANDROID_EVENHUB_TRANSPORT_SCRIPT, { __faceclawEvenHubPort: port });
context.__faceclawEvenHub.postMessage('evenAppMessage', '["{}"]', 7);
context.__faceclawEvenHub.wakeTimers();
assert.deepEqual(posted, [['call', 'evenAppMessage', '["{}"]', 7], ['wake']]);
assert.equal(runIn('https://elsewhere.example/', api.ANDROID_EVENHUB_TRANSPORT_SCRIPT).context.__faceclawEvenHub, undefined);
});
test('Android EvenHub apps fail visibly without a bridge, and stop using a WebView whose renderer is gone', () => {
const failed = androidWebView({ bridgeError: 'too old' });
assert.deepEqual(failed.failures, [['too old', true]]);
assert.ok(!failed.calls.some(call => call.startsWith('load ')));
const h = androidWebView();
h.listener().onRenderProcessGone(false);
assert.equal(h.failures.length, 1); assert.equal(h.failures[0][1], true);
h.handle.evaluateJs('window.ran = true');
assert.equal(h.evaluated.length, 0);
});
+54
View File
@@ -0,0 +1,54 @@
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const cache = path.join(os.homedir(), '.gradle/caches/modules-2/files-2.1');
/** A cached Maven artifact (`.jar` unless `extension` says otherwise), or null. */
function cachedArtifact(group, artifact, version, extension = 'jar') {
const directory = path.join(cache, group, artifact, version);
if (!fs.existsSync(directory)) return null;
for (const hash of fs.readdirSync(directory)) {
const file = path.join(directory, hash, `${artifact}-${version}.${extension}`);
if (fs.existsSync(file)) return file;
}
return null;
}
/** The newest cached version of an artifact, or null. */
function newestArtifact(group, artifact, extension = 'jar') {
const directory = path.join(cache, group, artifact);
if (!fs.existsSync(directory)) return null;
for (const version of fs.readdirSync(directory).sort().reverse()) {
const file = cachedArtifact(group, artifact, version, extension);
if (file) return file;
}
return null;
}
/**
* The Kotlin compiler NativeScript's Android build already cached (the version
* in before-plugins.gradle), or null before the first ./build.sh. Run it as
* `java -cp <classpath> org.jetbrains.kotlin.cli.jvm.K2JVMCompiler -no-stdlib -cp <stdlib> ...`.
*/
function kotlinCompiler() {
const gradle = fs.readFileSync(path.join(__dirname, '../../App_Resources/Android/before-plugins.gradle'), 'utf8')
.match(/kotlinVersion\s*=\s*"([^"]+)"/);
if (!gradle) return null;
const version = gradle[1];
const stdlib = cachedArtifact('org.jetbrains.kotlin', 'kotlin-stdlib', version);
const compiler = [
cachedArtifact('org.jetbrains.kotlin', 'kotlin-compiler-embeddable', version),
stdlib,
cachedArtifact('org.jetbrains.kotlin', 'kotlin-script-runtime', version),
cachedArtifact('org.jetbrains.kotlin', 'kotlin-daemon-embeddable', version),
newestArtifact('org.jetbrains.kotlin', 'kotlin-reflect'),
newestArtifact('org.jetbrains.intellij.deps', 'trove4j'),
newestArtifact('org.jetbrains', 'annotations'),
newestArtifact('org.jetbrains.kotlinx', 'kotlinx-coroutines-core-jvm'),
];
if (compiler.some(file => !file)) return null;
return { classpath: compiler.join(path.delimiter), stdlib };
}
module.exports = { cachedArtifact, newestArtifact, kotlinCompiler };
+36 -7
View File
@@ -15,6 +15,11 @@ fs.writeFileSync(path.join(dist, 'index.html'), `<script>flutter_inappwebview.ca
fs.writeFileSync(path.join(dist, 'app.js'), `
import { value } from './module.js';
const call = name => flutter_inappwebview.callHandler(name);
const params = new URLSearchParams(location.search);
if (params.has('code')) await call(['oauth', params.get('code'), params.get('state'), params.get('shim')].join(':'));
const frame = document.createElement('iframe'); frame.src = '/frame.html';
frame.onload = () => { if (frame.contentDocument.getElementById('frame')?.textContent === 'frame') call('iframe'); };
document.documentElement.appendChild(frame);
if (value === 42) await call('module');
const previous = localStorage.getItem('probe'); localStorage.setItem('probe','saved'); await call(previous === 'saved' ? 'restored' : 'stored');
if ((await (await fetch('/data.json')).json()).ok) await call('fetch');
@@ -24,24 +29,48 @@ await WebAssembly.instantiate(new Uint8Array([0,97,115,109,1,0,0,0])); await cal
if (!(await fetch('/%2e%2e/secret.txt')).ok) await call('traversal');
`);
fs.writeFileSync(path.join(dist, 'module.js'), 'export const value = 42;');
const untrusted = "<script>webkit.messageHandlers.faceclaw.postMessage({kind:'call', name:'UNTRUSTED', args:'[]', id:0})</script>";
fs.writeFileSync(path.join(dist, 'frame.html'), `<p id="frame">frame</p>${untrusted}`);
fs.writeFileSync(path.join(dist, 'data.json'), '{"ok":true}');
fs.writeFileSync(path.join(dist, 'pixel.png'), Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aBVkAAAAASUVORK5CYII=', 'base64'));
fs.writeFileSync(path.join(bundle, 'Info.plist'), `<?xml version="1.0"?><plist version="1.0"><dict><key>CFBundleIdentifier</key><string>com.faceclaw.evenhub-probe</string><key>CFBundleExecutable</key><string>EvenHubProbe</string><key>CFBundleName</key><string>EvenHubProbe</string><key>CFBundlePackageType</key><string>APPL</string><key>CFBundleVersion</key><string>1</string><key>CFBundleShortVersionString</key><string>1</string><key>NSAppTransportSecurity</key><dict><key>NSAllowsLocalNetworking</key><true/></dict><key>UILaunchScreen</key><dict/><key>LSRequiresIPhoneOS</key><true/></dict></plist>`);
const sdk = execFileSync('xcrun', ['--sdk', 'iphonesimulator', '--show-sdk-path'], { encoding: 'utf8' }).trim();
execFileSync('xcrun', ['clang', '-fobjc-arc', '-target', `${process.arch === 'arm64' ? 'arm64' : 'x86_64'}-apple-ios15.1-simulator`, '-isysroot', sdk,
'-framework', 'UIKit', '-framework', 'Foundation', '-framework', 'CoreGraphics', '-framework', 'WebKit', '-framework', 'UniformTypeIdentifiers',
'-framework', 'UIKit', '-framework', 'Foundation', '-framework', 'CoreGraphics', '-framework', 'WebKit', '-framework', 'SafariServices', '-framework', 'UniformTypeIdentifiers',
'-I', 'App_Resources/iOS/src', 'tests/native/ios-evenhub-test.m', 'App_Resources/iOS/src/FaceclawEvenHubWebView.m', 'App_Resources/iOS/src/FaceclawCrypto.m', '-o', path.join(bundle, 'EvenHubProbe')], { cwd: root, stdio: 'inherit' });
// Requests that must never arrive: the provider's reply landing outside the app,
// host messages evaluated in a page the app navigated away to, and the cookie the
// first package's sign-in page set reaching the server from another package.
// ownCookie (the first package sending it again later) shows the cookie stuck.
const hits = { callback: 0, awayEval: 0, cookieLeak: 0, ownCookie: 0 };
const server = http.createServer((request, response) => {
if (request.url === '/redirect') { response.writeHead(302, { Location: `http://localhost:${server.address().port}/untrusted` }); response.end(); return; }
if (request.url === '/untrusted') { response.end("<script>webkit.messageHandlers.faceclaw.postMessage({kind:'call', name:'UNTRUSTED', args:'[]', id:0})</script>"); return; }
const file = path.join(dist, request.url === '/' ? 'index.html' : request.url.slice(1));
const url = new URL(request.url, 'http://probe'), port = server.address().port;
if (/\bprobe=1\b/.test(request.headers.cookie ?? '')) {
if (url.pathname === '/away') hits.ownCookie++;
else if (url.pathname !== '/approve') hits.cookieLeak++;
}
// The app's URL redirects to another origin before loading; the app lives there.
if (url.pathname === '/redirect') { response.writeHead(302, { Location: `http://localhost:${port}/` }); response.end(); return; }
// A third-party sign-in page: no bridge or shim, then a server redirect to the app's redirect_uri.
if (url.pathname === '/authorize') { response.end(`${untrusted}<script>document.cookie = 'probe=1; max-age=3600'; location.replace('/approve' + location.search + '&shim=' + typeof window.flutter_inappwebview)</script>`); return; }
if (url.pathname === '/approve') {
const query = url.searchParams;
response.writeHead(302, { Location: `${query.get('redirect_uri')}?code=probe&state=${query.get('state')}&shim=${query.get('shim')}` }); response.end(); return;
}
if (url.pathname.startsWith('/callback')) { hits.callback++; response.end('callback'); return; }
if (url.pathname === '/away') { response.end('<p>away</p>'); return; }
if (url.pathname === '/away-eval') { hits.awayEval++; response.end(); return; }
const file = path.join(dist, url.pathname === '/' ? 'index.html' : url.pathname.slice(1));
if (!file.startsWith(dist + path.sep) || !fs.existsSync(file)) { response.writeHead(404); response.end(); return; }
response.setHeader('Content-Type', file.endsWith('.js') ? 'text/javascript' : file.endsWith('.json') ? 'application/json' : file.endsWith('.png') ? 'image/png' : 'text/html');
response.end(fs.readFileSync(file));
});
server.listen(0, '127.0.0.1', async () => {
try {
fs.writeFileSync(path.join(bundle, 'remote.txt'), `http://127.0.0.1:${server.address().port}/`);
const port = server.address().port;
fs.writeFileSync(path.join(bundle, 'remote.txt'), `http://127.0.0.1:${port}/`);
fs.writeFileSync(path.join(bundle, 'authorize.txt'),
`http://127.0.0.1:${port}/authorize?client_id=probe&redirect_uri=${encodeURIComponent(`http://localhost:${port}/callback/`)}&state=s1`);
const device = process.argv[2] || 'booted';
execFileSync('xcrun', ['simctl', 'install', device, bundle], { stdio: 'inherit' });
const container = execFileSync('xcrun', ['simctl', 'get_app_container', device, 'com.faceclaw.evenhub-probe', 'data'], { encoding: 'utf8' }).trim();
@@ -60,8 +89,8 @@ server.listen(0, '127.0.0.1', async () => {
await new Promise(resolve => setTimeout(resolve, 100));
}
const result = JSON.parse(fs.readFileSync(resultFile, 'utf8'));
console.log(JSON.stringify({ work, ...result }));
if (!result.passed) process.exitCode = 1;
console.log(JSON.stringify({ work, hits, ...result }));
if (!result.passed || hits.callback || hits.awayEval || hits.cookieLeak || !hits.ownCookie) process.exitCode = 1;
} catch (error) {
console.error(error); process.exitCode = 1;
} finally {
+49 -3
View File
@@ -78,8 +78,8 @@ test('local package runtimes unpack independently and clean up after closing or
assert.equal(files.size, 0);
});
function sessionHarness(overrides = {}, playBuzzer = () => {}) {
const settings = new Map(), logs = [], renders = [];
function sessionHarness(overrides = {}, playBuzzer = () => {}, { packageId = 'test.probe', settings = new Map() } = {}) {
const logs = [], renders = [];
const load = loader({ global: { isIOS: true }, setTimeout, clearTimeout, Promise }, {
'@nativescript/core': { ApplicationSettings: { getString: (k, d) => settings.get(k) ?? d, setString: (k, v) => settings.set(k, v) } },
'upng-js': require('upng-js'),
@@ -90,7 +90,7 @@ function sessionHarness(overrides = {}, playBuzzer = () => {}) {
'../../native/location': {}, '../../native/location-tracker': {}, '../../native/location-permissions': {}, ...overrides,
});
const api = load('app/apps/evenhub/session.ts');
const session = new api.EvenHubSession({ name: 'Probe', packageId: 'test.probe', permissions: [] }, '/test/dist', line => logs.push(line), '', playBuzzer);
const session = new api.EvenHubSession({ name: 'Probe', packageId, permissions: [] }, '/test/dist', line => logs.push(line), '', playBuzzer);
session.attachWindow({ requestRender: () => renders.push(1), windowId: 'probe', closeWindow() {} });
const web = vm.createContext({ Promise, Map, Date, console });
web.window = web;
@@ -138,6 +138,52 @@ test('iOS webview adapter defers loading until handles attach and destroys a not
remote.destroy();
});
test('iOS webview adapter passes fatal errors through and logs host notices', () => {
const native = {}, failures = [], logs = [];
const load = loader({ FaceclawEvenHubWebView: { new: () => native }, setTimeout: () => 1, clearTimeout() {},
console: { log: line => logs.push(line), warn() {} } }, {
'./session': { EVENHUB_BRIDGE_INJECT_SCRIPT: '', buildFaceclawExtensionsScript: () => '' }, '../../version': { FACECLAW_VERSION: 'test' },
});
load('app/apps/evenhub/webview.ios.ts').createEvenHubWebView({ manifest: { name: 'Probe' },
webViewFailed: (message, fatal) => failures.push([message, fatal]) });
native.eventHandler(JSON.stringify({ kind: 'error', message: 'offline' }));
native.eventHandler(JSON.stringify({ kind: 'error', message: 'crashed', fatal: true }));
native.eventHandler(JSON.stringify({ kind: 'notice', message: 'Blocked navigation to a mailto: URL.' }));
assert.deepEqual(failures, [['offline', false], ['crashed', true]]);
assert.deepEqual(logs, ['[evenhub:Probe] Blocked navigation to a mailto: URL.']);
});
test('EvenHub load errors replace the window only before the app loads, and a later load clears them', () => {
const drawn = [];
const h = sessionHarness({ '../../graphics/evenhub-font': { EvenHubFont: { get: () => ({
drawText: (_image, _x, _y, text) => drawn.push(text), drawTextWrapped() {}, lineHeight: 20 }) } } });
const heading = () => { drawn.length = 0; h.session.paint({ width: 576, height: 288 }, true); return drawn[0]; };
h.session.webViewFailed('offline');
assert.equal(heading(), 'Could not run Probe...');
h.session.webViewLoaded();
assert.equal(heading(), 'Loading Probe...');
// A failed navigation after the first load leaves the app's page running.
h.session.webViewFailed('A server with the specified hostname could not be found.');
assert.equal(heading(), 'Loading Probe...');
assert.ok(h.logs.includes('evenhub: A server with the specified hostname could not be found.'));
h.session.webViewFailed('The app\'s web process ended.', true);
assert.equal(heading(), 'Could not run Probe...');
h.session.close();
});
test('SDK storage is partitioned by package, even for package IDs containing the key separator', async () => {
const settings = new Map();
const [plain, colon, percent] = ['a', 'a:ls:b', 'a%3Als%3Ab'].map(packageId => sessionHarness({}, undefined, { packageId, settings }));
assert.equal(await colon.call('setLocalStorage', { key: 'c', value: 'secret' }), true);
assert.equal(await colon.call('getLocalStorage', { key: 'c' }), 'secret');
assert.equal(await plain.call('getLocalStorage', { key: 'b:ls:c' }), '');
assert.equal(await percent.call('getLocalStorage', { key: 'c' }), '');
// Ordinary package IDs keep their existing keys.
assert.equal(await plain.call('setLocalStorage', { key: 'k', value: 'v' }), true);
assert.equal(settings.get('evenhub:a:ls:k'), 'v');
for (const h of [plain, colon, percent]) h.session.close();
});
test('EvenHub location uses the platform boundary and closes its subscription', async () => {
let permission = true, callback, starts = 0, stops = 0;
const fix = { latitude: 12, longitude: 34, accuracyMeters: 5, timestampMs: 1234 };
+1 -40
View File
@@ -6,6 +6,7 @@ const path = require('node:path');
const vm = require('node:vm');
const { execFileSync } = require('node:child_process');
const ts = require('typescript');
const { kotlinCompiler } = require('./helpers/kotlin-compiler.cjs');
const source = (file) => fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
function load(file, requireModule, globals = {}) {
@@ -189,46 +190,6 @@ test('Music settings keeps toggles and selection when a new app arrives and supp
assert.equal(closes, 1);
});
// FaceclawMediaController is Kotlin compiled by the NativeScript Android build, so
// compile the extracted method with the same Kotlin compiler Gradle already cached.
function kotlinCompiler() {
const gradle = source('App_Resources/Android/before-plugins.gradle').match(/kotlinVersion\s*=\s*"([^"]+)"/);
const cache = path.join(os.homedir(), '.gradle/caches/modules-2/files-2.1');
const jar = (group, artifact, version) => {
const directory = path.join(cache, group, artifact, version);
if (!fs.existsSync(directory)) return null;
for (const hash of fs.readdirSync(directory)) {
const file = path.join(directory, hash, `${artifact}-${version}.jar`);
if (fs.existsSync(file)) return file;
}
return null;
};
const anyVersion = (group, artifact) => {
const directory = path.join(cache, group, artifact);
if (!fs.existsSync(directory)) return null;
for (const version of fs.readdirSync(directory).sort().reverse()) {
const file = jar(group, artifact, version);
if (file) return file;
}
return null;
};
if (!gradle) return null;
const version = gradle[1];
const stdlib = jar('org.jetbrains.kotlin', 'kotlin-stdlib', version);
const compiler = [
jar('org.jetbrains.kotlin', 'kotlin-compiler-embeddable', version),
stdlib,
jar('org.jetbrains.kotlin', 'kotlin-script-runtime', version),
jar('org.jetbrains.kotlin', 'kotlin-daemon-embeddable', version),
anyVersion('org.jetbrains.kotlin', 'kotlin-reflect'),
anyVersion('org.jetbrains.intellij.deps', 'trove4j'),
anyVersion('org.jetbrains', 'annotations'),
anyVersion('org.jetbrains.kotlinx', 'kotlinx-coroutines-core-jvm'),
];
if (compiler.some(file => !file)) return null;
return { classpath: compiler.join(path.delimiter), stdlib };
}
test('native session selection skips ignored playing and idle apps, including the all-ignored case', (t) => {
// Execute the production selection method with lightweight media-session doubles.
const compiler = kotlinCompiler();
+106
View File
@@ -0,0 +1,106 @@
package com.faceclaw.evenhubprobe
import android.app.Activity
import android.content.MutableContextWrapper
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.webkit.WebView
import com.faceclaw.app.FaceclawEvenHubChromeClient
import com.faceclaw.app.FaceclawEvenHubDocumentStart
import com.faceclaw.app.FaceclawEvenHubJsBridge
import com.faceclaw.app.FaceclawEvenHubListener
import com.faceclaw.app.FaceclawEvenHubProfile
import com.faceclaw.app.FaceclawEvenHubWebView
import com.faceclaw.app.FaceclawEvenHubWebViewClient
import com.faceclaw.app.FaceclawEvenHubWebViewHost
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
/**
* Runs the production EvenHub WebView classes (tests/android-evenhub-native.cjs),
* wired the way app/apps/evenhub/webview.ts wires them, and logs what the host saw.
*
* - A: a packaged app. It calls the bridge and gets a reply, embeds a same-origin
* and a cross-origin iframe, then navigates to a third-party page.
* - B: another packaged app (its own profile), which then visits a cookie check.
* - A2: a second WebView for A's package, which visits the same cookie check.
* - R: a remote app, served by the test server, with the document-start shim.
* - Then the shared renderer is crashed; the process must survive it.
*/
class ProbeActivity : Activity() {
private val handler = Handler(Looper.getMainLooper())
private val seen = LinkedHashSet<String>()
private val webViews = HashMap<String, WebView>()
private val checks = HashMap<String, String>()
private lateinit var config: JSONObject
private fun asset(name: String) = assets.open(name).use { it.readBytes().decodeToString() }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
config = JSONObject(asset("config.json"))
val dist = File(filesDir, "dist").apply { mkdirs() }
for (name in assets.list("dist")!!) File(dist, name).writeBytes(assets.open("dist/$name").use { it.readBytes() })
val third = config.getString("third")
handler.post { create("A", "probe.a", dist.path) }
handler.postDelayed({ evaluate("A", "location.href = '$third/third'") }, 4000)
handler.postDelayed({
// A now shows the third-party page: host scripts must not run there.
evaluate("A", "new Image().src = '$third/report?eval=leak'")
create("B", "probe.b", dist.path)
}, 6000)
handler.postDelayed({ create("A2", "probe.a", dist.path); create("R", "probe.remote", null) }, 8000)
handler.postDelayed({
evaluate("B", "location.href = '$third/cookie?app=B'")
evaluate("A2", "location.href = '$third/cookie?app=A2'")
}, 10000)
handler.postDelayed({ webViews["R"]?.loadUrl("chrome://crash") }, 13000)
handler.postDelayed({
Log.i(TAG, "RESULT " + JSONObject().put("seen", JSONArray(seen.toList())))
}, 17000)
}
private fun create(tag: String, packageId: String, distDir: String?) {
val startUrl = config.getJSONObject("start").getString(tag)
checks[tag] = config.getJSONObject("checks").getString(tag)
val web = FaceclawEvenHubWebView(MutableContextWrapper(this))
seen.add("$tag:profile=${FaceclawEvenHubProfile.apply(web, packageId)}")
web.settings.javaScriptEnabled = true
web.settings.domStorageEnabled = true
web.settings.allowFileAccess = false
val listener = object : FaceclawEvenHubListener {
override fun onEvenAppMessage(handlerName: String?, argsJson: String?, callId: Int) {
seen.add("$tag:" + JSONArray(argsJson ?: "[]").optString(0))
evaluate(tag, "window.__fcResolve($callId, true, true)")
}
override fun onPageFinished(url: String?) {}
override fun onRenderProcessGone(crashed: Boolean) {
seen.add("$tag:gone")
webViews.remove(tag)
}
}
val rule = FaceclawEvenHubJsBridge.originRule(startUrl)!!
FaceclawEvenHubJsBridge.install(web, rule, listener)?.let { seen.add("$tag:bridge-error") }
val inject = asset("inject-$tag.js")
val remote = distDir == null
val documentStart = remote && FaceclawEvenHubDocumentStart.install(web, inject, rule)
val host = if (remote) "" else android.net.Uri.parse(startUrl).host
web.webViewClient = FaceclawEvenHubWebViewClient(distDir, host, inject, remote && !documentStart, listener)
web.webChromeClient = FaceclawEvenHubChromeClient()
FaceclawEvenHubWebViewHost.getInstance().attach(this, web, checks[tag]!!)
webViews[tag] = web
web.loadUrl(startUrl)
}
/** As webview.ts's evaluateJs: guarded to the app's origin. */
private fun evaluate(tag: String, js: String) {
webViews[tag]?.evaluateJavascript("if (${checks[tag]}) {\n$js\n}", null)
}
companion object {
private const val TAG = "EHPROBE"
}
}
+35 -7
View File
@@ -12,6 +12,14 @@
@property(nonatomic) BOOL foregroundPassed;
@end
@implementation Probe
- (void)after:(double)seconds run:(void (^)(void))block {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(seconds * NSEC_PER_SEC)), dispatch_get_main_queue(), block);
}
- (UIButton *)button:(NSString *)identifier in:(UIView *)view {
if ([view isKindOfClass:UIButton.class] && [view.accessibilityIdentifier isEqual:identifier]) return (UIButton *)view;
for (UIView *child in view.subviews) { UIButton *found = [self button:identifier in:child]; if (found) return found; }
return nil;
}
- (void)writeResult:(NSDictionary *)result name:(NSString *)name {
NSData *data = [NSJSONSerialization dataWithJSONObject:result options:0 error:nil];
NSString *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
@@ -30,8 +38,10 @@
self.host.eventHandler = ^(NSString *json) {
NSLog(@"EHPROBE %@", json);
NSDictionary *event = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
if ([event[@"kind"] isEqual:@"error"] && [event[@"message"] containsString:@"outside the app origin"])
if ([event[@"kind"] isEqual:@"notice"] && [event[@"message"] containsString:@"Blocked navigation to a faceclaw-test:"])
[weakSelf.seen addObject:@"blocked-navigation"];
// Blocked and interrupted navigations are not load errors.
if ([event[@"kind"] isEqual:@"error"]) [weakSelf.seen addObject:[@"ERROR:" stringByAppendingString:event[@"message"]]];
if ([event[@"kind"] isEqual:@"call"]) {
[weakSelf.seen addObject:event[@"name"]];
[weakSelf.seen addObject:[NSString stringWithFormat:@"%ld:%@", (long)weakSelf.phase, event[@"name"]]];
@@ -46,6 +56,24 @@
};
NSString *root = NSBundle.mainBundle.resourcePath;
NSString *script = [NSString stringWithContentsOfFile:[root stringByAppendingPathComponent:@"bridge.js"] encoding:NSUTF8StringEncoding error:nil];
NSString *remote = [NSString stringWithContentsOfFile:[root stringByAppendingPathComponent:@"remote.txt"] encoding:NSUTF8StringEncoding error:nil];
NSString *authorize = [NSString stringWithContentsOfFile:[root stringByAppendingPathComponent:@"authorize.txt"] encoding:NSUTF8StringEncoding error:nil];
// Phase 1: an OAuth sign-in through a third-party page comes back to the packaged app.
[self after:2 run:^{ [self.host evaluate:[NSString stringWithFormat:@"location.href = '%@'", authorize]]; }];
// Phase 2: a non-web scheme is blocked without failing the app; a followed link
// leaves the app, which the Return button restores.
[self after:4.5 run:^{ [self.host evaluate:@"location.href = 'faceclaw-test:blocked'"]; }];
[self after:5 run:^{ [self.host evaluate:[NSString stringWithFormat:@"location.href = '%@away'", remote]]; }];
[self after:6 run:^{
UIButton *button = [self button:@"evenhub-return" in:self.window];
if (button && !button.hidden) [self.seen addObject:@"return-visible"];
[self.host evaluate:@"new Image().src = '/away-eval'"];
[button sendActionsForControlEvents:UIControlEventTouchUpInside];
}];
[self after:7 run:^{
if ([self button:@"evenhub-return" in:self.window].hidden) [self.seen addObject:@"return-hidden"];
[self.host evaluate:@"flutter_inappwebview.callHandler('returned')"];
}];
dispatch_async(dispatch_get_main_queue(), ^{
[self.host start:[root stringByAppendingPathComponent:@"dist"] entrypoint:@"index.html" script:script];
});
@@ -57,15 +85,15 @@
self.host.eventHandler = handler;
self.host.packageIdentifier = phase == 2 ? package : [package stringByAppendingString:@".other"];
if (phase <= 3) [self.host start:[root stringByAppendingPathComponent:@"dist"] entrypoint:@"index.html" script:script];
else {
NSString *url = [NSString stringWithContentsOfFile:[root stringByAppendingPathComponent:@"remote.txt"] encoding:NSUTF8StringEncoding error:nil];
[self.host startURL:phase == 5 ? [url stringByAppendingString:@"redirect"] : url script:script];
}
else [self.host startURL:phase == 5 ? [remote stringByAppendingString:@"redirect"] : remote script:script];
});
}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 21 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
NSArray *required = @[@"early", @"module", @"fetch", @"image", @"timer", @"raf", @"wasm", @"traversal", @"1:stored", @"2:restored", @"3:stored", @"4:early", @"4:module", @"4:fetch", @"4:timer", @"blocked-navigation"];
BOOL passed = [[NSSet setWithArray:required] isSubsetOfSet:self.seen] && ![self.seen containsObject:@"UNTRUSTED"];
NSArray *required = @[@"early", @"module", @"fetch", @"image", @"timer", @"raf", @"wasm", @"traversal", @"1:stored", @"2:restored", @"3:stored",
@"1:iframe", @"1:oauth:probe:s1:undefined", @"blocked-navigation", @"return-visible", @"return-hidden", @"2:returned",
@"4:early", @"4:module", @"4:fetch", @"4:timer", @"4:iframe", @"5:early", @"5:module"];
BOOL passed = [[NSSet setWithArray:required] isSubsetOfSet:self.seen] && ![self.seen containsObject:@"UNTRUSTED"] &&
![[self.seen.allObjects componentsJoinedByString:@"\n"] containsString:@"ERROR:"];
NSString *signature = [FaceclawCrypto hmacSha256:@"key" message:@"The quick brown fox jumps over the lazy dog"];
passed &= [signature isEqual:@"97yD9DBThCSxMpjmqm+xQ+9NWaFJRhdZl0edvC0aPNg="];
self.foregroundPassed = passed;