import { HttpMethod } from '@dripjs/types' ; import { stringify } from 'qs' ; import { apiBasePath } from '../rest/types' ; import { isNodeJs } from './helpers' ; const createHmac = require ( 'create-hmac' ) ; const urljoin = require ( 'url-join' ) ; param { String } secret param { String } verb param { String } url param { Number } nonce param { String | Object } data return { String } export function signMessage ( secret , verb , url , nonce , data ? ) { let body = '' ; if ( typeof data === 'object' ) body = JSON . stringify ( data ) ; return createHmac ( 'sha256' , secret ) . update ( `${ verb }${ url }${ nonce }${ body }` ) . digest ( 'hex' ) ; } let nonceCounter = 0 ; export function getWSAuthQuery ( apiKey , apiSecret ) { const nonce = Date . now ( ) * 1000 + ( nonceCounter ++ % 1000 ) ; const query = { 'api-nonce' : nonce , 'api-key' : apiKey , 'api-signature' : signMessage ( apiSecret , HttpMethod . GET , '/realtime' , nonce ) , } ; return stringify ( query ) ; } export function getRestAuthHeaders ( method , baseUrl , endpoint , apiKey , apiSecret , data ? ) { const query = method === HttpMethod . GET && Object . keys ( data ) . length !== 0 ? `?${ stringify ( data ) }` : '' ; const url = urljoin ( apiBasePath , endpoint , query ) ; const expires = Math . round ( Date . now ( ) / 1000 ) + 60 * 3 ; const body = method === HttpMethod . GET ? '' : data ; const signature = signMessage ( apiSecret , method , url , expires , body ) ; const authHeaders = { 'Content-Type' : 'application/json' , accept : 'application/json' , 'api-expires' : String ( expires ) , 'api-key' : apiKey , 'api-signature' : signature , } ; if ( isNodeJs ( ) ) { authHeaders . Origin = baseUrl ; } return authHeaders ; } export interface AuthHeaders { Origin ? : string ; 'Content-Type' : string ; accept : string ; 'api-expires' : string ; 'api-key' : string ; 'api-signature' : string ; }