forked from Blendman974/faceclaw
EvenHub compatibility for iOS
This commit is contained in:
1 parent
617cdc39eb
commit
7e58c7c05f
40 files changed
+629
-176
No files matched your search
@@ -0,0 +1,109 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { zstdCompressSync } = require('node:zlib');
|
||||
const { loader } = require('./helpers/load-typescript.cjs');
|
||||
const flush = () => new Promise(resolve => setImmediate(resolve));
|
||||
function pack(files) {
|
||||
const key = Buffer.from('EVEN REALITIES'), xor = b => Buffer.from(b.map((v, i) => v ^ key[i % key.length]));
|
||||
const header = Buffer.alloc(20); header.write('EHPK'); header.writeUInt32LE(20, 8);
|
||||
return Buffer.concat([header, ...Object.entries(files).map(([name, value]) => {
|
||||
const raw = Buffer.from(value), body = zstdCompressSync(raw), path = Buffer.from(name), h = Buffer.alloc(16);
|
||||
h.writeUInt32LE(0xbaa9bae4); h.writeUInt32LE(body.length, 4); h.writeUInt32LE(raw.length, 8); h.writeUInt16LE(path.length, 14);
|
||||
return Buffer.concat([h, xor(path), xor(body)]);
|
||||
})]);
|
||||
}
|
||||
function packageFixture() {
|
||||
const expanded = [], files = new Map(), settings = new Map();
|
||||
const bytes = pack({ 'app.json': JSON.stringify({ package_id: 'test.large', name: 'Large', permissions: [{ name: 'network' }] }),
|
||||
'dist/index.html': '<html>Test</html>', 'dist/icon.svg': '<svg/>', 'dist/engine.wasm': 'abcdef'.repeat(2_000_000) });
|
||||
const load = loader({ global: { isIOS: true } }, {
|
||||
fzstd: { decompress: (input, output) => { expanded.push(output.length); return require('fzstd').decompress(input, output); } },
|
||||
'../../native/file-access': { readBinaryFile: path => files.get(path) ?? null, readTextFile() {}, appFilesDirPath: () => '/app',
|
||||
writeBinaryFile: (path, bytes) => { files.set(path, bytes); return true; },
|
||||
deletePathRecursively: path => { for (const key of files.keys()) if (key.startsWith(path + '/')) files.delete(key); } },
|
||||
'../../native/settings-store': { getStringSetting: (key, fallback) => settings.get(key) ?? fallback, setStringSetting: (key, value) => settings.set(key, value) },
|
||||
'../../native/icon-image': {}, '../../graphics/icons': {}, '../../graphics/image': {},
|
||||
});
|
||||
files.set('/source.ehpk', bytes);
|
||||
return { load, bytes, expanded, files };
|
||||
}
|
||||
|
||||
test('permission inspection and installation never decompress the large app engine; extraction expands it once', () => {
|
||||
const h = packageFixture(), installed = h.load('app/apps/evenhub/installed-apps.ts');
|
||||
assert.equal(installed.readEvenHubPackageManifestBytes(h.bytes).packageId, 'test.large');
|
||||
assert.equal(h.expanded.length, 1);
|
||||
installed.installEvenHubPackageBytes(h.bytes);
|
||||
assert.ok(h.expanded.every(size => size < 1024), 'Only manifest, HTML and icon are needed to install');
|
||||
h.load('app/apps/evenhub/package-extraction.ts').extractPackage('/source.ehpk', '/runtime');
|
||||
assert.equal(h.expanded.filter(size => size === 12_000_000).length, 1);
|
||||
assert.equal(h.files.get('/runtime/dist/engine.wasm').length, 12_000_000);
|
||||
});
|
||||
|
||||
test('store install releases serialized input before download and permission approval finish', async () => {
|
||||
let completeDownload, dialog, installed = false, launched = false;
|
||||
const download = new Promise(resolve => { completeDownload = resolve; });
|
||||
const manifest = { name: 'Test', packageId: 'test', permissions: [{ name: 'network' }], privacyPolicyUrl: '' };
|
||||
const load = loader({}, {
|
||||
'../../graphics/ui-fonts': {}, '../../graphics/image': {}, '../../graphics/textwrap': {}, '../../ui/menu': {}, '../files/text-viewer': {}, '../../ui/metrics': {},
|
||||
'./even-api': { evenHubApi: { getStoreAppDetail: async () => null, downloadApp: () => download } },
|
||||
'./installed-apps': { getInstalledEvenHubApp: () => null, readEvenHubPackageManifestBytes: () => manifest,
|
||||
readEvenHubPackageManifest: () => null, installedEvenHubPackagePath: () => '', installedEvenHubAppId: id => id,
|
||||
installEvenHubPackageBytes: () => { installed = true; return { packageId: 'test', version: '1' }; } },
|
||||
'./manager': { closeRunningPackage() {} }, './updates': {},
|
||||
'./permission-dialog': { EvenHubPermissionDialogLayer: class {
|
||||
constructor(_name, _permissions, _policy, allow) { this.allow = allow; }
|
||||
handleInput() { this.allow(); }
|
||||
} },
|
||||
});
|
||||
const { EvenHubStoreDetailLayer } = load('app/apps/evenhub/store-detail-layer.ts');
|
||||
const layer = new EvenHubStoreDetailLayer({ packageId: 'test', name: 'Test' }, { appendLog() {}, launchApp: () => { launched = true; } });
|
||||
const ctx = { actions: { requestRender() {} }, stack: { push: value => { dialog = value; } } };
|
||||
let queue = Promise.resolve(), returned = false;
|
||||
queue = queue.then(() => layer.handleInput({ type: 'click' }, ctx)).then(() => { returned = true; });
|
||||
await flush(); assert.equal(returned, true, 'Input must return even while download is unresolved');
|
||||
completeDownload({ bytes: new Uint8Array(20), privacyPolicyUrl: '' });
|
||||
await flush(); assert.ok(dialog); assert.equal(installed, false);
|
||||
queue = queue.then(() => dialog.handleInput({ type: 'click' }, ctx));
|
||||
await queue; await flush();
|
||||
assert.equal(installed, true); assert.equal(launched, true);
|
||||
});
|
||||
|
||||
test('iOS extraction sends paths to a worker, leaves main responsive, and terminates on success or failure', async () => {
|
||||
const workers = [], timers = new Map(); let serial = 0;
|
||||
class Worker {
|
||||
constructor() { workers.push(this); } postMessage(value) { this.request = value; } terminate() { this.terminated = true; }
|
||||
}
|
||||
const { unpackRuntime } = loader({ Worker, setTimeout: fn => { timers.set(++serial, fn); return serial; }, clearTimeout: id => timers.delete(id) })('app/apps/evenhub/unpack-runtime.ios.ts');
|
||||
const work = unpackRuntime('/source.ehpk', '/runtime');
|
||||
assert.deepEqual(JSON.parse(JSON.stringify(workers[0].request)), { path: '/source.ehpk', directory: '/runtime' });
|
||||
await flush(); // The JS loop remains runnable while extraction is outstanding.
|
||||
workers[0].onmessage({ data: { manifest: { packageId: 'test' } } });
|
||||
assert.equal((await work).packageId, 'test'); assert.equal(workers[0].terminated, true); assert.equal(timers.size, 0);
|
||||
const failed = unpackRuntime('/bad.ehpk', '/runtime');
|
||||
workers[1].onerror({ message: 'fixture failure' });
|
||||
await assert.rejects(failed, /fixture failure/); assert.equal(workers[1].terminated, true);
|
||||
});
|
||||
|
||||
test('installed raster icons use the iOS decoder and retain decoded dimensions', () => {
|
||||
const calls = [];
|
||||
const iconLoader = loader({ global: { isIOS: true }, FaceclawGraphics: {
|
||||
decodeImageFileMaxWidthMaxHeight: (path, width, height) => {
|
||||
calls.push({ path, width, height });
|
||||
return path.endsWith('missing.png') ? null : new Uint8Array([2, 0, 1, 0, 80, 255]);
|
||||
},
|
||||
} }, { './kotlin-data': { fromData: data => data } })('app/native/icon-image.ios.ts');
|
||||
const installed = loader({}, {
|
||||
'../../native/icon-image': iconLoader,
|
||||
'../../native/file-access': { appFilesDirPath: () => '/app' },
|
||||
'../../native/settings-store': {}, '../../graphics/icons': {}, fzstd: require('fzstd'),
|
||||
})('app/apps/evenhub/installed-apps.ts');
|
||||
const record = { packageId: 'test', installedAt: 'today', iconFile: 'icon.png' };
|
||||
const image = installed.renderInstalledEvenHubIcon('test', 32, record);
|
||||
assert.equal(image.width, 2); assert.equal(image.height, 1);
|
||||
assert.deepEqual([...image.pixels], [80, 255]);
|
||||
assert.equal(calls[0].path, '/app/evenhub-installed/test/icon.png');
|
||||
assert.equal(calls[0].width, 32);
|
||||
assert.equal(installed.renderInstalledEvenHubIcon('test', 32, record), image);
|
||||
assert.equal(calls.length, 1);
|
||||
assert.equal(iconLoader.loadIconImage('/missing.png', 32, 32), null);
|
||||
});
|
||||
@@ -10,6 +10,38 @@ function load(file, context) {
|
||||
vm.runInNewContext(ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 } }).outputText, sandbox);
|
||||
return sandbox.exports;
|
||||
}
|
||||
|
||||
test('iOS installed apps launch, recover missing packages, and close before uninstall', async () => {
|
||||
const calls = [], app = { packageId: 'test.app', name: 'Test' };
|
||||
let present = true;
|
||||
const modules = {
|
||||
'../apps/all-apps': { ALL_APPS: [{ appId: 'evenhub' }] },
|
||||
'../apps/evenhub/installed-apps': { getInstalledEvenHubAppById: id => id === 'installed' ? app : null,
|
||||
installedEvenHubPackageId: id => id === 'installed' ? app.packageId : null,
|
||||
uninstallEvenHubPackage: id => calls.push(['uninstall', id]) },
|
||||
'../apps/evenhub/updates': { isInstalledPackagePresent: () => present },
|
||||
'../apps/evenhub': { openEvenHubStoreForPackage: (_ctx, value) => calls.push(['reinstall', value.packageId]) },
|
||||
'../apps/evenhub/manager': { launchInstalledPackage: (ctx, value) => calls.push(['launch', ctx.appId, value.packageId]),
|
||||
closeRunningPackage: id => calls.push(['close', id]) },
|
||||
};
|
||||
const { IosPreviewController } = load('app/g2/ios-preview-controller.ts', { require: id => modules[id] ?? {} });
|
||||
const host = Object.create(IosPreviewController.prototype);
|
||||
host.buildAppContext = app => app; host.fail = assert.fail; host.requestShellRender = () => {};
|
||||
await host.launchApp('installed'); present = false; await host.launchApp('installed');
|
||||
await host.uninstallApp('installed');
|
||||
assert.deepEqual(calls, [['launch', 'installed', 'test.app'], ['reinstall', 'test.app'], ['close', 'test.app'], ['uninstall', 'test.app']]);
|
||||
});
|
||||
|
||||
test('iOS settings prompts honor password input and report cancellation', async () => {
|
||||
const prompts = [], writes = [];
|
||||
const { IosPreviewController } = load('app/g2/ios-preview-controller.ts', { require: id => id === '@nativescript/core' ? {
|
||||
Dialogs: { prompt: async options => { prompts.push(options); return { result: false, text: 'discarded' }; } },
|
||||
} : {} });
|
||||
const host = Object.create(IosPreviewController.prototype); host.active = true;
|
||||
const accepted = await host.editSetting({ editorTitle: 'Password', inputKind: 'password', get: () => '', set: value => writes.push(value) });
|
||||
assert.equal(prompts[0].inputType, 'password');
|
||||
assert.equal(accepted, false); assert.deepEqual(writes, []);
|
||||
});
|
||||
test('iOS phone battery distinguishes unknown, charging, full and unplugged readings', () => {
|
||||
const device = { batteryLevel: -1, batteryState: 0 };
|
||||
const api = load('app/native/phone-battery.ts', { require: () => ({}), global: { isIOS: true },
|
||||
@@ -102,6 +134,7 @@ test('background glasses input still composites frames; phone resume preserves t
|
||||
'./glance-host': { GlanceHost: class { dismiss() {} isVisible() { return false; } } },
|
||||
'./device-addresses': { loadDeviceAddresses: () => ({}) }, './ios-peripheral-identity': { deviceAddressError: () => null },
|
||||
'../apps/launcher/launcher-app': { createLauncherWindow: () => window, LAUNCHER_SURFACE_ID: 'launcher' },
|
||||
'../apps/launcher': { launcherEntries: () => [] },
|
||||
'../apps/all-apps': { ALL_APPS: [] }, '../ui/dashboard-settings': settings,
|
||||
'../native/phone-battery': { readPhoneBatteryState: () => ({ battery: 80, charging: false }) },
|
||||
'../graphics/surface-compositor': { SurfaceCompositor: class {
|
||||
@@ -169,6 +202,7 @@ test('iOS bandwidth footer toggles live, polls only in foreground and resets its
|
||||
"../native/ios-navigation-sensors": {},
|
||||
'../native/compass.ios': { bindCompassSession() {}, receiveCompassEvent() {} },
|
||||
'@nativescript/core': core,
|
||||
'../apps/launcher': { launcherEntries: () => [] },
|
||||
'../apps/all-apps': { ALL_APPS: [] },
|
||||
'../g2/ios-preview-controller': { IosPreviewController: class { resume() {} pause() {} } },
|
||||
'./phone-gestures': { PhoneGestureRecognizer: class { cancel() {} } },
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// Run the production WKWebView host in an isolated simulator app, no glasses.
|
||||
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');
|
||||
@@ -25,11 +26,21 @@ if (!(await fetch('/%2e%2e/secret.txt')).ok) await call('traversal');
|
||||
fs.writeFileSync(path.join(dist, 'module.js'), 'export const value = 42;');
|
||||
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>UILaunchScreen</key><dict/><key>LSRequiresIPhoneOS</key><true/></dict></plist>`);
|
||||
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',
|
||||
'-I', 'App_Resources/iOS/src', 'tests/native/ios-evenhub-test.m', 'App_Resources/iOS/src/FaceclawEvenHubWebView.m', '-o', path.join(bundle, 'EvenHubProbe')], { cwd: root, stdio: 'inherit' });
|
||||
'-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' });
|
||||
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));
|
||||
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', () => {
|
||||
fs.writeFileSync(path.join(bundle, 'remote.txt'), `http://127.0.0.1:${server.address().port}/`);
|
||||
const device = process.argv[2] || 'booted';
|
||||
execFileSync('xcrun', ['simctl', 'install', device, bundle], { stdio: 'inherit' });
|
||||
execFileSync('xcrun', ['simctl', 'launch', '--terminate-running-process', device, 'com.faceclaw.evenhub-probe'], { stdio: 'inherit' });
|
||||
@@ -39,4 +50,6 @@ setTimeout(() => {
|
||||
const result = JSON.parse(fs.readFileSync(resultFile, 'utf8'));
|
||||
console.log(JSON.stringify({ work, ...result }));
|
||||
if (!result.passed) process.exitCode = 1;
|
||||
}, 14000);
|
||||
server.closeAllConnections(); server.close();
|
||||
}, 23000);
|
||||
});
|
||||
@@ -52,7 +52,7 @@ test('EHPK entrypoints and extraction paths cannot escape their package director
|
||||
});
|
||||
|
||||
test('Files on iOS exposes Run app for EHPKs and passes the selected local path', () => {
|
||||
let browserOptions, actions, opened;
|
||||
let browserOptions, actions, opened, installed;
|
||||
const load = loader({ global: { isIOS: true } }, {
|
||||
'../../native/file-access': {}, '../../native/font-files': { isFontFile: () => false },
|
||||
'../../graphics/installed-fonts': {}, '../../native/image-files': { isDecodableImageFile: () => false },
|
||||
@@ -62,12 +62,13 @@ test('Files on iOS exposes Run app for EHPKs and passes the selected local path'
|
||||
'./font-previewer': {}, './image-viewer': {}, './text-viewer': {},
|
||||
'../../ui/shell/in-process-window': { createInProcessWindow: () => ({}) }, '../../ui/shell/shell': {},
|
||||
});
|
||||
load('app/apps/files/files-app.ts').createFilesAppWindow({ openEhpkApp: path => { opened = path; } });
|
||||
load('app/apps/files/files-app.ts').createFilesAppWindow({ openEhpkApp: path => { opened = path; }, installEhpkApp: path => { installed = path; } });
|
||||
assert.equal(browserOptions.isSupportedFile('test.EHPK'), true);
|
||||
const ctx = { stack: { push() {}, pop() {} } };
|
||||
browserOptions.onFilePicked({ name: 'test.ehpk', path: '/Documents/test.ehpk' }, ctx);
|
||||
assert.deepEqual(Array.from(actions, a => a.label), ['Run app']);
|
||||
assert.deepEqual(Array.from(actions, a => a.label), ['Run app', 'Install']);
|
||||
actions[0].onSelect(ctx); assert.equal(opened, '/Documents/test.ehpk');
|
||||
actions[1].onSelect(ctx); assert.equal(installed, '/Documents/test.ehpk');
|
||||
});
|
||||
|
||||
test('local package runtimes unpack independently and clean up after closing or a failed launch', async () => {
|
||||
@@ -82,7 +83,7 @@ test('local package runtimes unpack independently and clean up after closing or
|
||||
deletePathRecursively: path => { for (const key of files.keys()) if (key.startsWith(path + '/')) files.delete(key); } },
|
||||
'./session': { EvenHubSession: Session }, './evenhub-window': { createEvenHubWindow: () => ({}) },
|
||||
'./webview': { createEvenHubWebView: () => ({ evaluateJs() {}, destroy() {} }) },
|
||||
'../../ui/shell/shell': {}, './installed-apps': {},
|
||||
'../../ui/shell/shell': {}, './installed-apps': { readEvenHubPackageManifest: () => ({ packageId: 'test.app' }) },
|
||||
});
|
||||
const manager = load('app/apps/evenhub/manager.ts'), ctx = { appendLog() {}, launchInProcessApp: async () => {} };
|
||||
await manager.launchPackage(ctx, '/test.ehpk'); await manager.launchPackage(ctx, '/test.ehpk');
|
||||
@@ -97,7 +98,7 @@ test('local package runtimes unpack independently and clean up after closing or
|
||||
assert.equal(files.size, 0);
|
||||
});
|
||||
|
||||
function sessionHarness() {
|
||||
function sessionHarness(overrides = {}) {
|
||||
const settings = new Map(), 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) } },
|
||||
@@ -106,7 +107,7 @@ function sessionHarness() {
|
||||
'../../ui/dashboard-settings': {}, '../../ui/sound-effects': {}, './api-key-dialog': {},
|
||||
'./mic-router': { evenHubMicRouter: {} }, './imu-router': { evenHubImuRouter: {} },
|
||||
'./compass-router': { evenHubCompassRouter: {} }, '../../assistant/tool-registry': {},
|
||||
'../../native/location': {}, '../../native/location-tracker': {}, '../../g2/android-permissions': {},
|
||||
'../../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));
|
||||
@@ -142,7 +143,7 @@ test('injected EvenHub RPC creates, updates and composites an image page with no
|
||||
|
||||
test('iOS webview adapter defers loading until handles attach and destroys a not-yet-loaded app', () => {
|
||||
const timers = new Map(), calls = [];
|
||||
const native = { startEntrypointScript: (...args) => calls.push(args), destroy: () => calls.push('destroy') };
|
||||
const native = { startEntrypointScript: (...args) => calls.push(args), startURLScript: (...args) => calls.push(args), destroy: () => calls.push('destroy') };
|
||||
const load = loader({ FaceclawEvenHubWebView: { new: () => native },
|
||||
setTimeout: fn => { timers.set(1, fn); return 1; }, clearTimeout: id => timers.delete(id) }, {
|
||||
'./session': { EVENHUB_BRIDGE_INJECT_SCRIPT: 'BRIDGE', buildFaceclawExtensionsScript: () => 'EXT' }, '../../version': { FACECLAW_VERSION: 'test' },
|
||||
@@ -152,5 +153,70 @@ test('iOS webview adapter defers loading until handles attach and destroys a not
|
||||
const host = createEvenHubWebView(session); assert.equal(calls.length, 0);
|
||||
timers.get(1)(); assert.equal(calls[0][0], '/app/dist'); assert.match(calls[0][2], /postMessage/); assert.match(calls[0][2], /BRIDGEEXT$/);
|
||||
host.destroy(); assert.equal(timers.size, 0); assert.equal(calls.at(-1), 'destroy');
|
||||
assert.throws(() => createEvenHubWebView({ ...session, remoteUrl: 'https://example.test' }), /local/);
|
||||
const remote = createEvenHubWebView({ ...session, remoteUrl: 'https://example.test' });
|
||||
timers.get(1)(); assert.equal(calls.at(-1)[0], 'https://example.test');
|
||||
remote.destroy();
|
||||
});
|
||||
|
||||
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 };
|
||||
const h = sessionHarness({
|
||||
'../../native/location-permissions': { ensureFineLocationPermission: async () => permission },
|
||||
'../../native/location': { getCurrentLocation: async () => fix },
|
||||
'../../native/location-tracker': { LocationTracker: class {
|
||||
constructor(value) { callback = value; } start() { starts++; } stop() { stops++; }
|
||||
} },
|
||||
});
|
||||
assert.equal(await h.call('getAppLocation'), null); // No manifest permission.
|
||||
h.session.manifest.permissions.push({ name: 'location' });
|
||||
assert.deepEqual(JSON.parse(JSON.stringify(await h.call('getAppLocation'))), {
|
||||
latitude: 12, longitude: 34, accuracy: 5, timestamp: 1234,
|
||||
});
|
||||
permission = false;
|
||||
assert.equal(await h.call('startAppLocationUpdates'), false);
|
||||
permission = true;
|
||||
assert.equal(await h.call('startAppLocationUpdates'), true);
|
||||
assert.equal(starts, 1);
|
||||
const events = [];
|
||||
h.web._listenEvenAppMessage = value => events.push(typeof value === 'string' ? JSON.parse(value) : value);
|
||||
callback.onLocation(fix);
|
||||
assert.equal(events.at(-1).method, 'appLocationChanged');
|
||||
h.session.close();
|
||||
assert.equal(stops, 1);
|
||||
});
|
||||
|
||||
test('iOS store terminal identity persists and signing crosses the native boundary', () => {
|
||||
const settings = new Map();
|
||||
const api = loader({ NSUUID: { UUID: () => ({ UUIDString: '12345678-1234-5678-90AB-123456789ABC' }) },
|
||||
FaceclawCrypto: { hmacSha256Message: (key, body) => require('node:crypto').createHmac('sha256', key).update(body).digest('base64') },
|
||||
}, { '../../native/settings-store': {
|
||||
getStringSetting: (key, fallback) => settings.get(key) ?? fallback,
|
||||
setStringSetting: (key, value) => settings.set(key, value),
|
||||
} })('app/apps/evenhub/even-platform.ios.ts');
|
||||
assert.equal(api.getPhoneOpenUdid(), '1234567812345678');
|
||||
assert.equal(api.getPhoneOpenUdid(), '1234567812345678');
|
||||
assert.equal(settings.size, 1);
|
||||
assert.equal(api.hmacSha256Base64('key', 'The quick brown fox jumps over the lazy dog'), '97yD9DBThCSxMpjmqm+xQ+9NWaFJRhdZl0edvC0aPNg=');
|
||||
});
|
||||
|
||||
test('store login and catalog requests use platform signing with the shared wire format', async () => {
|
||||
const requests = [], signatures = [];
|
||||
let token = '';
|
||||
const api = loader({ setTimeout, clearTimeout }, {
|
||||
'./even-platform': { getPhoneOpenUdid: () => 'fixture-terminal', hmacSha256Base64: (_key, value) => { signatures.push(value); return 'fixture-signature'; } },
|
||||
'./credentials': { getEvenHubToken: () => token, hasEvenHubCredentials: () => !!token,
|
||||
saveEvenHubSession: (_email, value) => { token = value; }, invalidateEvenHubToken() {} },
|
||||
'../../util/http': { fetchWithUserAgent: async (url, init) => {
|
||||
requests.push({ url, ...init });
|
||||
return { status: 200, json: async () => ({ code: 0, data: url.endsWith('/login') ? { token: 'fixture-token' } : { list: [], total: 0 } }) };
|
||||
} },
|
||||
})('app/apps/evenhub/even-api.ts');
|
||||
await api.evenHubApi.signIn('test@example.invalid', 'fixture-password', false);
|
||||
await api.evenHubApi.listApps();
|
||||
assert.equal(requests.length, 2);
|
||||
assert.match(requests[0].headers.common, /openUdid=fixture-terminal/);
|
||||
assert.equal(requests[1].headers.token, 'fixture-token');
|
||||
assert.equal(requests[1].headers.sign, 'fixture-signature');
|
||||
assert.equal(signatures[0], api.signingParts('POST', '/v2/g/login', requests[0].headers.common, '', '', requests[0].body));
|
||||
});
|
||||
@@ -82,6 +82,8 @@ function fixture() {
|
||||
'../native/nightscout-bridge': { nightscoutBridge: { async start() {}, async stop() {} } },
|
||||
'./glance-host': { GlanceHost }, './events': events,
|
||||
'./device-addresses': { loadDeviceAddresses: () => ({}) }, './ios-peripheral-identity': { deviceAddressError: () => null },
|
||||
'../apps/launcher': { launcherEntries: () => [] },
|
||||
'../apps/evenhub/installed-apps': {}, '../apps/evenhub/manager': {}, '../apps/evenhub/updates': {}, '../apps/evenhub': {},
|
||||
'../apps/launcher/launcher-app': { createLauncherWindow: () => window, LAUNCHER_SURFACE_ID: 'launcher' },
|
||||
'../apps/all-apps': { ALL_APPS: [{ appId: 'glanceboard', glanceboard: provider }] },
|
||||
'../ui/shell/worker-window': {}, '../ui/shell/in-process-window': {},
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#import <UIKit/UIKit.h>
|
||||
#import "FaceclawEvenHubWebView.h"
|
||||
#import "FaceclawCrypto.h"
|
||||
|
||||
@interface Probe : UIResponder <UIApplicationDelegate>
|
||||
@property(nonatomic) UIWindow *window;
|
||||
@@ -20,6 +21,8 @@
|
||||
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"])
|
||||
[weakSelf.seen addObject:@"blocked-navigation"];
|
||||
if ([event[@"kind"] isEqual:@"call"]) {
|
||||
[weakSelf.seen addObject:event[@"name"]];
|
||||
[weakSelf.seen addObject:[NSString stringWithFormat:@"%ld:%@", (long)weakSelf.phase, event[@"name"]]];
|
||||
@@ -31,19 +34,25 @@
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self.host start:[root stringByAppendingPathComponent:@"dist"] entrypoint:@"index.html" script:script];
|
||||
});
|
||||
for (NSInteger phase = 2; phase <= 3; phase++) {
|
||||
for (NSInteger phase = 2; phase <= 5; phase++) {
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (phase - 1) * 4 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
|
||||
void (^handler)(NSString *) = self.host.eventHandler;
|
||||
[self.host showOnPhone]; [self.host hideOnPhone]; [self.host destroy];
|
||||
self.phase = phase; self.host = [FaceclawEvenHubWebView new];
|
||||
self.host.eventHandler = handler;
|
||||
self.host.packageIdentifier = phase == 2 ? package : [package stringByAppendingString:@".other"];
|
||||
[self.host start:[root stringByAppendingPathComponent:@"dist"] entrypoint:@"index.html" script:script];
|
||||
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];
|
||||
}
|
||||
});
|
||||
}
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 12 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
|
||||
NSArray *required = @[@"early", @"module", @"fetch", @"image", @"timer", @"raf", @"wasm", @"traversal", @"1:stored", @"2:restored", @"3:stored"];
|
||||
BOOL passed = [[NSSet setWithArray:required] isSubsetOfSet:self.seen];
|
||||
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"];
|
||||
NSString *signature = [FaceclawCrypto hmacSha256:@"key" message:@"The quick brown fox jumps over the lazy dog"];
|
||||
passed &= [signature isEqual:@"97yD9DBThCSxMpjmqm+xQ+9NWaFJRhdZl0edvC0aPNg="];
|
||||
[self.host showOnPhone]; [self.host hideOnPhone]; [self.host destroy];
|
||||
NSDictionary *result = @{@"passed": @(passed), @"seen": self.seen.allObjects};
|
||||
NSData *data = [NSJSONSerialization dataWithJSONObject:result options:0 error:nil];
|
||||
|
||||
Reference in new issue
Block a user