File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ ---
2+ " @googleworkspace/cli " : patch
3+ ---
4+
5+ Verify SHA256 checksum of downloaded binary in npm postinstall script
Original file line number Diff line number Diff line change 22
33"use strict" ;
44
5+ const crypto = require ( "crypto" ) ;
56const fs = require ( "fs" ) ;
67const path = require ( "path" ) ;
78const os = require ( "os" ) ;
@@ -130,6 +131,23 @@ async function install() {
130131 console . error ( `Downloading gws from ${ url } ` ) ;
131132 await download ( url , tmpFile ) ;
132133
134+ // Verify SHA256 checksum
135+ const sha256Url = `${ url } .sha256` ;
136+ const sha256File = `${ tmpFile } .sha256` ;
137+ console . error ( `Verifying checksum from ${ sha256Url } ` ) ;
138+ await download ( sha256Url , sha256File ) ;
139+
140+ const expectedHash = fs . readFileSync ( sha256File , "utf8" ) . trim ( ) . split ( / \s + / ) [ 0 ] . toLowerCase ( ) ;
141+ const fileBuffer = fs . readFileSync ( tmpFile ) ;
142+ const actualHash = crypto . createHash ( "sha256" ) . update ( fileBuffer ) . digest ( "hex" ) . toLowerCase ( ) ;
143+
144+ if ( actualHash !== expectedHash ) {
145+ throw new Error (
146+ `SHA256 checksum mismatch!\n Expected: ${ expectedHash } \n Actual: ${ actualHash } \nThe downloaded binary may have been tampered with.` ,
147+ ) ;
148+ }
149+ console . error ( "Checksum verified ✓" ) ;
150+
133151 console . error ( `Extracting to ${ INSTALL_DIR } ` ) ;
134152 extract ( tmpFile , INSTALL_DIR ) ;
135153
You can’t perform that action at this time.
0 commit comments