|
| 1 | +import { createHash, randomUUID } from 'node:crypto'; |
| 2 | +import { createReadStream } from 'node:fs'; |
| 3 | +import { lstat, readFile, rename, rm, writeFile } from 'node:fs/promises'; |
| 4 | +import { basename } from 'node:path'; |
| 5 | + |
| 6 | +async function assertFile(path: string): Promise<void> { |
| 7 | + const stat = await lstat(path); |
| 8 | + if (!stat.isFile() || stat.size === 0) throw new Error(`文件不是非空普通文件:${path}`); |
| 9 | +} |
| 10 | + |
| 11 | +/** 流式计算非空普通文件的 SHA-256,拒绝符号链接 */ |
| 12 | +export async function sha256(path: string): Promise<string> { |
| 13 | + await assertFile(path); |
| 14 | + const hash = createHash('sha256'); |
| 15 | + for await (const chunk of createReadStream(path)) hash.update(chunk); |
| 16 | + return hash.digest('hex'); |
| 17 | +} |
| 18 | + |
| 19 | +function checksumLine(binary: string, digest: string): string { |
| 20 | + const name = basename(binary); |
| 21 | + if (/[\r\n]/.test(name)) throw new Error('二进制文件名不能包含换行'); |
| 22 | + // GNU 校验和对含反斜杠的文件名使用转义行前缀 |
| 23 | + return name.includes('\\') ? `\\${digest} ${name.replaceAll('\\', '\\\\')}\n` : `${digest} ${name}\n`; |
| 24 | +} |
| 25 | + |
| 26 | +/** 原子写入二进制旁的 .sha256,清单只引用同目录文件名 */ |
| 27 | +export async function writeBinaryChecksum(binary: string): Promise<string> { |
| 28 | + const sidecar = `${binary}.sha256`; |
| 29 | + const content = checksumLine(binary, await sha256(binary)); |
| 30 | + const temporary = `${sidecar}.${randomUUID()}.tmp`; |
| 31 | + try { |
| 32 | + await writeFile(temporary, content, { flag: 'wx' }); |
| 33 | + await rename(temporary, sidecar); |
| 34 | + return sidecar; |
| 35 | + } finally { await rm(temporary, { force: true }); } |
| 36 | +} |
| 37 | + |
| 38 | +/** 核对二进制、文件名与旁边的 .sha256;缺失、过期或格式不符时失败 */ |
| 39 | +export async function verifyBinaryChecksum(binary: string): Promise<string> { |
| 40 | + const sidecar = `${binary}.sha256`; |
| 41 | + await assertFile(sidecar); |
| 42 | + const content = await readFile(sidecar, 'utf8'); |
| 43 | + if (content !== checksumLine(binary, await sha256(binary))) { |
| 44 | + throw new Error(`二进制校验和或文件名不一致:${basename(sidecar)}`); |
| 45 | + } |
| 46 | + return sidecar; |
| 47 | +} |
0 commit comments