]> gerrit.simantics Code Review - simantics/district.git/blob - org.simantics.maps.server/node/node-v4.8.0-win-x64/node_modules/npm/node_modules/request/node_modules/aws4/aws4.js
Adding integrated tile server
[simantics/district.git] / org.simantics.maps.server / node / node-v4.8.0-win-x64 / node_modules / npm / node_modules / request / node_modules / aws4 / aws4.js
1 var aws4 = exports,
2     url = require('url'),
3     querystring = require('querystring'),
4     crypto = require('crypto'),
5     lru = require('./lru'),
6     credentialsCache = lru(1000)
7
8 // http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html
9
10 function hmac(key, string, encoding) {
11   return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding)
12 }
13
14 function hash(string, encoding) {
15   return crypto.createHash('sha256').update(string, 'utf8').digest(encoding)
16 }
17
18 // This function assumes the string has already been percent encoded
19 function encodeRfc3986(urlEncodedString) {
20   return urlEncodedString.replace(/[!'()*]/g, function(c) {
21     return '%' + c.charCodeAt(0).toString(16).toUpperCase()
22   })
23 }
24
25 // request: { path | body, [host], [method], [headers], [service], [region] }
26 // credentials: { accessKeyId, secretAccessKey, [sessionToken] }
27 function RequestSigner(request, credentials) {
28
29   if (typeof request === 'string') request = url.parse(request)
30
31   var headers = request.headers = (request.headers || {}),
32       hostParts = this.matchHost(request.hostname || request.host || headers.Host || headers.host)
33
34   this.request = request
35   this.credentials = credentials || this.defaultCredentials()
36
37   this.service = request.service || hostParts[0] || ''
38   this.region = request.region || hostParts[1] || 'us-east-1'
39
40   // SES uses a different domain from the service name
41   if (this.service === 'email') this.service = 'ses'
42
43   if (!request.method && request.body)
44     request.method = 'POST'
45
46   if (!headers.Host && !headers.host) {
47     headers.Host = request.hostname || request.host || this.createHost()
48
49     // If a port is specified explicitly, use it as is
50     if (request.port)
51       headers.Host += ':' + request.port
52   }
53   if (!request.hostname && !request.host)
54     request.hostname = headers.Host || headers.host
55 }
56
57 RequestSigner.prototype.matchHost = function(host) {
58   var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com$/)
59   var hostParts = (match || []).slice(1, 3)
60
61   // ES's hostParts are sometimes the other way round, if the value that is expected
62   // to be region equals ‘es’ switch them back
63   // e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com
64   if (hostParts[1] === 'es')
65     hostParts = hostParts.reverse()
66
67   return hostParts
68 }
69
70 // http://docs.aws.amazon.com/general/latest/gr/rande.html
71 RequestSigner.prototype.isSingleRegion = function() {
72   // Special case for S3 and SimpleDB in us-east-1
73   if (['s3', 'sdb'].indexOf(this.service) >= 0 && this.region === 'us-east-1') return true
74
75   return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts']
76     .indexOf(this.service) >= 0
77 }
78
79 RequestSigner.prototype.createHost = function() {
80   var region = this.isSingleRegion() ? '' :
81         (this.service === 's3' && this.region !== 'us-east-1' ? '-' : '.') + this.region,
82       service = this.service === 'ses' ? 'email' : this.service
83   return service + region + '.amazonaws.com'
84 }
85
86 RequestSigner.prototype.prepareRequest = function() {
87   this.parsePath()
88
89   var request = this.request, headers = request.headers, query
90
91   if (request.signQuery) {
92
93     this.parsedPath.query = query = this.parsedPath.query || {}
94
95     if (this.credentials.sessionToken)
96       query['X-Amz-Security-Token'] = this.credentials.sessionToken
97
98     if (this.service === 's3' && !query['X-Amz-Expires'])
99       query['X-Amz-Expires'] = 86400
100
101     if (query['X-Amz-Date'])
102       this.datetime = query['X-Amz-Date']
103     else
104       query['X-Amz-Date'] = this.getDateTime()
105
106     query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256'
107     query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString()
108     query['X-Amz-SignedHeaders'] = this.signedHeaders()
109
110   } else {
111
112     if (!request.doNotModifyHeaders) {
113       if (request.body && !headers['Content-Type'] && !headers['content-type'])
114         headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'
115
116       if (request.body && !headers['Content-Length'] && !headers['content-length'])
117         headers['Content-Length'] = Buffer.byteLength(request.body)
118
119       if (this.credentials.sessionToken)
120         headers['X-Amz-Security-Token'] = this.credentials.sessionToken
121
122       if (this.service === 's3')
123         headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex')
124
125       if (headers['X-Amz-Date'])
126         this.datetime = headers['X-Amz-Date']
127       else
128         headers['X-Amz-Date'] = this.getDateTime()
129     }
130
131     delete headers.Authorization
132     delete headers.authorization
133   }
134 }
135
136 RequestSigner.prototype.sign = function() {
137   if (!this.parsedPath) this.prepareRequest()
138
139   if (this.request.signQuery) {
140     this.parsedPath.query['X-Amz-Signature'] = this.signature()
141   } else {
142     this.request.headers.Authorization = this.authHeader()
143   }
144
145   this.request.path = this.formatPath()
146
147   return this.request
148 }
149
150 RequestSigner.prototype.getDateTime = function() {
151   if (!this.datetime) {
152     var headers = this.request.headers,
153       date = new Date(headers.Date || headers.date || new Date)
154
155     this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, '')
156   }
157   return this.datetime
158 }
159
160 RequestSigner.prototype.getDate = function() {
161   return this.getDateTime().substr(0, 8)
162 }
163
164 RequestSigner.prototype.authHeader = function() {
165   return [
166     'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(),
167     'SignedHeaders=' + this.signedHeaders(),
168     'Signature=' + this.signature(),
169   ].join(', ')
170 }
171
172 RequestSigner.prototype.signature = function() {
173   var date = this.getDate(),
174       cacheKey = [this.credentials.secretAccessKey, date, this.region, this.service].join(),
175       kDate, kRegion, kService, kCredentials = credentialsCache.get(cacheKey)
176   if (!kCredentials) {
177     kDate = hmac('AWS4' + this.credentials.secretAccessKey, date)
178     kRegion = hmac(kDate, this.region)
179     kService = hmac(kRegion, this.service)
180     kCredentials = hmac(kService, 'aws4_request')
181     credentialsCache.set(cacheKey, kCredentials)
182   }
183   return hmac(kCredentials, this.stringToSign(), 'hex')
184 }
185
186 RequestSigner.prototype.stringToSign = function() {
187   return [
188     'AWS4-HMAC-SHA256',
189     this.getDateTime(),
190     this.credentialString(),
191     hash(this.canonicalString(), 'hex'),
192   ].join('\n')
193 }
194
195 RequestSigner.prototype.canonicalString = function() {
196   if (!this.parsedPath) this.prepareRequest()
197
198   var pathStr = this.parsedPath.path,
199       query = this.parsedPath.query,
200       queryStr = '',
201       normalizePath = this.service !== 's3',
202       decodePath = this.service === 's3' || this.request.doNotEncodePath,
203       decodeSlashesInPath = this.service === 's3',
204       firstValOnly = this.service === 's3',
205       bodyHash = this.service === 's3' && this.request.signQuery ?
206         'UNSIGNED-PAYLOAD' : hash(this.request.body || '', 'hex')
207
208   if (query) {
209     queryStr = encodeRfc3986(querystring.stringify(Object.keys(query).sort().reduce(function(obj, key) {
210       if (!key) return obj
211       obj[key] = !Array.isArray(query[key]) ? query[key] :
212         (firstValOnly ? query[key][0] : query[key].slice().sort())
213       return obj
214     }, {})))
215   }
216   if (pathStr !== '/') {
217     if (normalizePath) pathStr = pathStr.replace(/\/{2,}/g, '/')
218     pathStr = pathStr.split('/').reduce(function(path, piece) {
219       if (normalizePath && piece === '..') {
220         path.pop()
221       } else if (!normalizePath || piece !== '.') {
222         if (decodePath) piece = querystring.unescape(piece)
223         path.push(encodeRfc3986(querystring.escape(piece)))
224       }
225       return path
226     }, []).join('/')
227     if (pathStr[0] !== '/') pathStr = '/' + pathStr
228     if (decodeSlashesInPath) pathStr = pathStr.replace(/%2F/g, '/')
229   }
230
231   return [
232     this.request.method || 'GET',
233     pathStr,
234     queryStr,
235     this.canonicalHeaders() + '\n',
236     this.signedHeaders(),
237     bodyHash,
238   ].join('\n')
239 }
240
241 RequestSigner.prototype.canonicalHeaders = function() {
242   var headers = this.request.headers
243   function trimAll(header) {
244     return header.toString().trim().replace(/\s+/g, ' ')
245   }
246   return Object.keys(headers)
247     .sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1 })
248     .map(function(key) { return key.toLowerCase() + ':' + trimAll(headers[key]) })
249     .join('\n')
250 }
251
252 RequestSigner.prototype.signedHeaders = function() {
253   return Object.keys(this.request.headers)
254     .map(function(key) { return key.toLowerCase() })
255     .sort()
256     .join(';')
257 }
258
259 RequestSigner.prototype.credentialString = function() {
260   return [
261     this.getDate(),
262     this.region,
263     this.service,
264     'aws4_request',
265   ].join('/')
266 }
267
268 RequestSigner.prototype.defaultCredentials = function() {
269   var env = process.env
270   return {
271     accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY,
272     secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY,
273     sessionToken: env.AWS_SESSION_TOKEN,
274   }
275 }
276
277 RequestSigner.prototype.parsePath = function() {
278   var path = this.request.path || '/',
279       queryIx = path.indexOf('?'),
280       query = null
281
282   if (queryIx >= 0) {
283     query = querystring.parse(path.slice(queryIx + 1))
284     path = path.slice(0, queryIx)
285   }
286
287   // S3 doesn't always encode characters > 127 correctly and
288   // all services don't encode characters > 255 correctly
289   // So if there are non-reserved chars (and it's not already all % encoded), just encode them all
290   if (/[^0-9A-Za-z!'()*\-._~%/]/.test(path)) {
291     path = path.split('/').map(function(piece) {
292       return querystring.escape(querystring.unescape(piece))
293     }).join('/')
294   }
295
296   this.parsedPath = {
297     path: path,
298     query: query,
299   }
300 }
301
302 RequestSigner.prototype.formatPath = function() {
303   var path = this.parsedPath.path,
304       query = this.parsedPath.query
305
306   if (!query) return path
307
308   // Services don't support empty query string keys
309   if (query[''] != null) delete query['']
310
311   return path + '?' + encodeRfc3986(querystring.stringify(query))
312 }
313
314 aws4.RequestSigner = RequestSigner
315
316 aws4.sign = function(request, credentials) {
317   return new RequestSigner(request, credentials).sign()
318 }