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

+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;