1- const JWS = require ( 'jws' ) ;
2-
3- const createJws = ( certificateId , payload , privateKey ) => JWS . sign ( {
4- header : {
5- alg : 'ES512' ,
6- kid : certificateId ,
7- } ,
8- payload,
9- privateKey,
10- } ) ;
11-
12- const detachContent = jws => {
13- const parts = jws . split ( '.' ) ;
14- return `${ parts [ 0 ] } ..${ parts [ 2 ] } ` ;
15- } ;
1+ const tlSigning = require ( 'truelayer-signing' ) ;
162
173const addTlSignatureToRequest = context => {
18- const payload = context . request . getBodyText ( ) ;
194 const jwsIsRequired = context . request . getEnvironmentVariable ( 'REQUIRE_JWS' ) === true ;
20-
215 if ( ! jwsIsRequired ) {
226 console . log ( 'no signing needed because the REQUIRE_JWS environment variable is either missing or !== true' ) ;
237 return ;
248 }
259
26- // we only need signing for requests with a body
27- if ( ! payload ) {
28- console . log ( 'no signing needed because there is no payload' ) ;
29- return false ;
30- }
31-
3210 const certificateId = context . request . getEnvironmentVariable ( 'CERTIFICATE_ID' ) ;
33-
3411 if ( ! certificateId ) {
3512 throw new Error ( 'Missing required `CERTIFICATE_ID` environment variable.' ) ;
3613 }
3714
3815 const privateKey = context . request . getEnvironmentVariable ( 'PRIVATE_KEY' ) ;
39-
4016 if ( ! privateKey ) {
4117 throw new Error ( 'Missing required `PRIVATE_KEY` environment variable.' ) ;
4218 }
4319
44- const jws = createJws ( certificateId , payload , privateKey ) ;
45- const jwsWithDetachedContent = detachContent ( jws ) ;
46- context . request . setHeader ( 'X-Tl-Signature' , jwsWithDetachedContent ) ;
20+ let idempotencyKey = context . request . getHeader ( "Idempotency-Key" ) ;
21+
22+ let v2Signature = tlSigning . sign ( {
23+ kid : certificateId ,
24+ privateKeyPem : privateKey ,
25+ method : context . request . getMethod ( ) ,
26+ path : new URL ( context . request . getUrl ( ) ) . pathname ,
27+ body : context . request . getBodyText ( ) ,
28+ headers : idempotencyKey ? { "Idempotency-Key" : idempotencyKey } : { } ,
29+ } ) ;
30+ context . request . setHeader ( 'Tl-Signature' , v2Signature ) ;
4731}
4832
33+
4934module . exports . requestHooks = [
5035 addTlSignatureToRequest
51- ] ;
36+ ] ;
0 commit comments