|
| 1 | +import hmacSHA1 from 'crypto-js/hmac-sha1'; |
| 2 | +import base64 from 'crypto-js/enc-base64'; |
| 3 | +import * as crypto from 'crypto'; |
| 4 | + |
| 5 | +interface TokenSet { |
| 6 | + access_token: string; |
| 7 | + secret: string; |
| 8 | +} |
| 9 | + |
| 10 | +/** |
| 11 | + * Generate API Authorization String |
| 12 | + * We must create a signed message for the API using the following: |
| 13 | + * - An API access token |
| 14 | + * - A UTC timestamp (in seconds) |
| 15 | + * - A nonce (random string between 10 and 35 characters long) |
| 16 | + * Note: Don't use the UTC timestamp as a nonce! |
| 17 | + * - Your request method (GET/POST) |
| 18 | + * - The host (mltshp.com) |
| 19 | + * - The port (443 for SSL) |
| 20 | + * - The API endpoint path (/api/sharedfile/GA4) |
| 21 | + * @see https://mltshp.com/developers |
| 22 | + */ |
| 23 | +const generateMltshpAuthString = ( |
| 24 | + token: TokenSet, |
| 25 | + path: string, |
| 26 | + method = 'GET' |
| 27 | +) => { |
| 28 | + const timestamp = Math.floor(Date.now() / 1000); |
| 29 | + const nonce = crypto.randomBytes(20).toString('hex'); |
| 30 | + |
| 31 | + // NOTE: using port 80 due to a bug in the API. |
| 32 | + // https://github.com/MLTSHP/mltshp/issues/567 |
| 33 | + const port = 80; |
| 34 | + |
| 35 | + // Normalize the message. |
| 36 | + // NOTE: The order, indentation, and linebreaks are important! |
| 37 | + const normalizedString = `${token.access_token} |
| 38 | +${timestamp} |
| 39 | +${nonce} |
| 40 | +${method} |
| 41 | +mltshp.com |
| 42 | +${port} |
| 43 | +${path} |
| 44 | +`; |
| 45 | + |
| 46 | + // Create a signature by taking the normalizedString and use the secret to |
| 47 | + // construct a hash using SHA1 encoding, then Base64 the result. |
| 48 | + const hash = hmacSHA1(normalizedString, token.secret); |
| 49 | + const signature = base64.stringify(hash); |
| 50 | + |
| 51 | + const authString = |
| 52 | + `MAC token=${token.access_token}, ` + |
| 53 | + `timestamp=${timestamp}, ` + |
| 54 | + `nonce=${nonce}, ` + |
| 55 | + `signature=${signature}`; |
| 56 | + |
| 57 | + return authString; |
| 58 | +}; |
| 59 | + |
| 60 | +export default generateMltshpAuthString; |
0 commit comments