This is a Node.js implementation of the CDNsun URL Signing Token function as described here.
It requires on CryptoJs.
| const CryptoJS = require('crypto-js') | |
| function generateSignedUrl(scheme = "http", cdnResourceUrl, filePath = "/", secretKey, expiryTimestamp = "", clientIp = "") { | |
| if (scheme === '' || cdnResourceUrl === '') { | |
| throw new Error('First argument "scheme" and/or second argument "cdnResourceUrl" cannot be empty.'); | |
| } | |
| // NOTE: We adhere to ngx_secure_link_module hashing strategy | |
| // Ref: http://nginx.org/en/docs/http/ngx_http_secure_link_module.html#secure_link | |
| let searchChars = ['+', '/', '=']; | |
| let replaceChars = ['-', '_', '']; | |
| // 1. Setup Token Key | |
| // 1.1 Append leading slash if missing | |
| if (filePath[0] != '/') { | |
| filePath = `/${filePath}`; | |
| } | |
| // 1.2 Extract uri, ignore arguments | |
| let pos = filePath.indexOf('?') | |
| if (pos != -1) { | |
| filePath = $filePath.substring(0, pos); | |
| } | |
| // 1.3 Formulate the token key | |
| tokenKey = expiryTimestamp + filePath + secretKey + clientIp; | |
| let secureString = CryptoJS.enc.Base64.stringify((CryptoJS.MD5(tokenKey))); | |
| for (replace in searchChars) { | |
| secureString = secureString.replace(new RegExp(`\\${searchChars[replace]}`, 'g'), replaceChars[replace]) | |
| } | |
| // 2. Setup URL | |
| // 2.1 Append argument - secure (compulsory) | |
| urlStr = `${scheme}://${cdnResourceUrl}${filePath}?secure=${secureString}`; | |
| // 2.2 Append argument - expires | |
| if (expiryTimestamp !== '' && expiryTimestamp !== "0" && expiryTimestamp !== 0) { | |
| urlStr += `&expires=${expiryTimestamp}`; | |
| } | |
| // 2.3 Append argument - ip | |
| if (clientIp !== '') { | |
| urlStr += `&ip=${clientIp}`; | |
| } | |
| return urlStr; | |
| } |