diff --git a/lib/cloudfrontUtil.js b/lib/cloudfrontUtil.js index 7ca74b9..83d5d45 100644 --- a/lib/cloudfrontUtil.js +++ b/lib/cloudfrontUtil.js @@ -10,13 +10,45 @@ var _ = require('lodash'); var CannedPolicy = require('./CannedPolicy'); /** - * Build an AWS signed URL. + * Build an AWS signed URL using WHATWG URL policy * - * @param {String} CloudFront resource URL - * @param {Object} Signature parameters + * @param {Object} params Signature parameters + * @return {String} Signed CloudFront URL + * @throws {TypeError} + */ +function getSignedWhatwgUrl(params) { + if (!params.url || !params.pathname) { + throw new TypeError('Invalid options; url and pathname are required.'); + } + + var cfUrl = params.url + params.pathname; + + var privateKey = _getPrivateKey(params); + var policy = _createPolicy( + cfUrl, _getExpireTime(params), _getIpRange(params)); + var signature = _createPolicySignature(policy, privateKey); + var policyStr = new Buffer(policy.toJSON()).toString('base64'); + + var whatwgUrl = new url.URL(params.pathname, params.url); + whatwgUrl.searchParams.append('Expires', policy.expireTime); + whatwgUrl.searchParams.append('Policy', normalizeBase64(policyStr)); + whatwgUrl.searchParams.append('Signature', normalizeBase64(signature)); + whatwgUrl.searchParams.append('Key-Pair-Id', params.keypairId); + return whatwgUrl.toString(); +} + +/** + * Build an AWS signed URL using the legacy nodejs URL object. + * + * @param {String} [cfUrl] CloudFront resource URL - optional, if omitted, params.url and params.pathname are required + * @param {Object} params Signature parameters * @return {String} Signed CloudFront URL */ function getSignedUrl(cfUrl, params) { + if (arguments.length === 1) { + return getSignedWhatwgUrl(cfUrl); + } + var privateKey = _getPrivateKey(params); var policy = _createPolicy( cfUrl, _getExpireTime(params), _getIpRange(params)); @@ -207,6 +239,7 @@ function _getPrivateKey(params) { exports.getSignedCookies = getSignedCookies; exports.getSignedUrl = getSignedUrl; +exports.getSignedWhatwgUrl = getSignedWhatwgUrl; exports.getSignedRTMPUrl = getSignedRTMPUrl; exports.normalizeSignature = normalizeSignature; exports.normalizeBase64 = normalizeBase64;