1 | import {typeOf} from "./index";
|
2 | import SHA1 from "./hash/sha1";
|
3 |
|
4 |
|
5 | export function buildCanonicalizedResource(resourcePath: string, parameters: string|string[]|{[key: string]:any}) {
|
6 | let resource = resourcePath;
|
7 | let separator = '?';
|
8 | const type = typeOf(parameters);
|
9 |
|
10 | if (type === 'string' && (<string>parameters).trim() !== '') {
|
11 | resource += separator + parameters;
|
12 | } else if (type === 'array') {
|
13 | (<string[]>parameters).sort();
|
14 | resource += separator + (<string[]>parameters).join('&');
|
15 | } else if (parameters) {
|
16 | const compareFunc = (a, b) => {
|
17 | if (a[0] > b[0]) return 1;
|
18 | if (a[0] < b[0]) return -1;
|
19 | return 0;
|
20 | };
|
21 | const processFunc = key => {
|
22 | resource += separator + key;
|
23 | if (parameters[key]) {
|
24 | resource += `=${parameters[key]}`;
|
25 | }
|
26 | separator = '&';
|
27 | };
|
28 | Object.keys(parameters).sort(compareFunc).forEach(processFunc);
|
29 | }
|
30 | return resource;
|
31 | }
|
32 |
|
33 | export function buildCanonicalString (method: string, resourcePath: string, request?, expires?: any) {
|
34 | const headers = request.headers || {};
|
35 | const OSS_PREFIX = 'x-oss-';
|
36 | const ossHeaders = [];
|
37 | const headersToSign = {};
|
38 |
|
39 | let signContent = [
|
40 | method.toUpperCase(),
|
41 | headers['Content-Md5'] || '',
|
42 | headers['Content-Type'] || headers['content-type'],
|
43 | expires || headers['x-oss-date'],
|
44 | ];
|
45 |
|
46 | Object.keys(headers).forEach(key => {
|
47 | const lowerKey = key.toLowerCase();
|
48 | if (lowerKey.indexOf(OSS_PREFIX) === 0) {
|
49 | headersToSign[lowerKey] = String(headers[key]).trim();
|
50 | }
|
51 | });
|
52 |
|
53 | Object.keys(headersToSign).sort().forEach(key => {
|
54 | ossHeaders.push(`${key}:${headersToSign[key]}`);
|
55 | });
|
56 |
|
57 | signContent = signContent.concat(ossHeaders);
|
58 |
|
59 | signContent.push(buildCanonicalizedResource(resourcePath, request.params));
|
60 |
|
61 | return signContent.join("\n");
|
62 | }
|
63 |
|
64 | export function computeSignature (accessKeySecret: string, canonicalString: string) {
|
65 | return new SHA1().b64_hmac(accessKeySecret, canonicalString);
|
66 | }
|
67 |
|
68 | export function authorization (accessKeyId: string, accessKeySecret: string, canonicalString: string) {
|
69 | return `OSS ${accessKeyId}:${computeSignature(accessKeySecret, canonicalString)}`;
|
70 | }
|