Skip to content

Commit

Permalink
Validate that the final file was written correctly (#1017)
Browse files Browse the repository at this point in the history
  • Loading branch information
GarboMuffin authored Jun 11, 2024
1 parent e697825 commit 0cf8b9d
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src-main/atomic-write-stream.js
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,8 @@ const createAtomicWriteStream = async (path) => {
// same directory as the destination file.
const isSeverelySandboxed = !!process.mas;

const runningHash = nodeCrypto.createHash('sha512');

const tempPath = getTemporaryPath(path, isSeverelySandboxed);
const fileHandle = await fsPromises.open(tempPath, 'w', originalMode);
const writeStream = fileHandle.createWriteStream({
Expand Down Expand Up @@ -225,13 +227,30 @@ const createAtomicWriteStream = async (path) => {
}
}

// One final check to make sure nothing went wrong
const expectedHash = runningHash.digest('hex');
const finalHash = await sha512(path);
if (expectedHash !== finalHash) {
throw new Error('Final integrity hash check failed');
}

writeStream.emit('atomic-finish');
releaseFileLock();
} catch (error) {
handleError(error);
}
});

const oldWrite = writeStream.write;
writeStream.write = function (chunk, ...extra) {
if (extra.length !== 0) {
throw new Error('Atomic write() only supports one argument');
}

runningHash.update(chunk);
return oldWrite.call(this, chunk);
};

return writeStream;
};

Expand Down

0 comments on commit 0cf8b9d

Please sign in to comment.