File size: 14,553 Bytes
8a29801
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
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()
    }
  })
})