signUtils.js 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. const crypto = require('crypto');
  2. const is = require('is-type-of');
  3. const { lowercaseKeyHeader } = require('./utils/lowercaseKeyHeader')
  4. /**
  5. *
  6. * @param {String} resourcePath
  7. * @param {Object} parameters
  8. * @return
  9. */
  10. exports.buildCanonicalizedResource = function buildCanonicalizedResource(resourcePath, parameters) {
  11. let canonicalizedResource = `${resourcePath}`;
  12. let separatorString = '?';
  13. if (is.string(parameters) && parameters.trim() !== '') {
  14. canonicalizedResource += separatorString + parameters;
  15. } else if (is.array(parameters)) {
  16. parameters.sort();
  17. canonicalizedResource += separatorString + parameters.join('&');
  18. } else if (parameters) {
  19. const compareFunc = (entry1, entry2) => {
  20. if (entry1[0] > entry2[0]) {
  21. return 1;
  22. } else if (entry1[0] < entry2[0]) {
  23. return -1;
  24. }
  25. return 0;
  26. };
  27. const processFunc = (key) => {
  28. canonicalizedResource += separatorString + key;
  29. if (parameters[key]) {
  30. canonicalizedResource += `=${parameters[key]}`;
  31. }
  32. separatorString = '&';
  33. };
  34. Object.keys(parameters).sort(compareFunc).forEach(processFunc);
  35. }
  36. return canonicalizedResource;
  37. };
  38. /**
  39. * @param {String} method
  40. * @param {String} resourcePath
  41. * @param {Object} request
  42. * @param {String} expires
  43. * @return {String} canonicalString
  44. */
  45. exports.buildCanonicalString = function canonicalString(method, resourcePath, request, expires) {
  46. request = request || {};
  47. const headers = lowercaseKeyHeader(request.headers);
  48. const OSS_PREFIX = 'x-oss-';
  49. const ossHeaders = [];
  50. const headersToSign = {};
  51. let signContent = [
  52. method.toUpperCase(),
  53. headers['content-md5'] || '',
  54. headers['content-type'],
  55. expires || headers['x-oss-date']
  56. ];
  57. Object.keys(headers).forEach((key) => {
  58. const lowerKey = key.toLowerCase();
  59. if (lowerKey.indexOf(OSS_PREFIX) === 0) {
  60. headersToSign[lowerKey] = String(headers[key]).trim();
  61. }
  62. });
  63. Object.keys(headersToSign).sort().forEach((key) => {
  64. ossHeaders.push(`${key}:${headersToSign[key]}`);
  65. });
  66. signContent = signContent.concat(ossHeaders);
  67. signContent.push(this.buildCanonicalizedResource(resourcePath, request.parameters));
  68. return signContent.join('\n');
  69. };
  70. /**
  71. * @param {String} accessKeySecret
  72. * @param {String} canonicalString
  73. */
  74. exports.computeSignature = function computeSignature(accessKeySecret, canonicalString, headerEncoding = 'utf-8') {
  75. const signature = crypto.createHmac('sha1', accessKeySecret);
  76. return signature.update(Buffer.from(canonicalString, headerEncoding)).digest('base64');
  77. };
  78. /**
  79. * @param {String} accessKeyId
  80. * @param {String} accessKeySecret
  81. * @param {String} canonicalString
  82. */
  83. exports.authorization = function authorization(accessKeyId, accessKeySecret, canonicalString, headerEncoding) {
  84. return `OSS ${accessKeyId}:${this.computeSignature(accessKeySecret, canonicalString, headerEncoding)}`;
  85. };
  86. /**
  87. *
  88. * @param {String} accessKeySecret
  89. * @param {Object} options
  90. * @param {String} resource
  91. * @param {Number} expires
  92. */
  93. exports._signatureForURL = function _signatureForURL(accessKeySecret, options = {}, resource, expires, headerEncoding) {
  94. const headers = {};
  95. const { subResource = {} } = options;
  96. if (options.process) {
  97. const processKeyword = 'x-oss-process';
  98. subResource[processKeyword] = options.process;
  99. }
  100. if (options.trafficLimit) {
  101. const trafficLimitKey = 'x-oss-traffic-limit';
  102. subResource[trafficLimitKey] = options.trafficLimit;
  103. }
  104. if (options.response) {
  105. Object.keys(options.response).forEach((k) => {
  106. const key = `response-${k.toLowerCase()}`;
  107. subResource[key] = options.response[k];
  108. });
  109. }
  110. Object.keys(options).forEach((key) => {
  111. const lowerKey = key.toLowerCase();
  112. const value = options[key];
  113. if (lowerKey.indexOf('x-oss-') === 0) {
  114. headers[lowerKey] = value;
  115. } else if (lowerKey.indexOf('content-md5') === 0) {
  116. headers[key] = value;
  117. } else if (lowerKey.indexOf('content-type') === 0) {
  118. headers[key] = value;
  119. }
  120. });
  121. if (Object.prototype.hasOwnProperty.call(options, 'security-token')) {
  122. subResource['security-token'] = options['security-token'];
  123. }
  124. if (Object.prototype.hasOwnProperty.call(options, 'callback')) {
  125. const json = {
  126. callbackUrl: encodeURI(options.callback.url),
  127. callbackBody: options.callback.body
  128. };
  129. if (options.callback.host) {
  130. json.callbackHost = options.callback.host;
  131. }
  132. if (options.callback.contentType) {
  133. json.callbackBodyType = options.callback.contentType;
  134. }
  135. subResource.callback = Buffer.from(JSON.stringify(json)).toString('base64');
  136. if (options.callback.customValue) {
  137. const callbackVar = {};
  138. Object.keys(options.callback.customValue).forEach((key) => {
  139. callbackVar[`x:${key}`] = options.callback.customValue[key];
  140. });
  141. subResource['callback-var'] = Buffer.from(JSON.stringify(callbackVar)).toString('base64');
  142. }
  143. }
  144. const canonicalString = this.buildCanonicalString(options.method, resource, {
  145. headers,
  146. parameters: subResource
  147. }, expires.toString());
  148. return {
  149. Signature: this.computeSignature(accessKeySecret, canonicalString, headerEncoding),
  150. subResource
  151. };
  152. };