desktop-upload-plan.ts 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. /** Validate packaged Desktop update artifacts before any network upload begins. */
  2. import { createHash } from 'node:crypto'
  3. import { createReadStream } from 'node:fs'
  4. import { readFile, stat } from 'node:fs/promises'
  5. import { basename, join, resolve } from 'node:path'
  6. import { load } from 'js-yaml'
  7. import type { DesktopPackageTargetName } from './package-target.ts'
  8. import {
  9. desktopBuildRecordFilename,
  10. desktopUpdateMetadataFilename,
  11. resolveDesktopUploadConfig,
  12. } from './desktop-auto-update-environment.mjs'
  13. import { desktopTargetBuildPaths } from './desktop-build-paths.mjs'
  14. const APP_ROOT = resolve(import.meta.dirname, '..')
  15. const REPOSITORY_ROOT = resolve(APP_ROOT, '..', '..')
  16. const TARGETS = {
  17. 'mac-arm64': { platform: 'darwin', arch: 'arm64', os: 'mac' },
  18. 'mac-x64': { platform: 'darwin', arch: 'x64', os: 'mac' },
  19. 'win-x64': { platform: 'win32', arch: 'x64', os: 'win' },
  20. } as const satisfies Record<DesktopPackageTargetName, {
  21. readonly platform: NodeJS.Platform
  22. readonly arch: string
  23. readonly os: string
  24. }>
  25. /** One local file and its final object metadata. */
  26. export interface DesktopUploadArtifact {
  27. readonly path: string
  28. readonly filename: string
  29. readonly key: string
  30. readonly contentType: string
  31. readonly cacheControl: string
  32. readonly channelMetadata: boolean
  33. }
  34. /** A fully validated upload operation with channel metadata ordered last. */
  35. export interface DesktopUploadPlan {
  36. readonly environment: 'test' | 'production'
  37. readonly target: DesktopPackageTargetName
  38. readonly version: string
  39. readonly publicUrl: string
  40. readonly bucket: string
  41. readonly secretIdEnvName: string
  42. readonly secretKeyEnvName: string
  43. readonly artifacts: readonly DesktopUploadArtifact[]
  44. }
  45. /** Filesystem and environment inputs used to validate one upload. */
  46. export interface DesktopUploadPlanOptions {
  47. readonly environment?: NodeJS.ProcessEnv
  48. readonly repositoryRoot?: string
  49. readonly appRoot?: string
  50. readonly artifactsRoot?: string
  51. }
  52. interface UpdateFileInfo {
  53. readonly filename: string
  54. readonly size: number
  55. readonly sha512: string
  56. }
  57. function object(value: unknown, label: string): Record<string, unknown> {
  58. if (typeof value !== 'object' || value === null || Array.isArray(value)) {
  59. throw new Error(`desktop upload: ${label} must be an object`)
  60. }
  61. return value as Record<string, unknown>
  62. }
  63. function stringField(value: unknown, label: string): string {
  64. if (typeof value !== 'string' || value === '') {
  65. throw new Error(`desktop upload: ${label} must be a non-empty string`)
  66. }
  67. return value
  68. }
  69. function numberField(value: unknown, label: string): number {
  70. if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) {
  71. throw new Error(`desktop upload: ${label} must be a positive integer`)
  72. }
  73. return value
  74. }
  75. async function jsonFile(path: string, label: string): Promise<Record<string, unknown>> {
  76. let parsed: unknown
  77. try {
  78. parsed = JSON.parse(await readFile(path, 'utf8'))
  79. }
  80. catch (error) {
  81. throw new Error(`desktop upload: cannot read ${label} at ${path}: ${error instanceof Error ? error.message : String(error)}`)
  82. }
  83. return object(parsed, label)
  84. }
  85. async function manifestVersion(path: string, label: string): Promise<string> {
  86. return stringField((await jsonFile(path, label)).version, `${label}.version`)
  87. }
  88. function updateFileInfo(value: unknown, label: string, expectedFilename: string): UpdateFileInfo {
  89. const info = object(value, label)
  90. const filename = stringField(info.url ?? info.path, `${label}.url`)
  91. if (filename !== basename(filename) || filename !== expectedFilename) {
  92. throw new Error(`desktop upload: ${label} must reference ${expectedFilename}, received ${filename}`)
  93. }
  94. return {
  95. filename,
  96. size: numberField(info.size, `${label}.size`),
  97. sha512: stringField(info.sha512, `${label}.sha512`),
  98. }
  99. }
  100. async function sha512(path: string): Promise<string> {
  101. const hash = createHash('sha512')
  102. for await (const chunk of createReadStream(path)) hash.update(chunk)
  103. return hash.digest('base64')
  104. }
  105. async function verifyChecksummedArtifact(
  106. artifactsRoot: string,
  107. info: UpdateFileInfo,
  108. ): Promise<string> {
  109. const path = join(artifactsRoot, info.filename)
  110. const details = await stat(path).catch(() => undefined)
  111. if (details === undefined || !details.isFile()) {
  112. throw new Error(`desktop upload: missing artifact ${path}`)
  113. }
  114. if (details.size !== info.size) {
  115. throw new Error(`desktop upload: ${info.filename} size ${details.size} does not match update metadata ${info.size}`)
  116. }
  117. const actual = await sha512(path)
  118. if (actual !== info.sha512) {
  119. throw new Error(`desktop upload: ${info.filename} SHA-512 does not match update metadata`)
  120. }
  121. return path
  122. }
  123. async function requireArtifact(artifactsRoot: string, filename: string): Promise<string> {
  124. const path = join(artifactsRoot, filename)
  125. const details = await stat(path).catch(() => undefined)
  126. if (details === undefined || !details.isFile() || details.size === 0) {
  127. throw new Error(`desktop upload: missing or empty artifact ${path}`)
  128. }
  129. return path
  130. }
  131. function uploadArtifact(
  132. path: string,
  133. keyPrefix: string,
  134. contentType: string,
  135. channelMetadata = false,
  136. ): DesktopUploadArtifact {
  137. const filename = basename(path)
  138. return {
  139. path,
  140. filename,
  141. key: `${keyPrefix}/${filename}`,
  142. contentType,
  143. cacheControl: channelMetadata
  144. ? 'no-cache'
  145. : 'public, max-age=31536000, immutable',
  146. channelMetadata,
  147. }
  148. }
  149. /**
  150. * Validate the completed package record, dsh version, update metadata, hashes, and target files.
  151. * @param targetName - Fixed platform and architecture selected by the upload command.
  152. * @param options - Optional filesystem roots and environment for tests or release automation.
  153. * @returns An upload plan whose mutable channel metadata is the final entry.
  154. */
  155. export async function createDesktopUploadPlan(
  156. targetName: DesktopPackageTargetName,
  157. options: DesktopUploadPlanOptions = {},
  158. ): Promise<DesktopUploadPlan> {
  159. const target = TARGETS[targetName]
  160. if (target === undefined) {
  161. throw new Error(`desktop upload: unsupported target ${String(targetName)}`)
  162. }
  163. const environment = options.environment ?? process.env
  164. const repositoryRoot = options.repositoryRoot ?? REPOSITORY_ROOT
  165. const appRoot = options.appRoot ?? APP_ROOT
  166. const artifactsRoot = options.artifactsRoot ?? desktopTargetBuildPaths(targetName).artifacts
  167. const dshVersion = await manifestVersion(join(repositoryRoot, 'package.json'), 'dsh package')
  168. const desktopVersion = await manifestVersion(join(appRoot, 'package.json'), 'desktop package')
  169. if (dshVersion !== desktopVersion) {
  170. throw new Error(`desktop upload: desktop version ${desktopVersion} does not match current dsh version ${dshVersion}`)
  171. }
  172. const update = resolveDesktopUploadConfig(environment, target.platform, target.arch)
  173. const buildRecord = await jsonFile(
  174. join(artifactsRoot, desktopBuildRecordFilename(targetName)),
  175. `${targetName} package completion record`,
  176. )
  177. if (buildRecord.schemaVersion !== 1
  178. || buildRecord.target !== targetName
  179. || buildRecord.version !== dshVersion
  180. || buildRecord.environment !== update.environment
  181. || buildRecord.publicUrl !== update.publicUrl) {
  182. throw new Error(`desktop upload: ${targetName} package completion record does not match dsh ${dshVersion} and ${update.environment} update destination`)
  183. }
  184. const metadataFilename = desktopUpdateMetadataFilename(dshVersion, target.platform)
  185. const metadataPath = join(artifactsRoot, metadataFilename)
  186. let metadataValue: unknown
  187. try {
  188. metadataValue = load(await readFile(metadataPath, 'utf8'))
  189. }
  190. catch (error) {
  191. throw new Error(`desktop upload: cannot read update metadata at ${metadataPath}: ${error instanceof Error ? error.message : String(error)}`)
  192. }
  193. const metadata = object(metadataValue, metadataFilename)
  194. const metadataVersion = stringField(metadata.version, `${metadataFilename}.version`)
  195. if (metadataVersion !== dshVersion) {
  196. throw new Error(`desktop upload: ${metadataFilename} version ${metadataVersion} does not match current dsh version ${dshVersion}`)
  197. }
  198. if (!Array.isArray(metadata.files) || metadata.files.length !== 1) {
  199. throw new Error(`desktop upload: ${metadataFilename}.files must contain exactly one target update file`)
  200. }
  201. const base = `deepseek-harness-${dshVersion}-${target.os}-${target.arch}`
  202. const updaterExtension = target.platform === 'darwin' ? 'zip' : 'exe'
  203. const updaterInfo = updateFileInfo(metadata.files[0], `${metadataFilename}.files[0]`, `${base}.${updaterExtension}`)
  204. const updaterPath = await verifyChecksummedArtifact(artifactsRoot, updaterInfo)
  205. const artifacts: DesktopUploadArtifact[] = []
  206. if (target.platform === 'darwin') {
  207. const dmgPath = await requireArtifact(artifactsRoot, `${base}.dmg`)
  208. const blockmapPath = await requireArtifact(artifactsRoot, `${base}.zip.blockmap`)
  209. artifacts.push(
  210. uploadArtifact(dmgPath, update.keyPrefix, 'application/x-apple-diskimage'),
  211. uploadArtifact(updaterPath, update.keyPrefix, 'application/zip'),
  212. uploadArtifact(blockmapPath, update.keyPrefix, 'application/octet-stream'),
  213. )
  214. }
  215. else {
  216. const blockMapSize = object(metadata.files[0], `${metadataFilename}.files[0]`).blockMapSize
  217. numberField(blockMapSize, `${metadataFilename}.files[0].blockMapSize`)
  218. artifacts.push(uploadArtifact(
  219. updaterPath,
  220. update.keyPrefix,
  221. 'application/vnd.microsoft.portable-executable',
  222. ))
  223. }
  224. artifacts.push(uploadArtifact(metadataPath, update.keyPrefix, 'application/yaml', true))
  225. return {
  226. environment: update.environment,
  227. target: targetName,
  228. version: dshVersion,
  229. publicUrl: update.publicUrl,
  230. bucket: update.bucket,
  231. secretIdEnvName: update.secretIdEnvName,
  232. secretKeyEnvName: update.secretKeyEnvName,
  233. artifacts,
  234. }
  235. }