1+
2+ import { createHash } from "crypto" ;
3+ import { type GetObjectCommandOutput } from "@aws-sdk/client-s3" ;
4+ import { InternalServerError } from "./errors" ;
5+ import { validRange } from "semver" ;
6+
7+ // Helper function to convert stream to string
8+ export async function streamToString ( stream : any ) : Promise < string > {
9+ const chunks : Uint8Array [ ] = [ ] ;
10+
11+ for await ( const chunk of stream ) {
12+ chunks . push ( chunk ) ;
13+ }
14+
15+ const result = Buffer . concat ( chunks ) . toString ( "utf-8" ) ;
16+ return result . trimEnd ( ) ;
17+ }
18+
19+ // Helper function to convert stream to buffer
20+ export async function streamToBuffer ( stream : any ) : Promise < Buffer > {
21+ const chunks = [ ] ;
22+ for await ( const chunk of stream ) {
23+ chunks . push ( chunk ) ;
24+ }
25+ return Buffer . concat ( chunks ) ;
26+ }
27+
28+ export async function verifyHash (
29+ file : GetObjectCommandOutput ,
30+ hashFile : GetObjectCommandOutput ,
31+ exception ?: string ,
32+ ) : Promise < boolean > {
33+ const content = await streamToBuffer ( file . Body ) ;
34+ const remoteHash = await streamToString ( hashFile . Body ) ;
35+ const localHash = createHash ( "sha256" ) . update ( content ) . digest ( "hex" ) ;
36+
37+ const matches = remoteHash . trim ( ) === localHash ;
38+ if ( ! matches && exception ) {
39+ throw new InternalServerError ( exception ) ;
40+ }
41+ return matches ;
42+ }
43+
44+ export function toSemverRange ( range ?: string ) {
45+ if ( ! range ) return "*" ;
46+ return validRange ( range ) || "*" ;
47+ }
0 commit comments