|
| 1 | +/** |
| 2 | + * Example from https://googlemaps.github.io/url-signing/urlSigner.js |
| 3 | + */ |
| 4 | +import crypto from 'crypto'; |
| 5 | + |
| 6 | +/** |
| 7 | + * Convert from 'web safe' base64 to true base64. |
| 8 | + * |
| 9 | + * @param {string} safeEncodedString The code you want to translate |
| 10 | + * from a web safe form. |
| 11 | + * @return {string} |
| 12 | + */ |
| 13 | +function removeWebSafe(safeEncodedString: string): string { |
| 14 | + return safeEncodedString.replace(/-/g, '+').replace(/_/g, '/'); |
| 15 | +} |
| 16 | + |
| 17 | +/** |
| 18 | + * Convert from true base64 to 'web safe' base64 |
| 19 | + * |
| 20 | + * @param {string} encodedString The code you want to translate to a |
| 21 | + * web safe form. |
| 22 | + * @return {string} |
| 23 | + */ |
| 24 | +function makeWebSafe(encodedString: string): string { |
| 25 | + return encodedString.replace(/\+/g, '-').replace(/\//g, '_'); |
| 26 | +} |
| 27 | + |
| 28 | +/** |
| 29 | + * Takes a base64 code and decodes it. |
| 30 | + * |
| 31 | + * @param {string} code The encoded data. |
| 32 | + * @return {Buffer} |
| 33 | + */ |
| 34 | +function decodeBase64Hash(code: string): Buffer { |
| 35 | + // "new Buffer(...)" is deprecated. Use Buffer.from if it exists. |
| 36 | + return Buffer.from ? Buffer.from(code, 'base64') : new Buffer(code, 'base64'); |
| 37 | +} |
| 38 | + |
| 39 | +/** |
| 40 | + * Takes a key and signs the data with it. |
| 41 | + * |
| 42 | + * @param {string} key Your unique secret key. |
| 43 | + * @param {string} data The url to sign. |
| 44 | + * @return {string} |
| 45 | + */ |
| 46 | +function encodeBase64Hash(key: string, data: string): string { |
| 47 | + return crypto.createHmac('sha1', key).update(data).digest('base64'); |
| 48 | +} |
| 49 | + |
| 50 | +/** |
| 51 | + * Sign a URL using a secret key. |
| 52 | + * |
| 53 | + * @param {string} path The url you want to sign. |
| 54 | + * @param {string} secret Your unique secret key. |
| 55 | + * @param {Object} query Query object |
| 56 | + * @return {string} |
| 57 | + */ |
| 58 | +export function urlSign(path: string, query: any, secret: string, ): string { |
| 59 | + const queryString = new URLSearchParams(JSON.stringify(query)).toString(); |
| 60 | + const safeSecret = decodeBase64Hash(removeWebSafe(secret)).toString('base64'); |
| 61 | + return makeWebSafe(encodeBase64Hash(safeSecret, path + queryString)); |
| 62 | +} |
0 commit comments