installed-update-qualification.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. /** Local-only material allocation and journal inspection for operator-driven installed updates. */
  2. import { createHash, randomBytes } from 'node:crypto'
  3. import { mkdir, mkdtemp, readFile, readdir, stat, writeFile } from 'node:fs/promises'
  4. import { dirname, join, resolve } from 'node:path'
  5. import { gt, valid } from 'semver'
  6. /** Source identifiers exclude file contents, configuration values, and credentials. */
  7. export interface InstalledUpdateSource {
  8. readonly version: string
  9. readonly commit: string
  10. readonly dirtyFiles: readonly string[]
  11. }
  12. /** A private test namespace; creating it performs no signing, installation, or remote operation. */
  13. export interface InstalledUpdateRun {
  14. readonly schemaVersion: 1
  15. readonly id: string
  16. readonly root: string
  17. readonly createdAt: string
  18. readonly source: InstalledUpdateSource
  19. readonly versions: readonly [string, string]
  20. readonly appId: string
  21. readonly productName: string
  22. readonly environment: 'test'
  23. readonly origin: string
  24. readonly bucket: string
  25. readonly feedKey: string
  26. readonly binPrefix: string
  27. }
  28. /**
  29. * Allocate a new local run and retain its manifest without reading release credentials.
  30. * @param parent Ignored material directory; each invocation acquires a separate child atomically.
  31. * @param versions Explicit original and successor Nightly versions, in increasing order.
  32. * @param source Source version, Git commit, and dirty-file list captured before material preparation.
  33. * @returns The retained run manifest; no package or publication is implied by its presence.
  34. */
  35. export async function createInstalledUpdateRun(
  36. parent: string, versions: readonly [string, string], source: InstalledUpdateSource,
  37. ): Promise<InstalledUpdateRun> {
  38. validateVersions(versions)
  39. if (valid(source.version) === null || !/^[a-f0-9]{40,64}$/u.test(source.commit)) {
  40. throw new Error('installed update: valid source version and Git commit are required')
  41. }
  42. await mkdir(parent, { recursive: true })
  43. const root = await mkdtemp(join(resolve(parent), 'installed-update-'))
  44. const id = randomBytes(12).toString('hex')
  45. const run: InstalledUpdateRun = {
  46. schemaVersion: 1, id, root, createdAt: new Date().toISOString(), source, versions,
  47. appId: `com.deepseek.dsh.qualification.q${id}`, productName: `DSH Update Test ${id}`,
  48. environment: 'test', origin: 'https://download-test.deepseek.com', bucket: 'bj-toc-download-test-1320056602',
  49. feedKey: `dsh-desk/feeds/qualification/${id}/win-x64/nightly.yml`,
  50. binPrefix: `dsh-desk/bin/qualification/${id}/win-x64`,
  51. }
  52. await writeFile(join(root, 'run.json'), `${JSON.stringify(run, null, 2)}\n`, { flag: 'wx', mode: 0o600, flush: true })
  53. return run
  54. }
  55. function validateVersions(versions: readonly [string, string]): void {
  56. if (versions.some(version => valid(version) !== version || !/^\d+\.\d+\.\d+-nightly\.[0-9.]+$/u.test(version))
  57. || !gt(versions[1], versions[0])) {
  58. throw new Error('installed update: two increasing numeric Nightly versions are required')
  59. }
  60. }
  61. /**
  62. * Load a retained manifest and reject altered destinations or application identities.
  63. * @param path Local run.json produced by the allocator.
  64. * @returns Validated test-only run; the directory must still be the original manifest location.
  65. */
  66. export async function readInstalledUpdateRun(path: string): Promise<InstalledUpdateRun> {
  67. const value: unknown = JSON.parse(await readFile(path, 'utf8'))
  68. if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new Error('installed update: invalid run manifest')
  69. const row = value as Record<string, unknown>
  70. if (row.schemaVersion !== 1 || typeof row.id !== 'string' || !/^[a-f0-9]{24}$/u.test(row.id)
  71. || row.root !== resolve(dirname(path)) || row.environment !== 'test'
  72. || row.origin !== 'https://download-test.deepseek.com' || row.bucket !== 'bj-toc-download-test-1320056602'
  73. || row.appId !== `com.deepseek.dsh.qualification.q${row.id}` || row.productName !== `DSH Update Test ${row.id}`
  74. || row.feedKey !== `dsh-desk/feeds/qualification/${row.id}/win-x64/nightly.yml`
  75. || row.binPrefix !== `dsh-desk/bin/qualification/${row.id}/win-x64`
  76. || !Array.isArray(row.versions) || row.versions.length !== 2 || row.versions.some(version => typeof version !== 'string')) {
  77. throw new Error('installed update: manifest identity, location, versions, or test destination changed')
  78. }
  79. validateVersions(row.versions as [string, string])
  80. if (typeof row.source !== 'object' || row.source === null || Array.isArray(row.source)) {
  81. throw new Error('installed update: missing source version and commit')
  82. }
  83. const source = row.source as Record<string, unknown>
  84. if (typeof source.version !== 'string' || valid(source.version) === null
  85. || typeof source.commit !== 'string' || !/^[a-f0-9]{40,64}$/u.test(source.commit)
  86. || !Array.isArray(source.dirtyFiles) || source.dirtyFiles.some(file => typeof file !== 'string')
  87. || typeof row.createdAt !== 'string' || !Number.isFinite(Date.parse(row.createdAt))) {
  88. throw new Error('installed update: invalid source version, commit, file list, or creation time')
  89. }
  90. return row as unknown as InstalledUpdateRun
  91. }
  92. interface JournalRecord {
  93. readonly pid: number
  94. readonly sequence: number
  95. readonly time: string
  96. readonly version: string
  97. readonly event: string
  98. readonly phase?: string
  99. readonly targetVersion?: string
  100. readonly failedOperation?: string
  101. readonly percent?: number
  102. }
  103. /** A location in retained evidence, never a copy of raw diagnostics. */
  104. export interface InstalledUpdateObservation {
  105. readonly file: string
  106. readonly sequence: number
  107. readonly time: string
  108. }
  109. /** Observed journal sequence is deliberately separate from operator acceptance. */
  110. export interface InstalledUpdateEvidence {
  111. readonly schemaVersion: 1
  112. readonly versions: readonly [string, string]
  113. readonly filesRead: number
  114. readonly recordedFlow: 'complete' | 'incomplete'
  115. readonly milestones: Readonly<Record<string, InstalledUpdateObservation>>
  116. readonly missing: readonly string[]
  117. readonly operatorVerificationRequired: readonly string[]
  118. }
  119. const FIELDS = new Set(['schemaVersion', 'sequence', 'time', 'pid', 'version', 'event', 'phase',
  120. 'targetVersion', 'percent', 'failedOperation', 'errorCode'])
  121. const ACTIONS = new Set(['started', 'workspace-ready', 'workspace-failed', 'check-requested',
  122. 'download-requested', 'install-confirmed', 'quit-requested', 'state'])
  123. const PHASES = new Set(['idle', 'checking', 'available', 'downloading', 'verifying', 'installing', 'ready', 'error'])
  124. const OPERATIONS = new Set(['check', 'download', 'install'])
  125. const ERROR_CODES = new Set(['ETIMEDOUT', 'ENOSPC', 'ERR_INTERNET_DISCONNECTED', 'ERR_CONNECTION_RESET',
  126. 'ERR_CONNECTION_CLOSED', 'ERR_NAME_NOT_RESOLVED', 'ERR_UPDATER_INVALID_SIGNATURE', 'ERR_UPDATER_CHECKSUM_MISMATCH', 'UNCLASSIFIED'])
  127. const STAGES = ['original-workspace', 'first-download', 'transfer-started', 'download-failed',
  128. 'manual-retry', 'download-ready', 'install-confirmed', 'original-quit', 'successor-started', 'successor-workspace'] as const
  129. function parseRecord(line: string, sequence: number): JournalRecord {
  130. let value: unknown
  131. try { value = JSON.parse(line) }
  132. catch { throw new Error('installed update: invalid journal JSON; raw input is withheld') }
  133. if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new Error('installed update: invalid journal record')
  134. const row = value as Record<string, unknown>
  135. if (Object.keys(row).some(key => !FIELDS.has(key)) || row.schemaVersion !== 1 || row.sequence !== sequence
  136. || !Number.isSafeInteger(row.pid) || (row.pid as number) <= 0
  137. || typeof row.time !== 'string' || !Number.isFinite(Date.parse(row.time))
  138. || new Date(row.time).toISOString() !== row.time || typeof row.version !== 'string' || valid(row.version) !== row.version
  139. || typeof row.event !== 'string' || !ACTIONS.has(row.event)
  140. || (sequence === 0 && row.event !== 'started') || (sequence > 0 && row.event === 'started')
  141. || (row.event === 'state' && (typeof row.phase !== 'string' || !PHASES.has(row.phase)))
  142. || (row.phase !== undefined && (typeof row.phase !== 'string' || !PHASES.has(row.phase)))
  143. || (row.failedOperation !== undefined && (typeof row.failedOperation !== 'string' || !OPERATIONS.has(row.failedOperation)))
  144. || (row.errorCode !== undefined && (typeof row.errorCode !== 'string' || !ERROR_CODES.has(row.errorCode)))
  145. || (row.percent !== undefined && (typeof row.percent !== 'number' || !Number.isInteger(row.percent)
  146. || row.percent < 0 || row.percent > 100))
  147. || (row.targetVersion !== undefined && (typeof row.targetVersion !== 'string' || valid(row.targetVersion) !== row.targetVersion))) {
  148. throw new Error('installed update: unsupported or inconsistent journal record; raw input is withheld')
  149. }
  150. return row as unknown as JournalRecord
  151. }
  152. /**
  153. * Inspect a private evidence directory without changing files or declaring the installation successful.
  154. * @param directory Directory containing only the qualification run's per-process JSONL journals.
  155. * @param versions Expected installed original and successor versions.
  156. * @returns Ordered failure/retry/restart observations plus required independent operator verification.
  157. */
  158. export async function inspectInstalledUpdateJournals(
  159. directory: string, versions: readonly [string, string],
  160. ): Promise<InstalledUpdateEvidence> {
  161. return inspectJournalRuns(await readJournalRuns(directory, versions), versions)
  162. }
  163. interface JournalRun { readonly file: string; readonly text: string; readonly records: JournalRecord[] }
  164. async function readJournalRuns(directory: string, versions: readonly [string, string]): Promise<JournalRun[]> {
  165. validateVersions(versions)
  166. const files = (await readdir(directory)).filter(file => file.endsWith('.jsonl')).sort()
  167. const runs: JournalRun[] = []
  168. let totalBytes = 0
  169. for (const file of files) {
  170. if (!/^\d+-[a-f0-9-]{36}\.jsonl$/u.test(file)) throw new Error('installed update: unexpected journal filename')
  171. if ((await stat(join(directory, file))).size > 10 * 1024 * 1024) throw new Error('installed update: journal exceeds 10 MiB inspection limit')
  172. const text = await readFile(join(directory, file), 'utf8')
  173. const bytes = Buffer.byteLength(text)
  174. totalBytes += bytes
  175. if (bytes > 10 * 1024 * 1024 || totalBytes > 50 * 1024 * 1024) throw new Error('installed update: journal snapshot exceeds inspection limit')
  176. if (!text.endsWith('\n')) throw new Error('installed update: incomplete journal tail')
  177. const records = text.slice(0, -1).split('\n').map(parseRecord)
  178. if (records.some(row => row.version !== records[0]!.version || row.pid !== records[0]!.pid || !versions.includes(row.version))) {
  179. throw new Error('installed update: mixed or unexpected installed versions')
  180. }
  181. runs.push({ file, text, records })
  182. }
  183. return runs
  184. }
  185. function inspectJournalRuns(runs: readonly JournalRun[], versions: readonly [string, string]): InstalledUpdateEvidence {
  186. let milestones: Record<string, InstalledUpdateObservation> = {}
  187. // A retry and installation authorization must belong to the same original process.
  188. for (const run of runs.filter(run => run.records[0]!.version === versions[0])) {
  189. const candidate: Record<string, InstalledUpdateObservation> = {}
  190. let stage = 0
  191. for (const record of run.records) {
  192. if (stage >= 6 && (record.event === 'download-requested' || (record.event === 'state' && record.phase === 'error'))) {
  193. for (const key of STAGES.slice(4)) delete candidate[key]
  194. stage = 4
  195. }
  196. const matches = [record.event === 'workspace-ready', record.event === 'download-requested',
  197. record.event === 'state' && record.phase === 'downloading' && record.targetVersion === versions[1]
  198. && record.percent !== undefined && record.percent > 0,
  199. record.event === 'state' && record.phase === 'error' && record.failedOperation === 'download'
  200. && record.targetVersion === versions[1],
  201. record.event === 'download-requested',
  202. record.event === 'state' && record.phase === 'ready' && record.targetVersion === versions[1],
  203. record.event === 'install-confirmed', record.event === 'quit-requested']
  204. if (stage < 8 && matches[stage]) {
  205. candidate[STAGES[stage]!] = { file: run.file, sequence: record.sequence, time: record.time }
  206. stage++
  207. }
  208. }
  209. if (Object.keys(candidate).length > Object.keys(milestones).length) milestones = candidate
  210. }
  211. const quit = milestones['original-quit']
  212. if (quit !== undefined) {
  213. for (const run of runs.filter(run => run.records[0]!.version === versions[1])) {
  214. const started = run.records[0]!
  215. if (Date.parse(started.time) < Date.parse(quit.time)) continue
  216. const ready = run.records.find(record => record.event === 'workspace-ready')
  217. if (ready === undefined) continue
  218. milestones['successor-started'] = { file: run.file, sequence: started.sequence, time: started.time }
  219. milestones['successor-workspace'] = { file: run.file, sequence: ready.sequence, time: ready.time }
  220. break
  221. }
  222. }
  223. const missing = STAGES.filter(stage => milestones[stage] === undefined)
  224. return { schemaVersion: 1, versions, filesRead: runs.length,
  225. recordedFlow: missing.length === 0 ? 'complete' : 'incomplete', milestones, missing,
  226. operatorVerificationRequired: ['feed-publication-after-original-startup', 'network-fault-and-recovery',
  227. 'installer-completion-and-installed-path', 'test-data-preserved', 'screenshots-and-user-confirmations'] }
  228. }
  229. /**
  230. * Retain validated journal bytes and a report from that same snapshot, without copying application data.
  231. * @param manifest Original test run manifest.
  232. * @param directory The run's installed-app journals directory; collection never changes its files.
  233. * @returns Independent local collection directory; incomplete flow is retained as incomplete, not acceptance.
  234. */
  235. export async function collectInstalledUpdateJournals(manifest: string, directory: string): Promise<string> {
  236. const run = await readInstalledUpdateRun(manifest)
  237. if (!resolve(directory).replaceAll('\\', '/').endsWith(`/dsh-update-qualification/${run.id}/journals`)) {
  238. throw new Error('installed update: matching installed-app journal directory is required')
  239. }
  240. const snapshots = await readJournalRuns(directory, run.versions)
  241. const evidence = inspectJournalRuns(snapshots, run.versions)
  242. const parent = join(run.root, 'evidence')
  243. await mkdir(parent, { recursive: true })
  244. const collection = await mkdtemp(join(parent, 'collection-'))
  245. try {
  246. await writeFile(join(collection, 'started.json'), `${JSON.stringify({ time: new Date().toISOString(), runId: run.id })}\n`,
  247. { flag: 'wx', mode: 0o600, flush: true })
  248. await mkdir(join(collection, 'journals'))
  249. for (const snapshot of snapshots) {
  250. await writeFile(join(collection, 'journals', snapshot.file), snapshot.text, { flag: 'wx', mode: 0o600, flush: true })
  251. }
  252. const result = { schemaVersion: 1, runId: run.id, collectedAt: new Date().toISOString(), sourceDirectory: resolve(directory),
  253. evidence, operatorAcceptance: 'pending', files: snapshots.map(snapshot => ({ path: `journals/${snapshot.file}`,
  254. bytes: Buffer.byteLength(snapshot.text), sha256: createHash('sha256').update(snapshot.text).digest('hex') })) }
  255. await writeFile(join(collection, 'report.json'), `${JSON.stringify(result, null, 2)}\n`, { flag: 'wx', mode: 0o600, flush: true })
  256. return collection
  257. } catch {
  258. await writeFile(join(collection, 'failed.json'), `${JSON.stringify({ failed: true, time: new Date().toISOString() })}\n`,
  259. { flag: 'wx', mode: 0o600, flush: true })
  260. throw new Error(`installed update: journal collection failed; partial evidence retained at ${collection}`)
  261. }
  262. }