2022-02-10 12:07:06 -08:00
|
|
|
import _sha1 from "sha1";
|
2022-07-07 16:11:30 +08:00
|
|
|
import _md5 from "md5";
|
2022-02-10 12:07:06 -08:00
|
|
|
|
2024-05-14 19:53:08 +08:00
|
|
|
import { HashDef } from "#types/hashDef.ts";
|
2022-02-10 12:07:06 -08:00
|
|
|
|
|
|
|
/**
|
2022-07-07 16:11:30 +08:00
|
|
|
* Returns the hash sum of bytes of given bytes using SHA1.
|
2022-02-10 12:07:06 -08:00
|
|
|
*
|
2022-07-07 16:11:30 +08:00
|
|
|
* This is what CurseForge and Forge are using to check files.
|
2022-02-10 12:07:06 -08:00
|
|
|
*/
|
2022-07-07 16:11:30 +08:00
|
|
|
export const sha1 = (inputBuffer: Buffer): string => {
|
|
|
|
return _sha1(inputBuffer);
|
2022-02-10 12:07:06 -08:00
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
2022-07-07 16:11:30 +08:00
|
|
|
* Returns the hash sum of bytes of given bytes using MD5.
|
2022-02-10 12:07:06 -08:00
|
|
|
*
|
2022-07-07 16:11:30 +08:00
|
|
|
* This is what CF is using to check files.
|
2022-02-10 12:07:06 -08:00
|
|
|
*/
|
2022-07-07 16:11:30 +08:00
|
|
|
export const md5 = (inputBuffer: Buffer): string => {
|
|
|
|
return _md5(inputBuffer);
|
2022-02-10 12:07:06 -08:00
|
|
|
};
|
|
|
|
|
|
|
|
const hashFuncs: { [key: string]: (buffer: Buffer) => string } = {
|
2022-07-07 16:11:30 +08:00
|
|
|
sha1,
|
|
|
|
md5,
|
2022-02-10 12:07:06 -08:00
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Compare buffer to the given HashDef.
|
|
|
|
*
|
|
|
|
* @param {Buffer} buffer
|
|
|
|
* @param {HashDef} hashDef
|
|
|
|
*
|
|
|
|
* @throws {Error} Throws a generic error if hashes don't match.
|
|
|
|
*/
|
2024-05-14 19:53:08 +08:00
|
|
|
export const compareBufferToHashDef = (
|
|
|
|
buffer: Buffer,
|
|
|
|
hashDef: HashDef,
|
|
|
|
): boolean => {
|
2022-02-10 12:07:06 -08:00
|
|
|
if (!hashFuncs[hashDef.id]) {
|
|
|
|
throw new Error(`No hash function found for ${hashDef.id}.`);
|
|
|
|
}
|
|
|
|
|
|
|
|
const sum = hashFuncs[hashDef.id](buffer);
|
2024-05-14 19:53:08 +08:00
|
|
|
return (
|
|
|
|
(Array.isArray(hashDef.hashes) && hashDef.hashes.includes(sum)) ||
|
|
|
|
hashDef.hashes == sum
|
|
|
|
);
|
2022-02-10 12:07:06 -08:00
|
|
|
};
|