diff --git a/App_Resources/iOS/Info.plist b/App_Resources/iOS/Info.plist index b79da82a..de7e7ba7 100644 --- a/App_Resources/iOS/Info.plist +++ b/App_Resources/iOS/Info.plist @@ -44,7 +44,7 @@ NSLocalNetworkUsageDescription - Faceclaw connects to the terminal servers you configure on your local network. + Faceclaw connects to the terminal servers and developer app URLs you configure on your local network. UILaunchScreen UISupportedInterfaceOrientations diff --git a/App_Resources/iOS/src/FaceclawCrypto.h b/App_Resources/iOS/src/FaceclawCrypto.h new file mode 100644 index 00000000..1ae03b25 --- /dev/null +++ b/App_Resources/iOS/src/FaceclawCrypto.h @@ -0,0 +1,4 @@ +#import +@interface FaceclawCrypto : NSObject ++ (NSString *)hmacSha256:(NSString *)secret message:(NSString *)message; +@end diff --git a/App_Resources/iOS/src/FaceclawCrypto.m b/App_Resources/iOS/src/FaceclawCrypto.m new file mode 100644 index 00000000..fe6b9362 --- /dev/null +++ b/App_Resources/iOS/src/FaceclawCrypto.m @@ -0,0 +1,12 @@ +#import "FaceclawCrypto.h" +#import +#import +@implementation FaceclawCrypto ++ (NSString *)hmacSha256:(NSString *)secret message:(NSString *)message { + NSData *key = [secret dataUsingEncoding:NSUTF8StringEncoding]; + NSData *data = [message dataUsingEncoding:NSUTF8StringEncoding]; + unsigned char digest[CC_SHA256_DIGEST_LENGTH]; + CCHmac(kCCHmacAlgSHA256, key.bytes, key.length, data.bytes, data.length, digest); + return [[NSData dataWithBytes:digest length:sizeof(digest)] base64EncodedStringWithOptions:0]; +} +@end diff --git a/App_Resources/iOS/src/FaceclawEvenHubWebView.h b/App_Resources/iOS/src/FaceclawEvenHubWebView.h index 04f3827d..0634e501 100644 --- a/App_Resources/iOS/src/FaceclawEvenHubWebView.h +++ b/App_Resources/iOS/src/FaceclawEvenHubWebView.h @@ -1,11 +1,12 @@ #import #import -/** One local EHPK runtime, retained by its TS session until its window closes. */ +/** One local or URL EvenHub runtime, retained by its TS session until its window closes. */ @interface FaceclawEvenHubWebView : NSObject @property(nonatomic, copy) void (^eventHandler)(NSString *json); @property(nonatomic, copy) NSString *packageIdentifier; - (void)start:(NSString *)directory entrypoint:(NSString *)entrypoint script:(NSString *)script; +- (void)startURL:(NSString *)url script:(NSString *)script; - (void)evaluate:(NSString *)script; - (void)showOnPhone; - (void)hideOnPhone; diff --git a/App_Resources/iOS/src/FaceclawEvenHubWebView.m b/App_Resources/iOS/src/FaceclawEvenHubWebView.m index f31b1cec..32f7bfd4 100644 --- a/App_Resources/iOS/src/FaceclawEvenHubWebView.m +++ b/App_Resources/iOS/src/FaceclawEvenHubWebView.m @@ -9,6 +9,7 @@ @property(nonatomic) UIButton *back; @property(nonatomic) NSTimer *timer; @property(nonatomic) NSString *directory; +@property(nonatomic) NSURL *remoteURL; @property(nonatomic) BOOL ticking; @property(nonatomic) BOOL destroyed; @end @@ -21,6 +22,20 @@ } - (void)start:(NSString *)directory entrypoint:(NSString *)entrypoint script:(NSString *)script { _directory = directory.stringByStandardizingPath.stringByResolvingSymlinksInPath; + NSURLComponents *url = [NSURLComponents new]; + url.scheme = @"faceclaw-ehpk"; url.host = @"app"; url.path = [@"/" stringByAppendingString:entrypoint]; + [self startRequest:url.URL script:script]; +} +- (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) { + [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; WKWebViewConfiguration *config = [WKWebViewConfiguration new]; // Isolate browser storage by package, retaining it across closing/reopening. // SDK storage also persists independently through the shared TS session. @@ -81,9 +96,7 @@ }]; }]; [NSRunLoop.mainRunLoop addTimer:_timer forMode:NSRunLoopCommonModes]; - NSURLComponents *url = [NSURLComponents new]; - url.scheme = @"faceclaw-ehpk"; url.host = @"app"; url.path = [@"/" stringByAppendingString:entrypoint]; - [_webView loadRequest:[NSURLRequest requestWithURL:url.URL]]; + [_webView loadRequest:[NSURLRequest requestWithURL:url]]; } - (void)evaluate:(NSString *)script { if (!_destroyed) [_webView evaluateJavaScript:script completionHandler:nil]; @@ -104,16 +117,25 @@ [_webView.configuration.userContentController removeAllUserScripts]; [_host removeFromSuperview]; _host = nil; _back = 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]; +} - (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 || ![url.scheme isEqual:@"faceclaw-ehpk"] || ![url.host isEqual:@"app"]) return; + if (!message.frameInfo.isMainFrame || ![self allowsURL:url]) 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 local = [url.scheme isEqual:@"faceclaw-ehpk"] && [url.host isEqual:@"app"]; - decisionHandler(local && action.targetFrame.isMainFrame ? WKNavigationActionPolicyAllow : WKNavigationActionPolicyCancel); + 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); } - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { [self emit:@{@"kind": @"loaded"}]; @@ -131,7 +153,7 @@ NSURL *url = task.request.URL; NSString *relative = [url.path stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"/"]]; NSString *file = [[_directory stringByAppendingPathComponent:relative] stringByStandardizingPath].stringByResolvingSymlinksInPath; - BOOL allowed = !_destroyed && [url.host isEqual:@"app"] && + BOOL allowed = !_destroyed && _directory.length && !_remoteURL && [url.host isEqual:@"app"] && [file hasPrefix:[_directory stringByAppendingString:@"/"]]; NSData *data = allowed ? [NSData dataWithContentsOfFile:file options:NSDataReadingMappedIfSafe error:nil] : nil; NSString *ext = file.pathExtension.lowercaseString; diff --git a/App_Resources/iOS/src/FaceclawGraphics.h b/App_Resources/iOS/src/FaceclawGraphics.h index 333f6bc2..1a8eacf7 100644 --- a/App_Resources/iOS/src/FaceclawGraphics.h +++ b/App_Resources/iOS/src/FaceclawGraphics.h @@ -4,4 +4,5 @@ + (UIImage *)preview:(NSData *)gray width:(NSInteger)width height:(NSInteger)height green:(BOOL)green; + (NSData *)renderSVG:(NSString *)svg size:(NSInteger)size; + (NSData *)decodeImage:(NSData *)data width:(NSInteger)width height:(NSInteger)height; ++ (NSData *)decodeImageFile:(NSString *)path maxWidth:(NSInteger)maxWidth maxHeight:(NSInteger)maxHeight; @end diff --git a/App_Resources/iOS/src/FaceclawGraphics.m b/App_Resources/iOS/src/FaceclawGraphics.m index 361e7353..b66b7411 100644 --- a/App_Resources/iOS/src/FaceclawGraphics.m +++ b/App_Resources/iOS/src/FaceclawGraphics.m @@ -3,6 +3,29 @@ #import @implementation FaceclawGraphics ++ (NSData *)decodeImageFile:(NSString *)path maxWidth:(NSInteger)maxWidth maxHeight:(NSInteger)maxHeight { + if (maxWidth <= 0 || maxHeight <= 0 || maxWidth > 2048 || maxHeight > 2048) return nil; + NSURL *url = [NSURL fileURLWithPath:path]; + CGImageSourceRef source = CGImageSourceCreateWithURL((__bridge CFURLRef)url, NULL); + if (!source) return nil; + NSDictionary *properties = CFBridgingRelease(CGImageSourceCopyPropertiesAtIndex(source, 0, NULL)); + CFRelease(source); + double width = [properties[(id)kCGImagePropertyPixelWidth] doubleValue]; + double height = [properties[(id)kCGImagePropertyPixelHeight] doubleValue]; + if (width <= 0 || height <= 0) return nil; + NSInteger orientation = [properties[(id)kCGImagePropertyOrientation] integerValue]; + if (orientation >= 5 && orientation <= 8) { double swap = width; width = height; height = swap; } + double scale = MIN(1.0, MIN(maxWidth / width, maxHeight / height)); + NSInteger w = MAX(1, lround(width * scale)), h = MAX(1, lround(height * scale)); + NSData *bytes = [NSData dataWithContentsOfURL:url options:NSDataReadingMappedIfSafe error:nil]; + NSData *gray = [self decodeImage:bytes width:w height:h]; + if (!gray) return nil; + // Same dimensions + pixels packet used by the shared image adapter. + uint8_t dimensions[] = { w & 255, (w >> 8) & 255, h & 255, (h >> 8) & 255 }; + NSMutableData *packet = [NSMutableData dataWithBytes:dimensions length:4]; + [packet appendData:gray]; + return packet; +} + (NSData *)decodeImage:(NSData *)data width:(NSInteger)width height:(NSInteger)height { if (!data.length || width <= 0 || height <= 0 || width > 2048 || height > 2048) return nil; CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL); diff --git a/App_Resources/iOS/src/module.modulemap b/App_Resources/iOS/src/module.modulemap index 0f331e57..7c750302 100644 --- a/App_Resources/iOS/src/module.modulemap +++ b/App_Resources/iOS/src/module.modulemap @@ -9,5 +9,6 @@ module FaceclawGraphics { header "FaceclawLocation.h" header "FaceclawConfigPort.h" header "FaceclawEvenHubWebView.h" + header "FaceclawCrypto.h" export * } diff --git a/app/apps/developer/developer-app.ts b/app/apps/developer/developer-app.ts index 0ae11eef..1d68b04d 100644 --- a/app/apps/developer/developer-app.ts +++ b/app/apps/developer/developer-app.ts @@ -108,8 +108,6 @@ export function createDeveloperAppWindow(appContext: AppContext, options: InProc [ { label: "Load app from URL", - disabled: global.isIOS, - description: global.isIOS ? "Not available on iOS yet." : undefined, onSelect: (ctx) => { const layer = new LoadAppFromUrlLayer(appContext); ctx.stack.push(layer); diff --git a/app/apps/evenhub/compass-router.ts b/app/apps/evenhub/compass-router.ts index 0d8e7910..e9a33d46 100644 --- a/app/apps/evenhub/compass-router.ts +++ b/app/apps/evenhub/compass-router.ts @@ -80,7 +80,7 @@ class EvenHubCompassRouter { }); } if (!this.enabled) { - setCompassEnabled(true); + setCompassEnabled(true, "evenhub"); this.enabled = true; // Uses location only if the wearer already granted it; an app turning // on the compass is not a reason to raise a system permission prompt. @@ -88,7 +88,7 @@ class EvenHubCompassRouter { } } else { if (this.enabled) { - setCompassEnabled(false); + setCompassEnabled(false, "evenhub"); this.enabled = false; } this.unsubscribe?.(); diff --git a/app/apps/evenhub/ehpk.ts b/app/apps/evenhub/ehpk.ts index 28638f1a..e7f56bae 100644 --- a/app/apps/evenhub/ehpk.ts +++ b/app/apps/evenhub/ehpk.ts @@ -76,42 +76,55 @@ export function utf8Decode(bytes: Uint8Array): string { return out; } -export function parseEhpk(data: Uint8Array): EhpkArchive { - if (data.length < 20 || data[0] !== 0x45 || data[1] !== 0x48 || data[2] !== 0x50 || data[3] !== 0x4b) { +/** Index compressed records without expanding assets merely to read app.json. */ +export function openEhpk(data: Uint8Array) { + if (data.length < 20 || data[0] !== 0x45 || data[1] !== 0x48 || data[2] !== 0x50 || data[3] !== 0x4b) throw new Error("not an EHPK file"); - } const view = new DataView(data.buffer, data.byteOffset, data.byteLength); - const firstRecord = view.getUint32(8, true); - const files = new Map(); - - let p = firstRecord; + const records = new Map(); + const requireBytes = (offset: number, length: number) => { + if (offset < 20 || length < 0 || offset + length > data.length) throw new Error("ehpk: truncated record"); + }; + let p = view.getUint32(8, true); + requireBytes(p, 0); while (p < data.length) { + requireBytes(p, 4); const type = data[p]!; - if (data[p + 1] !== 0xba || data[p + 2] !== 0xa9 || data[p + 3] !== 0xba) { + if (data[p + 1] !== 0xba || data[p + 2] !== 0xa9 || data[p + 3] !== 0xba) throw new Error(`ehpk: bad record magic at ${p}`); - } if (type === RECORD_FILE) { - const compressedLength = view.getUint32(p + 4, true); - const uncompressedLength = view.getUint32(p + 8, true); + requireBytes(p, 16); + const compressed = view.getUint32(p + 4, true), size = view.getUint32(p + 8, true); const nameLength = view.getUint16(p + 14, true); + requireBytes(p + 16, nameLength + compressed); const name = utf8Decode(unxor(data, p + 16, nameLength)); if (!safeEhpkPath(name)) throw new Error(`ehpk: invalid file path ${name}`); - const blob = unxor(data, p + 16 + nameLength, compressedLength); - const content = decompress(blob, new Uint8Array(uncompressedLength)); - if (content.length !== uncompressedLength) { - throw new Error(`ehpk: ${name}: expected ${uncompressedLength} bytes, got ${content.length}`); - } - files.set(name, content); - p += 16 + nameLength + compressedLength; + records.set(name, { offset: p + 16 + nameLength, compressed, size }); + p += 16 + nameLength + compressed; } else if (type === RECORD_DIR) { - const nameLength = view.getUint16(p + 6, true); - p += 8 + nameLength; - } else if (type === RECORD_FOOTER) { - break; - } else { - throw new Error(`ehpk: unknown record type 0x${type.toString(16)} at ${p}`); - } + requireBytes(p, 8); + const length = view.getUint16(p + 6, true); + requireBytes(p + 8, length); p += 8 + length; + } else if (type === RECORD_FOOTER) break; + else throw new Error(`ehpk: unknown record type 0x${type.toString(16)} at ${p}`); } + return { files: { + keys: () => records.keys(), + has: (name: string) => records.has(name), + get: (name: string): Uint8Array | undefined => { + const record = records.get(name); + if (!record) return undefined; + const content = decompress(unxor(data, record.offset, record.compressed), new Uint8Array(record.size)); + if (content.length !== record.size) throw new Error(`ehpk: ${name}: expected ${record.size} bytes, got ${content.length}`); + return content; + }, + } }; +} +export type EhpkIndex = ReturnType; + +export function parseEhpk(data: Uint8Array): EhpkArchive { + const index = openEhpk(data), files = new Map(); + for (const name of index.files.keys()) files.set(name, index.files.get(name)!); return { files }; } diff --git a/app/apps/evenhub/even-api.ts b/app/apps/evenhub/even-api.ts index 971a10ec..932e008c 100644 --- a/app/apps/evenhub/even-api.ts +++ b/app/apps/evenhub/even-api.ts @@ -5,16 +5,17 @@ * it only discovers and downloads public .ehpk packages. Authentication is * the same signed-header scheme used by the firmware API. */ -import { Application } from "@nativescript/core"; +import { hmacSha256Base64, getPhoneOpenUdid } from "./even-platform"; +export { getPhoneOpenUdid } from "./even-platform"; import { getEvenHubToken, hasEvenHubCredentials, invalidateEvenHubToken, saveEvenHubSession, } from "./credentials"; +import { downloadBinary } from "../../native/binary-http"; import { fetchWithUserAgent } from "../../util/http"; -declare const android: any; const API_HOST = "https://api.evenrealities.com"; const PUBLIC_CDN_HOST = "https://cdn-pub.evenhub.evenrealities.com"; @@ -128,9 +129,9 @@ export class EvenHubApiClient { const url = typeof metadata.url === "string" ? metadata.url : ""; if (!url.startsWith("https://")) throw new Error("EvenHub returned no package download URL."); - const response = await fetchWithTimeout(url, {}, 60_000); - if (!response.ok) throw new Error(`EvenHub package download failed (HTTP ${response.status}).`); - const bytes = new Uint8Array(await response.arrayBuffer()); + const response = await downloadBinary(url, 60_000); + if (response.status < 200 || response.status >= 300) throw new Error(`EvenHub package download failed (HTTP ${response.status}).`); + const bytes = response.bytes; const expectedSize = finiteNumber(metadata.size); if (expectedSize > 0 && bytes.length !== expectedSize) { throw new Error(`EvenHub package was truncated (${bytes.length} of ${expectedSize} bytes).`); @@ -156,11 +157,11 @@ export class EvenHubApiClient { if (!/^prod\/[A-Za-z0-9._~!$&'()*+,;=:@%/-]+\.(?:svg|png|webp|jpe?g)$/i.test(cleanPath) || cleanPath.includes("..")) { throw new Error("EvenHub returned an invalid public asset path."); } - const response = await fetchWithTimeout(`${PUBLIC_CDN_HOST}/${cleanPath}`, {}, 30_000); - if (!response.ok) throw new Error(`EvenHub icon download failed (HTTP ${response.status}).`); - const contentLength = Number(response.headers.get("Content-Length") ?? 0); + const response = await downloadBinary(`${PUBLIC_CDN_HOST}/${cleanPath}`, 30_000); + if (response.status < 200 || response.status >= 300) throw new Error(`EvenHub icon download failed (HTTP ${response.status}).`); + const contentLength = response.contentLength; if (contentLength > 1_000_000) throw new Error("EvenHub icon is unexpectedly large."); - const bytes = new Uint8Array(await response.arrayBuffer()); + const bytes = response.bytes; if (bytes.length === 0 || bytes.length > 1_000_000) throw new Error("EvenHub icon is empty or too large."); const extension = cleanPath.toLowerCase().match(/\.([a-z0-9]+)$/)?.[1] ?? ""; return { bytes, extension: extension === "jpeg" ? "jpg" : extension }; @@ -287,9 +288,9 @@ function buildCommon(version: 1 | 3): string { buildTime: "26060821", appId: "1001", v: version, - // This is Android's app-scoped SSAID. Even's login endpoint registers a - // previously unseen value as a terminal, so Faceclaw does not need the - // official Even app's differently-scoped ID. + // Keep the established wire profile on both platforms. Even registers + // this installation-scoped terminal ID at login (SSAID on Android, + // a persisted random ID on iOS). openUdid: getPhoneOpenUdid(), os: "1", sn: "", @@ -333,13 +334,7 @@ function formEncode(value: string): string { } function hmacSign(message: string): string { - if (!global.isAndroid) throw new Error("The EvenHub storefront is currently available only on Android."); - const charset = java.nio.charset.StandardCharsets.UTF_8; - const key = new javax.crypto.spec.SecretKeySpec(new java.lang.String(SIGN_KEY).getBytes(charset), "HmacSHA256"); - const mac = javax.crypto.Mac.getInstance("HmacSHA256"); - mac.init(key); - const digest = mac.doFinal(new java.lang.String(message).getBytes(charset)); - return String(android.util.Base64.encodeToString(digest, android.util.Base64.NO_WRAP)); + return hmacSha256Base64(SIGN_KEY, message); } async function fetchWithTimeout(url: string, init: RequestInit, timeoutMs = REQUEST_TIMEOUT_MS): Promise { @@ -368,17 +363,6 @@ function unwrap(envelope: ApiEnvelope, httpStatus: number, path: string): unknow return envelope.data; } -/** Return this installation's Android ID, which Even calls `openUdid`. */ -export function getPhoneOpenUdid(): string { - if (!global.isAndroid) throw new Error("The EvenHub storefront is currently available only on Android."); - const resolver = Application.android.context?.getContentResolver(); - const openUdid = resolver - ? String(android.provider.Settings.Secure.getString(resolver, android.provider.Settings.Secure.ANDROID_ID) ?? "") - : ""; - if (!openUdid) throw new Error("Android did not provide a device ID for EvenHub authentication."); - return openUdid; -} - /** * Parse a list response. The leaderboard returns `{list, total, page, * page_size}`; the ranking/search endpoints were only recovered from the diff --git a/app/apps/evenhub/even-platform.ios.ts b/app/apps/evenhub/even-platform.ios.ts new file mode 100644 index 00000000..3753f1eb --- /dev/null +++ b/app/apps/evenhub/even-platform.ios.ts @@ -0,0 +1,17 @@ +import { getStringSetting, setStringSetting } from "../../native/settings-store"; +declare const FaceclawCrypto: any; + +export function hmacSha256Base64(secret: string, message: string): string { + return FaceclawCrypto.hmacSha256Message(secret, message); +} + +/** A stable random terminal ID, independent of phone hardware identifiers. */ +export function getPhoneOpenUdid(): string { + const key = "integrations.evenhub.terminalId"; + let id = getStringSetting(key, ""); + if (!id) { + id = NSUUID.UUID().UUIDString.replace(/-/g, "").slice(0, 16).toLowerCase(); + setStringSetting(key, id); + } + return id; +} diff --git a/app/apps/evenhub/even-platform.ts b/app/apps/evenhub/even-platform.ts new file mode 100644 index 00000000..bee53a2c --- /dev/null +++ b/app/apps/evenhub/even-platform.ts @@ -0,0 +1,17 @@ +import { Application } from "@nativescript/core"; + +export function hmacSha256Base64(secret: string, message: string): string { + const charset = java.nio.charset.StandardCharsets.UTF_8; + const key = new javax.crypto.spec.SecretKeySpec(new java.lang.String(secret).getBytes(charset), "HmacSHA256"); + const mac = javax.crypto.Mac.getInstance("HmacSHA256"); + mac.init(key); + const digest = mac.doFinal(new java.lang.String(message).getBytes(charset)); + return String(android.util.Base64.encodeToString(digest, android.util.Base64.NO_WRAP)); +} + +export function getPhoneOpenUdid(): string { + const resolver = Application.android.context?.getContentResolver(); + const id = resolver ? String(android.provider.Settings.Secure.getString(resolver, android.provider.Settings.Secure.ANDROID_ID) ?? "") : ""; + if (!id) throw new Error("Android did not provide a device ID for EvenHub authentication."); + return id; +} diff --git a/app/apps/evenhub/installed-apps.ts b/app/apps/evenhub/installed-apps.ts index f9743cde..ea05c4f1 100644 --- a/app/apps/evenhub/installed-apps.ts +++ b/app/apps/evenhub/installed-apps.ts @@ -13,10 +13,10 @@ import { writeBinaryFile, } from "../../native/file-access"; import { getStringSetting, setStringSetting } from "../../native/settings-store"; -import { loadImageFileAsGray } from "../../native/image-files"; +import { loadIconImage } from "../../native/icon-image"; import { renderSvgIcon } from "../../graphics/icons"; import { type GrayImage } from "../../graphics/image"; -import { parseEhpk, parseManifest, utf8Decode, type EhpkArchive, type EvenHubManifest } from "./ehpk"; +import { openEhpk, parseManifest, utf8Decode, type EhpkIndex, type EvenHubManifest } from "./ehpk"; const STORAGE_KEY = "evenhub.installedApps.v1"; const APP_ID_PREFIX = "evenhub-installed:"; @@ -209,7 +209,7 @@ export function renderInstalledEvenHubIcon( const svg = readTextFile(path); if (svg) image = renderSvgIcon(cacheKey, svg, size); } else { - image = loadImageFileAsGray(path, size, size); + image = loadIconImage(path, size, size); } renderedIconCache.set(cacheKey, image); return image; @@ -220,8 +220,8 @@ export function getInstalledEvenHubFingerprint(): string { return getStringSetting(STORAGE_KEY, ""); } -function inspectEhpk(bytes: Uint8Array): { archive: EhpkArchive; manifest: EvenHubManifest } { - const archive = parseEhpk(bytes); +function inspectEhpk(bytes: Uint8Array): { archive: EhpkIndex; manifest: EvenHubManifest } { + const archive = openEhpk(bytes); const appJson = archive.files.get("app.json"); if (!appJson) throw new Error("The EHPK package has no app.json manifest."); return { archive, manifest: parseManifest(utf8Decode(appJson)) }; @@ -242,7 +242,7 @@ function saveInstalledApps(apps: InstalledEvenHubApp[]): void { ); } -function findEmbeddedIcon(archive: EhpkArchive, manifest: EvenHubManifest): EvenHubInstallIcon | null { +function findEmbeddedIcon(archive: EhpkIndex, manifest: EvenHubManifest): EvenHubInstallIcon | null { const candidates: string[] = []; for (const key of ["icon", "icon_path", "iconPath", "app_icon", "appIcon"]) { const value = manifest.raw[key]; @@ -270,11 +270,11 @@ function findEmbeddedIcon(archive: EhpkArchive, manifest: EvenHubManifest): Even if (content && extension) return { bytes: content, extension }; } } - const fallback = Array.from(archive.files.entries()).find(([path]) => + const fallback = Array.from(archive.files.keys()).find((path) => /(?:^|\/)(?:app-?)?(?:icon|favicon)\.(?:svg|png|webp|jpe?g)$/i.test(path), ); - const extension = fallback ? iconExtension(fallback[0]) : null; - return fallback && extension ? { bytes: fallback[1], extension } : null; + const extension = fallback ? iconExtension(fallback) : null; + return fallback && extension ? { bytes: archive.files.get(fallback)!, extension } : null; } function normalizeInstallIcon(icon: EvenHubInstallIcon | undefined): EvenHubInstallIcon | null { diff --git a/app/apps/evenhub/manager.ts b/app/apps/evenhub/manager.ts index 036f9b3e..a247d98b 100644 --- a/app/apps/evenhub/manager.ts +++ b/app/apps/evenhub/manager.ts @@ -15,16 +15,16 @@ import { type AppContext } from "../app-definition"; import { appFilesDirPath, deletePathRecursively, - readBinaryFile, - writeBinaryFile, } from "../../native/file-access"; -import { parseEhpk, parseManifest, utf8Decode, type EvenHubManifest } from "./ehpk"; +import { type EvenHubManifest } from "./ehpk"; +import { unpackRuntime } from "./unpack-runtime"; import { type EvenHubPermission } from "./permissions"; import { EvenHubSession } from "./session"; import { createEvenHubWindow } from "./evenhub-window"; import { createEvenHubWebView, type EvenHubWebView } from "./webview"; import { shell } from "../../ui/shell/shell"; import { + readEvenHubPackageManifest, installedEvenHubAppId, installedEvenHubPackagePath, type InstalledEvenHubApp, @@ -64,17 +64,6 @@ export async function launchPackage( ehpkPath: string, options: { appId?: string; singleton?: boolean } = {}, ): Promise { - const data = readBinaryFile(ehpkPath); - if (!data) { - throw new Error('Could not read the EHPK file.'); - } - const archive = parseEhpk(data); - const appJson = archive.files.get("app.json"); - if (!appJson) { - throw new Error('The EHPK package has no app.json.'); - } - const manifest = parseManifest(utf8Decode(appJson)); - if (!archive.files.has(`dist/${manifest.entrypoint}`)) throw new Error('The EHPK entrypoint is missing from dist/.'); const appId = options.appId ?? "evenhub"; if (options.singleton) { const existing = Array.from(running.values()).find((app) => app.appId === appId); @@ -85,20 +74,19 @@ export async function launchPackage( } } - // Unpack fresh into app-private storage, keyed by package id. + const manifest = readEvenHubPackageManifest(ehpkPath); + if (!manifest) throw new Error('Could not read the EHPK manifest.'); + // Unpack off the iOS UI thread; reserve a unique directory before awaiting. const safeId = manifest.packageId.replace(/[^A-Za-z0-9._-]/g, "_"); if (!safeId || safeId === '.' || safeId === '..') throw new Error('Invalid EHPK package ID'); - const baseDir = `${appFilesDirPath()}/evenhub-apps/${safeId}${global.isIOS ? `-${Date.now()}-${nextSerial}` : ''}`; - deletePathRecursively(baseDir); - for (const [name, content] of Array.from(archive.files)) { - if (!writeBinaryFile(`${baseDir}/${name}`, content)) { - deletePathRecursively(baseDir); - throw new Error(`Could not unpack ${name}.`); - } - } - - try { await startApp(ctx, manifest, `${baseDir}/dist`, "", appId, global.isIOS ? () => deletePathRecursively(baseDir) : undefined); } - catch (error) { deletePathRecursively(baseDir); throw error; } + const baseDir = `${appFilesDirPath()}/evenhub-apps/${safeId}${global.isIOS ? `-${Date.now()}-${nextSerial++}` : ''}`; + const started = Date.now(); + ctx.appendLog(`evenhub: unpacking ${manifest.name}`); + try { + const loadedManifest = await unpackRuntime(ehpkPath, baseDir); + ctx.appendLog(`evenhub: unpacked ${loadedManifest.name} in ${Date.now() - started} ms`); + await startApp(ctx, loadedManifest, `${baseDir}/dist`, "", appId, global.isIOS ? () => deletePathRecursively(baseDir) : undefined); + } catch (error) { deletePathRecursively(baseDir); throw error; } } /** diff --git a/app/apps/evenhub/package-extraction.ts b/app/apps/evenhub/package-extraction.ts new file mode 100644 index 00000000..bbe9720c --- /dev/null +++ b/app/apps/evenhub/package-extraction.ts @@ -0,0 +1,20 @@ +import { deletePathRecursively, readBinaryFile, writeBinaryFile } from '../../native/file-access'; +import { openEhpk, parseManifest, utf8Decode, type EvenHubManifest } from './ehpk'; + +/** Called on a worker on iOS. Hold only one expanded asset at a time. */ +export function extractPackage(path: string, directory: string): EvenHubManifest { + try { + const bytes = readBinaryFile(path); + if (!bytes) throw new Error('Could not read the EHPK file.'); + const archive = openEhpk(bytes); + const json = archive.files.get('app.json'); + if (!json) throw new Error('The EHPK package has no app.json.'); + const manifest = parseManifest(utf8Decode(json)); + if (!archive.files.has(`dist/${manifest.entrypoint}`)) throw new Error('The EHPK entrypoint is missing from dist/.'); + deletePathRecursively(directory); + for (const name of archive.files.keys()) { + if (!writeBinaryFile(`${directory}/${name}`, archive.files.get(name)!)) throw new Error(`Could not unpack ${name}.`); + } + return manifest; + } catch (error) { deletePathRecursively(directory); throw error; } +} diff --git a/app/apps/evenhub/package-extraction.worker.ts b/app/apps/evenhub/package-extraction.worker.ts new file mode 100644 index 00000000..3d6d0adc --- /dev/null +++ b/app/apps/evenhub/package-extraction.worker.ts @@ -0,0 +1,9 @@ +import '@nativescript/core/globals'; +import { extractPackage } from './package-extraction'; + +global.onmessage = (event: { data: { path: string; directory: string } }) => { + try { + const manifest = extractPackage(event.data.path, event.data.directory); + global.postMessage({ manifest }); + } catch (error) { global.postMessage({ error: String((error as Error)?.message ?? error) }); } +}; diff --git a/app/apps/evenhub/session.ts b/app/apps/evenhub/session.ts index 318f7cd6..f9b073a3 100644 --- a/app/apps/evenhub/session.ts +++ b/app/apps/evenhub/session.ts @@ -61,7 +61,7 @@ import { type ImuReading } from "../../native/imu"; import { toolRegistry, type ToolResult, type ToolSpec } from "../../assistant/tool-registry"; import { getCurrentLocation } from "../../native/location"; import { LocationTracker, type TrackedLocation } from "../../native/location-tracker"; -import { ensureFineLocationPermission } from "../../g2/android-permissions"; +import { ensureFineLocationPermission } from "../../native/location-permissions"; const UPNG = require("upng-js"); @@ -642,7 +642,6 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH /** getAppLocation(): one-shot fix, or null on denial/error (SDK contract). */ private async getAppLocation(): Promise { - if (global.isIOS) return null; if (!this.declaresLocation()) return null; if (!(await ensureFineLocationPermission())) return null; try { @@ -666,7 +665,6 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH * Navigate app's foreground-service-backed tracking. */ private async startLocationUpdates(data: Record): Promise { - if (global.isIOS) return false; if (!this.declaresLocation()) return false; if (!(await ensureFineLocationPermission())) return false; if (this.closed) return false; diff --git a/app/apps/evenhub/store-detail-layer.ts b/app/apps/evenhub/store-detail-layer.ts index ab179023..f3b93803 100644 --- a/app/apps/evenhub/store-detail-layer.ts +++ b/app/apps/evenhub/store-detail-layer.ts @@ -133,24 +133,36 @@ export class EvenHubStoreDetailLayer implements Layer { } if (event.type !== "click") return; - await this.ensureDetail(ctx); + // Never hold the serialized input queue across network work or a dialog + // that needs a subsequent input to resolve. + void this.activate(ctx); + } - if (this.selectedIndex === 0) { - ctx.stack.push(new TextViewerLayer(this.app.description || "No description supplied.", "About")); - return; - } - if (this.selectedIndex === 1) { - ctx.stack.push(new TextViewerLayer(this.app.changelog || "No release notes supplied.", "What's New")); - return; - } + private async activate(ctx: LayerContext): Promise { + this.working = true; + try { + await this.ensureDetail(ctx); - const installed = getInstalledEvenHubApp(this.app.packageId); - if (installed && this.primaryActionLabel(installed) === "Launch") { - await this.options.launchApp(installedEvenHubAppId(installed.packageId)); - return; - } + if (this.selectedIndex === 0) { + ctx.stack.push(new TextViewerLayer(this.app.description || "No description supplied.", "About")); + return; + } + if (this.selectedIndex === 1) { + ctx.stack.push(new TextViewerLayer(this.app.changelog || "No release notes supplied.", "What's New")); + return; + } - await this.install(ctx); + const installed = getInstalledEvenHubApp(this.app.packageId); + if (installed && this.primaryActionLabel(installed) === "Launch") { + await this.options.launchApp(installedEvenHubAppId(installed.packageId)); + return; + } + + await this.install(ctx); + } catch (error) { + this.status = cleanError(error); + this.options.appendLog(`evenhub store: ${this.status}`); + } finally { this.working = false; ctx.actions.requestRender(); } } /** Install for a new app; Update / Reinstall when the installed copy is stale or gone. */ diff --git a/app/apps/evenhub/store-layer.ts b/app/apps/evenhub/store-layer.ts index 82df0fee..c2c044e6 100644 --- a/app/apps/evenhub/store-layer.ts +++ b/app/apps/evenhub/store-layer.ts @@ -674,6 +674,7 @@ export class EvenHubStoreLayer implements Layer { void this.submitCredentials(ctx); }, { setting: evenHubRememberMeSetting, label: "Remember me" }, + () => { this.phoneEditor = "none"; clearEvenHubLoginForm(); }, ); } @@ -684,7 +685,7 @@ export class EvenHubStoreLayer implements Layer { this.phoneEditor = "none"; if (this.closed) return; void this.runSearch(ctx, evenHubSearchQuerySetting.get()); - }); + }, undefined, () => { this.phoneEditor = "none"; }); } /** Close the phone editor if one is open (optionally only a given kind). */ diff --git a/app/apps/evenhub/unpack-runtime.ios.ts b/app/apps/evenhub/unpack-runtime.ios.ts new file mode 100644 index 00000000..478294a3 --- /dev/null +++ b/app/apps/evenhub/unpack-runtime.ios.ts @@ -0,0 +1,21 @@ +import type { EvenHubManifest } from './ehpk'; + +/** Paths and a small manifest cross isolates; package bytes never become JSON. */ +export function unpackRuntime(path: string, directory: string): Promise { + return new Promise((resolve, reject) => { + const worker = new Worker('./package-extraction.worker'); + let settled = false; + const finish = (error?: string, manifest?: EvenHubManifest) => { + if (settled) return; + settled = true; clearTimeout(timeout); worker.terminate(); + if (error) reject(new Error(error)); + else if (manifest) resolve(manifest); + else reject(new Error('The package worker returned no manifest.')); + }; + const timeout = setTimeout(() => finish('Unpacking the EvenHub app timed out.'), 180_000); + worker.onmessage = (event: MessageEvent) => finish(event.data.error, event.data.manifest); + worker.onerror = event => { finish(String(event.message ?? event)); return true; }; + try { worker.postMessage({ path, directory }); } + catch (error) { finish(String(error)); } + }); +} diff --git a/app/apps/evenhub/unpack-runtime.ts b/app/apps/evenhub/unpack-runtime.ts new file mode 100644 index 00000000..5d7ceab6 --- /dev/null +++ b/app/apps/evenhub/unpack-runtime.ts @@ -0,0 +1,5 @@ +import { extractPackage } from './package-extraction'; +import type { EvenHubManifest } from './ehpk'; +export async function unpackRuntime(path: string, directory: string): Promise { + return extractPackage(path, directory); +} diff --git a/app/apps/evenhub/webview.ios.ts b/app/apps/evenhub/webview.ios.ts index d4421b0a..e32ecdbd 100644 --- a/app/apps/evenhub/webview.ios.ts +++ b/app/apps/evenhub/webview.ios.ts @@ -21,7 +21,6 @@ window.__faceclawEvenHub = { postMessage: function(name, args, id) { ` export function createEvenHubWebView(session: EvenHubSession): EvenHubWebView { - if (session.remoteUrl) throw new Error('On iOS, open a local .ehpk package from Files.') const host = FaceclawEvenHubWebView.new() host.packageIdentifier = session.manifest.packageId host.eventHandler = (json: string) => { @@ -35,8 +34,11 @@ export function createEvenHubWebView(session: EvenHubSession): EvenHubWebView { } catch (error) { console.warn(`EvenHub bridge: ${error}`) } } // Defer loading until manager.ts has attached the session/window handles. - const loading = setTimeout(() => host.startEntrypointScript(session.distDir, session.manifest.entrypoint, - IOS_EVENHUB_TRANSPORT_SCRIPT + EVENHUB_BRIDGE_INJECT_SCRIPT + buildFaceclawExtensionsScript(`Faceclaw/${FACECLAW_VERSION}`)), 0) + const script = IOS_EVENHUB_TRANSPORT_SCRIPT + EVENHUB_BRIDGE_INJECT_SCRIPT + buildFaceclawExtensionsScript(`Faceclaw/${FACECLAW_VERSION}`) + const loading = setTimeout(() => { + if (session.remoteUrl) host.startURLScript(session.remoteUrl, script) + else host.startEntrypointScript(session.distDir, session.manifest.entrypoint, script) + }, 0) return { native: host, evaluateJs: js => host.evaluate(js), destroy: () => { clearTimeout(loading); host.destroy() }, showOnPhone: () => host.showOnPhone(), hideOnPhone: () => host.hideOnPhone() } diff --git a/app/apps/files/files-app.ts b/app/apps/files/files-app.ts index f628289d..615c8f9a 100644 --- a/app/apps/files/files-app.ts +++ b/app/apps/files/files-app.ts @@ -210,7 +210,7 @@ function fileOpenActions(entry: DirectoryEntry, options: FilesAppOptions): FileI }, }, ]; - return global.isIOS ? actions.slice(0, 1) : actions; + return actions; } if (isDecodableImageFile(entry.name)) { return [ diff --git a/app/apps/ios-availability.ts b/app/apps/ios-availability.ts index 52de7cfd..6b585eb1 100644 --- a/app/apps/ios-availability.ts +++ b/app/apps/ios-availability.ts @@ -5,7 +5,6 @@ const unavailable: Record = { transcribe: 'Voice capture and transcription are not available on iOS yet.', microphones: 'Glasses microphone capture is not available on iOS yet.', calendar: 'Calendar access is not available on iOS yet.', - evenhub: 'Open a local .ehpk file in Files to run an EvenHub app. The EvenHub store is not available on iOS yet.', } export function iosAppUnavailableReason(appId: string): string | null { return unavailable[appId] ?? null diff --git a/app/apps/launcher/index.ts b/app/apps/launcher/index.ts index 1d3786cc..1c16f4b9 100644 --- a/app/apps/launcher/index.ts +++ b/app/apps/launcher/index.ts @@ -7,6 +7,28 @@ import { renderInstalledEvenHubIcon, } from "../evenhub/installed-apps"; +/** Shared built-in and installed-app listing for both phone hosts. */ +export function launcherEntries(apps: readonly AppDefinition[]) { + return [ + ...apps + .filter((app) => app.showInLauncher !== false) + .map((app) => ({ + appId: app.appId, + label: app.title, + icon: app.icon, + renderIcon: app.renderIcon, + })), + ...getInstalledEvenHubApps().map((app) => ({ + appId: installedEvenHubAppId(app.packageId), + label: app.name, + icon: "package" as const, + renderIcon: (size: number) => renderInstalledEvenHubIcon(app.packageId, size, app), + iconKey: `${app.installedAt}:${app.iconFile ?? ""}`, + uninstallable: true, + })), + ]; +} + const launcherApp: AppDefinition = { appId: "launcher", title: "Apps", @@ -22,24 +44,7 @@ const launcherApp: AppDefinition = { ...ctx.actions, requestRender: () => shell.foregroundWindow()?.requestRender(), }, - apps: () => [ - ...ctx.apps - .filter((app) => app.showInLauncher !== false) - .map((app) => ({ - appId: app.appId, - label: app.title, - icon: app.icon, - renderIcon: app.renderIcon, - })), - ...getInstalledEvenHubApps().map((app) => ({ - appId: installedEvenHubAppId(app.packageId), - label: app.name, - icon: "package" as const, - renderIcon: (size: number) => renderInstalledEvenHubIcon(app.packageId, size, app), - iconKey: `${app.installedAt}:${app.iconFile ?? ""}`, - uninstallable: true, - })), - ], + apps: () => launcherEntries(ctx.apps), launchApp: (appId) => ctx.launchApp(appId), uninstallApp: (appId) => ctx.uninstallApp(appId), submitFrame: (planes, paintMs, frameId) => ctx.submitWindowFrame(LAUNCHER_SURFACE_ID, planes, paintMs, frameId), diff --git a/app/g2/ios-preview-controller.ts b/app/g2/ios-preview-controller.ts index 2fe50f27..8e211581 100644 --- a/app/g2/ios-preview-controller.ts +++ b/app/g2/ios-preview-controller.ts @@ -1,3 +1,8 @@ +import { launcherEntries } from '../apps/launcher' +import { getInstalledEvenHubAppById, installedEvenHubPackageId, uninstallEvenHubPackage } from '../apps/evenhub/installed-apps' +import { isInstalledPackagePresent } from '../apps/evenhub/updates' +import { openEvenHubStoreForPackage } from '../apps/evenhub' +import { launchInstalledPackage, closeRunningPackage } from '../apps/evenhub/manager' import { registerSystemTools } from '../assistant/system-tools' import { registerWindowTools } from '../assistant/window-tools' import { registerNavigateTools } from '../assistant/navigate-tools' @@ -91,9 +96,14 @@ export class IosPreviewController { startVoiceCapture: () => this.startVoiceCapture(), stopVoiceCapture: () => iosVoiceInput.stopPushToTalk(), startContinuousVoiceCapture: () => this.onError("Voice capture is not available on iOS yet."), - startTextSettingEdit: setting => this.editSetting(setting), - startTextSettingsEdit: async (settings, _title, finished) => { - for (const setting of settings) await this.editSetting(setting) + startTextSettingEdit: async setting => { await this.editSetting(setting) }, + startTextSettingsEdit: async (settings, title, finished, toggle, cancelled) => { + for (const setting of settings) if (!await this.editSetting(setting)) { cancelled?.(); return } + if (toggle) { + const choice = await Dialogs.action({ title, cancelButtonText: 'Cancel', actions: [toggle.label, 'This session only'] }) + if (choice === 'Cancel') { cancelled?.(); return } + toggle.setting.set(choice === toggle.label) + } finished?.() }, } @@ -116,11 +126,9 @@ export class IosPreviewController { }) const launcher = createLauncherWindow({ actions: this.actions, - apps: () => ALL_APPS.filter(app => app.showInLauncher !== false).map(app => ({ - appId: app.appId, label: app.title, icon: app.icon, renderIcon: app.renderIcon, - })), + apps: () => launcherEntries(ALL_APPS), launchApp: id => this.launchApp(id), - uninstallApp: () => {}, + uninstallApp: id => this.uninstallApp(id), submitFrame: planes => this.submit(LAUNCHER_SURFACE_ID, planes), setSurfaceVisible: visible => { this.compositor.setSurfaceVisible(LAUNCHER_SURFACE_ID, visible); this.scheduleFrame() }, }) @@ -293,7 +301,19 @@ export class IosPreviewController { } async launchApp(id: string, params?: AppLaunchParams): Promise { const app = ALL_APPS.find(app => app.appId === id) - if (!app) return + if (!app) { + const installed = getInstalledEvenHubAppById(id) + const host = ALL_APPS.find(app => app.appId === 'evenhub') + if (installed && host) { + try { + if (isInstalledPackagePresent(installed.packageId)) + await launchInstalledPackage(this.buildAppContext({ ...host, appId: id }), installed) + else await openEvenHubStoreForPackage(this.buildAppContext(host), installed) + } + catch (error) { this.fail(error) } + } + return + } try { const reason = iosAppUnavailableReason(id) if (reason) { @@ -306,10 +326,17 @@ export class IosPreviewController { console.log(`[ios-preview] Launched ${id}`) } catch (error) { this.fail(error) } } + private async uninstallApp(id: string): Promise { + const packageId = installedEvenHubPackageId(id) + if (!packageId) return + closeRunningPackage(packageId) + uninstallEvenHubPackage(packageId) + this.requestShellRender() + } private buildAppContext(app: AppDefinition): AppContext { return { appId: app.appId, apps: ALL_APPS, actions: this.actions, - launchApp: (id, params) => this.launchApp(id, params), uninstallApp: async () => {}, + launchApp: (id, params) => this.launchApp(id, params), uninstallApp: id => this.uninstallApp(id), launchInProcessApp: (id, surface, create) => this.launchInProcessApp(id, surface, create), ensureWorkerHost: create => this.ensureWorkerHost(app.appId, create), submitWindowFrame: (id, planes) => this.submit(id, planes), @@ -441,12 +468,13 @@ export class IosPreviewController { } catch (error) { this.fail(error) } finally { this.prompting = false } } - private async editSetting(setting: { editorTitle: string; get(): string; set(value: string): void }): Promise { - if (!this.active) { this.logBluetooth('Editing text settings requires opening Faceclaw on the phone'); return } - const result = await Dialogs.prompt({ title: setting.editorTitle, defaultText: setting.get(), okButtonText: 'Save', cancelButtonText: 'Cancel' }) + private async editSetting(setting: { editorTitle: string; inputKind?: string; get(): string; set(value: string): void }): Promise { + if (!this.active) { this.logBluetooth('Editing text settings requires opening Faceclaw on the phone'); return false } + const result = await Dialogs.prompt({ title: setting.editorTitle, defaultText: setting.get(), inputType: setting.inputKind, okButtonText: 'Save', cancelButtonText: 'Cancel' }) if (result.result) { setting.set(result.text) if (setting === nightscoutSiteUrlSetting || setting === nightscoutApiTokenSetting) await nightscoutBridge.refreshNow() } + return result.result } } diff --git a/app/native/binary-http.ios.ts b/app/native/binary-http.ios.ts new file mode 100644 index 00000000..d96d9aad --- /dev/null +++ b/app/native/binary-http.ios.ts @@ -0,0 +1,10 @@ +import { Http } from '@nativescript/core'; +import { withUserAgent } from '../util/http'; +import type { BinaryResponse } from './binary-http'; + +/** Bulk NSData -> ArrayBuffer; bypass fetch's Blob/FileReader copies. */ +export async function downloadBinary(url: string, timeoutMs: number): Promise { + const response = await Http.request({ url, method: 'GET', headers: withUserAgent(), timeout: timeoutMs }); + const length = Object.entries(response.headers).find(([name]) => name.toLowerCase() === 'content-length')?.[1]; + return { status: response.statusCode, bytes: new Uint8Array(response.content.toArrayBuffer()), contentLength: Number(length ?? 0) }; +} diff --git a/app/native/binary-http.ts b/app/native/binary-http.ts new file mode 100644 index 00000000..b70b832b --- /dev/null +++ b/app/native/binary-http.ts @@ -0,0 +1,15 @@ +import { fetchWithUserAgent } from '../util/http'; +export type BinaryResponse = { status: number; bytes: Uint8Array; contentLength: number }; +export async function downloadBinary(url: string, timeoutMs: number): Promise { + let timer: ReturnType; + const request = async () => { + const response = await fetchWithUserAgent(url); + return { status: response.status, bytes: new Uint8Array(await response.arrayBuffer()), + contentLength: Number(response.headers.get('Content-Length') ?? 0) }; + }; + try { + return await Promise.race([request(), new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error('Download timed out.')), timeoutMs); + })]); + } finally { clearTimeout(timer!); } +} diff --git a/app/native/icon-image.ios.ts b/app/native/icon-image.ios.ts new file mode 100644 index 00000000..40282046 --- /dev/null +++ b/app/native/icon-image.ios.ts @@ -0,0 +1,9 @@ +import { grayImageFromPacket } from './image-files'; +import { fromData } from './kotlin-data'; +import type { GrayImage } from '../graphics/image'; +declare const FaceclawGraphics: any; + +export function loadIconImage(path: string, maxWidth: number, maxHeight: number): GrayImage | null { + const data = FaceclawGraphics.decodeImageFileMaxWidthMaxHeight(path, Math.round(maxWidth), Math.round(maxHeight)); + return data ? grayImageFromPacket(fromData(data)) : null; +} diff --git a/app/native/icon-image.ts b/app/native/icon-image.ts new file mode 100644 index 00000000..5e2145e4 --- /dev/null +++ b/app/native/icon-image.ts @@ -0,0 +1,3 @@ +import { loadImageFileAsGray } from './image-files'; +/** UI artwork uses flat grayscale, preserving its source aspect ratio. */ +export const loadIconImage = loadImageFileAsGray; diff --git a/app/phone-ui/main-page.ios.ts b/app/phone-ui/main-page.ios.ts index 6e50eac8..2c086ce9 100644 --- a/app/phone-ui/main-page.ios.ts +++ b/app/phone-ui/main-page.ios.ts @@ -1,5 +1,6 @@ import { Application, Button, Color, Dialogs, GridLayout, Image, Label, Page, StackLayout, type TouchGestureEventData } from '@nativescript/core' import { createConfigureDevicesPage } from './config-page.ios' +import { launcherEntries } from '../apps/launcher' import { ALL_APPS } from '../apps/all-apps' import { IosPreviewController } from '../g2/ios-preview-controller' import { PhoneGestureRecognizer } from './phone-gestures' @@ -107,9 +108,9 @@ export function createMainPage(): Page { } const sizeButton = button(controller.displayModeLabel, () => controller.cycleDisplayMode()) settings.addChild(button('Open app', () => { void (async () => { - const apps = ALL_APPS.filter(app => app.showInLauncher !== false).slice().sort((a, b) => a.title.localeCompare(b.title)) - const title = await Dialogs.action({ title: 'Open app', cancelButtonText: 'Cancel', actions: apps.map(app => app.title) }) - const app = apps.find(app => app.title === title) + const apps = launcherEntries(ALL_APPS).sort((a, b) => a.label.localeCompare(b.label)) + const title = await Dialogs.action({ title: 'Open app', cancelButtonText: 'Cancel', actions: apps.map(app => app.label) }) + const app = apps.find(app => app.label === title) if (app) { await controller.launchApp(app.appId); selectTab('watch') } })() })) settings.addChild(sizeButton) diff --git a/app/ui/layers.ts b/app/ui/layers.ts index 32315136..7bd79480 100644 --- a/app/ui/layers.ts +++ b/app/ui/layers.ts @@ -20,6 +20,7 @@ export type LayerActions = { title: string, onFinish?: () => void, toggle?: TextSettingsEditToggle, + onCancel?: () => void, ) => Promise | void; endTextSettingEdit: () => Promise | void; /** diff --git a/tests/evenhub-install-performance.test.cjs b/tests/evenhub-install-performance.test.cjs new file mode 100644 index 00000000..7422183e --- /dev/null +++ b/tests/evenhub-install-performance.test.cjs @@ -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': 'Test', 'dist/icon.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); +}); diff --git a/tests/ios-app-host.test.cjs b/tests/ios-app-host.test.cjs index 2aa4bc01..44435ca6 100644 --- a/tests/ios-app-host.test.cjs +++ b/tests/ios-app-host.test.cjs @@ -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() {} } }, diff --git a/tests/ios-evenhub-native.cjs b/tests/ios-evenhub-native.cjs index 209caffc..edb0b218 100644 --- a/tests/ios-evenhub-native.cjs +++ b/tests/ios-evenhub-native.cjs @@ -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'), `CFBundleIdentifiercom.faceclaw.evenhub-probeCFBundleExecutableEvenHubProbeCFBundleNameEvenHubProbeCFBundlePackageTypeAPPLCFBundleVersion1CFBundleShortVersionString1UILaunchScreenLSRequiresIPhoneOS`); +fs.writeFileSync(path.join(bundle, 'Info.plist'), `CFBundleIdentifiercom.faceclaw.evenhub-probeCFBundleExecutableEvenHubProbeCFBundleNameEvenHubProbeCFBundlePackageTypeAPPLCFBundleVersion1CFBundleShortVersionString1NSAppTransportSecurityNSAllowsLocalNetworkingUILaunchScreenLSRequiresIPhoneOS`); 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(""); 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); +}); diff --git a/tests/ios-evenhub.test.cjs b/tests/ios-evenhub.test.cjs index 69953879..cea6b99b 100644 --- a/tests/ios-evenhub.test.cjs +++ b/tests/ios-evenhub.test.cjs @@ -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)); }); diff --git a/tests/ios-glanceboard.test.cjs b/tests/ios-glanceboard.test.cjs index c90dc62f..0eb9e85e 100644 --- a/tests/ios-glanceboard.test.cjs +++ b/tests/ios-glanceboard.test.cjs @@ -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': {}, diff --git a/tests/native/ios-evenhub-test.m b/tests/native/ios-evenhub-test.m index 83c3230e..3a745d72 100644 --- a/tests/native/ios-evenhub-test.m +++ b/tests/native/ios-evenhub-test.m @@ -1,5 +1,6 @@ #import #import "FaceclawEvenHubWebView.h" +#import "FaceclawCrypto.h" @interface Probe : UIResponder @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];