Hashes a regular file with SHA-512 while enforcing size limits and TOCTOU safety checks, returning the digest, byte count, and a UTF-8 prefix for content inspection.
async function hashRegularFile(
path: string,
limit: number,
unsafeMessage: string,
): Promise<{ digest: Buffer; bytes: number; prefix: string }> {
let handle;
try {
const pathInfo = await lstat(path);
if (pathInfo.isSymbolicLink() || !pathInfo.isFile() || pathInfo.size > limit) {
throw new CliSafetyError(unsafeMessage);
}
handle = await open(path, fsConstants.O_RDONLY | NO_FOLLOW);
const before = await handle.stat();
if (!before.isFile() || !sameFile(pathInfo, before) || before.size > limit) {
throw new CliSafetyError(unsafeMessage);
}
const hash = createHash("sha512");
const buffer = Buffer.allocUnsafe(Math.min(64 * 1024, Math.max(1, before.size)));
const prefixChunks: Buffer[] = [];
let prefixBytes = 0;
let offset = 0
... (truncated -- full source via MCP)
See the full source, get the GitHub permalink, and search 40K more like it.
Get a free API key