forked from JonathanBennett/AkamaiOPEN-edgegrid-node
-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathhelpers.js
210 lines (171 loc) · 7.16 KB
/
helpers.js
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
const crypto = require('crypto'),
logger = require('./logger'),
path = require('path'),
os = require('os');
const MAX_BODY = 131072
function twoDigitNumberPad(number) {
return String(number).padStart(2, '0');
}
module.exports = {
/**
* Create timestamp with format "yyyyMMddTHH:mm:ss+0000"
*
* @see https://developer.akamai.com/legacy/introduction/Client_Auth.html#authorizationheaderfields
*/
MAX_BODY,
createTimestamp: function () {
const date = new Date(Date.now());
return date.getUTCFullYear() +
twoDigitNumberPad(date.getUTCMonth() + 1) +
twoDigitNumberPad(date.getUTCDate()) +
'T' +
twoDigitNumberPad(date.getUTCHours()) + ':' +
twoDigitNumberPad(date.getUTCMinutes()) +
':' +
twoDigitNumberPad(date.getUTCSeconds()) +
'+0000';
},
contentHash: function (request) {
let contentHash = '',
preparedBody = request.body || '',
isTarball = preparedBody instanceof Uint8Array && request.headers['Content-Type'] === 'application/gzip';
if (typeof preparedBody === 'object' && !isTarball) {
let postDataNew = '',
key;
logger.info('Body content is type Object, transforming to POST data');
for (key in preparedBody) {
postDataNew += key + '=' + encodeURIComponent(JSON.stringify(preparedBody[key])) + '&';
}
// Strip trailing ampersand
postDataNew = postDataNew.replace(/&+$/, "");
preparedBody = postDataNew;
request.body = preparedBody; // Is this required or being used?
}
logger.info('Body is \"' + preparedBody + '\"');
logger.debug('PREPARED BODY LENGTH', preparedBody.length);
if (request.method === 'POST' && preparedBody.length > 0) {
logger.info('Signing content: \"' + preparedBody + '\"');
// If body data is too large, cut down to max-body size which is const value
if (preparedBody.length > MAX_BODY) {
logger.warn('Data length (' + preparedBody.length + ') is larger than maximum ' + MAX_BODY);
if (isTarball)
preparedBody = preparedBody.slice(0, MAX_BODY);
else
preparedBody = preparedBody.substring(0, MAX_BODY);
logger.info('Body truncated. New value \"' + preparedBody + '\"');
}
logger.debug('PREPARED BODY', preparedBody);
contentHash = this.base64Sha256(preparedBody);
logger.info('Content hash is \"' + contentHash + '\"');
}
return contentHash;
},
/**
*
* @param {Object} request The request Object. Can optionally contain a
* 'headersToSign' property: An ordered list header names
* that will be included in the signature. This will be
* provided by specific APIs.
* @param {String} authHeader The authorization header.
* @param {Number} maxBody This value is deprecated.
* @deprecated maxBody
*/
dataToSign: function (request, authHeader, maxBody) {
const parsedUrl = new URL(request.url),
dataToSign = [
request.method.toUpperCase(),
parsedUrl.protocol.replace(":", ""),
parsedUrl.host,
parsedUrl.pathname + parsedUrl.search,
this.canonicalizeHeaders(request.headersToSign),
this.contentHash(request, maxBody),
authHeader
];
const dataToSignStr = dataToSign.join('\t').toString();
logger.info('Data to sign: "' + dataToSignStr + '" \n');
return dataToSignStr;
},
extend: function (a, b) {
let key;
for (key in b) {
if (!a.hasOwnProperty(key)) {
a[key] = b[key];
}
}
return a;
},
extendHeaders: function (headers) {
if (!headers.hasOwnProperty('Content-Type')) {
headers['Content-Type'] = "application/json";
}
if (!headers.hasOwnProperty('Accept')) {
headers['Accept'] = "application/json";
}
let userAgents = [headers['User-Agent']];
if (process.env['AKAMAI_CLI'] && process.env['AKAMAI_CLI_VERSION']) {
userAgents.push(`AkamaiCLI/${process.env['AKAMAI_CLI_VERSION']}`);
}
if (process.env['AKAMAI_CLI_COMMAND'] && process.env['AKAMAI_CLI_COMMAND_VERSION']) {
userAgents.push(`AkamaiCLI-${process.env['AKAMAI_CLI_COMMAND']}/${process.env['AKAMAI_CLI_COMMAND_VERSION']}`);
}
userAgents = userAgents.filter(v => v)
if (userAgents.length > 0) {
headers['User-Agent'] = userAgents.join(' ')
}
return headers;
},
isRedirect: function (statusCode) {
return [
300, 301, 302, 303, 307
].indexOf(statusCode) !== -1;
},
base64Sha256: function (data) {
const shasum = crypto.createHash('sha256').update(data);
return shasum.digest('base64');
},
base64HmacSha256: function (data, key) {
const encrypt = crypto.createHmac('sha256', key);
encrypt.update(data);
return encrypt.digest('base64');
},
/**
* Creates a String containing a tab delimited set of headers.
* @param {Object} headers Object containing the headers to add to the set.
* @return {String} String containing a tab delimited set of headers.
*/
canonicalizeHeaders: function (headers) {
const formattedHeaders = [];
let key;
for (key in headers) {
formattedHeaders.push(key.toLowerCase() + ':' + headers[key].trim().replace(/\s+/g, ' '));
}
return formattedHeaders.join('\t');
},
signingKey: function (timestamp, clientSecret) {
const key = this.base64HmacSha256(timestamp, clientSecret);
logger.info('Signing key: ' + key + '\n');
return key;
},
/**
*
* @param {Object} request The request Object. Can optionally contain a
* 'headersToSign' property: An ordered list header names
* that will be included in the signature. This will be
* provided by specific APIs.
* @param {Date} timestamp The timestamp with format "yyyyMMddTHH:mm:ss+0000".
* @param {String} clientSecret The client secret value from the .edgerc file.
* @param {String} authHeader The authorization header.
* @param maxBody This value is deprecated.
* @returns {string}
* @deprecated maxBody
*/
signRequest: function (request, timestamp, clientSecret, authHeader, maxBody) {
return this.base64HmacSha256(this.dataToSign(request, authHeader, maxBody), this.signingKey(timestamp, clientSecret));
},
resolveHome: function (filePath) {
if (filePath[0] === '~') {
return path.join(os.homedir(), filePath.slice(1));
}
return filePath;
},
};