import { createHash } from 'node:crypto'; import { createReadStream, type BigIntStats } from 'node:fs'; import { link, lstat } from 'node:fs/promises'; import { AppError } from '@shared/errors.ts'; import evidence from './hardlink-resources-2.61.0.43.json' with { type: 'json' }; interface ResourceEvidence { readonly bytes: number; readonly sha256: string; } const resources: Readonly> = evidence.files; export function hasHardlinkEvidence(version: string | null | undefined): boolean { return version === evidence.gameVersion; } /** Only an exact path and size from the sampled build can be offered as a candidate. */ export function hardlinkResource( version: string | null | undefined, relativePath: string, bytes: number, ): ResourceEvidence | undefined { if (!hasHardlinkEvidence(version)) return undefined; const path = relativePath.replaceAll('\\', '/').toLowerCase(); const resource = Object.hasOwn(resources, path) ? resources[path] : undefined; return resource?.bytes === bytes ? resource : undefined; } export async function fileHash(path: string, signal: AbortSignal): Promise { const hash = createHash('sha256'); for await (const chunk of createReadStream(path, { signal })) hash.update(chunk as Buffer); return hash.digest('hex'); } /** Read the measured bytes and retain the observed file identity until the link is created. */ export async function verifyHardlinkResource( path: string, resource: ResourceEvidence, signal: AbortSignal, ): Promise { signal.throwIfAborted(); const before = await lstat(path, { bigint: true }).catch((error: NodeJS.ErrnoException) => { if (error.code === 'ENOENT') return null; throw error; }); if (!before?.isFile() || before.size !== BigInt(resource.bytes)) return null; const checksum = await fileHash(path, signal); const after = await lstat(path, { bigint: true }); if (!sameResource(before, after)) throw new AppError('hardlink_file_changed'); return checksum === resource.sha256 ? after : null; } export function sameResource(left: BigIntStats, right: BigIntStats): boolean { return sameIdentityAndContents(left, right) && left.ctimeNs === right.ctimeNs; } export async function linkVerifiedResource(source: string, target: string, verified: BigIntStats): Promise { if (!sameResource(verified, await lstat(source, { bigint: true }))) throw new AppError('hardlink_file_changed'); await link(source, target); // Linking may change ctime. The inode, contents and modification time must stay the same. const linked = await lstat(target, { bigint: true }); if (!sameIdentityAndContents(verified, linked)) throw new AppError('hardlink_file_changed'); return linked; } function sameIdentityAndContents(left: BigIntStats, right: BigIntStats): boolean { return right.isFile() && left.dev === right.dev && left.ino === right.ino && left.size === right.size && left.mtimeNs === right.mtimeNs; }