Download mobile/modules/engine/src/services/__tests__/AppRegistryDevBuild.test.ts from Anirudh1950/MentraOS: direct link, hf CLI and curl.
- Browser
- Download file 14.6 kB
-
https://huggingface.co/Anirudh1950/MentraOS/resolve/main/mobile/modules/engine/src/services/__tests__/AppRegistryDevBuild.test.ts
- Command line
-
hf download hf://Anirudh1950/MentraOS/mobile/modules/engine/src/services/__tests__/AppRegistryDevBuild.test.ts
-
curl -L -o AppRegistryDevBuild.test.ts https://huggingface.co/Anirudh1950/MentraOS/resolve/main/mobile/modules/engine/src/services/__tests__/AppRegistryDevBuild.test.ts
14.6 kB
| import {beforeEach, describe, expect, mock, spyOn, test} from "bun:test" | |
| import {readFileSync} from "node:fs" | |
| import {result as Res} from "typesafe-ts" | |
| import type {MiniappReleaseIdentity} from "../AppRegistry" | |
| // A dev build of a package claims that package's name: the phone applies the | |
| // Android signer rule to it, and Core mints its token marked as a local build's. | |
| ;(globalThis as {__DEV__?: boolean}).__DEV__ = false | |
| const values = new Map<string, unknown>() | |
| const installationValues = new Map<string, string>() | |
| let candidateFingerprint: string | undefined | |
| /** The dev icon's download, which a test may hold open. */ | |
| let iconDownload: () => Promise<{uri: string}> = async () => { | |
| throw new Error("no network in this test") | |
| } | |
| let developmentAllowed = true | |
| let installedAllowed = (_identity: MiniappReleaseIdentity | null) => true | |
| mock.module("../../utils/storage/storage", () => ({ | |
| storage: { | |
| load: (key: string) => (values.has(key) ? Res.ok(values.get(key)) : Res.error(new Error("Missing key"))), | |
| save: (key: string, value: unknown) => { | |
| values.set(key, value) | |
| return Res.ok(undefined) | |
| }, | |
| remove: (key: string) => { | |
| values.delete(key) | |
| return Res.ok(undefined) | |
| }, | |
| }, | |
| })) | |
| mock.module("react-native-mmkv", () => ({ | |
| createMMKV: () => ({ | |
| getString: (key: string) => installationValues.get(key), | |
| set: (key: string, value: string) => installationValues.set(key, value), | |
| remove: (key: string) => installationValues.delete(key), | |
| }), | |
| })) | |
| mock.module("../../runtime/bootstrap", () => ({ | |
| assertMiniappDevelopmentAllowed: () => {}, | |
| getConfigValues: () => ({}), | |
| isDevMiniappAllowed: () => developmentAllowed, | |
| isLocalMiniappPackageAllowed: () => true, | |
| isInstalledMiniappAllowed: (_pkg: string, _version: string, identity: MiniappReleaseIdentity | null) => | |
| installedAllowed(identity), | |
| isOfflineSystemMiniappAllowed: () => true, | |
| isMiniappAvailable: () => true, | |
| })) | |
| mock.module("../../stores/settings", () => ({ | |
| SETTINGS: {super_mode: {key: "super_mode"}}, | |
| useSettingsStore: {getState: () => ({getSetting: () => false})}, | |
| })) | |
| // Downloads succeed; the archive's verified identity comes from the mocked | |
| // validator so each test chooses whether the candidate bundle is signed. | |
| mock.module("expo/fetch", () => ({ | |
| fetch: async (url: string) => { | |
| let read = false | |
| return { | |
| ok: true, | |
| url, | |
| headers: {get: () => null}, | |
| body: { | |
| getReader: () => ({ | |
| read: async () => { | |
| if (read) return {done: true} | |
| read = true | |
| return {done: false, value: Uint8Array.from([1, 2, 3])} | |
| }, | |
| cancel: async () => {}, | |
| releaseLock: () => {}, | |
| }), | |
| }, | |
| } | |
| }, | |
| })) | |
| mock.module("expo-file-system", () => ({ | |
| Directory: class { | |
| exists = false | |
| create() {} | |
| delete() {} | |
| list() { | |
| return [] | |
| } | |
| }, | |
| File: class { | |
| static downloadFileAsync() { | |
| return iconDownload() | |
| } | |
| uri = "file:///test-cache/bundle.zip" | |
| exists = false | |
| write() { | |
| this.exists = true | |
| } | |
| delete() { | |
| this.exists = false | |
| } | |
| async bytes() { | |
| return Uint8Array.from([1, 2, 3]) | |
| } | |
| }, | |
| Paths: {cache: {list: () => []}, document: "file:///test-documents"}, | |
| })) | |
| // Extraction is where an accepted bundle goes next. Reaching it proves the | |
| // publisher gate let the candidate through. | |
| let extractions = 0 | |
| // Extraction checks each unpacked file's real path through Crust. | |
| mock.module("@mentra/crust", () => ({default: {canonicalFilePath: (path: string) => path}})) | |
| mock.module("react-native-zip-archive", () => ({ | |
| unzip: async () => { | |
| extractions += 1 | |
| throw new Error("extraction stopped by test") | |
| }, | |
| })) | |
| mock.module("../../utils/storage/zip", () => ({printDirectory: mock()})) | |
| const realValidation = await import("../validateInstallBundle") | |
| mock.module("../validateInstallBundle", () => ({ | |
| ...realValidation, | |
| validateInstallBundleArchive: async () => ({ | |
| packageName, | |
| version: "1.0.0", | |
| ...(candidateFingerprint ? {publisherKeyFingerprint: candidateFingerprint} : {}), | |
| }), | |
| })) | |
| const { | |
| default: registry, | |
| assertDevBuildAllowed, | |
| getDevAppRecords, | |
| registerDevApp, | |
| SignedMiniappDevBuildError, | |
| } = await import("../AppRegistry") | |
| const {isLocalBuildContext, recordMiniappBuild} = await import("../miniappBuildKind") | |
| const packageName = "com.example.devbuild" | |
| const devRecord = {packageName, name: "Dev Build", iconUrl: "", devUrl: "http://192.168.1.20:3000", devPort: 3001} | |
| function install(version: string, identity: MiniappReleaseIdentity) { | |
| registry["finalizeInstall"](packageName, version, identity, () => {}).apply() | |
| } | |
| function installDevSnapshot() { | |
| return registry.installFromUrl("http://192.168.1.20:3000/bundle.zip", { | |
| expectedPackageName: packageName, | |
| versionOverride: "dev-1000", | |
| releaseIdentity: {source: "dev_snapshot"}, | |
| }) | |
| } | |
| /** The runtime's real token-request method, run against a recording Cloud Client. */ | |
| function tokenRequester() { | |
| const source = readFileSync(new URL("../LocalMiniappRuntime.ts", import.meta.url), "utf8") | |
| const start = source.search(/^ {2}private async requestMiniappAuth\(/m) | |
| if (start < 0) throw new Error("Missing requestMiniappAuth") | |
| const rest = source.slice(start) | |
| const method = rest.slice(0, rest.search(/^ {2}}$/m) + 3) | |
| const compiled = new Bun.Transpiler({loader: "ts"}).transformSync(`class Host { ${method} }`) | |
| const calls: unknown[][] = [] | |
| const cloudClientService = { | |
| hasCore: () => true, | |
| getMiniappAuthToken: async (...args: unknown[]) => { | |
| calls.push(args) | |
| return {token: "miniapp-token"} | |
| }, | |
| } | |
| const Host = new Function("cloudClientService", "isLocalBuildContext", `${compiled}; return Host`)( | |
| cloudClientService, | |
| isLocalBuildContext, | |
| ) | |
| return {host: new Host() as {requestMiniappAuth(pkg: string, opts?: unknown): Promise<unknown>}, calls} | |
| } | |
| beforeEach(() => { | |
| values.clear() | |
| installationValues.clear() | |
| recordMiniappBuild(packageName, {localBuild: false}) | |
| iconDownload = async () => { | |
| throw new Error("no network in this test") | |
| } | |
| candidateFingerprint = undefined | |
| developmentAllowed = true | |
| installedAllowed = () => true | |
| extractions = 0 | |
| }) | |
| describe("live dev builds follow the installed signer", () => { | |
| test("run when the package is not installed", async () => { | |
| await registerDevApp(devRecord) | |
| expect(values.get(`${packageName}_dev_url`)).toBe(devRecord.devUrl) | |
| }) | |
| test("unsigned installed X + unsigned dev X: allowed, marked as a dev build, token marked as a local build's", async () => { | |
| install("1.0.0", {source: "direct_download"}) | |
| expect(registry.getPublisherKeyFingerprint(packageName)).toBeNull() | |
| await registerDevApp(devRecord) | |
| // The phone keeps tracking X as a dev build: its record in the dev index, | |
| // its per-package routing keys, and the dev badge on the projected tile. | |
| expect(getDevAppRecords().map((record) => record.packageName)).toEqual([packageName]) | |
| expect(JSON.parse(values.get("dev_apps_index") as string)).toEqual([packageName]) | |
| expect(values.get(`${packageName}_dev_url`)).toBe(devRecord.devUrl) | |
| expect(values.get(`${packageName}_dev_port`)).toBe(devRecord.devPort) | |
| // Home merges the installed tile with the dev record; the dev build wins. | |
| const installedTile = {packageName, version: "1.0.0", name: "Installed", running: false} | |
| const tiles = registry["mergeProjectedApps"]([installedTile]).filter( | |
| (app: {packageName: string}) => app.packageName === packageName, | |
| ) | |
| expect(tiles).toHaveLength(1) | |
| expect(tiles[0]).toMatchObject({packageName, isMiniappDev: true, devUrl: devRecord.devUrl}) | |
| // The router starts X's context as a development build: its token request names X, marked as a local build. | |
| recordMiniappBuild(packageName, {localBuild: true}) | |
| const {host, calls} = tokenRequester() | |
| await host.requestMiniappAuth(packageName) | |
| await host.requestMiniappAuth(packageName, {minTtlMs: 60_000}) | |
| expect(calls).toEqual([ | |
| [packageName, {localBuild: true}], | |
| [packageName, {minTtlMs: 60_000, localBuild: true}], | |
| ]) | |
| // Its installed release, started again, asks for the package's own token. | |
| recordMiniappBuild(packageName, {localBuild: false}) | |
| await host.requestMiniappAuth(packageName) | |
| expect(calls.at(-1)).toEqual([packageName, undefined]) | |
| }) | |
| test("are refused over a signed install until it is uninstalled", async () => { | |
| install("1.0.0", {source: "direct_download", publisherKeyFingerprint: "sha256:publisher"}) | |
| const refused = registerDevApp(devRecord) | |
| await expect(refused).rejects.toBeInstanceOf(SignedMiniappDevBuildError) | |
| await expect(registerDevApp(devRecord)).rejects.toThrow( | |
| `${packageName} is installed with a publisher signature. Uninstall it before running a development build.`, | |
| ) | |
| expect(() => assertDevBuildAllowed(packageName)).toThrow(SignedMiniappDevBuildError) | |
| expect(values.has(`${packageName}_dev_url`)).toBe(false) | |
| expect(getDevAppRecords()).toEqual([]) | |
| // Uninstalling clears the recorded signer, so the dev build may run. | |
| expect((await registry.uninstall(packageName)).is_ok()).toBe(true) | |
| expect(registry.getPublisherKeyFingerprint(packageName)).toBeNull() | |
| await registerDevApp(devRecord) | |
| expect(values.get(`${packageName}_dev_url`)).toBe(devRecord.devUrl) | |
| }) | |
| }) | |
| describe("registering a dev build", () => { | |
| test("whose session ends while its icon downloads writes no record or routing", async () => { | |
| let finishDownload!: (file: {uri: string}) => void | |
| iconDownload = () => new Promise((resolve) => (finishDownload = resolve)) | |
| let sessionEnded = false | |
| const registering = registerDevApp( | |
| {...devRecord, iconUrl: "http://192.168.1.20:3000/icon.png"}, | |
| { | |
| assertCurrent: () => { | |
| if (sessionEnded) throw new Error("the install's session ended") | |
| }, | |
| }, | |
| ) | |
| await Promise.resolve() | |
| sessionEnded = true | |
| finishDownload({uri: "file:///test-documents/dev-miniapp-icons/icon.png"}) | |
| await expect(registering).rejects.toThrow("the install's session ended") | |
| expect([...values.keys()].filter((key) => key.startsWith(packageName) || key === "dev_apps_index")).toEqual([]) | |
| expect(getDevAppRecords()).toEqual([]) | |
| }) | |
| test("still current after its icon downloads, writes its record and routing", async () => { | |
| iconDownload = async () => ({uri: "file:///test-documents/dev-miniapp-icons/icon.png"}) | |
| await registerDevApp({...devRecord, iconUrl: "http://192.168.1.20:3000/icon.png"}, {assertCurrent: () => {}}) | |
| expect(values.get(`${packageName}_dev_url`)).toBe(devRecord.devUrl) | |
| expect(getDevAppRecords().map((record) => record.iconUrl)).toEqual([ | |
| "file:///test-documents/dev-miniapp-icons/icon.png", | |
| ]) | |
| }) | |
| }) | |
| describe("dev snapshots are installs like any other", () => { | |
| test("an unsigned snapshot cannot replace a signed install", async () => { | |
| install("1.0.0", {source: "direct_download", publisherKeyFingerprint: "sha256:publisher"}) | |
| const result = await installDevSnapshot() | |
| expect(result.is_error() && result.error.message).toContain( | |
| `Unsigned bundle cannot replace signed miniapp ${packageName}`, | |
| ) | |
| expect(extractions).toBe(0) | |
| }) | |
| test("a snapshot signed with another key cannot replace a signed install", async () => { | |
| install("1.0.0", {source: "direct_download", publisherKeyFingerprint: "sha256:publisher"}) | |
| candidateFingerprint = "sha256:laptop" | |
| const result = await installDevSnapshot() | |
| expect(result.is_error() && result.error.message).toContain("Publisher signature mismatch") | |
| expect(extractions).toBe(0) | |
| }) | |
| test("a snapshot signed with the installed key passes the publisher gate", async () => { | |
| install("1.0.0", {source: "direct_download", publisherKeyFingerprint: "sha256:publisher"}) | |
| candidateFingerprint = "sha256:publisher" | |
| await installDevSnapshot() | |
| expect(extractions).toBe(1) | |
| }) | |
| test("an unsigned snapshot replaces an unsigned install without pinning it", async () => { | |
| install("1.0.0", {source: "direct_download"}) | |
| await installDevSnapshot() | |
| expect(extractions).toBe(1) | |
| install("dev-1000", {source: "dev_snapshot"}) | |
| expect(registry.getPublisherKeyFingerprint(packageName)).toBeNull() | |
| }) | |
| test("a signed snapshot pins the package it installs", () => { | |
| install("dev-1000", {source: "dev_snapshot", publisherKeyFingerprint: "sha256:publisher"}) | |
| expect(registry.getPublisherKeyFingerprint(packageName)).toBe("sha256:publisher") | |
| expect(() => assertDevBuildAllowed(packageName)).toThrow(SignedMiniappDevBuildError) | |
| }) | |
| }) | |
| describe("the active version follows the deployment's policy", () => { | |
| test("the newest allowed release wins once development is off", async () => { | |
| const workspaceRelease: MiniappReleaseIdentity = { | |
| source: "deployment_manifest", | |
| bundleSha256: "abc", | |
| deploymentId: "acme", | |
| deploymentOrigin: "https://acme.example", | |
| } | |
| install("1.2.0", workspaceRelease) | |
| install("1.3.0", {source: "direct_download"}) | |
| install("1.4.0", {source: "url", sourceUrl: "https://notes.example.com/"}) | |
| // The workspace allows its managed release, and release-QR installs only while development is on. | |
| installedAllowed = (identity) => | |
| identity?.source === "deployment_manifest" || (developmentAllowed && identity?.source === "direct_download") | |
| const versions = spyOn(registry, "getInstalledVersions").mockReturnValue(["1.2.0", "1.3.0", "1.4.0"]) | |
| let notified = 0 | |
| const unsubscribe = registry.subscribe(() => notified++) | |
| try { | |
| values.set(`${packageName}_active_version`, "1.3.0") | |
| expect(await registry.getActiveVersion(packageName)).toBe("1.3.0") | |
| developmentAllowed = false | |
| expect(await registry.getActiveVersion(packageName)).toBe("1.2.0") | |
| // Selecting it refreshes cached app lists that still hold the release-QR version. | |
| expect(values.get(`${packageName}_active_version`)).toBe("1.2.0") | |
| expect(notified).toBeGreaterThan(0) | |
| } finally { | |
| unsubscribe() | |
| versions.mockRestore() | |
| } | |
| }) | |
| }) | |