installed-update-package-content.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. /** Verify identity and update configuration from an extracted installer payload, not a neighboring unpacked build. */
  2. import { createHash } from 'node:crypto'
  3. import { mkdtemp, readFile } from 'node:fs/promises'
  4. import { createRequire } from 'node:module'
  5. import { dirname, join } from 'node:path'
  6. import { load } from 'js-yaml'
  7. import { readAsar, type Node as AsarNode } from 'app-builder-lib/out/asar/asar.js'
  8. import { readInstalledUpdateRun } from './installed-update-qualification.ts'
  9. import { verifyInstalledUpdateApplication } from './prepare-installed-update-application.ts'
  10. import { inventoryDesktopRuntime, readDesktopRuntime, runtimePath, verifyDesktopRuntime } from '../src/runtime-tree.ts'
  11. import { resolveDesktopPolicyConfig } from '../src/mandatory-update-policy.ts'
  12. const require = createRequire(import.meta.url)
  13. const builderRequire = createRequire(require.resolve('app-builder-lib/package.json'))
  14. const { extractAll } = builderRequire('@electron/asar') as { extractAll: (archive: string, destination: string) => void }
  15. const { createTransformer } = builderRequire('app-builder-lib/out/fileTransformer.js') as {
  16. createTransformer: (source: string, configuration: object, metadata: null) =>
  17. (file: string) => string | null | Promise<string | null>
  18. }
  19. function object(value: unknown): Record<string, unknown> {
  20. if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new Error('installed update: invalid package metadata')
  21. return value as Record<string, unknown>
  22. }
  23. /**
  24. * Check the actual payload's ASAR, bundled runtime, private identity, feed, cache, and publisher metadata.
  25. * @param manifest Retained qualification manifest.
  26. * @param version Exact selected version.
  27. * @param payload Extracted installer payload in a private verification directory.
  28. * @param publisher Expected DN derived from the public release certificate.
  29. * @returns Content observations only; signatures, installation, and restart are separate checks.
  30. */
  31. export async function verifyInstalledUpdatePackageContent(manifest: string, version: string, payload: string, publisher: string) {
  32. const run = await readInstalledUpdateRun(manifest)
  33. if (!run.versions.includes(version)) throw new Error('installed update: payload version is outside the run')
  34. await verifyInstalledUpdateApplication(run.root)
  35. const archive = await readAsar(join(payload, 'resources/app.asar'))
  36. const metadata = object(await archive.readJson('package.json'))
  37. const policy = resolveDesktopPolicyConfig(metadata.dshMandatoryUpdatePolicy)
  38. if (metadata.name !== `dsh-update-test-${run.id}` || metadata.version !== version
  39. || metadata.dshDesktopAppId !== run.appId || metadata.main !== 'qualification-bootstrap.mjs'
  40. || metadata.type !== 'module' || policy?.authentication !== 'feishu-test') {
  41. throw new Error('installed update: packaged application identity, version, entry, or policy differs')
  42. }
  43. const inventory = JSON.parse(await readFile(join(run.root, 'application/result.json'), 'utf8')) as {
  44. files: { path: string; sha256: string }[]
  45. }
  46. const expectedPaths = new Set(inventory.files.map(file => file.path))
  47. const inspect = (node: AsarNode, path = ''): void => {
  48. if (path === 'node_modules' || path === 'package.json') return
  49. if (node.link !== undefined || (node.unpacked === true && !path.startsWith('dsh/'))) {
  50. throw new Error('installed update: application archive contains external entries')
  51. }
  52. if (node.files !== undefined) {
  53. for (const [name, child] of Object.entries(node.files)) {
  54. if (name === '.' || name === '..' || /[\\/:*?"<>|\x00-\x1f]/u.test(name)) {
  55. throw new Error('installed update: application archive contains an unsafe path')
  56. }
  57. inspect(child, path === '' ? name : `${path}/${name}`)
  58. }
  59. } else if (!path.startsWith('dsh/') && !expectedPaths.has(path)) {
  60. throw new Error('installed update: application archive contains additional files')
  61. }
  62. }
  63. inspect(archive.header)
  64. if (archive.header.files?.dsh?.files === undefined) throw new Error('installed update: application archive lacks the dsh runtime')
  65. for (const file of inventory.files) {
  66. const path = file.path.split('/').join(process.platform === 'win32' ? '\\' : '/')
  67. const node = archive.getFile(path, false)
  68. if (node.link !== undefined || node.unpacked === true
  69. || createHash('sha256').update(await archive.readFile(path)).digest('hex') !== file.sha256) {
  70. throw new Error('installed update: packaged application file differs from frozen inputs')
  71. }
  72. }
  73. const dependencies = []
  74. for (const name of ['electron-updater', 'semver']) {
  75. const actual = object(await archive.readJson(join('node_modules', name, 'package.json')))
  76. const expected = object(JSON.parse(await readFile(require.resolve(`${name}/package.json`), 'utf8')))
  77. if (actual.name !== name || actual.version !== expected.version) throw new Error('installed update: packaged updater dependency differs from verification tools')
  78. dependencies.push({ name, version: actual.version })
  79. }
  80. const update = object(load(await readFile(join(payload, 'resources/app-update.yml'), 'utf8')))
  81. const url = `${run.origin}/${run.feedKey.slice(0, -'nightly.yml'.length)}`
  82. if (update.provider !== 'generic' || update.url !== url || update.channel !== 'nightly'
  83. || update.updaterCacheDirName !== `dsh-update-test-${run.id}-updater`
  84. || !Array.isArray(update.publisherName) || update.publisherName.length !== 1 || update.publisherName[0] !== publisher) {
  85. throw new Error('installed update: packaged feed, cache identity, channel, or publisher differs')
  86. }
  87. const extracted = await mkdtemp(join(dirname(payload), 'asar-'))
  88. extractAll(join(payload, 'resources/app.asar'), extracted)
  89. const prepared = await verifyDesktopRuntime(join(run.root, version, 'dsh'), version, { platform: 'win32', arch: 'x64' })
  90. const runtime = readDesktopRuntime(join(extracted, 'dsh'))
  91. if (JSON.stringify(runtime.release) !== JSON.stringify(prepared.release)
  92. || JSON.stringify(runtime.sharedPackages) !== JSON.stringify(prepared.sharedPackages)
  93. || JSON.stringify(runtime.files.map(file => file.path)) !== JSON.stringify(prepared.files.map(file => file.path))) {
  94. throw new Error('installed update: packaged runtime does not describe the prepared release')
  95. }
  96. const actualFiles = inventoryDesktopRuntime(join(extracted, 'dsh'))
  97. if (JSON.stringify(actualFiles.map(file => file.path)) !== JSON.stringify(prepared.files.map(file => file.path))) {
  98. throw new Error('installed update: packaged runtime file list differs from prepared inputs')
  99. }
  100. const transform = createTransformer('', {}, null)
  101. for (const [index, file] of prepared.files.entries()) {
  102. if (file.path.endsWith('.exe')) continue
  103. if (runtime.files[index]!.sha256 !== file.sha256 || runtime.files[index]!.bytes !== file.bytes) {
  104. throw new Error('installed update: non-executable runtime descriptor differs from prepared inputs')
  105. }
  106. const transformed = file.path.startsWith('node_modules/') && file.path.endsWith('/package.json')
  107. ? await transform(runtimePath(join(run.root, version, 'dsh'), file.path)) : null
  108. const bytes = transformed === null ? file.bytes : Buffer.byteLength(transformed)
  109. const hash = transformed === null ? file.sha256 : createHash('sha256').update(transformed).digest('hex')
  110. if (actualFiles[index]!.sha256 !== hash || actualFiles[index]!.bytes !== bytes) {
  111. throw new Error('installed update: non-executable runtime bytes differ from prepared inputs')
  112. }
  113. }
  114. return { version, appId: run.appId, applicationFiles: inventory.files.length, dependencies, dependenciesFrozen: false,
  115. runtimeFiles: runtime.files.length, feedUrl: `${run.origin}/${run.feedKey}`, installed: false,
  116. resignedExecutables: runtime.files.filter(file => file.path.endsWith('.exe')).map((file) => {
  117. if (archive.getFile(join('dsh', file.path), false).unpacked !== true) {
  118. throw new Error('installed update: executable runtime file must be outside ASAR')
  119. }
  120. return join(payload, 'resources/app.asar.unpacked/dsh', file.path)
  121. }) }
  122. }