/
utils.ts
321 lines (289 loc) · 7.82 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
import crypto from 'crypto';
import moment from 'moment';
import chalk from 'chalk';
import qs from 'querystring';
import { CapiOptions } from './index';
export interface Payload {
Region?: string;
SecretId?: string;
Timestamp?: number | string;
Nonce?: number;
[propName: string]: any;
}
export interface HostParams {
ServiceType: string;
Region: string;
host: string | undefined;
baseHost: string | undefined;
path?: string;
protocol?: string;
}
export interface TencentSignResult {
url: string;
payload: Payload;
Host: string;
Authorization: string;
Timestamp: number | string;
}
export interface TencentSignResultV1 {
url: string;
method: string;
signPath: string;
}
export function logger(topic: string, content: string): void {
console.log(
`${chalk.black.bgYellow('[DEBUG]')} ${chalk.green(
`${topic}:`,
)} ${content} `,
);
}
export function getHost(
{ host, ServiceType, Region, baseHost }: HostParams,
isV1 = false,
) {
if (!host) {
host = `${ServiceType}${isV1 ? '' : `.${Region}`}.${baseHost}`;
}
return host;
}
export function getUrl(opts: HostParams, isV1 = false) {
opts = opts || {};
const host = getHost(opts, isV1);
const path = opts.path || '/';
return `${opts.protocol || 'https'}://${host}${path}`;
}
export function sign(
str: string,
secretKey: Buffer,
algorithm: string = 'sha256',
): Buffer {
const hmac = crypto.createHmac(algorithm, secretKey);
return hmac.update(Buffer.from(str, 'utf8')).digest();
}
/**
* is array
* @param obj object
*/
export function isArray(obj: any) {
return Object.prototype.toString.call(obj) == '[object Array]';
}
/**
* is object
* @param obj object
*/
export function isObject(obj: any) {
return obj === Object(obj);
}
/**
* iterate object or array
* @param obj object or array
* @param iterator iterator function
*/
export function _forEach(
obj: object | any[],
iterator: (value: any, index: number | string, array: any) => void,
) {
if (isArray(obj)) {
let arr = obj as Array<any>;
if (arr.forEach) {
arr.forEach(iterator);
return;
}
for (let i = 0; i < arr.length; i += 1) {
iterator(arr[i], i, arr);
}
} else {
const oo = obj as { [propName: string]: any };
for (let key in oo) {
if (obj.hasOwnProperty(key)) {
iterator(oo[key], key, obj);
}
}
}
}
/**
* flatter request parameter
* @param obj target object or array
*/
export function flatten(obj: {
[propName: string]: any;
}): { [propName: string]: any } {
if (!isArray(obj) && !isObject(obj)) {
return {};
}
const ret: { [propName: string]: any } = {};
const _dump = function(
obj: object | Array<any>,
prefix: string | null,
parents?: any[],
) {
const checkedParents: any[] = [];
if (parents) {
let i;
for (i = 0; i < parents.length; i++) {
if (parents[i] === obj) {
throw new Error('object has circular references');
}
checkedParents.push(obj);
}
}
checkedParents.push(obj);
if (!isArray(obj) && !isObject(obj)) {
if (!prefix) {
throw obj + 'is not object or array';
}
ret[prefix] = obj;
return {};
}
if (isArray(obj)) {
// it's an array
_forEach(obj, function(obj, i) {
_dump(obj, prefix ? prefix + '.' + i : '' + i, checkedParents);
});
} else {
// it's an object
_forEach(obj, function(obj, key) {
_dump(obj, prefix ? prefix + '.' + key : '' + key, checkedParents);
});
}
};
_dump(obj, null);
return ret;
}
/**
* generate tencent cloud sign result
*
* @param {Payload} payload
* @param {CapiOptions} options
* @returns {TencentSignResult}
*/
export function tencentSign(
payload: Payload,
options: CapiOptions,
): TencentSignResult {
const hostParams: HostParams = {
host: options.host,
path: options.path,
protocol: options.protocol,
baseHost: options.baseHost,
ServiceType: options.ServiceType,
Region: options.Region,
};
const url = getUrl(hostParams);
const Host = getHost(hostParams);
const nowTime = moment();
const Timestamp = nowTime.unix();
// const Nonce = Math.round(Math.random() * 65535)
const date = nowTime.toISOString().slice(0, 10);
const Algorithm = 'TC3-HMAC-SHA256';
payload.RequestClient = payload.RequestClient || 'TENCENT_SDK_CAPI';
payload = flatten(payload);
// 1. create Canonical request string
const HTTPRequestMethod = (options.method || 'POST').toUpperCase();
const CanonicalURI = '/';
const CanonicalQueryString = '';
const CanonicalHeaders = `content-type:application/json\nhost:${Host}\n`;
const SignedHeaders = 'content-type;host';
const HashedRequestPayload = crypto
.createHash('sha256')
.update(JSON.stringify(payload))
.digest('hex');
const CanonicalRequest = `${HTTPRequestMethod}\n${CanonicalURI}\n${CanonicalQueryString}\n${CanonicalHeaders}\n${SignedHeaders}\n${HashedRequestPayload}`;
// 2. create string to sign
const CredentialScope = `${date}/${options.ServiceType}/tc3_request`;
const HashedCanonicalRequest = crypto
.createHash('sha256')
.update(CanonicalRequest)
.digest('hex');
const StringToSign = `${Algorithm}\n${Timestamp}\n${CredentialScope}\n${HashedCanonicalRequest}`;
// 3. calculate signature
const SecretDate = sign(date, Buffer.from(`TC3${options.SecretKey}`, 'utf8'));
const SecretService = sign(options.ServiceType, SecretDate);
const SecretSigning = sign('tc3_request', SecretService);
const Signature = crypto
.createHmac('sha256', SecretSigning)
.update(Buffer.from(StringToSign, 'utf8'))
.digest('hex');
// 4. create authorization
const Authorization = `${Algorithm} Credential=${options.SecretId}/${CredentialScope}, SignedHeaders=${SignedHeaders}, Signature=${Signature}`;
// log debug info
if (options.debug) {
logger('CanonicalRequest', CanonicalRequest);
logger('StringToSign', StringToSign);
logger('Signature', Signature);
logger('Authorization', Authorization);
}
return {
url,
payload,
Host,
Authorization,
Timestamp,
};
}
/**
* version1: generate tencent cloud sign result
*
* @param {Payload} payload
* @param {CapiOptions} options
* @returns {TencentSignResultV1}
*/
export function tencentSignV1(
payload: Payload,
options: CapiOptions,
): TencentSignResultV1 {
const hostParams: HostParams = {
host: options.host,
path: options.path,
protocol: options.protocol,
baseHost: options.baseHost,
ServiceType: options.ServiceType,
Region: options.Region,
};
const url = getUrl(hostParams, true);
const Host = getHost(hostParams, true);
const nowTime = moment();
const Timestamp = nowTime.unix();
const Nonce = Math.round(Math.random() * 65535);
payload.Region = options.Region;
payload.Nonce = Nonce;
payload.Timestamp = Timestamp;
payload.SecretId = options.SecretId;
payload.RequestClient = payload.RequestClient || 'SDK_NODEJS_v0.0.1';
if (options.SignatureMethod === 'sha256') {
payload.SignatureMethod = 'HmacSHA256';
}
payload = flatten(payload);
const keys = Object.keys(payload).sort();
const method = (options.method || 'POST').toUpperCase();
let qstr = '';
keys.forEach(function(key) {
if (key === '') {
return;
}
key = key.indexOf('_') ? key.replace(/_/g, '.') : key;
let val = payload[key];
if (method === 'POST' && val && val[0] === '@') {
return;
}
if (
val === undefined ||
val === null ||
(typeof val === 'number' && isNaN(val))
) {
val = '';
}
qstr += `&${key}=${val}`;
});
qstr = qstr.slice(1);
payload.Signature = sign(
`${method}${Host}${options.path}?${qstr}`,
Buffer.from(options.SecretKey, 'utf8'),
options.SignatureMethod,
).toString('base64');
return {
url,
method,
signPath: qs.stringify(payload),
};
}