installed-update-qualification.ts 16 KB

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