Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/npm/cli.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRebecca Turner <me@re-becca.org>2016-01-28 03:43:14 +0300
committerRebecca Turner <me@re-becca.org>2016-01-29 01:58:48 +0300
commit220fc7702ae3e5d601dfefd3e95c14e9b32327de (patch)
tree9728ffb93a85ca6305402221332347313c21e7a9 /node_modules/request
parent9e5c84f1903748897e54f8ff099729ff744eab0f (diff)
request@2.69.0
A bunch of small bug fixes and module updates. Credit: @simov
Diffstat (limited to 'node_modules/request')
-rw-r--r--node_modules/request/CHANGELOG.md17
-rw-r--r--node_modules/request/README.md2
-rw-r--r--node_modules/request/lib/har.js5
-rw-r--r--node_modules/request/lib/multipart.js3
-rw-r--r--node_modules/request/lib/tunnel.js2
-rw-r--r--node_modules/request/node_modules/aws4/.npmignore3
-rw-r--r--node_modules/request/node_modules/aws4/.tern-port1
-rw-r--r--node_modules/request/node_modules/aws4/.travis.yml5
-rw-r--r--node_modules/request/node_modules/aws4/LICENSE19
-rw-r--r--node_modules/request/node_modules/aws4/README.md510
-rw-r--r--node_modules/request/node_modules/aws4/aws4.js313
-rw-r--r--node_modules/request/node_modules/aws4/example.js372
-rw-r--r--node_modules/request/node_modules/aws4/node_modules/lru-cache/.npmignore1
-rw-r--r--node_modules/request/node_modules/aws4/node_modules/lru-cache/.travis.yml8
-rw-r--r--node_modules/request/node_modules/aws4/node_modules/lru-cache/CONTRIBUTORS14
-rw-r--r--node_modules/request/node_modules/aws4/node_modules/lru-cache/LICENSE15
-rw-r--r--node_modules/request/node_modules/aws4/node_modules/lru-cache/README.md137
-rw-r--r--node_modules/request/node_modules/aws4/node_modules/lru-cache/lib/lru-cache.js334
-rw-r--r--node_modules/request/node_modules/aws4/node_modules/lru-cache/package.json84
-rw-r--r--node_modules/request/node_modules/aws4/node_modules/lru-cache/test/basic.js396
-rw-r--r--node_modules/request/node_modules/aws4/node_modules/lru-cache/test/foreach.js120
-rw-r--r--node_modules/request/node_modules/aws4/node_modules/lru-cache/test/memory-leak.js51
-rw-r--r--node_modules/request/node_modules/aws4/node_modules/lru-cache/test/serialize.js216
-rw-r--r--node_modules/request/node_modules/aws4/package.json130
-rwxr-xr-xnode_modules/request/node_modules/hawk/README.md1268
-rw-r--r--node_modules/request/node_modules/hawk/bower.json48
-rw-r--r--node_modules/request/node_modules/hawk/component.json36
-rw-r--r--node_modules/request/node_modules/hawk/dist/client.js683
-rwxr-xr-xnode_modules/request/node_modules/hawk/example/usage.js156
-rwxr-xr-xnode_modules/request/node_modules/hawk/lib/browser.js1274
-rwxr-xr-xnode_modules/request/node_modules/hawk/lib/client.js738
-rwxr-xr-xnode_modules/request/node_modules/hawk/lib/crypto.js252
-rwxr-xr-xnode_modules/request/node_modules/hawk/lib/index.js30
-rwxr-xr-xnode_modules/request/node_modules/hawk/lib/server.js1088
-rwxr-xr-xnode_modules/request/node_modules/hawk/lib/utils.js348
-rw-r--r--node_modules/request/node_modules/hawk/package.json20
-rwxr-xr-xnode_modules/request/node_modules/hawk/test/browser.js2984
-rwxr-xr-xnode_modules/request/node_modules/hawk/test/client.js880
-rwxr-xr-xnode_modules/request/node_modules/hawk/test/crypto.js140
-rwxr-xr-xnode_modules/request/node_modules/hawk/test/index.js756
-rwxr-xr-xnode_modules/request/node_modules/hawk/test/readme.js190
-rwxr-xr-xnode_modules/request/node_modules/hawk/test/server.js2631
-rwxr-xr-xnode_modules/request/node_modules/hawk/test/uri.js1676
-rwxr-xr-xnode_modules/request/node_modules/hawk/test/utils.js270
-rw-r--r--node_modules/request/node_modules/http-signature/CHANGES.md7
-rw-r--r--node_modules/request/node_modules/http-signature/http_signing.md74
-rw-r--r--node_modules/request/node_modules/http-signature/lib/signer.js5
-rw-r--r--node_modules/request/node_modules/http-signature/node_modules/assert-plus/AUTHORS (renamed from node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/assert-plus/AUTHORS)0
-rw-r--r--node_modules/request/node_modules/http-signature/node_modules/assert-plus/CHANGES.md (renamed from node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/assert-plus/CHANGES.md)0
-rw-r--r--node_modules/request/node_modules/http-signature/node_modules/assert-plus/README.md71
-rw-r--r--node_modules/request/node_modules/http-signature/node_modules/assert-plus/assert.js375
-rw-r--r--node_modules/request/node_modules/http-signature/node_modules/assert-plus/package.json115
-rw-r--r--node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/assert-plus/README.md155
-rw-r--r--node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/assert-plus/assert.js206
-rw-r--r--node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/assert-plus/package.json107
-rw-r--r--node_modules/request/node_modules/http-signature/package.json24
-rw-r--r--node_modules/request/node_modules/qs/.travis.yml71
-rw-r--r--node_modules/request/node_modules/qs/CHANGELOG.md161
-rw-r--r--node_modules/request/node_modules/qs/README.md166
-rw-r--r--node_modules/request/node_modules/qs/bower.json2
-rw-r--r--node_modules/request/node_modules/qs/component.json2
-rw-r--r--node_modules/request/node_modules/qs/dist/qs.js285
-rwxr-xr-x[-rw-r--r--]node_modules/request/node_modules/qs/lib/index.js8
-rwxr-xr-x[-rw-r--r--]node_modules/request/node_modules/qs/lib/parse.js75
-rwxr-xr-x[-rw-r--r--]node_modules/request/node_modules/qs/lib/stringify.js68
-rwxr-xr-x[-rw-r--r--]node_modules/request/node_modules/qs/lib/utils.js118
-rw-r--r--node_modules/request/node_modules/qs/package.json132
-rw-r--r--node_modules/request/node_modules/qs/test/index.js5
-rwxr-xr-x[-rw-r--r--]node_modules/request/node_modules/qs/test/parse.js557
-rwxr-xr-x[-rw-r--r--]node_modules/request/node_modules/qs/test/stringify.js336
-rwxr-xr-x[-rw-r--r--]node_modules/request/node_modules/qs/test/utils.js31
-rw-r--r--node_modules/request/package.json57
-rw-r--r--node_modules/request/request.js76
73 files changed, 11933 insertions, 9582 deletions
diff --git a/node_modules/request/CHANGELOG.md b/node_modules/request/CHANGELOG.md
index 7dc85ea14..86386a9ae 100644
--- a/node_modules/request/CHANGELOG.md
+++ b/node_modules/request/CHANGELOG.md
@@ -1,5 +1,20 @@
## Change Log
+### v2.68.0 (2016/01/27)
+- [#2036](https://github.com/request/request/pull/2036) Add AWS Signature Version 4 (@simov, @mirkods)
+- [#2022](https://github.com/request/request/pull/2022) Convert numeric multipart bodies to string (@simov, @feross)
+- [#2024](https://github.com/request/request/pull/2024) Update har-validator dependency for nsp advisory #76 (@TylerDixon)
+- [#2016](https://github.com/request/request/pull/2016) Update qs to version 6.0.2 🚀 (@greenkeeperio-bot)
+- [#2007](https://github.com/request/request/pull/2007) Use the `extend` module instead of util._extend (@simov)
+- [#2003](https://github.com/request/request/pull/2003) Update browserify to version 13.0.0 🚀 (@greenkeeperio-bot)
+- [#1989](https://github.com/request/request/pull/1989) Update buffer-equal to version 1.0.0 🚀 (@greenkeeperio-bot)
+- [#1956](https://github.com/request/request/pull/1956) Check form-data content-length value before setting up the header (@jongyoonlee)
+- [#1958](https://github.com/request/request/pull/1958) Use IncomingMessage.destroy method (@simov)
+- [#1952](https://github.com/request/request/pull/1952) Adds example for Tor proxy (@prometheansacrifice)
+- [#1943](https://github.com/request/request/pull/1943) Update eslint to version 1.10.3 🚀 (@simov, @greenkeeperio-bot)
+- [#1924](https://github.com/request/request/pull/1924) Update eslint to version 1.10.1 🚀 (@greenkeeperio-bot)
+- [#1915](https://github.com/request/request/pull/1915) Remove content-length and transfer-encoding headers from defaultProxyHeaderWhiteList (@yaxia)
+
### v2.67.0 (2015/11/19)
- [#1913](https://github.com/request/request/pull/1913) Update http-signature to version 1.1.0 🚀 (@greenkeeperio-bot)
@@ -455,7 +470,7 @@
- [#521](https://github.com/request/request/pull/521) Improving test-localAddress.js (@noway421)
- [#529](https://github.com/request/request/pull/529) dependencies versions bump (@jodaka)
-### v2.17.0 (2013/04/22)
+### v2.18.0 (2013/04/22)
- [#523](https://github.com/request/request/pull/523) Updating dependencies (@noway421)
- [#520](https://github.com/request/request/pull/520) Fixing test-tunnel.js (@noway421)
- [#519](https://github.com/request/request/pull/519) Update internal path state on post-creation QS changes (@jblebrun)
diff --git a/node_modules/request/README.md b/node_modules/request/README.md
index 77e30df58..6ee45b205 100644
--- a/node_modules/request/README.md
+++ b/node_modules/request/README.md
@@ -754,7 +754,7 @@ The first argument can be either a `url` or an `options` object. The only requir
- `auth` - A hash containing values `user` || `username`, `pass` || `password`, and `sendImmediately` (optional). See documentation above.
- `oauth` - Options for OAuth HMAC-SHA1 signing. See documentation above.
- `hawk` - Options for [Hawk signing](https://github.com/hueniverse/hawk). The `credentials` key must contain the necessary signing info, [see hawk docs for details](https://github.com/hueniverse/hawk#usage-example).
-- `aws` - `object` containing AWS signing information. Should have the properties `key`, `secret`. Also requires the property `bucket`, unless you’re specifying your `bucket` as part of the path, or the request doesn’t use a bucket (i.e. GET Services)
+- `aws` - `object` containing AWS signing information. Should have the properties `key`, `secret`. Also requires the property `bucket`, unless you’re specifying your `bucket` as part of the path, or the request doesn’t use a bucket (i.e. GET Services). If you want to use AWS sign version 4 use the parameter `sign_version` with value `4` otherwise the default is version 2. **Note:** you need to `npm install aws4` first.
- `httpSignature` - Options for the [HTTP Signature Scheme](https://github.com/joyent/node-http-signature/blob/master/http_signing.md) using [Joyent's library](https://github.com/joyent/node-http-signature). The `keyId` and `key` properties must be specified. See the docs for other options.
---
diff --git a/node_modules/request/lib/har.js b/node_modules/request/lib/har.js
index ceb1cd107..305957487 100644
--- a/node_modules/request/lib/har.js
+++ b/node_modules/request/lib/har.js
@@ -3,7 +3,7 @@
var fs = require('fs')
var qs = require('querystring')
var validate = require('har-validator')
-var util = require('util')
+var extend = require('extend')
function Har (request) {
this.request = request
@@ -118,7 +118,8 @@ Har.prototype.options = function (options) {
return options
}
- var har = util._extend({}, options.har)
+ var har = {}
+ extend(har, options.har)
// only process the first entry
if (har.log && har.log.entries) {
diff --git a/node_modules/request/lib/multipart.js b/node_modules/request/lib/multipart.js
index 03618588c..c12817261 100644
--- a/node_modules/request/lib/multipart.js
+++ b/node_modules/request/lib/multipart.js
@@ -68,6 +68,9 @@ Multipart.prototype.build = function (parts, chunked) {
var body = chunked ? new CombinedStream() : []
function add (part) {
+ if (typeof part === 'number') {
+ part = part.toString()
+ }
return chunked ? body.append(part) : body.push(new Buffer(part))
}
diff --git a/node_modules/request/lib/tunnel.js b/node_modules/request/lib/tunnel.js
index 918aec69a..bf96a8fec 100644
--- a/node_modules/request/lib/tunnel.js
+++ b/node_modules/request/lib/tunnel.js
@@ -12,7 +12,6 @@ var defaultProxyHeaderWhiteList = [
'cache-control',
'content-encoding',
'content-language',
- 'content-length',
'content-location',
'content-md5',
'content-range',
@@ -24,7 +23,6 @@ var defaultProxyHeaderWhiteList = [
'pragma',
'referer',
'te',
- 'transfer-encoding',
'user-agent',
'via'
]
diff --git a/node_modules/request/node_modules/aws4/.npmignore b/node_modules/request/node_modules/aws4/.npmignore
new file mode 100644
index 000000000..ccafa6b41
--- /dev/null
+++ b/node_modules/request/node_modules/aws4/.npmignore
@@ -0,0 +1,3 @@
+test
+coverage
+examples
diff --git a/node_modules/request/node_modules/aws4/.tern-port b/node_modules/request/node_modules/aws4/.tern-port
new file mode 100644
index 000000000..7fd1b5223
--- /dev/null
+++ b/node_modules/request/node_modules/aws4/.tern-port
@@ -0,0 +1 @@
+62638 \ No newline at end of file
diff --git a/node_modules/request/node_modules/aws4/.travis.yml b/node_modules/request/node_modules/aws4/.travis.yml
new file mode 100644
index 000000000..61d063404
--- /dev/null
+++ b/node_modules/request/node_modules/aws4/.travis.yml
@@ -0,0 +1,5 @@
+language: node_js
+node_js:
+ - "0.10"
+ - "0.12"
+ - "4.2"
diff --git a/node_modules/request/node_modules/aws4/LICENSE b/node_modules/request/node_modules/aws4/LICENSE
new file mode 100644
index 000000000..4f321e599
--- /dev/null
+++ b/node_modules/request/node_modules/aws4/LICENSE
@@ -0,0 +1,19 @@
+Copyright 2013 Michael Hart (michael.hart.au@gmail.com)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/node_modules/request/node_modules/aws4/README.md b/node_modules/request/node_modules/aws4/README.md
new file mode 100644
index 000000000..18a3a5376
--- /dev/null
+++ b/node_modules/request/node_modules/aws4/README.md
@@ -0,0 +1,510 @@
+aws4
+----
+
+[![Build Status](https://secure.travis-ci.org/mhart/aws4.png?branch=master)](http://travis-ci.org/mhart/aws4)
+
+A small utility to sign vanilla node.js http(s) request options using Amazon's
+[AWS Signature Version 4](http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html).
+
+This signature is supported by nearly all Amazon services, including
+[S3](http://docs.aws.amazon.com/AmazonS3/latest/API/),
+[EC2](http://docs.aws.amazon.com/AWSEC2/latest/APIReference/),
+[DynamoDB](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/API.html),
+[Kinesis](http://docs.aws.amazon.com/kinesis/latest/APIReference/),
+[Lambda](http://docs.aws.amazon.com/lambda/latest/dg/API_Reference.html),
+[SQS](http://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/),
+[SNS](http://docs.aws.amazon.com/sns/latest/api/),
+[IAM](http://docs.aws.amazon.com/IAM/latest/APIReference/),
+[STS](http://docs.aws.amazon.com/STS/latest/APIReference/),
+[RDS](http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/),
+[CloudWatch](http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/),
+[CloudWatch Logs](http://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/),
+[CodeDeploy](http://docs.aws.amazon.com/codedeploy/latest/APIReference/),
+[CloudFront](http://docs.aws.amazon.com/AmazonCloudFront/latest/APIReference/),
+[CloudTrail](http://docs.aws.amazon.com/awscloudtrail/latest/APIReference/),
+[ElastiCache](http://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/),
+[EMR](http://docs.aws.amazon.com/ElasticMapReduce/latest/API/),
+[Glacier](http://docs.aws.amazon.com/amazonglacier/latest/dev/amazon-glacier-api.html),
+[CloudSearch](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/APIReq.html),
+[Elastic Load Balancing](http://docs.aws.amazon.com/ElasticLoadBalancing/latest/APIReference/),
+[Elastic Transcoder](http://docs.aws.amazon.com/elastictranscoder/latest/developerguide/api-reference.html),
+[CloudFormation](http://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/),
+[Elastic Beanstalk](http://docs.aws.amazon.com/elasticbeanstalk/latest/api/),
+[Storage Gateway](http://docs.aws.amazon.com/storagegateway/latest/userguide/AWSStorageGatewayAPI.html),
+[Data Pipeline](http://docs.aws.amazon.com/datapipeline/latest/APIReference/),
+[Direct Connect](http://docs.aws.amazon.com/directconnect/latest/APIReference/),
+[Redshift](http://docs.aws.amazon.com/redshift/latest/APIReference/),
+[OpsWorks](http://docs.aws.amazon.com/opsworks/latest/APIReference/),
+[SES](http://docs.aws.amazon.com/ses/latest/APIReference/),
+[SWF](http://docs.aws.amazon.com/amazonswf/latest/apireference/),
+[AutoScaling](http://docs.aws.amazon.com/AutoScaling/latest/APIReference/),
+[Mobile Analytics](http://docs.aws.amazon.com/mobileanalytics/latest/ug/server-reference.html),
+[Cognito Identity](http://docs.aws.amazon.com/cognitoidentity/latest/APIReference/),
+[Cognito Sync](http://docs.aws.amazon.com/cognitosync/latest/APIReference/),
+[Container Service](http://docs.aws.amazon.com/AmazonECS/latest/APIReference/),
+[AppStream](http://docs.aws.amazon.com/appstream/latest/developerguide/appstream-api-rest.html),
+[Key Management Service](http://docs.aws.amazon.com/kms/latest/APIReference/),
+[Config](http://docs.aws.amazon.com/config/latest/APIReference/),
+[CloudHSM](http://docs.aws.amazon.com/cloudhsm/latest/dg/api-ref.html),
+[Route53](http://docs.aws.amazon.com/Route53/latest/APIReference/requests-rest.html) and
+[Route53 Domains](http://docs.aws.amazon.com/Route53/latest/APIReference/requests-rpc.html).
+
+Indeed, the only AWS services that *don't* support v4 as of 2014-12-30 are
+[Import/Export](http://docs.aws.amazon.com/AWSImportExport/latest/DG/api-reference.html) and
+[SimpleDB](http://docs.aws.amazon.com/AmazonSimpleDB/latest/DeveloperGuide/SDB_API.html)
+(they only support [AWS Signature Version 2](https://github.com/mhart/aws2)).
+
+It also provides defaults for a number of core AWS headers and
+request parameters, making it very easy to query AWS services, or
+build out a fully-featured AWS library.
+
+Example
+-------
+
+```javascript
+var http = require('http'),
+ https = require('https'),
+ aws4 = require('aws4')
+
+// given an options object you could pass to http.request
+var opts = {host: 'sqs.us-east-1.amazonaws.com', path: '/?Action=ListQueues'}
+
+// alternatively (as aws4 can infer the host):
+opts = {service: 'sqs', region: 'us-east-1', path: '/?Action=ListQueues'}
+
+// alternatively (as us-east-1 is default):
+opts = {service: 'sqs', path: '/?Action=ListQueues'}
+
+aws4.sign(opts) // assumes AWS credentials are available in process.env
+
+console.log(opts)
+/*
+{
+ host: 'sqs.us-east-1.amazonaws.com',
+ path: '/?Action=ListQueues',
+ headers: {
+ Host: 'sqs.us-east-1.amazonaws.com',
+ 'X-Amz-Date': '20121226T061030Z',
+ Authorization: 'AWS4-HMAC-SHA256 Credential=ABCDEF/20121226/us-east-1/sqs/aws4_request, ...'
+ }
+}
+*/
+
+// we can now use this to query AWS using the standard node.js http API
+http.request(opts, function(res) { res.pipe(process.stdout) }).end()
+/*
+<?xml version="1.0"?>
+<ListQueuesResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/">
+...
+*/
+```
+
+More options
+------------
+
+```javascript
+// you can also pass AWS credentials in explicitly (otherwise taken from process.env)
+aws4.sign(opts, {accessKeyId: '', secretAccessKey: ''})
+
+// can also add the signature to query strings
+aws4.sign({service: 's3', path: '/my-bucket?X-Amz-Expires=12345', signQuery: true})
+
+// create a utility function to pipe to stdout (with https this time)
+function request(o) { https.request(o, function(res) { res.pipe(process.stdout) }).end(o.body || '') }
+
+// aws4 can infer the HTTP method if a body is passed in
+// method will be POST and Content-Type: 'application/x-www-form-urlencoded; charset=utf-8'
+request(aws4.sign({service: 'iam', body: 'Action=ListGroups&Version=2010-05-08'}))
+/*
+<ListGroupsResponse xmlns="https://iam.amazonaws.com/doc/2010-05-08/">
+...
+*/
+
+// can specify any custom option or header as per usual
+request(aws4.sign({
+ service: 'dynamodb',
+ region: 'ap-southeast-2',
+ method: 'POST',
+ path: '/',
+ headers: {
+ 'Content-Type': 'application/x-amz-json-1.0',
+ 'X-Amz-Target': 'DynamoDB_20120810.ListTables'
+ },
+ body: '{}'
+}))
+/*
+{"TableNames":[]}
+...
+*/
+
+// works with all other services that support Signature Version 4
+
+request(aws4.sign({service: 's3', path: '/', signQuery: true}))
+/*
+<ListAllMyBucketsResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
+...
+*/
+
+request(aws4.sign({service: 'ec2', path: '/?Action=DescribeRegions&Version=2014-06-15'}))
+/*
+<DescribeRegionsResponse xmlns="http://ec2.amazonaws.com/doc/2014-06-15/">
+...
+*/
+
+request(aws4.sign({service: 'sns', path: '/?Action=ListTopics&Version=2010-03-31'}))
+/*
+<ListTopicsResponse xmlns="http://sns.amazonaws.com/doc/2010-03-31/">
+...
+*/
+
+request(aws4.sign({service: 'sts', path: '/?Action=GetSessionToken&Version=2011-06-15'}))
+/*
+<GetSessionTokenResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/">
+...
+*/
+
+request(aws4.sign({service: 'cloudsearch', path: '/?Action=ListDomainNames&Version=2013-01-01'}))
+/*
+<ListDomainNamesResponse xmlns="http://cloudsearch.amazonaws.com/doc/2013-01-01/">
+...
+*/
+
+request(aws4.sign({service: 'ses', path: '/?Action=ListIdentities&Version=2010-12-01'}))
+/*
+<ListIdentitiesResponse xmlns="http://ses.amazonaws.com/doc/2010-12-01/">
+...
+*/
+
+request(aws4.sign({service: 'autoscaling', path: '/?Action=DescribeAutoScalingInstances&Version=2011-01-01'}))
+/*
+<DescribeAutoScalingInstancesResponse xmlns="http://autoscaling.amazonaws.com/doc/2011-01-01/">
+...
+*/
+
+request(aws4.sign({service: 'elasticloadbalancing', path: '/?Action=DescribeLoadBalancers&Version=2012-06-01'}))
+/*
+<DescribeLoadBalancersResponse xmlns="http://elasticloadbalancing.amazonaws.com/doc/2012-06-01/">
+...
+*/
+
+request(aws4.sign({service: 'cloudformation', path: '/?Action=ListStacks&Version=2010-05-15'}))
+/*
+<ListStacksResponse xmlns="http://cloudformation.amazonaws.com/doc/2010-05-15/">
+...
+*/
+
+request(aws4.sign({service: 'elasticbeanstalk', path: '/?Action=ListAvailableSolutionStacks&Version=2010-12-01'}))
+/*
+<ListAvailableSolutionStacksResponse xmlns="http://elasticbeanstalk.amazonaws.com/docs/2010-12-01/">
+...
+*/
+
+request(aws4.sign({service: 'rds', path: '/?Action=DescribeDBInstances&Version=2012-09-17'}))
+/*
+<DescribeDBInstancesResponse xmlns="http://rds.amazonaws.com/doc/2012-09-17/">
+...
+*/
+
+request(aws4.sign({service: 'monitoring', path: '/?Action=ListMetrics&Version=2010-08-01'}))
+/*
+<ListMetricsResponse xmlns="http://monitoring.amazonaws.com/doc/2010-08-01/">
+...
+*/
+
+request(aws4.sign({service: 'redshift', path: '/?Action=DescribeClusters&Version=2012-12-01'}))
+/*
+<DescribeClustersResponse xmlns="http://redshift.amazonaws.com/doc/2012-12-01/">
+...
+*/
+
+request(aws4.sign({service: 'cloudfront', path: '/2014-05-31/distribution'}))
+/*
+<DistributionList xmlns="http://cloudfront.amazonaws.com/doc/2014-05-31/">
+...
+*/
+
+request(aws4.sign({service: 'elasticache', path: '/?Action=DescribeCacheClusters&Version=2014-07-15'}))
+/*
+<DescribeCacheClustersResponse xmlns="http://elasticache.amazonaws.com/doc/2014-07-15/">
+...
+*/
+
+request(aws4.sign({service: 'elasticmapreduce', path: '/?Action=DescribeJobFlows&Version=2009-03-31'}))
+/*
+<DescribeJobFlowsResponse xmlns="http://elasticmapreduce.amazonaws.com/doc/2009-03-31">
+...
+*/
+
+request(aws4.sign({service: 'route53', path: '/2013-04-01/hostedzone'}))
+/*
+<ListHostedZonesResponse xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
+...
+*/
+
+request(aws4.sign({service: 'appstream', path: '/applications'}))
+/*
+{"_links":{"curie":[{"href":"http://docs.aws.amazon.com/appstream/latest/...
+...
+*/
+
+request(aws4.sign({service: 'cognito-sync', path: '/identitypools'}))
+/*
+{"Count":0,"IdentityPoolUsages":[],"MaxResults":16,"NextToken":null}
+...
+*/
+
+request(aws4.sign({service: 'elastictranscoder', path: '/2012-09-25/pipelines'}))
+/*
+{"NextPageToken":null,"Pipelines":[]}
+...
+*/
+
+request(aws4.sign({service: 'lambda', path: '/2014-11-13/functions/'}))
+/*
+{"Functions":[],"NextMarker":null}
+...
+*/
+
+request(aws4.sign({service: 'ecs', path: '/?Action=ListClusters&Version=2014-11-13'}))
+/*
+<ListClustersResponse xmlns="http://ecs.amazonaws.com/doc/2014-11-13/">
+...
+*/
+
+request(aws4.sign({service: 'glacier', path: '/-/vaults', headers: {'X-Amz-Glacier-Version': '2012-06-01'}}))
+/*
+{"Marker":null,"VaultList":[]}
+...
+*/
+
+request(aws4.sign({service: 'storagegateway', body: '{}', headers: {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'StorageGateway_20120630.ListGateways'
+}}))
+/*
+{"Gateways":[]}
+...
+*/
+
+request(aws4.sign({service: 'datapipeline', body: '{}', headers: {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'DataPipeline.ListPipelines'
+}}))
+/*
+{"hasMoreResults":false,"pipelineIdList":[]}
+...
+*/
+
+request(aws4.sign({service: 'opsworks', body: '{}', headers: {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'OpsWorks_20130218.DescribeStacks'
+}}))
+/*
+{"Stacks":[]}
+...
+*/
+
+request(aws4.sign({service: 'route53domains', body: '{}', headers: {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'Route53Domains_v20140515.ListDomains'
+}}))
+/*
+{"Domains":[]}
+...
+*/
+
+request(aws4.sign({service: 'kinesis', body: '{}', headers: {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'Kinesis_20131202.ListStreams'
+}}))
+/*
+{"HasMoreStreams":false,"StreamNames":[]}
+...
+*/
+
+request(aws4.sign({service: 'cloudtrail', body: '{}', headers: {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'CloudTrail_20131101.DescribeTrails'
+}}))
+/*
+{"trailList":[]}
+...
+*/
+
+request(aws4.sign({service: 'logs', body: '{}', headers: {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'Logs_20140328.DescribeLogGroups'
+}}))
+/*
+{"logGroups":[]}
+...
+*/
+
+request(aws4.sign({service: 'codedeploy', body: '{}', headers: {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'CodeDeploy_20141006.ListApplications'
+}}))
+/*
+{"applications":[]}
+...
+*/
+
+request(aws4.sign({service: 'directconnect', body: '{}', headers: {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'OvertureService.DescribeConnections'
+}}))
+/*
+{"connections":[]}
+...
+*/
+
+request(aws4.sign({service: 'kms', body: '{}', headers: {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'TrentService.ListKeys'
+}}))
+/*
+{"Keys":[],"Truncated":false}
+...
+*/
+
+request(aws4.sign({service: 'config', body: '{}', headers: {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'StarlingDoveService.DescribeDeliveryChannels'
+}}))
+/*
+{"DeliveryChannels":[]}
+...
+*/
+
+request(aws4.sign({service: 'cloudhsm', body: '{}', headers: {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'CloudHsmFrontendService.ListAvailableZones'
+}}))
+/*
+{"AZList":["us-east-1a","us-east-1b","us-east-1c"]}
+...
+*/
+
+request(aws4.sign({
+ service: 'swf',
+ body: '{"registrationStatus":"REGISTERED"}',
+ headers: {
+ 'Content-Type': 'application/x-amz-json-1.0',
+ 'X-Amz-Target': 'SimpleWorkflowService.ListDomains'
+ }
+}))
+/*
+{"domainInfos":[]}
+...
+*/
+
+request(aws4.sign({
+ service: 'cognito-identity',
+ body: '{"MaxResults": 1}',
+ headers: {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'AWSCognitoIdentityService.ListIdentityPools'
+ }
+}))
+/*
+{"IdentityPools":[]}
+...
+*/
+
+request(aws4.sign({
+ service: 'mobileanalytics',
+ path: '/2014-06-05/events',
+ body: JSON.stringify({events:[{
+ eventType: 'a',
+ timestamp: new Date().toISOString(),
+ session: {},
+ }]}),
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-Amz-Client-Context': JSON.stringify({
+ client: {client_id: 'a', app_title: 'a'},
+ custom: {},
+ env: {platform: 'a'},
+ services: {},
+ }),
+ }
+}))
+/*
+(HTTP 202, empty response)
+*/
+```
+
+API
+---
+
+### aws4.sign(requestOptions, [credentials])
+
+This calculates and populates the `Authorization` header of
+`requestOptions`, and any other necessary AWS headers and/or request
+options. Returns `requestOptions` as a convenience for chaining.
+
+`requestOptions` is an object holding the same options that the node.js
+[http.request](http://nodejs.org/docs/latest/api/http.html#http_http_request_options_callback)
+function takes.
+
+The following properties of `requestOptions` are used in the signing or
+populated if they don't already exist:
+
+- `hostname` or `host` (will be determined from `service` and `region` if not given)
+- `method` (will use `'GET'` if not given or `'POST'` if there is a `body`)
+- `path` (will use `'/'` if not given)
+- `body` (will use `''` if not given)
+- `service` (will be calculated from `hostname` or `host` if not given)
+- `region` (will be calculated from `hostname` or `host` or use `'us-east-1'` if not given)
+- `headers['Host']` (will use `hostname` or `host` or be calculated if not given)
+- `headers['Content-Type']` (will use `'application/x-www-form-urlencoded; charset=utf-8'`
+ if not given and there is a `body`)
+- `headers['Date']` (used to calculate the signature date if given, otherwise `new Date` is used)
+
+Your AWS credentials (which can be found in your
+[AWS console](https://portal.aws.amazon.com/gp/aws/securityCredentials))
+can be specified in one of two ways:
+
+- As the second argument, like this:
+
+```javascript
+aws4.sign(requestOptions, {
+ secretAccessKey: "<your-secret-access-key>",
+ accessKeyId: "<your-access-key-id>",
+ sessionToken: "<your-session-token>"
+})
+```
+
+- From `process.env`, such as this:
+
+```
+export AWS_SECRET_ACCESS_KEY="<your-secret-access-key>"
+export AWS_ACCESS_KEY_ID="<your-access-key-id>"
+export AWS_SESSION_TOKEN="<your-session-token>"
+```
+
+(will also use `AWS_ACCESS_KEY` and `AWS_SECRET_KEY` if available)
+
+The `sessionToken` property and `AWS_SESSION_TOKEN` environment variable are optional for signing
+with [IAM STS temporary credentials](http://docs.aws.amazon.com/STS/latest/UsingSTS/using-temp-creds.html).
+
+Installation
+------------
+
+With [npm](http://npmjs.org/) do:
+
+```
+npm install aws4
+```
+
+Thanks
+------
+
+Thanks to [@jed](https://github.com/jed) for his
+[dynamo-client](https://github.com/jed/dynamo-client) lib where I first
+committed and subsequently extracted this code.
+
+Also thanks to the
+[official node.js AWS SDK](https://github.com/aws/aws-sdk-js) for giving
+me a start on implementing the v4 signature.
+
diff --git a/node_modules/request/node_modules/aws4/aws4.js b/node_modules/request/node_modules/aws4/aws4.js
new file mode 100644
index 000000000..3ef54a468
--- /dev/null
+++ b/node_modules/request/node_modules/aws4/aws4.js
@@ -0,0 +1,313 @@
+var aws4 = exports,
+ url = require('url'),
+ querystring = require('querystring'),
+ crypto = require('crypto'),
+ lru = require('lru-cache'),
+ credentialsCache = lru(1000)
+
+// http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html
+
+function hmac(key, string, encoding) {
+ return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding)
+}
+
+function hash(string, encoding) {
+ return crypto.createHash('sha256').update(string, 'utf8').digest(encoding)
+}
+
+// This function assumes the string has already been percent encoded
+function encodeRfc3986(urlEncodedString) {
+ return urlEncodedString.replace(/[!'()*]/g, function(c) {
+ return '%' + c.charCodeAt(0).toString(16).toUpperCase()
+ })
+}
+
+// request: { path | body, [host], [method], [headers], [service], [region] }
+// credentials: { accessKeyId, secretAccessKey, [sessionToken] }
+function RequestSigner(request, credentials) {
+
+ if (typeof request === 'string') request = url.parse(request)
+
+ var headers = request.headers = (request.headers || {}),
+ hostParts = this.matchHost(request.hostname || request.host || headers.Host || headers.host)
+
+ this.request = request
+ this.credentials = credentials || this.defaultCredentials()
+
+ this.service = request.service || hostParts[0] || ''
+ this.region = request.region || hostParts[1] || 'us-east-1'
+
+ // SES uses a different domain from the service name
+ if (this.service === 'email') this.service = 'ses'
+
+ if (!request.method && request.body)
+ request.method = 'POST'
+
+ if (!headers.Host && !headers.host)
+ headers.Host = request.hostname || request.host || this.createHost()
+ if (!request.hostname && !request.host)
+ request.hostname = headers.Host || headers.host
+}
+
+RequestSigner.prototype.matchHost = function(host) {
+ var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com$/)
+ var hostParts = (match || []).slice(1, 3)
+
+ // ES's hostParts are sometimes the other way round, if the value that is expected
+ // to be region equals ‘es’ switch them back
+ // e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com
+ if (hostParts[1] === 'es')
+ hostParts = hostParts.reverse()
+
+ return hostParts
+}
+
+// http://docs.aws.amazon.com/general/latest/gr/rande.html
+RequestSigner.prototype.isSingleRegion = function() {
+ // Special case for S3 and SimpleDB in us-east-1
+ if (['s3', 'sdb'].indexOf(this.service) >= 0 && this.region === 'us-east-1') return true
+
+ return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts']
+ .indexOf(this.service) >= 0
+}
+
+RequestSigner.prototype.createHost = function() {
+ var region = this.isSingleRegion() ? '' :
+ (this.service === 's3' && this.region !== 'us-east-1' ? '-' : '.') + this.region,
+ service = this.service === 'ses' ? 'email' : this.service
+ return service + region + '.amazonaws.com'
+}
+
+RequestSigner.prototype.prepareRequest = function() {
+ this.parsePath()
+
+ var request = this.request, headers = request.headers, query
+
+ if (request.signQuery) {
+
+ this.parsedPath.query = query = this.parsedPath.query || {}
+
+ if (this.credentials.sessionToken)
+ query['X-Amz-Security-Token'] = this.credentials.sessionToken
+
+ if (this.service === 's3' && !query['X-Amz-Expires'])
+ query['X-Amz-Expires'] = 86400
+
+ if (query['X-Amz-Date'])
+ this.datetime = query['X-Amz-Date']
+ else
+ query['X-Amz-Date'] = this.getDateTime()
+
+ query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256'
+ query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString()
+ query['X-Amz-SignedHeaders'] = this.signedHeaders()
+
+ } else {
+
+ if (!request.doNotModifyHeaders) {
+ if (request.body && !headers['Content-Type'] && !headers['content-type'])
+ headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'
+
+ if (request.body && !headers['Content-Length'] && !headers['content-length'])
+ headers['Content-Length'] = Buffer.byteLength(request.body)
+
+ if (this.credentials.sessionToken)
+ headers['X-Amz-Security-Token'] = this.credentials.sessionToken
+
+ if (this.service === 's3')
+ headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex')
+
+ if (headers['X-Amz-Date'])
+ this.datetime = headers['X-Amz-Date']
+ else
+ headers['X-Amz-Date'] = this.getDateTime()
+ }
+
+ delete headers.Authorization
+ delete headers.authorization
+ }
+}
+
+RequestSigner.prototype.sign = function() {
+ if (!this.parsedPath) this.prepareRequest()
+
+ if (this.request.signQuery) {
+ this.parsedPath.query['X-Amz-Signature'] = this.signature()
+ } else {
+ this.request.headers.Authorization = this.authHeader()
+ }
+
+ this.request.path = this.formatPath()
+
+ return this.request
+}
+
+RequestSigner.prototype.getDateTime = function() {
+ if (!this.datetime) {
+ var headers = this.request.headers,
+ date = new Date(headers.Date || headers.date || new Date)
+
+ this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, '')
+ }
+ return this.datetime
+}
+
+RequestSigner.prototype.getDate = function() {
+ return this.getDateTime().substr(0, 8)
+}
+
+RequestSigner.prototype.authHeader = function() {
+ return [
+ 'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(),
+ 'SignedHeaders=' + this.signedHeaders(),
+ 'Signature=' + this.signature(),
+ ].join(', ')
+}
+
+RequestSigner.prototype.signature = function() {
+ var date = this.getDate(),
+ cacheKey = [this.credentials.secretAccessKey, date, this.region, this.service].join(),
+ kDate, kRegion, kService, kCredentials = credentialsCache.get(cacheKey)
+ if (!kCredentials) {
+ kDate = hmac('AWS4' + this.credentials.secretAccessKey, date)
+ kRegion = hmac(kDate, this.region)
+ kService = hmac(kRegion, this.service)
+ kCredentials = hmac(kService, 'aws4_request')
+ credentialsCache.set(cacheKey, kCredentials)
+ }
+ return hmac(kCredentials, this.stringToSign(), 'hex')
+}
+
+RequestSigner.prototype.stringToSign = function() {
+ return [
+ 'AWS4-HMAC-SHA256',
+ this.getDateTime(),
+ this.credentialString(),
+ hash(this.canonicalString(), 'hex'),
+ ].join('\n')
+}
+
+RequestSigner.prototype.canonicalString = function() {
+ if (!this.parsedPath) this.prepareRequest()
+
+ var pathStr = this.parsedPath.path,
+ query = this.parsedPath.query,
+ queryStr = '',
+ normalizePath = this.service !== 's3',
+ decodePath = this.service === 's3' || this.request.doNotEncodePath,
+ decodeSlashesInPath = this.service === 's3',
+ firstValOnly = this.service === 's3',
+ bodyHash = this.service === 's3' && this.request.signQuery ?
+ 'UNSIGNED-PAYLOAD' : hash(this.request.body || '', 'hex')
+
+ if (query) {
+ queryStr = encodeRfc3986(querystring.stringify(Object.keys(query).sort().reduce(function(obj, key) {
+ if (!key) return obj
+ obj[key] = !Array.isArray(query[key]) ? query[key] :
+ (firstValOnly ? query[key][0] : query[key].slice().sort())
+ return obj
+ }, {})))
+ }
+ if (pathStr !== '/') {
+ if (normalizePath) pathStr = pathStr.replace(/\/{2,}/g, '/')
+ if (pathStr[0] === '/') pathStr = pathStr.slice(1)
+ pathStr = '/' + pathStr.split('/').reduce(function(path, piece) {
+ if (normalizePath && piece === '..') {
+ path.pop()
+ } else if (!normalizePath || piece !== '.') {
+ if (decodePath) piece = querystring.unescape(piece)
+ path.push(encodeRfc3986(querystring.escape(piece)))
+ }
+ return path
+ }, []).join('/')
+ if (decodeSlashesInPath) pathStr = pathStr.replace(/%2F/g, '/')
+ }
+
+ return [
+ this.request.method || 'GET',
+ pathStr,
+ queryStr,
+ this.canonicalHeaders() + '\n',
+ this.signedHeaders(),
+ bodyHash,
+ ].join('\n')
+}
+
+RequestSigner.prototype.canonicalHeaders = function() {
+ var headers = this.request.headers
+ function trimAll(header) {
+ return header.toString().trim().replace(/\s+/g, ' ')
+ }
+ return Object.keys(headers)
+ .sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1 })
+ .map(function(key) { return key.toLowerCase() + ':' + trimAll(headers[key]) })
+ .join('\n')
+}
+
+RequestSigner.prototype.signedHeaders = function() {
+ return Object.keys(this.request.headers)
+ .map(function(key) { return key.toLowerCase() })
+ .sort()
+ .join(';')
+}
+
+RequestSigner.prototype.credentialString = function() {
+ return [
+ this.getDate(),
+ this.region,
+ this.service,
+ 'aws4_request',
+ ].join('/')
+}
+
+RequestSigner.prototype.defaultCredentials = function() {
+ var env = process.env
+ return {
+ accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY,
+ secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY,
+ sessionToken: env.AWS_SESSION_TOKEN,
+ }
+}
+
+RequestSigner.prototype.parsePath = function() {
+ var path = this.request.path || '/',
+ queryIx = path.indexOf('?'),
+ query = null
+
+ if (queryIx >= 0) {
+ query = querystring.parse(path.slice(queryIx + 1))
+ path = path.slice(0, queryIx)
+ }
+
+ // S3 doesn't always encode characters > 127 correctly and
+ // all services don't encode characters > 255 correctly
+ // So if there are non-reserved chars (and it's not already all % encoded), just encode them all
+ if (/[^0-9A-Za-z!'()*\-._~%/]/.test(path)) {
+ path = path.split('/').map(function(piece) {
+ return querystring.escape(querystring.unescape(piece))
+ }).join('/')
+ }
+
+ this.parsedPath = {
+ path: path,
+ query: query,
+ }
+}
+
+RequestSigner.prototype.formatPath = function() {
+ var path = this.parsedPath.path,
+ query = this.parsedPath.query
+
+ if (!query) return path
+
+ // Services don't support empty query string keys
+ if (query[''] != null) delete query['']
+
+ return path + '?' + encodeRfc3986(querystring.stringify(query))
+}
+
+aws4.RequestSigner = RequestSigner
+
+aws4.sign = function(request, credentials) {
+ return new RequestSigner(request, credentials).sign()
+}
diff --git a/node_modules/request/node_modules/aws4/example.js b/node_modules/request/node_modules/aws4/example.js
new file mode 100644
index 000000000..6c1a95a0b
--- /dev/null
+++ b/node_modules/request/node_modules/aws4/example.js
@@ -0,0 +1,372 @@
+var http = require('http'),
+ https = require('https'),
+ aws4 = require('aws4')
+
+// given an options object you could pass to http.request
+var opts = {host: 'sqs.us-east-1.amazonaws.com', path: '/?Action=ListQueues'}
+
+// alternatively (as aws4 can infer the host):
+opts = {service: 'sqs', region: 'us-east-1', path: '/?Action=ListQueues'}
+
+// alternatively (as us-east-1 is default):
+opts = {service: 'sqs', path: '/?Action=ListQueues'}
+
+aws4.sign(opts) // assumes AWS credentials are available in process.env
+
+console.log(opts)
+/*
+{
+ host: 'sqs.us-east-1.amazonaws.com',
+ path: '/?Action=ListQueues',
+ headers: {
+ Host: 'sqs.us-east-1.amazonaws.com',
+ 'X-Amz-Date': '20121226T061030Z',
+ Authorization: 'AWS4-HMAC-SHA256 Credential=ABCDEF/20121226/us-east-1/sqs/aws4_request, ...'
+ }
+}
+*/
+
+// we can now use this to query AWS using the standard node.js http API
+http.request(opts, function(res) { res.pipe(process.stdout) }).end()
+/*
+<?xml version="1.0"?>
+<ListQueuesResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/">
+...
+*/
+
+// you can also pass AWS credentials in explicitly (otherwise taken from process.env)
+aws4.sign(opts, {accessKeyId: '', secretAccessKey: ''})
+
+// can also add the signature to query strings
+aws4.sign({service: 's3', path: '/my-bucket?X-Amz-Expires=12345', signQuery: true})
+
+// create a utility function to pipe to stdout (with https this time)
+function request(o) { https.request(o, function(res) { res.pipe(process.stdout) }).end(o.body || '') }
+
+// aws4 can infer the HTTP method if a body is passed in
+// method will be POST and Content-Type: 'application/x-www-form-urlencoded; charset=utf-8'
+request(aws4.sign({service: 'iam', body: 'Action=ListGroups&Version=2010-05-08'}))
+/*
+<ListGroupsResponse xmlns="https://iam.amazonaws.com/doc/2010-05-08/">
+...
+*/
+
+// can specify any custom option or header as per usual
+request(aws4.sign({
+ service: 'dynamodb',
+ region: 'ap-southeast-2',
+ method: 'POST',
+ path: '/',
+ headers: {
+ 'Content-Type': 'application/x-amz-json-1.0',
+ 'X-Amz-Target': 'DynamoDB_20120810.ListTables'
+ },
+ body: '{}'
+}))
+/*
+{"TableNames":[]}
+...
+*/
+
+// works with all other services that support Signature Version 4
+
+request(aws4.sign({service: 's3', path: '/', signQuery: true}))
+/*
+<ListAllMyBucketsResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
+...
+*/
+
+request(aws4.sign({service: 'ec2', path: '/?Action=DescribeRegions&Version=2014-06-15'}))
+/*
+<DescribeRegionsResponse xmlns="http://ec2.amazonaws.com/doc/2014-06-15/">
+...
+*/
+
+request(aws4.sign({service: 'sns', path: '/?Action=ListTopics&Version=2010-03-31'}))
+/*
+<ListTopicsResponse xmlns="http://sns.amazonaws.com/doc/2010-03-31/">
+...
+*/
+
+request(aws4.sign({service: 'sts', path: '/?Action=GetSessionToken&Version=2011-06-15'}))
+/*
+<GetSessionTokenResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/">
+...
+*/
+
+request(aws4.sign({service: 'cloudsearch', path: '/?Action=ListDomainNames&Version=2013-01-01'}))
+/*
+<ListDomainNamesResponse xmlns="http://cloudsearch.amazonaws.com/doc/2013-01-01/">
+...
+*/
+
+request(aws4.sign({service: 'ses', path: '/?Action=ListIdentities&Version=2010-12-01'}))
+/*
+<ListIdentitiesResponse xmlns="http://ses.amazonaws.com/doc/2010-12-01/">
+...
+*/
+
+request(aws4.sign({service: 'autoscaling', path: '/?Action=DescribeAutoScalingInstances&Version=2011-01-01'}))
+/*
+<DescribeAutoScalingInstancesResponse xmlns="http://autoscaling.amazonaws.com/doc/2011-01-01/">
+...
+*/
+
+request(aws4.sign({service: 'elasticloadbalancing', path: '/?Action=DescribeLoadBalancers&Version=2012-06-01'}))
+/*
+<DescribeLoadBalancersResponse xmlns="http://elasticloadbalancing.amazonaws.com/doc/2012-06-01/">
+...
+*/
+
+request(aws4.sign({service: 'cloudformation', path: '/?Action=ListStacks&Version=2010-05-15'}))
+/*
+<ListStacksResponse xmlns="http://cloudformation.amazonaws.com/doc/2010-05-15/">
+...
+*/
+
+request(aws4.sign({service: 'elasticbeanstalk', path: '/?Action=ListAvailableSolutionStacks&Version=2010-12-01'}))
+/*
+<ListAvailableSolutionStacksResponse xmlns="http://elasticbeanstalk.amazonaws.com/docs/2010-12-01/">
+...
+*/
+
+request(aws4.sign({service: 'rds', path: '/?Action=DescribeDBInstances&Version=2012-09-17'}))
+/*
+<DescribeDBInstancesResponse xmlns="http://rds.amazonaws.com/doc/2012-09-17/">
+...
+*/
+
+request(aws4.sign({service: 'monitoring', path: '/?Action=ListMetrics&Version=2010-08-01'}))
+/*
+<ListMetricsResponse xmlns="http://monitoring.amazonaws.com/doc/2010-08-01/">
+...
+*/
+
+request(aws4.sign({service: 'redshift', path: '/?Action=DescribeClusters&Version=2012-12-01'}))
+/*
+<DescribeClustersResponse xmlns="http://redshift.amazonaws.com/doc/2012-12-01/">
+...
+*/
+
+request(aws4.sign({service: 'cloudfront', path: '/2014-05-31/distribution'}))
+/*
+<DistributionList xmlns="http://cloudfront.amazonaws.com/doc/2014-05-31/">
+...
+*/
+
+request(aws4.sign({service: 'elasticache', path: '/?Action=DescribeCacheClusters&Version=2014-07-15'}))
+/*
+<DescribeCacheClustersResponse xmlns="http://elasticache.amazonaws.com/doc/2014-07-15/">
+...
+*/
+
+request(aws4.sign({service: 'elasticmapreduce', path: '/?Action=DescribeJobFlows&Version=2009-03-31'}))
+/*
+<DescribeJobFlowsResponse xmlns="http://elasticmapreduce.amazonaws.com/doc/2009-03-31">
+...
+*/
+
+request(aws4.sign({service: 'route53', path: '/2013-04-01/hostedzone'}))
+/*
+<ListHostedZonesResponse xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
+...
+*/
+
+request(aws4.sign({service: 'appstream', path: '/applications'}))
+/*
+{"_links":{"curie":[{"href":"http://docs.aws.amazon.com/appstream/latest/...
+...
+*/
+
+request(aws4.sign({service: 'cognito-sync', path: '/identitypools'}))
+/*
+{"Count":0,"IdentityPoolUsages":[],"MaxResults":16,"NextToken":null}
+...
+*/
+
+request(aws4.sign({service: 'elastictranscoder', path: '/2012-09-25/pipelines'}))
+/*
+{"NextPageToken":null,"Pipelines":[]}
+...
+*/
+
+request(aws4.sign({service: 'lambda', path: '/2014-11-13/functions/'}))
+/*
+{"Functions":[],"NextMarker":null}
+...
+*/
+
+request(aws4.sign({service: 'ecs', path: '/?Action=ListClusters&Version=2014-11-13'}))
+/*
+<ListClustersResponse xmlns="http://ecs.amazonaws.com/doc/2014-11-13/">
+...
+*/
+
+request(aws4.sign({service: 'glacier', path: '/-/vaults', headers: {'X-Amz-Glacier-Version': '2012-06-01'}}))
+/*
+{"Marker":null,"VaultList":[]}
+...
+*/
+
+request(aws4.sign({service: 'storagegateway', body: '{}', headers: {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'StorageGateway_20120630.ListGateways'
+}}))
+/*
+{"Gateways":[]}
+...
+*/
+
+request(aws4.sign({service: 'datapipeline', body: '{}', headers: {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'DataPipeline.ListPipelines'
+}}))
+/*
+{"hasMoreResults":false,"pipelineIdList":[]}
+...
+*/
+
+request(aws4.sign({service: 'opsworks', body: '{}', headers: {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'OpsWorks_20130218.DescribeStacks'
+}}))
+/*
+{"Stacks":[]}
+...
+*/
+
+request(aws4.sign({service: 'route53domains', body: '{}', headers: {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'Route53Domains_v20140515.ListDomains'
+}}))
+/*
+{"Domains":[]}
+...
+*/
+
+request(aws4.sign({service: 'kinesis', body: '{}', headers: {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'Kinesis_20131202.ListStreams'
+}}))
+/*
+{"HasMoreStreams":false,"StreamNames":[]}
+...
+*/
+
+request(aws4.sign({service: 'cloudtrail', body: '{}', headers: {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'CloudTrail_20131101.DescribeTrails'
+}}))
+/*
+{"trailList":[]}
+...
+*/
+
+request(aws4.sign({service: 'logs', body: '{}', headers: {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'Logs_20140328.DescribeLogGroups'
+}}))
+/*
+{"logGroups":[]}
+...
+*/
+
+request(aws4.sign({service: 'codedeploy', body: '{}', headers: {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'CodeDeploy_20141006.ListApplications'
+}}))
+/*
+{"applications":[]}
+...
+*/
+
+request(aws4.sign({service: 'directconnect', body: '{}', headers: {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'OvertureService.DescribeConnections'
+}}))
+/*
+{"connections":[]}
+...
+*/
+
+request(aws4.sign({service: 'kms', body: '{}', headers: {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'TrentService.ListKeys'
+}}))
+/*
+{"Keys":[],"Truncated":false}
+...
+*/
+
+request(aws4.sign({service: 'config', body: '{}', headers: {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'StarlingDoveService.DescribeDeliveryChannels'
+}}))
+/*
+{"DeliveryChannels":[]}
+...
+*/
+
+request(aws4.sign({service: 'cloudhsm', body: '{}', headers: {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'CloudHsmFrontendService.ListAvailableZones'
+}}))
+/*
+{"AZList":["us-east-1a","us-east-1b","us-east-1c"]}
+...
+*/
+
+request(aws4.sign({
+ service: 'swf',
+ body: '{"registrationStatus":"REGISTERED"}',
+ headers: {
+ 'Content-Type': 'application/x-amz-json-1.0',
+ 'X-Amz-Target': 'SimpleWorkflowService.ListDomains'
+ }
+}))
+/*
+{"domainInfos":[]}
+...
+*/
+
+request(aws4.sign({
+ service: 'cognito-identity',
+ body: '{"MaxResults": 1}',
+ headers: {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'AWSCognitoIdentityService.ListIdentityPools'
+ }
+}))
+/*
+{"IdentityPools":[]}
+...
+*/
+
+request(aws4.sign({
+ service: 'mobileanalytics',
+ path: '/2014-06-05/events',
+ body: JSON.stringify({events:[{
+ eventType: 'a',
+ timestamp: new Date().toISOString(),
+ session: {},
+ }]}),
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-Amz-Client-Context': JSON.stringify({
+ client: {client_id: 'a', app_title: 'a'},
+ custom: {},
+ env: {platform: 'a'},
+ services: {},
+ }),
+ }
+}))
+/*
+(HTTP 202, empty response)
+*/
+
+// Still not updated to v4...
+
+//request(aws4.sign({service: 'importexport', path: '/?Action=ListJobs&Version=2010-06-01'}))
+
+//request(aws4.sign({service: 'sdb', path: '/?Action=ListDomains&Version=2009-04-15'}))
+
diff --git a/node_modules/request/node_modules/aws4/node_modules/lru-cache/.npmignore b/node_modules/request/node_modules/aws4/node_modules/lru-cache/.npmignore
new file mode 100644
index 000000000..07e6e472c
--- /dev/null
+++ b/node_modules/request/node_modules/aws4/node_modules/lru-cache/.npmignore
@@ -0,0 +1 @@
+/node_modules
diff --git a/node_modules/request/node_modules/aws4/node_modules/lru-cache/.travis.yml b/node_modules/request/node_modules/aws4/node_modules/lru-cache/.travis.yml
new file mode 100644
index 000000000..4af02b3d1
--- /dev/null
+++ b/node_modules/request/node_modules/aws4/node_modules/lru-cache/.travis.yml
@@ -0,0 +1,8 @@
+language: node_js
+node_js:
+ - '0.8'
+ - '0.10'
+ - '0.12'
+ - 'iojs'
+before_install:
+ - npm install -g npm@latest
diff --git a/node_modules/request/node_modules/aws4/node_modules/lru-cache/CONTRIBUTORS b/node_modules/request/node_modules/aws4/node_modules/lru-cache/CONTRIBUTORS
new file mode 100644
index 000000000..4a0bc5033
--- /dev/null
+++ b/node_modules/request/node_modules/aws4/node_modules/lru-cache/CONTRIBUTORS
@@ -0,0 +1,14 @@
+# Authors, sorted by whether or not they are me
+Isaac Z. Schlueter <i@izs.me>
+Brian Cottingham <spiffytech@gmail.com>
+Carlos Brito Lage <carlos@carloslage.net>
+Jesse Dailey <jesse.dailey@gmail.com>
+Kevin O'Hara <kevinohara80@gmail.com>
+Marco Rogers <marco.rogers@gmail.com>
+Mark Cavage <mcavage@gmail.com>
+Marko Mikulicic <marko.mikulicic@isti.cnr.it>
+Nathan Rajlich <nathan@tootallnate.net>
+Satheesh Natesan <snateshan@myspace-inc.com>
+Trent Mick <trentm@gmail.com>
+ashleybrener <ashley@starlogik.com>
+n4kz <n4kz@n4kz.com>
diff --git a/node_modules/request/node_modules/aws4/node_modules/lru-cache/LICENSE b/node_modules/request/node_modules/aws4/node_modules/lru-cache/LICENSE
new file mode 100644
index 000000000..19129e315
--- /dev/null
+++ b/node_modules/request/node_modules/aws4/node_modules/lru-cache/LICENSE
@@ -0,0 +1,15 @@
+The ISC License
+
+Copyright (c) Isaac Z. Schlueter and Contributors
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
+IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
diff --git a/node_modules/request/node_modules/aws4/node_modules/lru-cache/README.md b/node_modules/request/node_modules/aws4/node_modules/lru-cache/README.md
new file mode 100644
index 000000000..c06814e04
--- /dev/null
+++ b/node_modules/request/node_modules/aws4/node_modules/lru-cache/README.md
@@ -0,0 +1,137 @@
+# lru cache
+
+A cache object that deletes the least-recently-used items.
+
+## Usage:
+
+```javascript
+var LRU = require("lru-cache")
+ , options = { max: 500
+ , length: function (n) { return n * 2 }
+ , dispose: function (key, n) { n.close() }
+ , maxAge: 1000 * 60 * 60 }
+ , cache = LRU(options)
+ , otherCache = LRU(50) // sets just the max size
+
+cache.set("key", "value")
+cache.get("key") // "value"
+
+cache.reset() // empty the cache
+```
+
+If you put more stuff in it, then items will fall out.
+
+If you try to put an oversized thing in it, then it'll fall out right
+away.
+
+## Keys should always be Strings or Numbers
+
+Note: this module will print warnings to `console.error` if you use a
+key that is not a String or Number. Because items are stored in an
+object, which coerces keys to a string, it won't go well for you if
+you try to use a key that is not a unique string, it'll cause surprise
+collisions. For example:
+
+```JavaScript
+// Bad Example! Dont' do this!
+var cache = LRU()
+var a = {}
+var b = {}
+cache.set(a, 'this is a')
+cache.set(b, 'this is b')
+console.log(cache.get(a)) // prints: 'this is b'
+```
+
+## Options
+
+* `max` The maximum size of the cache, checked by applying the length
+ function to all values in the cache. Not setting this is kind of
+ silly, since that's the whole purpose of this lib, but it defaults
+ to `Infinity`.
+* `maxAge` Maximum age in ms. Items are not pro-actively pruned out
+ as they age, but if you try to get an item that is too old, it'll
+ drop it and return undefined instead of giving it to you.
+* `length` Function that is used to calculate the length of stored
+ items. If you're storing strings or buffers, then you probably want
+ to do something like `function(n){return n.length}`. The default is
+ `function(n){return 1}`, which is fine if you want to store `max`
+ like-sized things.
+* `dispose` Function that is called on items when they are dropped
+ from the cache. This can be handy if you want to close file
+ descriptors or do other cleanup tasks when items are no longer
+ accessible. Called with `key, value`. It's called *before*
+ actually removing the item from the internal cache, so if you want
+ to immediately put it back in, you'll have to do that in a
+ `nextTick` or `setTimeout` callback or it won't do anything.
+* `stale` By default, if you set a `maxAge`, it'll only actually pull
+ stale items out of the cache when you `get(key)`. (That is, it's
+ not pre-emptively doing a `setTimeout` or anything.) If you set
+ `stale:true`, it'll return the stale value before deleting it. If
+ you don't set this, then it'll return `undefined` when you try to
+ get a stale entry, as if it had already been deleted.
+
+## API
+
+* `set(key, value, maxAge)`
+* `get(key) => value`
+
+ Both of these will update the "recently used"-ness of the key.
+ They do what you think. `max` is optional and overrides the
+ cache `max` option if provided.
+
+* `peek(key)`
+
+ Returns the key value (or `undefined` if not found) without
+ updating the "recently used"-ness of the key.
+
+ (If you find yourself using this a lot, you *might* be using the
+ wrong sort of data structure, but there are some use cases where
+ it's handy.)
+
+* `del(key)`
+
+ Deletes a key out of the cache.
+
+* `reset()`
+
+ Clear the cache entirely, throwing away all values.
+
+* `has(key)`
+
+ Check if a key is in the cache, without updating the recent-ness
+ or deleting it for being stale.
+
+* `forEach(function(value,key,cache), [thisp])`
+
+ Just like `Array.prototype.forEach`. Iterates over all the keys
+ in the cache, in order of recent-ness. (Ie, more recently used
+ items are iterated over first.)
+
+* `keys()`
+
+ Return an array of the keys in the cache.
+
+* `values()`
+
+ Return an array of the values in the cache.
+
+* `length()`
+
+ Return total length of objects in cache taking into account
+ `length` options function.
+
+* `itemCount`
+
+ Return total quantity of objects currently in cache. Note, that
+ `stale` (see options) items are returned as part of this item
+ count.
+
+* `dump()`
+
+ Return an array of the cache entries ready for serialization and usage
+ with 'destinationCache.load(arr)`.
+
+* `load(cacheEntriesArray)`
+
+ Loads another cache entries array, obtained with `sourceCache.dump()`,
+ into the cache. The destination cache is reset before loading new entries
diff --git a/node_modules/request/node_modules/aws4/node_modules/lru-cache/lib/lru-cache.js b/node_modules/request/node_modules/aws4/node_modules/lru-cache/lib/lru-cache.js
new file mode 100644
index 000000000..2bbe653be
--- /dev/null
+++ b/node_modules/request/node_modules/aws4/node_modules/lru-cache/lib/lru-cache.js
@@ -0,0 +1,334 @@
+;(function () { // closure for web browsers
+
+if (typeof module === 'object' && module.exports) {
+ module.exports = LRUCache
+} else {
+ // just set the global for non-node platforms.
+ this.LRUCache = LRUCache
+}
+
+function hOP (obj, key) {
+ return Object.prototype.hasOwnProperty.call(obj, key)
+}
+
+function naiveLength () { return 1 }
+
+var didTypeWarning = false
+function typeCheckKey(key) {
+ if (!didTypeWarning && typeof key !== 'string' && typeof key !== 'number') {
+ didTypeWarning = true
+ console.error(new TypeError("LRU: key must be a string or number. Almost certainly a bug! " + typeof key).stack)
+ }
+}
+
+function LRUCache (options) {
+ if (!(this instanceof LRUCache))
+ return new LRUCache(options)
+
+ if (typeof options === 'number')
+ options = { max: options }
+
+ if (!options)
+ options = {}
+
+ this._max = options.max
+ // Kind of weird to have a default max of Infinity, but oh well.
+ if (!this._max || !(typeof this._max === "number") || this._max <= 0 )
+ this._max = Infinity
+
+ this._lengthCalculator = options.length || naiveLength
+ if (typeof this._lengthCalculator !== "function")
+ this._lengthCalculator = naiveLength
+
+ this._allowStale = options.stale || false
+ this._maxAge = options.maxAge || null
+ this._dispose = options.dispose
+ this.reset()
+}
+
+// resize the cache when the max changes.
+Object.defineProperty(LRUCache.prototype, "max",
+ { set : function (mL) {
+ if (!mL || !(typeof mL === "number") || mL <= 0 ) mL = Infinity
+ this._max = mL
+ if (this._length > this._max) trim(this)
+ }
+ , get : function () { return this._max }
+ , enumerable : true
+ })
+
+// resize the cache when the lengthCalculator changes.
+Object.defineProperty(LRUCache.prototype, "lengthCalculator",
+ { set : function (lC) {
+ if (typeof lC !== "function") {
+ this._lengthCalculator = naiveLength
+ this._length = this._itemCount
+ for (var key in this._cache) {
+ this._cache[key].length = 1
+ }
+ } else {
+ this._lengthCalculator = lC
+ this._length = 0
+ for (var key in this._cache) {
+ this._cache[key].length = this._lengthCalculator(this._cache[key].value)
+ this._length += this._cache[key].length
+ }
+ }
+
+ if (this._length > this._max) trim(this)
+ }
+ , get : function () { return this._lengthCalculator }
+ , enumerable : true
+ })
+
+Object.defineProperty(LRUCache.prototype, "length",
+ { get : function () { return this._length }
+ , enumerable : true
+ })
+
+
+Object.defineProperty(LRUCache.prototype, "itemCount",
+ { get : function () { return this._itemCount }
+ , enumerable : true
+ })
+
+LRUCache.prototype.forEach = function (fn, thisp) {
+ thisp = thisp || this
+ var i = 0
+ var itemCount = this._itemCount
+
+ for (var k = this._mru - 1; k >= 0 && i < itemCount; k--) if (this._lruList[k]) {
+ i++
+ var hit = this._lruList[k]
+ if (isStale(this, hit)) {
+ del(this, hit)
+ if (!this._allowStale) hit = undefined
+ }
+ if (hit) {
+ fn.call(thisp, hit.value, hit.key, this)
+ }
+ }
+}
+
+LRUCache.prototype.keys = function () {
+ var keys = new Array(this._itemCount)
+ var i = 0
+ for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) if (this._lruList[k]) {
+ var hit = this._lruList[k]
+ keys[i++] = hit.key
+ }
+ return keys
+}
+
+LRUCache.prototype.values = function () {
+ var values = new Array(this._itemCount)
+ var i = 0
+ for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) if (this._lruList[k]) {
+ var hit = this._lruList[k]
+ values[i++] = hit.value
+ }
+ return values
+}
+
+LRUCache.prototype.reset = function () {
+ if (this._dispose && this._cache) {
+ for (var k in this._cache) {
+ this._dispose(k, this._cache[k].value)
+ }
+ }
+
+ this._cache = Object.create(null) // hash of items by key
+ this._lruList = Object.create(null) // list of items in order of use recency
+ this._mru = 0 // most recently used
+ this._lru = 0 // least recently used
+ this._length = 0 // number of items in the list
+ this._itemCount = 0
+}
+
+LRUCache.prototype.dump = function () {
+ var arr = []
+ var i = 0
+
+ for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) if (this._lruList[k]) {
+ var hit = this._lruList[k]
+ if (!isStale(this, hit)) {
+ //Do not store staled hits
+ ++i
+ arr.push({
+ k: hit.key,
+ v: hit.value,
+ e: hit.now + (hit.maxAge || 0)
+ });
+ }
+ }
+ //arr has the most read first
+ return arr
+}
+
+LRUCache.prototype.dumpLru = function () {
+ return this._lruList
+}
+
+LRUCache.prototype.set = function (key, value, maxAge) {
+ maxAge = maxAge || this._maxAge
+ typeCheckKey(key)
+
+ var now = maxAge ? Date.now() : 0
+ var len = this._lengthCalculator(value)
+
+ if (hOP(this._cache, key)) {
+ if (len > this._max) {
+ del(this, this._cache[key])
+ return false
+ }
+ // dispose of the old one before overwriting
+ if (this._dispose)
+ this._dispose(key, this._cache[key].value)
+
+ this._cache[key].now = now
+ this._cache[key].maxAge = maxAge
+ this._cache[key].value = value
+ this._length += (len - this._cache[key].length)
+ this._cache[key].length = len
+ this.get(key)
+
+ if (this._length > this._max)
+ trim(this)
+
+ return true
+ }
+
+ var hit = new Entry(key, value, this._mru++, len, now, maxAge)
+
+ // oversized objects fall out of cache automatically.
+ if (hit.length > this._max) {
+ if (this._dispose) this._dispose(key, value)
+ return false
+ }
+
+ this._length += hit.length
+ this._lruList[hit.lu] = this._cache[key] = hit
+ this._itemCount ++
+
+ if (this._length > this._max)
+ trim(this)
+
+ return true
+}
+
+LRUCache.prototype.has = function (key) {
+ typeCheckKey(key)
+ if (!hOP(this._cache, key)) return false
+ var hit = this._cache[key]
+ if (isStale(this, hit)) {
+ return false
+ }
+ return true
+}
+
+LRUCache.prototype.get = function (key) {
+ typeCheckKey(key)
+ return get(this, key, true)
+}
+
+LRUCache.prototype.peek = function (key) {
+ typeCheckKey(key)
+ return get(this, key, false)
+}
+
+LRUCache.prototype.pop = function () {
+ var hit = this._lruList[this._lru]
+ del(this, hit)
+ return hit || null
+}
+
+LRUCache.prototype.del = function (key) {
+ typeCheckKey(key)
+ del(this, this._cache[key])
+}
+
+LRUCache.prototype.load = function (arr) {
+ //reset the cache
+ this.reset();
+
+ var now = Date.now()
+ //A previous serialized cache has the most recent items first
+ for (var l = arr.length - 1; l >= 0; l-- ) {
+ var hit = arr[l]
+ typeCheckKey(hit.k)
+ var expiresAt = hit.e || 0
+ if (expiresAt === 0) {
+ //the item was created without expiration in a non aged cache
+ this.set(hit.k, hit.v)
+ } else {
+ var maxAge = expiresAt - now
+ //dont add already expired items
+ if (maxAge > 0) this.set(hit.k, hit.v, maxAge)
+ }
+ }
+}
+
+function get (self, key, doUse) {
+ typeCheckKey(key)
+ var hit = self._cache[key]
+ if (hit) {
+ if (isStale(self, hit)) {
+ del(self, hit)
+ if (!self._allowStale) hit = undefined
+ } else {
+ if (doUse) use(self, hit)
+ }
+ if (hit) hit = hit.value
+ }
+ return hit
+}
+
+function isStale(self, hit) {
+ if (!hit || (!hit.maxAge && !self._maxAge)) return false
+ var stale = false;
+ var diff = Date.now() - hit.now
+ if (hit.maxAge) {
+ stale = diff > hit.maxAge
+ } else {
+ stale = self._maxAge && (diff > self._maxAge)
+ }
+ return stale;
+}
+
+function use (self, hit) {
+ shiftLU(self, hit)
+ hit.lu = self._mru ++
+ self._lruList[hit.lu] = hit
+}
+
+function trim (self) {
+ while (self._lru < self._mru && self._length > self._max)
+ del(self, self._lruList[self._lru])
+}
+
+function shiftLU (self, hit) {
+ delete self._lruList[ hit.lu ]
+ while (self._lru < self._mru && !self._lruList[self._lru]) self._lru ++
+}
+
+function del (self, hit) {
+ if (hit) {
+ if (self._dispose) self._dispose(hit.key, hit.value)
+ self._length -= hit.length
+ self._itemCount --
+ delete self._cache[ hit.key ]
+ shiftLU(self, hit)
+ }
+}
+
+// classy, since V8 prefers predictable objects.
+function Entry (key, value, lu, length, now, maxAge) {
+ this.key = key
+ this.value = value
+ this.lu = lu
+ this.length = length
+ this.now = now
+ if (maxAge) this.maxAge = maxAge
+}
+
+})()
diff --git a/node_modules/request/node_modules/aws4/node_modules/lru-cache/package.json b/node_modules/request/node_modules/aws4/node_modules/lru-cache/package.json
new file mode 100644
index 000000000..501c3e735
--- /dev/null
+++ b/node_modules/request/node_modules/aws4/node_modules/lru-cache/package.json
@@ -0,0 +1,84 @@
+{
+ "_args": [
+ [
+ "lru-cache@^2.6.5",
+ "/Users/rebecca/code/npm/node_modules/request/node_modules/aws4"
+ ]
+ ],
+ "_from": "lru-cache@>=2.6.5 <3.0.0",
+ "_id": "lru-cache@2.7.3",
+ "_inCache": true,
+ "_installable": true,
+ "_location": "/request/aws4/lru-cache",
+ "_nodeVersion": "4.0.0",
+ "_npmUser": {
+ "email": "i@izs.me",
+ "name": "isaacs"
+ },
+ "_npmVersion": "3.3.2",
+ "_phantomChildren": {},
+ "_requested": {
+ "name": "lru-cache",
+ "raw": "lru-cache@^2.6.5",
+ "rawSpec": "^2.6.5",
+ "scope": null,
+ "spec": ">=2.6.5 <3.0.0",
+ "type": "range"
+ },
+ "_requiredBy": [
+ "/request/aws4"
+ ],
+ "_resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-2.7.3.tgz",
+ "_shasum": "6d4524e8b955f95d4f5b58851ce21dd72fb4e952",
+ "_shrinkwrap": null,
+ "_spec": "lru-cache@^2.6.5",
+ "_where": "/Users/rebecca/code/npm/node_modules/request/node_modules/aws4",
+ "author": {
+ "email": "i@izs.me",
+ "name": "Isaac Z. Schlueter"
+ },
+ "bugs": {
+ "url": "https://github.com/isaacs/node-lru-cache/issues"
+ },
+ "dependencies": {},
+ "description": "A cache object that deletes the least-recently-used items.",
+ "devDependencies": {
+ "tap": "^1.2.0",
+ "weak": ""
+ },
+ "directories": {},
+ "dist": {
+ "shasum": "6d4524e8b955f95d4f5b58851ce21dd72fb4e952",
+ "tarball": "http://registry.npmjs.org/lru-cache/-/lru-cache-2.7.3.tgz"
+ },
+ "gitHead": "292048199f6d28b77fbe584279a1898e25e4c714",
+ "homepage": "https://github.com/isaacs/node-lru-cache#readme",
+ "keywords": [
+ "cache",
+ "lru",
+ "mru"
+ ],
+ "license": "ISC",
+ "main": "lib/lru-cache.js",
+ "maintainers": [
+ {
+ "name": "isaacs",
+ "email": "isaacs@npmjs.com"
+ },
+ {
+ "name": "othiym23",
+ "email": "ogd@aoaioxxysz.net"
+ }
+ ],
+ "name": "lru-cache",
+ "optionalDependencies": {},
+ "readme": "ERROR: No README data found!",
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/isaacs/node-lru-cache.git"
+ },
+ "scripts": {
+ "test": "tap test --gc"
+ },
+ "version": "2.7.3"
+}
diff --git a/node_modules/request/node_modules/aws4/node_modules/lru-cache/test/basic.js b/node_modules/request/node_modules/aws4/node_modules/lru-cache/test/basic.js
new file mode 100644
index 000000000..b47225f10
--- /dev/null
+++ b/node_modules/request/node_modules/aws4/node_modules/lru-cache/test/basic.js
@@ -0,0 +1,396 @@
+var test = require("tap").test
+ , LRU = require("../")
+
+test("basic", function (t) {
+ var cache = new LRU({max: 10})
+ cache.set("key", "value")
+ t.equal(cache.get("key"), "value")
+ t.equal(cache.get("nada"), undefined)
+ t.equal(cache.length, 1)
+ t.equal(cache.max, 10)
+ t.end()
+})
+
+test("least recently set", function (t) {
+ var cache = new LRU(2)
+ cache.set("a", "A")
+ cache.set("b", "B")
+ cache.set("c", "C")
+ t.equal(cache.get("c"), "C")
+ t.equal(cache.get("b"), "B")
+ t.equal(cache.get("a"), undefined)
+ t.end()
+})
+
+test("lru recently gotten", function (t) {
+ var cache = new LRU(2)
+ cache.set("a", "A")
+ cache.set("b", "B")
+ cache.get("a")
+ cache.set("c", "C")
+ t.equal(cache.get("c"), "C")
+ t.equal(cache.get("b"), undefined)
+ t.equal(cache.get("a"), "A")
+ t.end()
+})
+
+test("del", function (t) {
+ var cache = new LRU(2)
+ cache.set("a", "A")
+ cache.del("a")
+ t.equal(cache.get("a"), undefined)
+ t.end()
+})
+
+test("max", function (t) {
+ var cache = new LRU(3)
+
+ // test changing the max, verify that the LRU items get dropped.
+ cache.max = 100
+ for (var i = 0; i < 100; i ++) cache.set(i, i)
+ t.equal(cache.length, 100)
+ for (var i = 0; i < 100; i ++) {
+ t.equal(cache.get(i), i)
+ }
+ cache.max = 3
+ t.equal(cache.length, 3)
+ for (var i = 0; i < 97; i ++) {
+ t.equal(cache.get(i), undefined)
+ }
+ for (var i = 98; i < 100; i ++) {
+ t.equal(cache.get(i), i)
+ }
+
+ // now remove the max restriction, and try again.
+ cache.max = "hello"
+ for (var i = 0; i < 100; i ++) cache.set(i, i)
+ t.equal(cache.length, 100)
+ for (var i = 0; i < 100; i ++) {
+ t.equal(cache.get(i), i)
+ }
+ // should trigger an immediate resize
+ cache.max = 3
+ t.equal(cache.length, 3)
+ for (var i = 0; i < 97; i ++) {
+ t.equal(cache.get(i), undefined)
+ }
+ for (var i = 98; i < 100; i ++) {
+ t.equal(cache.get(i), i)
+ }
+ t.end()
+})
+
+test("reset", function (t) {
+ var cache = new LRU(10)
+ cache.set("a", "A")
+ cache.set("b", "B")
+ cache.reset()
+ t.equal(cache.length, 0)
+ t.equal(cache.max, 10)
+ t.equal(cache.get("a"), undefined)
+ t.equal(cache.get("b"), undefined)
+ t.end()
+})
+
+
+test("basic with weighed length", function (t) {
+ var cache = new LRU({
+ max: 100,
+ length: function (item) { return item.size }
+ })
+ cache.set("key", {val: "value", size: 50})
+ t.equal(cache.get("key").val, "value")
+ t.equal(cache.get("nada"), undefined)
+ t.equal(cache.lengthCalculator(cache.get("key")), 50)
+ t.equal(cache.length, 50)
+ t.equal(cache.max, 100)
+ t.end()
+})
+
+
+test("weighed length item too large", function (t) {
+ var cache = new LRU({
+ max: 10,
+ length: function (item) { return item.size }
+ })
+ t.equal(cache.max, 10)
+
+ // should fall out immediately
+ cache.set("key", {val: "value", size: 50})
+
+ t.equal(cache.length, 0)
+ t.equal(cache.get("key"), undefined)
+ t.end()
+})
+
+test("least recently set with weighed length", function (t) {
+ var cache = new LRU({
+ max:8,
+ length: function (item) { return item.length }
+ })
+ cache.set("a", "A")
+ cache.set("b", "BB")
+ cache.set("c", "CCC")
+ cache.set("d", "DDDD")
+ t.equal(cache.get("d"), "DDDD")
+ t.equal(cache.get("c"), "CCC")
+ t.equal(cache.get("b"), undefined)
+ t.equal(cache.get("a"), undefined)
+ t.end()
+})
+
+test("lru recently gotten with weighed length", function (t) {
+ var cache = new LRU({
+ max: 8,
+ length: function (item) { return item.length }
+ })
+ cache.set("a", "A")
+ cache.set("b", "BB")
+ cache.set("c", "CCC")
+ cache.get("a")
+ cache.get("b")
+ cache.set("d", "DDDD")
+ t.equal(cache.get("c"), undefined)
+ t.equal(cache.get("d"), "DDDD")
+ t.equal(cache.get("b"), "BB")
+ t.equal(cache.get("a"), "A")
+ t.end()
+})
+
+test("lru recently updated with weighed length", function (t) {
+ var cache = new LRU({
+ max: 8,
+ length: function (item) { return item.length }
+ })
+ cache.set("a", "A")
+ cache.set("b", "BB")
+ cache.set("c", "CCC")
+ t.equal(cache.length, 6) //CCC BB A
+ cache.set("a", "+A")
+ t.equal(cache.length, 7) //+A CCC BB
+ cache.set("b", "++BB")
+ t.equal(cache.length, 6) //++BB +A
+ t.equal(cache.get("c"), undefined)
+
+ cache.set("c", "oversized")
+ t.equal(cache.length, 6) //++BB +A
+ t.equal(cache.get("c"), undefined)
+
+ cache.set("a", "oversized")
+ t.equal(cache.length, 4) //++BB
+ t.equal(cache.get("a"), undefined)
+ t.equal(cache.get("b"), "++BB")
+ t.end()
+})
+
+test("set returns proper booleans", function(t) {
+ var cache = new LRU({
+ max: 5,
+ length: function (item) { return item.length }
+ })
+
+ t.equal(cache.set("a", "A"), true)
+
+ // should return false for max exceeded
+ t.equal(cache.set("b", "donuts"), false)
+
+ t.equal(cache.set("b", "B"), true)
+ t.equal(cache.set("c", "CCCC"), true)
+ t.end()
+})
+
+test("drop the old items", function(t) {
+ var cache = new LRU({
+ max: 5,
+ maxAge: 50
+ })
+
+ cache.set("a", "A")
+
+ setTimeout(function () {
+ cache.set("b", "b")
+ t.equal(cache.get("a"), "A")
+ }, 25)
+
+ setTimeout(function () {
+ cache.set("c", "C")
+ // timed out
+ t.notOk(cache.get("a"))
+ }, 60 + 25)
+
+ setTimeout(function () {
+ t.notOk(cache.get("b"))
+ t.equal(cache.get("c"), "C")
+ }, 90)
+
+ setTimeout(function () {
+ t.notOk(cache.get("c"))
+ t.end()
+ }, 155)
+})
+
+test("individual item can have it's own maxAge", function(t) {
+ var cache = new LRU({
+ max: 5,
+ maxAge: 50
+ })
+
+ cache.set("a", "A", 20)
+ setTimeout(function () {
+ t.notOk(cache.get("a"))
+ t.end()
+ }, 25)
+})
+
+test("individual item can have it's own maxAge > cache's", function(t) {
+ var cache = new LRU({
+ max: 5,
+ maxAge: 20
+ })
+
+ cache.set("a", "A", 50)
+ setTimeout(function () {
+ t.equal(cache.get("a"), "A")
+ t.end()
+ }, 25)
+})
+
+test("disposal function", function(t) {
+ var disposed = false
+ var cache = new LRU({
+ max: 1,
+ dispose: function (k, n) {
+ disposed = n
+ }
+ })
+
+ cache.set(1, 1)
+ cache.set(2, 2)
+ t.equal(disposed, 1)
+ cache.set(3, 3)
+ t.equal(disposed, 2)
+ cache.reset()
+ t.equal(disposed, 3)
+ t.end()
+})
+
+test("disposal function on too big of item", function(t) {
+ var disposed = false
+ var cache = new LRU({
+ max: 1,
+ length: function (k) {
+ return k.length
+ },
+ dispose: function (k, n) {
+ disposed = n
+ }
+ })
+ var obj = [ 1, 2 ]
+
+ t.equal(disposed, false)
+ cache.set("obj", obj)
+ t.equal(disposed, obj)
+ t.end()
+})
+
+test("has()", function(t) {
+ var cache = new LRU({
+ max: 1,
+ maxAge: 10
+ })
+
+ cache.set('foo', 'bar')
+ t.equal(cache.has('foo'), true)
+ cache.set('blu', 'baz')
+ t.equal(cache.has('foo'), false)
+ t.equal(cache.has('blu'), true)
+ setTimeout(function() {
+ t.equal(cache.has('blu'), false)
+ t.end()
+ }, 15)
+})
+
+test("stale", function(t) {
+ var cache = new LRU({
+ maxAge: 10,
+ stale: true
+ })
+
+ cache.set('foo', 'bar')
+ t.equal(cache.get('foo'), 'bar')
+ t.equal(cache.has('foo'), true)
+ setTimeout(function() {
+ t.equal(cache.has('foo'), false)
+ t.equal(cache.get('foo'), 'bar')
+ t.equal(cache.get('foo'), undefined)
+ t.end()
+ }, 15)
+})
+
+test("lru update via set", function(t) {
+ var cache = LRU({ max: 2 });
+
+ cache.set('foo', 1);
+ cache.set('bar', 2);
+ cache.del('bar');
+ cache.set('baz', 3);
+ cache.set('qux', 4);
+
+ t.equal(cache.get('foo'), undefined)
+ t.equal(cache.get('bar'), undefined)
+ t.equal(cache.get('baz'), 3)
+ t.equal(cache.get('qux'), 4)
+ t.end()
+})
+
+test("least recently set w/ peek", function (t) {
+ var cache = new LRU(2)
+ cache.set("a", "A")
+ cache.set("b", "B")
+ t.equal(cache.peek("a"), "A")
+ cache.set("c", "C")
+ t.equal(cache.get("c"), "C")
+ t.equal(cache.get("b"), "B")
+ t.equal(cache.get("a"), undefined)
+ t.end()
+})
+
+test("pop the least used item", function (t) {
+ var cache = new LRU(3)
+ , last
+
+ cache.set("a", "A")
+ cache.set("b", "B")
+ cache.set("c", "C")
+
+ t.equal(cache.length, 3)
+ t.equal(cache.max, 3)
+
+ // Ensure we pop a, c, b
+ cache.get("b", "B")
+
+ last = cache.pop()
+ t.equal(last.key, "a")
+ t.equal(last.value, "A")
+ t.equal(cache.length, 2)
+ t.equal(cache.max, 3)
+
+ last = cache.pop()
+ t.equal(last.key, "c")
+ t.equal(last.value, "C")
+ t.equal(cache.length, 1)
+ t.equal(cache.max, 3)
+
+ last = cache.pop()
+ t.equal(last.key, "b")
+ t.equal(last.value, "B")
+ t.equal(cache.length, 0)
+ t.equal(cache.max, 3)
+
+ last = cache.pop()
+ t.equal(last, null)
+ t.equal(cache.length, 0)
+ t.equal(cache.max, 3)
+
+ t.end()
+})
diff --git a/node_modules/request/node_modules/aws4/node_modules/lru-cache/test/foreach.js b/node_modules/request/node_modules/aws4/node_modules/lru-cache/test/foreach.js
new file mode 100644
index 000000000..4190417cb
--- /dev/null
+++ b/node_modules/request/node_modules/aws4/node_modules/lru-cache/test/foreach.js
@@ -0,0 +1,120 @@
+var test = require('tap').test
+var LRU = require('../')
+
+test('forEach', function (t) {
+ var l = new LRU(5)
+ for (var i = 0; i < 10; i ++) {
+ l.set(i.toString(), i.toString(2))
+ }
+
+ var i = 9
+ l.forEach(function (val, key, cache) {
+ t.equal(cache, l)
+ t.equal(key, i.toString())
+ t.equal(val, i.toString(2))
+ i -= 1
+ })
+
+ // get in order of most recently used
+ l.get(6)
+ l.get(8)
+
+ var order = [ 8, 6, 9, 7, 5 ]
+ var i = 0
+
+ l.forEach(function (val, key, cache) {
+ var j = order[i ++]
+ t.equal(cache, l)
+ t.equal(key, j.toString())
+ t.equal(val, j.toString(2))
+ })
+ t.equal(i, order.length);
+
+ t.end()
+})
+
+test('keys() and values()', function (t) {
+ var l = new LRU(5)
+ for (var i = 0; i < 10; i ++) {
+ l.set(i.toString(), i.toString(2))
+ }
+
+ t.similar(l.keys(), ['9', '8', '7', '6', '5'])
+ t.similar(l.values(), ['1001', '1000', '111', '110', '101'])
+
+ // get in order of most recently used
+ l.get(6)
+ l.get(8)
+
+ t.similar(l.keys(), ['8', '6', '9', '7', '5'])
+ t.similar(l.values(), ['1000', '110', '1001', '111', '101'])
+
+ t.end()
+})
+
+test('all entries are iterated over', function(t) {
+ var l = new LRU(5)
+ for (var i = 0; i < 10; i ++) {
+ l.set(i.toString(), i.toString(2))
+ }
+
+ var i = 0
+ l.forEach(function (val, key, cache) {
+ if (i > 0) {
+ cache.del(key)
+ }
+ i += 1
+ })
+
+ t.equal(i, 5)
+ t.equal(l.keys().length, 1)
+
+ t.end()
+})
+
+test('all stale entries are removed', function(t) {
+ var l = new LRU({ max: 5, maxAge: -5, stale: true })
+ for (var i = 0; i < 10; i ++) {
+ l.set(i.toString(), i.toString(2))
+ }
+
+ var i = 0
+ l.forEach(function () {
+ i += 1
+ })
+
+ t.equal(i, 5)
+ t.equal(l.keys().length, 0)
+
+ t.end()
+})
+
+test('expires', function (t) {
+ var l = new LRU({
+ max: 10,
+ maxAge: 50
+ })
+ for (var i = 0; i < 10; i++) {
+ l.set(i.toString(), i.toString(2), ((i % 2) ? 25 : undefined))
+ }
+
+ var i = 0
+ var order = [ 8, 6, 4, 2, 0 ]
+ setTimeout(function () {
+ l.forEach(function (val, key, cache) {
+ var j = order[i++]
+ t.equal(cache, l)
+ t.equal(key, j.toString())
+ t.equal(val, j.toString(2))
+ })
+ t.equal(i, order.length);
+
+ setTimeout(function () {
+ var count = 0;
+ l.forEach(function (val, key, cache) { count++; })
+ t.equal(0, count);
+ t.end()
+ }, 25)
+
+ }, 26)
+})
diff --git a/node_modules/request/node_modules/aws4/node_modules/lru-cache/test/memory-leak.js b/node_modules/request/node_modules/aws4/node_modules/lru-cache/test/memory-leak.js
new file mode 100644
index 000000000..b5912f6f1
--- /dev/null
+++ b/node_modules/request/node_modules/aws4/node_modules/lru-cache/test/memory-leak.js
@@ -0,0 +1,51 @@
+#!/usr/bin/env node --expose_gc
+
+
+var weak = require('weak');
+var test = require('tap').test
+var LRU = require('../')
+var l = new LRU({ max: 10 })
+var refs = 0
+function X() {
+ refs ++
+ weak(this, deref)
+}
+
+function deref() {
+ refs --
+}
+
+test('no leaks', function (t) {
+ // fill up the cache
+ for (var i = 0; i < 100; i++) {
+ l.set(i, new X);
+ // throw some gets in there, too.
+ if (i % 2 === 0)
+ l.get(i / 2)
+ }
+
+ gc()
+
+ var start = process.memoryUsage()
+
+ // capture the memory
+ var startRefs = refs
+
+ // do it again, but more
+ for (var i = 0; i < 10000; i++) {
+ l.set(i, new X);
+ // throw some gets in there, too.
+ if (i % 2 === 0)
+ l.get(i / 2)
+ }
+
+ gc()
+
+ var end = process.memoryUsage()
+ t.equal(refs, startRefs, 'no leaky refs')
+
+ console.error('start: %j\n' +
+ 'end: %j', start, end);
+ t.pass();
+ t.end();
+})
diff --git a/node_modules/request/node_modules/aws4/node_modules/lru-cache/test/serialize.js b/node_modules/request/node_modules/aws4/node_modules/lru-cache/test/serialize.js
new file mode 100644
index 000000000..1094194a0
--- /dev/null
+++ b/node_modules/request/node_modules/aws4/node_modules/lru-cache/test/serialize.js
@@ -0,0 +1,216 @@
+var test = require('tap').test
+var LRU = require('../')
+
+test('dump', function (t) {
+ var cache = new LRU()
+
+ t.equal(cache.dump().length, 0, "nothing in dump for empty cache")
+
+ cache.set("a", "A")
+ cache.set("b", "B")
+ t.deepEqual(cache.dump(), [
+ { k: "b", v: "B", e: 0 },
+ { k: "a", v: "A", e: 0 }
+ ])
+
+ cache.set("a", "A");
+ t.deepEqual(cache.dump(), [
+ { k: "a", v: "A", e: 0 },
+ { k: "b", v: "B", e: 0 }
+ ])
+
+ cache.get("b");
+ t.deepEqual(cache.dump(), [
+ { k: "b", v: "B", e: 0 },
+ { k: "a", v: "A", e: 0 }
+ ])
+
+ cache.del("a");
+ t.deepEqual(cache.dump(), [
+ { k: "b", v: "B", e: 0 }
+ ])
+
+ t.end()
+})
+
+test("do not dump stale items", function(t) {
+ var cache = new LRU({
+ max: 5,
+ maxAge: 50
+ })
+
+ //expires at 50
+ cache.set("a", "A")
+
+ setTimeout(function () {
+ //expires at 75
+ cache.set("b", "B")
+ var s = cache.dump()
+ t.equal(s.length, 2)
+ t.equal(s[0].k, "b")
+ t.equal(s[1].k, "a")
+ }, 25)
+
+ setTimeout(function () {
+ //expires at 110
+ cache.set("c", "C")
+ var s = cache.dump()
+ t.equal(s.length, 2)
+ t.equal(s[0].k, "c")
+ t.equal(s[1].k, "b")
+ }, 60)
+
+ setTimeout(function () {
+ //expires at 130
+ cache.set("d", "D", 40)
+ var s = cache.dump()
+ t.equal(s.length, 2)
+ t.equal(s[0].k, "d")
+ t.equal(s[1].k, "c")
+ }, 90)
+
+ setTimeout(function () {
+ var s = cache.dump()
+ t.equal(s.length, 1)
+ t.equal(s[0].k, "d")
+ }, 120)
+
+ setTimeout(function () {
+ var s = cache.dump()
+ t.deepEqual(s, [])
+ t.end()
+ }, 155)
+})
+
+test("load basic cache", function(t) {
+ var cache = new LRU(),
+ copy = new LRU()
+
+ cache.set("a", "A")
+ cache.set("b", "B")
+
+ copy.load(cache.dump())
+ t.deepEquals(cache.dump(), copy.dump())
+
+ t.end()
+})
+
+
+test("load staled cache", function(t) {
+ var cache = new LRU({maxAge: 50}),
+ copy = new LRU({maxAge: 50}),
+ arr
+
+ //expires at 50
+ cache.set("a", "A")
+ setTimeout(function () {
+ //expires at 80
+ cache.set("b", "B")
+ arr = cache.dump()
+ t.equal(arr.length, 2)
+ }, 30)
+
+ setTimeout(function () {
+ copy.load(arr)
+ t.equal(copy.get("a"), undefined)
+ t.equal(copy.get("b"), "B")
+ }, 60)
+
+ setTimeout(function () {
+ t.equal(copy.get("b"), undefined)
+ t.end()
+ }, 90)
+})
+
+test("load to other size cache", function(t) {
+ var cache = new LRU({max: 2}),
+ copy = new LRU({max: 1})
+
+ cache.set("a", "A")
+ cache.set("b", "B")
+
+ copy.load(cache.dump())
+ t.equal(copy.get("a"), undefined)
+ t.equal(copy.get("b"), "B")
+
+ //update the last read from original cache
+ cache.get("a")
+ copy.load(cache.dump())
+ t.equal(copy.get("a"), "A")
+ t.equal(copy.get("b"), undefined)
+
+ t.end()
+})
+
+
+test("load to other age cache", function(t) {
+ var cache = new LRU({maxAge: 50}),
+ aged = new LRU({maxAge: 100}),
+ simple = new LRU(),
+ arr,
+ expired
+
+ //created at 0
+ //a would be valid till 0 + 50
+ cache.set("a", "A")
+ setTimeout(function () {
+ //created at 20
+ //b would be valid till 20 + 50
+ cache.set("b", "B")
+ //b would be valid till 20 + 70
+ cache.set("c", "C", 70)
+ arr = cache.dump()
+ t.equal(arr.length, 3)
+ }, 20)
+
+ setTimeout(function () {
+ t.equal(cache.get("a"), undefined)
+ t.equal(cache.get("b"), "B")
+ t.equal(cache.get("c"), "C")
+
+ aged.load(arr)
+ t.equal(aged.get("a"), undefined)
+ t.equal(aged.get("b"), "B")
+ t.equal(aged.get("c"), "C")
+
+ simple.load(arr)
+ t.equal(simple.get("a"), undefined)
+ t.equal(simple.get("b"), "B")
+ t.equal(simple.get("c"), "C")
+ }, 60)
+
+ setTimeout(function () {
+ t.equal(cache.get("a"), undefined)
+ t.equal(cache.get("b"), undefined)
+ t.equal(cache.get("c"), "C")
+
+ aged.load(arr)
+ t.equal(aged.get("a"), undefined)
+ t.equal(aged.get("b"), undefined)
+ t.equal(aged.get("c"), "C")
+
+ simple.load(arr)
+ t.equal(simple.get("a"), undefined)
+ t.equal(simple.get("b"), undefined)
+ t.equal(simple.get("c"), "C")
+ }, 80)
+
+ setTimeout(function () {
+ t.equal(cache.get("a"), undefined)
+ t.equal(cache.get("b"), undefined)
+ t.equal(cache.get("c"), undefined)
+
+ aged.load(arr)
+ t.equal(aged.get("a"), undefined)
+ t.equal(aged.get("b"), undefined)
+ t.equal(aged.get("c"), undefined)
+
+ simple.load(arr)
+ t.equal(simple.get("a"), undefined)
+ t.equal(simple.get("b"), undefined)
+ t.equal(simple.get("c"), undefined)
+ t.end()
+ }, 100)
+
+})
+
diff --git a/node_modules/request/node_modules/aws4/package.json b/node_modules/request/node_modules/aws4/package.json
new file mode 100644
index 000000000..31de63b47
--- /dev/null
+++ b/node_modules/request/node_modules/aws4/package.json
@@ -0,0 +1,130 @@
+{
+ "_args": [
+ [
+ "aws4@^1.2.1",
+ "/Users/rebecca/code/npm/node_modules/request"
+ ]
+ ],
+ "_from": "aws4@>=1.2.1 <2.0.0",
+ "_id": "aws4@1.2.1",
+ "_inCache": true,
+ "_installable": true,
+ "_location": "/request/aws4",
+ "_nodeVersion": "4.2.4",
+ "_npmUser": {
+ "email": "michael.hart.au@gmail.com",
+ "name": "hichaelmart"
+ },
+ "_npmVersion": "2.14.15",
+ "_phantomChildren": {},
+ "_requested": {
+ "name": "aws4",
+ "raw": "aws4@^1.2.1",
+ "rawSpec": "^1.2.1",
+ "scope": null,
+ "spec": ">=1.2.1 <2.0.0",
+ "type": "range"
+ },
+ "_requiredBy": [
+ "/request"
+ ],
+ "_resolved": "https://registry.npmjs.org/aws4/-/aws4-1.2.1.tgz",
+ "_shasum": "52b5659a4d32583d405f65e1124ac436d07fe5ac",
+ "_shrinkwrap": null,
+ "_spec": "aws4@^1.2.1",
+ "_where": "/Users/rebecca/code/npm/node_modules/request",
+ "author": {
+ "email": "michael.hart.au@gmail.com",
+ "name": "Michael Hart",
+ "url": "http://github.com/mhart"
+ },
+ "bugs": {
+ "url": "https://github.com/mhart/aws4/issues"
+ },
+ "dependencies": {
+ "lru-cache": "^2.6.5"
+ },
+ "description": "Signs and prepares requests using AWS Signature Version 4",
+ "devDependencies": {
+ "mocha": "^2.2.5",
+ "should": "^7.0.1"
+ },
+ "directories": {},
+ "dist": {
+ "shasum": "52b5659a4d32583d405f65e1124ac436d07fe5ac",
+ "tarball": "http://registry.npmjs.org/aws4/-/aws4-1.2.1.tgz"
+ },
+ "gitHead": "3d8a3a06a8415bd5255b4f60eb91576952e97f5c",
+ "homepage": "https://github.com/mhart/aws4#readme",
+ "keywords": [
+ "amazon",
+ "appstream",
+ "autoscaling",
+ "aws",
+ "cloudformation",
+ "cloudfront",
+ "cloudhsm",
+ "cloudsearch",
+ "cloudtrail",
+ "cloudwatch",
+ "codedeploy",
+ "cognito",
+ "cognitoidentity",
+ "cognitosync",
+ "config",
+ "containerservice",
+ "datapipeline",
+ "directconnect",
+ "dynamodb",
+ "ec2",
+ "ecs",
+ "elasticache",
+ "elasticbeanstalk",
+ "elasticloadbalancing",
+ "elasticmapreduce",
+ "elastictranscoder",
+ "elb",
+ "emr",
+ "glacier",
+ "iam",
+ "keymanagementservice",
+ "kinesis",
+ "kms",
+ "lambda",
+ "logs",
+ "mobileanalytics",
+ "monitoring",
+ "opsworks",
+ "rds",
+ "redshift",
+ "route53",
+ "route53domains",
+ "s3",
+ "ses",
+ "signature",
+ "sns",
+ "sqs",
+ "storagegateway",
+ "sts",
+ "swf"
+ ],
+ "license": "MIT",
+ "main": "aws4.js",
+ "maintainers": [
+ {
+ "name": "hichaelmart",
+ "email": "michael.hart.au@gmail.com"
+ }
+ ],
+ "name": "aws4",
+ "optionalDependencies": {},
+ "readme": "ERROR: No README data found!",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/mhart/aws4.git"
+ },
+ "scripts": {
+ "test": "mocha ./test/fast.js ./test/slow.js -b -t 100s -R list"
+ },
+ "version": "1.2.1"
+}
diff --git a/node_modules/request/node_modules/hawk/README.md b/node_modules/request/node_modules/hawk/README.md
index 4aff23f3a..b92cd7c43 100755
--- a/node_modules/request/node_modules/hawk/README.md
+++ b/node_modules/request/node_modules/hawk/README.md
@@ -1,634 +1,634 @@
-![hawk Logo](https://raw.github.com/hueniverse/hawk/master/images/hawk.png)
-
-<img align="right" src="https://raw.github.com/hueniverse/hawk/master/images/logo.png" /> **Hawk** is an HTTP authentication scheme using a message authentication code (MAC) algorithm to provide partial
-HTTP request cryptographic verification. For more complex use cases such as access delegation, see [Oz](https://github.com/hueniverse/oz).
-
-Current version: **3.x**
-
-Note: 3.x and 2.x are the same exact protocol as 1.1. The version increments reflect changes in the node API.
-
-[![Build Status](https://secure.travis-ci.org/hueniverse/hawk.png)](http://travis-ci.org/hueniverse/hawk)
-
-# Table of Content
-
-- [**Introduction**](#introduction)
- - [Replay Protection](#replay-protection)
- - [Usage Example](#usage-example)
- - [Protocol Example](#protocol-example)
- - [Payload Validation](#payload-validation)
- - [Response Payload Validation](#response-payload-validation)
- - [Browser Support and Considerations](#browser-support-and-considerations)
-<p></p>
-- [**Single URI Authorization**](#single-uri-authorization)
- - [Usage Example](#bewit-usage-example)
-<p></p>
-- [**Security Considerations**](#security-considerations)
- - [MAC Keys Transmission](#mac-keys-transmission)
- - [Confidentiality of Requests](#confidentiality-of-requests)
- - [Spoofing by Counterfeit Servers](#spoofing-by-counterfeit-servers)
- - [Plaintext Storage of Credentials](#plaintext-storage-of-credentials)
- - [Entropy of Keys](#entropy-of-keys)
- - [Coverage Limitations](#coverage-limitations)
- - [Future Time Manipulation](#future-time-manipulation)
- - [Client Clock Poisoning](#client-clock-poisoning)
- - [Bewit Limitations](#bewit-limitations)
- - [Host Header Forgery](#host-header-forgery)
-<p></p>
-- [**Frequently Asked Questions**](#frequently-asked-questions)
-<p></p>
-- [**Implementations**](#implementations)
-- [**Acknowledgements**](#acknowledgements)
-
-# Introduction
-
-**Hawk** is an HTTP authentication scheme providing mechanisms for making authenticated HTTP requests with
-partial cryptographic verification of the request and response, covering the HTTP method, request URI, host,
-and optionally the request payload.
-
-Similar to the HTTP [Digest access authentication schemes](http://www.ietf.org/rfc/rfc2617.txt), **Hawk** uses a set of
-client credentials which include an identifier (e.g. username) and key (e.g. password). Likewise, just as with the Digest scheme,
-the key is never included in authenticated requests. Instead, it is used to calculate a request MAC value which is
-included in its place.
-
-However, **Hawk** has several differences from Digest. In particular, while both use a nonce to limit the possibility of
-replay attacks, in **Hawk** the client generates the nonce and uses it in combination with a timestamp, leading to less
-"chattiness" (interaction with the server).
-
-Also unlike Digest, this scheme is not intended to protect the key itself (the password in Digest) because
-the client and server must both have access to the key material in the clear.
-
-The primary design goals of this scheme are to:
-* simplify and improve HTTP authentication for services that are unwilling or unable to deploy TLS for all resources,
-* secure credentials against leakage (e.g., when the client uses some form of dynamic configuration to determine where
- to send an authenticated request), and
-* avoid the exposure of credentials sent to a malicious server over an unauthenticated secure channel due to client
- failure to validate the server's identity as part of its TLS handshake.
-
-In addition, **Hawk** supports a method for granting third-parties temporary access to individual resources using
-a query parameter called _bewit_ (in falconry, a leather strap used to attach a tracking device to the leg of a hawk).
-
-The **Hawk** scheme requires the establishment of a shared symmetric key between the client and the server,
-which is beyond the scope of this module. Typically, the shared credentials are established via an initial
-TLS-protected phase or derived from some other shared confidential information available to both the client
-and the server.
-
-
-## Replay Protection
-
-Without replay protection, an attacker can use a compromised (but otherwise valid and authenticated) request more
-than once, gaining access to a protected resource. To mitigate this, clients include both a nonce and a timestamp when
-making requests. This gives the server enough information to prevent replay attacks.
-
-The nonce is generated by the client, and is a string unique across all requests with the same timestamp and
-key identifier combination.
-
-The timestamp enables the server to restrict the validity period of the credentials where requests occuring afterwards
-are rejected. It also removes the need for the server to retain an unbounded number of nonce values for future checks.
-By default, **Hawk** uses a time window of 1 minute to allow for time skew between the client and server (which in
-practice translates to a maximum of 2 minutes as the skew can be positive or negative).
-
-Using a timestamp requires the client's clock to be in sync with the server's clock. **Hawk** requires both the client
-clock and the server clock to use NTP to ensure synchronization. However, given the limitations of some client types
-(e.g. browsers) to deploy NTP, the server provides the client with its current time (in seconds precision) in response
-to a bad timestamp.
-
-There is no expectation that the client will adjust its system clock to match the server (in fact, this would be a
-potential attack vector). Instead, the client only uses the server's time to calculate an offset used only
-for communications with that particular server. The protocol rewards clients with synchronized clocks by reducing
-the number of round trips required to authenticate the first request.
-
-
-## Usage Example
-
-Server code:
-
-```javascript
-var Http = require('http');
-var Hawk = require('hawk');
-
-
-// Credentials lookup function
-
-var credentialsFunc = function (id, callback) {
-
- var credentials = {
- key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
- algorithm: 'sha256',
- user: 'Steve'
- };
-
- return callback(null, credentials);
-};
-
-// Create HTTP server
-
-var handler = function (req, res) {
-
- // Authenticate incoming request
-
- Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
-
- // Prepare response
-
- var payload = (!err ? 'Hello ' + credentials.user + ' ' + artifacts.ext : 'Shoosh!');
- var headers = { 'Content-Type': 'text/plain' };
-
- // Generate Server-Authorization response header
-
- var header = Hawk.server.header(credentials, artifacts, { payload: payload, contentType: headers['Content-Type'] });
- headers['Server-Authorization'] = header;
-
- // Send the response back
-
- res.writeHead(!err ? 200 : 401, headers);
- res.end(payload);
- });
-};
-
-// Start server
-
-Http.createServer(handler).listen(8000, 'example.com');
-```
-
-Client code:
-
-```javascript
-var Request = require('request');
-var Hawk = require('hawk');
-
-
-// Client credentials
-
-var credentials = {
- id: 'dh37fgj492je',
- key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
- algorithm: 'sha256'
-}
-
-// Request options
-
-var requestOptions = {
- uri: 'http://example.com:8000/resource/1?b=1&a=2',
- method: 'GET',
- headers: {}
-};
-
-// Generate Authorization request header
-
-var header = Hawk.client.header('http://example.com:8000/resource/1?b=1&a=2', 'GET', { credentials: credentials, ext: 'some-app-data' });
-requestOptions.headers.Authorization = header.field;
-
-// Send authenticated request
-
-Request(requestOptions, function (error, response, body) {
-
- // Authenticate the server's response
-
- var isValid = Hawk.client.authenticate(response, credentials, header.artifacts, { payload: body });
-
- // Output results
-
- console.log(response.statusCode + ': ' + body + (isValid ? ' (valid)' : ' (invalid)'));
-});
-```
-
-**Hawk** utilized the [**SNTP**](https://github.com/hueniverse/sntp) module for time sync management. By default, the local
-machine time is used. To automatically retrieve and synchronice the clock within the application, use the SNTP 'start()' method.
-
-```javascript
-Hawk.sntp.start();
-```
-
-
-## Protocol Example
-
-The client attempts to access a protected resource without authentication, sending the following HTTP request to
-the resource server:
-
-```
-GET /resource/1?b=1&a=2 HTTP/1.1
-Host: example.com:8000
-```
-
-The resource server returns an authentication challenge.
-
-```
-HTTP/1.1 401 Unauthorized
-WWW-Authenticate: Hawk
-```
-
-The client has previously obtained a set of **Hawk** credentials for accessing resources on the "http://example.com/"
-server. The **Hawk** credentials issued to the client include the following attributes:
-
-* Key identifier: dh37fgj492je
-* Key: werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn
-* Algorithm: sha256
-
-The client generates the authentication header by calculating a timestamp (e.g. the number of seconds since January 1,
-1970 00:00:00 GMT), generating a nonce, and constructing the normalized request string (each value followed by a newline
-character):
-
-```
-hawk.1.header
-1353832234
-j4h3g2
-GET
-/resource/1?b=1&a=2
-example.com
-8000
-
-some-app-ext-data
-
-```
-
-The request MAC is calculated using HMAC with the specified hash algorithm "sha256" and the key over the normalized request string.
-The result is base64-encoded to produce the request MAC:
-
-```
-6R4rV5iE+NPoym+WwjeHzjAGXUtLNIxmo1vpMofpLAE=
-```
-
-The client includes the **Hawk** key identifier, timestamp, nonce, application specific data, and request MAC with the request using
-the HTTP `Authorization` request header field:
-
-```
-GET /resource/1?b=1&a=2 HTTP/1.1
-Host: example.com:8000
-Authorization: Hawk id="dh37fgj492je", ts="1353832234", nonce="j4h3g2", ext="some-app-ext-data", mac="6R4rV5iE+NPoym+WwjeHzjAGXUtLNIxmo1vpMofpLAE="
-```
-
-The server validates the request by calculating the request MAC again based on the request received and verifies the validity
-and scope of the **Hawk** credentials. If valid, the server responds with the requested resource.
-
-
-### Payload Validation
-
-**Hawk** provides optional payload validation. When generating the authentication header, the client calculates a payload hash
-using the specified hash algorithm. The hash is calculated over the concatenated value of (each followed by a newline character):
-* `hawk.1.payload`
-* the content-type in lowercase, without any parameters (e.g. `application/json`)
-* the request payload prior to any content encoding (the exact representation requirements should be specified by the server for payloads other than simple single-part ascii to ensure interoperability)
-
-For example:
-
-* Payload: `Thank you for flying Hawk`
-* Content Type: `text/plain`
-* Hash (sha256): `Yi9LfIIFRtBEPt74PVmbTF/xVAwPn7ub15ePICfgnuY=`
-
-Results in the following input to the payload hash function (newline terminated values):
-
-```
-hawk.1.payload
-text/plain
-Thank you for flying Hawk
-
-```
-
-Which produces the following hash value:
-
-```
-Yi9LfIIFRtBEPt74PVmbTF/xVAwPn7ub15ePICfgnuY=
-```
-
-The client constructs the normalized request string (newline terminated values):
-
-```
-hawk.1.header
-1353832234
-j4h3g2
-POST
-/resource/1?a=1&b=2
-example.com
-8000
-Yi9LfIIFRtBEPt74PVmbTF/xVAwPn7ub15ePICfgnuY=
-some-app-ext-data
-
-```
-
-Then calculates the request MAC and includes the **Hawk** key identifier, timestamp, nonce, payload hash, application specific data,
-and request MAC, with the request using the HTTP `Authorization` request header field:
-
-```
-POST /resource/1?a=1&b=2 HTTP/1.1
-Host: example.com:8000
-Authorization: Hawk id="dh37fgj492je", ts="1353832234", nonce="j4h3g2", hash="Yi9LfIIFRtBEPt74PVmbTF/xVAwPn7ub15ePICfgnuY=", ext="some-app-ext-data", mac="aSe1DERmZuRl3pI36/9BdZmnErTw3sNzOOAUlfeKjVw="
-```
-
-It is up to the server if and when it validates the payload for any given request, based solely on it's security policy
-and the nature of the data included.
-
-If the payload is available at the time of authentication, the server uses the hash value provided by the client to construct
-the normalized string and validates the MAC. If the MAC is valid, the server calculates the payload hash and compares the value
-with the provided payload hash in the header. In many cases, checking the MAC first is faster than calculating the payload hash.
-
-However, if the payload is not available at authentication time (e.g. too large to fit in memory, streamed elsewhere, or processed
-at a different stage in the application), the server may choose to defer payload validation for later by retaining the hash value
-provided by the client after validating the MAC.
-
-It is important to note that MAC validation does not mean the hash value provided by the client is valid, only that the value
-included in the header was not modified. Without calculating the payload hash on the server and comparing it to the value provided
-by the client, the payload may be modified by an attacker.
-
-
-## Response Payload Validation
-
-**Hawk** provides partial response payload validation. The server includes the `Server-Authorization` response header which enables the
-client to authenticate the response and ensure it is talking to the right server. **Hawk** defines the HTTP `Server-Authorization` header
-as a response header using the exact same syntax as the `Authorization` request header field.
-
-The header is contructed using the same process as the client's request header. The server uses the same credentials and other
-artifacts provided by the client to constructs the normalized request string. The `ext` and `hash` values are replaced with
-new values based on the server response. The rest as identical to those used by the client.
-
-The result MAC digest is included with the optional `hash` and `ext` values:
-
-```
-Server-Authorization: Hawk mac="XIJRsMl/4oL+nn+vKoeVZPdCHXB4yJkNnBbTbHFZUYE=", hash="f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=", ext="response-specific"
-```
-
-
-## Browser Support and Considerations
-
-A browser script is provided for including using a `<script>` tag in [lib/browser.js](/lib/browser.js). It's also a [component](http://component.io/hueniverse/hawk).
-
-**Hawk** relies on the _Server-Authorization_ and _WWW-Authenticate_ headers in its response to communicate with the client.
-Therefore, in case of CORS requests, it is important to consider sending _Access-Control-Expose-Headers_ with the value
-_"WWW-Authenticate, Server-Authorization"_ on each response from your server. As explained in the
-[specifications](http://www.w3.org/TR/cors/#access-control-expose-headers-response-header), it will indicate that these headers
-can safely be accessed by the client (using getResponseHeader() on the XmlHttpRequest object). Otherwise you will be met with a
-["simple response header"](http://www.w3.org/TR/cors/#simple-response-header) which excludes these fields and would prevent the
-Hawk client from authenticating the requests.You can read more about the why and how in this
-[article](http://www.html5rocks.com/en/tutorials/cors/#toc-adding-cors-support-to-the-server)
-
-
-# Single URI Authorization
-
-There are cases in which limited and short-term access to a protected resource is granted to a third party which does not
-have access to the shared credentials. For example, displaying a protected image on a web page accessed by anyone. **Hawk**
-provides limited support for such URIs in the form of a _bewit_ - a URI query parameter appended to the request URI which contains
-the necessary credentials to authenticate the request.
-
-Because of the significant security risks involved in issuing such access, bewit usage is purposely limited only to GET requests
-and for a finite period of time. Both the client and server can issue bewit credentials, however, the server should not use the same
-credentials as the client to maintain clear traceability as to who issued which credentials.
-
-In order to simplify implementation, bewit credentials do not support single-use policy and can be replayed multiple times within
-the granted access timeframe.
-
-
-## Bewit Usage Example
-
-Server code:
-
-```javascript
-var Http = require('http');
-var Hawk = require('hawk');
-
-
-// Credentials lookup function
-
-var credentialsFunc = function (id, callback) {
-
- var credentials = {
- key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
- algorithm: 'sha256'
- };
-
- return callback(null, credentials);
-};
-
-// Create HTTP server
-
-var handler = function (req, res) {
-
- Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
-
- res.writeHead(!err ? 200 : 401, { 'Content-Type': 'text/plain' });
- res.end(!err ? 'Access granted' : 'Shoosh!');
- });
-};
-
-Http.createServer(handler).listen(8000, 'example.com');
-```
-
-Bewit code generation:
-
-```javascript
-var Request = require('request');
-var Hawk = require('hawk');
-
-
-// Client credentials
-
-var credentials = {
- id: 'dh37fgj492je',
- key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
- algorithm: 'sha256'
-}
-
-// Generate bewit
-
-var duration = 60 * 5; // 5 Minutes
-var bewit = Hawk.uri.getBewit('http://example.com:8080/resource/1?b=1&a=2', { credentials: credentials, ttlSec: duration, ext: 'some-app-data' });
-var uri = 'http://example.com:8000/resource/1?b=1&a=2' + '&bewit=' + bewit;
-```
-
-
-# Security Considerations
-
-The greatest sources of security risks are usually found not in **Hawk** but in the policies and procedures surrounding its use.
-Implementers are strongly encouraged to assess how this module addresses their security requirements. This section includes
-an incomplete list of security considerations that must be reviewed and understood before deploying **Hawk** on the server.
-Many of the protections provided in **Hawk** depends on whether and how they are used.
-
-### MAC Keys Transmission
-
-**Hawk** does not provide any mechanism for obtaining or transmitting the set of shared credentials required. Any mechanism used
-to obtain **Hawk** credentials must ensure that these transmissions are protected using transport-layer mechanisms such as TLS.
-
-### Confidentiality of Requests
-
-While **Hawk** provides a mechanism for verifying the integrity of HTTP requests, it provides no guarantee of request
-confidentiality. Unless other precautions are taken, eavesdroppers will have full access to the request content. Servers should
-carefully consider the types of data likely to be sent as part of such requests, and employ transport-layer security mechanisms
-to protect sensitive resources.
-
-### Spoofing by Counterfeit Servers
-
-**Hawk** provides limited verification of the server authenticity. When receiving a response back from the server, the server
-may choose to include a response `Server-Authorization` header which the client can use to verify the response. However, it is up to
-the server to determine when such measure is included, to up to the client to enforce that policy.
-
-A hostile party could take advantage of this by intercepting the client's requests and returning misleading or otherwise
-incorrect responses. Service providers should consider such attacks when developing services using this protocol, and should
-require transport-layer security for any requests where the authenticity of the resource server or of server responses is an issue.
-
-### Plaintext Storage of Credentials
-
-The **Hawk** key functions the same way passwords do in traditional authentication systems. In order to compute the request MAC,
-the server must have access to the key in plaintext form. This is in contrast, for example, to modern operating systems, which
-store only a one-way hash of user credentials.
-
-If an attacker were to gain access to these keys - or worse, to the server's database of all such keys - he or she would be able
-to perform any action on behalf of any resource owner. Accordingly, it is critical that servers protect these keys from unauthorized
-access.
-
-### Entropy of Keys
-
-Unless a transport-layer security protocol is used, eavesdroppers will have full access to authenticated requests and request
-MAC values, and will thus be able to mount offline brute-force attacks to recover the key used. Servers should be careful to
-assign keys which are long enough, and random enough, to resist such attacks for at least the length of time that the **Hawk**
-credentials are valid.
-
-For example, if the credentials are valid for two weeks, servers should ensure that it is not possible to mount a brute force
-attack that recovers the key in less than two weeks. Of course, servers are urged to err on the side of caution, and use the
-longest key reasonable.
-
-It is equally important that the pseudo-random number generator (PRNG) used to generate these keys be of sufficiently high
-quality. Many PRNG implementations generate number sequences that may appear to be random, but which nevertheless exhibit
-patterns or other weaknesses which make cryptanalysis or brute force attacks easier. Implementers should be careful to use
-cryptographically secure PRNGs to avoid these problems.
-
-### Coverage Limitations
-
-The request MAC only covers the HTTP `Host` header and optionally the `Content-Type` header. It does not cover any other headers
-which can often affect how the request body is interpreted by the server. If the server behavior is influenced by the presence
-or value of such headers, an attacker can manipulate the request headers without being detected. Implementers should use the
-`ext` feature to pass application-specific information via the `Authorization` header which is protected by the request MAC.
-
-The response authentication, when performed, only covers the response payload, content-type, and the request information
-provided by the client in it's request (method, resource, timestamp, nonce, etc.). It does not cover the HTTP status code or
-any other response header field (e.g. Location) which can affect the client's behaviour.
-
-### Future Time Manipulation
-
-The protocol relies on a clock sync between the client and server. To accomplish this, the server informs the client of its
-current time when an invalid timestamp is received.
-
-If an attacker is able to manipulate this information and cause the client to use an incorrect time, it would be able to cause
-the client to generate authenticated requests using time in the future. Such requests will fail when sent by the client, and will
-not likely leave a trace on the server (given the common implementation of nonce, if at all enforced). The attacker will then
-be able to replay the request at the correct time without detection.
-
-The client must only use the time information provided by the server if:
-* it was delivered over a TLS connection and the server identity has been verified, or
-* the `tsm` MAC digest calculated using the same client credentials over the timestamp has been verified.
-
-### Client Clock Poisoning
-
-When receiving a request with a bad timestamp, the server provides the client with its current time. The client must never use
-the time received from the server to adjust its own clock, and must only use it to calculate an offset for communicating with
-that particular server.
-
-### Bewit Limitations
-
-Special care must be taken when issuing bewit credentials to third parties. Bewit credentials are valid until expiration and cannot
-be revoked or limited without using other means. Whatever resource they grant access to will be completely exposed to anyone with
-access to the bewit credentials which act as bearer credentials for that particular resource. While bewit usage is limited to GET
-requests only and therefore cannot be used to perform transactions or change server state, it can still be used to expose private
-and sensitive information.
-
-### Host Header Forgery
-
-Hawk validates the incoming request MAC against the incoming HTTP Host header. However, unless the optional `host` and `port`
-options are used with `server.authenticate()`, a malicous client can mint new host names pointing to the server's IP address and
-use that to craft an attack by sending a valid request that's meant for another hostname than the one used by the server. Server
-implementors must manually verify that the host header received matches their expectation (or use the options mentioned above).
-
-# Frequently Asked Questions
-
-### Where is the protocol specification?
-
-If you are looking for some prose explaining how all this works, **this is it**. **Hawk** is being developed as an open source
-project instead of a standard. In other words, the [code](/hueniverse/hawk/tree/master/lib) is the specification. Not sure about
-something? Open an issue!
-
-### Is it done?
-
-As of version 0.10.0, **Hawk** is feature-complete. However, until this module reaches version 1.0.0 it is considered experimental
-and is likely to change. This also means your feedback and contribution are very welcome. Feel free to open issues with questions
-and suggestions.
-
-### Where can I find **Hawk** implementations in other languages?
-
-**Hawk**'s only reference implementation is provided in JavaScript as a node.js module. However, it has been ported to other languages.
-The full list is maintained [here](https://github.com/hueniverse/hawk/issues?labels=port&state=closed). Please add an issue if you are
-working on another port. A cross-platform test-suite is in the works.
-
-### Why isn't the algorithm part of the challenge or dynamically negotiated?
-
-The algorithm used is closely related to the key issued as different algorithms require different key sizes (and other
-requirements). While some keys can be used for multiple algorithm, the protocol is designed to closely bind the key and algorithm
-together as part of the issued credentials.
-
-### Why is Host and Content-Type the only headers covered by the request MAC?
-
-It is really hard to include other headers. Headers can be changed by proxies and other intermediaries and there is no
-well-established way to normalize them. Many platforms change the case of header field names and values. The only
-straight-forward solution is to include the headers in some blob (say, base64 encoded JSON) and include that with the request,
-an approach taken by JWT and other such formats. However, that design violates the HTTP header boundaries, repeats information,
-and introduces other security issues because firewalls will not be aware of these "hidden" headers. In addition, any information
-repeated must be compared to the duplicated information in the header and therefore only moves the problem elsewhere.
-
-### Why not just use HTTP Digest?
-
-Digest requires pre-negotiation to establish a nonce. This means you can't just make a request - you must first send
-a protocol handshake to the server. This pattern has become unacceptable for most web services, especially mobile
-where extra round-trip are costly.
-
-### Why bother with all this nonce and timestamp business?
-
-**Hawk** is an attempt to find a reasonable, practical compromise between security and usability. OAuth 1.0 got timestamp
-and nonces halfway right but failed when it came to scalability and consistent developer experience. **Hawk** addresses
-it by requiring the client to sync its clock, but provides it with tools to accomplish it.
-
-In general, replay protection is a matter of application-specific threat model. It is less of an issue on a TLS-protected
-system where the clients are implemented using best practices and are under the control of the server. Instead of dropping
-replay protection, **Hawk** offers a required time window and an optional nonce verification. Together, it provides developers
-with the ability to decide how to enforce their security policy without impacting the client's implementation.
-
-### What are `app` and `dlg` in the authorization header and normalized mac string?
-
-The original motivation for **Hawk** was to replace the OAuth 1.0 use cases. This included both a simple client-server mode which
-this module is specifically designed for, and a delegated access mode which is being developed separately in
-[Oz](https://github.com/hueniverse/oz). In addition to the **Hawk** use cases, Oz requires another attribute: the application id `app`.
-This provides binding between the credentials and the application in a way that prevents an attacker from tricking an application
-to use credentials issued to someone else. It also has an optional 'delegated-by' attribute `dlg` which is the application id of the
-application the credentials were directly issued to. The goal of these two additions is to allow Oz to utilize **Hawk** directly,
-but with the additional security of delegated credentials.
-
-### What is the purpose of the static strings used in each normalized MAC input?
-
-When calculating a hash or MAC, a static prefix (tag) is added. The prefix is used to prevent MAC values from being
-used or reused for a purpose other than what they were created for (i.e. prevents switching MAC values between a request,
-response, and a bewit use cases). It also protects against exploits created after a potential change in how the protocol
-creates the normalized string. For example, if a future version would switch the order of nonce and timestamp, it
-can create an exploit opportunity for cases where the nonce is similar in format to a timestamp.
-
-### Does **Hawk** have anything to do with OAuth?
-
-Short answer: no.
-
-**Hawk** was originally proposed as the OAuth MAC Token specification. However, the OAuth working group in its consistent
-incompetence failed to produce a final, usable solution to address one of the most popular use cases of OAuth 1.0 - using it
-to authenticate simple client-server transactions (i.e. two-legged). As you can guess, the OAuth working group is still hard
-at work to produce more garbage.
-
-**Hawk** provides a simple HTTP authentication scheme for making client-server requests. It does not address the OAuth use case
-of delegating access to a third party. If you are looking for an OAuth alternative, check out [Oz](https://github.com/hueniverse/oz).
-
-# Implementations
-
-- [Logibit Hawk in F#/.Net](https://github.com/logibit/logibit.hawk/)
-- [Tent Hawk in Ruby](https://github.com/tent/hawk-ruby)
-- [Wealdtech in Java](https://github.com/wealdtech/hawk)
-- [Kumar's Mohawk in Python](https://github.com/kumar303/mohawk/)
-
-# Acknowledgements
-
-**Hawk** is a derivative work of the [HTTP MAC Authentication Scheme](http://tools.ietf.org/html/draft-hammer-oauth-v2-mac-token-05) proposal
-co-authored by Ben Adida, Adam Barth, and Eran Hammer, which in turn was based on the OAuth 1.0 community specification.
-
-Special thanks to Ben Laurie for his always insightful feedback and advice.
-
-The **Hawk** logo was created by [Chris Carrasco](http://chriscarrasco.com).
+![hawk Logo](https://raw.github.com/hueniverse/hawk/master/images/hawk.png)
+
+<img align="right" src="https://raw.github.com/hueniverse/hawk/master/images/logo.png" /> **Hawk** is an HTTP authentication scheme using a message authentication code (MAC) algorithm to provide partial
+HTTP request cryptographic verification. For more complex use cases such as access delegation, see [Oz](https://github.com/hueniverse/oz).
+
+Current version: **3.x**
+
+Note: 3.x and 2.x are the same exact protocol as 1.1. The version increments reflect changes in the node API.
+
+[![Build Status](https://secure.travis-ci.org/hueniverse/hawk.png)](http://travis-ci.org/hueniverse/hawk)
+
+# Table of Content
+
+- [**Introduction**](#introduction)
+ - [Replay Protection](#replay-protection)
+ - [Usage Example](#usage-example)
+ - [Protocol Example](#protocol-example)
+ - [Payload Validation](#payload-validation)
+ - [Response Payload Validation](#response-payload-validation)
+ - [Browser Support and Considerations](#browser-support-and-considerations)
+<p></p>
+- [**Single URI Authorization**](#single-uri-authorization)
+ - [Usage Example](#bewit-usage-example)
+<p></p>
+- [**Security Considerations**](#security-considerations)
+ - [MAC Keys Transmission](#mac-keys-transmission)
+ - [Confidentiality of Requests](#confidentiality-of-requests)
+ - [Spoofing by Counterfeit Servers](#spoofing-by-counterfeit-servers)
+ - [Plaintext Storage of Credentials](#plaintext-storage-of-credentials)
+ - [Entropy of Keys](#entropy-of-keys)
+ - [Coverage Limitations](#coverage-limitations)
+ - [Future Time Manipulation](#future-time-manipulation)
+ - [Client Clock Poisoning](#client-clock-poisoning)
+ - [Bewit Limitations](#bewit-limitations)
+ - [Host Header Forgery](#host-header-forgery)
+<p></p>
+- [**Frequently Asked Questions**](#frequently-asked-questions)
+<p></p>
+- [**Implementations**](#implementations)
+- [**Acknowledgements**](#acknowledgements)
+
+# Introduction
+
+**Hawk** is an HTTP authentication scheme providing mechanisms for making authenticated HTTP requests with
+partial cryptographic verification of the request and response, covering the HTTP method, request URI, host,
+and optionally the request payload.
+
+Similar to the HTTP [Digest access authentication schemes](http://www.ietf.org/rfc/rfc2617.txt), **Hawk** uses a set of
+client credentials which include an identifier (e.g. username) and key (e.g. password). Likewise, just as with the Digest scheme,
+the key is never included in authenticated requests. Instead, it is used to calculate a request MAC value which is
+included in its place.
+
+However, **Hawk** has several differences from Digest. In particular, while both use a nonce to limit the possibility of
+replay attacks, in **Hawk** the client generates the nonce and uses it in combination with a timestamp, leading to less
+"chattiness" (interaction with the server).
+
+Also unlike Digest, this scheme is not intended to protect the key itself (the password in Digest) because
+the client and server must both have access to the key material in the clear.
+
+The primary design goals of this scheme are to:
+* simplify and improve HTTP authentication for services that are unwilling or unable to deploy TLS for all resources,
+* secure credentials against leakage (e.g., when the client uses some form of dynamic configuration to determine where
+ to send an authenticated request), and
+* avoid the exposure of credentials sent to a malicious server over an unauthenticated secure channel due to client
+ failure to validate the server's identity as part of its TLS handshake.
+
+In addition, **Hawk** supports a method for granting third-parties temporary access to individual resources using
+a query parameter called _bewit_ (in falconry, a leather strap used to attach a tracking device to the leg of a hawk).
+
+The **Hawk** scheme requires the establishment of a shared symmetric key between the client and the server,
+which is beyond the scope of this module. Typically, the shared credentials are established via an initial
+TLS-protected phase or derived from some other shared confidential information available to both the client
+and the server.
+
+
+## Replay Protection
+
+Without replay protection, an attacker can use a compromised (but otherwise valid and authenticated) request more
+than once, gaining access to a protected resource. To mitigate this, clients include both a nonce and a timestamp when
+making requests. This gives the server enough information to prevent replay attacks.
+
+The nonce is generated by the client, and is a string unique across all requests with the same timestamp and
+key identifier combination.
+
+The timestamp enables the server to restrict the validity period of the credentials where requests occuring afterwards
+are rejected. It also removes the need for the server to retain an unbounded number of nonce values for future checks.
+By default, **Hawk** uses a time window of 1 minute to allow for time skew between the client and server (which in
+practice translates to a maximum of 2 minutes as the skew can be positive or negative).
+
+Using a timestamp requires the client's clock to be in sync with the server's clock. **Hawk** requires both the client
+clock and the server clock to use NTP to ensure synchronization. However, given the limitations of some client types
+(e.g. browsers) to deploy NTP, the server provides the client with its current time (in seconds precision) in response
+to a bad timestamp.
+
+There is no expectation that the client will adjust its system clock to match the server (in fact, this would be a
+potential attack vector). Instead, the client only uses the server's time to calculate an offset used only
+for communications with that particular server. The protocol rewards clients with synchronized clocks by reducing
+the number of round trips required to authenticate the first request.
+
+
+## Usage Example
+
+Server code:
+
+```javascript
+var Http = require('http');
+var Hawk = require('hawk');
+
+
+// Credentials lookup function
+
+var credentialsFunc = function (id, callback) {
+
+ var credentials = {
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: 'sha256',
+ user: 'Steve'
+ };
+
+ return callback(null, credentials);
+};
+
+// Create HTTP server
+
+var handler = function (req, res) {
+
+ // Authenticate incoming request
+
+ Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
+
+ // Prepare response
+
+ var payload = (!err ? 'Hello ' + credentials.user + ' ' + artifacts.ext : 'Shoosh!');
+ var headers = { 'Content-Type': 'text/plain' };
+
+ // Generate Server-Authorization response header
+
+ var header = Hawk.server.header(credentials, artifacts, { payload: payload, contentType: headers['Content-Type'] });
+ headers['Server-Authorization'] = header;
+
+ // Send the response back
+
+ res.writeHead(!err ? 200 : 401, headers);
+ res.end(payload);
+ });
+};
+
+// Start server
+
+Http.createServer(handler).listen(8000, 'example.com');
+```
+
+Client code:
+
+```javascript
+var Request = require('request');
+var Hawk = require('hawk');
+
+
+// Client credentials
+
+var credentials = {
+ id: 'dh37fgj492je',
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: 'sha256'
+}
+
+// Request options
+
+var requestOptions = {
+ uri: 'http://example.com:8000/resource/1?b=1&a=2',
+ method: 'GET',
+ headers: {}
+};
+
+// Generate Authorization request header
+
+var header = Hawk.client.header('http://example.com:8000/resource/1?b=1&a=2', 'GET', { credentials: credentials, ext: 'some-app-data' });
+requestOptions.headers.Authorization = header.field;
+
+// Send authenticated request
+
+Request(requestOptions, function (error, response, body) {
+
+ // Authenticate the server's response
+
+ var isValid = Hawk.client.authenticate(response, credentials, header.artifacts, { payload: body });
+
+ // Output results
+
+ console.log(response.statusCode + ': ' + body + (isValid ? ' (valid)' : ' (invalid)'));
+});
+```
+
+**Hawk** utilized the [**SNTP**](https://github.com/hueniverse/sntp) module for time sync management. By default, the local
+machine time is used. To automatically retrieve and synchronice the clock within the application, use the SNTP 'start()' method.
+
+```javascript
+Hawk.sntp.start();
+```
+
+
+## Protocol Example
+
+The client attempts to access a protected resource without authentication, sending the following HTTP request to
+the resource server:
+
+```
+GET /resource/1?b=1&a=2 HTTP/1.1
+Host: example.com:8000
+```
+
+The resource server returns an authentication challenge.
+
+```
+HTTP/1.1 401 Unauthorized
+WWW-Authenticate: Hawk
+```
+
+The client has previously obtained a set of **Hawk** credentials for accessing resources on the "http://example.com/"
+server. The **Hawk** credentials issued to the client include the following attributes:
+
+* Key identifier: dh37fgj492je
+* Key: werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn
+* Algorithm: sha256
+
+The client generates the authentication header by calculating a timestamp (e.g. the number of seconds since January 1,
+1970 00:00:00 GMT), generating a nonce, and constructing the normalized request string (each value followed by a newline
+character):
+
+```
+hawk.1.header
+1353832234
+j4h3g2
+GET
+/resource/1?b=1&a=2
+example.com
+8000
+
+some-app-ext-data
+
+```
+
+The request MAC is calculated using HMAC with the specified hash algorithm "sha256" and the key over the normalized request string.
+The result is base64-encoded to produce the request MAC:
+
+```
+6R4rV5iE+NPoym+WwjeHzjAGXUtLNIxmo1vpMofpLAE=
+```
+
+The client includes the **Hawk** key identifier, timestamp, nonce, application specific data, and request MAC with the request using
+the HTTP `Authorization` request header field:
+
+```
+GET /resource/1?b=1&a=2 HTTP/1.1
+Host: example.com:8000
+Authorization: Hawk id="dh37fgj492je", ts="1353832234", nonce="j4h3g2", ext="some-app-ext-data", mac="6R4rV5iE+NPoym+WwjeHzjAGXUtLNIxmo1vpMofpLAE="
+```
+
+The server validates the request by calculating the request MAC again based on the request received and verifies the validity
+and scope of the **Hawk** credentials. If valid, the server responds with the requested resource.
+
+
+### Payload Validation
+
+**Hawk** provides optional payload validation. When generating the authentication header, the client calculates a payload hash
+using the specified hash algorithm. The hash is calculated over the concatenated value of (each followed by a newline character):
+* `hawk.1.payload`
+* the content-type in lowercase, without any parameters (e.g. `application/json`)
+* the request payload prior to any content encoding (the exact representation requirements should be specified by the server for payloads other than simple single-part ascii to ensure interoperability)
+
+For example:
+
+* Payload: `Thank you for flying Hawk`
+* Content Type: `text/plain`
+* Hash (sha256): `Yi9LfIIFRtBEPt74PVmbTF/xVAwPn7ub15ePICfgnuY=`
+
+Results in the following input to the payload hash function (newline terminated values):
+
+```
+hawk.1.payload
+text/plain
+Thank you for flying Hawk
+
+```
+
+Which produces the following hash value:
+
+```
+Yi9LfIIFRtBEPt74PVmbTF/xVAwPn7ub15ePICfgnuY=
+```
+
+The client constructs the normalized request string (newline terminated values):
+
+```
+hawk.1.header
+1353832234
+j4h3g2
+POST
+/resource/1?a=1&b=2
+example.com
+8000
+Yi9LfIIFRtBEPt74PVmbTF/xVAwPn7ub15ePICfgnuY=
+some-app-ext-data
+
+```
+
+Then calculates the request MAC and includes the **Hawk** key identifier, timestamp, nonce, payload hash, application specific data,
+and request MAC, with the request using the HTTP `Authorization` request header field:
+
+```
+POST /resource/1?a=1&b=2 HTTP/1.1
+Host: example.com:8000
+Authorization: Hawk id="dh37fgj492je", ts="1353832234", nonce="j4h3g2", hash="Yi9LfIIFRtBEPt74PVmbTF/xVAwPn7ub15ePICfgnuY=", ext="some-app-ext-data", mac="aSe1DERmZuRl3pI36/9BdZmnErTw3sNzOOAUlfeKjVw="
+```
+
+It is up to the server if and when it validates the payload for any given request, based solely on it's security policy
+and the nature of the data included.
+
+If the payload is available at the time of authentication, the server uses the hash value provided by the client to construct
+the normalized string and validates the MAC. If the MAC is valid, the server calculates the payload hash and compares the value
+with the provided payload hash in the header. In many cases, checking the MAC first is faster than calculating the payload hash.
+
+However, if the payload is not available at authentication time (e.g. too large to fit in memory, streamed elsewhere, or processed
+at a different stage in the application), the server may choose to defer payload validation for later by retaining the hash value
+provided by the client after validating the MAC.
+
+It is important to note that MAC validation does not mean the hash value provided by the client is valid, only that the value
+included in the header was not modified. Without calculating the payload hash on the server and comparing it to the value provided
+by the client, the payload may be modified by an attacker.
+
+
+## Response Payload Validation
+
+**Hawk** provides partial response payload validation. The server includes the `Server-Authorization` response header which enables the
+client to authenticate the response and ensure it is talking to the right server. **Hawk** defines the HTTP `Server-Authorization` header
+as a response header using the exact same syntax as the `Authorization` request header field.
+
+The header is contructed using the same process as the client's request header. The server uses the same credentials and other
+artifacts provided by the client to constructs the normalized request string. The `ext` and `hash` values are replaced with
+new values based on the server response. The rest as identical to those used by the client.
+
+The result MAC digest is included with the optional `hash` and `ext` values:
+
+```
+Server-Authorization: Hawk mac="XIJRsMl/4oL+nn+vKoeVZPdCHXB4yJkNnBbTbHFZUYE=", hash="f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=", ext="response-specific"
+```
+
+
+## Browser Support and Considerations
+
+A browser script is provided for including using a `<script>` tag in [lib/browser.js](/lib/browser.js). It's also a [component](http://component.io/hueniverse/hawk).
+
+**Hawk** relies on the _Server-Authorization_ and _WWW-Authenticate_ headers in its response to communicate with the client.
+Therefore, in case of CORS requests, it is important to consider sending _Access-Control-Expose-Headers_ with the value
+_"WWW-Authenticate, Server-Authorization"_ on each response from your server. As explained in the
+[specifications](http://www.w3.org/TR/cors/#access-control-expose-headers-response-header), it will indicate that these headers
+can safely be accessed by the client (using getResponseHeader() on the XmlHttpRequest object). Otherwise you will be met with a
+["simple response header"](http://www.w3.org/TR/cors/#simple-response-header) which excludes these fields and would prevent the
+Hawk client from authenticating the requests.You can read more about the why and how in this
+[article](http://www.html5rocks.com/en/tutorials/cors/#toc-adding-cors-support-to-the-server)
+
+
+# Single URI Authorization
+
+There are cases in which limited and short-term access to a protected resource is granted to a third party which does not
+have access to the shared credentials. For example, displaying a protected image on a web page accessed by anyone. **Hawk**
+provides limited support for such URIs in the form of a _bewit_ - a URI query parameter appended to the request URI which contains
+the necessary credentials to authenticate the request.
+
+Because of the significant security risks involved in issuing such access, bewit usage is purposely limited only to GET requests
+and for a finite period of time. Both the client and server can issue bewit credentials, however, the server should not use the same
+credentials as the client to maintain clear traceability as to who issued which credentials.
+
+In order to simplify implementation, bewit credentials do not support single-use policy and can be replayed multiple times within
+the granted access timeframe.
+
+
+## Bewit Usage Example
+
+Server code:
+
+```javascript
+var Http = require('http');
+var Hawk = require('hawk');
+
+
+// Credentials lookup function
+
+var credentialsFunc = function (id, callback) {
+
+ var credentials = {
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: 'sha256'
+ };
+
+ return callback(null, credentials);
+};
+
+// Create HTTP server
+
+var handler = function (req, res) {
+
+ Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
+
+ res.writeHead(!err ? 200 : 401, { 'Content-Type': 'text/plain' });
+ res.end(!err ? 'Access granted' : 'Shoosh!');
+ });
+};
+
+Http.createServer(handler).listen(8000, 'example.com');
+```
+
+Bewit code generation:
+
+```javascript
+var Request = require('request');
+var Hawk = require('hawk');
+
+
+// Client credentials
+
+var credentials = {
+ id: 'dh37fgj492je',
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: 'sha256'
+}
+
+// Generate bewit
+
+var duration = 60 * 5; // 5 Minutes
+var bewit = Hawk.uri.getBewit('http://example.com:8080/resource/1?b=1&a=2', { credentials: credentials, ttlSec: duration, ext: 'some-app-data' });
+var uri = 'http://example.com:8000/resource/1?b=1&a=2' + '&bewit=' + bewit;
+```
+
+
+# Security Considerations
+
+The greatest sources of security risks are usually found not in **Hawk** but in the policies and procedures surrounding its use.
+Implementers are strongly encouraged to assess how this module addresses their security requirements. This section includes
+an incomplete list of security considerations that must be reviewed and understood before deploying **Hawk** on the server.
+Many of the protections provided in **Hawk** depends on whether and how they are used.
+
+### MAC Keys Transmission
+
+**Hawk** does not provide any mechanism for obtaining or transmitting the set of shared credentials required. Any mechanism used
+to obtain **Hawk** credentials must ensure that these transmissions are protected using transport-layer mechanisms such as TLS.
+
+### Confidentiality of Requests
+
+While **Hawk** provides a mechanism for verifying the integrity of HTTP requests, it provides no guarantee of request
+confidentiality. Unless other precautions are taken, eavesdroppers will have full access to the request content. Servers should
+carefully consider the types of data likely to be sent as part of such requests, and employ transport-layer security mechanisms
+to protect sensitive resources.
+
+### Spoofing by Counterfeit Servers
+
+**Hawk** provides limited verification of the server authenticity. When receiving a response back from the server, the server
+may choose to include a response `Server-Authorization` header which the client can use to verify the response. However, it is up to
+the server to determine when such measure is included, to up to the client to enforce that policy.
+
+A hostile party could take advantage of this by intercepting the client's requests and returning misleading or otherwise
+incorrect responses. Service providers should consider such attacks when developing services using this protocol, and should
+require transport-layer security for any requests where the authenticity of the resource server or of server responses is an issue.
+
+### Plaintext Storage of Credentials
+
+The **Hawk** key functions the same way passwords do in traditional authentication systems. In order to compute the request MAC,
+the server must have access to the key in plaintext form. This is in contrast, for example, to modern operating systems, which
+store only a one-way hash of user credentials.
+
+If an attacker were to gain access to these keys - or worse, to the server's database of all such keys - he or she would be able
+to perform any action on behalf of any resource owner. Accordingly, it is critical that servers protect these keys from unauthorized
+access.
+
+### Entropy of Keys
+
+Unless a transport-layer security protocol is used, eavesdroppers will have full access to authenticated requests and request
+MAC values, and will thus be able to mount offline brute-force attacks to recover the key used. Servers should be careful to
+assign keys which are long enough, and random enough, to resist such attacks for at least the length of time that the **Hawk**
+credentials are valid.
+
+For example, if the credentials are valid for two weeks, servers should ensure that it is not possible to mount a brute force
+attack that recovers the key in less than two weeks. Of course, servers are urged to err on the side of caution, and use the
+longest key reasonable.
+
+It is equally important that the pseudo-random number generator (PRNG) used to generate these keys be of sufficiently high
+quality. Many PRNG implementations generate number sequences that may appear to be random, but which nevertheless exhibit
+patterns or other weaknesses which make cryptanalysis or brute force attacks easier. Implementers should be careful to use
+cryptographically secure PRNGs to avoid these problems.
+
+### Coverage Limitations
+
+The request MAC only covers the HTTP `Host` header and optionally the `Content-Type` header. It does not cover any other headers
+which can often affect how the request body is interpreted by the server. If the server behavior is influenced by the presence
+or value of such headers, an attacker can manipulate the request headers without being detected. Implementers should use the
+`ext` feature to pass application-specific information via the `Authorization` header which is protected by the request MAC.
+
+The response authentication, when performed, only covers the response payload, content-type, and the request information
+provided by the client in it's request (method, resource, timestamp, nonce, etc.). It does not cover the HTTP status code or
+any other response header field (e.g. Location) which can affect the client's behaviour.
+
+### Future Time Manipulation
+
+The protocol relies on a clock sync between the client and server. To accomplish this, the server informs the client of its
+current time when an invalid timestamp is received.
+
+If an attacker is able to manipulate this information and cause the client to use an incorrect time, it would be able to cause
+the client to generate authenticated requests using time in the future. Such requests will fail when sent by the client, and will
+not likely leave a trace on the server (given the common implementation of nonce, if at all enforced). The attacker will then
+be able to replay the request at the correct time without detection.
+
+The client must only use the time information provided by the server if:
+* it was delivered over a TLS connection and the server identity has been verified, or
+* the `tsm` MAC digest calculated using the same client credentials over the timestamp has been verified.
+
+### Client Clock Poisoning
+
+When receiving a request with a bad timestamp, the server provides the client with its current time. The client must never use
+the time received from the server to adjust its own clock, and must only use it to calculate an offset for communicating with
+that particular server.
+
+### Bewit Limitations
+
+Special care must be taken when issuing bewit credentials to third parties. Bewit credentials are valid until expiration and cannot
+be revoked or limited without using other means. Whatever resource they grant access to will be completely exposed to anyone with
+access to the bewit credentials which act as bearer credentials for that particular resource. While bewit usage is limited to GET
+requests only and therefore cannot be used to perform transactions or change server state, it can still be used to expose private
+and sensitive information.
+
+### Host Header Forgery
+
+Hawk validates the incoming request MAC against the incoming HTTP Host header. However, unless the optional `host` and `port`
+options are used with `server.authenticate()`, a malicous client can mint new host names pointing to the server's IP address and
+use that to craft an attack by sending a valid request that's meant for another hostname than the one used by the server. Server
+implementors must manually verify that the host header received matches their expectation (or use the options mentioned above).
+
+# Frequently Asked Questions
+
+### Where is the protocol specification?
+
+If you are looking for some prose explaining how all this works, **this is it**. **Hawk** is being developed as an open source
+project instead of a standard. In other words, the [code](/hueniverse/hawk/tree/master/lib) is the specification. Not sure about
+something? Open an issue!
+
+### Is it done?
+
+As of version 0.10.0, **Hawk** is feature-complete. However, until this module reaches version 1.0.0 it is considered experimental
+and is likely to change. This also means your feedback and contribution are very welcome. Feel free to open issues with questions
+and suggestions.
+
+### Where can I find **Hawk** implementations in other languages?
+
+**Hawk**'s only reference implementation is provided in JavaScript as a node.js module. However, it has been ported to other languages.
+The full list is maintained [here](https://github.com/hueniverse/hawk/issues?labels=port&state=closed). Please add an issue if you are
+working on another port. A cross-platform test-suite is in the works.
+
+### Why isn't the algorithm part of the challenge or dynamically negotiated?
+
+The algorithm used is closely related to the key issued as different algorithms require different key sizes (and other
+requirements). While some keys can be used for multiple algorithm, the protocol is designed to closely bind the key and algorithm
+together as part of the issued credentials.
+
+### Why is Host and Content-Type the only headers covered by the request MAC?
+
+It is really hard to include other headers. Headers can be changed by proxies and other intermediaries and there is no
+well-established way to normalize them. Many platforms change the case of header field names and values. The only
+straight-forward solution is to include the headers in some blob (say, base64 encoded JSON) and include that with the request,
+an approach taken by JWT and other such formats. However, that design violates the HTTP header boundaries, repeats information,
+and introduces other security issues because firewalls will not be aware of these "hidden" headers. In addition, any information
+repeated must be compared to the duplicated information in the header and therefore only moves the problem elsewhere.
+
+### Why not just use HTTP Digest?
+
+Digest requires pre-negotiation to establish a nonce. This means you can't just make a request - you must first send
+a protocol handshake to the server. This pattern has become unacceptable for most web services, especially mobile
+where extra round-trip are costly.
+
+### Why bother with all this nonce and timestamp business?
+
+**Hawk** is an attempt to find a reasonable, practical compromise between security and usability. OAuth 1.0 got timestamp
+and nonces halfway right but failed when it came to scalability and consistent developer experience. **Hawk** addresses
+it by requiring the client to sync its clock, but provides it with tools to accomplish it.
+
+In general, replay protection is a matter of application-specific threat model. It is less of an issue on a TLS-protected
+system where the clients are implemented using best practices and are under the control of the server. Instead of dropping
+replay protection, **Hawk** offers a required time window and an optional nonce verification. Together, it provides developers
+with the ability to decide how to enforce their security policy without impacting the client's implementation.
+
+### What are `app` and `dlg` in the authorization header and normalized mac string?
+
+The original motivation for **Hawk** was to replace the OAuth 1.0 use cases. This included both a simple client-server mode which
+this module is specifically designed for, and a delegated access mode which is being developed separately in
+[Oz](https://github.com/hueniverse/oz). In addition to the **Hawk** use cases, Oz requires another attribute: the application id `app`.
+This provides binding between the credentials and the application in a way that prevents an attacker from tricking an application
+to use credentials issued to someone else. It also has an optional 'delegated-by' attribute `dlg` which is the application id of the
+application the credentials were directly issued to. The goal of these two additions is to allow Oz to utilize **Hawk** directly,
+but with the additional security of delegated credentials.
+
+### What is the purpose of the static strings used in each normalized MAC input?
+
+When calculating a hash or MAC, a static prefix (tag) is added. The prefix is used to prevent MAC values from being
+used or reused for a purpose other than what they were created for (i.e. prevents switching MAC values between a request,
+response, and a bewit use cases). It also protects against exploits created after a potential change in how the protocol
+creates the normalized string. For example, if a future version would switch the order of nonce and timestamp, it
+can create an exploit opportunity for cases where the nonce is similar in format to a timestamp.
+
+### Does **Hawk** have anything to do with OAuth?
+
+Short answer: no.
+
+**Hawk** was originally proposed as the OAuth MAC Token specification. However, the OAuth working group in its consistent
+incompetence failed to produce a final, usable solution to address one of the most popular use cases of OAuth 1.0 - using it
+to authenticate simple client-server transactions (i.e. two-legged). As you can guess, the OAuth working group is still hard
+at work to produce more garbage.
+
+**Hawk** provides a simple HTTP authentication scheme for making client-server requests. It does not address the OAuth use case
+of delegating access to a third party. If you are looking for an OAuth alternative, check out [Oz](https://github.com/hueniverse/oz).
+
+# Implementations
+
+- [Logibit Hawk in F#/.Net](https://github.com/logibit/logibit.hawk/)
+- [Tent Hawk in Ruby](https://github.com/tent/hawk-ruby)
+- [Wealdtech in Java](https://github.com/wealdtech/hawk)
+- [Kumar's Mohawk in Python](https://github.com/kumar303/mohawk/)
+
+# Acknowledgements
+
+**Hawk** is a derivative work of the [HTTP MAC Authentication Scheme](http://tools.ietf.org/html/draft-hammer-oauth-v2-mac-token-05) proposal
+co-authored by Ben Adida, Adam Barth, and Eran Hammer, which in turn was based on the OAuth 1.0 community specification.
+
+Special thanks to Ben Laurie for his always insightful feedback and advice.
+
+The **Hawk** logo was created by [Chris Carrasco](http://chriscarrasco.com).
diff --git a/node_modules/request/node_modules/hawk/bower.json b/node_modules/request/node_modules/hawk/bower.json
index 7d2d120e0..02729c5dc 100644
--- a/node_modules/request/node_modules/hawk/bower.json
+++ b/node_modules/request/node_modules/hawk/bower.json
@@ -1,24 +1,24 @@
-{
- "name": "hawk",
- "main": "lib/browser.js",
- "license": "./LICENSE",
- "ignore": [
- "!lib",
- "lib/*",
- "!lib/browser.js",
- "index.js"
- ],
- "keywords": [
- "http",
- "authentication",
- "scheme",
- "hawk"
- ],
- "authors": [
- "Eran Hammer <eran@hammer.io>"
- ],
- "repository": {
- "type": "git",
- "url": "git://github.com/hueniverse/hawk.git"
- }
-}
+{
+ "name": "hawk",
+ "main": "lib/browser.js",
+ "license": "./LICENSE",
+ "ignore": [
+ "!lib",
+ "lib/*",
+ "!lib/browser.js",
+ "index.js"
+ ],
+ "keywords": [
+ "http",
+ "authentication",
+ "scheme",
+ "hawk"
+ ],
+ "authors": [
+ "Eran Hammer <eran@hammer.io>"
+ ],
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/hueniverse/hawk.git"
+ }
+}
diff --git a/node_modules/request/node_modules/hawk/component.json b/node_modules/request/node_modules/hawk/component.json
index 63e76a2e3..57be3ebf2 100644
--- a/node_modules/request/node_modules/hawk/component.json
+++ b/node_modules/request/node_modules/hawk/component.json
@@ -1,19 +1,19 @@
-{
- "name": "hawk",
- "repo": "hueniverse/hawk",
- "description": "HTTP Hawk Authentication Scheme",
- "version": "1.0.0",
- "keywords": [
- "http",
- "authentication",
- "scheme",
- "hawk"
- ],
- "dependencies": {},
- "development": {},
- "license": "BSD",
- "main": "lib/browser.js",
- "scripts": [
- "lib/browser.js"
- ]
+{
+ "name": "hawk",
+ "repo": "hueniverse/hawk",
+ "description": "HTTP Hawk Authentication Scheme",
+ "version": "1.0.0",
+ "keywords": [
+ "http",
+ "authentication",
+ "scheme",
+ "hawk"
+ ],
+ "dependencies": {},
+ "development": {},
+ "license": "BSD",
+ "main": "lib/browser.js",
+ "scripts": [
+ "lib/browser.js"
+ ]
} \ No newline at end of file
diff --git a/node_modules/request/node_modules/hawk/dist/client.js b/node_modules/request/node_modules/hawk/dist/client.js
index 155412351..1827386ed 100644
--- a/node_modules/request/node_modules/hawk/dist/client.js
+++ b/node_modules/request/node_modules/hawk/dist/client.js
@@ -1,340 +1,343 @@
-'use strict'
-
-// Load modules
-
-;
-
-function _typeof(obj) { return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj; }
-
-var Url = require('url');
-var Hoek = require('hoek');
-var Cryptiles = require('cryptiles');
-var Crypto = require('./crypto');
-var Utils = require('./utils');
-
-// Declare internals
-
-var internals = {};
-
-// Generate an Authorization header for a given request
-
-/*
- uri: 'http://example.com/resource?a=b' or object from Url.parse()
- method: HTTP verb (e.g. 'GET', 'POST')
- options: {
-
- // Required
-
- credentials: {
- id: 'dh37fgj492je',
- key: 'aoijedoaijsdlaksjdl',
- algorithm: 'sha256' // 'sha1', 'sha256'
- },
-
- // Optional
-
- ext: 'application-specific', // Application specific data sent via the ext attribute
- timestamp: Date.now(), // A pre-calculated timestamp
- nonce: '2334f34f', // A pre-generated nonce
- localtimeOffsetMsec: 400, // Time offset to sync with server time (ignored if timestamp provided)
- payload: '{"some":"payload"}', // UTF-8 encoded string for body hash generation (ignored if hash provided)
- contentType: 'application/json', // Payload content-type (ignored if hash provided)
- hash: 'U4MKKSmiVxk37JCCrAVIjV=', // Pre-calculated payload hash
- app: '24s23423f34dx', // Oz application id
- dlg: '234sz34tww3sd' // Oz delegated-by application id
- }
-*/
-
-exports.header = function (uri, method, options) {
-
- var result = {
- field: '',
- artifacts: {}
- };
-
- // Validate inputs
-
- if (!uri || typeof uri !== 'string' && (typeof uri === 'undefined' ? 'undefined' : _typeof(uri)) !== 'object' || !method || typeof method !== 'string' || !options || (typeof options === 'undefined' ? 'undefined' : _typeof(options)) !== 'object') {
-
- result.err = 'Invalid argument type';
- return result;
- }
-
- // Application time
-
- var timestamp = options.timestamp || Utils.nowSecs(options.localtimeOffsetMsec);
-
- // Validate credentials
-
- var credentials = options.credentials;
- if (!credentials || !credentials.id || !credentials.key || !credentials.algorithm) {
-
- result.err = 'Invalid credential object';
- return result;
- }
-
- if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
- result.err = 'Unknown algorithm';
- return result;
- }
-
- // Parse URI
-
- if (typeof uri === 'string') {
- uri = Url.parse(uri);
- }
-
- // Calculate signature
-
- var artifacts = {
- ts: timestamp,
- nonce: options.nonce || Cryptiles.randomString(6),
- method: method,
- resource: uri.pathname + (uri.search || ''), // Maintain trailing '?'
- host: uri.hostname,
- port: uri.port || (uri.protocol === 'http:' ? 80 : 443),
- hash: options.hash,
- ext: options.ext,
- app: options.app,
- dlg: options.dlg
- };
-
- result.artifacts = artifacts;
-
- // Calculate payload hash
-
- if (!artifacts.hash && (options.payload || options.payload === '')) {
-
- artifacts.hash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType);
- }
-
- var mac = Crypto.calculateMac('header', credentials, artifacts);
-
- // Construct header
-
- var hasExt = artifacts.ext !== null && artifacts.ext !== undefined && artifacts.ext !== ''; // Other falsey values allowed
- var header = 'Hawk id="' + credentials.id + '", ts="' + artifacts.ts + '", nonce="' + artifacts.nonce + (artifacts.hash ? '", hash="' + artifacts.hash : '') + (hasExt ? '", ext="' + Hoek.escapeHeaderAttribute(artifacts.ext) : '') + '", mac="' + mac + '"';
-
- if (artifacts.app) {
- header = header + ', app="' + artifacts.app + (artifacts.dlg ? '", dlg="' + artifacts.dlg : '') + '"';
- }
-
- result.field = header;
-
- return result;
-};
-
-// Validate server response
-
-/*
- res: node's response object
- artifacts: object received from header().artifacts
- options: {
- payload: optional payload received
- required: specifies if a Server-Authorization header is required. Defaults to 'false'
- }
-*/
-
-exports.authenticate = function (res, credentials, artifacts, options) {
-
- artifacts = Hoek.clone(artifacts);
- options = options || {};
-
- if (res.headers['www-authenticate']) {
-
- // Parse HTTP WWW-Authenticate header
-
- var wwwAttributes = Utils.parseAuthorizationHeader(res.headers['www-authenticate'], ['ts', 'tsm', 'error']);
- if (wwwAttributes instanceof Error) {
- return false;
- }
-
- // Validate server timestamp (not used to update clock since it is done via the SNPT client)
-
- if (wwwAttributes.ts) {
- var tsm = Crypto.calculateTsMac(wwwAttributes.ts, credentials);
- if (tsm !== wwwAttributes.tsm) {
- return false;
- }
- }
- }
-
- // Parse HTTP Server-Authorization header
-
- if (!res.headers['server-authorization'] && !options.required) {
-
- return true;
- }
-
- var attributes = Utils.parseAuthorizationHeader(res.headers['server-authorization'], ['mac', 'ext', 'hash']);
- if (attributes instanceof Error) {
- return false;
- }
-
- artifacts.ext = attributes.ext;
- artifacts.hash = attributes.hash;
-
- var mac = Crypto.calculateMac('response', credentials, artifacts);
- if (mac !== attributes.mac) {
- return false;
- }
-
- if (!options.payload && options.payload !== '') {
-
- return true;
- }
-
- if (!attributes.hash) {
- return false;
- }
-
- var calculatedHash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, res.headers['content-type']);
- return calculatedHash === attributes.hash;
-};
-
-// Generate a bewit value for a given URI
-
-/*
- uri: 'http://example.com/resource?a=b' or object from Url.parse()
- options: {
-
- // Required
-
- credentials: {
- id: 'dh37fgj492je',
- key: 'aoijedoaijsdlaksjdl',
- algorithm: 'sha256' // 'sha1', 'sha256'
- },
- ttlSec: 60 * 60, // TTL in seconds
-
- // Optional
-
- ext: 'application-specific', // Application specific data sent via the ext attribute
- localtimeOffsetMsec: 400 // Time offset to sync with server time
- };
-*/
-
-exports.getBewit = function (uri, options) {
-
- // Validate inputs
-
- if (!uri || typeof uri !== 'string' && (typeof uri === 'undefined' ? 'undefined' : _typeof(uri)) !== 'object' || !options || (typeof options === 'undefined' ? 'undefined' : _typeof(options)) !== 'object' || !options.ttlSec) {
-
- return '';
- }
-
- options.ext = options.ext === null || options.ext === undefined ? '' : options.ext; // Zero is valid value
-
- // Application time
-
- var now = Utils.now(options.localtimeOffsetMsec);
-
- // Validate credentials
-
- var credentials = options.credentials;
- if (!credentials || !credentials.id || !credentials.key || !credentials.algorithm) {
-
- return '';
- }
-
- if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
- return '';
- }
-
- // Parse URI
-
- if (typeof uri === 'string') {
- uri = Url.parse(uri);
- }
-
- // Calculate signature
-
- var exp = Math.floor(now / 1000) + options.ttlSec;
- var mac = Crypto.calculateMac('bewit', credentials, {
- ts: exp,
- nonce: '',
- method: 'GET',
- resource: uri.pathname + (uri.search || ''), // Maintain trailing '?'
- host: uri.hostname,
- port: uri.port || (uri.protocol === 'http:' ? 80 : 443),
- ext: options.ext
- });
-
- // Construct bewit: id\exp\mac\ext
-
- var bewit = credentials.id + '\\' + exp + '\\' + mac + '\\' + options.ext;
- return Hoek.base64urlEncode(bewit);
-};
-
-// Generate an authorization string for a message
-
-/*
- host: 'example.com',
- port: 8000,
- message: '{"some":"payload"}', // UTF-8 encoded string for body hash generation
- options: {
-
- // Required
-
- credentials: {
- id: 'dh37fgj492je',
- key: 'aoijedoaijsdlaksjdl',
- algorithm: 'sha256' // 'sha1', 'sha256'
- },
-
- // Optional
-
- timestamp: Date.now(), // A pre-calculated timestamp
- nonce: '2334f34f', // A pre-generated nonce
- localtimeOffsetMsec: 400, // Time offset to sync with server time (ignored if timestamp provided)
- }
-*/
-
-exports.message = function (host, port, message, options) {
-
- // Validate inputs
-
- if (!host || typeof host !== 'string' || !port || typeof port !== 'number' || message === null || message === undefined || typeof message !== 'string' || !options || (typeof options === 'undefined' ? 'undefined' : _typeof(options)) !== 'object') {
-
- return null;
- }
-
- // Application time
-
- var timestamp = options.timestamp || Utils.nowSecs(options.localtimeOffsetMsec);
-
- // Validate credentials
-
- var credentials = options.credentials;
- if (!credentials || !credentials.id || !credentials.key || !credentials.algorithm) {
-
- // Invalid credential object
- return null;
- }
-
- if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
- return null;
- }
-
- // Calculate signature
-
- var artifacts = {
- ts: timestamp,
- nonce: options.nonce || Cryptiles.randomString(6),
- host: host,
- port: port,
- hash: Crypto.calculatePayloadHash(message, credentials.algorithm)
- };
-
- // Construct authorization
-
- var result = {
- id: credentials.id,
- ts: artifacts.ts,
- nonce: artifacts.nonce,
- hash: artifacts.hash,
- mac: Crypto.calculateMac('message', credentials, artifacts)
- };
-
- return result;
-};
+'use strict'
+
+// Load modules
+
+;
+
+var _typeof = function (obj) {
+
+ return obj && typeof Symbol !== 'undefined' && obj.constructor === Symbol ? 'symbol' : typeof obj;
+};
+
+var Url = require('url');
+var Hoek = require('hoek');
+var Cryptiles = require('cryptiles');
+var Crypto = require('./crypto');
+var Utils = require('./utils');
+
+// Declare internals
+
+var internals = {};
+
+// Generate an Authorization header for a given request
+
+/*
+ uri: 'http://example.com/resource?a=b' or object from Url.parse()
+ method: HTTP verb (e.g. 'GET', 'POST')
+ options: {
+
+ // Required
+
+ credentials: {
+ id: 'dh37fgj492je',
+ key: 'aoijedoaijsdlaksjdl',
+ algorithm: 'sha256' // 'sha1', 'sha256'
+ },
+
+ // Optional
+
+ ext: 'application-specific', // Application specific data sent via the ext attribute
+ timestamp: Date.now(), // A pre-calculated timestamp
+ nonce: '2334f34f', // A pre-generated nonce
+ localtimeOffsetMsec: 400, // Time offset to sync with server time (ignored if timestamp provided)
+ payload: '{"some":"payload"}', // UTF-8 encoded string for body hash generation (ignored if hash provided)
+ contentType: 'application/json', // Payload content-type (ignored if hash provided)
+ hash: 'U4MKKSmiVxk37JCCrAVIjV=', // Pre-calculated payload hash
+ app: '24s23423f34dx', // Oz application id
+ dlg: '234sz34tww3sd' // Oz delegated-by application id
+ }
+*/
+
+exports.header = function (uri, method, options) {
+
+ var result = {
+ field: '',
+ artifacts: {}
+ };
+
+ // Validate inputs
+
+ if (!uri || typeof uri !== 'string' && (typeof uri === 'undefined' ? 'undefined' : _typeof(uri)) !== 'object' || !method || typeof method !== 'string' || !options || (typeof options === 'undefined' ? 'undefined' : _typeof(options)) !== 'object') {
+
+ result.err = 'Invalid argument type';
+ return result;
+ }
+
+ // Application time
+
+ var timestamp = options.timestamp || Utils.nowSecs(options.localtimeOffsetMsec);
+
+ // Validate credentials
+
+ var credentials = options.credentials;
+ if (!credentials || !credentials.id || !credentials.key || !credentials.algorithm) {
+
+ result.err = 'Invalid credential object';
+ return result;
+ }
+
+ if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
+ result.err = 'Unknown algorithm';
+ return result;
+ }
+
+ // Parse URI
+
+ if (typeof uri === 'string') {
+ uri = Url.parse(uri);
+ }
+
+ // Calculate signature
+
+ var artifacts = {
+ ts: timestamp,
+ nonce: options.nonce || Cryptiles.randomString(6),
+ method: method,
+ resource: uri.pathname + (uri.search || ''), // Maintain trailing '?'
+ host: uri.hostname,
+ port: uri.port || (uri.protocol === 'http:' ? 80 : 443),
+ hash: options.hash,
+ ext: options.ext,
+ app: options.app,
+ dlg: options.dlg
+ };
+
+ result.artifacts = artifacts;
+
+ // Calculate payload hash
+
+ if (!artifacts.hash && (options.payload || options.payload === '')) {
+
+ artifacts.hash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType);
+ }
+
+ var mac = Crypto.calculateMac('header', credentials, artifacts);
+
+ // Construct header
+
+ var hasExt = artifacts.ext !== null && artifacts.ext !== undefined && artifacts.ext !== ''; // Other falsey values allowed
+ var header = 'Hawk id="' + credentials.id + '", ts="' + artifacts.ts + '", nonce="' + artifacts.nonce + (artifacts.hash ? '", hash="' + artifacts.hash : '') + (hasExt ? '", ext="' + Hoek.escapeHeaderAttribute(artifacts.ext) : '') + '", mac="' + mac + '"';
+
+ if (artifacts.app) {
+ header = header + ', app="' + artifacts.app + (artifacts.dlg ? '", dlg="' + artifacts.dlg : '') + '"';
+ }
+
+ result.field = header;
+
+ return result;
+};
+
+// Validate server response
+
+/*
+ res: node's response object
+ artifacts: object received from header().artifacts
+ options: {
+ payload: optional payload received
+ required: specifies if a Server-Authorization header is required. Defaults to 'false'
+ }
+*/
+
+exports.authenticate = function (res, credentials, artifacts, options) {
+
+ artifacts = Hoek.clone(artifacts);
+ options = options || {};
+
+ if (res.headers['www-authenticate']) {
+
+ // Parse HTTP WWW-Authenticate header
+
+ var wwwAttributes = Utils.parseAuthorizationHeader(res.headers['www-authenticate'], ['ts', 'tsm', 'error']);
+ if (wwwAttributes instanceof Error) {
+ return false;
+ }
+
+ // Validate server timestamp (not used to update clock since it is done via the SNPT client)
+
+ if (wwwAttributes.ts) {
+ var tsm = Crypto.calculateTsMac(wwwAttributes.ts, credentials);
+ if (tsm !== wwwAttributes.tsm) {
+ return false;
+ }
+ }
+ }
+
+ // Parse HTTP Server-Authorization header
+
+ if (!res.headers['server-authorization'] && !options.required) {
+
+ return true;
+ }
+
+ var attributes = Utils.parseAuthorizationHeader(res.headers['server-authorization'], ['mac', 'ext', 'hash']);
+ if (attributes instanceof Error) {
+ return false;
+ }
+
+ artifacts.ext = attributes.ext;
+ artifacts.hash = attributes.hash;
+
+ var mac = Crypto.calculateMac('response', credentials, artifacts);
+ if (mac !== attributes.mac) {
+ return false;
+ }
+
+ if (!options.payload && options.payload !== '') {
+
+ return true;
+ }
+
+ if (!attributes.hash) {
+ return false;
+ }
+
+ var calculatedHash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, res.headers['content-type']);
+ return calculatedHash === attributes.hash;
+};
+
+// Generate a bewit value for a given URI
+
+/*
+ uri: 'http://example.com/resource?a=b' or object from Url.parse()
+ options: {
+
+ // Required
+
+ credentials: {
+ id: 'dh37fgj492je',
+ key: 'aoijedoaijsdlaksjdl',
+ algorithm: 'sha256' // 'sha1', 'sha256'
+ },
+ ttlSec: 60 * 60, // TTL in seconds
+
+ // Optional
+
+ ext: 'application-specific', // Application specific data sent via the ext attribute
+ localtimeOffsetMsec: 400 // Time offset to sync with server time
+ };
+*/
+
+exports.getBewit = function (uri, options) {
+
+ // Validate inputs
+
+ if (!uri || typeof uri !== 'string' && (typeof uri === 'undefined' ? 'undefined' : _typeof(uri)) !== 'object' || !options || (typeof options === 'undefined' ? 'undefined' : _typeof(options)) !== 'object' || !options.ttlSec) {
+
+ return '';
+ }
+
+ options.ext = options.ext === null || options.ext === undefined ? '' : options.ext; // Zero is valid value
+
+ // Application time
+
+ var now = Utils.now(options.localtimeOffsetMsec);
+
+ // Validate credentials
+
+ var credentials = options.credentials;
+ if (!credentials || !credentials.id || !credentials.key || !credentials.algorithm) {
+
+ return '';
+ }
+
+ if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
+ return '';
+ }
+
+ // Parse URI
+
+ if (typeof uri === 'string') {
+ uri = Url.parse(uri);
+ }
+
+ // Calculate signature
+
+ var exp = Math.floor(now / 1000) + options.ttlSec;
+ var mac = Crypto.calculateMac('bewit', credentials, {
+ ts: exp,
+ nonce: '',
+ method: 'GET',
+ resource: uri.pathname + (uri.search || ''), // Maintain trailing '?'
+ host: uri.hostname,
+ port: uri.port || (uri.protocol === 'http:' ? 80 : 443),
+ ext: options.ext
+ });
+
+ // Construct bewit: id\exp\mac\ext
+
+ var bewit = credentials.id + '\\' + exp + '\\' + mac + '\\' + options.ext;
+ return Hoek.base64urlEncode(bewit);
+};
+
+// Generate an authorization string for a message
+
+/*
+ host: 'example.com',
+ port: 8000,
+ message: '{"some":"payload"}', // UTF-8 encoded string for body hash generation
+ options: {
+
+ // Required
+
+ credentials: {
+ id: 'dh37fgj492je',
+ key: 'aoijedoaijsdlaksjdl',
+ algorithm: 'sha256' // 'sha1', 'sha256'
+ },
+
+ // Optional
+
+ timestamp: Date.now(), // A pre-calculated timestamp
+ nonce: '2334f34f', // A pre-generated nonce
+ localtimeOffsetMsec: 400, // Time offset to sync with server time (ignored if timestamp provided)
+ }
+*/
+
+exports.message = function (host, port, message, options) {
+
+ // Validate inputs
+
+ if (!host || typeof host !== 'string' || !port || typeof port !== 'number' || message === null || message === undefined || typeof message !== 'string' || !options || (typeof options === 'undefined' ? 'undefined' : _typeof(options)) !== 'object') {
+
+ return null;
+ }
+
+ // Application time
+
+ var timestamp = options.timestamp || Utils.nowSecs(options.localtimeOffsetMsec);
+
+ // Validate credentials
+
+ var credentials = options.credentials;
+ if (!credentials || !credentials.id || !credentials.key || !credentials.algorithm) {
+
+ // Invalid credential object
+ return null;
+ }
+
+ if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
+ return null;
+ }
+
+ // Calculate signature
+
+ var artifacts = {
+ ts: timestamp,
+ nonce: options.nonce || Cryptiles.randomString(6),
+ host: host,
+ port: port,
+ hash: Crypto.calculatePayloadHash(message, credentials.algorithm)
+ };
+
+ // Construct authorization
+
+ var result = {
+ id: credentials.id,
+ ts: artifacts.ts,
+ nonce: artifacts.nonce,
+ hash: artifacts.hash,
+ mac: Crypto.calculateMac('message', credentials, artifacts)
+ };
+
+ return result;
+};
diff --git a/node_modules/request/node_modules/hawk/example/usage.js b/node_modules/request/node_modules/hawk/example/usage.js
index 13b860b4c..f55af03cd 100755
--- a/node_modules/request/node_modules/hawk/example/usage.js
+++ b/node_modules/request/node_modules/hawk/example/usage.js
@@ -1,78 +1,78 @@
-// Load modules
-
-var Http = require('http');
-var Request = require('request');
-var Hawk = require('../lib');
-
-
-// Declare internals
-
-var internals = {
- credentials: {
- dh37fgj492je: {
- id: 'dh37fgj492je', // Required by Hawk.client.header
- key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
- algorithm: 'sha256',
- user: 'Steve'
- }
- }
-};
-
-
-// Credentials lookup function
-
-var credentialsFunc = function (id, callback) {
-
- return callback(null, internals.credentials[id]);
-};
-
-
-// Create HTTP server
-
-var handler = function (req, res) {
-
- Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
-
- var payload = (!err ? 'Hello ' + credentials.user + ' ' + artifacts.ext : 'Shoosh!');
- var headers = {
- 'Content-Type': 'text/plain',
- 'Server-Authorization': Hawk.server.header(credentials, artifacts, { payload: payload, contentType: 'text/plain' })
- };
-
- res.writeHead(!err ? 200 : 401, headers);
- res.end(payload);
- });
-};
-
-Http.createServer(handler).listen(8000, '127.0.0.1');
-
-
-// Send unauthenticated request
-
-Request('http://127.0.0.1:8000/resource/1?b=1&a=2', function (error, response, body) {
-
- console.log(response.statusCode + ': ' + body);
-});
-
-
-// Send authenticated request
-
-credentialsFunc('dh37fgj492je', function (err, credentials) {
-
- var header = Hawk.client.header('http://127.0.0.1:8000/resource/1?b=1&a=2', 'GET', { credentials: credentials, ext: 'and welcome!' });
- var options = {
- uri: 'http://127.0.0.1:8000/resource/1?b=1&a=2',
- method: 'GET',
- headers: {
- authorization: header.field
- }
- };
-
- Request(options, function (error, response, body) {
-
- var isValid = Hawk.client.authenticate(response, credentials, header.artifacts, { payload: body });
- console.log(response.statusCode + ': ' + body + (isValid ? ' (valid)' : ' (invalid)'));
- process.exit(0);
- });
-});
-
+// Load modules
+
+var Http = require('http');
+var Request = require('request');
+var Hawk = require('../lib');
+
+
+// Declare internals
+
+var internals = {
+ credentials: {
+ dh37fgj492je: {
+ id: 'dh37fgj492je', // Required by Hawk.client.header
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: 'sha256',
+ user: 'Steve'
+ }
+ }
+};
+
+
+// Credentials lookup function
+
+var credentialsFunc = function (id, callback) {
+
+ return callback(null, internals.credentials[id]);
+};
+
+
+// Create HTTP server
+
+var handler = function (req, res) {
+
+ Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
+
+ var payload = (!err ? 'Hello ' + credentials.user + ' ' + artifacts.ext : 'Shoosh!');
+ var headers = {
+ 'Content-Type': 'text/plain',
+ 'Server-Authorization': Hawk.server.header(credentials, artifacts, { payload: payload, contentType: 'text/plain' })
+ };
+
+ res.writeHead(!err ? 200 : 401, headers);
+ res.end(payload);
+ });
+};
+
+Http.createServer(handler).listen(8000, '127.0.0.1');
+
+
+// Send unauthenticated request
+
+Request('http://127.0.0.1:8000/resource/1?b=1&a=2', function (error, response, body) {
+
+ console.log(response.statusCode + ': ' + body);
+});
+
+
+// Send authenticated request
+
+credentialsFunc('dh37fgj492je', function (err, credentials) {
+
+ var header = Hawk.client.header('http://127.0.0.1:8000/resource/1?b=1&a=2', 'GET', { credentials: credentials, ext: 'and welcome!' });
+ var options = {
+ uri: 'http://127.0.0.1:8000/resource/1?b=1&a=2',
+ method: 'GET',
+ headers: {
+ authorization: header.field
+ }
+ };
+
+ Request(options, function (error, response, body) {
+
+ var isValid = Hawk.client.authenticate(response, credentials, header.artifacts, { payload: body });
+ console.log(response.statusCode + ': ' + body + (isValid ? ' (valid)' : ' (invalid)'));
+ process.exit(0);
+ });
+});
+
diff --git a/node_modules/request/node_modules/hawk/lib/browser.js b/node_modules/request/node_modules/hawk/lib/browser.js
index a7945d0dd..3f6e85d07 100755
--- a/node_modules/request/node_modules/hawk/lib/browser.js
+++ b/node_modules/request/node_modules/hawk/lib/browser.js
@@ -1,637 +1,637 @@
-/*
- HTTP Hawk Authentication Scheme
- Copyright (c) 2012-2014, Eran Hammer <eran@hammer.io>
- BSD Licensed
-*/
-
-
-// Declare namespace
-
-var hawk = {
- internals: {}
-};
-
-
-hawk.client = {
-
- // Generate an Authorization header for a given request
-
- /*
- uri: 'http://example.com/resource?a=b' or object generated by hawk.utils.parseUri()
- method: HTTP verb (e.g. 'GET', 'POST')
- options: {
-
- // Required
-
- credentials: {
- id: 'dh37fgj492je',
- key: 'aoijedoaijsdlaksjdl',
- algorithm: 'sha256' // 'sha1', 'sha256'
- },
-
- // Optional
-
- ext: 'application-specific', // Application specific data sent via the ext attribute
- timestamp: Date.now() / 1000, // A pre-calculated timestamp in seconds
- nonce: '2334f34f', // A pre-generated nonce
- localtimeOffsetMsec: 400, // Time offset to sync with server time (ignored if timestamp provided)
- payload: '{"some":"payload"}', // UTF-8 encoded string for body hash generation (ignored if hash provided)
- contentType: 'application/json', // Payload content-type (ignored if hash provided)
- hash: 'U4MKKSmiVxk37JCCrAVIjV=', // Pre-calculated payload hash
- app: '24s23423f34dx', // Oz application id
- dlg: '234sz34tww3sd' // Oz delegated-by application id
- }
- */
-
- header: function (uri, method, options) {
-
- var result = {
- field: '',
- artifacts: {}
- };
-
- // Validate inputs
-
- if (!uri || (typeof uri !== 'string' && typeof uri !== 'object') ||
- !method || typeof method !== 'string' ||
- !options || typeof options !== 'object') {
-
- result.err = 'Invalid argument type';
- return result;
- }
-
- // Application time
-
- var timestamp = options.timestamp || hawk.utils.now(options.localtimeOffsetMsec);
-
- // Validate credentials
-
- var credentials = options.credentials;
- if (!credentials ||
- !credentials.id ||
- !credentials.key ||
- !credentials.algorithm) {
-
- result.err = 'Invalid credentials object';
- return result;
- }
-
- if (hawk.crypto.algorithms.indexOf(credentials.algorithm) === -1) {
- result.err = 'Unknown algorithm';
- return result;
- }
-
- // Parse URI
-
- if (typeof uri === 'string') {
- uri = hawk.utils.parseUri(uri);
- }
-
- // Calculate signature
-
- var artifacts = {
- ts: timestamp,
- nonce: options.nonce || hawk.utils.randomString(6),
- method: method,
- resource: uri.resource,
- host: uri.host,
- port: uri.port,
- hash: options.hash,
- ext: options.ext,
- app: options.app,
- dlg: options.dlg
- };
-
- result.artifacts = artifacts;
-
- // Calculate payload hash
-
- if (!artifacts.hash &&
- (options.payload || options.payload === '')) {
-
- artifacts.hash = hawk.crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType);
- }
-
- var mac = hawk.crypto.calculateMac('header', credentials, artifacts);
-
- // Construct header
-
- var hasExt = artifacts.ext !== null && artifacts.ext !== undefined && artifacts.ext !== ''; // Other falsey values allowed
- var header = 'Hawk id="' + credentials.id +
- '", ts="' + artifacts.ts +
- '", nonce="' + artifacts.nonce +
- (artifacts.hash ? '", hash="' + artifacts.hash : '') +
- (hasExt ? '", ext="' + hawk.utils.escapeHeaderAttribute(artifacts.ext) : '') +
- '", mac="' + mac + '"';
-
- if (artifacts.app) {
- header += ', app="' + artifacts.app +
- (artifacts.dlg ? '", dlg="' + artifacts.dlg : '') + '"';
- }
-
- result.field = header;
-
- return result;
- },
-
- // Generate a bewit value for a given URI
-
- /*
- uri: 'http://example.com/resource?a=b'
- options: {
-
- // Required
-
- credentials: {
- id: 'dh37fgj492je',
- key: 'aoijedoaijsdlaksjdl',
- algorithm: 'sha256' // 'sha1', 'sha256'
- },
- ttlSec: 60 * 60, // TTL in seconds
-
- // Optional
-
- ext: 'application-specific', // Application specific data sent via the ext attribute
- localtimeOffsetMsec: 400 // Time offset to sync with server time
- };
- */
-
- bewit: function (uri, options) {
-
- // Validate inputs
-
- if (!uri ||
- (typeof uri !== 'string') ||
- !options ||
- typeof options !== 'object' ||
- !options.ttlSec) {
-
- return '';
- }
-
- options.ext = (options.ext === null || options.ext === undefined ? '' : options.ext); // Zero is valid value
-
- // Application time
-
- var now = hawk.utils.now(options.localtimeOffsetMsec);
-
- // Validate credentials
-
- var credentials = options.credentials;
- if (!credentials ||
- !credentials.id ||
- !credentials.key ||
- !credentials.algorithm) {
-
- return '';
- }
-
- if (hawk.crypto.algorithms.indexOf(credentials.algorithm) === -1) {
- return '';
- }
-
- // Parse URI
-
- uri = hawk.utils.parseUri(uri);
-
- // Calculate signature
-
- var exp = now + options.ttlSec;
- var mac = hawk.crypto.calculateMac('bewit', credentials, {
- ts: exp,
- nonce: '',
- method: 'GET',
- resource: uri.resource, // Maintain trailing '?' and query params
- host: uri.host,
- port: uri.port,
- ext: options.ext
- });
-
- // Construct bewit: id\exp\mac\ext
-
- var bewit = credentials.id + '\\' + exp + '\\' + mac + '\\' + options.ext;
- return hawk.utils.base64urlEncode(bewit);
- },
-
- // Validate server response
-
- /*
- request: object created via 'new XMLHttpRequest()' after response received
- artifacts: object received from header().artifacts
- options: {
- payload: optional payload received
- required: specifies if a Server-Authorization header is required. Defaults to 'false'
- }
- */
-
- authenticate: function (request, credentials, artifacts, options) {
-
- options = options || {};
-
- var getHeader = function (name) {
-
- return request.getResponseHeader ? request.getResponseHeader(name) : request.getHeader(name);
- };
-
- var wwwAuthenticate = getHeader('www-authenticate');
- if (wwwAuthenticate) {
-
- // Parse HTTP WWW-Authenticate header
-
- var wwwAttributes = hawk.utils.parseAuthorizationHeader(wwwAuthenticate, ['ts', 'tsm', 'error']);
- if (!wwwAttributes) {
- return false;
- }
-
- if (wwwAttributes.ts) {
- var tsm = hawk.crypto.calculateTsMac(wwwAttributes.ts, credentials);
- if (tsm !== wwwAttributes.tsm) {
- return false;
- }
-
- hawk.utils.setNtpOffset(wwwAttributes.ts - Math.floor((new Date()).getTime() / 1000)); // Keep offset at 1 second precision
- }
- }
-
- // Parse HTTP Server-Authorization header
-
- var serverAuthorization = getHeader('server-authorization');
- if (!serverAuthorization &&
- !options.required) {
-
- return true;
- }
-
- var attributes = hawk.utils.parseAuthorizationHeader(serverAuthorization, ['mac', 'ext', 'hash']);
- if (!attributes) {
- return false;
- }
-
- var modArtifacts = {
- ts: artifacts.ts,
- nonce: artifacts.nonce,
- method: artifacts.method,
- resource: artifacts.resource,
- host: artifacts.host,
- port: artifacts.port,
- hash: attributes.hash,
- ext: attributes.ext,
- app: artifacts.app,
- dlg: artifacts.dlg
- };
-
- var mac = hawk.crypto.calculateMac('response', credentials, modArtifacts);
- if (mac !== attributes.mac) {
- return false;
- }
-
- if (!options.payload &&
- options.payload !== '') {
-
- return true;
- }
-
- if (!attributes.hash) {
- return false;
- }
-
- var calculatedHash = hawk.crypto.calculatePayloadHash(options.payload, credentials.algorithm, getHeader('content-type'));
- return (calculatedHash === attributes.hash);
- },
-
- message: function (host, port, message, options) {
-
- // Validate inputs
-
- if (!host || typeof host !== 'string' ||
- !port || typeof port !== 'number' ||
- message === null || message === undefined || typeof message !== 'string' ||
- !options || typeof options !== 'object') {
-
- return null;
- }
-
- // Application time
-
- var timestamp = options.timestamp || hawk.utils.now(options.localtimeOffsetMsec);
-
- // Validate credentials
-
- var credentials = options.credentials;
- if (!credentials ||
- !credentials.id ||
- !credentials.key ||
- !credentials.algorithm) {
-
- // Invalid credential object
- return null;
- }
-
- if (hawk.crypto.algorithms.indexOf(credentials.algorithm) === -1) {
- return null;
- }
-
- // Calculate signature
-
- var artifacts = {
- ts: timestamp,
- nonce: options.nonce || hawk.utils.randomString(6),
- host: host,
- port: port,
- hash: hawk.crypto.calculatePayloadHash(message, credentials.algorithm)
- };
-
- // Construct authorization
-
- var result = {
- id: credentials.id,
- ts: artifacts.ts,
- nonce: artifacts.nonce,
- hash: artifacts.hash,
- mac: hawk.crypto.calculateMac('message', credentials, artifacts)
- };
-
- return result;
- },
-
- authenticateTimestamp: function (message, credentials, updateClock) { // updateClock defaults to true
-
- var tsm = hawk.crypto.calculateTsMac(message.ts, credentials);
- if (tsm !== message.tsm) {
- return false;
- }
-
- if (updateClock !== false) {
- hawk.utils.setNtpOffset(message.ts - Math.floor((new Date()).getTime() / 1000)); // Keep offset at 1 second precision
- }
-
- return true;
- }
-};
-
-
-hawk.crypto = {
-
- headerVersion: '1',
-
- algorithms: ['sha1', 'sha256'],
-
- calculateMac: function (type, credentials, options) {
-
- var normalized = hawk.crypto.generateNormalizedString(type, options);
-
- var hmac = CryptoJS['Hmac' + credentials.algorithm.toUpperCase()](normalized, credentials.key);
- return hmac.toString(CryptoJS.enc.Base64);
- },
-
- generateNormalizedString: function (type, options) {
-
- var normalized = 'hawk.' + hawk.crypto.headerVersion + '.' + type + '\n' +
- options.ts + '\n' +
- options.nonce + '\n' +
- (options.method || '').toUpperCase() + '\n' +
- (options.resource || '') + '\n' +
- options.host.toLowerCase() + '\n' +
- options.port + '\n' +
- (options.hash || '') + '\n';
-
- if (options.ext) {
- normalized += options.ext.replace('\\', '\\\\').replace('\n', '\\n');
- }
-
- normalized += '\n';
-
- if (options.app) {
- normalized += options.app + '\n' +
- (options.dlg || '') + '\n';
- }
-
- return normalized;
- },
-
- calculatePayloadHash: function (payload, algorithm, contentType) {
-
- var hash = CryptoJS.algo[algorithm.toUpperCase()].create();
- hash.update('hawk.' + hawk.crypto.headerVersion + '.payload\n');
- hash.update(hawk.utils.parseContentType(contentType) + '\n');
- hash.update(payload);
- hash.update('\n');
- return hash.finalize().toString(CryptoJS.enc.Base64);
- },
-
- calculateTsMac: function (ts, credentials) {
-
- var hash = CryptoJS['Hmac' + credentials.algorithm.toUpperCase()]('hawk.' + hawk.crypto.headerVersion + '.ts\n' + ts + '\n', credentials.key);
- return hash.toString(CryptoJS.enc.Base64);
- }
-};
-
-
-// localStorage compatible interface
-
-hawk.internals.LocalStorage = function () {
-
- this._cache = {};
- this.length = 0;
-
- this.getItem = function (key) {
-
- return this._cache.hasOwnProperty(key) ? String(this._cache[key]) : null;
- };
-
- this.setItem = function (key, value) {
-
- this._cache[key] = String(value);
- this.length = Object.keys(this._cache).length;
- };
-
- this.removeItem = function (key) {
-
- delete this._cache[key];
- this.length = Object.keys(this._cache).length;
- };
-
- this.clear = function () {
-
- this._cache = {};
- this.length = 0;
- };
-
- this.key = function (i) {
-
- return Object.keys(this._cache)[i || 0];
- };
-};
-
-
-hawk.utils = {
-
- storage: new hawk.internals.LocalStorage(),
-
- setStorage: function (storage) {
-
- var ntpOffset = hawk.utils.storage.getItem('hawk_ntp_offset');
- hawk.utils.storage = storage;
- if (ntpOffset) {
- hawk.utils.setNtpOffset(ntpOffset);
- }
- },
-
- setNtpOffset: function (offset) {
-
- try {
- hawk.utils.storage.setItem('hawk_ntp_offset', offset);
- }
- catch (err) {
- console.error('[hawk] could not write to storage.');
- console.error(err);
- }
- },
-
- getNtpOffset: function () {
-
- var offset = hawk.utils.storage.getItem('hawk_ntp_offset');
- if (!offset) {
- return 0;
- }
-
- return parseInt(offset, 10);
- },
-
- now: function (localtimeOffsetMsec) {
-
- return Math.floor(((new Date()).getTime() + (localtimeOffsetMsec || 0)) / 1000) + hawk.utils.getNtpOffset();
- },
-
- escapeHeaderAttribute: function (attribute) {
-
- return attribute.replace(/\\/g, '\\\\').replace(/\"/g, '\\"');
- },
-
- parseContentType: function (header) {
-
- if (!header) {
- return '';
- }
-
- return header.split(';')[0].replace(/^\s+|\s+$/g, '').toLowerCase();
- },
-
- parseAuthorizationHeader: function (header, keys) {
-
- if (!header) {
- return null;
- }
-
- var headerParts = header.match(/^(\w+)(?:\s+(.*))?$/); // Header: scheme[ something]
- if (!headerParts) {
- return null;
- }
-
- var scheme = headerParts[1];
- if (scheme.toLowerCase() !== 'hawk') {
- return null;
- }
-
- var attributesString = headerParts[2];
- if (!attributesString) {
- return null;
- }
-
- var attributes = {};
- var verify = attributesString.replace(/(\w+)="([^"\\]*)"\s*(?:,\s*|$)/g, function ($0, $1, $2) {
-
- // Check valid attribute names
-
- if (keys.indexOf($1) === -1) {
- return;
- }
-
- // Allowed attribute value characters: !#$%&'()*+,-./:;<=>?@[]^_`{|}~ and space, a-z, A-Z, 0-9
-
- if ($2.match(/^[ \w\!#\$%&'\(\)\*\+,\-\.\/\:;<\=>\?@\[\]\^`\{\|\}~]+$/) === null) {
- return;
- }
-
- // Check for duplicates
-
- if (attributes.hasOwnProperty($1)) {
- return;
- }
-
- attributes[$1] = $2;
- return '';
- });
-
- if (verify !== '') {
- return null;
- }
-
- return attributes;
- },
-
- randomString: function (size) {
-
- var randomSource = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
- var len = randomSource.length;
-
- var result = [];
- for (var i = 0; i < size; ++i) {
- result[i] = randomSource[Math.floor(Math.random() * len)];
- }
-
- return result.join('');
- },
-
- uriRegex: /^([^:]+)\:\/\/(?:[^@]*@)?([^\/:]+)(?:\:(\d+))?([^#]*)(?:#.*)?$/, // scheme://credentials@host:port/resource#fragment
- parseUri: function (input) {
-
- var parts = input.match(hawk.utils.uriRegex);
- if (!parts) {
- return { host: '', port: '', resource: '' };
- }
-
- var scheme = parts[1].toLowerCase();
- var uri = {
- host: parts[2],
- port: parts[3] || (scheme === 'http' ? '80' : (scheme === 'https' ? '443' : '')),
- resource: parts[4]
- };
-
- return uri;
- },
-
- base64urlEncode: function (value) {
-
- var wordArray = CryptoJS.enc.Utf8.parse(value);
- var encoded = CryptoJS.enc.Base64.stringify(wordArray);
- return encoded.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');
- }
-};
-
-
-// $lab:coverage:off$
-/* eslint-disable */
-
-// Based on: Crypto-JS v3.1.2
-// Copyright (c) 2009-2013, Jeff Mott. All rights reserved.
-// http://code.google.com/p/crypto-js/
-// http://code.google.com/p/crypto-js/wiki/License
-
-var CryptoJS = CryptoJS || function (h, r) { var k = {}, l = k.lib = {}, n = function () { }, f = l.Base = { extend: function (a) { n.prototype = this; var b = new n; a && b.mixIn(a); b.hasOwnProperty("init") || (b.init = function () { b.$super.init.apply(this, arguments) }); b.init.prototype = b; b.$super = this; return b }, create: function () { var a = this.extend(); a.init.apply(a, arguments); return a }, init: function () { }, mixIn: function (a) { for (var b in a) a.hasOwnProperty(b) && (this[b] = a[b]); a.hasOwnProperty("toString") && (this.toString = a.toString) }, clone: function () { return this.init.prototype.extend(this) } }, j = l.WordArray = f.extend({ init: function (a, b) { a = this.words = a || []; this.sigBytes = b != r ? b : 4 * a.length }, toString: function (a) { return (a || s).stringify(this) }, concat: function (a) { var b = this.words, d = a.words, c = this.sigBytes; a = a.sigBytes; this.clamp(); if (c % 4) for (var e = 0; e < a; e++) b[c + e >>> 2] |= (d[e >>> 2] >>> 24 - 8 * (e % 4) & 255) << 24 - 8 * ((c + e) % 4); else if (65535 < d.length) for (e = 0; e < a; e += 4) b[c + e >>> 2] = d[e >>> 2]; else b.push.apply(b, d); this.sigBytes += a; return this }, clamp: function () { var a = this.words, b = this.sigBytes; a[b >>> 2] &= 4294967295 << 32 - 8 * (b % 4); a.length = h.ceil(b / 4) }, clone: function () { var a = f.clone.call(this); a.words = this.words.slice(0); return a }, random: function (a) { for (var b = [], d = 0; d < a; d += 4) b.push(4294967296 * h.random() | 0); return new j.init(b, a) } }), m = k.enc = {}, s = m.Hex = { stringify: function (a) { var b = a.words; a = a.sigBytes; for (var d = [], c = 0; c < a; c++) { var e = b[c >>> 2] >>> 24 - 8 * (c % 4) & 255; d.push((e >>> 4).toString(16)); d.push((e & 15).toString(16)) } return d.join("") }, parse: function (a) { for (var b = a.length, d = [], c = 0; c < b; c += 2) d[c >>> 3] |= parseInt(a.substr(c, 2), 16) << 24 - 4 * (c % 8); return new j.init(d, b / 2) } }, p = m.Latin1 = { stringify: function (a) { var b = a.words; a = a.sigBytes; for (var d = [], c = 0; c < a; c++) d.push(String.fromCharCode(b[c >>> 2] >>> 24 - 8 * (c % 4) & 255)); return d.join("") }, parse: function (a) { for (var b = a.length, d = [], c = 0; c < b; c++) d[c >>> 2] |= (a.charCodeAt(c) & 255) << 24 - 8 * (c % 4); return new j.init(d, b) } }, t = m.Utf8 = { stringify: function (a) { try { return decodeURIComponent(escape(p.stringify(a))) } catch (b) { throw Error("Malformed UTF-8 data"); } }, parse: function (a) { return p.parse(unescape(encodeURIComponent(a))) } }, q = l.BufferedBlockAlgorithm = f.extend({ reset: function () { this._data = new j.init; this._nDataBytes = 0 }, _append: function (a) { "string" == typeof a && (a = t.parse(a)); this._data.concat(a); this._nDataBytes += a.sigBytes }, _process: function (a) { var b = this._data, d = b.words, c = b.sigBytes, e = this.blockSize, f = c / (4 * e), f = a ? h.ceil(f) : h.max((f | 0) - this._minBufferSize, 0); a = f * e; c = h.min(4 * a, c); if (a) { for (var g = 0; g < a; g += e) this._doProcessBlock(d, g); g = d.splice(0, a); b.sigBytes -= c } return new j.init(g, c) }, clone: function () { var a = f.clone.call(this); a._data = this._data.clone(); return a }, _minBufferSize: 0 }); l.Hasher = q.extend({ cfg: f.extend(), init: function (a) { this.cfg = this.cfg.extend(a); this.reset() }, reset: function () { q.reset.call(this); this._doReset() }, update: function (a) { this._append(a); this._process(); return this }, finalize: function (a) { a && this._append(a); return this._doFinalize() }, blockSize: 16, _createHelper: function (a) { return function (b, d) { return (new a.init(d)).finalize(b) } }, _createHmacHelper: function (a) { return function (b, d) { return (new u.HMAC.init(a, d)).finalize(b) } } }); var u = k.algo = {}; return k }(Math);
-(function () { var k = CryptoJS, b = k.lib, m = b.WordArray, l = b.Hasher, d = [], b = k.algo.SHA1 = l.extend({ _doReset: function () { this._hash = new m.init([1732584193, 4023233417, 2562383102, 271733878, 3285377520]) }, _doProcessBlock: function (n, p) { for (var a = this._hash.words, e = a[0], f = a[1], h = a[2], j = a[3], b = a[4], c = 0; 80 > c; c++) { if (16 > c) d[c] = n[p + c] | 0; else { var g = d[c - 3] ^ d[c - 8] ^ d[c - 14] ^ d[c - 16]; d[c] = g << 1 | g >>> 31 } g = (e << 5 | e >>> 27) + b + d[c]; g = 20 > c ? g + ((f & h | ~f & j) + 1518500249) : 40 > c ? g + ((f ^ h ^ j) + 1859775393) : 60 > c ? g + ((f & h | f & j | h & j) - 1894007588) : g + ((f ^ h ^ j) - 899497514); b = j; j = h; h = f << 30 | f >>> 2; f = e; e = g } a[0] = a[0] + e | 0; a[1] = a[1] + f | 0; a[2] = a[2] + h | 0; a[3] = a[3] + j | 0; a[4] = a[4] + b | 0 }, _doFinalize: function () { var b = this._data, d = b.words, a = 8 * this._nDataBytes, e = 8 * b.sigBytes; d[e >>> 5] |= 128 << 24 - e % 32; d[(e + 64 >>> 9 << 4) + 14] = Math.floor(a / 4294967296); d[(e + 64 >>> 9 << 4) + 15] = a; b.sigBytes = 4 * d.length; this._process(); return this._hash }, clone: function () { var b = l.clone.call(this); b._hash = this._hash.clone(); return b } }); k.SHA1 = l._createHelper(b); k.HmacSHA1 = l._createHmacHelper(b) })();
-(function (k) { for (var g = CryptoJS, h = g.lib, v = h.WordArray, j = h.Hasher, h = g.algo, s = [], t = [], u = function (q) { return 4294967296 * (q - (q | 0)) | 0 }, l = 2, b = 0; 64 > b;) { var d; a: { d = l; for (var w = k.sqrt(d), r = 2; r <= w; r++) if (!(d % r)) { d = !1; break a } d = !0 } d && (8 > b && (s[b] = u(k.pow(l, 0.5))), t[b] = u(k.pow(l, 1 / 3)), b++); l++ } var n = [], h = h.SHA256 = j.extend({ _doReset: function () { this._hash = new v.init(s.slice(0)) }, _doProcessBlock: function (q, h) { for (var a = this._hash.words, c = a[0], d = a[1], b = a[2], k = a[3], f = a[4], g = a[5], j = a[6], l = a[7], e = 0; 64 > e; e++) { if (16 > e) n[e] = q[h + e] | 0; else { var m = n[e - 15], p = n[e - 2]; n[e] = ((m << 25 | m >>> 7) ^ (m << 14 | m >>> 18) ^ m >>> 3) + n[e - 7] + ((p << 15 | p >>> 17) ^ (p << 13 | p >>> 19) ^ p >>> 10) + n[e - 16] } m = l + ((f << 26 | f >>> 6) ^ (f << 21 | f >>> 11) ^ (f << 7 | f >>> 25)) + (f & g ^ ~f & j) + t[e] + n[e]; p = ((c << 30 | c >>> 2) ^ (c << 19 | c >>> 13) ^ (c << 10 | c >>> 22)) + (c & d ^ c & b ^ d & b); l = j; j = g; g = f; f = k + m | 0; k = b; b = d; d = c; c = m + p | 0 } a[0] = a[0] + c | 0; a[1] = a[1] + d | 0; a[2] = a[2] + b | 0; a[3] = a[3] + k | 0; a[4] = a[4] + f | 0; a[5] = a[5] + g | 0; a[6] = a[6] + j | 0; a[7] = a[7] + l | 0 }, _doFinalize: function () { var d = this._data, b = d.words, a = 8 * this._nDataBytes, c = 8 * d.sigBytes; b[c >>> 5] |= 128 << 24 - c % 32; b[(c + 64 >>> 9 << 4) + 14] = k.floor(a / 4294967296); b[(c + 64 >>> 9 << 4) + 15] = a; d.sigBytes = 4 * b.length; this._process(); return this._hash }, clone: function () { var b = j.clone.call(this); b._hash = this._hash.clone(); return b } }); g.SHA256 = j._createHelper(h); g.HmacSHA256 = j._createHmacHelper(h) })(Math);
-(function () { var c = CryptoJS, k = c.enc.Utf8; c.algo.HMAC = c.lib.Base.extend({ init: function (a, b) { a = this._hasher = new a.init; "string" == typeof b && (b = k.parse(b)); var c = a.blockSize, e = 4 * c; b.sigBytes > e && (b = a.finalize(b)); b.clamp(); for (var f = this._oKey = b.clone(), g = this._iKey = b.clone(), h = f.words, j = g.words, d = 0; d < c; d++) h[d] ^= 1549556828, j[d] ^= 909522486; f.sigBytes = g.sigBytes = e; this.reset() }, reset: function () { var a = this._hasher; a.reset(); a.update(this._iKey) }, update: function (a) { this._hasher.update(a); return this }, finalize: function (a) { var b = this._hasher; a = b.finalize(a); b.reset(); return b.finalize(this._oKey.clone().concat(a)) } }) })();
-(function () { var h = CryptoJS, j = h.lib.WordArray; h.enc.Base64 = { stringify: function (b) { var e = b.words, f = b.sigBytes, c = this._map; b.clamp(); b = []; for (var a = 0; a < f; a += 3) for (var d = (e[a >>> 2] >>> 24 - 8 * (a % 4) & 255) << 16 | (e[a + 1 >>> 2] >>> 24 - 8 * ((a + 1) % 4) & 255) << 8 | e[a + 2 >>> 2] >>> 24 - 8 * ((a + 2) % 4) & 255, g = 0; 4 > g && a + 0.75 * g < f; g++) b.push(c.charAt(d >>> 6 * (3 - g) & 63)); if (e = c.charAt(64)) for (; b.length % 4;) b.push(e); return b.join("") }, parse: function (b) { var e = b.length, f = this._map, c = f.charAt(64); c && (c = b.indexOf(c), -1 != c && (e = c)); for (var c = [], a = 0, d = 0; d < e; d++) if (d % 4) { var g = f.indexOf(b.charAt(d - 1)) << 2 * (d % 4), h = f.indexOf(b.charAt(d)) >>> 6 - 2 * (d % 4); c[a >>> 2] |= (g | h) << 24 - 8 * (a % 4); a++ } return j.create(c, a) }, _map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" } })();
-
-hawk.crypto.internals = CryptoJS;
-
-
-// Export if used as a module
-
-if (typeof module !== 'undefined' && module.exports) {
- module.exports = hawk;
-}
-
-/* eslint-enable */
-// $lab:coverage:on$
+/*
+ HTTP Hawk Authentication Scheme
+ Copyright (c) 2012-2014, Eran Hammer <eran@hammer.io>
+ BSD Licensed
+*/
+
+
+// Declare namespace
+
+var hawk = {
+ internals: {}
+};
+
+
+hawk.client = {
+
+ // Generate an Authorization header for a given request
+
+ /*
+ uri: 'http://example.com/resource?a=b' or object generated by hawk.utils.parseUri()
+ method: HTTP verb (e.g. 'GET', 'POST')
+ options: {
+
+ // Required
+
+ credentials: {
+ id: 'dh37fgj492je',
+ key: 'aoijedoaijsdlaksjdl',
+ algorithm: 'sha256' // 'sha1', 'sha256'
+ },
+
+ // Optional
+
+ ext: 'application-specific', // Application specific data sent via the ext attribute
+ timestamp: Date.now() / 1000, // A pre-calculated timestamp in seconds
+ nonce: '2334f34f', // A pre-generated nonce
+ localtimeOffsetMsec: 400, // Time offset to sync with server time (ignored if timestamp provided)
+ payload: '{"some":"payload"}', // UTF-8 encoded string for body hash generation (ignored if hash provided)
+ contentType: 'application/json', // Payload content-type (ignored if hash provided)
+ hash: 'U4MKKSmiVxk37JCCrAVIjV=', // Pre-calculated payload hash
+ app: '24s23423f34dx', // Oz application id
+ dlg: '234sz34tww3sd' // Oz delegated-by application id
+ }
+ */
+
+ header: function (uri, method, options) {
+
+ var result = {
+ field: '',
+ artifacts: {}
+ };
+
+ // Validate inputs
+
+ if (!uri || (typeof uri !== 'string' && typeof uri !== 'object') ||
+ !method || typeof method !== 'string' ||
+ !options || typeof options !== 'object') {
+
+ result.err = 'Invalid argument type';
+ return result;
+ }
+
+ // Application time
+
+ var timestamp = options.timestamp || hawk.utils.now(options.localtimeOffsetMsec);
+
+ // Validate credentials
+
+ var credentials = options.credentials;
+ if (!credentials ||
+ !credentials.id ||
+ !credentials.key ||
+ !credentials.algorithm) {
+
+ result.err = 'Invalid credentials object';
+ return result;
+ }
+
+ if (hawk.crypto.algorithms.indexOf(credentials.algorithm) === -1) {
+ result.err = 'Unknown algorithm';
+ return result;
+ }
+
+ // Parse URI
+
+ if (typeof uri === 'string') {
+ uri = hawk.utils.parseUri(uri);
+ }
+
+ // Calculate signature
+
+ var artifacts = {
+ ts: timestamp,
+ nonce: options.nonce || hawk.utils.randomString(6),
+ method: method,
+ resource: uri.resource,
+ host: uri.host,
+ port: uri.port,
+ hash: options.hash,
+ ext: options.ext,
+ app: options.app,
+ dlg: options.dlg
+ };
+
+ result.artifacts = artifacts;
+
+ // Calculate payload hash
+
+ if (!artifacts.hash &&
+ (options.payload || options.payload === '')) {
+
+ artifacts.hash = hawk.crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType);
+ }
+
+ var mac = hawk.crypto.calculateMac('header', credentials, artifacts);
+
+ // Construct header
+
+ var hasExt = artifacts.ext !== null && artifacts.ext !== undefined && artifacts.ext !== ''; // Other falsey values allowed
+ var header = 'Hawk id="' + credentials.id +
+ '", ts="' + artifacts.ts +
+ '", nonce="' + artifacts.nonce +
+ (artifacts.hash ? '", hash="' + artifacts.hash : '') +
+ (hasExt ? '", ext="' + hawk.utils.escapeHeaderAttribute(artifacts.ext) : '') +
+ '", mac="' + mac + '"';
+
+ if (artifacts.app) {
+ header += ', app="' + artifacts.app +
+ (artifacts.dlg ? '", dlg="' + artifacts.dlg : '') + '"';
+ }
+
+ result.field = header;
+
+ return result;
+ },
+
+ // Generate a bewit value for a given URI
+
+ /*
+ uri: 'http://example.com/resource?a=b'
+ options: {
+
+ // Required
+
+ credentials: {
+ id: 'dh37fgj492je',
+ key: 'aoijedoaijsdlaksjdl',
+ algorithm: 'sha256' // 'sha1', 'sha256'
+ },
+ ttlSec: 60 * 60, // TTL in seconds
+
+ // Optional
+
+ ext: 'application-specific', // Application specific data sent via the ext attribute
+ localtimeOffsetMsec: 400 // Time offset to sync with server time
+ };
+ */
+
+ bewit: function (uri, options) {
+
+ // Validate inputs
+
+ if (!uri ||
+ (typeof uri !== 'string') ||
+ !options ||
+ typeof options !== 'object' ||
+ !options.ttlSec) {
+
+ return '';
+ }
+
+ options.ext = (options.ext === null || options.ext === undefined ? '' : options.ext); // Zero is valid value
+
+ // Application time
+
+ var now = hawk.utils.now(options.localtimeOffsetMsec);
+
+ // Validate credentials
+
+ var credentials = options.credentials;
+ if (!credentials ||
+ !credentials.id ||
+ !credentials.key ||
+ !credentials.algorithm) {
+
+ return '';
+ }
+
+ if (hawk.crypto.algorithms.indexOf(credentials.algorithm) === -1) {
+ return '';
+ }
+
+ // Parse URI
+
+ uri = hawk.utils.parseUri(uri);
+
+ // Calculate signature
+
+ var exp = now + options.ttlSec;
+ var mac = hawk.crypto.calculateMac('bewit', credentials, {
+ ts: exp,
+ nonce: '',
+ method: 'GET',
+ resource: uri.resource, // Maintain trailing '?' and query params
+ host: uri.host,
+ port: uri.port,
+ ext: options.ext
+ });
+
+ // Construct bewit: id\exp\mac\ext
+
+ var bewit = credentials.id + '\\' + exp + '\\' + mac + '\\' + options.ext;
+ return hawk.utils.base64urlEncode(bewit);
+ },
+
+ // Validate server response
+
+ /*
+ request: object created via 'new XMLHttpRequest()' after response received
+ artifacts: object received from header().artifacts
+ options: {
+ payload: optional payload received
+ required: specifies if a Server-Authorization header is required. Defaults to 'false'
+ }
+ */
+
+ authenticate: function (request, credentials, artifacts, options) {
+
+ options = options || {};
+
+ var getHeader = function (name) {
+
+ return request.getResponseHeader ? request.getResponseHeader(name) : request.getHeader(name);
+ };
+
+ var wwwAuthenticate = getHeader('www-authenticate');
+ if (wwwAuthenticate) {
+
+ // Parse HTTP WWW-Authenticate header
+
+ var wwwAttributes = hawk.utils.parseAuthorizationHeader(wwwAuthenticate, ['ts', 'tsm', 'error']);
+ if (!wwwAttributes) {
+ return false;
+ }
+
+ if (wwwAttributes.ts) {
+ var tsm = hawk.crypto.calculateTsMac(wwwAttributes.ts, credentials);
+ if (tsm !== wwwAttributes.tsm) {
+ return false;
+ }
+
+ hawk.utils.setNtpOffset(wwwAttributes.ts - Math.floor((new Date()).getTime() / 1000)); // Keep offset at 1 second precision
+ }
+ }
+
+ // Parse HTTP Server-Authorization header
+
+ var serverAuthorization = getHeader('server-authorization');
+ if (!serverAuthorization &&
+ !options.required) {
+
+ return true;
+ }
+
+ var attributes = hawk.utils.parseAuthorizationHeader(serverAuthorization, ['mac', 'ext', 'hash']);
+ if (!attributes) {
+ return false;
+ }
+
+ var modArtifacts = {
+ ts: artifacts.ts,
+ nonce: artifacts.nonce,
+ method: artifacts.method,
+ resource: artifacts.resource,
+ host: artifacts.host,
+ port: artifacts.port,
+ hash: attributes.hash,
+ ext: attributes.ext,
+ app: artifacts.app,
+ dlg: artifacts.dlg
+ };
+
+ var mac = hawk.crypto.calculateMac('response', credentials, modArtifacts);
+ if (mac !== attributes.mac) {
+ return false;
+ }
+
+ if (!options.payload &&
+ options.payload !== '') {
+
+ return true;
+ }
+
+ if (!attributes.hash) {
+ return false;
+ }
+
+ var calculatedHash = hawk.crypto.calculatePayloadHash(options.payload, credentials.algorithm, getHeader('content-type'));
+ return (calculatedHash === attributes.hash);
+ },
+
+ message: function (host, port, message, options) {
+
+ // Validate inputs
+
+ if (!host || typeof host !== 'string' ||
+ !port || typeof port !== 'number' ||
+ message === null || message === undefined || typeof message !== 'string' ||
+ !options || typeof options !== 'object') {
+
+ return null;
+ }
+
+ // Application time
+
+ var timestamp = options.timestamp || hawk.utils.now(options.localtimeOffsetMsec);
+
+ // Validate credentials
+
+ var credentials = options.credentials;
+ if (!credentials ||
+ !credentials.id ||
+ !credentials.key ||
+ !credentials.algorithm) {
+
+ // Invalid credential object
+ return null;
+ }
+
+ if (hawk.crypto.algorithms.indexOf(credentials.algorithm) === -1) {
+ return null;
+ }
+
+ // Calculate signature
+
+ var artifacts = {
+ ts: timestamp,
+ nonce: options.nonce || hawk.utils.randomString(6),
+ host: host,
+ port: port,
+ hash: hawk.crypto.calculatePayloadHash(message, credentials.algorithm)
+ };
+
+ // Construct authorization
+
+ var result = {
+ id: credentials.id,
+ ts: artifacts.ts,
+ nonce: artifacts.nonce,
+ hash: artifacts.hash,
+ mac: hawk.crypto.calculateMac('message', credentials, artifacts)
+ };
+
+ return result;
+ },
+
+ authenticateTimestamp: function (message, credentials, updateClock) { // updateClock defaults to true
+
+ var tsm = hawk.crypto.calculateTsMac(message.ts, credentials);
+ if (tsm !== message.tsm) {
+ return false;
+ }
+
+ if (updateClock !== false) {
+ hawk.utils.setNtpOffset(message.ts - Math.floor((new Date()).getTime() / 1000)); // Keep offset at 1 second precision
+ }
+
+ return true;
+ }
+};
+
+
+hawk.crypto = {
+
+ headerVersion: '1',
+
+ algorithms: ['sha1', 'sha256'],
+
+ calculateMac: function (type, credentials, options) {
+
+ var normalized = hawk.crypto.generateNormalizedString(type, options);
+
+ var hmac = CryptoJS['Hmac' + credentials.algorithm.toUpperCase()](normalized, credentials.key);
+ return hmac.toString(CryptoJS.enc.Base64);
+ },
+
+ generateNormalizedString: function (type, options) {
+
+ var normalized = 'hawk.' + hawk.crypto.headerVersion + '.' + type + '\n' +
+ options.ts + '\n' +
+ options.nonce + '\n' +
+ (options.method || '').toUpperCase() + '\n' +
+ (options.resource || '') + '\n' +
+ options.host.toLowerCase() + '\n' +
+ options.port + '\n' +
+ (options.hash || '') + '\n';
+
+ if (options.ext) {
+ normalized += options.ext.replace('\\', '\\\\').replace('\n', '\\n');
+ }
+
+ normalized += '\n';
+
+ if (options.app) {
+ normalized += options.app + '\n' +
+ (options.dlg || '') + '\n';
+ }
+
+ return normalized;
+ },
+
+ calculatePayloadHash: function (payload, algorithm, contentType) {
+
+ var hash = CryptoJS.algo[algorithm.toUpperCase()].create();
+ hash.update('hawk.' + hawk.crypto.headerVersion + '.payload\n');
+ hash.update(hawk.utils.parseContentType(contentType) + '\n');
+ hash.update(payload);
+ hash.update('\n');
+ return hash.finalize().toString(CryptoJS.enc.Base64);
+ },
+
+ calculateTsMac: function (ts, credentials) {
+
+ var hash = CryptoJS['Hmac' + credentials.algorithm.toUpperCase()]('hawk.' + hawk.crypto.headerVersion + '.ts\n' + ts + '\n', credentials.key);
+ return hash.toString(CryptoJS.enc.Base64);
+ }
+};
+
+
+// localStorage compatible interface
+
+hawk.internals.LocalStorage = function () {
+
+ this._cache = {};
+ this.length = 0;
+
+ this.getItem = function (key) {
+
+ return this._cache.hasOwnProperty(key) ? String(this._cache[key]) : null;
+ };
+
+ this.setItem = function (key, value) {
+
+ this._cache[key] = String(value);
+ this.length = Object.keys(this._cache).length;
+ };
+
+ this.removeItem = function (key) {
+
+ delete this._cache[key];
+ this.length = Object.keys(this._cache).length;
+ };
+
+ this.clear = function () {
+
+ this._cache = {};
+ this.length = 0;
+ };
+
+ this.key = function (i) {
+
+ return Object.keys(this._cache)[i || 0];
+ };
+};
+
+
+hawk.utils = {
+
+ storage: new hawk.internals.LocalStorage(),
+
+ setStorage: function (storage) {
+
+ var ntpOffset = hawk.utils.storage.getItem('hawk_ntp_offset');
+ hawk.utils.storage = storage;
+ if (ntpOffset) {
+ hawk.utils.setNtpOffset(ntpOffset);
+ }
+ },
+
+ setNtpOffset: function (offset) {
+
+ try {
+ hawk.utils.storage.setItem('hawk_ntp_offset', offset);
+ }
+ catch (err) {
+ console.error('[hawk] could not write to storage.');
+ console.error(err);
+ }
+ },
+
+ getNtpOffset: function () {
+
+ var offset = hawk.utils.storage.getItem('hawk_ntp_offset');
+ if (!offset) {
+ return 0;
+ }
+
+ return parseInt(offset, 10);
+ },
+
+ now: function (localtimeOffsetMsec) {
+
+ return Math.floor(((new Date()).getTime() + (localtimeOffsetMsec || 0)) / 1000) + hawk.utils.getNtpOffset();
+ },
+
+ escapeHeaderAttribute: function (attribute) {
+
+ return attribute.replace(/\\/g, '\\\\').replace(/\"/g, '\\"');
+ },
+
+ parseContentType: function (header) {
+
+ if (!header) {
+ return '';
+ }
+
+ return header.split(';')[0].replace(/^\s+|\s+$/g, '').toLowerCase();
+ },
+
+ parseAuthorizationHeader: function (header, keys) {
+
+ if (!header) {
+ return null;
+ }
+
+ var headerParts = header.match(/^(\w+)(?:\s+(.*))?$/); // Header: scheme[ something]
+ if (!headerParts) {
+ return null;
+ }
+
+ var scheme = headerParts[1];
+ if (scheme.toLowerCase() !== 'hawk') {
+ return null;
+ }
+
+ var attributesString = headerParts[2];
+ if (!attributesString) {
+ return null;
+ }
+
+ var attributes = {};
+ var verify = attributesString.replace(/(\w+)="([^"\\]*)"\s*(?:,\s*|$)/g, function ($0, $1, $2) {
+
+ // Check valid attribute names
+
+ if (keys.indexOf($1) === -1) {
+ return;
+ }
+
+ // Allowed attribute value characters: !#$%&'()*+,-./:;<=>?@[]^_`{|}~ and space, a-z, A-Z, 0-9
+
+ if ($2.match(/^[ \w\!#\$%&'\(\)\*\+,\-\.\/\:;<\=>\?@\[\]\^`\{\|\}~]+$/) === null) {
+ return;
+ }
+
+ // Check for duplicates
+
+ if (attributes.hasOwnProperty($1)) {
+ return;
+ }
+
+ attributes[$1] = $2;
+ return '';
+ });
+
+ if (verify !== '') {
+ return null;
+ }
+
+ return attributes;
+ },
+
+ randomString: function (size) {
+
+ var randomSource = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
+ var len = randomSource.length;
+
+ var result = [];
+ for (var i = 0; i < size; ++i) {
+ result[i] = randomSource[Math.floor(Math.random() * len)];
+ }
+
+ return result.join('');
+ },
+
+ uriRegex: /^([^:]+)\:\/\/(?:[^@]*@)?([^\/:]+)(?:\:(\d+))?([^#]*)(?:#.*)?$/, // scheme://credentials@host:port/resource#fragment
+ parseUri: function (input) {
+
+ var parts = input.match(hawk.utils.uriRegex);
+ if (!parts) {
+ return { host: '', port: '', resource: '' };
+ }
+
+ var scheme = parts[1].toLowerCase();
+ var uri = {
+ host: parts[2],
+ port: parts[3] || (scheme === 'http' ? '80' : (scheme === 'https' ? '443' : '')),
+ resource: parts[4]
+ };
+
+ return uri;
+ },
+
+ base64urlEncode: function (value) {
+
+ var wordArray = CryptoJS.enc.Utf8.parse(value);
+ var encoded = CryptoJS.enc.Base64.stringify(wordArray);
+ return encoded.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');
+ }
+};
+
+
+// $lab:coverage:off$
+/* eslint-disable */
+
+// Based on: Crypto-JS v3.1.2
+// Copyright (c) 2009-2013, Jeff Mott. All rights reserved.
+// http://code.google.com/p/crypto-js/
+// http://code.google.com/p/crypto-js/wiki/License
+
+var CryptoJS = CryptoJS || function (h, r) { var k = {}, l = k.lib = {}, n = function () { }, f = l.Base = { extend: function (a) { n.prototype = this; var b = new n; a && b.mixIn(a); b.hasOwnProperty("init") || (b.init = function () { b.$super.init.apply(this, arguments) }); b.init.prototype = b; b.$super = this; return b }, create: function () { var a = this.extend(); a.init.apply(a, arguments); return a }, init: function () { }, mixIn: function (a) { for (var b in a) a.hasOwnProperty(b) && (this[b] = a[b]); a.hasOwnProperty("toString") && (this.toString = a.toString) }, clone: function () { return this.init.prototype.extend(this) } }, j = l.WordArray = f.extend({ init: function (a, b) { a = this.words = a || []; this.sigBytes = b != r ? b : 4 * a.length }, toString: function (a) { return (a || s).stringify(this) }, concat: function (a) { var b = this.words, d = a.words, c = this.sigBytes; a = a.sigBytes; this.clamp(); if (c % 4) for (var e = 0; e < a; e++) b[c + e >>> 2] |= (d[e >>> 2] >>> 24 - 8 * (e % 4) & 255) << 24 - 8 * ((c + e) % 4); else if (65535 < d.length) for (e = 0; e < a; e += 4) b[c + e >>> 2] = d[e >>> 2]; else b.push.apply(b, d); this.sigBytes += a; return this }, clamp: function () { var a = this.words, b = this.sigBytes; a[b >>> 2] &= 4294967295 << 32 - 8 * (b % 4); a.length = h.ceil(b / 4) }, clone: function () { var a = f.clone.call(this); a.words = this.words.slice(0); return a }, random: function (a) { for (var b = [], d = 0; d < a; d += 4) b.push(4294967296 * h.random() | 0); return new j.init(b, a) } }), m = k.enc = {}, s = m.Hex = { stringify: function (a) { var b = a.words; a = a.sigBytes; for (var d = [], c = 0; c < a; c++) { var e = b[c >>> 2] >>> 24 - 8 * (c % 4) & 255; d.push((e >>> 4).toString(16)); d.push((e & 15).toString(16)) } return d.join("") }, parse: function (a) { for (var b = a.length, d = [], c = 0; c < b; c += 2) d[c >>> 3] |= parseInt(a.substr(c, 2), 16) << 24 - 4 * (c % 8); return new j.init(d, b / 2) } }, p = m.Latin1 = { stringify: function (a) { var b = a.words; a = a.sigBytes; for (var d = [], c = 0; c < a; c++) d.push(String.fromCharCode(b[c >>> 2] >>> 24 - 8 * (c % 4) & 255)); return d.join("") }, parse: function (a) { for (var b = a.length, d = [], c = 0; c < b; c++) d[c >>> 2] |= (a.charCodeAt(c) & 255) << 24 - 8 * (c % 4); return new j.init(d, b) } }, t = m.Utf8 = { stringify: function (a) { try { return decodeURIComponent(escape(p.stringify(a))) } catch (b) { throw Error("Malformed UTF-8 data"); } }, parse: function (a) { return p.parse(unescape(encodeURIComponent(a))) } }, q = l.BufferedBlockAlgorithm = f.extend({ reset: function () { this._data = new j.init; this._nDataBytes = 0 }, _append: function (a) { "string" == typeof a && (a = t.parse(a)); this._data.concat(a); this._nDataBytes += a.sigBytes }, _process: function (a) { var b = this._data, d = b.words, c = b.sigBytes, e = this.blockSize, f = c / (4 * e), f = a ? h.ceil(f) : h.max((f | 0) - this._minBufferSize, 0); a = f * e; c = h.min(4 * a, c); if (a) { for (var g = 0; g < a; g += e) this._doProcessBlock(d, g); g = d.splice(0, a); b.sigBytes -= c } return new j.init(g, c) }, clone: function () { var a = f.clone.call(this); a._data = this._data.clone(); return a }, _minBufferSize: 0 }); l.Hasher = q.extend({ cfg: f.extend(), init: function (a) { this.cfg = this.cfg.extend(a); this.reset() }, reset: function () { q.reset.call(this); this._doReset() }, update: function (a) { this._append(a); this._process(); return this }, finalize: function (a) { a && this._append(a); return this._doFinalize() }, blockSize: 16, _createHelper: function (a) { return function (b, d) { return (new a.init(d)).finalize(b) } }, _createHmacHelper: function (a) { return function (b, d) { return (new u.HMAC.init(a, d)).finalize(b) } } }); var u = k.algo = {}; return k }(Math);
+(function () { var k = CryptoJS, b = k.lib, m = b.WordArray, l = b.Hasher, d = [], b = k.algo.SHA1 = l.extend({ _doReset: function () { this._hash = new m.init([1732584193, 4023233417, 2562383102, 271733878, 3285377520]) }, _doProcessBlock: function (n, p) { for (var a = this._hash.words, e = a[0], f = a[1], h = a[2], j = a[3], b = a[4], c = 0; 80 > c; c++) { if (16 > c) d[c] = n[p + c] | 0; else { var g = d[c - 3] ^ d[c - 8] ^ d[c - 14] ^ d[c - 16]; d[c] = g << 1 | g >>> 31 } g = (e << 5 | e >>> 27) + b + d[c]; g = 20 > c ? g + ((f & h | ~f & j) + 1518500249) : 40 > c ? g + ((f ^ h ^ j) + 1859775393) : 60 > c ? g + ((f & h | f & j | h & j) - 1894007588) : g + ((f ^ h ^ j) - 899497514); b = j; j = h; h = f << 30 | f >>> 2; f = e; e = g } a[0] = a[0] + e | 0; a[1] = a[1] + f | 0; a[2] = a[2] + h | 0; a[3] = a[3] + j | 0; a[4] = a[4] + b | 0 }, _doFinalize: function () { var b = this._data, d = b.words, a = 8 * this._nDataBytes, e = 8 * b.sigBytes; d[e >>> 5] |= 128 << 24 - e % 32; d[(e + 64 >>> 9 << 4) + 14] = Math.floor(a / 4294967296); d[(e + 64 >>> 9 << 4) + 15] = a; b.sigBytes = 4 * d.length; this._process(); return this._hash }, clone: function () { var b = l.clone.call(this); b._hash = this._hash.clone(); return b } }); k.SHA1 = l._createHelper(b); k.HmacSHA1 = l._createHmacHelper(b) })();
+(function (k) { for (var g = CryptoJS, h = g.lib, v = h.WordArray, j = h.Hasher, h = g.algo, s = [], t = [], u = function (q) { return 4294967296 * (q - (q | 0)) | 0 }, l = 2, b = 0; 64 > b;) { var d; a: { d = l; for (var w = k.sqrt(d), r = 2; r <= w; r++) if (!(d % r)) { d = !1; break a } d = !0 } d && (8 > b && (s[b] = u(k.pow(l, 0.5))), t[b] = u(k.pow(l, 1 / 3)), b++); l++ } var n = [], h = h.SHA256 = j.extend({ _doReset: function () { this._hash = new v.init(s.slice(0)) }, _doProcessBlock: function (q, h) { for (var a = this._hash.words, c = a[0], d = a[1], b = a[2], k = a[3], f = a[4], g = a[5], j = a[6], l = a[7], e = 0; 64 > e; e++) { if (16 > e) n[e] = q[h + e] | 0; else { var m = n[e - 15], p = n[e - 2]; n[e] = ((m << 25 | m >>> 7) ^ (m << 14 | m >>> 18) ^ m >>> 3) + n[e - 7] + ((p << 15 | p >>> 17) ^ (p << 13 | p >>> 19) ^ p >>> 10) + n[e - 16] } m = l + ((f << 26 | f >>> 6) ^ (f << 21 | f >>> 11) ^ (f << 7 | f >>> 25)) + (f & g ^ ~f & j) + t[e] + n[e]; p = ((c << 30 | c >>> 2) ^ (c << 19 | c >>> 13) ^ (c << 10 | c >>> 22)) + (c & d ^ c & b ^ d & b); l = j; j = g; g = f; f = k + m | 0; k = b; b = d; d = c; c = m + p | 0 } a[0] = a[0] + c | 0; a[1] = a[1] + d | 0; a[2] = a[2] + b | 0; a[3] = a[3] + k | 0; a[4] = a[4] + f | 0; a[5] = a[5] + g | 0; a[6] = a[6] + j | 0; a[7] = a[7] + l | 0 }, _doFinalize: function () { var d = this._data, b = d.words, a = 8 * this._nDataBytes, c = 8 * d.sigBytes; b[c >>> 5] |= 128 << 24 - c % 32; b[(c + 64 >>> 9 << 4) + 14] = k.floor(a / 4294967296); b[(c + 64 >>> 9 << 4) + 15] = a; d.sigBytes = 4 * b.length; this._process(); return this._hash }, clone: function () { var b = j.clone.call(this); b._hash = this._hash.clone(); return b } }); g.SHA256 = j._createHelper(h); g.HmacSHA256 = j._createHmacHelper(h) })(Math);
+(function () { var c = CryptoJS, k = c.enc.Utf8; c.algo.HMAC = c.lib.Base.extend({ init: function (a, b) { a = this._hasher = new a.init; "string" == typeof b && (b = k.parse(b)); var c = a.blockSize, e = 4 * c; b.sigBytes > e && (b = a.finalize(b)); b.clamp(); for (var f = this._oKey = b.clone(), g = this._iKey = b.clone(), h = f.words, j = g.words, d = 0; d < c; d++) h[d] ^= 1549556828, j[d] ^= 909522486; f.sigBytes = g.sigBytes = e; this.reset() }, reset: function () { var a = this._hasher; a.reset(); a.update(this._iKey) }, update: function (a) { this._hasher.update(a); return this }, finalize: function (a) { var b = this._hasher; a = b.finalize(a); b.reset(); return b.finalize(this._oKey.clone().concat(a)) } }) })();
+(function () { var h = CryptoJS, j = h.lib.WordArray; h.enc.Base64 = { stringify: function (b) { var e = b.words, f = b.sigBytes, c = this._map; b.clamp(); b = []; for (var a = 0; a < f; a += 3) for (var d = (e[a >>> 2] >>> 24 - 8 * (a % 4) & 255) << 16 | (e[a + 1 >>> 2] >>> 24 - 8 * ((a + 1) % 4) & 255) << 8 | e[a + 2 >>> 2] >>> 24 - 8 * ((a + 2) % 4) & 255, g = 0; 4 > g && a + 0.75 * g < f; g++) b.push(c.charAt(d >>> 6 * (3 - g) & 63)); if (e = c.charAt(64)) for (; b.length % 4;) b.push(e); return b.join("") }, parse: function (b) { var e = b.length, f = this._map, c = f.charAt(64); c && (c = b.indexOf(c), -1 != c && (e = c)); for (var c = [], a = 0, d = 0; d < e; d++) if (d % 4) { var g = f.indexOf(b.charAt(d - 1)) << 2 * (d % 4), h = f.indexOf(b.charAt(d)) >>> 6 - 2 * (d % 4); c[a >>> 2] |= (g | h) << 24 - 8 * (a % 4); a++ } return j.create(c, a) }, _map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" } })();
+
+hawk.crypto.internals = CryptoJS;
+
+
+// Export if used as a module
+
+if (typeof module !== 'undefined' && module.exports) {
+ module.exports = hawk;
+}
+
+/* eslint-enable */
+// $lab:coverage:on$
diff --git a/node_modules/request/node_modules/hawk/lib/client.js b/node_modules/request/node_modules/hawk/lib/client.js
index b3e8649e3..601f51ca1 100755
--- a/node_modules/request/node_modules/hawk/lib/client.js
+++ b/node_modules/request/node_modules/hawk/lib/client.js
@@ -1,369 +1,369 @@
-// Load modules
-
-var Url = require('url');
-var Hoek = require('hoek');
-var Cryptiles = require('cryptiles');
-var Crypto = require('./crypto');
-var Utils = require('./utils');
-
-
-// Declare internals
-
-var internals = {};
-
-
-// Generate an Authorization header for a given request
-
-/*
- uri: 'http://example.com/resource?a=b' or object from Url.parse()
- method: HTTP verb (e.g. 'GET', 'POST')
- options: {
-
- // Required
-
- credentials: {
- id: 'dh37fgj492je',
- key: 'aoijedoaijsdlaksjdl',
- algorithm: 'sha256' // 'sha1', 'sha256'
- },
-
- // Optional
-
- ext: 'application-specific', // Application specific data sent via the ext attribute
- timestamp: Date.now(), // A pre-calculated timestamp
- nonce: '2334f34f', // A pre-generated nonce
- localtimeOffsetMsec: 400, // Time offset to sync with server time (ignored if timestamp provided)
- payload: '{"some":"payload"}', // UTF-8 encoded string for body hash generation (ignored if hash provided)
- contentType: 'application/json', // Payload content-type (ignored if hash provided)
- hash: 'U4MKKSmiVxk37JCCrAVIjV=', // Pre-calculated payload hash
- app: '24s23423f34dx', // Oz application id
- dlg: '234sz34tww3sd' // Oz delegated-by application id
- }
-*/
-
-exports.header = function (uri, method, options) {
-
- var result = {
- field: '',
- artifacts: {}
- };
-
- // Validate inputs
-
- if (!uri || (typeof uri !== 'string' && typeof uri !== 'object') ||
- !method || typeof method !== 'string' ||
- !options || typeof options !== 'object') {
-
- result.err = 'Invalid argument type';
- return result;
- }
-
- // Application time
-
- var timestamp = options.timestamp || Utils.nowSecs(options.localtimeOffsetMsec);
-
- // Validate credentials
-
- var credentials = options.credentials;
- if (!credentials ||
- !credentials.id ||
- !credentials.key ||
- !credentials.algorithm) {
-
- result.err = 'Invalid credential object';
- return result;
- }
-
- if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
- result.err = 'Unknown algorithm';
- return result;
- }
-
- // Parse URI
-
- if (typeof uri === 'string') {
- uri = Url.parse(uri);
- }
-
- // Calculate signature
-
- var artifacts = {
- ts: timestamp,
- nonce: options.nonce || Cryptiles.randomString(6),
- method: method,
- resource: uri.pathname + (uri.search || ''), // Maintain trailing '?'
- host: uri.hostname,
- port: uri.port || (uri.protocol === 'http:' ? 80 : 443),
- hash: options.hash,
- ext: options.ext,
- app: options.app,
- dlg: options.dlg
- };
-
- result.artifacts = artifacts;
-
- // Calculate payload hash
-
- if (!artifacts.hash &&
- (options.payload || options.payload === '')) {
-
- artifacts.hash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType);
- }
-
- var mac = Crypto.calculateMac('header', credentials, artifacts);
-
- // Construct header
-
- var hasExt = artifacts.ext !== null && artifacts.ext !== undefined && artifacts.ext !== ''; // Other falsey values allowed
- var header = 'Hawk id="' + credentials.id +
- '", ts="' + artifacts.ts +
- '", nonce="' + artifacts.nonce +
- (artifacts.hash ? '", hash="' + artifacts.hash : '') +
- (hasExt ? '", ext="' + Hoek.escapeHeaderAttribute(artifacts.ext) : '') +
- '", mac="' + mac + '"';
-
- if (artifacts.app) {
- header += ', app="' + artifacts.app +
- (artifacts.dlg ? '", dlg="' + artifacts.dlg : '') + '"';
- }
-
- result.field = header;
-
- return result;
-};
-
-
-// Validate server response
-
-/*
- res: node's response object
- artifacts: object received from header().artifacts
- options: {
- payload: optional payload received
- required: specifies if a Server-Authorization header is required. Defaults to 'false'
- }
-*/
-
-exports.authenticate = function (res, credentials, artifacts, options) {
-
- artifacts = Hoek.clone(artifacts);
- options = options || {};
-
- if (res.headers['www-authenticate']) {
-
- // Parse HTTP WWW-Authenticate header
-
- var wwwAttributes = Utils.parseAuthorizationHeader(res.headers['www-authenticate'], ['ts', 'tsm', 'error']);
- if (wwwAttributes instanceof Error) {
- return false;
- }
-
- // Validate server timestamp (not used to update clock since it is done via the SNPT client)
-
- if (wwwAttributes.ts) {
- var tsm = Crypto.calculateTsMac(wwwAttributes.ts, credentials);
- if (tsm !== wwwAttributes.tsm) {
- return false;
- }
- }
- }
-
- // Parse HTTP Server-Authorization header
-
- if (!res.headers['server-authorization'] &&
- !options.required) {
-
- return true;
- }
-
- var attributes = Utils.parseAuthorizationHeader(res.headers['server-authorization'], ['mac', 'ext', 'hash']);
- if (attributes instanceof Error) {
- return false;
- }
-
- artifacts.ext = attributes.ext;
- artifacts.hash = attributes.hash;
-
- var mac = Crypto.calculateMac('response', credentials, artifacts);
- if (mac !== attributes.mac) {
- return false;
- }
-
- if (!options.payload &&
- options.payload !== '') {
-
- return true;
- }
-
- if (!attributes.hash) {
- return false;
- }
-
- var calculatedHash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, res.headers['content-type']);
- return (calculatedHash === attributes.hash);
-};
-
-
-// Generate a bewit value for a given URI
-
-/*
- uri: 'http://example.com/resource?a=b' or object from Url.parse()
- options: {
-
- // Required
-
- credentials: {
- id: 'dh37fgj492je',
- key: 'aoijedoaijsdlaksjdl',
- algorithm: 'sha256' // 'sha1', 'sha256'
- },
- ttlSec: 60 * 60, // TTL in seconds
-
- // Optional
-
- ext: 'application-specific', // Application specific data sent via the ext attribute
- localtimeOffsetMsec: 400 // Time offset to sync with server time
- };
-*/
-
-exports.getBewit = function (uri, options) {
-
- // Validate inputs
-
- if (!uri ||
- (typeof uri !== 'string' && typeof uri !== 'object') ||
- !options ||
- typeof options !== 'object' ||
- !options.ttlSec) {
-
- return '';
- }
-
- options.ext = (options.ext === null || options.ext === undefined ? '' : options.ext); // Zero is valid value
-
- // Application time
-
- var now = Utils.now(options.localtimeOffsetMsec);
-
- // Validate credentials
-
- var credentials = options.credentials;
- if (!credentials ||
- !credentials.id ||
- !credentials.key ||
- !credentials.algorithm) {
-
- return '';
- }
-
- if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
- return '';
- }
-
- // Parse URI
-
- if (typeof uri === 'string') {
- uri = Url.parse(uri);
- }
-
- // Calculate signature
-
- var exp = Math.floor(now / 1000) + options.ttlSec;
- var mac = Crypto.calculateMac('bewit', credentials, {
- ts: exp,
- nonce: '',
- method: 'GET',
- resource: uri.pathname + (uri.search || ''), // Maintain trailing '?'
- host: uri.hostname,
- port: uri.port || (uri.protocol === 'http:' ? 80 : 443),
- ext: options.ext
- });
-
- // Construct bewit: id\exp\mac\ext
-
- var bewit = credentials.id + '\\' + exp + '\\' + mac + '\\' + options.ext;
- return Hoek.base64urlEncode(bewit);
-};
-
-
-// Generate an authorization string for a message
-
-/*
- host: 'example.com',
- port: 8000,
- message: '{"some":"payload"}', // UTF-8 encoded string for body hash generation
- options: {
-
- // Required
-
- credentials: {
- id: 'dh37fgj492je',
- key: 'aoijedoaijsdlaksjdl',
- algorithm: 'sha256' // 'sha1', 'sha256'
- },
-
- // Optional
-
- timestamp: Date.now(), // A pre-calculated timestamp
- nonce: '2334f34f', // A pre-generated nonce
- localtimeOffsetMsec: 400, // Time offset to sync with server time (ignored if timestamp provided)
- }
-*/
-
-exports.message = function (host, port, message, options) {
-
- // Validate inputs
-
- if (!host || typeof host !== 'string' ||
- !port || typeof port !== 'number' ||
- message === null || message === undefined || typeof message !== 'string' ||
- !options || typeof options !== 'object') {
-
- return null;
- }
-
- // Application time
-
- var timestamp = options.timestamp || Utils.nowSecs(options.localtimeOffsetMsec);
-
- // Validate credentials
-
- var credentials = options.credentials;
- if (!credentials ||
- !credentials.id ||
- !credentials.key ||
- !credentials.algorithm) {
-
- // Invalid credential object
- return null;
- }
-
- if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
- return null;
- }
-
- // Calculate signature
-
- var artifacts = {
- ts: timestamp,
- nonce: options.nonce || Cryptiles.randomString(6),
- host: host,
- port: port,
- hash: Crypto.calculatePayloadHash(message, credentials.algorithm)
- };
-
- // Construct authorization
-
- var result = {
- id: credentials.id,
- ts: artifacts.ts,
- nonce: artifacts.nonce,
- hash: artifacts.hash,
- mac: Crypto.calculateMac('message', credentials, artifacts)
- };
-
- return result;
-};
-
-
-
+// Load modules
+
+var Url = require('url');
+var Hoek = require('hoek');
+var Cryptiles = require('cryptiles');
+var Crypto = require('./crypto');
+var Utils = require('./utils');
+
+
+// Declare internals
+
+var internals = {};
+
+
+// Generate an Authorization header for a given request
+
+/*
+ uri: 'http://example.com/resource?a=b' or object from Url.parse()
+ method: HTTP verb (e.g. 'GET', 'POST')
+ options: {
+
+ // Required
+
+ credentials: {
+ id: 'dh37fgj492je',
+ key: 'aoijedoaijsdlaksjdl',
+ algorithm: 'sha256' // 'sha1', 'sha256'
+ },
+
+ // Optional
+
+ ext: 'application-specific', // Application specific data sent via the ext attribute
+ timestamp: Date.now(), // A pre-calculated timestamp
+ nonce: '2334f34f', // A pre-generated nonce
+ localtimeOffsetMsec: 400, // Time offset to sync with server time (ignored if timestamp provided)
+ payload: '{"some":"payload"}', // UTF-8 encoded string for body hash generation (ignored if hash provided)
+ contentType: 'application/json', // Payload content-type (ignored if hash provided)
+ hash: 'U4MKKSmiVxk37JCCrAVIjV=', // Pre-calculated payload hash
+ app: '24s23423f34dx', // Oz application id
+ dlg: '234sz34tww3sd' // Oz delegated-by application id
+ }
+*/
+
+exports.header = function (uri, method, options) {
+
+ var result = {
+ field: '',
+ artifacts: {}
+ };
+
+ // Validate inputs
+
+ if (!uri || (typeof uri !== 'string' && typeof uri !== 'object') ||
+ !method || typeof method !== 'string' ||
+ !options || typeof options !== 'object') {
+
+ result.err = 'Invalid argument type';
+ return result;
+ }
+
+ // Application time
+
+ var timestamp = options.timestamp || Utils.nowSecs(options.localtimeOffsetMsec);
+
+ // Validate credentials
+
+ var credentials = options.credentials;
+ if (!credentials ||
+ !credentials.id ||
+ !credentials.key ||
+ !credentials.algorithm) {
+
+ result.err = 'Invalid credential object';
+ return result;
+ }
+
+ if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
+ result.err = 'Unknown algorithm';
+ return result;
+ }
+
+ // Parse URI
+
+ if (typeof uri === 'string') {
+ uri = Url.parse(uri);
+ }
+
+ // Calculate signature
+
+ var artifacts = {
+ ts: timestamp,
+ nonce: options.nonce || Cryptiles.randomString(6),
+ method: method,
+ resource: uri.pathname + (uri.search || ''), // Maintain trailing '?'
+ host: uri.hostname,
+ port: uri.port || (uri.protocol === 'http:' ? 80 : 443),
+ hash: options.hash,
+ ext: options.ext,
+ app: options.app,
+ dlg: options.dlg
+ };
+
+ result.artifacts = artifacts;
+
+ // Calculate payload hash
+
+ if (!artifacts.hash &&
+ (options.payload || options.payload === '')) {
+
+ artifacts.hash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType);
+ }
+
+ var mac = Crypto.calculateMac('header', credentials, artifacts);
+
+ // Construct header
+
+ var hasExt = artifacts.ext !== null && artifacts.ext !== undefined && artifacts.ext !== ''; // Other falsey values allowed
+ var header = 'Hawk id="' + credentials.id +
+ '", ts="' + artifacts.ts +
+ '", nonce="' + artifacts.nonce +
+ (artifacts.hash ? '", hash="' + artifacts.hash : '') +
+ (hasExt ? '", ext="' + Hoek.escapeHeaderAttribute(artifacts.ext) : '') +
+ '", mac="' + mac + '"';
+
+ if (artifacts.app) {
+ header += ', app="' + artifacts.app +
+ (artifacts.dlg ? '", dlg="' + artifacts.dlg : '') + '"';
+ }
+
+ result.field = header;
+
+ return result;
+};
+
+
+// Validate server response
+
+/*
+ res: node's response object
+ artifacts: object received from header().artifacts
+ options: {
+ payload: optional payload received
+ required: specifies if a Server-Authorization header is required. Defaults to 'false'
+ }
+*/
+
+exports.authenticate = function (res, credentials, artifacts, options) {
+
+ artifacts = Hoek.clone(artifacts);
+ options = options || {};
+
+ if (res.headers['www-authenticate']) {
+
+ // Parse HTTP WWW-Authenticate header
+
+ var wwwAttributes = Utils.parseAuthorizationHeader(res.headers['www-authenticate'], ['ts', 'tsm', 'error']);
+ if (wwwAttributes instanceof Error) {
+ return false;
+ }
+
+ // Validate server timestamp (not used to update clock since it is done via the SNPT client)
+
+ if (wwwAttributes.ts) {
+ var tsm = Crypto.calculateTsMac(wwwAttributes.ts, credentials);
+ if (tsm !== wwwAttributes.tsm) {
+ return false;
+ }
+ }
+ }
+
+ // Parse HTTP Server-Authorization header
+
+ if (!res.headers['server-authorization'] &&
+ !options.required) {
+
+ return true;
+ }
+
+ var attributes = Utils.parseAuthorizationHeader(res.headers['server-authorization'], ['mac', 'ext', 'hash']);
+ if (attributes instanceof Error) {
+ return false;
+ }
+
+ artifacts.ext = attributes.ext;
+ artifacts.hash = attributes.hash;
+
+ var mac = Crypto.calculateMac('response', credentials, artifacts);
+ if (mac !== attributes.mac) {
+ return false;
+ }
+
+ if (!options.payload &&
+ options.payload !== '') {
+
+ return true;
+ }
+
+ if (!attributes.hash) {
+ return false;
+ }
+
+ var calculatedHash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, res.headers['content-type']);
+ return (calculatedHash === attributes.hash);
+};
+
+
+// Generate a bewit value for a given URI
+
+/*
+ uri: 'http://example.com/resource?a=b' or object from Url.parse()
+ options: {
+
+ // Required
+
+ credentials: {
+ id: 'dh37fgj492je',
+ key: 'aoijedoaijsdlaksjdl',
+ algorithm: 'sha256' // 'sha1', 'sha256'
+ },
+ ttlSec: 60 * 60, // TTL in seconds
+
+ // Optional
+
+ ext: 'application-specific', // Application specific data sent via the ext attribute
+ localtimeOffsetMsec: 400 // Time offset to sync with server time
+ };
+*/
+
+exports.getBewit = function (uri, options) {
+
+ // Validate inputs
+
+ if (!uri ||
+ (typeof uri !== 'string' && typeof uri !== 'object') ||
+ !options ||
+ typeof options !== 'object' ||
+ !options.ttlSec) {
+
+ return '';
+ }
+
+ options.ext = (options.ext === null || options.ext === undefined ? '' : options.ext); // Zero is valid value
+
+ // Application time
+
+ var now = Utils.now(options.localtimeOffsetMsec);
+
+ // Validate credentials
+
+ var credentials = options.credentials;
+ if (!credentials ||
+ !credentials.id ||
+ !credentials.key ||
+ !credentials.algorithm) {
+
+ return '';
+ }
+
+ if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
+ return '';
+ }
+
+ // Parse URI
+
+ if (typeof uri === 'string') {
+ uri = Url.parse(uri);
+ }
+
+ // Calculate signature
+
+ var exp = Math.floor(now / 1000) + options.ttlSec;
+ var mac = Crypto.calculateMac('bewit', credentials, {
+ ts: exp,
+ nonce: '',
+ method: 'GET',
+ resource: uri.pathname + (uri.search || ''), // Maintain trailing '?'
+ host: uri.hostname,
+ port: uri.port || (uri.protocol === 'http:' ? 80 : 443),
+ ext: options.ext
+ });
+
+ // Construct bewit: id\exp\mac\ext
+
+ var bewit = credentials.id + '\\' + exp + '\\' + mac + '\\' + options.ext;
+ return Hoek.base64urlEncode(bewit);
+};
+
+
+// Generate an authorization string for a message
+
+/*
+ host: 'example.com',
+ port: 8000,
+ message: '{"some":"payload"}', // UTF-8 encoded string for body hash generation
+ options: {
+
+ // Required
+
+ credentials: {
+ id: 'dh37fgj492je',
+ key: 'aoijedoaijsdlaksjdl',
+ algorithm: 'sha256' // 'sha1', 'sha256'
+ },
+
+ // Optional
+
+ timestamp: Date.now(), // A pre-calculated timestamp
+ nonce: '2334f34f', // A pre-generated nonce
+ localtimeOffsetMsec: 400, // Time offset to sync with server time (ignored if timestamp provided)
+ }
+*/
+
+exports.message = function (host, port, message, options) {
+
+ // Validate inputs
+
+ if (!host || typeof host !== 'string' ||
+ !port || typeof port !== 'number' ||
+ message === null || message === undefined || typeof message !== 'string' ||
+ !options || typeof options !== 'object') {
+
+ return null;
+ }
+
+ // Application time
+
+ var timestamp = options.timestamp || Utils.nowSecs(options.localtimeOffsetMsec);
+
+ // Validate credentials
+
+ var credentials = options.credentials;
+ if (!credentials ||
+ !credentials.id ||
+ !credentials.key ||
+ !credentials.algorithm) {
+
+ // Invalid credential object
+ return null;
+ }
+
+ if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
+ return null;
+ }
+
+ // Calculate signature
+
+ var artifacts = {
+ ts: timestamp,
+ nonce: options.nonce || Cryptiles.randomString(6),
+ host: host,
+ port: port,
+ hash: Crypto.calculatePayloadHash(message, credentials.algorithm)
+ };
+
+ // Construct authorization
+
+ var result = {
+ id: credentials.id,
+ ts: artifacts.ts,
+ nonce: artifacts.nonce,
+ hash: artifacts.hash,
+ mac: Crypto.calculateMac('message', credentials, artifacts)
+ };
+
+ return result;
+};
+
+
+
diff --git a/node_modules/request/node_modules/hawk/lib/crypto.js b/node_modules/request/node_modules/hawk/lib/crypto.js
index d3c8244a9..565ae496c 100755
--- a/node_modules/request/node_modules/hawk/lib/crypto.js
+++ b/node_modules/request/node_modules/hawk/lib/crypto.js
@@ -1,126 +1,126 @@
-// Load modules
-
-var Crypto = require('crypto');
-var Url = require('url');
-var Utils = require('./utils');
-
-
-// Declare internals
-
-var internals = {};
-
-
-// MAC normalization format version
-
-exports.headerVersion = '1'; // Prevent comparison of mac values generated with different normalized string formats
-
-
-// Supported HMAC algorithms
-
-exports.algorithms = ['sha1', 'sha256'];
-
-
-// Calculate the request MAC
-
-/*
- type: 'header', // 'header', 'bewit', 'response'
- credentials: {
- key: 'aoijedoaijsdlaksjdl',
- algorithm: 'sha256' // 'sha1', 'sha256'
- },
- options: {
- method: 'GET',
- resource: '/resource?a=1&b=2',
- host: 'example.com',
- port: 8080,
- ts: 1357718381034,
- nonce: 'd3d345f',
- hash: 'U4MKKSmiVxk37JCCrAVIjV/OhB3y+NdwoCr6RShbVkE=',
- ext: 'app-specific-data',
- app: 'hf48hd83qwkj', // Application id (Oz)
- dlg: 'd8djwekds9cj' // Delegated by application id (Oz), requires options.app
- }
-*/
-
-exports.calculateMac = function (type, credentials, options) {
-
- var normalized = exports.generateNormalizedString(type, options);
-
- var hmac = Crypto.createHmac(credentials.algorithm, credentials.key).update(normalized);
- var digest = hmac.digest('base64');
- return digest;
-};
-
-
-exports.generateNormalizedString = function (type, options) {
-
- var resource = options.resource || '';
- if (resource &&
- resource[0] !== '/') {
-
- var url = Url.parse(resource, false);
- resource = url.path; // Includes query
- }
-
- var normalized = 'hawk.' + exports.headerVersion + '.' + type + '\n' +
- options.ts + '\n' +
- options.nonce + '\n' +
- (options.method || '').toUpperCase() + '\n' +
- resource + '\n' +
- options.host.toLowerCase() + '\n' +
- options.port + '\n' +
- (options.hash || '') + '\n';
-
- if (options.ext) {
- normalized += options.ext.replace('\\', '\\\\').replace('\n', '\\n');
- }
-
- normalized += '\n';
-
- if (options.app) {
- normalized += options.app + '\n' +
- (options.dlg || '') + '\n';
- }
-
- return normalized;
-};
-
-
-exports.calculatePayloadHash = function (payload, algorithm, contentType) {
-
- var hash = exports.initializePayloadHash(algorithm, contentType);
- hash.update(payload || '');
- return exports.finalizePayloadHash(hash);
-};
-
-
-exports.initializePayloadHash = function (algorithm, contentType) {
-
- var hash = Crypto.createHash(algorithm);
- hash.update('hawk.' + exports.headerVersion + '.payload\n');
- hash.update(Utils.parseContentType(contentType) + '\n');
- return hash;
-};
-
-
-exports.finalizePayloadHash = function (hash) {
-
- hash.update('\n');
- return hash.digest('base64');
-};
-
-
-exports.calculateTsMac = function (ts, credentials) {
-
- var hmac = Crypto.createHmac(credentials.algorithm, credentials.key);
- hmac.update('hawk.' + exports.headerVersion + '.ts\n' + ts + '\n');
- return hmac.digest('base64');
-};
-
-
-exports.timestampMessage = function (credentials, localtimeOffsetMsec) {
-
- var now = Utils.nowSecs(localtimeOffsetMsec);
- var tsm = exports.calculateTsMac(now, credentials);
- return { ts: now, tsm: tsm };
-};
+// Load modules
+
+var Crypto = require('crypto');
+var Url = require('url');
+var Utils = require('./utils');
+
+
+// Declare internals
+
+var internals = {};
+
+
+// MAC normalization format version
+
+exports.headerVersion = '1'; // Prevent comparison of mac values generated with different normalized string formats
+
+
+// Supported HMAC algorithms
+
+exports.algorithms = ['sha1', 'sha256'];
+
+
+// Calculate the request MAC
+
+/*
+ type: 'header', // 'header', 'bewit', 'response'
+ credentials: {
+ key: 'aoijedoaijsdlaksjdl',
+ algorithm: 'sha256' // 'sha1', 'sha256'
+ },
+ options: {
+ method: 'GET',
+ resource: '/resource?a=1&b=2',
+ host: 'example.com',
+ port: 8080,
+ ts: 1357718381034,
+ nonce: 'd3d345f',
+ hash: 'U4MKKSmiVxk37JCCrAVIjV/OhB3y+NdwoCr6RShbVkE=',
+ ext: 'app-specific-data',
+ app: 'hf48hd83qwkj', // Application id (Oz)
+ dlg: 'd8djwekds9cj' // Delegated by application id (Oz), requires options.app
+ }
+*/
+
+exports.calculateMac = function (type, credentials, options) {
+
+ var normalized = exports.generateNormalizedString(type, options);
+
+ var hmac = Crypto.createHmac(credentials.algorithm, credentials.key).update(normalized);
+ var digest = hmac.digest('base64');
+ return digest;
+};
+
+
+exports.generateNormalizedString = function (type, options) {
+
+ var resource = options.resource || '';
+ if (resource &&
+ resource[0] !== '/') {
+
+ var url = Url.parse(resource, false);
+ resource = url.path; // Includes query
+ }
+
+ var normalized = 'hawk.' + exports.headerVersion + '.' + type + '\n' +
+ options.ts + '\n' +
+ options.nonce + '\n' +
+ (options.method || '').toUpperCase() + '\n' +
+ resource + '\n' +
+ options.host.toLowerCase() + '\n' +
+ options.port + '\n' +
+ (options.hash || '') + '\n';
+
+ if (options.ext) {
+ normalized += options.ext.replace('\\', '\\\\').replace('\n', '\\n');
+ }
+
+ normalized += '\n';
+
+ if (options.app) {
+ normalized += options.app + '\n' +
+ (options.dlg || '') + '\n';
+ }
+
+ return normalized;
+};
+
+
+exports.calculatePayloadHash = function (payload, algorithm, contentType) {
+
+ var hash = exports.initializePayloadHash(algorithm, contentType);
+ hash.update(payload || '');
+ return exports.finalizePayloadHash(hash);
+};
+
+
+exports.initializePayloadHash = function (algorithm, contentType) {
+
+ var hash = Crypto.createHash(algorithm);
+ hash.update('hawk.' + exports.headerVersion + '.payload\n');
+ hash.update(Utils.parseContentType(contentType) + '\n');
+ return hash;
+};
+
+
+exports.finalizePayloadHash = function (hash) {
+
+ hash.update('\n');
+ return hash.digest('base64');
+};
+
+
+exports.calculateTsMac = function (ts, credentials) {
+
+ var hmac = Crypto.createHmac(credentials.algorithm, credentials.key);
+ hmac.update('hawk.' + exports.headerVersion + '.ts\n' + ts + '\n');
+ return hmac.digest('base64');
+};
+
+
+exports.timestampMessage = function (credentials, localtimeOffsetMsec) {
+
+ var now = Utils.nowSecs(localtimeOffsetMsec);
+ var tsm = exports.calculateTsMac(now, credentials);
+ return { ts: now, tsm: tsm };
+};
diff --git a/node_modules/request/node_modules/hawk/lib/index.js b/node_modules/request/node_modules/hawk/lib/index.js
index a883882c8..58b5bc38e 100755
--- a/node_modules/request/node_modules/hawk/lib/index.js
+++ b/node_modules/request/node_modules/hawk/lib/index.js
@@ -1,15 +1,15 @@
-// Export sub-modules
-
-exports.error = exports.Error = require('boom');
-exports.sntp = require('sntp');
-
-exports.server = require('./server');
-exports.client = require('./client');
-exports.crypto = require('./crypto');
-exports.utils = require('./utils');
-
-exports.uri = {
- authenticate: exports.server.authenticateBewit,
- getBewit: exports.client.getBewit
-};
-
+// Export sub-modules
+
+exports.error = exports.Error = require('boom');
+exports.sntp = require('sntp');
+
+exports.server = require('./server');
+exports.client = require('./client');
+exports.crypto = require('./crypto');
+exports.utils = require('./utils');
+
+exports.uri = {
+ authenticate: exports.server.authenticateBewit,
+ getBewit: exports.client.getBewit
+};
+
diff --git a/node_modules/request/node_modules/hawk/lib/server.js b/node_modules/request/node_modules/hawk/lib/server.js
index a325d56a5..67e1a069b 100755
--- a/node_modules/request/node_modules/hawk/lib/server.js
+++ b/node_modules/request/node_modules/hawk/lib/server.js
@@ -1,540 +1,548 @@
-// Load modules
-
-var Boom = require('boom');
-var Hoek = require('hoek');
-var Cryptiles = require('cryptiles');
-var Crypto = require('./crypto');
-var Utils = require('./utils');
-
-
-// Declare internals
-
-var internals = {};
-
-
-// Hawk authentication
-
-/*
- req: node's HTTP request object or an object as follows:
-
- var request = {
- method: 'GET',
- url: '/resource/4?a=1&b=2',
- host: 'example.com',
- port: 8080,
- authorization: 'Hawk id="dh37fgj492je", ts="1353832234", nonce="j4h3g2", ext="some-app-ext-data", mac="6R4rV5iE+NPoym+WwjeHzjAGXUtLNIxmo1vpMofpLAE="'
- };
-
- credentialsFunc: required function to lookup the set of Hawk credentials based on the provided credentials id.
- The credentials include the MAC key, MAC algorithm, and other attributes (such as username)
- needed by the application. This function is the equivalent of verifying the username and
- password in Basic authentication.
-
- var credentialsFunc = function (id, callback) {
-
- // Lookup credentials in database
- db.lookup(id, function (err, item) {
-
- if (err || !item) {
- return callback(err);
- }
-
- var credentials = {
- // Required
- key: item.key,
- algorithm: item.algorithm,
- // Application specific
- user: item.user
- };
-
- return callback(null, credentials);
- });
- };
-
- options: {
-
- hostHeaderName: optional header field name, used to override the default 'Host' header when used
- behind a cache of a proxy. Apache2 changes the value of the 'Host' header while preserving
- the original (which is what the module must verify) in the 'x-forwarded-host' header field.
- Only used when passed a node Http.ServerRequest object.
-
- nonceFunc: optional nonce validation function. The function signature is function(key, nonce, ts, callback)
- where 'callback' must be called using the signature function(err).
-
- timestampSkewSec: optional number of seconds of permitted clock skew for incoming timestamps. Defaults to 60 seconds.
- Provides a +/- skew which means actual allowed window is double the number of seconds.
-
- localtimeOffsetMsec: optional local clock time offset express in a number of milliseconds (positive or negative).
- Defaults to 0.
-
- payload: optional payload for validation. The client calculates the hash value and includes it via the 'hash'
- header attribute. The server always ensures the value provided has been included in the request
- MAC. When this option is provided, it validates the hash value itself. Validation is done by calculating
- a hash value over the entire payload (assuming it has already be normalized to the same format and
- encoding used by the client to calculate the hash on request). If the payload is not available at the time
- of authentication, the authenticatePayload() method can be used by passing it the credentials and
- attributes.hash returned in the authenticate callback.
-
- host: optional host name override. Only used when passed a node request object.
- port: optional port override. Only used when passed a node request object.
- }
-
- callback: function (err, credentials, artifacts) { }
- */
-
-exports.authenticate = function (req, credentialsFunc, options, callback) {
-
- callback = Hoek.nextTick(callback);
-
- // Default options
-
- options.nonceFunc = options.nonceFunc || internals.nonceFunc;
- options.timestampSkewSec = options.timestampSkewSec || 60; // 60 seconds
-
- // Application time
-
- var now = Utils.now(options.localtimeOffsetMsec); // Measure now before any other processing
-
- // Convert node Http request object to a request configuration object
-
- var request = Utils.parseRequest(req, options);
- if (request instanceof Error) {
- return callback(Boom.badRequest(request.message));
- }
-
- // Parse HTTP Authorization header
-
- var attributes = Utils.parseAuthorizationHeader(request.authorization);
- if (attributes instanceof Error) {
- return callback(attributes);
- }
-
- // Construct artifacts container
-
- var artifacts = {
- method: request.method,
- host: request.host,
- port: request.port,
- resource: request.url,
- ts: attributes.ts,
- nonce: attributes.nonce,
- hash: attributes.hash,
- ext: attributes.ext,
- app: attributes.app,
- dlg: attributes.dlg,
- mac: attributes.mac,
- id: attributes.id
- };
-
- // Verify required header attributes
-
- if (!attributes.id ||
- !attributes.ts ||
- !attributes.nonce ||
- !attributes.mac) {
-
- return callback(Boom.badRequest('Missing attributes'), null, artifacts);
- }
-
- // Fetch Hawk credentials
-
- credentialsFunc(attributes.id, function (err, credentials) {
-
- if (err) {
- return callback(err, credentials || null, artifacts);
- }
-
- if (!credentials) {
- return callback(Boom.unauthorized('Unknown credentials', 'Hawk'), null, artifacts);
- }
-
- if (!credentials.key ||
- !credentials.algorithm) {
-
- return callback(Boom.internal('Invalid credentials'), credentials, artifacts);
- }
-
- if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
- return callback(Boom.internal('Unknown algorithm'), credentials, artifacts);
- }
-
- // Calculate MAC
-
- var mac = Crypto.calculateMac('header', credentials, artifacts);
- if (!Cryptiles.fixedTimeComparison(mac, attributes.mac)) {
- return callback(Boom.unauthorized('Bad mac', 'Hawk'), credentials, artifacts);
- }
-
- // Check payload hash
-
- if (options.payload ||
- options.payload === '') {
-
- if (!attributes.hash) {
- return callback(Boom.unauthorized('Missing required payload hash', 'Hawk'), credentials, artifacts);
- }
-
- var hash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, request.contentType);
- if (!Cryptiles.fixedTimeComparison(hash, attributes.hash)) {
- return callback(Boom.unauthorized('Bad payload hash', 'Hawk'), credentials, artifacts);
- }
- }
-
- // Check nonce
-
- options.nonceFunc(credentials.key, attributes.nonce, attributes.ts, function (err) {
-
- if (err) {
- return callback(Boom.unauthorized('Invalid nonce', 'Hawk'), credentials, artifacts);
- }
-
- // Check timestamp staleness
-
- if (Math.abs((attributes.ts * 1000) - now) > (options.timestampSkewSec * 1000)) {
- var tsm = Crypto.timestampMessage(credentials, options.localtimeOffsetMsec);
- return callback(Boom.unauthorized('Stale timestamp', 'Hawk', tsm), credentials, artifacts);
- }
-
- // Successful authentication
-
- return callback(null, credentials, artifacts);
- });
- });
-};
-
-
-// Authenticate payload hash - used when payload cannot be provided during authenticate()
-
-/*
- payload: raw request payload
- credentials: from authenticate callback
- artifacts: from authenticate callback
- contentType: req.headers['content-type']
-*/
-
-exports.authenticatePayload = function (payload, credentials, artifacts, contentType) {
-
- var calculatedHash = Crypto.calculatePayloadHash(payload, credentials.algorithm, contentType);
- return Cryptiles.fixedTimeComparison(calculatedHash, artifacts.hash);
-};
-
-
-// Authenticate payload hash - used when payload cannot be provided during authenticate()
-
-/*
- calculatedHash: the payload hash calculated using Crypto.calculatePayloadHash()
- artifacts: from authenticate callback
-*/
-
-exports.authenticatePayloadHash = function (calculatedHash, artifacts) {
-
- return Cryptiles.fixedTimeComparison(calculatedHash, artifacts.hash);
-};
-
-
-// Generate a Server-Authorization header for a given response
-
-/*
- credentials: {}, // Object received from authenticate()
- artifacts: {} // Object received from authenticate(); 'mac', 'hash', and 'ext' - ignored
- options: {
- ext: 'application-specific', // Application specific data sent via the ext attribute
- payload: '{"some":"payload"}', // UTF-8 encoded string for body hash generation (ignored if hash provided)
- contentType: 'application/json', // Payload content-type (ignored if hash provided)
- hash: 'U4MKKSmiVxk37JCCrAVIjV=' // Pre-calculated payload hash
- }
-*/
-
-exports.header = function (credentials, artifacts, options) {
-
- // Prepare inputs
-
- options = options || {};
-
- if (!artifacts ||
- typeof artifacts !== 'object' ||
- typeof options !== 'object') {
-
- return '';
- }
-
- artifacts = Hoek.clone(artifacts);
- delete artifacts.mac;
- artifacts.hash = options.hash;
- artifacts.ext = options.ext;
-
- // Validate credentials
-
- if (!credentials ||
- !credentials.key ||
- !credentials.algorithm) {
-
- // Invalid credential object
- return '';
- }
-
- if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
- return '';
- }
-
- // Calculate payload hash
-
- if (!artifacts.hash &&
- (options.payload || options.payload === '')) {
-
- artifacts.hash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType);
- }
-
- var mac = Crypto.calculateMac('response', credentials, artifacts);
-
- // Construct header
-
- var header = 'Hawk mac="' + mac + '"' +
- (artifacts.hash ? ', hash="' + artifacts.hash + '"' : '');
-
- if (artifacts.ext !== null &&
- artifacts.ext !== undefined &&
- artifacts.ext !== '') { // Other falsey values allowed
-
- header += ', ext="' + Hoek.escapeHeaderAttribute(artifacts.ext) + '"';
- }
-
- return header;
-};
-
-
-/*
- * Arguments and options are the same as authenticate() with the exception that the only supported options are:
- * 'hostHeaderName', 'localtimeOffsetMsec', 'host', 'port'
- */
-
-exports.authenticateBewit = function (req, credentialsFunc, options, callback) {
-
- callback = Hoek.nextTick(callback);
-
- // Application time
-
- var now = Utils.now(options.localtimeOffsetMsec);
-
- // Convert node Http request object to a request configuration object
-
- var request = Utils.parseRequest(req, options);
- if (request instanceof Error) {
- return callback(Boom.badRequest(request.message));
- }
-
- // Extract bewit
-
- // 1 2 3 4
- var resource = request.url.match(/^(\/.*)([\?&])bewit\=([^&$]*)(?:&(.+))?$/);
- if (!resource) {
- return callback(Boom.unauthorized(null, 'Hawk'));
- }
-
- // Bewit not empty
-
- if (!resource[3]) {
- return callback(Boom.unauthorized('Empty bewit', 'Hawk'));
- }
-
- // Verify method is GET
-
- if (request.method !== 'GET' &&
- request.method !== 'HEAD') {
-
- return callback(Boom.unauthorized('Invalid method', 'Hawk'));
- }
-
- // No other authentication
-
- if (request.authorization) {
- return callback(Boom.badRequest('Multiple authentications'));
- }
-
- // Parse bewit
-
- var bewitString = Hoek.base64urlDecode(resource[3]);
- if (bewitString instanceof Error) {
- return callback(Boom.badRequest('Invalid bewit encoding'));
- }
-
- // Bewit format: id\exp\mac\ext ('\' is used because it is a reserved header attribute character)
-
- var bewitParts = bewitString.split('\\');
- if (bewitParts.length !== 4) {
- return callback(Boom.badRequest('Invalid bewit structure'));
- }
-
- var bewit = {
- id: bewitParts[0],
- exp: parseInt(bewitParts[1], 10),
- mac: bewitParts[2],
- ext: bewitParts[3] || ''
- };
-
- if (!bewit.id ||
- !bewit.exp ||
- !bewit.mac) {
-
- return callback(Boom.badRequest('Missing bewit attributes'));
- }
-
- // Construct URL without bewit
-
- var url = resource[1];
- if (resource[4]) {
- url += resource[2] + resource[4];
- }
-
- // Check expiration
-
- if (bewit.exp * 1000 <= now) {
- return callback(Boom.unauthorized('Access expired', 'Hawk'), null, bewit);
- }
-
- // Fetch Hawk credentials
-
- credentialsFunc(bewit.id, function (err, credentials) {
-
- if (err) {
- return callback(err, credentials || null, bewit.ext);
- }
-
- if (!credentials) {
- return callback(Boom.unauthorized('Unknown credentials', 'Hawk'), null, bewit);
- }
-
- if (!credentials.key ||
- !credentials.algorithm) {
-
- return callback(Boom.internal('Invalid credentials'), credentials, bewit);
- }
-
- if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
- return callback(Boom.internal('Unknown algorithm'), credentials, bewit);
- }
-
- // Calculate MAC
-
- var mac = Crypto.calculateMac('bewit', credentials, {
- ts: bewit.exp,
- nonce: '',
- method: 'GET',
- resource: url,
- host: request.host,
- port: request.port,
- ext: bewit.ext
- });
-
- if (!Cryptiles.fixedTimeComparison(mac, bewit.mac)) {
- return callback(Boom.unauthorized('Bad mac', 'Hawk'), credentials, bewit);
- }
-
- // Successful authentication
-
- return callback(null, credentials, bewit);
- });
-};
-
-
-/*
- * options are the same as authenticate() with the exception that the only supported options are:
- * 'nonceFunc', 'timestampSkewSec', 'localtimeOffsetMsec'
- */
-
-exports.authenticateMessage = function (host, port, message, authorization, credentialsFunc, options, callback) {
-
- callback = Hoek.nextTick(callback);
-
- // Default options
-
- options.nonceFunc = options.nonceFunc || internals.nonceFunc;
- options.timestampSkewSec = options.timestampSkewSec || 60; // 60 seconds
-
- // Application time
-
- var now = Utils.now(options.localtimeOffsetMsec); // Measure now before any other processing
-
- // Validate authorization
-
- if (!authorization.id ||
- !authorization.ts ||
- !authorization.nonce ||
- !authorization.hash ||
- !authorization.mac) {
-
- return callback(Boom.badRequest('Invalid authorization'));
- }
-
- // Fetch Hawk credentials
-
- credentialsFunc(authorization.id, function (err, credentials) {
-
- if (err) {
- return callback(err, credentials || null);
- }
-
- if (!credentials) {
- return callback(Boom.unauthorized('Unknown credentials', 'Hawk'));
- }
-
- if (!credentials.key ||
- !credentials.algorithm) {
-
- return callback(Boom.internal('Invalid credentials'), credentials);
- }
-
- if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
- return callback(Boom.internal('Unknown algorithm'), credentials);
- }
-
- // Construct artifacts container
-
- var artifacts = {
- ts: authorization.ts,
- nonce: authorization.nonce,
- host: host,
- port: port,
- hash: authorization.hash
- };
-
- // Calculate MAC
-
- var mac = Crypto.calculateMac('message', credentials, artifacts);
- if (!Cryptiles.fixedTimeComparison(mac, authorization.mac)) {
- return callback(Boom.unauthorized('Bad mac', 'Hawk'), credentials);
- }
-
- // Check payload hash
-
- var hash = Crypto.calculatePayloadHash(message, credentials.algorithm);
- if (!Cryptiles.fixedTimeComparison(hash, authorization.hash)) {
- return callback(Boom.unauthorized('Bad message hash', 'Hawk'), credentials);
- }
-
- // Check nonce
-
- options.nonceFunc(credentials.key, authorization.nonce, authorization.ts, function (err) {
-
- if (err) {
- return callback(Boom.unauthorized('Invalid nonce', 'Hawk'), credentials);
- }
-
- // Check timestamp staleness
-
- if (Math.abs((authorization.ts * 1000) - now) > (options.timestampSkewSec * 1000)) {
- return callback(Boom.unauthorized('Stale timestamp'), credentials);
- }
-
- // Successful authentication
-
- return callback(null, credentials);
- });
- });
-};
-
-
-internals.nonceFunc = function (key, nonce, ts, nonceCallback) {
-
- return nonceCallback(); // No validation
-};
+// Load modules
+
+var Boom = require('boom');
+var Hoek = require('hoek');
+var Cryptiles = require('cryptiles');
+var Crypto = require('./crypto');
+var Utils = require('./utils');
+
+
+// Declare internals
+
+var internals = {};
+
+
+// Hawk authentication
+
+/*
+ req: node's HTTP request object or an object as follows:
+
+ var request = {
+ method: 'GET',
+ url: '/resource/4?a=1&b=2',
+ host: 'example.com',
+ port: 8080,
+ authorization: 'Hawk id="dh37fgj492je", ts="1353832234", nonce="j4h3g2", ext="some-app-ext-data", mac="6R4rV5iE+NPoym+WwjeHzjAGXUtLNIxmo1vpMofpLAE="'
+ };
+
+ credentialsFunc: required function to lookup the set of Hawk credentials based on the provided credentials id.
+ The credentials include the MAC key, MAC algorithm, and other attributes (such as username)
+ needed by the application. This function is the equivalent of verifying the username and
+ password in Basic authentication.
+
+ var credentialsFunc = function (id, callback) {
+
+ // Lookup credentials in database
+ db.lookup(id, function (err, item) {
+
+ if (err || !item) {
+ return callback(err);
+ }
+
+ var credentials = {
+ // Required
+ key: item.key,
+ algorithm: item.algorithm,
+ // Application specific
+ user: item.user
+ };
+
+ return callback(null, credentials);
+ });
+ };
+
+ options: {
+
+ hostHeaderName: optional header field name, used to override the default 'Host' header when used
+ behind a cache of a proxy. Apache2 changes the value of the 'Host' header while preserving
+ the original (which is what the module must verify) in the 'x-forwarded-host' header field.
+ Only used when passed a node Http.ServerRequest object.
+
+ nonceFunc: optional nonce validation function. The function signature is function(key, nonce, ts, callback)
+ where 'callback' must be called using the signature function(err).
+
+ timestampSkewSec: optional number of seconds of permitted clock skew for incoming timestamps. Defaults to 60 seconds.
+ Provides a +/- skew which means actual allowed window is double the number of seconds.
+
+ localtimeOffsetMsec: optional local clock time offset express in a number of milliseconds (positive or negative).
+ Defaults to 0.
+
+ payload: optional payload for validation. The client calculates the hash value and includes it via the 'hash'
+ header attribute. The server always ensures the value provided has been included in the request
+ MAC. When this option is provided, it validates the hash value itself. Validation is done by calculating
+ a hash value over the entire payload (assuming it has already be normalized to the same format and
+ encoding used by the client to calculate the hash on request). If the payload is not available at the time
+ of authentication, the authenticatePayload() method can be used by passing it the credentials and
+ attributes.hash returned in the authenticate callback.
+
+ host: optional host name override. Only used when passed a node request object.
+ port: optional port override. Only used when passed a node request object.
+ }
+
+ callback: function (err, credentials, artifacts) { }
+ */
+
+exports.authenticate = function (req, credentialsFunc, options, callback) {
+
+ callback = Hoek.nextTick(callback);
+
+ // Default options
+
+ options.nonceFunc = options.nonceFunc || internals.nonceFunc;
+ options.timestampSkewSec = options.timestampSkewSec || 60; // 60 seconds
+
+ // Application time
+
+ var now = Utils.now(options.localtimeOffsetMsec); // Measure now before any other processing
+
+ // Convert node Http request object to a request configuration object
+
+ var request = Utils.parseRequest(req, options);
+ if (request instanceof Error) {
+ return callback(Boom.badRequest(request.message));
+ }
+
+ // Parse HTTP Authorization header
+
+ var attributes = Utils.parseAuthorizationHeader(request.authorization);
+ if (attributes instanceof Error) {
+ return callback(attributes);
+ }
+
+ // Construct artifacts container
+
+ var artifacts = {
+ method: request.method,
+ host: request.host,
+ port: request.port,
+ resource: request.url,
+ ts: attributes.ts,
+ nonce: attributes.nonce,
+ hash: attributes.hash,
+ ext: attributes.ext,
+ app: attributes.app,
+ dlg: attributes.dlg,
+ mac: attributes.mac,
+ id: attributes.id
+ };
+
+ // Verify required header attributes
+
+ if (!attributes.id ||
+ !attributes.ts ||
+ !attributes.nonce ||
+ !attributes.mac) {
+
+ return callback(Boom.badRequest('Missing attributes'), null, artifacts);
+ }
+
+ // Fetch Hawk credentials
+
+ credentialsFunc(attributes.id, function (err, credentials) {
+
+ if (err) {
+ return callback(err, credentials || null, artifacts);
+ }
+
+ if (!credentials) {
+ return callback(Boom.unauthorized('Unknown credentials', 'Hawk'), null, artifacts);
+ }
+
+ if (!credentials.key ||
+ !credentials.algorithm) {
+
+ return callback(Boom.internal('Invalid credentials'), credentials, artifacts);
+ }
+
+ if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
+ return callback(Boom.internal('Unknown algorithm'), credentials, artifacts);
+ }
+
+ // Calculate MAC
+
+ var mac = Crypto.calculateMac('header', credentials, artifacts);
+ if (!Cryptiles.fixedTimeComparison(mac, attributes.mac)) {
+ return callback(Boom.unauthorized('Bad mac', 'Hawk'), credentials, artifacts);
+ }
+
+ // Check payload hash
+
+ if (options.payload ||
+ options.payload === '') {
+
+ if (!attributes.hash) {
+ return callback(Boom.unauthorized('Missing required payload hash', 'Hawk'), credentials, artifacts);
+ }
+
+ var hash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, request.contentType);
+ if (!Cryptiles.fixedTimeComparison(hash, attributes.hash)) {
+ return callback(Boom.unauthorized('Bad payload hash', 'Hawk'), credentials, artifacts);
+ }
+ }
+
+ // Check nonce
+
+ options.nonceFunc(credentials.key, attributes.nonce, attributes.ts, function (err) {
+
+ if (err) {
+ return callback(Boom.unauthorized('Invalid nonce', 'Hawk'), credentials, artifacts);
+ }
+
+ // Check timestamp staleness
+
+ if (Math.abs((attributes.ts * 1000) - now) > (options.timestampSkewSec * 1000)) {
+ var tsm = Crypto.timestampMessage(credentials, options.localtimeOffsetMsec);
+ return callback(Boom.unauthorized('Stale timestamp', 'Hawk', tsm), credentials, artifacts);
+ }
+
+ // Successful authentication
+
+ return callback(null, credentials, artifacts);
+ });
+ });
+};
+
+
+// Authenticate payload hash - used when payload cannot be provided during authenticate()
+
+/*
+ payload: raw request payload
+ credentials: from authenticate callback
+ artifacts: from authenticate callback
+ contentType: req.headers['content-type']
+*/
+
+exports.authenticatePayload = function (payload, credentials, artifacts, contentType) {
+
+ var calculatedHash = Crypto.calculatePayloadHash(payload, credentials.algorithm, contentType);
+ return Cryptiles.fixedTimeComparison(calculatedHash, artifacts.hash);
+};
+
+
+// Authenticate payload hash - used when payload cannot be provided during authenticate()
+
+/*
+ calculatedHash: the payload hash calculated using Crypto.calculatePayloadHash()
+ artifacts: from authenticate callback
+*/
+
+exports.authenticatePayloadHash = function (calculatedHash, artifacts) {
+
+ return Cryptiles.fixedTimeComparison(calculatedHash, artifacts.hash);
+};
+
+
+// Generate a Server-Authorization header for a given response
+
+/*
+ credentials: {}, // Object received from authenticate()
+ artifacts: {} // Object received from authenticate(); 'mac', 'hash', and 'ext' - ignored
+ options: {
+ ext: 'application-specific', // Application specific data sent via the ext attribute
+ payload: '{"some":"payload"}', // UTF-8 encoded string for body hash generation (ignored if hash provided)
+ contentType: 'application/json', // Payload content-type (ignored if hash provided)
+ hash: 'U4MKKSmiVxk37JCCrAVIjV=' // Pre-calculated payload hash
+ }
+*/
+
+exports.header = function (credentials, artifacts, options) {
+
+ // Prepare inputs
+
+ options = options || {};
+
+ if (!artifacts ||
+ typeof artifacts !== 'object' ||
+ typeof options !== 'object') {
+
+ return '';
+ }
+
+ artifacts = Hoek.clone(artifacts);
+ delete artifacts.mac;
+ artifacts.hash = options.hash;
+ artifacts.ext = options.ext;
+
+ // Validate credentials
+
+ if (!credentials ||
+ !credentials.key ||
+ !credentials.algorithm) {
+
+ // Invalid credential object
+ return '';
+ }
+
+ if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
+ return '';
+ }
+
+ // Calculate payload hash
+
+ if (!artifacts.hash &&
+ (options.payload || options.payload === '')) {
+
+ artifacts.hash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType);
+ }
+
+ var mac = Crypto.calculateMac('response', credentials, artifacts);
+
+ // Construct header
+
+ var header = 'Hawk mac="' + mac + '"' +
+ (artifacts.hash ? ', hash="' + artifacts.hash + '"' : '');
+
+ if (artifacts.ext !== null &&
+ artifacts.ext !== undefined &&
+ artifacts.ext !== '') { // Other falsey values allowed
+
+ header += ', ext="' + Hoek.escapeHeaderAttribute(artifacts.ext) + '"';
+ }
+
+ return header;
+};
+
+
+/*
+ * Arguments and options are the same as authenticate() with the exception that the only supported options are:
+ * 'hostHeaderName', 'localtimeOffsetMsec', 'host', 'port'
+ */
+
+
+// 1 2 3 4
+internals.bewitRegex = /^(\/.*)([\?&])bewit\=([^&$]*)(?:&(.+))?$/;
+
+
+exports.authenticateBewit = function (req, credentialsFunc, options, callback) {
+
+ callback = Hoek.nextTick(callback);
+
+ // Application time
+
+ var now = Utils.now(options.localtimeOffsetMsec);
+
+ // Convert node Http request object to a request configuration object
+
+ var request = Utils.parseRequest(req, options);
+ if (request instanceof Error) {
+ return callback(Boom.badRequest(request.message));
+ }
+
+ // Extract bewit
+
+ if (request.url.length > Utils.limits.maxMatchLength) {
+ return callback(Boom.badRequest('Resource path exceeds max length'));
+ }
+
+ var resource = request.url.match(internals.bewitRegex);
+ if (!resource) {
+ return callback(Boom.unauthorized(null, 'Hawk'));
+ }
+
+ // Bewit not empty
+
+ if (!resource[3]) {
+ return callback(Boom.unauthorized('Empty bewit', 'Hawk'));
+ }
+
+ // Verify method is GET
+
+ if (request.method !== 'GET' &&
+ request.method !== 'HEAD') {
+
+ return callback(Boom.unauthorized('Invalid method', 'Hawk'));
+ }
+
+ // No other authentication
+
+ if (request.authorization) {
+ return callback(Boom.badRequest('Multiple authentications'));
+ }
+
+ // Parse bewit
+
+ var bewitString = Hoek.base64urlDecode(resource[3]);
+ if (bewitString instanceof Error) {
+ return callback(Boom.badRequest('Invalid bewit encoding'));
+ }
+
+ // Bewit format: id\exp\mac\ext ('\' is used because it is a reserved header attribute character)
+
+ var bewitParts = bewitString.split('\\');
+ if (bewitParts.length !== 4) {
+ return callback(Boom.badRequest('Invalid bewit structure'));
+ }
+
+ var bewit = {
+ id: bewitParts[0],
+ exp: parseInt(bewitParts[1], 10),
+ mac: bewitParts[2],
+ ext: bewitParts[3] || ''
+ };
+
+ if (!bewit.id ||
+ !bewit.exp ||
+ !bewit.mac) {
+
+ return callback(Boom.badRequest('Missing bewit attributes'));
+ }
+
+ // Construct URL without bewit
+
+ var url = resource[1];
+ if (resource[4]) {
+ url += resource[2] + resource[4];
+ }
+
+ // Check expiration
+
+ if (bewit.exp * 1000 <= now) {
+ return callback(Boom.unauthorized('Access expired', 'Hawk'), null, bewit);
+ }
+
+ // Fetch Hawk credentials
+
+ credentialsFunc(bewit.id, function (err, credentials) {
+
+ if (err) {
+ return callback(err, credentials || null, bewit.ext);
+ }
+
+ if (!credentials) {
+ return callback(Boom.unauthorized('Unknown credentials', 'Hawk'), null, bewit);
+ }
+
+ if (!credentials.key ||
+ !credentials.algorithm) {
+
+ return callback(Boom.internal('Invalid credentials'), credentials, bewit);
+ }
+
+ if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
+ return callback(Boom.internal('Unknown algorithm'), credentials, bewit);
+ }
+
+ // Calculate MAC
+
+ var mac = Crypto.calculateMac('bewit', credentials, {
+ ts: bewit.exp,
+ nonce: '',
+ method: 'GET',
+ resource: url,
+ host: request.host,
+ port: request.port,
+ ext: bewit.ext
+ });
+
+ if (!Cryptiles.fixedTimeComparison(mac, bewit.mac)) {
+ return callback(Boom.unauthorized('Bad mac', 'Hawk'), credentials, bewit);
+ }
+
+ // Successful authentication
+
+ return callback(null, credentials, bewit);
+ });
+};
+
+
+/*
+ * options are the same as authenticate() with the exception that the only supported options are:
+ * 'nonceFunc', 'timestampSkewSec', 'localtimeOffsetMsec'
+ */
+
+exports.authenticateMessage = function (host, port, message, authorization, credentialsFunc, options, callback) {
+
+ callback = Hoek.nextTick(callback);
+
+ // Default options
+
+ options.nonceFunc = options.nonceFunc || internals.nonceFunc;
+ options.timestampSkewSec = options.timestampSkewSec || 60; // 60 seconds
+
+ // Application time
+
+ var now = Utils.now(options.localtimeOffsetMsec); // Measure now before any other processing
+
+ // Validate authorization
+
+ if (!authorization.id ||
+ !authorization.ts ||
+ !authorization.nonce ||
+ !authorization.hash ||
+ !authorization.mac) {
+
+ return callback(Boom.badRequest('Invalid authorization'));
+ }
+
+ // Fetch Hawk credentials
+
+ credentialsFunc(authorization.id, function (err, credentials) {
+
+ if (err) {
+ return callback(err, credentials || null);
+ }
+
+ if (!credentials) {
+ return callback(Boom.unauthorized('Unknown credentials', 'Hawk'));
+ }
+
+ if (!credentials.key ||
+ !credentials.algorithm) {
+
+ return callback(Boom.internal('Invalid credentials'), credentials);
+ }
+
+ if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
+ return callback(Boom.internal('Unknown algorithm'), credentials);
+ }
+
+ // Construct artifacts container
+
+ var artifacts = {
+ ts: authorization.ts,
+ nonce: authorization.nonce,
+ host: host,
+ port: port,
+ hash: authorization.hash
+ };
+
+ // Calculate MAC
+
+ var mac = Crypto.calculateMac('message', credentials, artifacts);
+ if (!Cryptiles.fixedTimeComparison(mac, authorization.mac)) {
+ return callback(Boom.unauthorized('Bad mac', 'Hawk'), credentials);
+ }
+
+ // Check payload hash
+
+ var hash = Crypto.calculatePayloadHash(message, credentials.algorithm);
+ if (!Cryptiles.fixedTimeComparison(hash, authorization.hash)) {
+ return callback(Boom.unauthorized('Bad message hash', 'Hawk'), credentials);
+ }
+
+ // Check nonce
+
+ options.nonceFunc(credentials.key, authorization.nonce, authorization.ts, function (err) {
+
+ if (err) {
+ return callback(Boom.unauthorized('Invalid nonce', 'Hawk'), credentials);
+ }
+
+ // Check timestamp staleness
+
+ if (Math.abs((authorization.ts * 1000) - now) > (options.timestampSkewSec * 1000)) {
+ return callback(Boom.unauthorized('Stale timestamp'), credentials);
+ }
+
+ // Successful authentication
+
+ return callback(null, credentials);
+ });
+ });
+};
+
+
+internals.nonceFunc = function (key, nonce, ts, nonceCallback) {
+
+ return nonceCallback(); // No validation
+};
diff --git a/node_modules/request/node_modules/hawk/lib/utils.js b/node_modules/request/node_modules/hawk/lib/utils.js
index 8d2719abc..1df97c0e0 100755
--- a/node_modules/request/node_modules/hawk/lib/utils.js
+++ b/node_modules/request/node_modules/hawk/lib/utils.js
@@ -1,164 +1,184 @@
-// Load modules
-
-var Sntp = require('sntp');
-var Boom = require('boom');
-
-
-// Declare internals
-
-var internals = {};
-
-
-exports.version = function () {
-
- return require('../package.json').version;
-};
-
-
-// Extract host and port from request
-
-// $1 $2
-internals.hostHeaderRegex = /^(?:(?:\r\n)?\s)*((?:[^:]+)|(?:\[[^\]]+\]))(?::(\d+))?(?:(?:\r\n)?\s)*$/; // (IPv4, hostname)|(IPv6)
-
-
-exports.parseHost = function (req, hostHeaderName) {
-
- hostHeaderName = (hostHeaderName ? hostHeaderName.toLowerCase() : 'host');
- var hostHeader = req.headers[hostHeaderName];
- if (!hostHeader) {
- return null;
- }
-
- var hostParts = hostHeader.match(internals.hostHeaderRegex);
- if (!hostParts) {
- return null;
- }
-
- return {
- name: hostParts[1],
- port: (hostParts[2] ? hostParts[2] : (req.connection && req.connection.encrypted ? 443 : 80))
- };
-};
-
-
-// Parse Content-Type header content
-
-exports.parseContentType = function (header) {
-
- if (!header) {
- return '';
- }
-
- return header.split(';')[0].trim().toLowerCase();
-};
-
-
-// Convert node's to request configuration object
-
-exports.parseRequest = function (req, options) {
-
- if (!req.headers) {
- return req;
- }
-
- // Obtain host and port information
-
- if (!options.host || !options.port) {
- var host = exports.parseHost(req, options.hostHeaderName);
- if (!host) {
- return new Error('Invalid Host header');
- }
- }
-
- var request = {
- method: req.method,
- url: req.url,
- host: options.host || host.name,
- port: options.port || host.port,
- authorization: req.headers.authorization,
- contentType: req.headers['content-type'] || ''
- };
-
- return request;
-};
-
-
-exports.now = function (localtimeOffsetMsec) {
-
- return Sntp.now() + (localtimeOffsetMsec || 0);
-};
-
-
-exports.nowSecs = function (localtimeOffsetMsec) {
-
- return Math.floor(exports.now(localtimeOffsetMsec) / 1000);
-};
-
-
-// Parse Hawk HTTP Authorization header
-
-exports.parseAuthorizationHeader = function (header, keys) {
-
- keys = keys || ['id', 'ts', 'nonce', 'hash', 'ext', 'mac', 'app', 'dlg'];
-
- if (!header) {
- return Boom.unauthorized(null, 'Hawk');
- }
-
- var headerParts = header.match(/^(\w+)(?:\s+(.*))?$/); // Header: scheme[ something]
- if (!headerParts) {
- return Boom.badRequest('Invalid header syntax');
- }
-
- var scheme = headerParts[1];
- if (scheme.toLowerCase() !== 'hawk') {
- return Boom.unauthorized(null, 'Hawk');
- }
-
- var attributesString = headerParts[2];
- if (!attributesString) {
- return Boom.badRequest('Invalid header syntax');
- }
-
- var attributes = {};
- var errorMessage = '';
- var verify = attributesString.replace(/(\w+)="([^"\\]*)"\s*(?:,\s*|$)/g, function ($0, $1, $2) {
-
- // Check valid attribute names
-
- if (keys.indexOf($1) === -1) {
- errorMessage = 'Unknown attribute: ' + $1;
- return;
- }
-
- // Allowed attribute value characters: !#$%&'()*+,-./:;<=>?@[]^_`{|}~ and space, a-z, A-Z, 0-9
-
- if ($2.match(/^[ \w\!#\$%&'\(\)\*\+,\-\.\/\:;<\=>\?@\[\]\^`\{\|\}~]+$/) === null) {
- errorMessage = 'Bad attribute value: ' + $1;
- return;
- }
-
- // Check for duplicates
-
- if (attributes.hasOwnProperty($1)) {
- errorMessage = 'Duplicate attribute: ' + $1;
- return;
- }
-
- attributes[$1] = $2;
- return '';
- });
-
- if (verify !== '') {
- return Boom.badRequest(errorMessage || 'Bad header format');
- }
-
- return attributes;
-};
-
-
-exports.unauthorized = function (message, attributes) {
-
- return Boom.unauthorized(message, 'Hawk', attributes);
-};
-
+// Load modules
+
+var Sntp = require('sntp');
+var Boom = require('boom');
+
+
+// Declare internals
+
+var internals = {};
+
+
+exports.version = function () {
+
+ return require('../package.json').version;
+};
+
+
+exports.limits = {
+ maxMatchLength: 4096 // Limit the length of uris and headers to avoid a DoS attack on string matching
+};
+
+
+// Extract host and port from request
+
+// $1 $2
+internals.hostHeaderRegex = /^(?:(?:\r\n)?\s)*((?:[^:]+)|(?:\[[^\]]+\]))(?::(\d+))?(?:(?:\r\n)?\s)*$/; // (IPv4, hostname)|(IPv6)
+
+
+exports.parseHost = function (req, hostHeaderName) {
+
+ hostHeaderName = (hostHeaderName ? hostHeaderName.toLowerCase() : 'host');
+ var hostHeader = req.headers[hostHeaderName];
+ if (!hostHeader) {
+ return null;
+ }
+
+ if (hostHeader.length > exports.limits.maxMatchLength) {
+ return null;
+ }
+
+ var hostParts = hostHeader.match(internals.hostHeaderRegex);
+ if (!hostParts) {
+ return null;
+ }
+
+ return {
+ name: hostParts[1],
+ port: (hostParts[2] ? hostParts[2] : (req.connection && req.connection.encrypted ? 443 : 80))
+ };
+};
+
+
+// Parse Content-Type header content
+
+exports.parseContentType = function (header) {
+
+ if (!header) {
+ return '';
+ }
+
+ return header.split(';')[0].trim().toLowerCase();
+};
+
+
+// Convert node's to request configuration object
+
+exports.parseRequest = function (req, options) {
+
+ if (!req.headers) {
+ return req;
+ }
+
+ // Obtain host and port information
+
+ var host;
+ if (!options.host ||
+ !options.port) {
+
+ host = exports.parseHost(req, options.hostHeaderName);
+ if (!host) {
+ return new Error('Invalid Host header');
+ }
+ }
+
+ var request = {
+ method: req.method,
+ url: req.url,
+ host: options.host || host.name,
+ port: options.port || host.port,
+ authorization: req.headers.authorization,
+ contentType: req.headers['content-type'] || ''
+ };
+
+ return request;
+};
+
+
+exports.now = function (localtimeOffsetMsec) {
+
+ return Sntp.now() + (localtimeOffsetMsec || 0);
+};
+
+
+exports.nowSecs = function (localtimeOffsetMsec) {
+
+ return Math.floor(exports.now(localtimeOffsetMsec) / 1000);
+};
+
+
+internals.authHeaderRegex = /^(\w+)(?:\s+(.*))?$/; // Header: scheme[ something]
+internals.attributeRegex = /^[ \w\!#\$%&'\(\)\*\+,\-\.\/\:;<\=>\?@\[\]\^`\{\|\}~]+$/; // !#$%&'()*+,-./:;<=>?@[]^_`{|}~ and space, a-z, A-Z, 0-9
+
+
+// Parse Hawk HTTP Authorization header
+
+exports.parseAuthorizationHeader = function (header, keys) {
+
+ keys = keys || ['id', 'ts', 'nonce', 'hash', 'ext', 'mac', 'app', 'dlg'];
+
+ if (!header) {
+ return Boom.unauthorized(null, 'Hawk');
+ }
+
+ if (header.length > exports.limits.maxMatchLength) {
+ return Boom.badRequest('Header length too long');
+ }
+
+ var headerParts = header.match(internals.authHeaderRegex);
+ if (!headerParts) {
+ return Boom.badRequest('Invalid header syntax');
+ }
+
+ var scheme = headerParts[1];
+ if (scheme.toLowerCase() !== 'hawk') {
+ return Boom.unauthorized(null, 'Hawk');
+ }
+
+ var attributesString = headerParts[2];
+ if (!attributesString) {
+ return Boom.badRequest('Invalid header syntax');
+ }
+
+ var attributes = {};
+ var errorMessage = '';
+ var verify = attributesString.replace(/(\w+)="([^"\\]*)"\s*(?:,\s*|$)/g, function ($0, $1, $2) {
+
+ // Check valid attribute names
+
+ if (keys.indexOf($1) === -1) {
+ errorMessage = 'Unknown attribute: ' + $1;
+ return;
+ }
+
+ // Allowed attribute value characters
+
+ if ($2.match(internals.attributeRegex) === null) {
+ errorMessage = 'Bad attribute value: ' + $1;
+ return;
+ }
+
+ // Check for duplicates
+
+ if (attributes.hasOwnProperty($1)) {
+ errorMessage = 'Duplicate attribute: ' + $1;
+ return;
+ }
+
+ attributes[$1] = $2;
+ return '';
+ });
+
+ if (verify !== '') {
+ return Boom.badRequest(errorMessage || 'Bad header format');
+ }
+
+ return attributes;
+};
+
+
+exports.unauthorized = function (message, attributes) {
+
+ return Boom.unauthorized(message, 'Hawk', attributes);
+};
+
diff --git a/node_modules/request/node_modules/hawk/package.json b/node_modules/request/node_modules/hawk/package.json
index 4a51ea4ca..4bae96efe 100644
--- a/node_modules/request/node_modules/hawk/package.json
+++ b/node_modules/request/node_modules/hawk/package.json
@@ -2,15 +2,15 @@
"_args": [
[
"hawk@~3.1.0",
- "/Users/ogd/Documents/projects/npm/npm/node_modules/request"
+ "/Users/rebecca/code/npm/node_modules/request"
]
],
"_from": "hawk@>=3.1.0 <3.2.0",
- "_id": "hawk@3.1.2",
+ "_id": "hawk@3.1.3",
"_inCache": true,
"_installable": true,
"_location": "/request/hawk",
- "_nodeVersion": "5.0.0",
+ "_nodeVersion": "5.4.1",
"_npmUser": {
"email": "eran@hammer.io",
"name": "hueniverse"
@@ -28,11 +28,11 @@
"_requiredBy": [
"/request"
],
- "_resolved": "https://registry.npmjs.org/hawk/-/hawk-3.1.2.tgz",
- "_shasum": "90c90118886e21975d1ad4ae9b3e284ed19a2de8",
+ "_resolved": "https://registry.npmjs.org/hawk/-/hawk-3.1.3.tgz",
+ "_shasum": "078444bd7c1640b0fe540d2c9b73d59678e8e1c4",
"_shrinkwrap": null,
"_spec": "hawk@~3.1.0",
- "_where": "/Users/ogd/Documents/projects/npm/npm/node_modules/request",
+ "_where": "/Users/rebecca/code/npm/node_modules/request",
"author": {
"email": "eran@hammer.io",
"name": "Eran Hammer",
@@ -56,13 +56,13 @@
},
"directories": {},
"dist": {
- "shasum": "90c90118886e21975d1ad4ae9b3e284ed19a2de8",
- "tarball": "http://registry.npmjs.org/hawk/-/hawk-3.1.2.tgz"
+ "shasum": "078444bd7c1640b0fe540d2c9b73d59678e8e1c4",
+ "tarball": "http://registry.npmjs.org/hawk/-/hawk-3.1.3.tgz"
},
"engines": {
"node": ">=0.10.32"
},
- "gitHead": "66dd8f9b32058c2e834b0976b2f112e19f38ee72",
+ "gitHead": "2f0b93b34ed9b0ebc865838ef70c6a4035591430",
"homepage": "https://github.com/hueniverse/hawk#readme",
"keywords": [
"authentication",
@@ -89,5 +89,5 @@
"test": "lab -a code -t 100 -L",
"test-cov-html": "lab -a code -r html -o coverage.html"
},
- "version": "3.1.2"
+ "version": "3.1.3"
}
diff --git a/node_modules/request/node_modules/hawk/test/browser.js b/node_modules/request/node_modules/hawk/test/browser.js
index 9bec675fe..e18edf78a 100755
--- a/node_modules/request/node_modules/hawk/test/browser.js
+++ b/node_modules/request/node_modules/hawk/test/browser.js
@@ -1,1492 +1,1492 @@
-// Load modules
-
-var Url = require('url');
-var Code = require('code');
-var Hawk = require('../lib');
-var Hoek = require('hoek');
-var Lab = require('lab');
-var Browser = require('../lib/browser');
-
-
-// Declare internals
-
-var internals = {};
-
-
-// Test shortcuts
-
-var lab = exports.lab = Lab.script();
-var describe = lab.experiment;
-var it = lab.test;
-var expect = Code.expect;
-
-
-describe('Browser', function () {
-
- var credentialsFunc = function (id, callback) {
-
- var credentials = {
- id: id,
- key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
- algorithm: (id === '1' ? 'sha1' : 'sha256'),
- user: 'steve'
- };
-
- return callback(null, credentials);
- };
-
- it('should generate a bewit then successfully authenticate it', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?a=1&b=2',
- host: 'example.com',
- port: 80
- };
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var bewit = Browser.client.bewit('http://example.com/resource/4?a=1&b=2', { credentials: credentials1, ttlSec: 60 * 60 * 24 * 365 * 100, ext: 'some-app-data' });
- req.url += '&bewit=' + bewit;
-
- Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials2, attributes) {
-
- expect(err).to.not.exist();
- expect(credentials2.user).to.equal('steve');
- expect(attributes.ext).to.equal('some-app-data');
- done();
- });
- });
- });
-
- it('should generate a bewit then successfully authenticate it (no ext)', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?a=1&b=2',
- host: 'example.com',
- port: 80
- };
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var bewit = Browser.client.bewit('http://example.com/resource/4?a=1&b=2', { credentials: credentials1, ttlSec: 60 * 60 * 24 * 365 * 100 });
- req.url += '&bewit=' + bewit;
-
- Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials2, attributes) {
-
- expect(err).to.not.exist();
- expect(credentials2.user).to.equal('steve');
- done();
- });
- });
- });
-
- describe('bewit()', function () {
-
- it('returns a valid bewit value', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' });
- expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdca3NjeHdOUjJ0SnBQMVQxekRMTlBiQjVVaUtJVTl0T1NKWFRVZEc3WDloOD1ceGFuZHlhbmR6');
- done();
- });
-
- it('returns a valid bewit value (explicit HTTP port)', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var bewit = Browser.client.bewit('http://example.com:8080/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' });
- expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdcaFpiSjNQMmNLRW80a3kwQzhqa1pBa1J5Q1p1ZWc0V1NOYnhWN3ZxM3hIVT1ceGFuZHlhbmR6');
- done();
- });
-
- it('returns a valid bewit value (explicit HTTPS port)', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var bewit = Browser.client.bewit('https://example.com:8043/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' });
- expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdcL2t4UjhwK0xSaTdvQTRnUXc3cWlxa3BiVHRKYkR4OEtRMC9HRUwvVytTUT1ceGFuZHlhbmR6');
- done();
- });
-
- it('returns a valid bewit value (null ext)', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: null });
- expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdcSUdZbUxnSXFMckNlOEN4dktQczRKbFdJQStValdKSm91d2dBUmlWaENBZz1c');
- done();
- });
-
- it('errors on invalid options', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', 4);
- expect(bewit).to.equal('');
- done();
- });
-
- it('errors on missing uri', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var bewit = Browser.client.bewit('', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' });
- expect(bewit).to.equal('');
- done();
- });
-
- it('errors on invalid uri', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var bewit = Browser.client.bewit(5, { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' });
- expect(bewit).to.equal('');
- done();
- });
-
- it('errors on invalid credentials (id)', function (done) {
-
- var credentials = {
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 3000, ext: 'xandyandz' });
- expect(bewit).to.equal('');
- done();
- });
-
- it('errors on missing credentials', function (done) {
-
- var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', { ttlSec: 3000, ext: 'xandyandz' });
- expect(bewit).to.equal('');
- done();
- });
-
- it('errors on invalid credentials (key)', function (done) {
-
- var credentials = {
- id: '123456',
- algorithm: 'sha256'
- };
-
- var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 3000, ext: 'xandyandz' });
- expect(bewit).to.equal('');
- done();
- });
-
- it('errors on invalid algorithm', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'hmac-sha-0'
- };
-
- var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, ext: 'xandyandz' });
- expect(bewit).to.equal('');
- done();
- });
-
- it('errors on missing options', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'hmac-sha-0'
- };
-
- var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow');
- expect(bewit).to.equal('');
- done();
- });
- });
-
- it('generates a header then successfully parse it (configuration)', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080
- };
-
- credentialsFunc('123456', function (err, credentials1) {
-
- req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data' }).field;
- expect(req.authorization).to.exist();
-
- Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
-
- expect(err).to.not.exist();
- expect(credentials2.user).to.equal('steve');
- expect(artifacts.ext).to.equal('some-app-data');
- done();
- });
- });
- });
-
- it('generates a header then successfully parse it (node request)', function (done) {
-
- var req = {
- method: 'POST',
- url: '/resource/4?filter=a',
- headers: {
- host: 'example.com:8080',
- 'content-type': 'text/plain;x=y'
- }
- };
-
- var payload = 'some not so random text';
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var reqHeader = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] });
- req.headers.authorization = reqHeader.field;
-
- Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
-
- expect(err).to.not.exist();
- expect(credentials2.user).to.equal('steve');
- expect(artifacts.ext).to.equal('some-app-data');
- expect(Hawk.server.authenticatePayload(payload, credentials2, artifacts, req.headers['content-type'])).to.equal(true);
-
- var res = {
- headers: {
- 'content-type': 'text/plain'
- },
- getResponseHeader: function (header) {
-
- return res.headers[header.toLowerCase()];
- }
- };
-
- res.headers['server-authorization'] = Hawk.server.header(credentials2, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' });
- expect(res.headers['server-authorization']).to.exist();
-
- expect(Browser.client.authenticate(res, credentials2, artifacts, { payload: 'some reply' })).to.equal(true);
- done();
- });
- });
- });
-
- it('generates a header then successfully parse it (browserify)', function (done) {
-
- var req = {
- method: 'POST',
- url: '/resource/4?filter=a',
- headers: {
- host: 'example.com:8080',
- 'content-type': 'text/plain;x=y'
- }
- };
-
- var payload = 'some not so random text';
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var reqHeader = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] });
- req.headers.authorization = reqHeader.field;
-
- Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
-
- expect(err).to.not.exist();
- expect(credentials2.user).to.equal('steve');
- expect(artifacts.ext).to.equal('some-app-data');
- expect(Hawk.server.authenticatePayload(payload, credentials2, artifacts, req.headers['content-type'])).to.equal(true);
-
- var res = {
- headers: {
- 'content-type': 'text/plain'
- },
- getHeader: function (header) {
-
- return res.headers[header.toLowerCase()];
- }
- };
-
- res.headers['server-authorization'] = Hawk.server.header(credentials2, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' });
- expect(res.headers['server-authorization']).to.exist();
-
- expect(Browser.client.authenticate(res, credentials2, artifacts, { payload: 'some reply' })).to.equal(true);
- done();
- });
- });
- });
-
- it('generates a header then successfully parse it (time offset)', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080
- };
-
- credentialsFunc('123456', function (err, credentials1) {
-
- req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', localtimeOffsetMsec: 100000 }).field;
- expect(req.authorization).to.exist();
-
- Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 100000 }, function (err, credentials2, artifacts) {
-
- expect(err).to.not.exist();
- expect(credentials2.user).to.equal('steve');
- expect(artifacts.ext).to.equal('some-app-data');
- done();
- });
- });
- });
-
- it('generates a header then successfully parse it (no server header options)', function (done) {
-
- var req = {
- method: 'POST',
- url: '/resource/4?filter=a',
- headers: {
- host: 'example.com:8080',
- 'content-type': 'text/plain;x=y'
- }
- };
-
- var payload = 'some not so random text';
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var reqHeader = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] });
- req.headers.authorization = reqHeader.field;
-
- Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
-
- expect(err).to.not.exist();
- expect(credentials2.user).to.equal('steve');
- expect(artifacts.ext).to.equal('some-app-data');
- expect(Hawk.server.authenticatePayload(payload, credentials2, artifacts, req.headers['content-type'])).to.equal(true);
-
- var res = {
- headers: {
- 'content-type': 'text/plain'
- },
- getResponseHeader: function (header) {
-
- return res.headers[header.toLowerCase()];
- }
- };
-
- res.headers['server-authorization'] = Hawk.server.header(credentials2, artifacts);
- expect(res.headers['server-authorization']).to.exist();
-
- expect(Browser.client.authenticate(res, credentials2, artifacts)).to.equal(true);
- done();
- });
- });
- });
-
- it('generates a header then successfully parse it (no server header)', function (done) {
-
- var req = {
- method: 'POST',
- url: '/resource/4?filter=a',
- headers: {
- host: 'example.com:8080',
- 'content-type': 'text/plain;x=y'
- }
- };
-
- var payload = 'some not so random text';
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var reqHeader = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] });
- req.headers.authorization = reqHeader.field;
-
- Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
-
- expect(err).to.not.exist();
- expect(credentials2.user).to.equal('steve');
- expect(artifacts.ext).to.equal('some-app-data');
- expect(Hawk.server.authenticatePayload(payload, credentials2, artifacts, req.headers['content-type'])).to.equal(true);
-
- var res = {
- headers: {
- 'content-type': 'text/plain'
- },
- getResponseHeader: function (header) {
-
- return res.headers[header.toLowerCase()];
- }
- };
-
- expect(Browser.client.authenticate(res, credentials2, artifacts)).to.equal(true);
- done();
- });
- });
- });
-
- it('generates a header with stale ts and successfully authenticate on second call', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080
- };
-
- credentialsFunc('123456', function (err, credentials1) {
-
- Browser.utils.setNtpOffset(60 * 60 * 1000);
- var header = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data' });
- req.authorization = header.field;
- expect(req.authorization).to.exist();
-
- Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts2) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('Stale timestamp');
-
- var res = {
- headers: {
- 'www-authenticate': err.output.headers['WWW-Authenticate']
- },
- getResponseHeader: function (lookup) {
-
- return res.headers[lookup.toLowerCase()];
- }
- };
-
- expect(Browser.utils.getNtpOffset()).to.equal(60 * 60 * 1000);
- expect(Browser.client.authenticate(res, credentials2, header.artifacts)).to.equal(true);
- expect(Browser.utils.getNtpOffset()).to.equal(0);
-
- req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials2, ext: 'some-app-data' }).field;
- expect(req.authorization).to.exist();
-
- Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials3, artifacts3) {
-
- expect(err).to.not.exist();
- expect(credentials3.user).to.equal('steve');
- expect(artifacts3.ext).to.equal('some-app-data');
- done();
- });
- });
- });
- });
-
- it('generates a header with stale ts and successfully authenticate on second call (manual localStorage)', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080
- };
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var localStorage = new Browser.internals.LocalStorage();
-
- Browser.utils.setStorage(localStorage);
-
- Browser.utils.setNtpOffset(60 * 60 * 1000);
- var header = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data' });
- req.authorization = header.field;
- expect(req.authorization).to.exist();
-
- Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts2) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('Stale timestamp');
-
- var res = {
- headers: {
- 'www-authenticate': err.output.headers['WWW-Authenticate']
- },
- getResponseHeader: function (lookup) {
-
- return res.headers[lookup.toLowerCase()];
- }
- };
-
- expect(parseInt(localStorage.getItem('hawk_ntp_offset'))).to.equal(60 * 60 * 1000);
- expect(Browser.utils.getNtpOffset()).to.equal(60 * 60 * 1000);
- expect(Browser.client.authenticate(res, credentials2, header.artifacts)).to.equal(true);
- expect(Browser.utils.getNtpOffset()).to.equal(0);
- expect(parseInt(localStorage.getItem('hawk_ntp_offset'))).to.equal(0);
-
- req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials2, ext: 'some-app-data' }).field;
- expect(req.authorization).to.exist();
-
- Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials3, artifacts3) {
-
- expect(err).to.not.exist();
- expect(credentials3.user).to.equal('steve');
- expect(artifacts3.ext).to.equal('some-app-data');
- done();
- });
- });
- });
- });
-
- it('generates a header then fails to parse it (missing server header hash)', function (done) {
-
- var req = {
- method: 'POST',
- url: '/resource/4?filter=a',
- headers: {
- host: 'example.com:8080',
- 'content-type': 'text/plain;x=y'
- }
- };
-
- var payload = 'some not so random text';
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var reqHeader = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] });
- req.headers.authorization = reqHeader.field;
-
- Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
-
- expect(err).to.not.exist();
- expect(credentials2.user).to.equal('steve');
- expect(artifacts.ext).to.equal('some-app-data');
- expect(Hawk.server.authenticatePayload(payload, credentials2, artifacts, req.headers['content-type'])).to.equal(true);
-
- var res = {
- headers: {
- 'content-type': 'text/plain'
- },
- getResponseHeader: function (header) {
-
- return res.headers[header.toLowerCase()];
- }
- };
-
- res.headers['server-authorization'] = Hawk.server.header(credentials2, artifacts);
- expect(res.headers['server-authorization']).to.exist();
-
- expect(Browser.client.authenticate(res, credentials2, artifacts, { payload: 'some reply' })).to.equal(false);
- done();
- });
- });
- });
-
- it('generates a header then successfully parse it (with hash)', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080
- };
-
- credentialsFunc('123456', function (err, credentials1) {
-
- req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, payload: 'hola!', ext: 'some-app-data' }).field;
- Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
-
- expect(err).to.not.exist();
- expect(credentials2.user).to.equal('steve');
- expect(artifacts.ext).to.equal('some-app-data');
- done();
- });
- });
- });
-
- it('generates a header then successfully parse it then validate payload', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080
- };
-
- credentialsFunc('123456', function (err, credentials1) {
-
- req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, payload: 'hola!', ext: 'some-app-data' }).field;
- Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
-
- expect(err).to.not.exist();
- expect(credentials2.user).to.equal('steve');
- expect(artifacts.ext).to.equal('some-app-data');
- expect(Hawk.server.authenticatePayload('hola!', credentials2, artifacts)).to.be.true();
- expect(Hawk.server.authenticatePayload('hello!', credentials2, artifacts)).to.be.false();
- done();
- });
- });
- });
-
- it('generates a header then successfully parse it (app)', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080
- };
-
- credentialsFunc('123456', function (err, credentials1) {
-
- req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', app: 'asd23ased' }).field;
- Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
-
- expect(err).to.not.exist();
- expect(credentials2.user).to.equal('steve');
- expect(artifacts.ext).to.equal('some-app-data');
- expect(artifacts.app).to.equal('asd23ased');
- done();
- });
- });
- });
-
- it('generates a header then successfully parse it (app, dlg)', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080
- };
-
- credentialsFunc('123456', function (err, credentials1) {
-
- req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', app: 'asd23ased', dlg: '23434szr3q4d' }).field;
- Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
-
- expect(err).to.not.exist();
- expect(credentials2.user).to.equal('steve');
- expect(artifacts.ext).to.equal('some-app-data');
- expect(artifacts.app).to.equal('asd23ased');
- expect(artifacts.dlg).to.equal('23434szr3q4d');
- done();
- });
- });
- });
-
- it('generates a header then fail authentication due to bad hash', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080
- };
-
- credentialsFunc('123456', function (err, credentials1) {
-
- req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, payload: 'hola!', ext: 'some-app-data' }).field;
- Hawk.server.authenticate(req, credentialsFunc, { payload: 'byebye!' }, function (err, credentials2, artifacts) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Bad payload hash');
- done();
- });
- });
- });
-
- it('generates a header for one resource then fail to authenticate another', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080
- };
-
- credentialsFunc('123456', function (err, credentials1) {
-
- req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data' }).field;
- req.url = '/something/else';
-
- Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
-
- expect(err).to.exist();
- expect(credentials2).to.exist();
- done();
- });
- });
- });
-
- describe('client', function () {
-
- describe('header()', function () {
-
- it('returns a valid authorization header (sha1)', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha1'
- };
-
- var header = Browser.client.header('http://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about' }).field;
- expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="bsvY3IfUllw6V5rvk4tStEvpBhE=", ext="Bazinga!", mac="qbf1ZPG/r/e06F4ht+T77LXi5vw="');
- done();
- });
-
- it('returns a valid authorization header (sha256)', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' }).field;
- expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", ext="Bazinga!", mac="q1CwFoSHzPZSkbIvl0oYlD+91rBUEvFk763nMjMndj8="');
- done();
- });
-
- it('returns a valid authorization header (empty payload)', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha1'
- };
-
- var header = Browser.client.header('http://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207, nonce: 'Ygvqdz', payload: '' }).field;
- expect(header).to.equal('Hawk id=\"123456\", ts=\"1353809207\", nonce=\"Ygvqdz\", hash=\"404ghL7K+hfyhByKKejFBRGgTjU=\", ext=\"Bazinga!\", mac=\"Bh1sj1DOfFRWOdi3ww52nLCJdBE=\"');
- done();
- });
-
- it('returns a valid authorization header (no ext)', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' }).field;
- expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", mac="HTgtd0jPI6E4izx8e4OHdO36q00xFCU0FolNq3RiCYs="');
- done();
- });
-
- it('returns a valid authorization header (null ext)', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain', ext: null }).field;
- expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", mac="HTgtd0jPI6E4izx8e4OHdO36q00xFCU0FolNq3RiCYs="');
- done();
- });
-
- it('returns a valid authorization header (uri object)', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var uri = Browser.utils.parseUri('https://example.net/somewhere/over/the/rainbow');
- var header = Browser.client.header(uri, 'POST', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' }).field;
- expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", mac="HTgtd0jPI6E4izx8e4OHdO36q00xFCU0FolNq3RiCYs="');
- done();
- });
-
- it('errors on missing options', function (done) {
-
- var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST');
- expect(header.field).to.equal('');
- expect(header.err).to.equal('Invalid argument type');
- done();
- });
-
- it('errors on empty uri', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var header = Browser.client.header('', 'POST', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' });
- expect(header.field).to.equal('');
- expect(header.err).to.equal('Invalid argument type');
- done();
- });
-
- it('errors on invalid uri', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var header = Browser.client.header(4, 'POST', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' });
- expect(header.field).to.equal('');
- expect(header.err).to.equal('Invalid argument type');
- done();
- });
-
- it('errors on missing method', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', '', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' });
- expect(header.field).to.equal('');
- expect(header.err).to.equal('Invalid argument type');
- done();
- });
-
- it('errors on invalid method', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 5, { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' });
- expect(header.field).to.equal('');
- expect(header.err).to.equal('Invalid argument type');
- done();
- });
-
- it('errors on missing credentials', function (done) {
-
- var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { ext: 'Bazinga!', timestamp: 1353809207 });
- expect(header.field).to.equal('');
- expect(header.err).to.equal('Invalid credentials object');
- done();
- });
-
- it('errors on invalid credentials (id)', function (done) {
-
- var credentials = {
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207 });
- expect(header.field).to.equal('');
- expect(header.err).to.equal('Invalid credentials object');
- done();
- });
-
- it('errors on invalid credentials (key)', function (done) {
-
- var credentials = {
- id: '123456',
- algorithm: 'sha256'
- };
-
- var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207 });
- expect(header.field).to.equal('');
- expect(header.err).to.equal('Invalid credentials object');
- done();
- });
-
- it('errors on invalid algorithm', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'hmac-sha-0'
- };
-
- var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, payload: 'something, anything!', ext: 'Bazinga!', timestamp: 1353809207 });
- expect(header.field).to.equal('');
- expect(header.err).to.equal('Unknown algorithm');
- done();
- });
-
- it('uses a pre-calculated payload hash', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var options = { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' };
- options.hash = Browser.crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType);
- var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', options).field;
- expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", ext="Bazinga!", mac="q1CwFoSHzPZSkbIvl0oYlD+91rBUEvFk763nMjMndj8="');
- done();
- });
- });
-
- describe('authenticate()', function () {
-
- it('skips tsm validation when missing ts', function (done) {
-
- var res = {
- headers: {
- 'www-authenticate': 'Hawk error="Stale timestamp"'
- },
- getResponseHeader: function (header) {
-
- return res.headers[header.toLowerCase()];
- }
- };
-
- var credentials = {
- id: '123456',
- key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
- algorithm: 'sha256',
- user: 'steve'
- };
-
- var artifacts = {
- ts: 1402135580,
- nonce: 'iBRB6t',
- method: 'GET',
- resource: '/resource/4?filter=a',
- host: 'example.com',
- port: '8080',
- ext: 'some-app-data'
- };
-
- expect(Browser.client.authenticate(res, credentials, artifacts)).to.equal(true);
- done();
- });
-
- it('returns false on invalid header', function (done) {
-
- var res = {
- headers: {
- 'server-authorization': 'Hawk mac="abc", bad="xyz"'
- },
- getResponseHeader: function (header) {
-
- return res.headers[header.toLowerCase()];
- }
- };
-
- expect(Browser.client.authenticate(res, {})).to.equal(false);
- done();
- });
-
- it('returns false on invalid mac', function (done) {
-
- var res = {
- headers: {
- 'content-type': 'text/plain',
- 'server-authorization': 'Hawk mac="_IJRsMl/4oL+nn+vKoeVZPdCHXB4yJkNnBbTbHFZUYE=", hash="f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=", ext="response-specific"'
- },
- getResponseHeader: function (header) {
-
- return res.headers[header.toLowerCase()];
- }
- };
-
- var artifacts = {
- method: 'POST',
- host: 'example.com',
- port: '8080',
- resource: '/resource/4?filter=a',
- ts: '1362336900',
- nonce: 'eb5S_L',
- hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
- ext: 'some-app-data',
- app: undefined,
- dlg: undefined,
- mac: 'BlmSe8K+pbKIb6YsZCnt4E1GrYvY1AaYayNR82dGpIk=',
- id: '123456'
- };
-
- var credentials = {
- id: '123456',
- key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
- algorithm: 'sha256',
- user: 'steve'
- };
-
- expect(Browser.client.authenticate(res, credentials, artifacts)).to.equal(false);
- done();
- });
-
- it('returns true on ignoring hash', function (done) {
-
- var res = {
- headers: {
- 'content-type': 'text/plain',
- 'server-authorization': 'Hawk mac="XIJRsMl/4oL+nn+vKoeVZPdCHXB4yJkNnBbTbHFZUYE=", hash="f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=", ext="response-specific"'
- },
- getResponseHeader: function (header) {
-
- return res.headers[header.toLowerCase()];
- }
- };
-
- var artifacts = {
- method: 'POST',
- host: 'example.com',
- port: '8080',
- resource: '/resource/4?filter=a',
- ts: '1362336900',
- nonce: 'eb5S_L',
- hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
- ext: 'some-app-data',
- app: undefined,
- dlg: undefined,
- mac: 'BlmSe8K+pbKIb6YsZCnt4E1GrYvY1AaYayNR82dGpIk=',
- id: '123456'
- };
-
- var credentials = {
- id: '123456',
- key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
- algorithm: 'sha256',
- user: 'steve'
- };
-
- expect(Browser.client.authenticate(res, credentials, artifacts)).to.equal(true);
- done();
- });
-
- it('errors on invalid WWW-Authenticate header format', function (done) {
-
- var res = {
- headers: {
- 'www-authenticate': 'Hawk ts="1362346425875", tsm="PhwayS28vtnn3qbv0mqRBYSXebN/zggEtucfeZ620Zo=", x="Stale timestamp"'
- },
- getResponseHeader: function (header) {
-
- return res.headers[header.toLowerCase()];
- }
- };
-
- expect(Browser.client.authenticate(res, {})).to.equal(false);
- done();
- });
-
- it('errors on invalid WWW-Authenticate header format', function (done) {
-
- var credentials = {
- id: '123456',
- key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
- algorithm: 'sha256',
- user: 'steve'
- };
-
- var res = {
- headers: {
- 'www-authenticate': 'Hawk ts="1362346425875", tsm="hwayS28vtnn3qbv0mqRBYSXebN/zggEtucfeZ620Zo=", error="Stale timestamp"'
- },
- getResponseHeader: function (header) {
-
- return res.headers[header.toLowerCase()];
- }
- };
-
- expect(Browser.client.authenticate(res, credentials)).to.equal(false);
- done();
- });
- });
-
- describe('message()', function () {
-
- it('generates an authorization then successfully parse it', function (done) {
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var auth = Browser.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
- expect(auth).to.exist();
-
- Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials2) {
-
- expect(err).to.not.exist();
- expect(credentials2.user).to.equal('steve');
- done();
- });
- });
- });
-
- it('generates an authorization using custom nonce/timestamp', function (done) {
-
- credentialsFunc('123456', function (err, credentials) {
-
- var auth = Browser.client.message('example.com', 8080, 'some message', { credentials: credentials, nonce: 'abc123', timestamp: 1398536270957 });
- expect(auth).to.exist();
- expect(auth.nonce).to.equal('abc123');
- expect(auth.ts).to.equal(1398536270957);
- done();
- });
- });
-
- it('errors on missing host', function (done) {
-
- credentialsFunc('123456', function (err, credentials) {
-
- var auth = Browser.client.message(null, 8080, 'some message', { credentials: credentials });
- expect(auth).to.not.exist();
- done();
- });
- });
-
- it('errors on invalid host', function (done) {
-
- credentialsFunc('123456', function (err, credentials) {
-
- var auth = Browser.client.message(5, 8080, 'some message', { credentials: credentials });
- expect(auth).to.not.exist();
- done();
- });
- });
-
- it('errors on missing port', function (done) {
-
- credentialsFunc('123456', function (err, credentials) {
-
- var auth = Browser.client.message('example.com', 0, 'some message', { credentials: credentials });
- expect(auth).to.not.exist();
- done();
- });
- });
-
- it('errors on invalid port', function (done) {
-
- credentialsFunc('123456', function (err, credentials) {
-
- var auth = Browser.client.message('example.com', 'a', 'some message', { credentials: credentials });
- expect(auth).to.not.exist();
- done();
- });
- });
-
- it('errors on missing message', function (done) {
-
- credentialsFunc('123456', function (err, credentials) {
-
- var auth = Browser.client.message('example.com', 8080, undefined, { credentials: credentials });
- expect(auth).to.not.exist();
- done();
- });
- });
-
- it('errors on null message', function (done) {
-
- credentialsFunc('123456', function (err, credentials) {
-
- var auth = Browser.client.message('example.com', 8080, null, { credentials: credentials });
- expect(auth).to.not.exist();
- done();
- });
- });
-
- it('errors on invalid message', function (done) {
-
- credentialsFunc('123456', function (err, credentials) {
-
- var auth = Browser.client.message('example.com', 8080, 5, { credentials: credentials });
- expect(auth).to.not.exist();
- done();
- });
- });
-
- it('errors on missing credentials', function (done) {
-
- var auth = Browser.client.message('example.com', 8080, 'some message', {});
- expect(auth).to.not.exist();
- done();
- });
-
- it('errors on missing options', function (done) {
-
- var auth = Browser.client.message('example.com', 8080, 'some message');
- expect(auth).to.not.exist();
- done();
- });
-
- it('errors on invalid credentials (id)', function (done) {
-
- credentialsFunc('123456', function (err, credentials) {
-
- var creds = Hoek.clone(credentials);
- delete creds.id;
- var auth = Browser.client.message('example.com', 8080, 'some message', { credentials: creds });
- expect(auth).to.not.exist();
- done();
- });
- });
-
- it('errors on invalid credentials (key)', function (done) {
-
- credentialsFunc('123456', function (err, credentials) {
-
- var creds = Hoek.clone(credentials);
- delete creds.key;
- var auth = Browser.client.message('example.com', 8080, 'some message', { credentials: creds });
- expect(auth).to.not.exist();
- done();
- });
- });
-
- it('errors on invalid algorithm', function (done) {
-
- credentialsFunc('123456', function (err, credentials) {
-
- var creds = Hoek.clone(credentials);
- creds.algorithm = 'blah';
- var auth = Browser.client.message('example.com', 8080, 'some message', { credentials: creds });
- expect(auth).to.not.exist();
- done();
- });
- });
- });
-
- describe('authenticateTimestamp()', function (done) {
-
- it('validates a timestamp', function (done) {
-
- credentialsFunc('123456', function (err, credentials) {
-
- var tsm = Hawk.crypto.timestampMessage(credentials);
- expect(Browser.client.authenticateTimestamp(tsm, credentials)).to.equal(true);
- done();
- });
- });
-
- it('validates a timestamp without updating local time', function (done) {
-
- credentialsFunc('123456', function (err, credentials) {
-
- var offset = Browser.utils.getNtpOffset();
- var tsm = Hawk.crypto.timestampMessage(credentials, 10000);
- expect(Browser.client.authenticateTimestamp(tsm, credentials, false)).to.equal(true);
- expect(offset).to.equal(Browser.utils.getNtpOffset());
- done();
- });
- });
-
- it('detects a bad timestamp', function (done) {
-
- credentialsFunc('123456', function (err, credentials) {
-
- var tsm = Hawk.crypto.timestampMessage(credentials);
- tsm.ts = 4;
- expect(Browser.client.authenticateTimestamp(tsm, credentials)).to.equal(false);
- done();
- });
- });
- });
- });
-
- describe('internals', function () {
-
- describe('LocalStorage', function () {
-
- it('goes through the full lifecycle', function (done) {
-
- var storage = new Browser.internals.LocalStorage();
- expect(storage.length).to.equal(0);
- expect(storage.getItem('a')).to.equal(null);
- storage.setItem('a', 5);
- expect(storage.length).to.equal(1);
- expect(storage.key()).to.equal('a');
- expect(storage.key(0)).to.equal('a');
- expect(storage.getItem('a')).to.equal('5');
- storage.setItem('b', 'test');
- expect(storage.key()).to.equal('a');
- expect(storage.key(0)).to.equal('a');
- expect(storage.key(1)).to.equal('b');
- expect(storage.length).to.equal(2);
- expect(storage.getItem('b')).to.equal('test');
- storage.removeItem('a');
- expect(storage.length).to.equal(1);
- expect(storage.getItem('a')).to.equal(null);
- expect(storage.getItem('b')).to.equal('test');
- storage.clear();
- expect(storage.length).to.equal(0);
- expect(storage.getItem('a')).to.equal(null);
- expect(storage.getItem('b')).to.equal(null);
- done();
- });
- });
- });
-
- describe('utils', function () {
-
- describe('setStorage()', function () {
-
- it('sets storage for the first time', function (done) {
-
- Browser.utils.storage = new Browser.internals.LocalStorage(); // Reset state
-
- expect(Browser.utils.storage.getItem('hawk_ntp_offset')).to.not.exist();
- Browser.utils.storage.setItem('test', '1');
- Browser.utils.setStorage(new Browser.internals.LocalStorage());
- expect(Browser.utils.storage.getItem('test')).to.not.exist();
- Browser.utils.storage.setItem('test', '2');
- expect(Browser.utils.storage.getItem('test')).to.equal('2');
- done();
- });
- });
-
- describe('setNtpOffset()', function (done) {
-
- it('catches localStorage errors', { parallel: false }, function (done) {
-
- var orig = Browser.utils.storage.setItem;
- var consoleOrig = console.error;
- var count = 0;
- console.error = function () {
-
- if (count++ === 2) {
-
- console.error = consoleOrig;
- }
- };
-
- Browser.utils.storage.setItem = function () {
-
- Browser.utils.storage.setItem = orig;
- throw new Error();
- };
-
- expect(function () {
-
- Browser.utils.setNtpOffset(100);
- }).not.to.throw();
-
- done();
- });
- });
-
- describe('parseAuthorizationHeader()', function (done) {
-
- it('returns null on missing header', function (done) {
-
- expect(Browser.utils.parseAuthorizationHeader()).to.equal(null);
- done();
- });
-
- it('returns null on bad header syntax (structure)', function (done) {
-
- expect(Browser.utils.parseAuthorizationHeader('Hawk')).to.equal(null);
- done();
- });
-
- it('returns null on bad header syntax (parts)', function (done) {
-
- expect(Browser.utils.parseAuthorizationHeader(' ')).to.equal(null);
- done();
- });
-
- it('returns null on bad scheme name', function (done) {
-
- expect(Browser.utils.parseAuthorizationHeader('Basic asdasd')).to.equal(null);
- done();
- });
-
- it('returns null on bad attribute value', function (done) {
-
- expect(Browser.utils.parseAuthorizationHeader('Hawk test="\t"', ['test'])).to.equal(null);
- done();
- });
-
- it('returns null on duplicated attribute', function (done) {
-
- expect(Browser.utils.parseAuthorizationHeader('Hawk test="a", test="b"', ['test'])).to.equal(null);
- done();
- });
- });
-
- describe('parseUri()', function () {
-
- it('returns empty object on invalid', function (done) {
-
- var uri = Browser.utils.parseUri('ftp');
- expect(uri).to.deep.equal({ host: '', port: '', resource: '' });
- done();
- });
-
- it('returns empty port when unknown scheme', function (done) {
-
- var uri = Browser.utils.parseUri('ftp://example.com');
- expect(uri.port).to.equal('');
- done();
- });
-
- it('returns default port when missing', function (done) {
-
- var uri = Browser.utils.parseUri('http://example.com');
- expect(uri.port).to.equal('80');
- done();
- });
-
- it('handles unusual characters correctly', function (done) {
-
- var parts = {
- protocol: 'http+vnd.my-extension',
- user: 'user!$&\'()*+,;=%40my-domain.com',
- password: 'pass!$&\'()*+,;=%40:word',
- hostname: 'foo-bar.com',
- port: '99',
- pathname: '/path/%40/!$&\'()*+,;=:@/',
- query: 'query%40/!$&\'()*+,;=:@/?',
- fragment: 'fragm%40/!$&\'()*+,;=:@/?'
- };
-
- parts.userInfo = parts.user + ':' + parts.password;
- parts.authority = parts.userInfo + '@' + parts.hostname + ':' + parts.port;
- parts.relative = parts.pathname + '?' + parts.query;
- parts.resource = parts.relative + '#' + parts.fragment;
- parts.source = parts.protocol + '://' + parts.authority + parts.resource;
-
- var uri = Browser.utils.parseUri(parts.source);
- expect(uri.host).to.equal('foo-bar.com');
- expect(uri.port).to.equal('99');
- expect(uri.resource).to.equal(parts.pathname + '?' + parts.query);
- done();
- });
- });
-
- var str = 'https://www.google.ca/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=url';
- var base64str = 'aHR0cHM6Ly93d3cuZ29vZ2xlLmNhL3dlYmhwP3NvdXJjZWlkPWNocm9tZS1pbnN0YW50Jmlvbj0xJmVzcHY9MiZpZT1VVEYtOCNxPXVybA';
-
- describe('base64urlEncode()', function () {
-
- it('should base64 URL-safe decode a string', function (done) {
-
- expect(Browser.utils.base64urlEncode(str)).to.equal(base64str);
- done();
- });
- });
- });
-});
+// Load modules
+
+var Url = require('url');
+var Code = require('code');
+var Hawk = require('../lib');
+var Hoek = require('hoek');
+var Lab = require('lab');
+var Browser = require('../lib/browser');
+
+
+// Declare internals
+
+var internals = {};
+
+
+// Test shortcuts
+
+var lab = exports.lab = Lab.script();
+var describe = lab.experiment;
+var it = lab.test;
+var expect = Code.expect;
+
+
+describe('Browser', function () {
+
+ var credentialsFunc = function (id, callback) {
+
+ var credentials = {
+ id: id,
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: (id === '1' ? 'sha1' : 'sha256'),
+ user: 'steve'
+ };
+
+ return callback(null, credentials);
+ };
+
+ it('should generate a bewit then successfully authenticate it', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?a=1&b=2',
+ host: 'example.com',
+ port: 80
+ };
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var bewit = Browser.client.bewit('http://example.com/resource/4?a=1&b=2', { credentials: credentials1, ttlSec: 60 * 60 * 24 * 365 * 100, ext: 'some-app-data' });
+ req.url += '&bewit=' + bewit;
+
+ Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials2, attributes) {
+
+ expect(err).to.not.exist();
+ expect(credentials2.user).to.equal('steve');
+ expect(attributes.ext).to.equal('some-app-data');
+ done();
+ });
+ });
+ });
+
+ it('should generate a bewit then successfully authenticate it (no ext)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?a=1&b=2',
+ host: 'example.com',
+ port: 80
+ };
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var bewit = Browser.client.bewit('http://example.com/resource/4?a=1&b=2', { credentials: credentials1, ttlSec: 60 * 60 * 24 * 365 * 100 });
+ req.url += '&bewit=' + bewit;
+
+ Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials2, attributes) {
+
+ expect(err).to.not.exist();
+ expect(credentials2.user).to.equal('steve');
+ done();
+ });
+ });
+ });
+
+ describe('bewit()', function () {
+
+ it('returns a valid bewit value', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' });
+ expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdca3NjeHdOUjJ0SnBQMVQxekRMTlBiQjVVaUtJVTl0T1NKWFRVZEc3WDloOD1ceGFuZHlhbmR6');
+ done();
+ });
+
+ it('returns a valid bewit value (explicit HTTP port)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Browser.client.bewit('http://example.com:8080/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' });
+ expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdcaFpiSjNQMmNLRW80a3kwQzhqa1pBa1J5Q1p1ZWc0V1NOYnhWN3ZxM3hIVT1ceGFuZHlhbmR6');
+ done();
+ });
+
+ it('returns a valid bewit value (explicit HTTPS port)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Browser.client.bewit('https://example.com:8043/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' });
+ expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdcL2t4UjhwK0xSaTdvQTRnUXc3cWlxa3BiVHRKYkR4OEtRMC9HRUwvVytTUT1ceGFuZHlhbmR6');
+ done();
+ });
+
+ it('returns a valid bewit value (null ext)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: null });
+ expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdcSUdZbUxnSXFMckNlOEN4dktQczRKbFdJQStValdKSm91d2dBUmlWaENBZz1c');
+ done();
+ });
+
+ it('errors on invalid options', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', 4);
+ expect(bewit).to.equal('');
+ done();
+ });
+
+ it('errors on missing uri', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Browser.client.bewit('', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' });
+ expect(bewit).to.equal('');
+ done();
+ });
+
+ it('errors on invalid uri', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Browser.client.bewit(5, { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' });
+ expect(bewit).to.equal('');
+ done();
+ });
+
+ it('errors on invalid credentials (id)', function (done) {
+
+ var credentials = {
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 3000, ext: 'xandyandz' });
+ expect(bewit).to.equal('');
+ done();
+ });
+
+ it('errors on missing credentials', function (done) {
+
+ var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', { ttlSec: 3000, ext: 'xandyandz' });
+ expect(bewit).to.equal('');
+ done();
+ });
+
+ it('errors on invalid credentials (key)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 3000, ext: 'xandyandz' });
+ expect(bewit).to.equal('');
+ done();
+ });
+
+ it('errors on invalid algorithm', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'hmac-sha-0'
+ };
+
+ var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, ext: 'xandyandz' });
+ expect(bewit).to.equal('');
+ done();
+ });
+
+ it('errors on missing options', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'hmac-sha-0'
+ };
+
+ var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow');
+ expect(bewit).to.equal('');
+ done();
+ });
+ });
+
+ it('generates a header then successfully parse it (configuration)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080
+ };
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data' }).field;
+ expect(req.authorization).to.exist();
+
+ Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
+
+ expect(err).to.not.exist();
+ expect(credentials2.user).to.equal('steve');
+ expect(artifacts.ext).to.equal('some-app-data');
+ done();
+ });
+ });
+ });
+
+ it('generates a header then successfully parse it (node request)', function (done) {
+
+ var req = {
+ method: 'POST',
+ url: '/resource/4?filter=a',
+ headers: {
+ host: 'example.com:8080',
+ 'content-type': 'text/plain;x=y'
+ }
+ };
+
+ var payload = 'some not so random text';
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var reqHeader = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] });
+ req.headers.authorization = reqHeader.field;
+
+ Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
+
+ expect(err).to.not.exist();
+ expect(credentials2.user).to.equal('steve');
+ expect(artifacts.ext).to.equal('some-app-data');
+ expect(Hawk.server.authenticatePayload(payload, credentials2, artifacts, req.headers['content-type'])).to.equal(true);
+
+ var res = {
+ headers: {
+ 'content-type': 'text/plain'
+ },
+ getResponseHeader: function (header) {
+
+ return res.headers[header.toLowerCase()];
+ }
+ };
+
+ res.headers['server-authorization'] = Hawk.server.header(credentials2, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' });
+ expect(res.headers['server-authorization']).to.exist();
+
+ expect(Browser.client.authenticate(res, credentials2, artifacts, { payload: 'some reply' })).to.equal(true);
+ done();
+ });
+ });
+ });
+
+ it('generates a header then successfully parse it (browserify)', function (done) {
+
+ var req = {
+ method: 'POST',
+ url: '/resource/4?filter=a',
+ headers: {
+ host: 'example.com:8080',
+ 'content-type': 'text/plain;x=y'
+ }
+ };
+
+ var payload = 'some not so random text';
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var reqHeader = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] });
+ req.headers.authorization = reqHeader.field;
+
+ Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
+
+ expect(err).to.not.exist();
+ expect(credentials2.user).to.equal('steve');
+ expect(artifacts.ext).to.equal('some-app-data');
+ expect(Hawk.server.authenticatePayload(payload, credentials2, artifacts, req.headers['content-type'])).to.equal(true);
+
+ var res = {
+ headers: {
+ 'content-type': 'text/plain'
+ },
+ getHeader: function (header) {
+
+ return res.headers[header.toLowerCase()];
+ }
+ };
+
+ res.headers['server-authorization'] = Hawk.server.header(credentials2, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' });
+ expect(res.headers['server-authorization']).to.exist();
+
+ expect(Browser.client.authenticate(res, credentials2, artifacts, { payload: 'some reply' })).to.equal(true);
+ done();
+ });
+ });
+ });
+
+ it('generates a header then successfully parse it (time offset)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080
+ };
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', localtimeOffsetMsec: 100000 }).field;
+ expect(req.authorization).to.exist();
+
+ Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 100000 }, function (err, credentials2, artifacts) {
+
+ expect(err).to.not.exist();
+ expect(credentials2.user).to.equal('steve');
+ expect(artifacts.ext).to.equal('some-app-data');
+ done();
+ });
+ });
+ });
+
+ it('generates a header then successfully parse it (no server header options)', function (done) {
+
+ var req = {
+ method: 'POST',
+ url: '/resource/4?filter=a',
+ headers: {
+ host: 'example.com:8080',
+ 'content-type': 'text/plain;x=y'
+ }
+ };
+
+ var payload = 'some not so random text';
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var reqHeader = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] });
+ req.headers.authorization = reqHeader.field;
+
+ Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
+
+ expect(err).to.not.exist();
+ expect(credentials2.user).to.equal('steve');
+ expect(artifacts.ext).to.equal('some-app-data');
+ expect(Hawk.server.authenticatePayload(payload, credentials2, artifacts, req.headers['content-type'])).to.equal(true);
+
+ var res = {
+ headers: {
+ 'content-type': 'text/plain'
+ },
+ getResponseHeader: function (header) {
+
+ return res.headers[header.toLowerCase()];
+ }
+ };
+
+ res.headers['server-authorization'] = Hawk.server.header(credentials2, artifacts);
+ expect(res.headers['server-authorization']).to.exist();
+
+ expect(Browser.client.authenticate(res, credentials2, artifacts)).to.equal(true);
+ done();
+ });
+ });
+ });
+
+ it('generates a header then successfully parse it (no server header)', function (done) {
+
+ var req = {
+ method: 'POST',
+ url: '/resource/4?filter=a',
+ headers: {
+ host: 'example.com:8080',
+ 'content-type': 'text/plain;x=y'
+ }
+ };
+
+ var payload = 'some not so random text';
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var reqHeader = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] });
+ req.headers.authorization = reqHeader.field;
+
+ Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
+
+ expect(err).to.not.exist();
+ expect(credentials2.user).to.equal('steve');
+ expect(artifacts.ext).to.equal('some-app-data');
+ expect(Hawk.server.authenticatePayload(payload, credentials2, artifacts, req.headers['content-type'])).to.equal(true);
+
+ var res = {
+ headers: {
+ 'content-type': 'text/plain'
+ },
+ getResponseHeader: function (header) {
+
+ return res.headers[header.toLowerCase()];
+ }
+ };
+
+ expect(Browser.client.authenticate(res, credentials2, artifacts)).to.equal(true);
+ done();
+ });
+ });
+ });
+
+ it('generates a header with stale ts and successfully authenticate on second call', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080
+ };
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ Browser.utils.setNtpOffset(60 * 60 * 1000);
+ var header = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data' });
+ req.authorization = header.field;
+ expect(req.authorization).to.exist();
+
+ Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts2) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Stale timestamp');
+
+ var res = {
+ headers: {
+ 'www-authenticate': err.output.headers['WWW-Authenticate']
+ },
+ getResponseHeader: function (lookup) {
+
+ return res.headers[lookup.toLowerCase()];
+ }
+ };
+
+ expect(Browser.utils.getNtpOffset()).to.equal(60 * 60 * 1000);
+ expect(Browser.client.authenticate(res, credentials2, header.artifacts)).to.equal(true);
+ expect(Browser.utils.getNtpOffset()).to.equal(0);
+
+ req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials2, ext: 'some-app-data' }).field;
+ expect(req.authorization).to.exist();
+
+ Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials3, artifacts3) {
+
+ expect(err).to.not.exist();
+ expect(credentials3.user).to.equal('steve');
+ expect(artifacts3.ext).to.equal('some-app-data');
+ done();
+ });
+ });
+ });
+ });
+
+ it('generates a header with stale ts and successfully authenticate on second call (manual localStorage)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080
+ };
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var localStorage = new Browser.internals.LocalStorage();
+
+ Browser.utils.setStorage(localStorage);
+
+ Browser.utils.setNtpOffset(60 * 60 * 1000);
+ var header = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data' });
+ req.authorization = header.field;
+ expect(req.authorization).to.exist();
+
+ Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts2) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Stale timestamp');
+
+ var res = {
+ headers: {
+ 'www-authenticate': err.output.headers['WWW-Authenticate']
+ },
+ getResponseHeader: function (lookup) {
+
+ return res.headers[lookup.toLowerCase()];
+ }
+ };
+
+ expect(parseInt(localStorage.getItem('hawk_ntp_offset'))).to.equal(60 * 60 * 1000);
+ expect(Browser.utils.getNtpOffset()).to.equal(60 * 60 * 1000);
+ expect(Browser.client.authenticate(res, credentials2, header.artifacts)).to.equal(true);
+ expect(Browser.utils.getNtpOffset()).to.equal(0);
+ expect(parseInt(localStorage.getItem('hawk_ntp_offset'))).to.equal(0);
+
+ req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials2, ext: 'some-app-data' }).field;
+ expect(req.authorization).to.exist();
+
+ Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials3, artifacts3) {
+
+ expect(err).to.not.exist();
+ expect(credentials3.user).to.equal('steve');
+ expect(artifacts3.ext).to.equal('some-app-data');
+ done();
+ });
+ });
+ });
+ });
+
+ it('generates a header then fails to parse it (missing server header hash)', function (done) {
+
+ var req = {
+ method: 'POST',
+ url: '/resource/4?filter=a',
+ headers: {
+ host: 'example.com:8080',
+ 'content-type': 'text/plain;x=y'
+ }
+ };
+
+ var payload = 'some not so random text';
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var reqHeader = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] });
+ req.headers.authorization = reqHeader.field;
+
+ Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
+
+ expect(err).to.not.exist();
+ expect(credentials2.user).to.equal('steve');
+ expect(artifacts.ext).to.equal('some-app-data');
+ expect(Hawk.server.authenticatePayload(payload, credentials2, artifacts, req.headers['content-type'])).to.equal(true);
+
+ var res = {
+ headers: {
+ 'content-type': 'text/plain'
+ },
+ getResponseHeader: function (header) {
+
+ return res.headers[header.toLowerCase()];
+ }
+ };
+
+ res.headers['server-authorization'] = Hawk.server.header(credentials2, artifacts);
+ expect(res.headers['server-authorization']).to.exist();
+
+ expect(Browser.client.authenticate(res, credentials2, artifacts, { payload: 'some reply' })).to.equal(false);
+ done();
+ });
+ });
+ });
+
+ it('generates a header then successfully parse it (with hash)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080
+ };
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, payload: 'hola!', ext: 'some-app-data' }).field;
+ Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
+
+ expect(err).to.not.exist();
+ expect(credentials2.user).to.equal('steve');
+ expect(artifacts.ext).to.equal('some-app-data');
+ done();
+ });
+ });
+ });
+
+ it('generates a header then successfully parse it then validate payload', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080
+ };
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, payload: 'hola!', ext: 'some-app-data' }).field;
+ Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
+
+ expect(err).to.not.exist();
+ expect(credentials2.user).to.equal('steve');
+ expect(artifacts.ext).to.equal('some-app-data');
+ expect(Hawk.server.authenticatePayload('hola!', credentials2, artifacts)).to.be.true();
+ expect(Hawk.server.authenticatePayload('hello!', credentials2, artifacts)).to.be.false();
+ done();
+ });
+ });
+ });
+
+ it('generates a header then successfully parse it (app)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080
+ };
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', app: 'asd23ased' }).field;
+ Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
+
+ expect(err).to.not.exist();
+ expect(credentials2.user).to.equal('steve');
+ expect(artifacts.ext).to.equal('some-app-data');
+ expect(artifacts.app).to.equal('asd23ased');
+ done();
+ });
+ });
+ });
+
+ it('generates a header then successfully parse it (app, dlg)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080
+ };
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', app: 'asd23ased', dlg: '23434szr3q4d' }).field;
+ Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
+
+ expect(err).to.not.exist();
+ expect(credentials2.user).to.equal('steve');
+ expect(artifacts.ext).to.equal('some-app-data');
+ expect(artifacts.app).to.equal('asd23ased');
+ expect(artifacts.dlg).to.equal('23434szr3q4d');
+ done();
+ });
+ });
+ });
+
+ it('generates a header then fail authentication due to bad hash', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080
+ };
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, payload: 'hola!', ext: 'some-app-data' }).field;
+ Hawk.server.authenticate(req, credentialsFunc, { payload: 'byebye!' }, function (err, credentials2, artifacts) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Bad payload hash');
+ done();
+ });
+ });
+ });
+
+ it('generates a header for one resource then fail to authenticate another', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080
+ };
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data' }).field;
+ req.url = '/something/else';
+
+ Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
+
+ expect(err).to.exist();
+ expect(credentials2).to.exist();
+ done();
+ });
+ });
+ });
+
+ describe('client', function () {
+
+ describe('header()', function () {
+
+ it('returns a valid authorization header (sha1)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha1'
+ };
+
+ var header = Browser.client.header('http://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about' }).field;
+ expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="bsvY3IfUllw6V5rvk4tStEvpBhE=", ext="Bazinga!", mac="qbf1ZPG/r/e06F4ht+T77LXi5vw="');
+ done();
+ });
+
+ it('returns a valid authorization header (sha256)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' }).field;
+ expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", ext="Bazinga!", mac="q1CwFoSHzPZSkbIvl0oYlD+91rBUEvFk763nMjMndj8="');
+ done();
+ });
+
+ it('returns a valid authorization header (empty payload)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha1'
+ };
+
+ var header = Browser.client.header('http://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207, nonce: 'Ygvqdz', payload: '' }).field;
+ expect(header).to.equal('Hawk id=\"123456\", ts=\"1353809207\", nonce=\"Ygvqdz\", hash=\"404ghL7K+hfyhByKKejFBRGgTjU=\", ext=\"Bazinga!\", mac=\"Bh1sj1DOfFRWOdi3ww52nLCJdBE=\"');
+ done();
+ });
+
+ it('returns a valid authorization header (no ext)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' }).field;
+ expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", mac="HTgtd0jPI6E4izx8e4OHdO36q00xFCU0FolNq3RiCYs="');
+ done();
+ });
+
+ it('returns a valid authorization header (null ext)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain', ext: null }).field;
+ expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", mac="HTgtd0jPI6E4izx8e4OHdO36q00xFCU0FolNq3RiCYs="');
+ done();
+ });
+
+ it('returns a valid authorization header (uri object)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var uri = Browser.utils.parseUri('https://example.net/somewhere/over/the/rainbow');
+ var header = Browser.client.header(uri, 'POST', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' }).field;
+ expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", mac="HTgtd0jPI6E4izx8e4OHdO36q00xFCU0FolNq3RiCYs="');
+ done();
+ });
+
+ it('errors on missing options', function (done) {
+
+ var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST');
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid argument type');
+ done();
+ });
+
+ it('errors on empty uri', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var header = Browser.client.header('', 'POST', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' });
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid argument type');
+ done();
+ });
+
+ it('errors on invalid uri', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var header = Browser.client.header(4, 'POST', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' });
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid argument type');
+ done();
+ });
+
+ it('errors on missing method', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', '', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' });
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid argument type');
+ done();
+ });
+
+ it('errors on invalid method', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 5, { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' });
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid argument type');
+ done();
+ });
+
+ it('errors on missing credentials', function (done) {
+
+ var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { ext: 'Bazinga!', timestamp: 1353809207 });
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid credentials object');
+ done();
+ });
+
+ it('errors on invalid credentials (id)', function (done) {
+
+ var credentials = {
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207 });
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid credentials object');
+ done();
+ });
+
+ it('errors on invalid credentials (key)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ algorithm: 'sha256'
+ };
+
+ var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207 });
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid credentials object');
+ done();
+ });
+
+ it('errors on invalid algorithm', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'hmac-sha-0'
+ };
+
+ var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, payload: 'something, anything!', ext: 'Bazinga!', timestamp: 1353809207 });
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Unknown algorithm');
+ done();
+ });
+
+ it('uses a pre-calculated payload hash', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var options = { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' };
+ options.hash = Browser.crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType);
+ var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', options).field;
+ expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", ext="Bazinga!", mac="q1CwFoSHzPZSkbIvl0oYlD+91rBUEvFk763nMjMndj8="');
+ done();
+ });
+ });
+
+ describe('authenticate()', function () {
+
+ it('skips tsm validation when missing ts', function (done) {
+
+ var res = {
+ headers: {
+ 'www-authenticate': 'Hawk error="Stale timestamp"'
+ },
+ getResponseHeader: function (header) {
+
+ return res.headers[header.toLowerCase()];
+ }
+ };
+
+ var credentials = {
+ id: '123456',
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: 'sha256',
+ user: 'steve'
+ };
+
+ var artifacts = {
+ ts: 1402135580,
+ nonce: 'iBRB6t',
+ method: 'GET',
+ resource: '/resource/4?filter=a',
+ host: 'example.com',
+ port: '8080',
+ ext: 'some-app-data'
+ };
+
+ expect(Browser.client.authenticate(res, credentials, artifacts)).to.equal(true);
+ done();
+ });
+
+ it('returns false on invalid header', function (done) {
+
+ var res = {
+ headers: {
+ 'server-authorization': 'Hawk mac="abc", bad="xyz"'
+ },
+ getResponseHeader: function (header) {
+
+ return res.headers[header.toLowerCase()];
+ }
+ };
+
+ expect(Browser.client.authenticate(res, {})).to.equal(false);
+ done();
+ });
+
+ it('returns false on invalid mac', function (done) {
+
+ var res = {
+ headers: {
+ 'content-type': 'text/plain',
+ 'server-authorization': 'Hawk mac="_IJRsMl/4oL+nn+vKoeVZPdCHXB4yJkNnBbTbHFZUYE=", hash="f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=", ext="response-specific"'
+ },
+ getResponseHeader: function (header) {
+
+ return res.headers[header.toLowerCase()];
+ }
+ };
+
+ var artifacts = {
+ method: 'POST',
+ host: 'example.com',
+ port: '8080',
+ resource: '/resource/4?filter=a',
+ ts: '1362336900',
+ nonce: 'eb5S_L',
+ hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
+ ext: 'some-app-data',
+ app: undefined,
+ dlg: undefined,
+ mac: 'BlmSe8K+pbKIb6YsZCnt4E1GrYvY1AaYayNR82dGpIk=',
+ id: '123456'
+ };
+
+ var credentials = {
+ id: '123456',
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: 'sha256',
+ user: 'steve'
+ };
+
+ expect(Browser.client.authenticate(res, credentials, artifacts)).to.equal(false);
+ done();
+ });
+
+ it('returns true on ignoring hash', function (done) {
+
+ var res = {
+ headers: {
+ 'content-type': 'text/plain',
+ 'server-authorization': 'Hawk mac="XIJRsMl/4oL+nn+vKoeVZPdCHXB4yJkNnBbTbHFZUYE=", hash="f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=", ext="response-specific"'
+ },
+ getResponseHeader: function (header) {
+
+ return res.headers[header.toLowerCase()];
+ }
+ };
+
+ var artifacts = {
+ method: 'POST',
+ host: 'example.com',
+ port: '8080',
+ resource: '/resource/4?filter=a',
+ ts: '1362336900',
+ nonce: 'eb5S_L',
+ hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
+ ext: 'some-app-data',
+ app: undefined,
+ dlg: undefined,
+ mac: 'BlmSe8K+pbKIb6YsZCnt4E1GrYvY1AaYayNR82dGpIk=',
+ id: '123456'
+ };
+
+ var credentials = {
+ id: '123456',
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: 'sha256',
+ user: 'steve'
+ };
+
+ expect(Browser.client.authenticate(res, credentials, artifacts)).to.equal(true);
+ done();
+ });
+
+ it('errors on invalid WWW-Authenticate header format', function (done) {
+
+ var res = {
+ headers: {
+ 'www-authenticate': 'Hawk ts="1362346425875", tsm="PhwayS28vtnn3qbv0mqRBYSXebN/zggEtucfeZ620Zo=", x="Stale timestamp"'
+ },
+ getResponseHeader: function (header) {
+
+ return res.headers[header.toLowerCase()];
+ }
+ };
+
+ expect(Browser.client.authenticate(res, {})).to.equal(false);
+ done();
+ });
+
+ it('errors on invalid WWW-Authenticate header format', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: 'sha256',
+ user: 'steve'
+ };
+
+ var res = {
+ headers: {
+ 'www-authenticate': 'Hawk ts="1362346425875", tsm="hwayS28vtnn3qbv0mqRBYSXebN/zggEtucfeZ620Zo=", error="Stale timestamp"'
+ },
+ getResponseHeader: function (header) {
+
+ return res.headers[header.toLowerCase()];
+ }
+ };
+
+ expect(Browser.client.authenticate(res, credentials)).to.equal(false);
+ done();
+ });
+ });
+
+ describe('message()', function () {
+
+ it('generates an authorization then successfully parse it', function (done) {
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var auth = Browser.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
+ expect(auth).to.exist();
+
+ Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials2) {
+
+ expect(err).to.not.exist();
+ expect(credentials2.user).to.equal('steve');
+ done();
+ });
+ });
+ });
+
+ it('generates an authorization using custom nonce/timestamp', function (done) {
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var auth = Browser.client.message('example.com', 8080, 'some message', { credentials: credentials, nonce: 'abc123', timestamp: 1398536270957 });
+ expect(auth).to.exist();
+ expect(auth.nonce).to.equal('abc123');
+ expect(auth.ts).to.equal(1398536270957);
+ done();
+ });
+ });
+
+ it('errors on missing host', function (done) {
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var auth = Browser.client.message(null, 8080, 'some message', { credentials: credentials });
+ expect(auth).to.not.exist();
+ done();
+ });
+ });
+
+ it('errors on invalid host', function (done) {
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var auth = Browser.client.message(5, 8080, 'some message', { credentials: credentials });
+ expect(auth).to.not.exist();
+ done();
+ });
+ });
+
+ it('errors on missing port', function (done) {
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var auth = Browser.client.message('example.com', 0, 'some message', { credentials: credentials });
+ expect(auth).to.not.exist();
+ done();
+ });
+ });
+
+ it('errors on invalid port', function (done) {
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var auth = Browser.client.message('example.com', 'a', 'some message', { credentials: credentials });
+ expect(auth).to.not.exist();
+ done();
+ });
+ });
+
+ it('errors on missing message', function (done) {
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var auth = Browser.client.message('example.com', 8080, undefined, { credentials: credentials });
+ expect(auth).to.not.exist();
+ done();
+ });
+ });
+
+ it('errors on null message', function (done) {
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var auth = Browser.client.message('example.com', 8080, null, { credentials: credentials });
+ expect(auth).to.not.exist();
+ done();
+ });
+ });
+
+ it('errors on invalid message', function (done) {
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var auth = Browser.client.message('example.com', 8080, 5, { credentials: credentials });
+ expect(auth).to.not.exist();
+ done();
+ });
+ });
+
+ it('errors on missing credentials', function (done) {
+
+ var auth = Browser.client.message('example.com', 8080, 'some message', {});
+ expect(auth).to.not.exist();
+ done();
+ });
+
+ it('errors on missing options', function (done) {
+
+ var auth = Browser.client.message('example.com', 8080, 'some message');
+ expect(auth).to.not.exist();
+ done();
+ });
+
+ it('errors on invalid credentials (id)', function (done) {
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var creds = Hoek.clone(credentials);
+ delete creds.id;
+ var auth = Browser.client.message('example.com', 8080, 'some message', { credentials: creds });
+ expect(auth).to.not.exist();
+ done();
+ });
+ });
+
+ it('errors on invalid credentials (key)', function (done) {
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var creds = Hoek.clone(credentials);
+ delete creds.key;
+ var auth = Browser.client.message('example.com', 8080, 'some message', { credentials: creds });
+ expect(auth).to.not.exist();
+ done();
+ });
+ });
+
+ it('errors on invalid algorithm', function (done) {
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var creds = Hoek.clone(credentials);
+ creds.algorithm = 'blah';
+ var auth = Browser.client.message('example.com', 8080, 'some message', { credentials: creds });
+ expect(auth).to.not.exist();
+ done();
+ });
+ });
+ });
+
+ describe('authenticateTimestamp()', function (done) {
+
+ it('validates a timestamp', function (done) {
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var tsm = Hawk.crypto.timestampMessage(credentials);
+ expect(Browser.client.authenticateTimestamp(tsm, credentials)).to.equal(true);
+ done();
+ });
+ });
+
+ it('validates a timestamp without updating local time', function (done) {
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var offset = Browser.utils.getNtpOffset();
+ var tsm = Hawk.crypto.timestampMessage(credentials, 10000);
+ expect(Browser.client.authenticateTimestamp(tsm, credentials, false)).to.equal(true);
+ expect(offset).to.equal(Browser.utils.getNtpOffset());
+ done();
+ });
+ });
+
+ it('detects a bad timestamp', function (done) {
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var tsm = Hawk.crypto.timestampMessage(credentials);
+ tsm.ts = 4;
+ expect(Browser.client.authenticateTimestamp(tsm, credentials)).to.equal(false);
+ done();
+ });
+ });
+ });
+ });
+
+ describe('internals', function () {
+
+ describe('LocalStorage', function () {
+
+ it('goes through the full lifecycle', function (done) {
+
+ var storage = new Browser.internals.LocalStorage();
+ expect(storage.length).to.equal(0);
+ expect(storage.getItem('a')).to.equal(null);
+ storage.setItem('a', 5);
+ expect(storage.length).to.equal(1);
+ expect(storage.key()).to.equal('a');
+ expect(storage.key(0)).to.equal('a');
+ expect(storage.getItem('a')).to.equal('5');
+ storage.setItem('b', 'test');
+ expect(storage.key()).to.equal('a');
+ expect(storage.key(0)).to.equal('a');
+ expect(storage.key(1)).to.equal('b');
+ expect(storage.length).to.equal(2);
+ expect(storage.getItem('b')).to.equal('test');
+ storage.removeItem('a');
+ expect(storage.length).to.equal(1);
+ expect(storage.getItem('a')).to.equal(null);
+ expect(storage.getItem('b')).to.equal('test');
+ storage.clear();
+ expect(storage.length).to.equal(0);
+ expect(storage.getItem('a')).to.equal(null);
+ expect(storage.getItem('b')).to.equal(null);
+ done();
+ });
+ });
+ });
+
+ describe('utils', function () {
+
+ describe('setStorage()', function () {
+
+ it('sets storage for the first time', function (done) {
+
+ Browser.utils.storage = new Browser.internals.LocalStorage(); // Reset state
+
+ expect(Browser.utils.storage.getItem('hawk_ntp_offset')).to.not.exist();
+ Browser.utils.storage.setItem('test', '1');
+ Browser.utils.setStorage(new Browser.internals.LocalStorage());
+ expect(Browser.utils.storage.getItem('test')).to.not.exist();
+ Browser.utils.storage.setItem('test', '2');
+ expect(Browser.utils.storage.getItem('test')).to.equal('2');
+ done();
+ });
+ });
+
+ describe('setNtpOffset()', function (done) {
+
+ it('catches localStorage errors', { parallel: false }, function (done) {
+
+ var orig = Browser.utils.storage.setItem;
+ var consoleOrig = console.error;
+ var count = 0;
+ console.error = function () {
+
+ if (count++ === 2) {
+
+ console.error = consoleOrig;
+ }
+ };
+
+ Browser.utils.storage.setItem = function () {
+
+ Browser.utils.storage.setItem = orig;
+ throw new Error();
+ };
+
+ expect(function () {
+
+ Browser.utils.setNtpOffset(100);
+ }).not.to.throw();
+
+ done();
+ });
+ });
+
+ describe('parseAuthorizationHeader()', function (done) {
+
+ it('returns null on missing header', function (done) {
+
+ expect(Browser.utils.parseAuthorizationHeader()).to.equal(null);
+ done();
+ });
+
+ it('returns null on bad header syntax (structure)', function (done) {
+
+ expect(Browser.utils.parseAuthorizationHeader('Hawk')).to.equal(null);
+ done();
+ });
+
+ it('returns null on bad header syntax (parts)', function (done) {
+
+ expect(Browser.utils.parseAuthorizationHeader(' ')).to.equal(null);
+ done();
+ });
+
+ it('returns null on bad scheme name', function (done) {
+
+ expect(Browser.utils.parseAuthorizationHeader('Basic asdasd')).to.equal(null);
+ done();
+ });
+
+ it('returns null on bad attribute value', function (done) {
+
+ expect(Browser.utils.parseAuthorizationHeader('Hawk test="\t"', ['test'])).to.equal(null);
+ done();
+ });
+
+ it('returns null on duplicated attribute', function (done) {
+
+ expect(Browser.utils.parseAuthorizationHeader('Hawk test="a", test="b"', ['test'])).to.equal(null);
+ done();
+ });
+ });
+
+ describe('parseUri()', function () {
+
+ it('returns empty object on invalid', function (done) {
+
+ var uri = Browser.utils.parseUri('ftp');
+ expect(uri).to.deep.equal({ host: '', port: '', resource: '' });
+ done();
+ });
+
+ it('returns empty port when unknown scheme', function (done) {
+
+ var uri = Browser.utils.parseUri('ftp://example.com');
+ expect(uri.port).to.equal('');
+ done();
+ });
+
+ it('returns default port when missing', function (done) {
+
+ var uri = Browser.utils.parseUri('http://example.com');
+ expect(uri.port).to.equal('80');
+ done();
+ });
+
+ it('handles unusual characters correctly', function (done) {
+
+ var parts = {
+ protocol: 'http+vnd.my-extension',
+ user: 'user!$&\'()*+,;=%40my-domain.com',
+ password: 'pass!$&\'()*+,;=%40:word',
+ hostname: 'foo-bar.com',
+ port: '99',
+ pathname: '/path/%40/!$&\'()*+,;=:@/',
+ query: 'query%40/!$&\'()*+,;=:@/?',
+ fragment: 'fragm%40/!$&\'()*+,;=:@/?'
+ };
+
+ parts.userInfo = parts.user + ':' + parts.password;
+ parts.authority = parts.userInfo + '@' + parts.hostname + ':' + parts.port;
+ parts.relative = parts.pathname + '?' + parts.query;
+ parts.resource = parts.relative + '#' + parts.fragment;
+ parts.source = parts.protocol + '://' + parts.authority + parts.resource;
+
+ var uri = Browser.utils.parseUri(parts.source);
+ expect(uri.host).to.equal('foo-bar.com');
+ expect(uri.port).to.equal('99');
+ expect(uri.resource).to.equal(parts.pathname + '?' + parts.query);
+ done();
+ });
+ });
+
+ var str = 'https://www.google.ca/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=url';
+ var base64str = 'aHR0cHM6Ly93d3cuZ29vZ2xlLmNhL3dlYmhwP3NvdXJjZWlkPWNocm9tZS1pbnN0YW50Jmlvbj0xJmVzcHY9MiZpZT1VVEYtOCNxPXVybA';
+
+ describe('base64urlEncode()', function () {
+
+ it('should base64 URL-safe decode a string', function (done) {
+
+ expect(Browser.utils.base64urlEncode(str)).to.equal(base64str);
+ done();
+ });
+ });
+ });
+});
diff --git a/node_modules/request/node_modules/hawk/test/client.js b/node_modules/request/node_modules/hawk/test/client.js
index d6be231ae..d5ed1c609 100755
--- a/node_modules/request/node_modules/hawk/test/client.js
+++ b/node_modules/request/node_modules/hawk/test/client.js
@@ -1,440 +1,440 @@
-// Load modules
-
-var Url = require('url');
-var Code = require('code');
-var Hawk = require('../lib');
-var Lab = require('lab');
-
-
-// Declare internals
-
-var internals = {};
-
-
-// Test shortcuts
-
-var lab = exports.lab = Lab.script();
-var describe = lab.experiment;
-var it = lab.test;
-var expect = Code.expect;
-
-
-describe('Client', function () {
-
- describe('header()', function () {
-
- it('returns a valid authorization header (sha1)', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha1'
- };
-
- var header = Hawk.client.header('http://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about' }).field;
- expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="bsvY3IfUllw6V5rvk4tStEvpBhE=", ext="Bazinga!", mac="qbf1ZPG/r/e06F4ht+T77LXi5vw="');
- done();
- });
-
- it('returns a valid authorization header (sha256)', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' }).field;
- expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", ext="Bazinga!", mac="q1CwFoSHzPZSkbIvl0oYlD+91rBUEvFk763nMjMndj8="');
- done();
- });
-
- it('returns a valid authorization header (no ext)', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' }).field;
- expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", mac="HTgtd0jPI6E4izx8e4OHdO36q00xFCU0FolNq3RiCYs="');
- done();
- });
-
- it('returns a valid authorization header (null ext)', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain', ext: null }).field;
- expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", mac="HTgtd0jPI6E4izx8e4OHdO36q00xFCU0FolNq3RiCYs="');
- done();
- });
-
- it('returns a valid authorization header (empty payload)', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: '', contentType: 'text/plain' }).field;
- expect(header).to.equal('Hawk id=\"123456\", ts=\"1353809207\", nonce=\"Ygvqdz\", hash=\"q/t+NNAkQZNlq/aAD6PlexImwQTxwgT2MahfTa9XRLA=\", mac=\"U5k16YEzn3UnBHKeBzsDXn067Gu3R4YaY6xOt9PYRZM=\"');
- done();
- });
-
- it('returns a valid authorization header (pre hashed payload)', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var options = { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' };
- options.hash = Hawk.crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType);
- var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', options).field;
- expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", mac="HTgtd0jPI6E4izx8e4OHdO36q00xFCU0FolNq3RiCYs="');
- done();
- });
-
- it('errors on missing uri', function (done) {
-
- var header = Hawk.client.header('', 'POST');
- expect(header.field).to.equal('');
- expect(header.err).to.equal('Invalid argument type');
- done();
- });
-
- it('errors on invalid uri', function (done) {
-
- var header = Hawk.client.header(4, 'POST');
- expect(header.field).to.equal('');
- expect(header.err).to.equal('Invalid argument type');
- done();
- });
-
- it('errors on missing method', function (done) {
-
- var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', '');
- expect(header.field).to.equal('');
- expect(header.err).to.equal('Invalid argument type');
- done();
- });
-
- it('errors on invalid method', function (done) {
-
- var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 5);
- expect(header.field).to.equal('');
- expect(header.err).to.equal('Invalid argument type');
- done();
- });
-
- it('errors on missing options', function (done) {
-
- var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST');
- expect(header.field).to.equal('');
- expect(header.err).to.equal('Invalid argument type');
- done();
- });
-
- it('errors on invalid credentials (id)', function (done) {
-
- var credentials = {
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207 });
- expect(header.field).to.equal('');
- expect(header.err).to.equal('Invalid credential object');
- done();
- });
-
- it('errors on missing credentials', function (done) {
-
- var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { ext: 'Bazinga!', timestamp: 1353809207 });
- expect(header.field).to.equal('');
- expect(header.err).to.equal('Invalid credential object');
- done();
- });
-
- it('errors on invalid credentials', function (done) {
-
- var credentials = {
- id: '123456',
- algorithm: 'sha256'
- };
-
- var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207 });
- expect(header.field).to.equal('');
- expect(header.err).to.equal('Invalid credential object');
- done();
- });
-
- it('errors on invalid algorithm', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'hmac-sha-0'
- };
-
- var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, payload: 'something, anything!', ext: 'Bazinga!', timestamp: 1353809207 });
- expect(header.field).to.equal('');
- expect(header.err).to.equal('Unknown algorithm');
- done();
- });
- });
-
- describe('authenticate()', function () {
-
- it('returns false on invalid header', function (done) {
-
- var res = {
- headers: {
- 'server-authorization': 'Hawk mac="abc", bad="xyz"'
- }
- };
-
- expect(Hawk.client.authenticate(res, {})).to.equal(false);
- done();
- });
-
- it('returns false on invalid mac', function (done) {
-
- var res = {
- headers: {
- 'content-type': 'text/plain',
- 'server-authorization': 'Hawk mac="_IJRsMl/4oL+nn+vKoeVZPdCHXB4yJkNnBbTbHFZUYE=", hash="f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=", ext="response-specific"'
- }
- };
-
- var artifacts = {
- method: 'POST',
- host: 'example.com',
- port: '8080',
- resource: '/resource/4?filter=a',
- ts: '1362336900',
- nonce: 'eb5S_L',
- hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
- ext: 'some-app-data',
- app: undefined,
- dlg: undefined,
- mac: 'BlmSe8K+pbKIb6YsZCnt4E1GrYvY1AaYayNR82dGpIk=',
- id: '123456'
- };
-
- var credentials = {
- id: '123456',
- key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
- algorithm: 'sha256',
- user: 'steve'
- };
-
- expect(Hawk.client.authenticate(res, credentials, artifacts)).to.equal(false);
- done();
- });
-
- it('returns true on ignoring hash', function (done) {
-
- var res = {
- headers: {
- 'content-type': 'text/plain',
- 'server-authorization': 'Hawk mac="XIJRsMl/4oL+nn+vKoeVZPdCHXB4yJkNnBbTbHFZUYE=", hash="f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=", ext="response-specific"'
- }
- };
-
- var artifacts = {
- method: 'POST',
- host: 'example.com',
- port: '8080',
- resource: '/resource/4?filter=a',
- ts: '1362336900',
- nonce: 'eb5S_L',
- hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
- ext: 'some-app-data',
- app: undefined,
- dlg: undefined,
- mac: 'BlmSe8K+pbKIb6YsZCnt4E1GrYvY1AaYayNR82dGpIk=',
- id: '123456'
- };
-
- var credentials = {
- id: '123456',
- key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
- algorithm: 'sha256',
- user: 'steve'
- };
-
- expect(Hawk.client.authenticate(res, credentials, artifacts)).to.equal(true);
- done();
- });
-
- it('fails on invalid WWW-Authenticate header format', function (done) {
-
- var header = 'Hawk ts="1362346425875", tsm="PhwayS28vtnn3qbv0mqRBYSXebN/zggEtucfeZ620Zo=", x="Stale timestamp"';
- expect(Hawk.client.authenticate({ headers: { 'www-authenticate': header } }, {})).to.equal(false);
- done();
- });
-
- it('fails on invalid WWW-Authenticate header format', function (done) {
-
- var credentials = {
- id: '123456',
- key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
- algorithm: 'sha256',
- user: 'steve'
- };
-
- var header = 'Hawk ts="1362346425875", tsm="hwayS28vtnn3qbv0mqRBYSXebN/zggEtucfeZ620Zo=", error="Stale timestamp"';
- expect(Hawk.client.authenticate({ headers: { 'www-authenticate': header } }, credentials)).to.equal(false);
- done();
- });
-
- it('skips tsm validation when missing ts', function (done) {
-
- var header = 'Hawk error="Stale timestamp"';
- expect(Hawk.client.authenticate({ headers: { 'www-authenticate': header } }, {})).to.equal(true);
- done();
- });
- });
-
- describe('message()', function () {
-
- it('generates authorization', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha1'
- };
-
- var auth = Hawk.client.message('example.com', 80, 'I am the boodyman', { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' });
- expect(auth).to.exist();
- expect(auth.ts).to.equal(1353809207);
- expect(auth.nonce).to.equal('abc123');
- done();
- });
-
- it('errors on invalid host', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha1'
- };
-
- var auth = Hawk.client.message(5, 80, 'I am the boodyman', { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' });
- expect(auth).to.not.exist();
- done();
- });
-
- it('errors on invalid port', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha1'
- };
-
- var auth = Hawk.client.message('example.com', '80', 'I am the boodyman', { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' });
- expect(auth).to.not.exist();
- done();
- });
-
- it('errors on missing host', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha1'
- };
-
- var auth = Hawk.client.message('example.com', 0, 'I am the boodyman', { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' });
- expect(auth).to.not.exist();
- done();
- });
-
- it('errors on null message', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha1'
- };
-
- var auth = Hawk.client.message('example.com', 80, null, { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' });
- expect(auth).to.not.exist();
- done();
- });
-
- it('errors on missing message', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha1'
- };
-
- var auth = Hawk.client.message('example.com', 80, undefined, { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' });
- expect(auth).to.not.exist();
- done();
- });
-
- it('errors on invalid message', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha1'
- };
-
- var auth = Hawk.client.message('example.com', 80, 5, { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' });
- expect(auth).to.not.exist();
- done();
- });
-
- it('errors on missing options', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha1'
- };
-
- var auth = Hawk.client.message('example.com', 80, 'I am the boodyman');
- expect(auth).to.not.exist();
- done();
- });
-
- it('errors on invalid credentials (id)', function (done) {
-
- var credentials = {
- key: '2983d45yun89q',
- algorithm: 'sha1'
- };
-
- var auth = Hawk.client.message('example.com', 80, 'I am the boodyman', { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' });
- expect(auth).to.not.exist();
- done();
- });
-
- it('errors on invalid credentials (key)', function (done) {
-
- var credentials = {
- id: '123456',
- algorithm: 'sha1'
- };
-
- var auth = Hawk.client.message('example.com', 80, 'I am the boodyman', { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' });
- expect(auth).to.not.exist();
- done();
- });
- });
-});
+// Load modules
+
+var Url = require('url');
+var Code = require('code');
+var Hawk = require('../lib');
+var Lab = require('lab');
+
+
+// Declare internals
+
+var internals = {};
+
+
+// Test shortcuts
+
+var lab = exports.lab = Lab.script();
+var describe = lab.experiment;
+var it = lab.test;
+var expect = Code.expect;
+
+
+describe('Client', function () {
+
+ describe('header()', function () {
+
+ it('returns a valid authorization header (sha1)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha1'
+ };
+
+ var header = Hawk.client.header('http://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about' }).field;
+ expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="bsvY3IfUllw6V5rvk4tStEvpBhE=", ext="Bazinga!", mac="qbf1ZPG/r/e06F4ht+T77LXi5vw="');
+ done();
+ });
+
+ it('returns a valid authorization header (sha256)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' }).field;
+ expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", ext="Bazinga!", mac="q1CwFoSHzPZSkbIvl0oYlD+91rBUEvFk763nMjMndj8="');
+ done();
+ });
+
+ it('returns a valid authorization header (no ext)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' }).field;
+ expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", mac="HTgtd0jPI6E4izx8e4OHdO36q00xFCU0FolNq3RiCYs="');
+ done();
+ });
+
+ it('returns a valid authorization header (null ext)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain', ext: null }).field;
+ expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", mac="HTgtd0jPI6E4izx8e4OHdO36q00xFCU0FolNq3RiCYs="');
+ done();
+ });
+
+ it('returns a valid authorization header (empty payload)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: '', contentType: 'text/plain' }).field;
+ expect(header).to.equal('Hawk id=\"123456\", ts=\"1353809207\", nonce=\"Ygvqdz\", hash=\"q/t+NNAkQZNlq/aAD6PlexImwQTxwgT2MahfTa9XRLA=\", mac=\"U5k16YEzn3UnBHKeBzsDXn067Gu3R4YaY6xOt9PYRZM=\"');
+ done();
+ });
+
+ it('returns a valid authorization header (pre hashed payload)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var options = { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' };
+ options.hash = Hawk.crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType);
+ var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', options).field;
+ expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", mac="HTgtd0jPI6E4izx8e4OHdO36q00xFCU0FolNq3RiCYs="');
+ done();
+ });
+
+ it('errors on missing uri', function (done) {
+
+ var header = Hawk.client.header('', 'POST');
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid argument type');
+ done();
+ });
+
+ it('errors on invalid uri', function (done) {
+
+ var header = Hawk.client.header(4, 'POST');
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid argument type');
+ done();
+ });
+
+ it('errors on missing method', function (done) {
+
+ var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', '');
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid argument type');
+ done();
+ });
+
+ it('errors on invalid method', function (done) {
+
+ var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 5);
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid argument type');
+ done();
+ });
+
+ it('errors on missing options', function (done) {
+
+ var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST');
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid argument type');
+ done();
+ });
+
+ it('errors on invalid credentials (id)', function (done) {
+
+ var credentials = {
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207 });
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid credential object');
+ done();
+ });
+
+ it('errors on missing credentials', function (done) {
+
+ var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { ext: 'Bazinga!', timestamp: 1353809207 });
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid credential object');
+ done();
+ });
+
+ it('errors on invalid credentials', function (done) {
+
+ var credentials = {
+ id: '123456',
+ algorithm: 'sha256'
+ };
+
+ var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207 });
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid credential object');
+ done();
+ });
+
+ it('errors on invalid algorithm', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'hmac-sha-0'
+ };
+
+ var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, payload: 'something, anything!', ext: 'Bazinga!', timestamp: 1353809207 });
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Unknown algorithm');
+ done();
+ });
+ });
+
+ describe('authenticate()', function () {
+
+ it('returns false on invalid header', function (done) {
+
+ var res = {
+ headers: {
+ 'server-authorization': 'Hawk mac="abc", bad="xyz"'
+ }
+ };
+
+ expect(Hawk.client.authenticate(res, {})).to.equal(false);
+ done();
+ });
+
+ it('returns false on invalid mac', function (done) {
+
+ var res = {
+ headers: {
+ 'content-type': 'text/plain',
+ 'server-authorization': 'Hawk mac="_IJRsMl/4oL+nn+vKoeVZPdCHXB4yJkNnBbTbHFZUYE=", hash="f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=", ext="response-specific"'
+ }
+ };
+
+ var artifacts = {
+ method: 'POST',
+ host: 'example.com',
+ port: '8080',
+ resource: '/resource/4?filter=a',
+ ts: '1362336900',
+ nonce: 'eb5S_L',
+ hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
+ ext: 'some-app-data',
+ app: undefined,
+ dlg: undefined,
+ mac: 'BlmSe8K+pbKIb6YsZCnt4E1GrYvY1AaYayNR82dGpIk=',
+ id: '123456'
+ };
+
+ var credentials = {
+ id: '123456',
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: 'sha256',
+ user: 'steve'
+ };
+
+ expect(Hawk.client.authenticate(res, credentials, artifacts)).to.equal(false);
+ done();
+ });
+
+ it('returns true on ignoring hash', function (done) {
+
+ var res = {
+ headers: {
+ 'content-type': 'text/plain',
+ 'server-authorization': 'Hawk mac="XIJRsMl/4oL+nn+vKoeVZPdCHXB4yJkNnBbTbHFZUYE=", hash="f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=", ext="response-specific"'
+ }
+ };
+
+ var artifacts = {
+ method: 'POST',
+ host: 'example.com',
+ port: '8080',
+ resource: '/resource/4?filter=a',
+ ts: '1362336900',
+ nonce: 'eb5S_L',
+ hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
+ ext: 'some-app-data',
+ app: undefined,
+ dlg: undefined,
+ mac: 'BlmSe8K+pbKIb6YsZCnt4E1GrYvY1AaYayNR82dGpIk=',
+ id: '123456'
+ };
+
+ var credentials = {
+ id: '123456',
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: 'sha256',
+ user: 'steve'
+ };
+
+ expect(Hawk.client.authenticate(res, credentials, artifacts)).to.equal(true);
+ done();
+ });
+
+ it('fails on invalid WWW-Authenticate header format', function (done) {
+
+ var header = 'Hawk ts="1362346425875", tsm="PhwayS28vtnn3qbv0mqRBYSXebN/zggEtucfeZ620Zo=", x="Stale timestamp"';
+ expect(Hawk.client.authenticate({ headers: { 'www-authenticate': header } }, {})).to.equal(false);
+ done();
+ });
+
+ it('fails on invalid WWW-Authenticate header format', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: 'sha256',
+ user: 'steve'
+ };
+
+ var header = 'Hawk ts="1362346425875", tsm="hwayS28vtnn3qbv0mqRBYSXebN/zggEtucfeZ620Zo=", error="Stale timestamp"';
+ expect(Hawk.client.authenticate({ headers: { 'www-authenticate': header } }, credentials)).to.equal(false);
+ done();
+ });
+
+ it('skips tsm validation when missing ts', function (done) {
+
+ var header = 'Hawk error="Stale timestamp"';
+ expect(Hawk.client.authenticate({ headers: { 'www-authenticate': header } }, {})).to.equal(true);
+ done();
+ });
+ });
+
+ describe('message()', function () {
+
+ it('generates authorization', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha1'
+ };
+
+ var auth = Hawk.client.message('example.com', 80, 'I am the boodyman', { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' });
+ expect(auth).to.exist();
+ expect(auth.ts).to.equal(1353809207);
+ expect(auth.nonce).to.equal('abc123');
+ done();
+ });
+
+ it('errors on invalid host', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha1'
+ };
+
+ var auth = Hawk.client.message(5, 80, 'I am the boodyman', { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' });
+ expect(auth).to.not.exist();
+ done();
+ });
+
+ it('errors on invalid port', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha1'
+ };
+
+ var auth = Hawk.client.message('example.com', '80', 'I am the boodyman', { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' });
+ expect(auth).to.not.exist();
+ done();
+ });
+
+ it('errors on missing host', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha1'
+ };
+
+ var auth = Hawk.client.message('example.com', 0, 'I am the boodyman', { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' });
+ expect(auth).to.not.exist();
+ done();
+ });
+
+ it('errors on null message', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha1'
+ };
+
+ var auth = Hawk.client.message('example.com', 80, null, { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' });
+ expect(auth).to.not.exist();
+ done();
+ });
+
+ it('errors on missing message', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha1'
+ };
+
+ var auth = Hawk.client.message('example.com', 80, undefined, { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' });
+ expect(auth).to.not.exist();
+ done();
+ });
+
+ it('errors on invalid message', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha1'
+ };
+
+ var auth = Hawk.client.message('example.com', 80, 5, { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' });
+ expect(auth).to.not.exist();
+ done();
+ });
+
+ it('errors on missing options', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha1'
+ };
+
+ var auth = Hawk.client.message('example.com', 80, 'I am the boodyman');
+ expect(auth).to.not.exist();
+ done();
+ });
+
+ it('errors on invalid credentials (id)', function (done) {
+
+ var credentials = {
+ key: '2983d45yun89q',
+ algorithm: 'sha1'
+ };
+
+ var auth = Hawk.client.message('example.com', 80, 'I am the boodyman', { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' });
+ expect(auth).to.not.exist();
+ done();
+ });
+
+ it('errors on invalid credentials (key)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ algorithm: 'sha1'
+ };
+
+ var auth = Hawk.client.message('example.com', 80, 'I am the boodyman', { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' });
+ expect(auth).to.not.exist();
+ done();
+ });
+ });
+});
diff --git a/node_modules/request/node_modules/hawk/test/crypto.js b/node_modules/request/node_modules/hawk/test/crypto.js
index 1131628bf..a43753b24 100755
--- a/node_modules/request/node_modules/hawk/test/crypto.js
+++ b/node_modules/request/node_modules/hawk/test/crypto.js
@@ -1,70 +1,70 @@
-// Load modules
-
-var Code = require('code');
-var Hawk = require('../lib');
-var Lab = require('lab');
-
-
-// Declare internals
-
-var internals = {};
-
-
-// Test shortcuts
-
-var lab = exports.lab = Lab.script();
-var describe = lab.experiment;
-var it = lab.test;
-var expect = Code.expect;
-
-
-describe('Crypto', function () {
-
- describe('generateNormalizedString()', function () {
-
- it('should return a valid normalized string', function (done) {
-
- expect(Hawk.crypto.generateNormalizedString('header', {
- ts: 1357747017,
- nonce: 'k3k4j5',
- method: 'GET',
- resource: '/resource/something',
- host: 'example.com',
- port: 8080
- })).to.equal('hawk.1.header\n1357747017\nk3k4j5\nGET\n/resource/something\nexample.com\n8080\n\n\n');
-
- done();
- });
-
- it('should return a valid normalized string (ext)', function (done) {
-
- expect(Hawk.crypto.generateNormalizedString('header', {
- ts: 1357747017,
- nonce: 'k3k4j5',
- method: 'GET',
- resource: '/resource/something',
- host: 'example.com',
- port: 8080,
- ext: 'this is some app data'
- })).to.equal('hawk.1.header\n1357747017\nk3k4j5\nGET\n/resource/something\nexample.com\n8080\n\nthis is some app data\n');
-
- done();
- });
-
- it('should return a valid normalized string (payload + ext)', function (done) {
-
- expect(Hawk.crypto.generateNormalizedString('header', {
- ts: 1357747017,
- nonce: 'k3k4j5',
- method: 'GET',
- resource: '/resource/something',
- host: 'example.com',
- port: 8080,
- hash: 'U4MKKSmiVxk37JCCrAVIjV/OhB3y+NdwoCr6RShbVkE=',
- ext: 'this is some app data'
- })).to.equal('hawk.1.header\n1357747017\nk3k4j5\nGET\n/resource/something\nexample.com\n8080\nU4MKKSmiVxk37JCCrAVIjV/OhB3y+NdwoCr6RShbVkE=\nthis is some app data\n');
-
- done();
- });
- });
-});
+// Load modules
+
+var Code = require('code');
+var Hawk = require('../lib');
+var Lab = require('lab');
+
+
+// Declare internals
+
+var internals = {};
+
+
+// Test shortcuts
+
+var lab = exports.lab = Lab.script();
+var describe = lab.experiment;
+var it = lab.test;
+var expect = Code.expect;
+
+
+describe('Crypto', function () {
+
+ describe('generateNormalizedString()', function () {
+
+ it('should return a valid normalized string', function (done) {
+
+ expect(Hawk.crypto.generateNormalizedString('header', {
+ ts: 1357747017,
+ nonce: 'k3k4j5',
+ method: 'GET',
+ resource: '/resource/something',
+ host: 'example.com',
+ port: 8080
+ })).to.equal('hawk.1.header\n1357747017\nk3k4j5\nGET\n/resource/something\nexample.com\n8080\n\n\n');
+
+ done();
+ });
+
+ it('should return a valid normalized string (ext)', function (done) {
+
+ expect(Hawk.crypto.generateNormalizedString('header', {
+ ts: 1357747017,
+ nonce: 'k3k4j5',
+ method: 'GET',
+ resource: '/resource/something',
+ host: 'example.com',
+ port: 8080,
+ ext: 'this is some app data'
+ })).to.equal('hawk.1.header\n1357747017\nk3k4j5\nGET\n/resource/something\nexample.com\n8080\n\nthis is some app data\n');
+
+ done();
+ });
+
+ it('should return a valid normalized string (payload + ext)', function (done) {
+
+ expect(Hawk.crypto.generateNormalizedString('header', {
+ ts: 1357747017,
+ nonce: 'k3k4j5',
+ method: 'GET',
+ resource: '/resource/something',
+ host: 'example.com',
+ port: 8080,
+ hash: 'U4MKKSmiVxk37JCCrAVIjV/OhB3y+NdwoCr6RShbVkE=',
+ ext: 'this is some app data'
+ })).to.equal('hawk.1.header\n1357747017\nk3k4j5\nGET\n/resource/something\nexample.com\n8080\nU4MKKSmiVxk37JCCrAVIjV/OhB3y+NdwoCr6RShbVkE=\nthis is some app data\n');
+
+ done();
+ });
+ });
+});
diff --git a/node_modules/request/node_modules/hawk/test/index.js b/node_modules/request/node_modules/hawk/test/index.js
index e67afab57..7d1f91969 100755
--- a/node_modules/request/node_modules/hawk/test/index.js
+++ b/node_modules/request/node_modules/hawk/test/index.js
@@ -1,378 +1,378 @@
-// Load modules
-
-var Url = require('url');
-var Code = require('code');
-var Hawk = require('../lib');
-var Lab = require('lab');
-
-
-// Declare internals
-
-var internals = {};
-
-
-// Test shortcuts
-
-var lab = exports.lab = Lab.script();
-var describe = lab.experiment;
-var it = lab.test;
-var expect = Code.expect;
-
-
-describe('Hawk', function () {
-
- var credentialsFunc = function (id, callback) {
-
- var credentials = {
- id: id,
- key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
- algorithm: (id === '1' ? 'sha1' : 'sha256'),
- user: 'steve'
- };
-
- return callback(null, credentials);
- };
-
- it('generates a header then successfully parse it (configuration)', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080
- };
-
- credentialsFunc('123456', function (err, credentials1) {
-
- req.authorization = Hawk.client.header(Url.parse('http://example.com:8080/resource/4?filter=a'), req.method, { credentials: credentials1, ext: 'some-app-data' }).field;
- expect(req.authorization).to.exist();
-
- Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
-
- expect(err).to.not.exist();
- expect(credentials2.user).to.equal('steve');
- expect(artifacts.ext).to.equal('some-app-data');
- done();
- });
- });
- });
-
- it('generates a header then successfully parse it (node request)', function (done) {
-
- var req = {
- method: 'POST',
- url: '/resource/4?filter=a',
- headers: {
- host: 'example.com:8080',
- 'content-type': 'text/plain;x=y'
- }
- };
-
- var payload = 'some not so random text';
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var reqHeader = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] });
- req.headers.authorization = reqHeader.field;
-
- Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
-
- expect(err).to.not.exist();
- expect(credentials2.user).to.equal('steve');
- expect(artifacts.ext).to.equal('some-app-data');
- expect(Hawk.server.authenticatePayload(payload, credentials2, artifacts, req.headers['content-type'])).to.equal(true);
-
- var res = {
- headers: {
- 'content-type': 'text/plain'
- }
- };
-
- res.headers['server-authorization'] = Hawk.server.header(credentials2, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' });
- expect(res.headers['server-authorization']).to.exist();
-
- expect(Hawk.client.authenticate(res, credentials2, artifacts, { payload: 'some reply' })).to.equal(true);
- done();
- });
- });
- });
-
- it('generates a header then successfully parse it (absolute request uri)', function (done) {
-
- var req = {
- method: 'POST',
- url: 'http://example.com:8080/resource/4?filter=a',
- headers: {
- host: 'example.com:8080',
- 'content-type': 'text/plain;x=y'
- }
- };
-
- var payload = 'some not so random text';
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var reqHeader = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] });
- req.headers.authorization = reqHeader.field;
-
- Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
-
- expect(err).to.not.exist();
- expect(credentials2.user).to.equal('steve');
- expect(artifacts.ext).to.equal('some-app-data');
- expect(Hawk.server.authenticatePayload(payload, credentials2, artifacts, req.headers['content-type'])).to.equal(true);
-
- var res = {
- headers: {
- 'content-type': 'text/plain'
- }
- };
-
- res.headers['server-authorization'] = Hawk.server.header(credentials2, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' });
- expect(res.headers['server-authorization']).to.exist();
-
- expect(Hawk.client.authenticate(res, credentials2, artifacts, { payload: 'some reply' })).to.equal(true);
- done();
- });
- });
- });
-
- it('generates a header then successfully parse it (no server header options)', function (done) {
-
- var req = {
- method: 'POST',
- url: '/resource/4?filter=a',
- headers: {
- host: 'example.com:8080',
- 'content-type': 'text/plain;x=y'
- }
- };
-
- var payload = 'some not so random text';
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var reqHeader = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] });
- req.headers.authorization = reqHeader.field;
-
- Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
-
- expect(err).to.not.exist();
- expect(credentials2.user).to.equal('steve');
- expect(artifacts.ext).to.equal('some-app-data');
- expect(Hawk.server.authenticatePayload(payload, credentials2, artifacts, req.headers['content-type'])).to.equal(true);
-
- var res = {
- headers: {
- 'content-type': 'text/plain'
- }
- };
-
- res.headers['server-authorization'] = Hawk.server.header(credentials2, artifacts);
- expect(res.headers['server-authorization']).to.exist();
-
- expect(Hawk.client.authenticate(res, credentials2, artifacts)).to.equal(true);
- done();
- });
- });
- });
-
- it('generates a header then fails to parse it (missing server header hash)', function (done) {
-
- var req = {
- method: 'POST',
- url: '/resource/4?filter=a',
- headers: {
- host: 'example.com:8080',
- 'content-type': 'text/plain;x=y'
- }
- };
-
- var payload = 'some not so random text';
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var reqHeader = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] });
- req.headers.authorization = reqHeader.field;
-
- Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
-
- expect(err).to.not.exist();
- expect(credentials2.user).to.equal('steve');
- expect(artifacts.ext).to.equal('some-app-data');
- expect(Hawk.server.authenticatePayload(payload, credentials2, artifacts, req.headers['content-type'])).to.equal(true);
-
- var res = {
- headers: {
- 'content-type': 'text/plain'
- }
- };
-
- res.headers['server-authorization'] = Hawk.server.header(credentials2, artifacts);
- expect(res.headers['server-authorization']).to.exist();
-
- expect(Hawk.client.authenticate(res, credentials2, artifacts, { payload: 'some reply' })).to.equal(false);
- done();
- });
- });
- });
-
- it('generates a header then successfully parse it (with hash)', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080
- };
-
- credentialsFunc('123456', function (err, credentials1) {
-
- req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, payload: 'hola!', ext: 'some-app-data' }).field;
- Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
-
- expect(err).to.not.exist();
- expect(credentials2.user).to.equal('steve');
- expect(artifacts.ext).to.equal('some-app-data');
- done();
- });
- });
- });
-
- it('generates a header then successfully parse it then validate payload', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080
- };
-
- credentialsFunc('123456', function (err, credentials1) {
-
- req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, payload: 'hola!', ext: 'some-app-data' }).field;
- Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
-
- expect(err).to.not.exist();
- expect(credentials2.user).to.equal('steve');
- expect(artifacts.ext).to.equal('some-app-data');
- expect(Hawk.server.authenticatePayload('hola!', credentials2, artifacts)).to.be.true();
- expect(Hawk.server.authenticatePayload('hello!', credentials2, artifacts)).to.be.false();
- done();
- });
- });
- });
-
- it('generates a header then successfully parses and validates payload', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080
- };
-
- credentialsFunc('123456', function (err, credentials1) {
-
- req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, payload: 'hola!', ext: 'some-app-data' }).field;
- Hawk.server.authenticate(req, credentialsFunc, { payload: 'hola!' }, function (err, credentials2, artifacts) {
-
- expect(err).to.not.exist();
- expect(credentials2.user).to.equal('steve');
- expect(artifacts.ext).to.equal('some-app-data');
- done();
- });
- });
- });
-
- it('generates a header then successfully parse it (app)', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080
- };
-
- credentialsFunc('123456', function (err, credentials1) {
-
- req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', app: 'asd23ased' }).field;
- Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
-
- expect(err).to.not.exist();
- expect(credentials2.user).to.equal('steve');
- expect(artifacts.ext).to.equal('some-app-data');
- expect(artifacts.app).to.equal('asd23ased');
- done();
- });
- });
- });
-
- it('generates a header then successfully parse it (app, dlg)', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080
- };
-
- credentialsFunc('123456', function (err, credentials1) {
-
- req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', app: 'asd23ased', dlg: '23434szr3q4d' }).field;
- Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
-
- expect(err).to.not.exist();
- expect(credentials2.user).to.equal('steve');
- expect(artifacts.ext).to.equal('some-app-data');
- expect(artifacts.app).to.equal('asd23ased');
- expect(artifacts.dlg).to.equal('23434szr3q4d');
- done();
- });
- });
- });
-
- it('generates a header then fail authentication due to bad hash', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080
- };
-
- credentialsFunc('123456', function (err, credentials1) {
-
- req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, payload: 'hola!', ext: 'some-app-data' }).field;
- Hawk.server.authenticate(req, credentialsFunc, { payload: 'byebye!' }, function (err, credentials2, artifacts) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Bad payload hash');
- done();
- });
- });
- });
-
- it('generates a header for one resource then fail to authenticate another', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080
- };
-
- credentialsFunc('123456', function (err, credentials1) {
-
- req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data' }).field;
- req.url = '/something/else';
-
- Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
-
- expect(err).to.exist();
- expect(credentials2).to.exist();
- done();
- });
- });
- });
-});
+// Load modules
+
+var Url = require('url');
+var Code = require('code');
+var Hawk = require('../lib');
+var Lab = require('lab');
+
+
+// Declare internals
+
+var internals = {};
+
+
+// Test shortcuts
+
+var lab = exports.lab = Lab.script();
+var describe = lab.experiment;
+var it = lab.test;
+var expect = Code.expect;
+
+
+describe('Hawk', function () {
+
+ var credentialsFunc = function (id, callback) {
+
+ var credentials = {
+ id: id,
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: (id === '1' ? 'sha1' : 'sha256'),
+ user: 'steve'
+ };
+
+ return callback(null, credentials);
+ };
+
+ it('generates a header then successfully parse it (configuration)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080
+ };
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ req.authorization = Hawk.client.header(Url.parse('http://example.com:8080/resource/4?filter=a'), req.method, { credentials: credentials1, ext: 'some-app-data' }).field;
+ expect(req.authorization).to.exist();
+
+ Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
+
+ expect(err).to.not.exist();
+ expect(credentials2.user).to.equal('steve');
+ expect(artifacts.ext).to.equal('some-app-data');
+ done();
+ });
+ });
+ });
+
+ it('generates a header then successfully parse it (node request)', function (done) {
+
+ var req = {
+ method: 'POST',
+ url: '/resource/4?filter=a',
+ headers: {
+ host: 'example.com:8080',
+ 'content-type': 'text/plain;x=y'
+ }
+ };
+
+ var payload = 'some not so random text';
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var reqHeader = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] });
+ req.headers.authorization = reqHeader.field;
+
+ Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
+
+ expect(err).to.not.exist();
+ expect(credentials2.user).to.equal('steve');
+ expect(artifacts.ext).to.equal('some-app-data');
+ expect(Hawk.server.authenticatePayload(payload, credentials2, artifacts, req.headers['content-type'])).to.equal(true);
+
+ var res = {
+ headers: {
+ 'content-type': 'text/plain'
+ }
+ };
+
+ res.headers['server-authorization'] = Hawk.server.header(credentials2, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' });
+ expect(res.headers['server-authorization']).to.exist();
+
+ expect(Hawk.client.authenticate(res, credentials2, artifacts, { payload: 'some reply' })).to.equal(true);
+ done();
+ });
+ });
+ });
+
+ it('generates a header then successfully parse it (absolute request uri)', function (done) {
+
+ var req = {
+ method: 'POST',
+ url: 'http://example.com:8080/resource/4?filter=a',
+ headers: {
+ host: 'example.com:8080',
+ 'content-type': 'text/plain;x=y'
+ }
+ };
+
+ var payload = 'some not so random text';
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var reqHeader = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] });
+ req.headers.authorization = reqHeader.field;
+
+ Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
+
+ expect(err).to.not.exist();
+ expect(credentials2.user).to.equal('steve');
+ expect(artifacts.ext).to.equal('some-app-data');
+ expect(Hawk.server.authenticatePayload(payload, credentials2, artifacts, req.headers['content-type'])).to.equal(true);
+
+ var res = {
+ headers: {
+ 'content-type': 'text/plain'
+ }
+ };
+
+ res.headers['server-authorization'] = Hawk.server.header(credentials2, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' });
+ expect(res.headers['server-authorization']).to.exist();
+
+ expect(Hawk.client.authenticate(res, credentials2, artifacts, { payload: 'some reply' })).to.equal(true);
+ done();
+ });
+ });
+ });
+
+ it('generates a header then successfully parse it (no server header options)', function (done) {
+
+ var req = {
+ method: 'POST',
+ url: '/resource/4?filter=a',
+ headers: {
+ host: 'example.com:8080',
+ 'content-type': 'text/plain;x=y'
+ }
+ };
+
+ var payload = 'some not so random text';
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var reqHeader = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] });
+ req.headers.authorization = reqHeader.field;
+
+ Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
+
+ expect(err).to.not.exist();
+ expect(credentials2.user).to.equal('steve');
+ expect(artifacts.ext).to.equal('some-app-data');
+ expect(Hawk.server.authenticatePayload(payload, credentials2, artifacts, req.headers['content-type'])).to.equal(true);
+
+ var res = {
+ headers: {
+ 'content-type': 'text/plain'
+ }
+ };
+
+ res.headers['server-authorization'] = Hawk.server.header(credentials2, artifacts);
+ expect(res.headers['server-authorization']).to.exist();
+
+ expect(Hawk.client.authenticate(res, credentials2, artifacts)).to.equal(true);
+ done();
+ });
+ });
+ });
+
+ it('generates a header then fails to parse it (missing server header hash)', function (done) {
+
+ var req = {
+ method: 'POST',
+ url: '/resource/4?filter=a',
+ headers: {
+ host: 'example.com:8080',
+ 'content-type': 'text/plain;x=y'
+ }
+ };
+
+ var payload = 'some not so random text';
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var reqHeader = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] });
+ req.headers.authorization = reqHeader.field;
+
+ Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
+
+ expect(err).to.not.exist();
+ expect(credentials2.user).to.equal('steve');
+ expect(artifacts.ext).to.equal('some-app-data');
+ expect(Hawk.server.authenticatePayload(payload, credentials2, artifacts, req.headers['content-type'])).to.equal(true);
+
+ var res = {
+ headers: {
+ 'content-type': 'text/plain'
+ }
+ };
+
+ res.headers['server-authorization'] = Hawk.server.header(credentials2, artifacts);
+ expect(res.headers['server-authorization']).to.exist();
+
+ expect(Hawk.client.authenticate(res, credentials2, artifacts, { payload: 'some reply' })).to.equal(false);
+ done();
+ });
+ });
+ });
+
+ it('generates a header then successfully parse it (with hash)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080
+ };
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, payload: 'hola!', ext: 'some-app-data' }).field;
+ Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
+
+ expect(err).to.not.exist();
+ expect(credentials2.user).to.equal('steve');
+ expect(artifacts.ext).to.equal('some-app-data');
+ done();
+ });
+ });
+ });
+
+ it('generates a header then successfully parse it then validate payload', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080
+ };
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, payload: 'hola!', ext: 'some-app-data' }).field;
+ Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
+
+ expect(err).to.not.exist();
+ expect(credentials2.user).to.equal('steve');
+ expect(artifacts.ext).to.equal('some-app-data');
+ expect(Hawk.server.authenticatePayload('hola!', credentials2, artifacts)).to.be.true();
+ expect(Hawk.server.authenticatePayload('hello!', credentials2, artifacts)).to.be.false();
+ done();
+ });
+ });
+ });
+
+ it('generates a header then successfully parses and validates payload', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080
+ };
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, payload: 'hola!', ext: 'some-app-data' }).field;
+ Hawk.server.authenticate(req, credentialsFunc, { payload: 'hola!' }, function (err, credentials2, artifacts) {
+
+ expect(err).to.not.exist();
+ expect(credentials2.user).to.equal('steve');
+ expect(artifacts.ext).to.equal('some-app-data');
+ done();
+ });
+ });
+ });
+
+ it('generates a header then successfully parse it (app)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080
+ };
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', app: 'asd23ased' }).field;
+ Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
+
+ expect(err).to.not.exist();
+ expect(credentials2.user).to.equal('steve');
+ expect(artifacts.ext).to.equal('some-app-data');
+ expect(artifacts.app).to.equal('asd23ased');
+ done();
+ });
+ });
+ });
+
+ it('generates a header then successfully parse it (app, dlg)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080
+ };
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', app: 'asd23ased', dlg: '23434szr3q4d' }).field;
+ Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
+
+ expect(err).to.not.exist();
+ expect(credentials2.user).to.equal('steve');
+ expect(artifacts.ext).to.equal('some-app-data');
+ expect(artifacts.app).to.equal('asd23ased');
+ expect(artifacts.dlg).to.equal('23434szr3q4d');
+ done();
+ });
+ });
+ });
+
+ it('generates a header then fail authentication due to bad hash', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080
+ };
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, payload: 'hola!', ext: 'some-app-data' }).field;
+ Hawk.server.authenticate(req, credentialsFunc, { payload: 'byebye!' }, function (err, credentials2, artifacts) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Bad payload hash');
+ done();
+ });
+ });
+ });
+
+ it('generates a header for one resource then fail to authenticate another', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080
+ };
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data' }).field;
+ req.url = '/something/else';
+
+ Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) {
+
+ expect(err).to.exist();
+ expect(credentials2).to.exist();
+ done();
+ });
+ });
+ });
+});
diff --git a/node_modules/request/node_modules/hawk/test/readme.js b/node_modules/request/node_modules/hawk/test/readme.js
index a46626466..abc162445 100755
--- a/node_modules/request/node_modules/hawk/test/readme.js
+++ b/node_modules/request/node_modules/hawk/test/readme.js
@@ -1,95 +1,95 @@
-// Load modules
-
-var Code = require('code');
-var Hawk = require('../lib');
-var Hoek = require('hoek');
-var Lab = require('lab');
-
-
-// Declare internals
-
-var internals = {};
-
-
-// Test shortcuts
-
-var lab = exports.lab = Lab.script();
-var describe = lab.experiment;
-var it = lab.test;
-var expect = Code.expect;
-
-
-describe('README', function () {
-
- describe('core', function () {
-
- var credentials = {
- id: 'dh37fgj492je',
- key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
- algorithm: 'sha256'
- };
-
- var options = {
- credentials: credentials,
- timestamp: 1353832234,
- nonce: 'j4h3g2',
- ext: 'some-app-ext-data'
- };
-
- it('should generate a header protocol example', function (done) {
-
- var header = Hawk.client.header('http://example.com:8000/resource/1?b=1&a=2', 'GET', options).field;
-
- expect(header).to.equal('Hawk id="dh37fgj492je", ts="1353832234", nonce="j4h3g2", ext="some-app-ext-data", mac="6R4rV5iE+NPoym+WwjeHzjAGXUtLNIxmo1vpMofpLAE="');
- done();
- });
-
- it('should generate a normalized string protocol example', function (done) {
-
- var normalized = Hawk.crypto.generateNormalizedString('header', {
- credentials: credentials,
- ts: options.timestamp,
- nonce: options.nonce,
- method: 'GET',
- resource: '/resource?a=1&b=2',
- host: 'example.com',
- port: 8000,
- ext: options.ext
- });
-
- expect(normalized).to.equal('hawk.1.header\n1353832234\nj4h3g2\nGET\n/resource?a=1&b=2\nexample.com\n8000\n\nsome-app-ext-data\n');
- done();
- });
-
- var payloadOptions = Hoek.clone(options);
- payloadOptions.payload = 'Thank you for flying Hawk';
- payloadOptions.contentType = 'text/plain';
-
- it('should generate a header protocol example (with payload)', function (done) {
-
- var header = Hawk.client.header('http://example.com:8000/resource/1?b=1&a=2', 'POST', payloadOptions).field;
-
- expect(header).to.equal('Hawk id="dh37fgj492je", ts="1353832234", nonce="j4h3g2", hash="Yi9LfIIFRtBEPt74PVmbTF/xVAwPn7ub15ePICfgnuY=", ext="some-app-ext-data", mac="aSe1DERmZuRl3pI36/9BdZmnErTw3sNzOOAUlfeKjVw="');
- done();
- });
-
- it('should generate a normalized string protocol example (with payload)', function (done) {
-
- var normalized = Hawk.crypto.generateNormalizedString('header', {
- credentials: credentials,
- ts: options.timestamp,
- nonce: options.nonce,
- method: 'POST',
- resource: '/resource?a=1&b=2',
- host: 'example.com',
- port: 8000,
- hash: Hawk.crypto.calculatePayloadHash(payloadOptions.payload, credentials.algorithm, payloadOptions.contentType),
- ext: options.ext
- });
-
- expect(normalized).to.equal('hawk.1.header\n1353832234\nj4h3g2\nPOST\n/resource?a=1&b=2\nexample.com\n8000\nYi9LfIIFRtBEPt74PVmbTF/xVAwPn7ub15ePICfgnuY=\nsome-app-ext-data\n');
- done();
- });
- });
-});
-
+// Load modules
+
+var Code = require('code');
+var Hawk = require('../lib');
+var Hoek = require('hoek');
+var Lab = require('lab');
+
+
+// Declare internals
+
+var internals = {};
+
+
+// Test shortcuts
+
+var lab = exports.lab = Lab.script();
+var describe = lab.experiment;
+var it = lab.test;
+var expect = Code.expect;
+
+
+describe('README', function () {
+
+ describe('core', function () {
+
+ var credentials = {
+ id: 'dh37fgj492je',
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: 'sha256'
+ };
+
+ var options = {
+ credentials: credentials,
+ timestamp: 1353832234,
+ nonce: 'j4h3g2',
+ ext: 'some-app-ext-data'
+ };
+
+ it('should generate a header protocol example', function (done) {
+
+ var header = Hawk.client.header('http://example.com:8000/resource/1?b=1&a=2', 'GET', options).field;
+
+ expect(header).to.equal('Hawk id="dh37fgj492je", ts="1353832234", nonce="j4h3g2", ext="some-app-ext-data", mac="6R4rV5iE+NPoym+WwjeHzjAGXUtLNIxmo1vpMofpLAE="');
+ done();
+ });
+
+ it('should generate a normalized string protocol example', function (done) {
+
+ var normalized = Hawk.crypto.generateNormalizedString('header', {
+ credentials: credentials,
+ ts: options.timestamp,
+ nonce: options.nonce,
+ method: 'GET',
+ resource: '/resource?a=1&b=2',
+ host: 'example.com',
+ port: 8000,
+ ext: options.ext
+ });
+
+ expect(normalized).to.equal('hawk.1.header\n1353832234\nj4h3g2\nGET\n/resource?a=1&b=2\nexample.com\n8000\n\nsome-app-ext-data\n');
+ done();
+ });
+
+ var payloadOptions = Hoek.clone(options);
+ payloadOptions.payload = 'Thank you for flying Hawk';
+ payloadOptions.contentType = 'text/plain';
+
+ it('should generate a header protocol example (with payload)', function (done) {
+
+ var header = Hawk.client.header('http://example.com:8000/resource/1?b=1&a=2', 'POST', payloadOptions).field;
+
+ expect(header).to.equal('Hawk id="dh37fgj492je", ts="1353832234", nonce="j4h3g2", hash="Yi9LfIIFRtBEPt74PVmbTF/xVAwPn7ub15ePICfgnuY=", ext="some-app-ext-data", mac="aSe1DERmZuRl3pI36/9BdZmnErTw3sNzOOAUlfeKjVw="');
+ done();
+ });
+
+ it('should generate a normalized string protocol example (with payload)', function (done) {
+
+ var normalized = Hawk.crypto.generateNormalizedString('header', {
+ credentials: credentials,
+ ts: options.timestamp,
+ nonce: options.nonce,
+ method: 'POST',
+ resource: '/resource?a=1&b=2',
+ host: 'example.com',
+ port: 8000,
+ hash: Hawk.crypto.calculatePayloadHash(payloadOptions.payload, credentials.algorithm, payloadOptions.contentType),
+ ext: options.ext
+ });
+
+ expect(normalized).to.equal('hawk.1.header\n1353832234\nj4h3g2\nPOST\n/resource?a=1&b=2\nexample.com\n8000\nYi9LfIIFRtBEPt74PVmbTF/xVAwPn7ub15ePICfgnuY=\nsome-app-ext-data\n');
+ done();
+ });
+ });
+});
+
diff --git a/node_modules/request/node_modules/hawk/test/server.js b/node_modules/request/node_modules/hawk/test/server.js
index 66ce36c9d..8c54f0e30 100755
--- a/node_modules/request/node_modules/hawk/test/server.js
+++ b/node_modules/request/node_modules/hawk/test/server.js
@@ -1,1302 +1,1329 @@
-// Load modules
-
-var Url = require('url');
-var Code = require('code');
-var Hawk = require('../lib');
-var Hoek = require('hoek');
-var Lab = require('lab');
-
-
-// Declare internals
-
-var internals = {};
-
-
-// Test shortcuts
-
-var lab = exports.lab = Lab.script();
-var describe = lab.experiment;
-var it = lab.test;
-var expect = Code.expect;
-
-
-describe('Server', function () {
-
- var credentialsFunc = function (id, callback) {
-
- var credentials = {
- id: id,
- key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
- algorithm: (id === '1' ? 'sha1' : 'sha256'),
- user: 'steve'
- };
-
- return callback(null, credentials);
- };
-
- describe('authenticate()', function () {
-
- it('parses a valid authentication header (sha1)', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080,
- authorization: 'Hawk id="1", ts="1353788437", nonce="k3j4h2", mac="zy79QQ5/EYFmQqutVnYb73gAc/U=", ext="hello"'
- };
-
- Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
-
- expect(err).to.not.exist();
- expect(credentials.user).to.equal('steve');
- done();
- });
- });
-
- it('parses a valid authentication header (sha256)', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/1?b=1&a=2',
- host: 'example.com',
- port: 8000,
- authorization: 'Hawk id="dh37fgj492je", ts="1353832234", nonce="j4h3g2", mac="m8r1rHbXN6NgO+KIIhjO7sFRyd78RNGVUwehe8Cp2dU=", ext="some-app-data"'
- };
-
- Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353832234000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
-
- expect(err).to.not.exist();
- expect(credentials.user).to.equal('steve');
- done();
- });
- });
-
- it('parses a valid authentication header (host override)', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- headers: {
- host: 'example1.com:8080',
- authorization: 'Hawk id="1", ts="1353788437", nonce="k3j4h2", mac="zy79QQ5/EYFmQqutVnYb73gAc/U=", ext="hello"'
- }
- };
-
- Hawk.server.authenticate(req, credentialsFunc, { host: 'example.com', localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
-
- expect(err).to.not.exist();
- expect(credentials.user).to.equal('steve');
- done();
- });
- });
-
- it('parses a valid authentication header (host port override)', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- headers: {
- host: 'example1.com:80',
- authorization: 'Hawk id="1", ts="1353788437", nonce="k3j4h2", mac="zy79QQ5/EYFmQqutVnYb73gAc/U=", ext="hello"'
- }
- };
-
- Hawk.server.authenticate(req, credentialsFunc, { host: 'example.com', port: 8080, localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
-
- expect(err).to.not.exist();
- expect(credentials.user).to.equal('steve');
- done();
- });
- });
-
- it('parses a valid authentication header (POST with payload)', function (done) {
-
- var req = {
- method: 'POST',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080,
- authorization: 'Hawk id="123456", ts="1357926341", nonce="1AwuJD", hash="qAiXIVv+yjDATneWxZP2YCTa9aHRgQdnH9b3Wc+o3dg=", ext="some-app-data", mac="UeYcj5UoTVaAWXNvJfLVia7kU3VabxCqrccXP8sUGC4="'
- };
-
- Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1357926341000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
-
- expect(err).to.not.exist();
- expect(credentials.user).to.equal('steve');
- done();
- });
- });
-
- it('errors on missing hash', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/1?b=1&a=2',
- host: 'example.com',
- port: 8000,
- authorization: 'Hawk id="dh37fgj492je", ts="1353832234", nonce="j4h3g2", mac="m8r1rHbXN6NgO+KIIhjO7sFRyd78RNGVUwehe8Cp2dU=", ext="some-app-data"'
- };
-
- Hawk.server.authenticate(req, credentialsFunc, { payload: 'body', localtimeOffsetMsec: 1353832234000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Missing required payload hash');
- done();
- });
- });
-
- it('errors on a stale timestamp', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080,
- authorization: 'Hawk id="123456", ts="1362337299", nonce="UzmxSs", ext="some-app-data", mac="wnNUxchvvryMH2RxckTdZ/gY3ijzvccx4keVvELC61w="'
- };
-
- Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Stale timestamp');
- var header = err.output.headers['WWW-Authenticate'];
- var ts = header.match(/^Hawk ts\=\"(\d+)\"\, tsm\=\"([^\"]+)\"\, error=\"Stale timestamp\"$/);
- var now = Hawk.utils.now();
- expect(parseInt(ts[1], 10) * 1000).to.be.within(now - 1000, now + 1000);
-
- var res = {
- headers: {
- 'www-authenticate': header
- }
- };
-
- expect(Hawk.client.authenticate(res, credentials, artifacts)).to.equal(true);
- done();
- });
- });
-
- it('errors on a replay', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080,
- authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="bXx7a7p1h9QYQNZ8x7QhvDQym8ACgab4m3lVSFn4DBw=", ext="hello"'
- };
-
- var memoryCache = {};
- var options = {
- localtimeOffsetMsec: 1353788437000 - Hawk.utils.now(),
- nonceFunc: function (key, nonce, ts, callback) {
-
- if (memoryCache[key + nonce]) {
- return callback(new Error());
- }
-
- memoryCache[key + nonce] = true;
- return callback();
- }
- };
-
- Hawk.server.authenticate(req, credentialsFunc, options, function (err, credentials1, artifacts1) {
-
- expect(err).to.not.exist();
- expect(credentials1.user).to.equal('steve');
-
- Hawk.server.authenticate(req, credentialsFunc, options, function (err, credentials2, artifacts2) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Invalid nonce');
- done();
- });
- });
- });
-
- it('does not error on nonce collision if keys differ', function (done) {
-
- var reqSteve = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080,
- authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="bXx7a7p1h9QYQNZ8x7QhvDQym8ACgab4m3lVSFn4DBw=", ext="hello"'
- };
-
- var reqBob = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080,
- authorization: 'Hawk id="456", ts="1353788437", nonce="k3j4h2", mac="LXfmTnRzrLd9TD7yfH+4se46Bx6AHyhpM94hLCiNia4=", ext="hello"'
- };
-
- var credentialsFuncion = function (id, callback) {
-
- var credentials = {
- '123': {
- id: id,
- key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
- algorithm: (id === '1' ? 'sha1' : 'sha256'),
- user: 'steve'
- },
- '456': {
- id: id,
- key: 'xrunpaw3489ruxnpa98w4rxnwerxhqb98rpaxn39848',
- algorithm: (id === '1' ? 'sha1' : 'sha256'),
- user: 'bob'
- }
- };
-
- return callback(null, credentials[id]);
- };
-
- var memoryCache = {};
- var options = {
- localtimeOffsetMsec: 1353788437000 - Hawk.utils.now(),
- nonceFunc: function (key, nonce, ts, callback) {
-
- if (memoryCache[key + nonce]) {
- return callback(new Error());
- }
-
- memoryCache[key + nonce] = true;
- return callback();
- }
- };
-
- Hawk.server.authenticate(reqSteve, credentialsFuncion, options, function (err, credentials1, artifacts1) {
-
- expect(err).to.not.exist();
- expect(credentials1.user).to.equal('steve');
-
- Hawk.server.authenticate(reqBob, credentialsFuncion, options, function (err, credentials2, artifacts2) {
-
- expect(err).to.not.exist();
- expect(credentials2.user).to.equal('bob');
- done();
- });
- });
- });
-
- it('errors on an invalid authentication header: wrong scheme', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080,
- authorization: 'Basic asdasdasdasd'
- };
-
- Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.not.exist();
- done();
- });
- });
-
- it('errors on an invalid authentication header: no scheme', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080,
- authorization: '!@#'
- };
-
- Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Invalid header syntax');
- done();
- });
- });
-
- it('errors on an missing authorization header', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080
- };
-
- Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
-
- expect(err).to.exist();
- expect(err.isMissing).to.equal(true);
- done();
- });
- });
-
- it('errors on an missing host header', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- headers: {
- authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
- }
- };
-
- Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Invalid Host header');
- done();
- });
- });
-
- it('errors on an missing authorization attribute (id)', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080,
- authorization: 'Hawk ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
- };
-
- Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Missing attributes');
- done();
- });
- });
-
- it('errors on an missing authorization attribute (ts)', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080,
- authorization: 'Hawk id="123", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
- };
-
- Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Missing attributes');
- done();
- });
- });
-
- it('errors on an missing authorization attribute (nonce)', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080,
- authorization: 'Hawk id="123", ts="1353788437", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
- };
-
- Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Missing attributes');
- done();
- });
- });
-
- it('errors on an missing authorization attribute (mac)', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080,
- authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", ext="hello"'
- };
-
- Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Missing attributes');
- done();
- });
- });
-
- it('errors on an unknown authorization attribute', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080,
- authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", x="3", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
- };
-
- Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Unknown attribute: x');
- done();
- });
- });
-
- it('errors on an bad authorization header format', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080,
- authorization: 'Hawk id="123\\", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
- };
-
- Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Bad header format');
- done();
- });
- });
-
- it('errors on an bad authorization attribute value', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080,
- authorization: 'Hawk id="\t", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
- };
-
- Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Bad attribute value: id');
- done();
- });
- });
-
- it('errors on an empty authorization attribute value', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080,
- authorization: 'Hawk id="", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
- };
-
- Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Bad attribute value: id');
- done();
- });
- });
-
- it('errors on duplicated authorization attribute key', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080,
- authorization: 'Hawk id="123", id="456", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
- };
-
- Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Duplicate attribute: id');
- done();
- });
- });
-
- it('errors on an invalid authorization header format', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080,
- authorization: 'Hawk'
- };
-
- Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Invalid header syntax');
- done();
- });
- });
-
- it('errors on an bad host header (missing host)', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- headers: {
- host: ':8080',
- authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
- }
- };
-
- Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Invalid Host header');
- done();
- });
- });
-
- it('errors on an bad host header (pad port)', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- headers: {
- host: 'example.com:something',
- authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
- }
- };
-
- Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Invalid Host header');
- done();
- });
- });
-
- it('errors on credentialsFunc error', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080,
- authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
- };
-
- var credentialsFuncion = function (id, callback) {
-
- return callback(new Error('Unknown user'));
- };
-
- Hawk.server.authenticate(req, credentialsFuncion, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('Unknown user');
- done();
- });
- });
-
- it('errors on credentialsFunc error (with credentials)', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080,
- authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
- };
-
- var credentialsFuncion = function (id, callback) {
-
- return callback(new Error('Unknown user'), { some: 'value' });
- };
-
- Hawk.server.authenticate(req, credentialsFuncion, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('Unknown user');
- expect(credentials.some).to.equal('value');
- done();
- });
- });
-
- it('errors on missing credentials', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080,
- authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
- };
-
- var credentialsFuncion = function (id, callback) {
-
- return callback(null, null);
- };
-
- Hawk.server.authenticate(req, credentialsFuncion, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Unknown credentials');
- done();
- });
- });
-
- it('errors on invalid credentials (id)', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080,
- authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
- };
-
- var credentialsFuncion = function (id, callback) {
-
- var credentials = {
- key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
- user: 'steve'
- };
-
- return callback(null, credentials);
- };
-
- Hawk.server.authenticate(req, credentialsFuncion, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('Invalid credentials');
- expect(err.output.payload.message).to.equal('An internal server error occurred');
- done();
- });
- });
-
- it('errors on invalid credentials (key)', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080,
- authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
- };
-
- var credentialsFuncion = function (id, callback) {
-
- var credentials = {
- id: '23434d3q4d5345d',
- user: 'steve'
- };
-
- return callback(null, credentials);
- };
-
- Hawk.server.authenticate(req, credentialsFuncion, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('Invalid credentials');
- expect(err.output.payload.message).to.equal('An internal server error occurred');
- done();
- });
- });
-
- it('errors on unknown credentials algorithm', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080,
- authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
- };
-
- var credentialsFuncion = function (id, callback) {
-
- var credentials = {
- key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
- algorithm: 'hmac-sha-0',
- user: 'steve'
- };
-
- return callback(null, credentials);
- };
-
- Hawk.server.authenticate(req, credentialsFuncion, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('Unknown algorithm');
- expect(err.output.payload.message).to.equal('An internal server error occurred');
- done();
- });
- });
-
- it('errors on unknown bad mac', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080,
- authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcU4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
- };
-
- var credentialsFuncion = function (id, callback) {
-
- var credentials = {
- key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
- algorithm: 'sha256',
- user: 'steve'
- };
-
- return callback(null, credentials);
- };
-
- Hawk.server.authenticate(req, credentialsFuncion, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Bad mac');
- done();
- });
- });
- });
-
- describe('header()', function () {
-
- it('generates header', function (done) {
-
- var credentials = {
- id: '123456',
- key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
- algorithm: 'sha256',
- user: 'steve'
- };
-
- var artifacts = {
- method: 'POST',
- host: 'example.com',
- port: '8080',
- resource: '/resource/4?filter=a',
- ts: '1398546787',
- nonce: 'xUwusx',
- hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
- ext: 'some-app-data',
- mac: 'dvIvMThwi28J61Jc3P0ryAhuKpanU63GXdx6hkmQkJA=',
- id: '123456'
- };
-
- var header = Hawk.server.header(credentials, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' });
- expect(header).to.equal('Hawk mac=\"n14wVJK4cOxAytPUMc5bPezQzuJGl5n7MYXhFQgEKsE=\", hash=\"f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=\", ext=\"response-specific\"');
- done();
- });
-
- it('generates header (empty payload)', function (done) {
-
- var credentials = {
- id: '123456',
- key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
- algorithm: 'sha256',
- user: 'steve'
- };
-
- var artifacts = {
- method: 'POST',
- host: 'example.com',
- port: '8080',
- resource: '/resource/4?filter=a',
- ts: '1398546787',
- nonce: 'xUwusx',
- hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
- ext: 'some-app-data',
- mac: 'dvIvMThwi28J61Jc3P0ryAhuKpanU63GXdx6hkmQkJA=',
- id: '123456'
- };
-
- var header = Hawk.server.header(credentials, artifacts, { payload: '', contentType: 'text/plain', ext: 'response-specific' });
- expect(header).to.equal('Hawk mac=\"i8/kUBDx0QF+PpCtW860kkV/fa9dbwEoe/FpGUXowf0=\", hash=\"q/t+NNAkQZNlq/aAD6PlexImwQTxwgT2MahfTa9XRLA=\", ext=\"response-specific\"');
- done();
- });
-
- it('generates header (pre calculated hash)', function (done) {
-
- var credentials = {
- id: '123456',
- key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
- algorithm: 'sha256',
- user: 'steve'
- };
-
- var artifacts = {
- method: 'POST',
- host: 'example.com',
- port: '8080',
- resource: '/resource/4?filter=a',
- ts: '1398546787',
- nonce: 'xUwusx',
- hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
- ext: 'some-app-data',
- mac: 'dvIvMThwi28J61Jc3P0ryAhuKpanU63GXdx6hkmQkJA=',
- id: '123456'
- };
-
- var options = { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' };
- options.hash = Hawk.crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType);
- var header = Hawk.server.header(credentials, artifacts, options);
- expect(header).to.equal('Hawk mac=\"n14wVJK4cOxAytPUMc5bPezQzuJGl5n7MYXhFQgEKsE=\", hash=\"f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=\", ext=\"response-specific\"');
- done();
- });
-
- it('generates header (null ext)', function (done) {
-
- var credentials = {
- id: '123456',
- key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
- algorithm: 'sha256',
- user: 'steve'
- };
-
- var artifacts = {
- method: 'POST',
- host: 'example.com',
- port: '8080',
- resource: '/resource/4?filter=a',
- ts: '1398546787',
- nonce: 'xUwusx',
- hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
- mac: 'dvIvMThwi28J61Jc3P0ryAhuKpanU63GXdx6hkmQkJA=',
- id: '123456'
- };
-
- var header = Hawk.server.header(credentials, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: null });
- expect(header).to.equal('Hawk mac=\"6PrybJTJs20jsgBw5eilXpcytD8kUbaIKNYXL+6g0ns=\", hash=\"f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=\"');
- done();
- });
-
- it('errors on missing artifacts', function (done) {
-
- var credentials = {
- id: '123456',
- key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
- algorithm: 'sha256',
- user: 'steve'
- };
-
- var header = Hawk.server.header(credentials, null, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' });
- expect(header).to.equal('');
- done();
- });
-
- it('errors on invalid artifacts', function (done) {
-
- var credentials = {
- id: '123456',
- key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
- algorithm: 'sha256',
- user: 'steve'
- };
-
- var header = Hawk.server.header(credentials, 5, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' });
- expect(header).to.equal('');
- done();
- });
-
- it('errors on missing credentials', function (done) {
-
- var artifacts = {
- method: 'POST',
- host: 'example.com',
- port: '8080',
- resource: '/resource/4?filter=a',
- ts: '1398546787',
- nonce: 'xUwusx',
- hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
- ext: 'some-app-data',
- mac: 'dvIvMThwi28J61Jc3P0ryAhuKpanU63GXdx6hkmQkJA=',
- id: '123456'
- };
-
- var header = Hawk.server.header(null, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' });
- expect(header).to.equal('');
- done();
- });
-
- it('errors on invalid credentials (key)', function (done) {
-
- var credentials = {
- id: '123456',
- algorithm: 'sha256',
- user: 'steve'
- };
-
- var artifacts = {
- method: 'POST',
- host: 'example.com',
- port: '8080',
- resource: '/resource/4?filter=a',
- ts: '1398546787',
- nonce: 'xUwusx',
- hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
- ext: 'some-app-data',
- mac: 'dvIvMThwi28J61Jc3P0ryAhuKpanU63GXdx6hkmQkJA=',
- id: '123456'
- };
-
- var header = Hawk.server.header(credentials, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' });
- expect(header).to.equal('');
- done();
- });
-
- it('errors on invalid algorithm', function (done) {
-
- var credentials = {
- id: '123456',
- key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
- algorithm: 'x',
- user: 'steve'
- };
-
- var artifacts = {
- method: 'POST',
- host: 'example.com',
- port: '8080',
- resource: '/resource/4?filter=a',
- ts: '1398546787',
- nonce: 'xUwusx',
- hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
- ext: 'some-app-data',
- mac: 'dvIvMThwi28J61Jc3P0ryAhuKpanU63GXdx6hkmQkJA=',
- id: '123456'
- };
-
- var header = Hawk.server.header(credentials, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' });
- expect(header).to.equal('');
- done();
- });
- });
-
- describe('authenticateMessage()', function () {
-
- it('errors on invalid authorization (ts)', function (done) {
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
- delete auth.ts;
-
- Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials2) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('Invalid authorization');
- done();
- });
- });
- });
-
- it('errors on invalid authorization (nonce)', function (done) {
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
- delete auth.nonce;
-
- Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials2) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('Invalid authorization');
- done();
- });
- });
- });
-
- it('errors on invalid authorization (hash)', function (done) {
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
- delete auth.hash;
-
- Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials2) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('Invalid authorization');
- done();
- });
- });
- });
-
- it('errors with credentials', function (done) {
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
-
- Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, function (id, callback) {
-
- callback(new Error('something'), { some: 'value' });
- }, {}, function (err, credentials2) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('something');
- expect(credentials2.some).to.equal('value');
- done();
- });
- });
- });
-
- it('errors on nonce collision', function (done) {
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
- Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {
- nonceFunc: function (key, nonce, ts, nonceCallback) {
-
- nonceCallback(true);
- }
- }, function (err, credentials2) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('Invalid nonce');
- done();
- });
- });
- });
-
- it('should generate an authorization then successfully parse it', function (done) {
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
- expect(auth).to.exist();
-
- Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials2) {
-
- expect(err).to.not.exist();
- expect(credentials2.user).to.equal('steve');
- done();
- });
- });
- });
-
- it('should fail authorization on mismatching host', function (done) {
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
- expect(auth).to.exist();
-
- Hawk.server.authenticateMessage('example1.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials2) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('Bad mac');
- done();
- });
- });
- });
-
- it('should fail authorization on stale timestamp', function (done) {
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
- expect(auth).to.exist();
-
- Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, { localtimeOffsetMsec: 100000 }, function (err, credentials2) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('Stale timestamp');
- done();
- });
- });
- });
-
- it('overrides timestampSkewSec', function (done) {
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1, localtimeOffsetMsec: 100000 });
- expect(auth).to.exist();
-
- Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, { timestampSkewSec: 500 }, function (err, credentials2) {
-
- expect(err).to.not.exist();
- done();
- });
- });
- });
-
- it('should fail authorization on invalid authorization', function (done) {
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
- expect(auth).to.exist();
- delete auth.id;
-
- Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials2) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('Invalid authorization');
- done();
- });
- });
- });
-
- it('should fail authorization on bad hash', function (done) {
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
- expect(auth).to.exist();
-
- Hawk.server.authenticateMessage('example.com', 8080, 'some message1', auth, credentialsFunc, {}, function (err, credentials2) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('Bad message hash');
- done();
- });
- });
- });
-
- it('should fail authorization on nonce error', function (done) {
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
- expect(auth).to.exist();
-
- Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {
- nonceFunc: function (key, nonce, ts, callback) {
-
- callback(new Error('kaboom'));
- }
- }, function (err, credentials2) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('Invalid nonce');
- done();
- });
- });
- });
-
- it('should fail authorization on credentials error', function (done) {
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
- expect(auth).to.exist();
-
- var errFunc = function (id, callback) {
-
- callback(new Error('kablooey'));
- };
-
- Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, errFunc, {}, function (err, credentials2) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('kablooey');
- done();
- });
- });
- });
-
- it('should fail authorization on missing credentials', function (done) {
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
- expect(auth).to.exist();
-
- var errFunc = function (id, callback) {
-
- callback();
- };
-
- Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, errFunc, {}, function (err, credentials2) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('Unknown credentials');
- done();
- });
- });
- });
-
- it('should fail authorization on invalid credentials', function (done) {
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
- expect(auth).to.exist();
-
- var errFunc = function (id, callback) {
-
- callback(null, {});
- };
-
- Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, errFunc, {}, function (err, credentials2) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('Invalid credentials');
- done();
- });
- });
- });
-
- it('should fail authorization on invalid credentials algorithm', function (done) {
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
- expect(auth).to.exist();
-
- var errFunc = function (id, callback) {
-
- callback(null, { key: '123', algorithm: '456' });
- };
-
- Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, errFunc, {}, function (err, credentials2) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('Unknown algorithm');
- done();
- });
- });
- });
-
- it('should fail on missing host', function (done) {
-
- credentialsFunc('123456', function (err, credentials) {
-
- var auth = Hawk.client.message(null, 8080, 'some message', { credentials: credentials });
- expect(auth).to.not.exist();
- done();
- });
- });
-
- it('should fail on missing credentials', function (done) {
-
- var auth = Hawk.client.message('example.com', 8080, 'some message', {});
- expect(auth).to.not.exist();
- done();
- });
-
- it('should fail on invalid algorithm', function (done) {
-
- credentialsFunc('123456', function (err, credentials) {
-
- var creds = Hoek.clone(credentials);
- creds.algorithm = 'blah';
- var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: creds });
- expect(auth).to.not.exist();
- done();
- });
- });
- });
-
- describe('authenticatePayloadHash()', function () {
-
- it('checks payload hash', function (done) {
-
- expect(Hawk.server.authenticatePayloadHash('abcdefg', { hash: 'abcdefg' })).to.equal(true);
- expect(Hawk.server.authenticatePayloadHash('1234567', { hash: 'abcdefg' })).to.equal(false);
- done();
- });
- });
-});
-
+// Load modules
+
+var Url = require('url');
+var Code = require('code');
+var Hawk = require('../lib');
+var Hoek = require('hoek');
+var Lab = require('lab');
+
+
+// Declare internals
+
+var internals = {};
+
+
+// Test shortcuts
+
+var lab = exports.lab = Lab.script();
+var describe = lab.experiment;
+var it = lab.test;
+var expect = Code.expect;
+
+
+describe('Server', function () {
+
+ var credentialsFunc = function (id, callback) {
+
+ var credentials = {
+ id: id,
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: (id === '1' ? 'sha1' : 'sha256'),
+ user: 'steve'
+ };
+
+ return callback(null, credentials);
+ };
+
+ describe('authenticate()', function () {
+
+ it('parses a valid authentication header (sha1)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080,
+ authorization: 'Hawk id="1", ts="1353788437", nonce="k3j4h2", mac="zy79QQ5/EYFmQqutVnYb73gAc/U=", ext="hello"'
+ };
+
+ Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
+
+ expect(err).to.not.exist();
+ expect(credentials.user).to.equal('steve');
+ done();
+ });
+ });
+
+ it('parses a valid authentication header (sha256)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/1?b=1&a=2',
+ host: 'example.com',
+ port: 8000,
+ authorization: 'Hawk id="dh37fgj492je", ts="1353832234", nonce="j4h3g2", mac="m8r1rHbXN6NgO+KIIhjO7sFRyd78RNGVUwehe8Cp2dU=", ext="some-app-data"'
+ };
+
+ Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353832234000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
+
+ expect(err).to.not.exist();
+ expect(credentials.user).to.equal('steve');
+ done();
+ });
+ });
+
+ it('parses a valid authentication header (host override)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ headers: {
+ host: 'example1.com:8080',
+ authorization: 'Hawk id="1", ts="1353788437", nonce="k3j4h2", mac="zy79QQ5/EYFmQqutVnYb73gAc/U=", ext="hello"'
+ }
+ };
+
+ Hawk.server.authenticate(req, credentialsFunc, { host: 'example.com', localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
+
+ expect(err).to.not.exist();
+ expect(credentials.user).to.equal('steve');
+ done();
+ });
+ });
+
+ it('parses a valid authentication header (host port override)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ headers: {
+ host: 'example1.com:80',
+ authorization: 'Hawk id="1", ts="1353788437", nonce="k3j4h2", mac="zy79QQ5/EYFmQqutVnYb73gAc/U=", ext="hello"'
+ }
+ };
+
+ Hawk.server.authenticate(req, credentialsFunc, { host: 'example.com', port: 8080, localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
+
+ expect(err).to.not.exist();
+ expect(credentials.user).to.equal('steve');
+ done();
+ });
+ });
+
+ it('parses a valid authentication header (POST with payload)', function (done) {
+
+ var req = {
+ method: 'POST',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080,
+ authorization: 'Hawk id="123456", ts="1357926341", nonce="1AwuJD", hash="qAiXIVv+yjDATneWxZP2YCTa9aHRgQdnH9b3Wc+o3dg=", ext="some-app-data", mac="UeYcj5UoTVaAWXNvJfLVia7kU3VabxCqrccXP8sUGC4="'
+ };
+
+ Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1357926341000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
+
+ expect(err).to.not.exist();
+ expect(credentials.user).to.equal('steve');
+ done();
+ });
+ });
+
+ it('errors on missing hash', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/1?b=1&a=2',
+ host: 'example.com',
+ port: 8000,
+ authorization: 'Hawk id="dh37fgj492je", ts="1353832234", nonce="j4h3g2", mac="m8r1rHbXN6NgO+KIIhjO7sFRyd78RNGVUwehe8Cp2dU=", ext="some-app-data"'
+ };
+
+ Hawk.server.authenticate(req, credentialsFunc, { payload: 'body', localtimeOffsetMsec: 1353832234000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Missing required payload hash');
+ done();
+ });
+ });
+
+ it('errors on a stale timestamp', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080,
+ authorization: 'Hawk id="123456", ts="1362337299", nonce="UzmxSs", ext="some-app-data", mac="wnNUxchvvryMH2RxckTdZ/gY3ijzvccx4keVvELC61w="'
+ };
+
+ Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Stale timestamp');
+ var header = err.output.headers['WWW-Authenticate'];
+ var ts = header.match(/^Hawk ts\=\"(\d+)\"\, tsm\=\"([^\"]+)\"\, error=\"Stale timestamp\"$/);
+ var now = Hawk.utils.now();
+ expect(parseInt(ts[1], 10) * 1000).to.be.within(now - 1000, now + 1000);
+
+ var res = {
+ headers: {
+ 'www-authenticate': header
+ }
+ };
+
+ expect(Hawk.client.authenticate(res, credentials, artifacts)).to.equal(true);
+ done();
+ });
+ });
+
+ it('errors on a replay', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080,
+ authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="bXx7a7p1h9QYQNZ8x7QhvDQym8ACgab4m3lVSFn4DBw=", ext="hello"'
+ };
+
+ var memoryCache = {};
+ var options = {
+ localtimeOffsetMsec: 1353788437000 - Hawk.utils.now(),
+ nonceFunc: function (key, nonce, ts, callback) {
+
+ if (memoryCache[key + nonce]) {
+ return callback(new Error());
+ }
+
+ memoryCache[key + nonce] = true;
+ return callback();
+ }
+ };
+
+ Hawk.server.authenticate(req, credentialsFunc, options, function (err, credentials1, artifacts1) {
+
+ expect(err).to.not.exist();
+ expect(credentials1.user).to.equal('steve');
+
+ Hawk.server.authenticate(req, credentialsFunc, options, function (err, credentials2, artifacts2) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Invalid nonce');
+ done();
+ });
+ });
+ });
+
+ it('does not error on nonce collision if keys differ', function (done) {
+
+ var reqSteve = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080,
+ authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="bXx7a7p1h9QYQNZ8x7QhvDQym8ACgab4m3lVSFn4DBw=", ext="hello"'
+ };
+
+ var reqBob = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080,
+ authorization: 'Hawk id="456", ts="1353788437", nonce="k3j4h2", mac="LXfmTnRzrLd9TD7yfH+4se46Bx6AHyhpM94hLCiNia4=", ext="hello"'
+ };
+
+ var credentialsFuncion = function (id, callback) {
+
+ var credentials = {
+ '123': {
+ id: id,
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: (id === '1' ? 'sha1' : 'sha256'),
+ user: 'steve'
+ },
+ '456': {
+ id: id,
+ key: 'xrunpaw3489ruxnpa98w4rxnwerxhqb98rpaxn39848',
+ algorithm: (id === '1' ? 'sha1' : 'sha256'),
+ user: 'bob'
+ }
+ };
+
+ return callback(null, credentials[id]);
+ };
+
+ var memoryCache = {};
+ var options = {
+ localtimeOffsetMsec: 1353788437000 - Hawk.utils.now(),
+ nonceFunc: function (key, nonce, ts, callback) {
+
+ if (memoryCache[key + nonce]) {
+ return callback(new Error());
+ }
+
+ memoryCache[key + nonce] = true;
+ return callback();
+ }
+ };
+
+ Hawk.server.authenticate(reqSteve, credentialsFuncion, options, function (err, credentials1, artifacts1) {
+
+ expect(err).to.not.exist();
+ expect(credentials1.user).to.equal('steve');
+
+ Hawk.server.authenticate(reqBob, credentialsFuncion, options, function (err, credentials2, artifacts2) {
+
+ expect(err).to.not.exist();
+ expect(credentials2.user).to.equal('bob');
+ done();
+ });
+ });
+ });
+
+ it('errors on an invalid authentication header: wrong scheme', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080,
+ authorization: 'Basic asdasdasdasd'
+ };
+
+ Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.not.exist();
+ done();
+ });
+ });
+
+ it('errors on an invalid authentication header: no scheme', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080,
+ authorization: '!@#'
+ };
+
+ Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Invalid header syntax');
+ done();
+ });
+ });
+
+ it('errors on an missing authorization header', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080
+ };
+
+ Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
+
+ expect(err).to.exist();
+ expect(err.isMissing).to.equal(true);
+ done();
+ });
+ });
+
+ it('errors on an missing host header', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ headers: {
+ authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
+ }
+ };
+
+ Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Invalid Host header');
+ done();
+ });
+ });
+
+ it('errors on an missing authorization attribute (id)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080,
+ authorization: 'Hawk ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
+ };
+
+ Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Missing attributes');
+ done();
+ });
+ });
+
+ it('errors on an missing authorization attribute (ts)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080,
+ authorization: 'Hawk id="123", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
+ };
+
+ Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Missing attributes');
+ done();
+ });
+ });
+
+ it('errors on an missing authorization attribute (nonce)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080,
+ authorization: 'Hawk id="123", ts="1353788437", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
+ };
+
+ Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Missing attributes');
+ done();
+ });
+ });
+
+ it('errors on an missing authorization attribute (mac)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080,
+ authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", ext="hello"'
+ };
+
+ Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Missing attributes');
+ done();
+ });
+ });
+
+ it('errors on an unknown authorization attribute', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080,
+ authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", x="3", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
+ };
+
+ Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Unknown attribute: x');
+ done();
+ });
+ });
+
+ it('errors on an bad authorization header format', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080,
+ authorization: 'Hawk id="123\\", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
+ };
+
+ Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Bad header format');
+ done();
+ });
+ });
+
+ it('errors on an bad authorization attribute value', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080,
+ authorization: 'Hawk id="\t", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
+ };
+
+ Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Bad attribute value: id');
+ done();
+ });
+ });
+
+ it('errors on an empty authorization attribute value', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080,
+ authorization: 'Hawk id="", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
+ };
+
+ Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Bad attribute value: id');
+ done();
+ });
+ });
+
+ it('errors on duplicated authorization attribute key', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080,
+ authorization: 'Hawk id="123", id="456", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
+ };
+
+ Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Duplicate attribute: id');
+ done();
+ });
+ });
+
+ it('errors on an invalid authorization header format', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080,
+ authorization: 'Hawk'
+ };
+
+ Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Invalid header syntax');
+ done();
+ });
+ });
+
+ it('errors on an bad host header (missing host)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ headers: {
+ host: ':8080',
+ authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
+ }
+ };
+
+ Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Invalid Host header');
+ done();
+ });
+ });
+
+ it('errors on an bad host header (pad port)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ headers: {
+ host: 'example.com:something',
+ authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
+ }
+ };
+
+ Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Invalid Host header');
+ done();
+ });
+ });
+
+ it('errors on credentialsFunc error', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080,
+ authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
+ };
+
+ var credentialsFuncion = function (id, callback) {
+
+ return callback(new Error('Unknown user'));
+ };
+
+ Hawk.server.authenticate(req, credentialsFuncion, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Unknown user');
+ done();
+ });
+ });
+
+ it('errors on credentialsFunc error (with credentials)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080,
+ authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
+ };
+
+ var credentialsFuncion = function (id, callback) {
+
+ return callback(new Error('Unknown user'), { some: 'value' });
+ };
+
+ Hawk.server.authenticate(req, credentialsFuncion, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Unknown user');
+ expect(credentials.some).to.equal('value');
+ done();
+ });
+ });
+
+ it('errors on missing credentials', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080,
+ authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
+ };
+
+ var credentialsFuncion = function (id, callback) {
+
+ return callback(null, null);
+ };
+
+ Hawk.server.authenticate(req, credentialsFuncion, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Unknown credentials');
+ done();
+ });
+ });
+
+ it('errors on invalid credentials (id)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080,
+ authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
+ };
+
+ var credentialsFuncion = function (id, callback) {
+
+ var credentials = {
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ user: 'steve'
+ };
+
+ return callback(null, credentials);
+ };
+
+ Hawk.server.authenticate(req, credentialsFuncion, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Invalid credentials');
+ expect(err.output.payload.message).to.equal('An internal server error occurred');
+ done();
+ });
+ });
+
+ it('errors on invalid credentials (key)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080,
+ authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
+ };
+
+ var credentialsFuncion = function (id, callback) {
+
+ var credentials = {
+ id: '23434d3q4d5345d',
+ user: 'steve'
+ };
+
+ return callback(null, credentials);
+ };
+
+ Hawk.server.authenticate(req, credentialsFuncion, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Invalid credentials');
+ expect(err.output.payload.message).to.equal('An internal server error occurred');
+ done();
+ });
+ });
+
+ it('errors on unknown credentials algorithm', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080,
+ authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
+ };
+
+ var credentialsFuncion = function (id, callback) {
+
+ var credentials = {
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: 'hmac-sha-0',
+ user: 'steve'
+ };
+
+ return callback(null, credentials);
+ };
+
+ Hawk.server.authenticate(req, credentialsFuncion, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Unknown algorithm');
+ expect(err.output.payload.message).to.equal('An internal server error occurred');
+ done();
+ });
+ });
+
+ it('errors on unknown bad mac', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080,
+ authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcU4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
+ };
+
+ var credentialsFuncion = function (id, callback) {
+
+ var credentials = {
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: 'sha256',
+ user: 'steve'
+ };
+
+ return callback(null, credentials);
+ };
+
+ Hawk.server.authenticate(req, credentialsFuncion, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Bad mac');
+ done();
+ });
+ });
+ });
+
+ describe('header()', function () {
+
+ it('generates header', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: 'sha256',
+ user: 'steve'
+ };
+
+ var artifacts = {
+ method: 'POST',
+ host: 'example.com',
+ port: '8080',
+ resource: '/resource/4?filter=a',
+ ts: '1398546787',
+ nonce: 'xUwusx',
+ hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
+ ext: 'some-app-data',
+ mac: 'dvIvMThwi28J61Jc3P0ryAhuKpanU63GXdx6hkmQkJA=',
+ id: '123456'
+ };
+
+ var header = Hawk.server.header(credentials, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' });
+ expect(header).to.equal('Hawk mac=\"n14wVJK4cOxAytPUMc5bPezQzuJGl5n7MYXhFQgEKsE=\", hash=\"f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=\", ext=\"response-specific\"');
+ done();
+ });
+
+ it('generates header (empty payload)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: 'sha256',
+ user: 'steve'
+ };
+
+ var artifacts = {
+ method: 'POST',
+ host: 'example.com',
+ port: '8080',
+ resource: '/resource/4?filter=a',
+ ts: '1398546787',
+ nonce: 'xUwusx',
+ hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
+ ext: 'some-app-data',
+ mac: 'dvIvMThwi28J61Jc3P0ryAhuKpanU63GXdx6hkmQkJA=',
+ id: '123456'
+ };
+
+ var header = Hawk.server.header(credentials, artifacts, { payload: '', contentType: 'text/plain', ext: 'response-specific' });
+ expect(header).to.equal('Hawk mac=\"i8/kUBDx0QF+PpCtW860kkV/fa9dbwEoe/FpGUXowf0=\", hash=\"q/t+NNAkQZNlq/aAD6PlexImwQTxwgT2MahfTa9XRLA=\", ext=\"response-specific\"');
+ done();
+ });
+
+ it('generates header (pre calculated hash)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: 'sha256',
+ user: 'steve'
+ };
+
+ var artifacts = {
+ method: 'POST',
+ host: 'example.com',
+ port: '8080',
+ resource: '/resource/4?filter=a',
+ ts: '1398546787',
+ nonce: 'xUwusx',
+ hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
+ ext: 'some-app-data',
+ mac: 'dvIvMThwi28J61Jc3P0ryAhuKpanU63GXdx6hkmQkJA=',
+ id: '123456'
+ };
+
+ var options = { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' };
+ options.hash = Hawk.crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType);
+ var header = Hawk.server.header(credentials, artifacts, options);
+ expect(header).to.equal('Hawk mac=\"n14wVJK4cOxAytPUMc5bPezQzuJGl5n7MYXhFQgEKsE=\", hash=\"f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=\", ext=\"response-specific\"');
+ done();
+ });
+
+ it('generates header (null ext)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: 'sha256',
+ user: 'steve'
+ };
+
+ var artifacts = {
+ method: 'POST',
+ host: 'example.com',
+ port: '8080',
+ resource: '/resource/4?filter=a',
+ ts: '1398546787',
+ nonce: 'xUwusx',
+ hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
+ mac: 'dvIvMThwi28J61Jc3P0ryAhuKpanU63GXdx6hkmQkJA=',
+ id: '123456'
+ };
+
+ var header = Hawk.server.header(credentials, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: null });
+ expect(header).to.equal('Hawk mac=\"6PrybJTJs20jsgBw5eilXpcytD8kUbaIKNYXL+6g0ns=\", hash=\"f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=\"');
+ done();
+ });
+
+ it('errors on missing artifacts', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: 'sha256',
+ user: 'steve'
+ };
+
+ var header = Hawk.server.header(credentials, null, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' });
+ expect(header).to.equal('');
+ done();
+ });
+
+ it('errors on invalid artifacts', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: 'sha256',
+ user: 'steve'
+ };
+
+ var header = Hawk.server.header(credentials, 5, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' });
+ expect(header).to.equal('');
+ done();
+ });
+
+ it('errors on missing credentials', function (done) {
+
+ var artifacts = {
+ method: 'POST',
+ host: 'example.com',
+ port: '8080',
+ resource: '/resource/4?filter=a',
+ ts: '1398546787',
+ nonce: 'xUwusx',
+ hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
+ ext: 'some-app-data',
+ mac: 'dvIvMThwi28J61Jc3P0ryAhuKpanU63GXdx6hkmQkJA=',
+ id: '123456'
+ };
+
+ var header = Hawk.server.header(null, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' });
+ expect(header).to.equal('');
+ done();
+ });
+
+ it('errors on invalid credentials (key)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ algorithm: 'sha256',
+ user: 'steve'
+ };
+
+ var artifacts = {
+ method: 'POST',
+ host: 'example.com',
+ port: '8080',
+ resource: '/resource/4?filter=a',
+ ts: '1398546787',
+ nonce: 'xUwusx',
+ hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
+ ext: 'some-app-data',
+ mac: 'dvIvMThwi28J61Jc3P0ryAhuKpanU63GXdx6hkmQkJA=',
+ id: '123456'
+ };
+
+ var header = Hawk.server.header(credentials, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' });
+ expect(header).to.equal('');
+ done();
+ });
+
+ it('errors on invalid algorithm', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: 'x',
+ user: 'steve'
+ };
+
+ var artifacts = {
+ method: 'POST',
+ host: 'example.com',
+ port: '8080',
+ resource: '/resource/4?filter=a',
+ ts: '1398546787',
+ nonce: 'xUwusx',
+ hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
+ ext: 'some-app-data',
+ mac: 'dvIvMThwi28J61Jc3P0ryAhuKpanU63GXdx6hkmQkJA=',
+ id: '123456'
+ };
+
+ var header = Hawk.server.header(credentials, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' });
+ expect(header).to.equal('');
+ done();
+ });
+ });
+
+ describe('authenticateBewit()', function () {
+
+ it('errors on uri too long', function (done) {
+
+ var long = '/';
+ for (var i = 0; i < 5000; ++i) {
+ long += 'x';
+ }
+
+ var req = {
+ method: 'GET',
+ url: long,
+ host: 'example.com',
+ port: 8080,
+ authorization: 'Hawk id="1", ts="1353788437", nonce="k3j4h2", mac="zy79QQ5/EYFmQqutVnYb73gAc/U=", ext="hello"'
+ };
+
+ Hawk.server.authenticateBewit(req, credentialsFunc, {}, function (err, credentials, bewit) {
+
+ expect(err).to.exist();
+ expect(err.output.statusCode).to.equal(400);
+ expect(err.message).to.equal('Resource path exceeds max length');
+ done();
+ });
+ });
+ });
+
+ describe('authenticateMessage()', function () {
+
+ it('errors on invalid authorization (ts)', function (done) {
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
+ delete auth.ts;
+
+ Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials2) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Invalid authorization');
+ done();
+ });
+ });
+ });
+
+ it('errors on invalid authorization (nonce)', function (done) {
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
+ delete auth.nonce;
+
+ Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials2) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Invalid authorization');
+ done();
+ });
+ });
+ });
+
+ it('errors on invalid authorization (hash)', function (done) {
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
+ delete auth.hash;
+
+ Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials2) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Invalid authorization');
+ done();
+ });
+ });
+ });
+
+ it('errors with credentials', function (done) {
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
+
+ Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, function (id, callback) {
+
+ callback(new Error('something'), { some: 'value' });
+ }, {}, function (err, credentials2) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('something');
+ expect(credentials2.some).to.equal('value');
+ done();
+ });
+ });
+ });
+
+ it('errors on nonce collision', function (done) {
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
+ Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {
+ nonceFunc: function (key, nonce, ts, nonceCallback) {
+
+ nonceCallback(true);
+ }
+ }, function (err, credentials2) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Invalid nonce');
+ done();
+ });
+ });
+ });
+
+ it('should generate an authorization then successfully parse it', function (done) {
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
+ expect(auth).to.exist();
+
+ Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials2) {
+
+ expect(err).to.not.exist();
+ expect(credentials2.user).to.equal('steve');
+ done();
+ });
+ });
+ });
+
+ it('should fail authorization on mismatching host', function (done) {
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
+ expect(auth).to.exist();
+
+ Hawk.server.authenticateMessage('example1.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials2) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Bad mac');
+ done();
+ });
+ });
+ });
+
+ it('should fail authorization on stale timestamp', function (done) {
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
+ expect(auth).to.exist();
+
+ Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, { localtimeOffsetMsec: 100000 }, function (err, credentials2) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Stale timestamp');
+ done();
+ });
+ });
+ });
+
+ it('overrides timestampSkewSec', function (done) {
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1, localtimeOffsetMsec: 100000 });
+ expect(auth).to.exist();
+
+ Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, { timestampSkewSec: 500 }, function (err, credentials2) {
+
+ expect(err).to.not.exist();
+ done();
+ });
+ });
+ });
+
+ it('should fail authorization on invalid authorization', function (done) {
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
+ expect(auth).to.exist();
+ delete auth.id;
+
+ Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials2) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Invalid authorization');
+ done();
+ });
+ });
+ });
+
+ it('should fail authorization on bad hash', function (done) {
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
+ expect(auth).to.exist();
+
+ Hawk.server.authenticateMessage('example.com', 8080, 'some message1', auth, credentialsFunc, {}, function (err, credentials2) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Bad message hash');
+ done();
+ });
+ });
+ });
+
+ it('should fail authorization on nonce error', function (done) {
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
+ expect(auth).to.exist();
+
+ Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {
+ nonceFunc: function (key, nonce, ts, callback) {
+
+ callback(new Error('kaboom'));
+ }
+ }, function (err, credentials2) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Invalid nonce');
+ done();
+ });
+ });
+ });
+
+ it('should fail authorization on credentials error', function (done) {
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
+ expect(auth).to.exist();
+
+ var errFunc = function (id, callback) {
+
+ callback(new Error('kablooey'));
+ };
+
+ Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, errFunc, {}, function (err, credentials2) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('kablooey');
+ done();
+ });
+ });
+ });
+
+ it('should fail authorization on missing credentials', function (done) {
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
+ expect(auth).to.exist();
+
+ var errFunc = function (id, callback) {
+
+ callback();
+ };
+
+ Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, errFunc, {}, function (err, credentials2) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Unknown credentials');
+ done();
+ });
+ });
+ });
+
+ it('should fail authorization on invalid credentials', function (done) {
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
+ expect(auth).to.exist();
+
+ var errFunc = function (id, callback) {
+
+ callback(null, {});
+ };
+
+ Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, errFunc, {}, function (err, credentials2) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Invalid credentials');
+ done();
+ });
+ });
+ });
+
+ it('should fail authorization on invalid credentials algorithm', function (done) {
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
+ expect(auth).to.exist();
+
+ var errFunc = function (id, callback) {
+
+ callback(null, { key: '123', algorithm: '456' });
+ };
+
+ Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, errFunc, {}, function (err, credentials2) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Unknown algorithm');
+ done();
+ });
+ });
+ });
+
+ it('should fail on missing host', function (done) {
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var auth = Hawk.client.message(null, 8080, 'some message', { credentials: credentials });
+ expect(auth).to.not.exist();
+ done();
+ });
+ });
+
+ it('should fail on missing credentials', function (done) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', {});
+ expect(auth).to.not.exist();
+ done();
+ });
+
+ it('should fail on invalid algorithm', function (done) {
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var creds = Hoek.clone(credentials);
+ creds.algorithm = 'blah';
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: creds });
+ expect(auth).to.not.exist();
+ done();
+ });
+ });
+ });
+
+ describe('authenticatePayloadHash()', function () {
+
+ it('checks payload hash', function (done) {
+
+ expect(Hawk.server.authenticatePayloadHash('abcdefg', { hash: 'abcdefg' })).to.equal(true);
+ expect(Hawk.server.authenticatePayloadHash('1234567', { hash: 'abcdefg' })).to.equal(false);
+ done();
+ });
+ });
+});
+
diff --git a/node_modules/request/node_modules/hawk/test/uri.js b/node_modules/request/node_modules/hawk/test/uri.js
index f3c6ba2d6..dee7c6432 100755
--- a/node_modules/request/node_modules/hawk/test/uri.js
+++ b/node_modules/request/node_modules/hawk/test/uri.js
@@ -1,838 +1,838 @@
-// Load modules
-
-var Http = require('http');
-var Url = require('url');
-var Code = require('code');
-var Hawk = require('../lib');
-var Hoek = require('hoek');
-var Lab = require('lab');
-
-
-// Declare internals
-
-var internals = {};
-
-
-// Test shortcuts
-
-var lab = exports.lab = Lab.script();
-var describe = lab.experiment;
-var it = lab.test;
-var expect = Code.expect;
-
-
-describe('Uri', function () {
-
- var credentialsFunc = function (id, callback) {
-
- var credentials = {
- id: id,
- key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
- algorithm: (id === '1' ? 'sha1' : 'sha256'),
- user: 'steve'
- };
-
- return callback(null, credentials);
- };
-
- it('should generate a bewit then successfully authenticate it', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?a=1&b=2',
- host: 'example.com',
- port: 80
- };
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var bewit = Hawk.uri.getBewit('http://example.com/resource/4?a=1&b=2', { credentials: credentials1, ttlSec: 60 * 60 * 24 * 365 * 100, ext: 'some-app-data' });
- req.url += '&bewit=' + bewit;
-
- Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials2, attributes) {
-
- expect(err).to.not.exist();
- expect(credentials2.user).to.equal('steve');
- expect(attributes.ext).to.equal('some-app-data');
- done();
- });
- });
- });
-
- it('should generate a bewit then successfully authenticate it (no ext)', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?a=1&b=2',
- host: 'example.com',
- port: 80
- };
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var bewit = Hawk.uri.getBewit('http://example.com/resource/4?a=1&b=2', { credentials: credentials1, ttlSec: 60 * 60 * 24 * 365 * 100 });
- req.url += '&bewit=' + bewit;
-
- Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials2, attributes) {
-
- expect(err).to.not.exist();
- expect(credentials2.user).to.equal('steve');
- done();
- });
- });
- });
-
- it('should successfully authenticate a request (last param)', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?a=1&b=2&bewit=MTIzNDU2XDQ1MTE0ODQ2MjFcMzFjMmNkbUJFd1NJRVZDOVkva1NFb2c3d3YrdEVNWjZ3RXNmOGNHU2FXQT1cc29tZS1hcHAtZGF0YQ',
- host: 'example.com',
- port: 8080
- };
-
- Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
-
- expect(err).to.not.exist();
- expect(credentials.user).to.equal('steve');
- expect(attributes.ext).to.equal('some-app-data');
- done();
- });
- });
-
- it('should successfully authenticate a request (first param)', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?bewit=MTIzNDU2XDQ1MTE0ODQ2MjFcMzFjMmNkbUJFd1NJRVZDOVkva1NFb2c3d3YrdEVNWjZ3RXNmOGNHU2FXQT1cc29tZS1hcHAtZGF0YQ&a=1&b=2',
- host: 'example.com',
- port: 8080
- };
-
- Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
-
- expect(err).to.not.exist();
- expect(credentials.user).to.equal('steve');
- expect(attributes.ext).to.equal('some-app-data');
- done();
- });
- });
-
- it('should successfully authenticate a request (only param)', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?bewit=MTIzNDU2XDQ1MTE0ODQ2NDFcZm1CdkNWT3MvcElOTUUxSTIwbWhrejQ3UnBwTmo4Y1VrSHpQd3Q5OXJ1cz1cc29tZS1hcHAtZGF0YQ',
- host: 'example.com',
- port: 8080
- };
-
- Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
-
- expect(err).to.not.exist();
- expect(credentials.user).to.equal('steve');
- expect(attributes.ext).to.equal('some-app-data');
- done();
- });
- });
-
- it('should fail on multiple authentication', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?bewit=MTIzNDU2XDQ1MTE0ODQ2NDFcZm1CdkNWT3MvcElOTUUxSTIwbWhrejQ3UnBwTmo4Y1VrSHpQd3Q5OXJ1cz1cc29tZS1hcHAtZGF0YQ',
- host: 'example.com',
- port: 8080,
- authorization: 'Basic asdasdasdasd'
- };
-
- Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Multiple authentications');
- done();
- });
- });
-
- it('should fail on method other than GET', function (done) {
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var req = {
- method: 'POST',
- url: '/resource/4?filter=a',
- host: 'example.com',
- port: 8080
- };
-
- var exp = Math.floor(Hawk.utils.now() / 1000) + 60;
- var ext = 'some-app-data';
- var mac = Hawk.crypto.calculateMac('bewit', credentials1, {
- timestamp: exp,
- nonce: '',
- method: req.method,
- resource: req.url,
- host: req.host,
- port: req.port,
- ext: ext
- });
-
- var bewit = credentials1.id + '\\' + exp + '\\' + mac + '\\' + ext;
-
- req.url += '&bewit=' + Hoek.base64urlEncode(bewit);
-
- Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials2, attributes) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Invalid method');
- done();
- });
- });
- });
-
- it('should fail on invalid host header', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?bewit=MTIzNDU2XDQ1MDk5OTE3MTlcTUE2eWkwRWRwR0pEcWRwb0JkYVdvVDJrL0hDSzA1T0Y3MkhuZlVmVy96Zz1cc29tZS1hcHAtZGF0YQ',
- headers: {
- host: 'example.com:something'
- }
- };
-
- Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Invalid Host header');
- done();
- });
- });
-
- it('should fail on empty bewit', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?bewit=',
- host: 'example.com',
- port: 8080
- };
-
- Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Empty bewit');
- expect(err.isMissing).to.not.exist();
- done();
- });
- });
-
- it('should fail on invalid bewit', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?bewit=*',
- host: 'example.com',
- port: 8080
- };
-
- Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Invalid bewit encoding');
- expect(err.isMissing).to.not.exist();
- done();
- });
- });
-
- it('should fail on missing bewit', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4',
- host: 'example.com',
- port: 8080
- };
-
- Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.not.exist();
- expect(err.isMissing).to.equal(true);
- done();
- });
- });
-
- it('should fail on invalid bewit structure', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?bewit=abc',
- host: 'example.com',
- port: 8080
- };
-
- Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Invalid bewit structure');
- done();
- });
- });
-
- it('should fail on empty bewit attribute', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?bewit=YVxcY1xk',
- host: 'example.com',
- port: 8080
- };
-
- Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Missing bewit attributes');
- done();
- });
- });
-
- it('should fail on missing bewit id attribute', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?bewit=XDQ1NTIxNDc2MjJcK0JFbFhQMXhuWjcvd1Nrbm1ldGhlZm5vUTNHVjZNSlFVRHk4NWpTZVJ4VT1cc29tZS1hcHAtZGF0YQ',
- host: 'example.com',
- port: 8080
- };
-
- Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Missing bewit attributes');
- done();
- });
- });
-
- it('should fail on expired access', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?a=1&b=2&bewit=MTIzNDU2XDEzNTY0MTg1ODNcWk1wZlMwWU5KNHV0WHpOMmRucTRydEk3NXNXTjFjeWVITTcrL0tNZFdVQT1cc29tZS1hcHAtZGF0YQ',
- host: 'example.com',
- port: 8080
- };
-
- Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Access expired');
- done();
- });
- });
-
- it('should fail on credentials function error', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?bewit=MTIzNDU2XDQ1MDk5OTE3MTlcTUE2eWkwRWRwR0pEcWRwb0JkYVdvVDJrL0hDSzA1T0Y3MkhuZlVmVy96Zz1cc29tZS1hcHAtZGF0YQ',
- host: 'example.com',
- port: 8080
- };
-
- Hawk.uri.authenticate(req, function (id, callback) {
-
- callback(Hawk.error.badRequest('Boom'));
- }, {}, function (err, credentials, attributes) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Boom');
- done();
- });
- });
-
- it('should fail on credentials function error with credentials', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?bewit=MTIzNDU2XDQ1MDk5OTE3MTlcTUE2eWkwRWRwR0pEcWRwb0JkYVdvVDJrL0hDSzA1T0Y3MkhuZlVmVy96Zz1cc29tZS1hcHAtZGF0YQ',
- host: 'example.com',
- port: 8080
- };
-
- Hawk.uri.authenticate(req, function (id, callback) {
-
- callback(Hawk.error.badRequest('Boom'), { some: 'value' });
- }, {}, function (err, credentials, attributes) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Boom');
- expect(credentials.some).to.equal('value');
- done();
- });
- });
-
- it('should fail on null credentials function response', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?bewit=MTIzNDU2XDQ1MDk5OTE3MTlcTUE2eWkwRWRwR0pEcWRwb0JkYVdvVDJrL0hDSzA1T0Y3MkhuZlVmVy96Zz1cc29tZS1hcHAtZGF0YQ',
- host: 'example.com',
- port: 8080
- };
-
- Hawk.uri.authenticate(req, function (id, callback) {
-
- callback(null, null);
- }, {}, function (err, credentials, attributes) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Unknown credentials');
- done();
- });
- });
-
- it('should fail on invalid credentials function response', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?bewit=MTIzNDU2XDQ1MDk5OTE3MTlcTUE2eWkwRWRwR0pEcWRwb0JkYVdvVDJrL0hDSzA1T0Y3MkhuZlVmVy96Zz1cc29tZS1hcHAtZGF0YQ',
- host: 'example.com',
- port: 8080
- };
-
- Hawk.uri.authenticate(req, function (id, callback) {
-
- callback(null, {});
- }, {}, function (err, credentials, attributes) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('Invalid credentials');
- done();
- });
- });
-
- it('should fail on invalid credentials function response (unknown algorithm)', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?bewit=MTIzNDU2XDQ1MDk5OTE3MTlcTUE2eWkwRWRwR0pEcWRwb0JkYVdvVDJrL0hDSzA1T0Y3MkhuZlVmVy96Zz1cc29tZS1hcHAtZGF0YQ',
- host: 'example.com',
- port: 8080
- };
-
- Hawk.uri.authenticate(req, function (id, callback) {
-
- callback(null, { key: 'xxx', algorithm: 'xxx' });
- }, {}, function (err, credentials, attributes) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('Unknown algorithm');
- done();
- });
- });
-
- it('should fail on expired access', function (done) {
-
- var req = {
- method: 'GET',
- url: '/resource/4?bewit=MTIzNDU2XDQ1MDk5OTE3MTlcTUE2eWkwRWRwR0pEcWRwb0JkYVdvVDJrL0hDSzA1T0Y3MkhuZlVmVy96Zz1cc29tZS1hcHAtZGF0YQ',
- host: 'example.com',
- port: 8080
- };
-
- Hawk.uri.authenticate(req, function (id, callback) {
-
- callback(null, { key: 'xxx', algorithm: 'sha256' });
- }, {}, function (err, credentials, attributes) {
-
- expect(err).to.exist();
- expect(err.output.payload.message).to.equal('Bad mac');
- done();
- });
- });
-
- describe('getBewit()', function () {
-
- it('returns a valid bewit value', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var bewit = Hawk.uri.getBewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' });
- expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdca3NjeHdOUjJ0SnBQMVQxekRMTlBiQjVVaUtJVTl0T1NKWFRVZEc3WDloOD1ceGFuZHlhbmR6');
- done();
- });
-
- it('returns a valid bewit value (explicit port)', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var bewit = Hawk.uri.getBewit('https://example.com:8080/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' });
- expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdcaFpiSjNQMmNLRW80a3kwQzhqa1pBa1J5Q1p1ZWc0V1NOYnhWN3ZxM3hIVT1ceGFuZHlhbmR6');
- done();
- });
-
- it('returns a valid bewit value (null ext)', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var bewit = Hawk.uri.getBewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: null });
- expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdcSUdZbUxnSXFMckNlOEN4dktQczRKbFdJQStValdKSm91d2dBUmlWaENBZz1c');
- done();
- });
-
- it('returns a valid bewit value (parsed uri)', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var bewit = Hawk.uri.getBewit(Url.parse('https://example.com/somewhere/over/the/rainbow'), { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' });
- expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdca3NjeHdOUjJ0SnBQMVQxekRMTlBiQjVVaUtJVTl0T1NKWFRVZEc3WDloOD1ceGFuZHlhbmR6');
- done();
- });
-
- it('errors on invalid options', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var bewit = Hawk.uri.getBewit('https://example.com/somewhere/over/the/rainbow', 4);
- expect(bewit).to.equal('');
- done();
- });
-
- it('errors on missing uri', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var bewit = Hawk.uri.getBewit('', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' });
- expect(bewit).to.equal('');
- done();
- });
-
- it('errors on invalid uri', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var bewit = Hawk.uri.getBewit(5, { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' });
- expect(bewit).to.equal('');
- done();
- });
-
- it('errors on invalid credentials (id)', function (done) {
-
- var credentials = {
- key: '2983d45yun89q',
- algorithm: 'sha256'
- };
-
- var bewit = Hawk.uri.getBewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 3000, ext: 'xandyandz' });
- expect(bewit).to.equal('');
- done();
- });
-
- it('errors on missing credentials', function (done) {
-
- var bewit = Hawk.uri.getBewit('https://example.com/somewhere/over/the/rainbow', { ttlSec: 3000, ext: 'xandyandz' });
- expect(bewit).to.equal('');
- done();
- });
-
- it('errors on invalid credentials (key)', function (done) {
-
- var credentials = {
- id: '123456',
- algorithm: 'sha256'
- };
-
- var bewit = Hawk.uri.getBewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 3000, ext: 'xandyandz' });
- expect(bewit).to.equal('');
- done();
- });
-
- it('errors on invalid algorithm', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'hmac-sha-0'
- };
-
- var bewit = Hawk.uri.getBewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, ext: 'xandyandz' });
- expect(bewit).to.equal('');
- done();
- });
-
- it('errors on missing options', function (done) {
-
- var credentials = {
- id: '123456',
- key: '2983d45yun89q',
- algorithm: 'hmac-sha-0'
- };
-
- var bewit = Hawk.uri.getBewit('https://example.com/somewhere/over/the/rainbow');
- expect(bewit).to.equal('');
- done();
- });
- });
-
- describe('authenticateMessage()', function () {
-
- it('should generate an authorization then successfully parse it', function (done) {
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
- expect(auth).to.exist();
-
- Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials2) {
-
- expect(err).to.not.exist();
- expect(credentials2.user).to.equal('steve');
- done();
- });
- });
- });
-
- it('should fail authorization on mismatching host', function (done) {
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
- expect(auth).to.exist();
-
- Hawk.server.authenticateMessage('example1.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials2) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('Bad mac');
- done();
- });
- });
- });
-
- it('should fail authorization on stale timestamp', function (done) {
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
- expect(auth).to.exist();
-
- Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, { localtimeOffsetMsec: 100000 }, function (err, credentials2) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('Stale timestamp');
- done();
- });
- });
- });
-
- it('overrides timestampSkewSec', function (done) {
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1, localtimeOffsetMsec: 100000 });
- expect(auth).to.exist();
-
- Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, { timestampSkewSec: 500 }, function (err, credentials2) {
-
- expect(err).to.not.exist();
- done();
- });
- });
- });
-
- it('should fail authorization on invalid authorization', function (done) {
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
- expect(auth).to.exist();
- delete auth.id;
-
- Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials2) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('Invalid authorization');
- done();
- });
- });
- });
-
- it('should fail authorization on bad hash', function (done) {
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
- expect(auth).to.exist();
-
- Hawk.server.authenticateMessage('example.com', 8080, 'some message1', auth, credentialsFunc, {}, function (err, credentials2) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('Bad message hash');
- done();
- });
- });
- });
-
- it('should fail authorization on nonce error', function (done) {
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
- expect(auth).to.exist();
-
- Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {
- nonceFunc: function (key, nonce, ts, callback) {
-
- callback(new Error('kaboom'));
- }
- }, function (err, credentials2) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('Invalid nonce');
- done();
- });
- });
- });
-
- it('should fail authorization on credentials error', function (done) {
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
- expect(auth).to.exist();
-
- var errFunc = function (id, callback) {
-
- callback(new Error('kablooey'));
- };
-
- Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, errFunc, {}, function (err, credentials2) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('kablooey');
- done();
- });
- });
- });
-
- it('should fail authorization on missing credentials', function (done) {
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
- expect(auth).to.exist();
-
- var errFunc = function (id, callback) {
-
- callback();
- };
-
- Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, errFunc, {}, function (err, credentials2) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('Unknown credentials');
- done();
- });
- });
- });
-
- it('should fail authorization on invalid credentials', function (done) {
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
- expect(auth).to.exist();
-
- var errFunc = function (id, callback) {
-
- callback(null, {});
- };
-
- Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, errFunc, {}, function (err, credentials2) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('Invalid credentials');
- done();
- });
- });
- });
-
- it('should fail authorization on invalid credentials algorithm', function (done) {
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
- expect(auth).to.exist();
-
- var errFunc = function (id, callback) {
-
- callback(null, { key: '123', algorithm: '456' });
- };
-
- Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, errFunc, {}, function (err, credentials2) {
-
- expect(err).to.exist();
- expect(err.message).to.equal('Unknown algorithm');
- done();
- });
- });
- });
-
- it('should fail on missing host', function (done) {
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var auth = Hawk.client.message(null, 8080, 'some message', { credentials: credentials1 });
- expect(auth).to.not.exist();
- done();
- });
- });
-
- it('should fail on missing credentials', function (done) {
-
- var auth = Hawk.client.message('example.com', 8080, 'some message', {});
- expect(auth).to.not.exist();
- done();
- });
-
- it('should fail on invalid algorithm', function (done) {
-
- credentialsFunc('123456', function (err, credentials1) {
-
- var creds = Hoek.clone(credentials1);
- creds.algorithm = 'blah';
- var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: creds });
- expect(auth).to.not.exist();
- done();
- });
- });
- });
-});
-
+// Load modules
+
+var Http = require('http');
+var Url = require('url');
+var Code = require('code');
+var Hawk = require('../lib');
+var Hoek = require('hoek');
+var Lab = require('lab');
+
+
+// Declare internals
+
+var internals = {};
+
+
+// Test shortcuts
+
+var lab = exports.lab = Lab.script();
+var describe = lab.experiment;
+var it = lab.test;
+var expect = Code.expect;
+
+
+describe('Uri', function () {
+
+ var credentialsFunc = function (id, callback) {
+
+ var credentials = {
+ id: id,
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: (id === '1' ? 'sha1' : 'sha256'),
+ user: 'steve'
+ };
+
+ return callback(null, credentials);
+ };
+
+ it('should generate a bewit then successfully authenticate it', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?a=1&b=2',
+ host: 'example.com',
+ port: 80
+ };
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var bewit = Hawk.uri.getBewit('http://example.com/resource/4?a=1&b=2', { credentials: credentials1, ttlSec: 60 * 60 * 24 * 365 * 100, ext: 'some-app-data' });
+ req.url += '&bewit=' + bewit;
+
+ Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials2, attributes) {
+
+ expect(err).to.not.exist();
+ expect(credentials2.user).to.equal('steve');
+ expect(attributes.ext).to.equal('some-app-data');
+ done();
+ });
+ });
+ });
+
+ it('should generate a bewit then successfully authenticate it (no ext)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?a=1&b=2',
+ host: 'example.com',
+ port: 80
+ };
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var bewit = Hawk.uri.getBewit('http://example.com/resource/4?a=1&b=2', { credentials: credentials1, ttlSec: 60 * 60 * 24 * 365 * 100 });
+ req.url += '&bewit=' + bewit;
+
+ Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials2, attributes) {
+
+ expect(err).to.not.exist();
+ expect(credentials2.user).to.equal('steve');
+ done();
+ });
+ });
+ });
+
+ it('should successfully authenticate a request (last param)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?a=1&b=2&bewit=MTIzNDU2XDQ1MTE0ODQ2MjFcMzFjMmNkbUJFd1NJRVZDOVkva1NFb2c3d3YrdEVNWjZ3RXNmOGNHU2FXQT1cc29tZS1hcHAtZGF0YQ',
+ host: 'example.com',
+ port: 8080
+ };
+
+ Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
+
+ expect(err).to.not.exist();
+ expect(credentials.user).to.equal('steve');
+ expect(attributes.ext).to.equal('some-app-data');
+ done();
+ });
+ });
+
+ it('should successfully authenticate a request (first param)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?bewit=MTIzNDU2XDQ1MTE0ODQ2MjFcMzFjMmNkbUJFd1NJRVZDOVkva1NFb2c3d3YrdEVNWjZ3RXNmOGNHU2FXQT1cc29tZS1hcHAtZGF0YQ&a=1&b=2',
+ host: 'example.com',
+ port: 8080
+ };
+
+ Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
+
+ expect(err).to.not.exist();
+ expect(credentials.user).to.equal('steve');
+ expect(attributes.ext).to.equal('some-app-data');
+ done();
+ });
+ });
+
+ it('should successfully authenticate a request (only param)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?bewit=MTIzNDU2XDQ1MTE0ODQ2NDFcZm1CdkNWT3MvcElOTUUxSTIwbWhrejQ3UnBwTmo4Y1VrSHpQd3Q5OXJ1cz1cc29tZS1hcHAtZGF0YQ',
+ host: 'example.com',
+ port: 8080
+ };
+
+ Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
+
+ expect(err).to.not.exist();
+ expect(credentials.user).to.equal('steve');
+ expect(attributes.ext).to.equal('some-app-data');
+ done();
+ });
+ });
+
+ it('should fail on multiple authentication', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?bewit=MTIzNDU2XDQ1MTE0ODQ2NDFcZm1CdkNWT3MvcElOTUUxSTIwbWhrejQ3UnBwTmo4Y1VrSHpQd3Q5OXJ1cz1cc29tZS1hcHAtZGF0YQ',
+ host: 'example.com',
+ port: 8080,
+ authorization: 'Basic asdasdasdasd'
+ };
+
+ Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Multiple authentications');
+ done();
+ });
+ });
+
+ it('should fail on method other than GET', function (done) {
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var req = {
+ method: 'POST',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080
+ };
+
+ var exp = Math.floor(Hawk.utils.now() / 1000) + 60;
+ var ext = 'some-app-data';
+ var mac = Hawk.crypto.calculateMac('bewit', credentials1, {
+ timestamp: exp,
+ nonce: '',
+ method: req.method,
+ resource: req.url,
+ host: req.host,
+ port: req.port,
+ ext: ext
+ });
+
+ var bewit = credentials1.id + '\\' + exp + '\\' + mac + '\\' + ext;
+
+ req.url += '&bewit=' + Hoek.base64urlEncode(bewit);
+
+ Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials2, attributes) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Invalid method');
+ done();
+ });
+ });
+ });
+
+ it('should fail on invalid host header', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?bewit=MTIzNDU2XDQ1MDk5OTE3MTlcTUE2eWkwRWRwR0pEcWRwb0JkYVdvVDJrL0hDSzA1T0Y3MkhuZlVmVy96Zz1cc29tZS1hcHAtZGF0YQ',
+ headers: {
+ host: 'example.com:something'
+ }
+ };
+
+ Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Invalid Host header');
+ done();
+ });
+ });
+
+ it('should fail on empty bewit', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?bewit=',
+ host: 'example.com',
+ port: 8080
+ };
+
+ Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Empty bewit');
+ expect(err.isMissing).to.not.exist();
+ done();
+ });
+ });
+
+ it('should fail on invalid bewit', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?bewit=*',
+ host: 'example.com',
+ port: 8080
+ };
+
+ Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Invalid bewit encoding');
+ expect(err.isMissing).to.not.exist();
+ done();
+ });
+ });
+
+ it('should fail on missing bewit', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4',
+ host: 'example.com',
+ port: 8080
+ };
+
+ Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.not.exist();
+ expect(err.isMissing).to.equal(true);
+ done();
+ });
+ });
+
+ it('should fail on invalid bewit structure', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?bewit=abc',
+ host: 'example.com',
+ port: 8080
+ };
+
+ Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Invalid bewit structure');
+ done();
+ });
+ });
+
+ it('should fail on empty bewit attribute', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?bewit=YVxcY1xk',
+ host: 'example.com',
+ port: 8080
+ };
+
+ Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Missing bewit attributes');
+ done();
+ });
+ });
+
+ it('should fail on missing bewit id attribute', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?bewit=XDQ1NTIxNDc2MjJcK0JFbFhQMXhuWjcvd1Nrbm1ldGhlZm5vUTNHVjZNSlFVRHk4NWpTZVJ4VT1cc29tZS1hcHAtZGF0YQ',
+ host: 'example.com',
+ port: 8080
+ };
+
+ Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Missing bewit attributes');
+ done();
+ });
+ });
+
+ it('should fail on expired access', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?a=1&b=2&bewit=MTIzNDU2XDEzNTY0MTg1ODNcWk1wZlMwWU5KNHV0WHpOMmRucTRydEk3NXNXTjFjeWVITTcrL0tNZFdVQT1cc29tZS1hcHAtZGF0YQ',
+ host: 'example.com',
+ port: 8080
+ };
+
+ Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Access expired');
+ done();
+ });
+ });
+
+ it('should fail on credentials function error', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?bewit=MTIzNDU2XDQ1MDk5OTE3MTlcTUE2eWkwRWRwR0pEcWRwb0JkYVdvVDJrL0hDSzA1T0Y3MkhuZlVmVy96Zz1cc29tZS1hcHAtZGF0YQ',
+ host: 'example.com',
+ port: 8080
+ };
+
+ Hawk.uri.authenticate(req, function (id, callback) {
+
+ callback(Hawk.error.badRequest('Boom'));
+ }, {}, function (err, credentials, attributes) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Boom');
+ done();
+ });
+ });
+
+ it('should fail on credentials function error with credentials', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?bewit=MTIzNDU2XDQ1MDk5OTE3MTlcTUE2eWkwRWRwR0pEcWRwb0JkYVdvVDJrL0hDSzA1T0Y3MkhuZlVmVy96Zz1cc29tZS1hcHAtZGF0YQ',
+ host: 'example.com',
+ port: 8080
+ };
+
+ Hawk.uri.authenticate(req, function (id, callback) {
+
+ callback(Hawk.error.badRequest('Boom'), { some: 'value' });
+ }, {}, function (err, credentials, attributes) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Boom');
+ expect(credentials.some).to.equal('value');
+ done();
+ });
+ });
+
+ it('should fail on null credentials function response', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?bewit=MTIzNDU2XDQ1MDk5OTE3MTlcTUE2eWkwRWRwR0pEcWRwb0JkYVdvVDJrL0hDSzA1T0Y3MkhuZlVmVy96Zz1cc29tZS1hcHAtZGF0YQ',
+ host: 'example.com',
+ port: 8080
+ };
+
+ Hawk.uri.authenticate(req, function (id, callback) {
+
+ callback(null, null);
+ }, {}, function (err, credentials, attributes) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Unknown credentials');
+ done();
+ });
+ });
+
+ it('should fail on invalid credentials function response', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?bewit=MTIzNDU2XDQ1MDk5OTE3MTlcTUE2eWkwRWRwR0pEcWRwb0JkYVdvVDJrL0hDSzA1T0Y3MkhuZlVmVy96Zz1cc29tZS1hcHAtZGF0YQ',
+ host: 'example.com',
+ port: 8080
+ };
+
+ Hawk.uri.authenticate(req, function (id, callback) {
+
+ callback(null, {});
+ }, {}, function (err, credentials, attributes) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Invalid credentials');
+ done();
+ });
+ });
+
+ it('should fail on invalid credentials function response (unknown algorithm)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?bewit=MTIzNDU2XDQ1MDk5OTE3MTlcTUE2eWkwRWRwR0pEcWRwb0JkYVdvVDJrL0hDSzA1T0Y3MkhuZlVmVy96Zz1cc29tZS1hcHAtZGF0YQ',
+ host: 'example.com',
+ port: 8080
+ };
+
+ Hawk.uri.authenticate(req, function (id, callback) {
+
+ callback(null, { key: 'xxx', algorithm: 'xxx' });
+ }, {}, function (err, credentials, attributes) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Unknown algorithm');
+ done();
+ });
+ });
+
+ it('should fail on expired access', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?bewit=MTIzNDU2XDQ1MDk5OTE3MTlcTUE2eWkwRWRwR0pEcWRwb0JkYVdvVDJrL0hDSzA1T0Y3MkhuZlVmVy96Zz1cc29tZS1hcHAtZGF0YQ',
+ host: 'example.com',
+ port: 8080
+ };
+
+ Hawk.uri.authenticate(req, function (id, callback) {
+
+ callback(null, { key: 'xxx', algorithm: 'sha256' });
+ }, {}, function (err, credentials, attributes) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Bad mac');
+ done();
+ });
+ });
+
+ describe('getBewit()', function () {
+
+ it('returns a valid bewit value', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Hawk.uri.getBewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' });
+ expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdca3NjeHdOUjJ0SnBQMVQxekRMTlBiQjVVaUtJVTl0T1NKWFRVZEc3WDloOD1ceGFuZHlhbmR6');
+ done();
+ });
+
+ it('returns a valid bewit value (explicit port)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Hawk.uri.getBewit('https://example.com:8080/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' });
+ expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdcaFpiSjNQMmNLRW80a3kwQzhqa1pBa1J5Q1p1ZWc0V1NOYnhWN3ZxM3hIVT1ceGFuZHlhbmR6');
+ done();
+ });
+
+ it('returns a valid bewit value (null ext)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Hawk.uri.getBewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: null });
+ expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdcSUdZbUxnSXFMckNlOEN4dktQczRKbFdJQStValdKSm91d2dBUmlWaENBZz1c');
+ done();
+ });
+
+ it('returns a valid bewit value (parsed uri)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Hawk.uri.getBewit(Url.parse('https://example.com/somewhere/over/the/rainbow'), { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' });
+ expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdca3NjeHdOUjJ0SnBQMVQxekRMTlBiQjVVaUtJVTl0T1NKWFRVZEc3WDloOD1ceGFuZHlhbmR6');
+ done();
+ });
+
+ it('errors on invalid options', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Hawk.uri.getBewit('https://example.com/somewhere/over/the/rainbow', 4);
+ expect(bewit).to.equal('');
+ done();
+ });
+
+ it('errors on missing uri', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Hawk.uri.getBewit('', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' });
+ expect(bewit).to.equal('');
+ done();
+ });
+
+ it('errors on invalid uri', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Hawk.uri.getBewit(5, { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' });
+ expect(bewit).to.equal('');
+ done();
+ });
+
+ it('errors on invalid credentials (id)', function (done) {
+
+ var credentials = {
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Hawk.uri.getBewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 3000, ext: 'xandyandz' });
+ expect(bewit).to.equal('');
+ done();
+ });
+
+ it('errors on missing credentials', function (done) {
+
+ var bewit = Hawk.uri.getBewit('https://example.com/somewhere/over/the/rainbow', { ttlSec: 3000, ext: 'xandyandz' });
+ expect(bewit).to.equal('');
+ done();
+ });
+
+ it('errors on invalid credentials (key)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Hawk.uri.getBewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 3000, ext: 'xandyandz' });
+ expect(bewit).to.equal('');
+ done();
+ });
+
+ it('errors on invalid algorithm', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'hmac-sha-0'
+ };
+
+ var bewit = Hawk.uri.getBewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, ext: 'xandyandz' });
+ expect(bewit).to.equal('');
+ done();
+ });
+
+ it('errors on missing options', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'hmac-sha-0'
+ };
+
+ var bewit = Hawk.uri.getBewit('https://example.com/somewhere/over/the/rainbow');
+ expect(bewit).to.equal('');
+ done();
+ });
+ });
+
+ describe('authenticateMessage()', function () {
+
+ it('should generate an authorization then successfully parse it', function (done) {
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
+ expect(auth).to.exist();
+
+ Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials2) {
+
+ expect(err).to.not.exist();
+ expect(credentials2.user).to.equal('steve');
+ done();
+ });
+ });
+ });
+
+ it('should fail authorization on mismatching host', function (done) {
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
+ expect(auth).to.exist();
+
+ Hawk.server.authenticateMessage('example1.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials2) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Bad mac');
+ done();
+ });
+ });
+ });
+
+ it('should fail authorization on stale timestamp', function (done) {
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
+ expect(auth).to.exist();
+
+ Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, { localtimeOffsetMsec: 100000 }, function (err, credentials2) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Stale timestamp');
+ done();
+ });
+ });
+ });
+
+ it('overrides timestampSkewSec', function (done) {
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1, localtimeOffsetMsec: 100000 });
+ expect(auth).to.exist();
+
+ Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, { timestampSkewSec: 500 }, function (err, credentials2) {
+
+ expect(err).to.not.exist();
+ done();
+ });
+ });
+ });
+
+ it('should fail authorization on invalid authorization', function (done) {
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
+ expect(auth).to.exist();
+ delete auth.id;
+
+ Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials2) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Invalid authorization');
+ done();
+ });
+ });
+ });
+
+ it('should fail authorization on bad hash', function (done) {
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
+ expect(auth).to.exist();
+
+ Hawk.server.authenticateMessage('example.com', 8080, 'some message1', auth, credentialsFunc, {}, function (err, credentials2) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Bad message hash');
+ done();
+ });
+ });
+ });
+
+ it('should fail authorization on nonce error', function (done) {
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
+ expect(auth).to.exist();
+
+ Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {
+ nonceFunc: function (key, nonce, ts, callback) {
+
+ callback(new Error('kaboom'));
+ }
+ }, function (err, credentials2) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Invalid nonce');
+ done();
+ });
+ });
+ });
+
+ it('should fail authorization on credentials error', function (done) {
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
+ expect(auth).to.exist();
+
+ var errFunc = function (id, callback) {
+
+ callback(new Error('kablooey'));
+ };
+
+ Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, errFunc, {}, function (err, credentials2) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('kablooey');
+ done();
+ });
+ });
+ });
+
+ it('should fail authorization on missing credentials', function (done) {
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
+ expect(auth).to.exist();
+
+ var errFunc = function (id, callback) {
+
+ callback();
+ };
+
+ Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, errFunc, {}, function (err, credentials2) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Unknown credentials');
+ done();
+ });
+ });
+ });
+
+ it('should fail authorization on invalid credentials', function (done) {
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
+ expect(auth).to.exist();
+
+ var errFunc = function (id, callback) {
+
+ callback(null, {});
+ };
+
+ Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, errFunc, {}, function (err, credentials2) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Invalid credentials');
+ done();
+ });
+ });
+ });
+
+ it('should fail authorization on invalid credentials algorithm', function (done) {
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials1 });
+ expect(auth).to.exist();
+
+ var errFunc = function (id, callback) {
+
+ callback(null, { key: '123', algorithm: '456' });
+ };
+
+ Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, errFunc, {}, function (err, credentials2) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Unknown algorithm');
+ done();
+ });
+ });
+ });
+
+ it('should fail on missing host', function (done) {
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var auth = Hawk.client.message(null, 8080, 'some message', { credentials: credentials1 });
+ expect(auth).to.not.exist();
+ done();
+ });
+ });
+
+ it('should fail on missing credentials', function (done) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', {});
+ expect(auth).to.not.exist();
+ done();
+ });
+
+ it('should fail on invalid algorithm', function (done) {
+
+ credentialsFunc('123456', function (err, credentials1) {
+
+ var creds = Hoek.clone(credentials1);
+ creds.algorithm = 'blah';
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: creds });
+ expect(auth).to.not.exist();
+ done();
+ });
+ });
+ });
+});
+
diff --git a/node_modules/request/node_modules/hawk/test/utils.js b/node_modules/request/node_modules/hawk/test/utils.js
index 1bfef65f8..ccfcd412a 100755
--- a/node_modules/request/node_modules/hawk/test/utils.js
+++ b/node_modules/request/node_modules/hawk/test/utils.js
@@ -1,121 +1,149 @@
-// Load modules
-
-var Code = require('code');
-var Hawk = require('../lib');
-var Lab = require('lab');
-var Package = require('../package.json');
-
-
-// Declare internals
-
-var internals = {};
-
-
-// Test shortcuts
-
-var lab = exports.lab = Lab.script();
-var describe = lab.experiment;
-var it = lab.test;
-var expect = Code.expect;
-
-
-describe('Utils', function () {
-
- describe('parseHost()', function () {
-
- it('returns port 80 for non tls node request', function (done) {
-
- var req = {
- method: 'POST',
- url: '/resource/4?filter=a',
- headers: {
- host: 'example.com',
- 'content-type': 'text/plain;x=y'
- }
- };
-
- expect(Hawk.utils.parseHost(req, 'Host').port).to.equal(80);
- done();
- });
-
- it('returns port 443 for non tls node request', function (done) {
-
- var req = {
- method: 'POST',
- url: '/resource/4?filter=a',
- headers: {
- host: 'example.com',
- 'content-type': 'text/plain;x=y'
- },
- connection: {
- encrypted: true
- }
- };
-
- expect(Hawk.utils.parseHost(req, 'Host').port).to.equal(443);
- done();
- });
-
- it('returns port 443 for non tls node request (IPv6)', function (done) {
-
- var req = {
- method: 'POST',
- url: '/resource/4?filter=a',
- headers: {
- host: '[123:123:123]',
- 'content-type': 'text/plain;x=y'
- },
- connection: {
- encrypted: true
- }
- };
-
- expect(Hawk.utils.parseHost(req, 'Host').port).to.equal(443);
- done();
- });
-
- it('parses IPv6 headers', function (done) {
-
- var req = {
- method: 'POST',
- url: '/resource/4?filter=a',
- headers: {
- host: '[123:123:123]:8000',
- 'content-type': 'text/plain;x=y'
- },
- connection: {
- encrypted: true
- }
- };
-
- var host = Hawk.utils.parseHost(req, 'Host');
- expect(host.port).to.equal('8000');
- expect(host.name).to.equal('[123:123:123]');
- done();
- });
- });
-
- describe('version()', function () {
-
- it('returns the correct package version number', function (done) {
-
- expect(Hawk.utils.version()).to.equal(Package.version);
- done();
- });
- });
-
- describe('unauthorized()', function () {
-
- it('returns a hawk 401', function (done) {
-
- expect(Hawk.utils.unauthorized('kaboom').output.headers['WWW-Authenticate']).to.equal('Hawk error="kaboom"');
- done();
- });
-
- it('supports attributes', function (done) {
-
- expect(Hawk.utils.unauthorized('kaboom', { a: 'b' }).output.headers['WWW-Authenticate']).to.equal('Hawk a="b", error="kaboom"');
- done();
- });
- });
-});
+// Load modules
+
+var Code = require('code');
+var Hawk = require('../lib');
+var Lab = require('lab');
+var Package = require('../package.json');
+
+
+// Declare internals
+
+var internals = {};
+
+
+// Test shortcuts
+
+var lab = exports.lab = Lab.script();
+var describe = lab.experiment;
+var it = lab.test;
+var expect = Code.expect;
+
+
+describe('Utils', function () {
+
+ describe('parseHost()', function () {
+
+ it('returns port 80 for non tls node request', function (done) {
+
+ var req = {
+ method: 'POST',
+ url: '/resource/4?filter=a',
+ headers: {
+ host: 'example.com',
+ 'content-type': 'text/plain;x=y'
+ }
+ };
+
+ expect(Hawk.utils.parseHost(req, 'Host').port).to.equal(80);
+ done();
+ });
+
+ it('returns port 443 for non tls node request', function (done) {
+
+ var req = {
+ method: 'POST',
+ url: '/resource/4?filter=a',
+ headers: {
+ host: 'example.com',
+ 'content-type': 'text/plain;x=y'
+ },
+ connection: {
+ encrypted: true
+ }
+ };
+
+ expect(Hawk.utils.parseHost(req, 'Host').port).to.equal(443);
+ done();
+ });
+
+ it('returns port 443 for non tls node request (IPv6)', function (done) {
+
+ var req = {
+ method: 'POST',
+ url: '/resource/4?filter=a',
+ headers: {
+ host: '[123:123:123]',
+ 'content-type': 'text/plain;x=y'
+ },
+ connection: {
+ encrypted: true
+ }
+ };
+
+ expect(Hawk.utils.parseHost(req, 'Host').port).to.equal(443);
+ done();
+ });
+
+ it('parses IPv6 headers', function (done) {
+
+ var req = {
+ method: 'POST',
+ url: '/resource/4?filter=a',
+ headers: {
+ host: '[123:123:123]:8000',
+ 'content-type': 'text/plain;x=y'
+ },
+ connection: {
+ encrypted: true
+ }
+ };
+
+ var host = Hawk.utils.parseHost(req, 'Host');
+ expect(host.port).to.equal('8000');
+ expect(host.name).to.equal('[123:123:123]');
+ done();
+ });
+
+ it('errors on header too long', function (done) {
+
+ var long = '';
+ for (var i = 0; i < 5000; ++i) {
+ long += 'x';
+ }
+
+ expect(Hawk.utils.parseHost({ headers: { host: long } })).to.be.null();
+ done();
+ });
+ });
+
+ describe('parseAuthorizationHeader()', function () {
+
+ it('errors on header too long', function (done) {
+
+ var long = 'Scheme a="';
+ for (var i = 0; i < 5000; ++i) {
+ long += 'x';
+ }
+ long += '"';
+
+ var err = Hawk.utils.parseAuthorizationHeader(long, ['a']);
+ expect(err).to.be.instanceof(Error);
+ expect(err.message).to.equal('Header length too long');
+ done();
+ });
+ });
+
+ describe('version()', function () {
+
+ it('returns the correct package version number', function (done) {
+
+ expect(Hawk.utils.version()).to.equal(Package.version);
+ done();
+ });
+ });
+
+ describe('unauthorized()', function () {
+
+ it('returns a hawk 401', function (done) {
+
+ expect(Hawk.utils.unauthorized('kaboom').output.headers['WWW-Authenticate']).to.equal('Hawk error="kaboom"');
+ done();
+ });
+
+ it('supports attributes', function (done) {
+
+ expect(Hawk.utils.unauthorized('kaboom', { a: 'b' }).output.headers['WWW-Authenticate']).to.equal('Hawk a="b", error="kaboom"');
+ done();
+ });
+ });
+});
diff --git a/node_modules/request/node_modules/http-signature/CHANGES.md b/node_modules/request/node_modules/http-signature/CHANGES.md
index 82be35900..6f69444ba 100644
--- a/node_modules/request/node_modules/http-signature/CHANGES.md
+++ b/node_modules/request/node_modules/http-signature/CHANGES.md
@@ -1,5 +1,12 @@
# node-http-signature changelog
+## 1.1.1
+
+- Version of dependency `assert-plus` updated: old version was missing
+ some license information
+- Corrected examples in `http_signing.md`, added auto-tests to
+ automatically validate these examples
+
## 1.1.0
- Bump version of `sshpk` dependency, remove peerDependency on it since
diff --git a/node_modules/request/node_modules/http-signature/http_signing.md b/node_modules/request/node_modules/http-signature/http_signing.md
index d08a5250c..4f24d28c3 100644
--- a/node_modules/request/node_modules/http-signature/http_signing.md
+++ b/node_modules/request/node_modules/http-signature/http_signing.md
@@ -231,7 +231,7 @@ will want to enforce, but service providers SHOULD at minimum include the
# Appendix A - Test Values
-The following test data uses the RSA (2048b) keys, which we will refer
+The following test data uses the RSA (1024b) keys, which we will refer
to as `keyId=Test` in the following samples:
-----BEGIN PUBLIC KEY-----
@@ -259,6 +259,8 @@ to as `keyId=Test` in the following samples:
And all examples use this request:
+<!-- httpreq -->
+
POST /foo?param=value&pet=dog HTTP/1.1
Host: example.com
Date: Thu, 05 Jan 2014 21:31:40 GMT
@@ -268,21 +270,35 @@ And all examples use this request:
{"hello": "world"}
+<!-- /httpreq -->
+
### Default
The string to sign would be:
+<!-- sign {"name": "Default", "options": {"keyId":"Test", "algorithm": "rsa-sha256"}} -->
+<!-- signstring -->
+
date: Thu, 05 Jan 2014 21:31:40 GMT
+<!-- /signstring -->
+
The Authorization header would be:
- Authorization: Signature keyId="Test",algorithm="rsa-sha256",signature="ATp0r26dbMIxOopqw0OfABDT7CKMIoENumuruOtarj8n/97Q3htHFYpH8yOSQk3Z5zh8UxUym6FYTb5+A0Nz3NRsXJibnYi7brE/4tx5But9kkFGzG+xpUmimN4c3TMN7OFH//+r8hBf7BT9/GmHDUVZT2JzWGLZES2xDOUuMtA="
+<!-- authz -->
+
+ Authorization: Signature keyId="Test",algorithm="rsa-sha256",headers="date",signature="jKyvPcxB4JbmYY4mByyBY7cZfNl4OW9HpFQlG7N4YcJPteKTu4MWCLyk+gIr0wDgqtLWf9NLpMAMimdfsH7FSWGfbMFSrsVTHNTk0rK3usrfFnti1dxsM4jl0kYJCKTGI/UWkqiaxwNiKqGcdlEDrTcUhhsFsOIo8VhddmZTZ8w="
+
+<!-- /authz -->
### All Headers
Parameterized to include all headers, the string to sign would be (`+ "\n"`
inserted for readability):
+<!-- sign {"name": "All Headers", "options": {"keyId":"Test", "algorithm": "rsa-sha256", "headers": ["(request-target)", "host", "date", "content-type", "digest", "content-length"]}} -->
+<!-- signstring -->
+
(request-target): post /foo?param=value&pet=dog
host: example.com
date: Thu, 05 Jan 2014 21:31:40 GMT
@@ -290,6 +306,58 @@ inserted for readability):
digest: SHA-256=X48E9qOokqqrvdts8nOJRJN3OWDUoyWxBf7kbu9DBPE=
content-length: 18
+<!-- /signstring -->
+
The Authorization header would be:
- Authorization: Signature keyId="Test",algorithm="rsa-sha256",headers="(request-target) host date content-type digest content-length",signature="jgSqYK0yKclIHfF9zdApVEbDp5eqj8C4i4X76pE+XHoxugXv7qnVrGR+30bmBgtpR39I4utq17s9ghz/2QFVxlnToYAvbSVZJ9ulLd1HQBugO0jOyn9sXOtcN7uNHBjqNCqUsnt0sw/cJA6B6nJZpyNqNyAXKdxZZItOuhIs78w="
+<!-- authz -->
+
+ Authorization: Signature keyId="Test",algorithm="rsa-sha256",headers="(request-target) host date content-type digest content-length",signature="Ef7MlxLXoBovhil3AlyjtBwAL9g4TN3tibLj7uuNB3CROat/9KaeQ4hW2NiJ+pZ6HQEOx9vYZAyi+7cmIkmJszJCut5kQLAwuX+Ms/mUFvpKlSo9StS2bMXDBNjOh4Auj774GFj4gwjS+3NhFeoqyr/MuN6HsEnkvn6zdgfE2i0="
+
+<!-- /authz -->
+
+## Generating and verifying signatures using `openssl`
+
+The `openssl` commandline tool can be used to generate or verify the signatures listed above.
+
+Compose the signing string as usual, and pipe it into the the `openssl dgst` command, then into `openssl enc -base64`, as follows:
+
+ $ printf 'date: Thu, 05 Jan 2014 21:31:40 GMT' | \
+ openssl dgst -binary -sign /path/to/private.pem -sha256 | \
+ openssl enc -base64
+ jKyvPcxB4JbmYY4mByyBY7cZfNl4OW9Hp...
+ $
+
+The `-sha256` option is necessary to produce an `rsa-sha256` signature. You can select other hash algorithms such as `sha1` by changing this argument.
+
+To verify a signature, first save the signature data, Base64-decoded, into a file, then use `openssl dgst` again with the `-verify` option:
+
+ $ echo 'jKyvPcxB4JbmYY4mByy...' | openssl enc -A -d -base64 > signature
+ $ printf 'date: Thu, 05 Jan 2014 21:31:40 GMT' | \
+ openssl dgst -sha256 -verify /path/to/public.pem -signature ./signature
+ Verified OK
+ $
+
+## Generating and verifying signatures using `sshpk-sign`
+
+You can also generate and check signatures using the `sshpk-sign` tool which is
+included with the `sshpk` package in `npm`.
+
+Compose the signing string as above, and pipe it into `sshpk-sign` as follows:
+
+ $ printf 'date: Thu, 05 Jan 2014 21:31:40 GMT' | \
+ sshpk-sign -i /path/to/private.pem
+ jKyvPcxB4JbmYY4mByyBY7cZfNl4OW9Hp...
+ $
+
+This will produce an `rsa-sha256` signature by default, as you can see using
+the `-v` option:
+
+ sshpk-sign: using rsa-sha256 with a 1024 bit key
+
+You can also use `sshpk-verify` in a similar manner:
+
+ $ printf 'date: Thu, 05 Jan 2014 21:31:40 GMT' | \
+ sshpk-verify -i ./public.pem -s 'jKyvPcxB4JbmYY...'
+ OK
+ $
diff --git a/node_modules/request/node_modules/http-signature/lib/signer.js b/node_modules/request/node_modules/http-signature/lib/signer.js
index c8fd366ee..ef9946f77 100644
--- a/node_modules/request/node_modules/http-signature/lib/signer.js
+++ b/node_modules/request/node_modules/http-signature/lib/signer.js
@@ -342,6 +342,11 @@ module.exports = {
stringToSign += '\n';
}
+ /* This is just for unit tests. */
+ if (request.hasOwnProperty('_stringToSign')) {
+ request._stringToSign = stringToSign;
+ }
+
var signature;
if (alg[0] === 'hmac') {
if (typeof (options.key) !== 'string' && !Buffer.isBuffer(options.key))
diff --git a/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/assert-plus/AUTHORS b/node_modules/request/node_modules/http-signature/node_modules/assert-plus/AUTHORS
index 1923524fe..1923524fe 100644
--- a/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/assert-plus/AUTHORS
+++ b/node_modules/request/node_modules/http-signature/node_modules/assert-plus/AUTHORS
diff --git a/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/assert-plus/CHANGES.md b/node_modules/request/node_modules/http-signature/node_modules/assert-plus/CHANGES.md
index d249d9b2a..d249d9b2a 100644
--- a/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/assert-plus/CHANGES.md
+++ b/node_modules/request/node_modules/http-signature/node_modules/assert-plus/CHANGES.md
diff --git a/node_modules/request/node_modules/http-signature/node_modules/assert-plus/README.md b/node_modules/request/node_modules/http-signature/node_modules/assert-plus/README.md
index c0c3a5308..0b39593ce 100644
--- a/node_modules/request/node_modules/http-signature/node_modules/assert-plus/README.md
+++ b/node_modules/request/node_modules/http-signature/node_modules/assert-plus/README.md
@@ -1,24 +1,26 @@
-# node-assert-plus
+# assert-plus
This library is a super small wrapper over node's assert module that has two
things: (1) the ability to disable assertions with the environment variable
-NODE_NDEBUG, and (2) some API wrappers for argument testing. Like
+NODE\_NDEBUG, and (2) some API wrappers for argument testing. Like
`assert.string(myArg, 'myArg')`. As a simple example, most of my code looks
like this:
+```javascript
var assert = require('assert-plus');
function fooAccount(options, callback) {
- assert.object(options, 'options');
- assert.number(options.id, 'options.id);
- assert.bool(options.isManager, 'options.isManager');
- assert.string(options.name, 'options.name');
- assert.arrayOfString(options.email, 'options.email');
- assert.func(callback, 'callback');
+ assert.object(options, 'options');
+ assert.number(options.id, 'options.id');
+ assert.bool(options.isManager, 'options.isManager');
+ assert.string(options.name, 'options.name');
+ assert.arrayOfString(options.email, 'options.email');
+ assert.func(callback, 'callback');
// Do stuff
- callback(null, {});
+ callback(null, {});
}
+```
# API
@@ -27,60 +29,87 @@ take an argument, and then a string 'name' that's not a message; `AssertionError
will be thrown if the assertion fails with a message like:
AssertionError: foo (string) is required
- at test (/home/mark/work/foo/foo.js:3:9)
- at Object.<anonymous> (/home/mark/work/foo/foo.js:15:1)
- at Module._compile (module.js:446:26)
- at Object..js (module.js:464:10)
- at Module.load (module.js:353:31)
- at Function._load (module.js:311:12)
- at Array.0 (module.js:484:10)
- at EventEmitter._tickCallback (node.js:190:38)
+ at test (/home/mark/work/foo/foo.js:3:9)
+ at Object.<anonymous> (/home/mark/work/foo/foo.js:15:1)
+ at Module._compile (module.js:446:26)
+ at Object..js (module.js:464:10)
+ at Module.load (module.js:353:31)
+ at Function._load (module.js:311:12)
+ at Array.0 (module.js:484:10)
+ at EventEmitter._tickCallback (node.js:190:38)
from:
+```javascript
function test(foo) {
- assert.string(foo, 'foo');
+ assert.string(foo, 'foo');
}
+```
-There you go. You can check that arrays are of a homogenous type with `Arrayof$Type`:
+There you go. You can check that arrays are of a homogeneous type with `Arrayof$Type`:
+```javascript
function test(foo) {
- assert.arrayOfString(foo, 'foo');
+ assert.arrayOfString(foo, 'foo');
}
+```
You can assert IFF an argument is not `undefined` (i.e., an optional arg):
+```javascript
assert.optionalString(foo, 'foo');
+```
Lastly, you can opt-out of assertion checking altogether by setting the
environment variable `NODE_NDEBUG=1`. This is pseudo-useful if you have
lots of assertions, and don't want to pay `typeof ()` taxes to v8 in
-production.
+production. Be advised: The standard functions re-exported from `assert` are
+also disabled in assert-plus if NDEBUG is specified. Using them directly from
+the `assert` module avoids this behavior.
The complete list of APIs is:
+* assert.array
* assert.bool
* assert.buffer
* assert.func
* assert.number
* assert.object
* assert.string
+* assert.stream
+* assert.date
+* assert.regex
+* assert.uuid
+* assert.arrayOfArray
* assert.arrayOfBool
+* assert.arrayOfBuffer
* assert.arrayOfFunc
* assert.arrayOfNumber
* assert.arrayOfObject
* assert.arrayOfString
+* assert.arrayOfStream
+* assert.arrayOfDate
+* assert.arrayOfUuid
+* assert.optionalArray
* assert.optionalBool
* assert.optionalBuffer
* assert.optionalFunc
* assert.optionalNumber
* assert.optionalObject
* assert.optionalString
+* assert.optionalStream
+* assert.optionalDate
+* assert.optionalUuid
+* assert.optionalArrayOfArray
* assert.optionalArrayOfBool
+* assert.optionalArrayOfBuffer
* assert.optionalArrayOfFunc
* assert.optionalArrayOfNumber
* assert.optionalArrayOfObject
* assert.optionalArrayOfString
+* assert.optionalArrayOfStream
+* assert.optionalArrayOfDate
+* assert.optionalArrayOfUuid
* assert.AssertionError
* assert.fail
* assert.ok
diff --git a/node_modules/request/node_modules/http-signature/node_modules/assert-plus/assert.js b/node_modules/request/node_modules/http-signature/node_modules/assert-plus/assert.js
index ff2ba02de..6bce4d8c6 100644
--- a/node_modules/request/node_modules/http-signature/node_modules/assert-plus/assert.js
+++ b/node_modules/request/node_modules/http-signature/node_modules/assert-plus/assert.js
@@ -1,245 +1,206 @@
// Copyright (c) 2012, Mark Cavage. All rights reserved.
+// Copyright 2015 Joyent, Inc.
var assert = require('assert');
var Stream = require('stream').Stream;
var util = require('util');
-
///--- Globals
-var NDEBUG = process.env.NODE_NDEBUG || false;
+/* JSSTYLED */
var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/;
-
-///--- Messages
-
-var ARRAY_TYPE_REQUIRED = '%s ([%s]) required';
-var TYPE_REQUIRED = '%s (%s) is required';
-
-
-
///--- Internal
-function capitalize(str) {
- return (str.charAt(0).toUpperCase() + str.slice(1));
+function _capitalize(str) {
+ return (str.charAt(0).toUpperCase() + str.slice(1));
}
-function uncapitalize(str) {
- return (str.charAt(0).toLowerCase() + str.slice(1));
+function _toss(name, expected, oper, arg, actual) {
+ throw new assert.AssertionError({
+ message: util.format('%s (%s) is required', name, expected),
+ actual: (actual === undefined) ? typeof (arg) : actual(arg),
+ expected: expected,
+ operator: oper || '===',
+ stackStartFunction: _toss.caller
+ });
}
-function _() {
- return (util.format.apply(util, arguments));
+function _getClass(arg) {
+ return (Object.prototype.toString.call(arg).slice(8, -1));
}
-
-function _assert(arg, type, name, stackFunc) {
- if (!NDEBUG) {
- name = name || type;
- stackFunc = stackFunc || _assert.caller;
- var t = typeof (arg);
-
- if (t !== type) {
- throw new assert.AssertionError({
- message: _(TYPE_REQUIRED, name, type),
- actual: t,
- expected: type,
- operator: '===',
- stackStartFunction: stackFunc
- });
- }
- }
+function noop() {
+ // Why even bother with asserts?
}
-function _instanceof(arg, type, name, stackFunc) {
- if (!NDEBUG) {
- name = name || type;
- stackFunc = stackFunc || _instanceof.caller;
+///--- Exports
- if (!(arg instanceof type)) {
- throw new assert.AssertionError({
- message: _(TYPE_REQUIRED, name, type.name),
- actual: _getClass(arg),
- expected: type.name,
- operator: 'instanceof',
- stackStartFunction: stackFunc
- });
- }
+var types = {
+ bool: {
+ check: function (arg) { return typeof (arg) === 'boolean'; }
+ },
+ func: {
+ check: function (arg) { return typeof (arg) === 'function'; }
+ },
+ string: {
+ check: function (arg) { return typeof (arg) === 'string'; }
+ },
+ object: {
+ check: function (arg) {
+ return typeof (arg) === 'object' && arg !== null;
}
-}
-
-function _getClass(object) {
- return (Object.prototype.toString.call(object).slice(8, -1));
+ },
+ number: {
+ check: function (arg) {
+ return typeof (arg) === 'number' && !isNaN(arg) && isFinite(arg);
+ }
+ },
+ buffer: {
+ check: function (arg) { return Buffer.isBuffer(arg); },
+ operator: 'Buffer.isBuffer'
+ },
+ array: {
+ check: function (arg) { return Array.isArray(arg); },
+ operator: 'Array.isArray'
+ },
+ stream: {
+ check: function (arg) { return arg instanceof Stream; },
+ operator: 'instanceof',
+ actual: _getClass
+ },
+ date: {
+ check: function (arg) { return arg instanceof Date; },
+ operator: 'instanceof',
+ actual: _getClass
+ },
+ regexp: {
+ check: function (arg) { return arg instanceof RegExp; },
+ operator: 'instanceof',
+ actual: _getClass
+ },
+ uuid: {
+ check: function (arg) {
+ return typeof (arg) === 'string' && UUID_REGEXP.test(arg);
+ },
+ operator: 'isUUID'
+ }
};
+function _setExports(ndebug) {
+ var keys = Object.keys(types);
+ var out;
+
+ /* re-export standard assert */
+ if (process.env.NODE_NDEBUG) {
+ out = noop;
+ } else {
+ out = function (arg, msg) {
+ if (!arg) {
+ _toss(msg, 'true', arg);
+ }
+ };
+ }
-
-///--- API
-
-function array(arr, type, name) {
- if (!NDEBUG) {
- name = name || type;
-
- if (!Array.isArray(arr)) {
- throw new assert.AssertionError({
- message: _(ARRAY_TYPE_REQUIRED, name, type),
- actual: typeof (arr),
- expected: 'array',
- operator: 'Array.isArray',
- stackStartFunction: array.caller
- });
- }
-
- for (var i = 0; i < arr.length; i++) {
- _assert(arr[i], type, name, array);
- }
+ /* standard checks */
+ keys.forEach(function (k) {
+ if (ndebug) {
+ out[k] = noop;
+ return;
}
-}
-
-
-function bool(arg, name) {
- _assert(arg, 'boolean', name, bool);
-}
-
-
-function buffer(arg, name) {
- if (!Buffer.isBuffer(arg)) {
- throw new assert.AssertionError({
- message: _(TYPE_REQUIRED, name || '', 'Buffer'),
- actual: typeof (arg),
- expected: 'buffer',
- operator: 'Buffer.isBuffer',
- stackStartFunction: buffer
- });
+ var type = types[k];
+ out[k] = function (arg, msg) {
+ if (!type.check(arg)) {
+ _toss(msg, k, type.operator, arg, type.actual);
+ }
+ };
+ });
+
+ /* optional checks */
+ keys.forEach(function (k) {
+ var name = 'optional' + _capitalize(k);
+ if (ndebug) {
+ out[name] = noop;
+ return;
}
-}
-
-
-function func(arg, name) {
- _assert(arg, 'function', name);
-}
-
-
-function number(arg, name) {
- _assert(arg, 'number', name);
- if (!NDEBUG && (isNaN(arg) || !isFinite(arg))) {
- throw new assert.AssertionError({
- message: _(TYPE_REQUIRED, name, 'number'),
- actual: arg,
- expected: 'number',
- operator: 'isNaN',
- stackStartFunction: number
- });
+ var type = types[k];
+ out[name] = function (arg, msg) {
+ if (arg === undefined || arg === null) {
+ return;
+ }
+ if (!type.check(arg)) {
+ _toss(msg, k, type.operator, arg, type.actual);
+ }
+ };
+ });
+
+ /* arrayOf checks */
+ keys.forEach(function (k) {
+ var name = 'arrayOf' + _capitalize(k);
+ if (ndebug) {
+ out[name] = noop;
+ return;
}
-}
-
-
-function object(arg, name) {
- _assert(arg, 'object', name);
-}
-
-
-function stream(arg, name) {
- _instanceof(arg, Stream, name);
-}
-
-
-function date(arg, name) {
- _instanceof(arg, Date, name);
-}
-
-function regexp(arg, name) {
- _instanceof(arg, RegExp, name);
-}
-
-
-function string(arg, name) {
- _assert(arg, 'string', name);
-}
-
-
-function uuid(arg, name) {
- string(arg, name);
- if (!NDEBUG && !UUID_REGEXP.test(arg)) {
- throw new assert.AssertionError({
- message: _(TYPE_REQUIRED, name, 'uuid'),
- actual: 'string',
- expected: 'uuid',
- operator: 'test',
- stackStartFunction: uuid
- });
+ var type = types[k];
+ var expected = '[' + k + ']';
+ out[name] = function (arg, msg) {
+ if (!Array.isArray(arg)) {
+ _toss(msg, expected, type.operator, arg, type.actual);
+ }
+ var i;
+ for (i = 0; i < arg.length; i++) {
+ if (!type.check(arg[i])) {
+ _toss(msg, expected, type.operator, arg, type.actual);
+ }
+ }
+ };
+ });
+
+ /* optionalArrayOf checks */
+ keys.forEach(function (k) {
+ var name = 'optionalArrayOf' + _capitalize(k);
+ if (ndebug) {
+ out[name] = noop;
+ return;
}
-}
-
-
-///--- Exports
-
-module.exports = {
- bool: bool,
- buffer: buffer,
- date: date,
- func: func,
- number: number,
- object: object,
- regexp: regexp,
- stream: stream,
- string: string,
- uuid: uuid
-};
-
-
-Object.keys(module.exports).forEach(function (k) {
- if (k === 'buffer')
+ var type = types[k];
+ var expected = '[' + k + ']';
+ out[name] = function (arg, msg) {
+ if (arg === undefined || arg === null) {
return;
-
- var name = 'arrayOf' + capitalize(k);
-
- if (k === 'bool')
- k = 'boolean';
- if (k === 'func')
- k = 'function';
- module.exports[name] = function (arg, name) {
- array(arg, k, name);
+ }
+ if (!Array.isArray(arg)) {
+ _toss(msg, expected, type.operator, arg, type.actual);
+ }
+ var i;
+ for (i = 0; i < arg.length; i++) {
+ if (!type.check(arg[i])) {
+ _toss(msg, expected, type.operator, arg, type.actual);
+ }
+ }
};
-});
-
-Object.keys(module.exports).forEach(function (k) {
- var _name = 'optional' + capitalize(k);
- var s = uncapitalize(k.replace('arrayOf', ''));
- if (s === 'bool')
- s = 'boolean';
- if (s === 'func')
- s = 'function';
-
- if (k.indexOf('arrayOf') !== -1) {
- module.exports[_name] = function (arg, name) {
- if (!NDEBUG && arg !== undefined) {
- array(arg, s, name);
- }
- };
- } else {
- module.exports[_name] = function (arg, name) {
- if (!NDEBUG && arg !== undefined) {
- _assert(arg, s, name);
- }
- };
- }
-});
-
+ });
-// Reexport built-in assertions
-Object.keys(assert).forEach(function (k) {
+ /* re-export built-in assertions */
+ Object.keys(assert).forEach(function (k) {
if (k === 'AssertionError') {
- module.exports[k] = assert[k];
- return;
+ out[k] = assert[k];
+ return;
}
+ if (ndebug) {
+ out[k] = noop;
+ return;
+ }
+ out[k] = assert[k];
+ });
- module.exports[k] = function () {
- if (!NDEBUG) {
- assert[k].apply(assert[k], arguments);
- }
- };
-});
+ /* export ourselves (for unit tests _only_) */
+ out._setExports = _setExports;
+
+ return out;
+}
+
+module.exports = _setExports(process.env.NODE_NDEBUG);
diff --git a/node_modules/request/node_modules/http-signature/node_modules/assert-plus/package.json b/node_modules/request/node_modules/http-signature/node_modules/assert-plus/package.json
index b3317675d..b596b28af 100644
--- a/node_modules/request/node_modules/http-signature/node_modules/assert-plus/package.json
+++ b/node_modules/request/node_modules/http-signature/node_modules/assert-plus/package.json
@@ -1,30 +1,109 @@
{
+ "_args": [
+ [
+ "assert-plus@^0.2.0",
+ "/Users/rebecca/code/npm/node_modules/request/node_modules/http-signature"
+ ]
+ ],
+ "_from": "assert-plus@>=0.2.0 <0.3.0",
+ "_id": "assert-plus@0.2.0",
+ "_inCache": true,
+ "_installable": true,
+ "_location": "/request/http-signature/assert-plus",
+ "_nodeVersion": "0.10.36",
+ "_npmUser": {
+ "email": "patrick.f.mooney@gmail.com",
+ "name": "pfmooney"
+ },
+ "_npmVersion": "3.3.8",
+ "_phantomChildren": {},
+ "_requested": {
+ "name": "assert-plus",
+ "raw": "assert-plus@^0.2.0",
+ "rawSpec": "^0.2.0",
+ "scope": null,
+ "spec": ">=0.2.0 <0.3.0",
+ "type": "range"
+ },
+ "_requiredBy": [
+ "/request/http-signature",
+ "/request/http-signature/sshpk",
+ "/request/http-signature/sshpk/dashdash"
+ ],
+ "_resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-0.2.0.tgz",
+ "_shasum": "d74e1b87e7affc0db8aadb7021f3fe48101ab234",
+ "_shrinkwrap": null,
+ "_spec": "assert-plus@^0.2.0",
+ "_where": "/Users/rebecca/code/npm/node_modules/request/node_modules/http-signature",
"author": {
- "name": "Mark Cavage",
- "email": "mcavage@gmail.com"
+ "email": "mcavage@gmail.com",
+ "name": "Mark Cavage"
},
- "name": "assert-plus",
+ "bugs": {
+ "url": "https://github.com/mcavage/node-assert-plus/issues"
+ },
+ "contributors": [
+ {
+ "name": "Dave Eddy",
+ "email": "dave@daveeddy.com"
+ },
+ {
+ "name": "Fred Kuo",
+ "email": "fred.kuo@joyent.com"
+ },
+ {
+ "name": "Lars-Magnus Skog",
+ "email": "ralphtheninja@riseup.net"
+ },
+ {
+ "name": "Mark Cavage",
+ "email": "mcavage@gmail.com"
+ },
+ {
+ "name": "Patrick Mooney",
+ "email": "pmooney@pfmooney.com"
+ },
+ {
+ "name": "Rob Gulewich",
+ "email": "robert.gulewich@joyent.com"
+ }
+ ],
+ "dependencies": {},
"description": "Extra assertions on top of node's assert module",
- "version": "0.1.5",
+ "devDependencies": {
+ "faucet": "0.0.1",
+ "tape": "4.2.2"
+ },
+ "directories": {},
+ "dist": {
+ "shasum": "d74e1b87e7affc0db8aadb7021f3fe48101ab234",
+ "tarball": "http://registry.npmjs.org/assert-plus/-/assert-plus-0.2.0.tgz"
+ },
+ "engines": {
+ "node": ">=0.8"
+ },
+ "homepage": "https://github.com/mcavage/node-assert-plus#readme",
+ "license": "MIT",
"main": "./assert.js",
- "devDependencies": {},
+ "maintainers": [
+ {
+ "name": "mcavage",
+ "email": "mcavage@gmail.com"
+ },
+ {
+ "name": "pfmooney",
+ "email": "patrick.f.mooney@gmail.com"
+ }
+ ],
+ "name": "assert-plus",
"optionalDependencies": {},
+ "readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/mcavage/node-assert-plus.git"
},
- "engines": {
- "node": ">=0.8"
- },
- "readme": "# node-assert-plus\n\nThis library is a super small wrapper over node's assert module that has two\nthings: (1) the ability to disable assertions with the environment variable\nNODE_NDEBUG, and (2) some API wrappers for argument testing. Like\n`assert.string(myArg, 'myArg')`. As a simple example, most of my code looks\nlike this:\n\n var assert = require('assert-plus');\n\n function fooAccount(options, callback) {\n\t assert.object(options, 'options');\n\t\tassert.number(options.id, 'options.id);\n\t\tassert.bool(options.isManager, 'options.isManager');\n\t\tassert.string(options.name, 'options.name');\n\t\tassert.arrayOfString(options.email, 'options.email');\n\t\tassert.func(callback, 'callback');\n\n // Do stuff\n\t\tcallback(null, {});\n }\n\n# API\n\nAll methods that *aren't* part of node's core assert API are simply assumed to\ntake an argument, and then a string 'name' that's not a message; `AssertionError`\nwill be thrown if the assertion fails with a message like:\n\n AssertionError: foo (string) is required\n\tat test (/home/mark/work/foo/foo.js:3:9)\n\tat Object.<anonymous> (/home/mark/work/foo/foo.js:15:1)\n\tat Module._compile (module.js:446:26)\n\tat Object..js (module.js:464:10)\n\tat Module.load (module.js:353:31)\n\tat Function._load (module.js:311:12)\n\tat Array.0 (module.js:484:10)\n\tat EventEmitter._tickCallback (node.js:190:38)\n\nfrom:\n\n function test(foo) {\n\t assert.string(foo, 'foo');\n }\n\nThere you go. You can check that arrays are of a homogenous type with `Arrayof$Type`:\n\n function test(foo) {\n\t assert.arrayOfString(foo, 'foo');\n }\n\nYou can assert IFF an argument is not `undefined` (i.e., an optional arg):\n\n assert.optionalString(foo, 'foo');\n\nLastly, you can opt-out of assertion checking altogether by setting the\nenvironment variable `NODE_NDEBUG=1`. This is pseudo-useful if you have\nlots of assertions, and don't want to pay `typeof ()` taxes to v8 in\nproduction.\n\nThe complete list of APIs is:\n\n* assert.bool\n* assert.buffer\n* assert.func\n* assert.number\n* assert.object\n* assert.string\n* assert.arrayOfBool\n* assert.arrayOfFunc\n* assert.arrayOfNumber\n* assert.arrayOfObject\n* assert.arrayOfString\n* assert.optionalBool\n* assert.optionalBuffer\n* assert.optionalFunc\n* assert.optionalNumber\n* assert.optionalObject\n* assert.optionalString\n* assert.optionalArrayOfBool\n* assert.optionalArrayOfFunc\n* assert.optionalArrayOfNumber\n* assert.optionalArrayOfObject\n* assert.optionalArrayOfString\n* assert.AssertionError\n* assert.fail\n* assert.ok\n* assert.equal\n* assert.notEqual\n* assert.deepEqual\n* assert.notDeepEqual\n* assert.strictEqual\n* assert.notStrictEqual\n* assert.throws\n* assert.doesNotThrow\n* assert.ifError\n\n# Installation\n\n npm install assert-plus\n\n## License\n\nThe MIT License (MIT)\nCopyright (c) 2012 Mark Cavage\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n## Bugs\n\nSee <https://github.com/mcavage/node-assert-plus/issues>.\n",
- "readmeFilename": "README.md",
- "bugs": {
- "url": "https://github.com/mcavage/node-assert-plus/issues"
+ "scripts": {
+ "test": "tape tests/*.js | ./node_modules/.bin/faucet"
},
- "homepage": "https://github.com/mcavage/node-assert-plus#readme",
- "dependencies": {},
- "_id": "assert-plus@0.1.5",
- "_shasum": "ee74009413002d84cec7219c6ac811812e723160",
- "_resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-0.1.5.tgz",
- "_from": "assert-plus@>=0.1.5 <0.2.0"
+ "version": "0.2.0"
}
diff --git a/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/assert-plus/README.md b/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/assert-plus/README.md
deleted file mode 100644
index 0b39593ce..000000000
--- a/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/assert-plus/README.md
+++ /dev/null
@@ -1,155 +0,0 @@
-# assert-plus
-
-This library is a super small wrapper over node's assert module that has two
-things: (1) the ability to disable assertions with the environment variable
-NODE\_NDEBUG, and (2) some API wrappers for argument testing. Like
-`assert.string(myArg, 'myArg')`. As a simple example, most of my code looks
-like this:
-
-```javascript
- var assert = require('assert-plus');
-
- function fooAccount(options, callback) {
- assert.object(options, 'options');
- assert.number(options.id, 'options.id');
- assert.bool(options.isManager, 'options.isManager');
- assert.string(options.name, 'options.name');
- assert.arrayOfString(options.email, 'options.email');
- assert.func(callback, 'callback');
-
- // Do stuff
- callback(null, {});
- }
-```
-
-# API
-
-All methods that *aren't* part of node's core assert API are simply assumed to
-take an argument, and then a string 'name' that's not a message; `AssertionError`
-will be thrown if the assertion fails with a message like:
-
- AssertionError: foo (string) is required
- at test (/home/mark/work/foo/foo.js:3:9)
- at Object.<anonymous> (/home/mark/work/foo/foo.js:15:1)
- at Module._compile (module.js:446:26)
- at Object..js (module.js:464:10)
- at Module.load (module.js:353:31)
- at Function._load (module.js:311:12)
- at Array.0 (module.js:484:10)
- at EventEmitter._tickCallback (node.js:190:38)
-
-from:
-
-```javascript
- function test(foo) {
- assert.string(foo, 'foo');
- }
-```
-
-There you go. You can check that arrays are of a homogeneous type with `Arrayof$Type`:
-
-```javascript
- function test(foo) {
- assert.arrayOfString(foo, 'foo');
- }
-```
-
-You can assert IFF an argument is not `undefined` (i.e., an optional arg):
-
-```javascript
- assert.optionalString(foo, 'foo');
-```
-
-Lastly, you can opt-out of assertion checking altogether by setting the
-environment variable `NODE_NDEBUG=1`. This is pseudo-useful if you have
-lots of assertions, and don't want to pay `typeof ()` taxes to v8 in
-production. Be advised: The standard functions re-exported from `assert` are
-also disabled in assert-plus if NDEBUG is specified. Using them directly from
-the `assert` module avoids this behavior.
-
-The complete list of APIs is:
-
-* assert.array
-* assert.bool
-* assert.buffer
-* assert.func
-* assert.number
-* assert.object
-* assert.string
-* assert.stream
-* assert.date
-* assert.regex
-* assert.uuid
-* assert.arrayOfArray
-* assert.arrayOfBool
-* assert.arrayOfBuffer
-* assert.arrayOfFunc
-* assert.arrayOfNumber
-* assert.arrayOfObject
-* assert.arrayOfString
-* assert.arrayOfStream
-* assert.arrayOfDate
-* assert.arrayOfUuid
-* assert.optionalArray
-* assert.optionalBool
-* assert.optionalBuffer
-* assert.optionalFunc
-* assert.optionalNumber
-* assert.optionalObject
-* assert.optionalString
-* assert.optionalStream
-* assert.optionalDate
-* assert.optionalUuid
-* assert.optionalArrayOfArray
-* assert.optionalArrayOfBool
-* assert.optionalArrayOfBuffer
-* assert.optionalArrayOfFunc
-* assert.optionalArrayOfNumber
-* assert.optionalArrayOfObject
-* assert.optionalArrayOfString
-* assert.optionalArrayOfStream
-* assert.optionalArrayOfDate
-* assert.optionalArrayOfUuid
-* assert.AssertionError
-* assert.fail
-* assert.ok
-* assert.equal
-* assert.notEqual
-* assert.deepEqual
-* assert.notDeepEqual
-* assert.strictEqual
-* assert.notStrictEqual
-* assert.throws
-* assert.doesNotThrow
-* assert.ifError
-
-# Installation
-
- npm install assert-plus
-
-## License
-
-The MIT License (MIT)
-Copyright (c) 2012 Mark Cavage
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of
-this software and associated documentation files (the "Software"), to deal in
-the Software without restriction, including without limitation the rights to
-use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
-the Software, and to permit persons to whom the Software is furnished to do so,
-subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-
-## Bugs
-
-See <https://github.com/mcavage/node-assert-plus/issues>.
diff --git a/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/assert-plus/assert.js b/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/assert-plus/assert.js
deleted file mode 100644
index 6bce4d8c6..000000000
--- a/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/assert-plus/assert.js
+++ /dev/null
@@ -1,206 +0,0 @@
-// Copyright (c) 2012, Mark Cavage. All rights reserved.
-// Copyright 2015 Joyent, Inc.
-
-var assert = require('assert');
-var Stream = require('stream').Stream;
-var util = require('util');
-
-
-///--- Globals
-
-/* JSSTYLED */
-var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/;
-
-
-///--- Internal
-
-function _capitalize(str) {
- return (str.charAt(0).toUpperCase() + str.slice(1));
-}
-
-function _toss(name, expected, oper, arg, actual) {
- throw new assert.AssertionError({
- message: util.format('%s (%s) is required', name, expected),
- actual: (actual === undefined) ? typeof (arg) : actual(arg),
- expected: expected,
- operator: oper || '===',
- stackStartFunction: _toss.caller
- });
-}
-
-function _getClass(arg) {
- return (Object.prototype.toString.call(arg).slice(8, -1));
-}
-
-function noop() {
- // Why even bother with asserts?
-}
-
-
-///--- Exports
-
-var types = {
- bool: {
- check: function (arg) { return typeof (arg) === 'boolean'; }
- },
- func: {
- check: function (arg) { return typeof (arg) === 'function'; }
- },
- string: {
- check: function (arg) { return typeof (arg) === 'string'; }
- },
- object: {
- check: function (arg) {
- return typeof (arg) === 'object' && arg !== null;
- }
- },
- number: {
- check: function (arg) {
- return typeof (arg) === 'number' && !isNaN(arg) && isFinite(arg);
- }
- },
- buffer: {
- check: function (arg) { return Buffer.isBuffer(arg); },
- operator: 'Buffer.isBuffer'
- },
- array: {
- check: function (arg) { return Array.isArray(arg); },
- operator: 'Array.isArray'
- },
- stream: {
- check: function (arg) { return arg instanceof Stream; },
- operator: 'instanceof',
- actual: _getClass
- },
- date: {
- check: function (arg) { return arg instanceof Date; },
- operator: 'instanceof',
- actual: _getClass
- },
- regexp: {
- check: function (arg) { return arg instanceof RegExp; },
- operator: 'instanceof',
- actual: _getClass
- },
- uuid: {
- check: function (arg) {
- return typeof (arg) === 'string' && UUID_REGEXP.test(arg);
- },
- operator: 'isUUID'
- }
-};
-
-function _setExports(ndebug) {
- var keys = Object.keys(types);
- var out;
-
- /* re-export standard assert */
- if (process.env.NODE_NDEBUG) {
- out = noop;
- } else {
- out = function (arg, msg) {
- if (!arg) {
- _toss(msg, 'true', arg);
- }
- };
- }
-
- /* standard checks */
- keys.forEach(function (k) {
- if (ndebug) {
- out[k] = noop;
- return;
- }
- var type = types[k];
- out[k] = function (arg, msg) {
- if (!type.check(arg)) {
- _toss(msg, k, type.operator, arg, type.actual);
- }
- };
- });
-
- /* optional checks */
- keys.forEach(function (k) {
- var name = 'optional' + _capitalize(k);
- if (ndebug) {
- out[name] = noop;
- return;
- }
- var type = types[k];
- out[name] = function (arg, msg) {
- if (arg === undefined || arg === null) {
- return;
- }
- if (!type.check(arg)) {
- _toss(msg, k, type.operator, arg, type.actual);
- }
- };
- });
-
- /* arrayOf checks */
- keys.forEach(function (k) {
- var name = 'arrayOf' + _capitalize(k);
- if (ndebug) {
- out[name] = noop;
- return;
- }
- var type = types[k];
- var expected = '[' + k + ']';
- out[name] = function (arg, msg) {
- if (!Array.isArray(arg)) {
- _toss(msg, expected, type.operator, arg, type.actual);
- }
- var i;
- for (i = 0; i < arg.length; i++) {
- if (!type.check(arg[i])) {
- _toss(msg, expected, type.operator, arg, type.actual);
- }
- }
- };
- });
-
- /* optionalArrayOf checks */
- keys.forEach(function (k) {
- var name = 'optionalArrayOf' + _capitalize(k);
- if (ndebug) {
- out[name] = noop;
- return;
- }
- var type = types[k];
- var expected = '[' + k + ']';
- out[name] = function (arg, msg) {
- if (arg === undefined || arg === null) {
- return;
- }
- if (!Array.isArray(arg)) {
- _toss(msg, expected, type.operator, arg, type.actual);
- }
- var i;
- for (i = 0; i < arg.length; i++) {
- if (!type.check(arg[i])) {
- _toss(msg, expected, type.operator, arg, type.actual);
- }
- }
- };
- });
-
- /* re-export built-in assertions */
- Object.keys(assert).forEach(function (k) {
- if (k === 'AssertionError') {
- out[k] = assert[k];
- return;
- }
- if (ndebug) {
- out[k] = noop;
- return;
- }
- out[k] = assert[k];
- });
-
- /* export ourselves (for unit tests _only_) */
- out._setExports = _setExports;
-
- return out;
-}
-
-module.exports = _setExports(process.env.NODE_NDEBUG);
diff --git a/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/assert-plus/package.json b/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/assert-plus/package.json
deleted file mode 100644
index 09597df69..000000000
--- a/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/assert-plus/package.json
+++ /dev/null
@@ -1,107 +0,0 @@
-{
- "_args": [
- [
- "assert-plus@>=0.2.0 <0.3.0",
- "/Users/ogd/Documents/projects/npm/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk"
- ]
- ],
- "_from": "assert-plus@>=0.2.0 <0.3.0",
- "_id": "assert-plus@0.2.0",
- "_inCache": true,
- "_installable": true,
- "_location": "/request/http-signature/sshpk/assert-plus",
- "_nodeVersion": "0.10.36",
- "_npmUser": {
- "email": "patrick.f.mooney@gmail.com",
- "name": "pfmooney"
- },
- "_npmVersion": "3.3.8",
- "_phantomChildren": {},
- "_requested": {
- "name": "assert-plus",
- "raw": "assert-plus@>=0.2.0 <0.3.0",
- "rawSpec": ">=0.2.0 <0.3.0",
- "scope": null,
- "spec": ">=0.2.0 <0.3.0",
- "type": "range"
- },
- "_requiredBy": [
- "/request/http-signature/sshpk"
- ],
- "_resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-0.2.0.tgz",
- "_shasum": "d74e1b87e7affc0db8aadb7021f3fe48101ab234",
- "_shrinkwrap": null,
- "_spec": "assert-plus@>=0.2.0 <0.3.0",
- "_where": "/Users/ogd/Documents/projects/npm/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk",
- "author": {
- "email": "mcavage@gmail.com",
- "name": "Mark Cavage"
- },
- "bugs": {
- "url": "https://github.com/mcavage/node-assert-plus/issues"
- },
- "contributors": [
- {
- "name": "Dave Eddy",
- "email": "dave@daveeddy.com"
- },
- {
- "name": "Fred Kuo",
- "email": "fred.kuo@joyent.com"
- },
- {
- "name": "Lars-Magnus Skog",
- "email": "ralphtheninja@riseup.net"
- },
- {
- "name": "Mark Cavage",
- "email": "mcavage@gmail.com"
- },
- {
- "name": "Patrick Mooney",
- "email": "pmooney@pfmooney.com"
- },
- {
- "name": "Rob Gulewich",
- "email": "robert.gulewich@joyent.com"
- }
- ],
- "dependencies": {},
- "description": "Extra assertions on top of node's assert module",
- "devDependencies": {
- "faucet": "0.0.1",
- "tape": "4.2.2"
- },
- "directories": {},
- "dist": {
- "shasum": "d74e1b87e7affc0db8aadb7021f3fe48101ab234",
- "tarball": "http://registry.npmjs.org/assert-plus/-/assert-plus-0.2.0.tgz"
- },
- "engines": {
- "node": ">=0.8"
- },
- "homepage": "https://github.com/mcavage/node-assert-plus#readme",
- "license": "MIT",
- "main": "./assert.js",
- "maintainers": [
- {
- "name": "mcavage",
- "email": "mcavage@gmail.com"
- },
- {
- "name": "pfmooney",
- "email": "patrick.f.mooney@gmail.com"
- }
- ],
- "name": "assert-plus",
- "optionalDependencies": {},
- "readme": "ERROR: No README data found!",
- "repository": {
- "type": "git",
- "url": "git+https://github.com/mcavage/node-assert-plus.git"
- },
- "scripts": {
- "test": "tape tests/*.js | ./node_modules/.bin/faucet"
- },
- "version": "0.2.0"
-}
diff --git a/node_modules/request/node_modules/http-signature/package.json b/node_modules/request/node_modules/http-signature/package.json
index 136df23b6..c7479c09f 100644
--- a/node_modules/request/node_modules/http-signature/package.json
+++ b/node_modules/request/node_modules/http-signature/package.json
@@ -2,20 +2,20 @@
"_args": [
[
"http-signature@~1.1.0",
- "/Users/ogd/Documents/projects/npm/npm/node_modules/request"
+ "/Users/rebecca/code/npm/node_modules/request"
]
],
"_from": "http-signature@>=1.1.0 <1.2.0",
- "_id": "http-signature@1.1.0",
+ "_id": "http-signature@1.1.1",
"_inCache": true,
"_installable": true,
"_location": "/request/http-signature",
- "_nodeVersion": "0.12.7",
+ "_nodeVersion": "0.12.9",
"_npmUser": {
"email": "alex@cooperi.net",
"name": "arekinath"
},
- "_npmVersion": "2.14.4",
+ "_npmVersion": "2.14.9",
"_phantomChildren": {},
"_requested": {
"name": "http-signature",
@@ -28,11 +28,11 @@
"_requiredBy": [
"/request"
],
- "_resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.1.0.tgz",
- "_shasum": "5d2d7e9b6ef49980ad5b128d8e4ef09a31c90d95",
+ "_resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.1.1.tgz",
+ "_shasum": "df72e267066cd0ac67fb76adf8e134a8fbcf91bf",
"_shrinkwrap": null,
"_spec": "http-signature@~1.1.0",
- "_where": "/Users/ogd/Documents/projects/npm/npm/node_modules/request",
+ "_where": "/Users/rebecca/code/npm/node_modules/request",
"author": {
"name": "Joyent, Inc"
},
@@ -54,7 +54,7 @@
}
],
"dependencies": {
- "assert-plus": "^0.1.5",
+ "assert-plus": "^0.2.0",
"jsprim": "^1.2.2",
"sshpk": "^1.7.0"
},
@@ -65,14 +65,14 @@
},
"directories": {},
"dist": {
- "shasum": "5d2d7e9b6ef49980ad5b128d8e4ef09a31c90d95",
- "tarball": "http://registry.npmjs.org/http-signature/-/http-signature-1.1.0.tgz"
+ "shasum": "df72e267066cd0ac67fb76adf8e134a8fbcf91bf",
+ "tarball": "http://registry.npmjs.org/http-signature/-/http-signature-1.1.1.tgz"
},
"engines": {
"node": ">=0.8",
"npm": ">=1.3.7"
},
- "gitHead": "162c2f0144b0645a57517d6d91fafcde3840cde2",
+ "gitHead": "74d3f35e3aa436d83723c53b01e266f448e8149a",
"homepage": "https://github.com/joyent/node-http-signature/",
"keywords": [
"https",
@@ -104,5 +104,5 @@
"scripts": {
"test": "tap test/*.js"
},
- "version": "1.1.0"
+ "version": "1.1.1"
}
diff --git a/node_modules/request/node_modules/qs/.travis.yml b/node_modules/request/node_modules/qs/.travis.yml
index 335fded1a..63bdc12be 100644
--- a/node_modules/request/node_modules/qs/.travis.yml
+++ b/node_modules/request/node_modules/qs/.travis.yml
@@ -1,8 +1,69 @@
language: node_js
-
node_js:
- - 0.10
- - 4.0
- - 4
-
+ - "5.3"
+ - "5.2"
+ - "5.1"
+ - "5.0"
+ - "4.2"
+ - "4.1"
+ - "4.0"
+ - "iojs-v3.3"
+ - "iojs-v3.2"
+ - "iojs-v3.1"
+ - "iojs-v3.0"
+ - "iojs-v2.5"
+ - "iojs-v2.4"
+ - "iojs-v2.3"
+ - "iojs-v2.2"
+ - "iojs-v2.1"
+ - "iojs-v2.0"
+ - "iojs-v1.8"
+ - "iojs-v1.7"
+ - "iojs-v1.6"
+ - "iojs-v1.5"
+ - "iojs-v1.4"
+ - "iojs-v1.3"
+ - "iojs-v1.2"
+ - "iojs-v1.1"
+ - "iojs-v1.0"
+ - "0.12"
+ - "0.11"
+ - "0.10"
+ - "0.9"
+ - "0.8"
+ - "0.6"
+ - "0.4"
+before_install:
+ - 'if [ "${TRAVIS_NODE_VERSION}" != "0.9" ]; then case "$(npm --version)" in 1.*) npm install -g npm@1.4.28 ;; 2.*) npm install -g npm@2 ;; esac ; fi'
+ - 'if [ "${TRAVIS_NODE_VERSION}" != "0.6" ] && [ "${TRAVIS_NODE_VERSION}" != "0.9" ]; then npm install -g npm; fi'
+script:
+ - 'if [ "${TRAVIS_NODE_VERSION}" != "4.2" ]; then npm run tests-only ; else npm test ; fi'
sudo: false
+matrix:
+ fast_finish: true
+ allow_failures:
+ - node_js: "5.2"
+ - node_js: "5.1"
+ - node_js: "5.0"
+ - node_js: "4.1"
+ - node_js: "4.0"
+ - node_js: "iojs-v3.2"
+ - node_js: "iojs-v3.1"
+ - node_js: "iojs-v3.0"
+ - node_js: "iojs-v2.4"
+ - node_js: "iojs-v2.3"
+ - node_js: "iojs-v2.2"
+ - node_js: "iojs-v2.1"
+ - node_js: "iojs-v2.0"
+ - node_js: "iojs-v1.7"
+ - node_js: "iojs-v1.6"
+ - node_js: "iojs-v1.5"
+ - node_js: "iojs-v1.4"
+ - node_js: "iojs-v1.3"
+ - node_js: "iojs-v1.2"
+ - node_js: "iojs-v1.1"
+ - node_js: "iojs-v1.0"
+ - node_js: "0.11"
+ - node_js: "0.9"
+ - node_js: "0.6"
+ - node_js: "0.4"
diff --git a/node_modules/request/node_modules/qs/CHANGELOG.md b/node_modules/request/node_modules/qs/CHANGELOG.md
index e43b1aceb..2df5e9d37 100644
--- a/node_modules/request/node_modules/qs/CHANGELOG.md
+++ b/node_modules/request/node_modules/qs/CHANGELOG.md
@@ -1,99 +1,110 @@
+## [**6.0.2**](https://github.com/ljharb/qs/issues?milestone=33&state=closed)
+- Revert ES6 requirement and restore support for node down to v0.8.
-## [**5.1.0**](https://github.com/hapijs/qs/issues?milestone=29&state=open)
-- [**#117**](https://github.com/hapijs/qs/issues/117) make URI encoding stringified results optional
-- [**#106**](https://github.com/hapijs/qs/issues/106) Add flag `skipNulls` to optionally skip null values in stringify
+## [**6.0.1**](https://github.com/ljharb/qs/issues?milestone=32&state=closed)
+- [**#127**](https://github.com/ljharb/qs/pull/127) Fix engines definition in package.json
-## [**5.0.0**](https://github.com/hapijs/qs/issues?milestone=28&state=closed)
-- [**#114**](https://github.com/hapijs/qs/issues/114) default allowDots to false
-- [**#100**](https://github.com/hapijs/qs/issues/100) include dist to npm
+## [**6.0.0**](https://github.com/ljharb/qs/issues?milestone=31&state=closed)
+- [**#124**](https://github.com/ljharb/qs/issues/124) Use ES6 and drop support for node < v4
-## [**4.0.0**](https://github.com/hapijs/qs/issues?milestone=26&state=closed)
-- [**#98**](https://github.com/hapijs/qs/issues/98) make returning plain objects and allowing prototype overwriting properties optional
+## [**5.2.0**](https://github.com/ljharb/qs/issues?milestone=30&state=closed)
+- [**#64**](https://github.com/ljharb/qs/issues/64) Add option to sort object keys in the query string
-## [**3.1.0**](https://github.com/hapijs/qs/issues?milestone=24&state=closed)
-- [**#89**](https://github.com/hapijs/qs/issues/89) Add option to disable "Transform dot notation to bracket notation"
+## [**5.1.0**](https://github.com/ljharb/qs/issues?milestone=29&state=closed)
+- [**#117**](https://github.com/ljharb/qs/issues/117) make URI encoding stringified results optional
+- [**#106**](https://github.com/ljharb/qs/issues/106) Add flag `skipNulls` to optionally skip null values in stringify
-## [**3.0.0**](https://github.com/hapijs/qs/issues?milestone=23&state=closed)
-- [**#80**](https://github.com/hapijs/qs/issues/80) qs.parse silently drops properties
-- [**#77**](https://github.com/hapijs/qs/issues/77) Perf boost
-- [**#60**](https://github.com/hapijs/qs/issues/60) Add explicit option to disable array parsing
-- [**#74**](https://github.com/hapijs/qs/issues/74) Bad parse when turning array into object
-- [**#81**](https://github.com/hapijs/qs/issues/81) Add a `filter` option
-- [**#68**](https://github.com/hapijs/qs/issues/68) Fixed issue with recursion and passing strings into objects.
-- [**#66**](https://github.com/hapijs/qs/issues/66) Add mixed array and object dot notation support Closes: #47
-- [**#76**](https://github.com/hapijs/qs/issues/76) RFC 3986
-- [**#85**](https://github.com/hapijs/qs/issues/85) No equal sign
-- [**#84**](https://github.com/hapijs/qs/issues/84) update license attribute
+## [**5.0.0**](https://github.com/ljharb/qs/issues?milestone=28&state=closed)
+- [**#114**](https://github.com/ljharb/qs/issues/114) default allowDots to false
+- [**#100**](https://github.com/ljharb/qs/issues/100) include dist to npm
-## [**2.4.1**](https://github.com/hapijs/qs/issues?milestone=20&state=closed)
-- [**#73**](https://github.com/hapijs/qs/issues/73) Property 'hasOwnProperty' of object #<Object> is not a function
+## [**4.0.0**](https://github.com/ljharb/qs/issues?milestone=26&state=closed)
+- [**#98**](https://github.com/ljharb/qs/issues/98) make returning plain objects and allowing prototype overwriting properties optional
-## [**2.4.0**](https://github.com/hapijs/qs/issues?milestone=19&state=closed)
-- [**#70**](https://github.com/hapijs/qs/issues/70) Add arrayFormat option
+## [**3.1.0**](https://github.com/ljharb/qs/issues?milestone=24&state=closed)
+- [**#89**](https://github.com/ljharb/qs/issues/89) Add option to disable "Transform dot notation to bracket notation"
-## [**2.3.3**](https://github.com/hapijs/qs/issues?milestone=18&state=closed)
-- [**#59**](https://github.com/hapijs/qs/issues/59) make sure array indexes are >= 0, closes #57
-- [**#58**](https://github.com/hapijs/qs/issues/58) make qs usable for browser loader
+## [**3.0.0**](https://github.com/ljharb/qs/issues?milestone=23&state=closed)
+- [**#80**](https://github.com/ljharb/qs/issues/80) qs.parse silently drops properties
+- [**#77**](https://github.com/ljharb/qs/issues/77) Perf boost
+- [**#60**](https://github.com/ljharb/qs/issues/60) Add explicit option to disable array parsing
+- [**#74**](https://github.com/ljharb/qs/issues/74) Bad parse when turning array into object
+- [**#81**](https://github.com/ljharb/qs/issues/81) Add a `filter` option
+- [**#68**](https://github.com/ljharb/qs/issues/68) Fixed issue with recursion and passing strings into objects.
+- [**#66**](https://github.com/ljharb/qs/issues/66) Add mixed array and object dot notation support Closes: #47
+- [**#76**](https://github.com/ljharb/qs/issues/76) RFC 3986
+- [**#85**](https://github.com/ljharb/qs/issues/85) No equal sign
+- [**#84**](https://github.com/ljharb/qs/issues/84) update license attribute
-## [**2.3.2**](https://github.com/hapijs/qs/issues?milestone=17&state=closed)
-- [**#55**](https://github.com/hapijs/qs/issues/55) allow merging a string into an object
+## [**2.4.1**](https://github.com/ljharb/qs/issues?milestone=20&state=closed)
+- [**#73**](https://github.com/ljharb/qs/issues/73) Property 'hasOwnProperty' of object #<Object> is not a function
-## [**2.3.1**](https://github.com/hapijs/qs/issues?milestone=16&state=closed)
-- [**#52**](https://github.com/hapijs/qs/issues/52) Return "undefined" and "false" instead of throwing "TypeError".
+## [**2.4.0**](https://github.com/ljharb/qs/issues?milestone=19&state=closed)
+- [**#70**](https://github.com/ljharb/qs/issues/70) Add arrayFormat option
-## [**2.3.0**](https://github.com/hapijs/qs/issues?milestone=15&state=closed)
-- [**#50**](https://github.com/hapijs/qs/issues/50) add option to omit array indices, closes #46
+## [**2.3.3**](https://github.com/ljharb/qs/issues?milestone=18&state=closed)
+- [**#59**](https://github.com/ljharb/qs/issues/59) make sure array indexes are >= 0, closes #57
+- [**#58**](https://github.com/ljharb/qs/issues/58) make qs usable for browser loader
-## [**2.2.5**](https://github.com/hapijs/qs/issues?milestone=14&state=closed)
-- [**#39**](https://github.com/hapijs/qs/issues/39) Is there an alternative to Buffer.isBuffer?
-- [**#49**](https://github.com/hapijs/qs/issues/49) refactor utils.merge, fixes #45
-- [**#41**](https://github.com/hapijs/qs/issues/41) avoid browserifying Buffer, for #39
+## [**2.3.2**](https://github.com/ljharb/qs/issues?milestone=17&state=closed)
+- [**#55**](https://github.com/ljharb/qs/issues/55) allow merging a string into an object
-## [**2.2.4**](https://github.com/hapijs/qs/issues?milestone=13&state=closed)
-- [**#38**](https://github.com/hapijs/qs/issues/38) how to handle object keys beginning with a number
+## [**2.3.1**](https://github.com/ljharb/qs/issues?milestone=16&state=closed)
+- [**#52**](https://github.com/ljharb/qs/issues/52) Return "undefined" and "false" instead of throwing "TypeError".
-## [**2.2.3**](https://github.com/hapijs/qs/issues?milestone=12&state=closed)
-- [**#37**](https://github.com/hapijs/qs/issues/37) parser discards first empty value in array
-- [**#36**](https://github.com/hapijs/qs/issues/36) Update to lab 4.x
+## [**2.3.0**](https://github.com/ljharb/qs/issues?milestone=15&state=closed)
+- [**#50**](https://github.com/ljharb/qs/issues/50) add option to omit array indices, closes #46
-## [**2.2.2**](https://github.com/hapijs/qs/issues?milestone=11&state=closed)
-- [**#33**](https://github.com/hapijs/qs/issues/33) Error when plain object in a value
-- [**#34**](https://github.com/hapijs/qs/issues/34) use Object.prototype.hasOwnProperty.call instead of obj.hasOwnProperty
-- [**#24**](https://github.com/hapijs/qs/issues/24) Changelog? Semver?
+## [**2.2.5**](https://github.com/ljharb/qs/issues?milestone=14&state=closed)
+- [**#39**](https://github.com/ljharb/qs/issues/39) Is there an alternative to Buffer.isBuffer?
+- [**#49**](https://github.com/ljharb/qs/issues/49) refactor utils.merge, fixes #45
+- [**#41**](https://github.com/ljharb/qs/issues/41) avoid browserifying Buffer, for #39
-## [**2.2.1**](https://github.com/hapijs/qs/issues?milestone=10&state=closed)
-- [**#32**](https://github.com/hapijs/qs/issues/32) account for circular references properly, closes #31
-- [**#31**](https://github.com/hapijs/qs/issues/31) qs.parse stackoverflow on circular objects
+## [**2.2.4**](https://github.com/ljharb/qs/issues?milestone=13&state=closed)
+- [**#38**](https://github.com/ljharb/qs/issues/38) how to handle object keys beginning with a number
-## [**2.2.0**](https://github.com/hapijs/qs/issues?milestone=9&state=closed)
-- [**#26**](https://github.com/hapijs/qs/issues/26) Don't use Buffer global if it's not present
-- [**#30**](https://github.com/hapijs/qs/issues/30) Bug when merging non-object values into arrays
-- [**#29**](https://github.com/hapijs/qs/issues/29) Don't call Utils.clone at the top of Utils.merge
-- [**#23**](https://github.com/hapijs/qs/issues/23) Ability to not limit parameters?
+## [**2.2.3**](https://github.com/ljharb/qs/issues?milestone=12&state=closed)
+- [**#37**](https://github.com/ljharb/qs/issues/37) parser discards first empty value in array
+- [**#36**](https://github.com/ljharb/qs/issues/36) Update to lab 4.x
-## [**2.1.0**](https://github.com/hapijs/qs/issues?milestone=8&state=closed)
-- [**#22**](https://github.com/hapijs/qs/issues/22) Enable using a RegExp as delimiter
+## [**2.2.2**](https://github.com/ljharb/qs/issues?milestone=11&state=closed)
+- [**#33**](https://github.com/ljharb/qs/issues/33) Error when plain object in a value
+- [**#34**](https://github.com/ljharb/qs/issues/34) use Object.prototype.hasOwnProperty.call instead of obj.hasOwnProperty
+- [**#24**](https://github.com/ljharb/qs/issues/24) Changelog? Semver?
-## [**2.0.0**](https://github.com/hapijs/qs/issues?milestone=7&state=closed)
-- [**#18**](https://github.com/hapijs/qs/issues/18) Why is there arrayLimit?
-- [**#20**](https://github.com/hapijs/qs/issues/20) Configurable parametersLimit
-- [**#21**](https://github.com/hapijs/qs/issues/21) make all limits optional, for #18, for #20
+## [**2.2.1**](https://github.com/ljharb/qs/issues?milestone=10&state=closed)
+- [**#32**](https://github.com/ljharb/qs/issues/32) account for circular references properly, closes #31
+- [**#31**](https://github.com/ljharb/qs/issues/31) qs.parse stackoverflow on circular objects
-## [**1.2.2**](https://github.com/hapijs/qs/issues?milestone=6&state=closed)
-- [**#19**](https://github.com/hapijs/qs/issues/19) Don't overwrite null values
+## [**2.2.0**](https://github.com/ljharb/qs/issues?milestone=9&state=closed)
+- [**#26**](https://github.com/ljharb/qs/issues/26) Don't use Buffer global if it's not present
+- [**#30**](https://github.com/ljharb/qs/issues/30) Bug when merging non-object values into arrays
+- [**#29**](https://github.com/ljharb/qs/issues/29) Don't call Utils.clone at the top of Utils.merge
+- [**#23**](https://github.com/ljharb/qs/issues/23) Ability to not limit parameters?
-## [**1.2.1**](https://github.com/hapijs/qs/issues?milestone=5&state=closed)
-- [**#16**](https://github.com/hapijs/qs/issues/16) ignore non-string delimiters
-- [**#15**](https://github.com/hapijs/qs/issues/15) Close code block
+## [**2.1.0**](https://github.com/ljharb/qs/issues?milestone=8&state=closed)
+- [**#22**](https://github.com/ljharb/qs/issues/22) Enable using a RegExp as delimiter
-## [**1.2.0**](https://github.com/hapijs/qs/issues?milestone=4&state=closed)
-- [**#12**](https://github.com/hapijs/qs/issues/12) Add optional delim argument
-- [**#13**](https://github.com/hapijs/qs/issues/13) fix #11: flattened keys in array are now correctly parsed
+## [**2.0.0**](https://github.com/ljharb/qs/issues?milestone=7&state=closed)
+- [**#18**](https://github.com/ljharb/qs/issues/18) Why is there arrayLimit?
+- [**#20**](https://github.com/ljharb/qs/issues/20) Configurable parametersLimit
+- [**#21**](https://github.com/ljharb/qs/issues/21) make all limits optional, for #18, for #20
-## [**1.1.0**](https://github.com/hapijs/qs/issues?milestone=3&state=closed)
-- [**#7**](https://github.com/hapijs/qs/issues/7) Empty values of a POST array disappear after being submitted
-- [**#9**](https://github.com/hapijs/qs/issues/9) Should not omit equals signs (=) when value is null
-- [**#6**](https://github.com/hapijs/qs/issues/6) Minor grammar fix in README
+## [**1.2.2**](https://github.com/ljharb/qs/issues?milestone=6&state=closed)
+- [**#19**](https://github.com/ljharb/qs/issues/19) Don't overwrite null values
-## [**1.0.2**](https://github.com/hapijs/qs/issues?milestone=2&state=closed)
-- [**#5**](https://github.com/hapijs/qs/issues/5) array holes incorrectly copied into object on large index
+## [**1.2.1**](https://github.com/ljharb/qs/issues?milestone=5&state=closed)
+- [**#16**](https://github.com/ljharb/qs/issues/16) ignore non-string delimiters
+- [**#15**](https://github.com/ljharb/qs/issues/15) Close code block
+
+## [**1.2.0**](https://github.com/ljharb/qs/issues?milestone=4&state=closed)
+- [**#12**](https://github.com/ljharb/qs/issues/12) Add optional delim argument
+- [**#13**](https://github.com/ljharb/qs/issues/13) fix #11: flattened keys in array are now correctly parsed
+
+## [**1.1.0**](https://github.com/ljharb/qs/issues?milestone=3&state=closed)
+- [**#7**](https://github.com/ljharb/qs/issues/7) Empty values of a POST array disappear after being submitted
+- [**#9**](https://github.com/ljharb/qs/issues/9) Should not omit equals signs (=) when value is null
+- [**#6**](https://github.com/ljharb/qs/issues/6) Minor grammar fix in README
+
+## [**1.0.2**](https://github.com/ljharb/qs/issues?milestone=2&state=closed)
+- [**#5**](https://github.com/ljharb/qs/issues/5) array holes incorrectly copied into object on large index
diff --git a/node_modules/request/node_modules/qs/README.md b/node_modules/request/node_modules/qs/README.md
index 3c61db31a..335eafb4b 100644
--- a/node_modules/request/node_modules/qs/README.md
+++ b/node_modules/request/node_modules/qs/README.md
@@ -2,76 +2,82 @@
A querystring parsing and stringifying library with some added security.
-[![Build Status](https://secure.travis-ci.org/hapijs/qs.svg)](http://travis-ci.org/hapijs/qs)
+[![Build Status](https://api.travis-ci.org/ljharb/qs.svg)](http://travis-ci.org/ljharb/qs)
-Lead Maintainer: [Nathan LaFreniere](https://github.com/nlf)
+Lead Maintainer: [Jordan Harband](https://github.com/ljharb)
The **qs** module was originally created and maintained by [TJ Holowaychuk](https://github.com/visionmedia/node-querystring).
## Usage
```javascript
-var Qs = require('qs');
+var qs = require('qs');
+var assert = require('assert');
-var obj = Qs.parse('a=c'); // { a: 'c' }
-var str = Qs.stringify(obj); // 'a=c'
+var obj = qs.parse('a=c');
+assert.deepEqual(obj, { a: 'c' });
+
+var str = qs.stringify(obj);
+assert.equal(str, 'a=c');
```
### Parsing Objects
+[](#preventEval)
```javascript
-Qs.parse(string, [options]);
+qs.parse(string, [options]);
```
**qs** allows you to create nested objects within your query strings, by surrounding the name of sub-keys with square brackets `[]`.
For example, the string `'foo[bar]=baz'` converts to:
```javascript
-{
+assert.deepEqual(qs.parse('foo[bar]=baz'), {
foo: {
bar: 'baz'
}
-}
+});
```
When using the `plainObjects` option the parsed value is returned as a plain object, created via `Object.create(null)` and as such you should be aware that prototype methods will not exist on it and a user may set those names to whatever value they like:
```javascript
-Qs.parse('a.hasOwnProperty=b', { plainObjects: true });
-// { a: { hasOwnProperty: 'b' } }
+var plainObject = qs.parse('a[hasOwnProperty]=b', { plainObjects: true });
+assert.deepEqual(plainObject, { a: { hasOwnProperty: 'b' } });
```
By default parameters that would overwrite properties on the object prototype are ignored, if you wish to keep the data from those fields either use `plainObjects` as mentioned above, or set `allowPrototypes` to `true` which will allow user input to overwrite those properties. *WARNING* It is generally a bad idea to enable this option as it can cause problems when attempting to use the properties that have been overwritten. Always be careful with this option.
```javascript
-Qs.parse('a.hasOwnProperty=b', { allowPrototypes: true });
-// { a: { hasOwnProperty: 'b' } }
+var protoObject = qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true });
+assert.deepEqual(protoObject, { a: { hasOwnProperty: 'b' } });
```
URI encoded strings work too:
```javascript
-Qs.parse('a%5Bb%5D=c');
-// { a: { b: 'c' } }
+assert.deepEqual(qs.parse('a%5Bb%5D=c'), {
+ a: { b: 'c' }
+});
```
You can also nest your objects, like `'foo[bar][baz]=foobarbaz'`:
```javascript
-{
+assert.deepEqual(qs.parse('foo[bar][baz]=foobarbaz'), {
foo: {
bar: {
baz: 'foobarbaz'
}
}
-}
+});
```
By default, when nesting objects **qs** will only parse up to 5 children deep. This means if you attempt to parse a string like
`'a[b][c][d][e][f][g][h][i]=j'` your resulting object will be:
```javascript
-{
+var expected = {
a: {
b: {
c: {
@@ -85,14 +91,16 @@ By default, when nesting objects **qs** will only parse up to 5 children deep. T
}
}
}
-}
+};
+var string = 'a[b][c][d][e][f][g][h][i]=j';
+assert.deepEqual(qs.parse(string), expected);
```
-This depth can be overridden by passing a `depth` option to `Qs.parse(string, [options])`:
+This depth can be overridden by passing a `depth` option to `qs.parse(string, [options])`:
```javascript
-Qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1 });
-// { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } }
+var deep = qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1 });
+assert.deepEqual(deep, { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } });
```
The depth limit helps mitigate abuse when **qs** is used to parse user input, and it is recommended to keep it a reasonably small number.
@@ -100,29 +108,29 @@ The depth limit helps mitigate abuse when **qs** is used to parse user input, an
For similar reasons, by default **qs** will only parse up to 1000 parameters. This can be overridden by passing a `parameterLimit` option:
```javascript
-Qs.parse('a=b&c=d', { parameterLimit: 1 });
-// { a: 'b' }
+var limited = qs.parse('a=b&c=d', { parameterLimit: 1 });
+assert.deepEqual(limited, { a: 'b' });
```
An optional delimiter can also be passed:
```javascript
-Qs.parse('a=b;c=d', { delimiter: ';' });
-// { a: 'b', c: 'd' }
+var delimited = qs.parse('a=b;c=d', { delimiter: ';' });
+assert.deepEqual(delimited, { a: 'b', c: 'd' });
```
Delimiters can be a regular expression too:
```javascript
-Qs.parse('a=b;c=d,e=f', { delimiter: /[;,]/ });
-// { a: 'b', c: 'd', e: 'f' }
+var regexed = qs.parse('a=b;c=d,e=f', { delimiter: /[;,]/ });
+assert.deepEqual(regexed, { a: 'b', c: 'd', e: 'f' });
```
Option `allowDots` can be used to enable dot notation:
```javascript
-Qs.parse('a.b=c', { allowDots: true });
-// { a: { b: 'c' } }
+var withDots = qs.parse('a.b=c', { allowDots: true });
+assert.deepEqual(withDots, { a: { b: 'c' } });
```
### Parsing Arrays
@@ -130,15 +138,15 @@ Qs.parse('a.b=c', { allowDots: true });
**qs** can also parse arrays using a similar `[]` notation:
```javascript
-Qs.parse('a[]=b&a[]=c');
-// { a: ['b', 'c'] }
+var withArray = qs.parse('a[]=b&a[]=c');
+assert.deepEqual(withArray, { a: ['b', 'c'] });
```
You may specify an index as well:
```javascript
-Qs.parse('a[1]=c&a[0]=b');
-// { a: ['b', 'c'] }
+var withIndexes = qs.parse('a[1]=c&a[0]=b');
+assert.deepEqual(withIndexes, { a: ['b', 'c'] });
```
Note that the only difference between an index in an array and a key in an object is that the value between the brackets must be a number
@@ -146,75 +154,75 @@ to create an array. When creating arrays with specific indices, **qs** will comp
their order:
```javascript
-Qs.parse('a[1]=b&a[15]=c');
-// { a: ['b', 'c'] }
+var noSparse = qs.parse('a[1]=b&a[15]=c');
+assert.deepEqual(noSparse, { a: ['b', 'c'] });
```
Note that an empty string is also a value, and will be preserved:
```javascript
-Qs.parse('a[]=&a[]=b');
-// { a: ['', 'b'] }
-Qs.parse('a[0]=b&a[1]=&a[2]=c');
-// { a: ['b', '', 'c'] }
+var withEmptyString = qs.parse('a[]=&a[]=b');
+assert.deepEqual(withEmptyString, { a: ['', 'b'] });
+
+var withIndexedEmptyString = qs.parse('a[0]=b&a[1]=&a[2]=c');
+assert.deepEqual(withIndexedEmptyString, { a: ['b', '', 'c'] });
```
**qs** will also limit specifying indices in an array to a maximum index of `20`. Any array members with an index of greater than `20` will
instead be converted to an object with the index as the key:
```javascript
-Qs.parse('a[100]=b');
-// { a: { '100': 'b' } }
+var withMaxIndex = qs.parse('a[100]=b');
+assert.deepEqual(withMaxIndex, { a: { '100': 'b' } });
```
This limit can be overridden by passing an `arrayLimit` option:
```javascript
-Qs.parse('a[1]=b', { arrayLimit: 0 });
-// { a: { '1': 'b' } }
+var withArrayLimit = qs.parse('a[1]=b', { arrayLimit: 0 });
+assert.deepEqual(withArrayLimit, { a: { '1': 'b' } });
```
To disable array parsing entirely, set `parseArrays` to `false`.
```javascript
-Qs.parse('a[]=b', { parseArrays: false });
-// { a: { '0': 'b' } }
+var noParsingArrays = qs.parse('a[]=b', { parseArrays: false });
+assert.deepEqual(noParsingArrays, { a: { '0': 'b' } });
```
If you mix notations, **qs** will merge the two items into an object:
```javascript
-Qs.parse('a[0]=b&a[b]=c');
-// { a: { '0': 'b', b: 'c' } }
+var mixedNotation = qs.parse('a[0]=b&a[b]=c');
+assert.deepEqual(mixedNotation, { a: { '0': 'b', b: 'c' } });
```
You can also create arrays of objects:
```javascript
-Qs.parse('a[][b]=c');
-// { a: [{ b: 'c' }] }
+var arraysOfObjects = qs.parse('a[][b]=c');
+assert.deepEqual(arraysOfObjects, { a: [{ b: 'c' }] });
```
### Stringifying
+[](#preventEval)
```javascript
-Qs.stringify(object, [options]);
+qs.stringify(object, [options]);
```
When stringifying, **qs** by default URI encodes output. Objects are stringified as you would expect:
```javascript
-Qs.stringify({ a: 'b' });
-// 'a=b'
-Qs.stringify({ a: { b: 'c' } });
-// 'a%5Bb%5D=c'
+assert.equal(qs.stringify({ a: 'b' }), 'a=b');
+assert.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c');
```
This encoding can be disabled by setting the `encode` option to `false`:
```javascript
-Qs.stringify({ a: { b: 'c' } }, { encode: false });
-// 'a[b]=c'
+var unencoded = qs.stringify({ a: { b: 'c' } }, { encode: false });
+assert.equal(unencoded, 'a[b]=c');
```
Examples beyond this point will be shown as though the output is not URI encoded for clarity. Please note that the return values in these cases *will* be URI encoded during real usage.
@@ -222,47 +230,44 @@ Examples beyond this point will be shown as though the output is not URI encoded
When arrays are stringified, by default they are given explicit indices:
```javascript
-Qs.stringify({ a: ['b', 'c', 'd'] });
+qs.stringify({ a: ['b', 'c', 'd'] });
// 'a[0]=b&a[1]=c&a[2]=d'
```
You may override this by setting the `indices` option to `false`:
```javascript
-Qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false });
+qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false });
// 'a=b&a=c&a=d'
```
You may use the `arrayFormat` option to specify the format of the output array
```javascript
-Qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' })
+qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' })
// 'a[0]=b&a[1]=c'
-Qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' })
+qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' })
// 'a[]=b&a[]=c'
-Qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' })
+qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' })
// 'a=b&a=c'
```
Empty strings and null values will omit the value, but the equals sign (=) remains in place:
```javascript
-Qs.stringify({ a: '' });
-// 'a='
+assert.equal(qs.stringify({ a: '' }), 'a=');
```
Properties that are set to `undefined` will be omitted entirely:
```javascript
-Qs.stringify({ a: null, b: undefined });
-// 'a='
+assert.equal(qs.stringify({ a: null, b: undefined }), 'a=');
```
The delimiter may be overridden with stringify as well:
```javascript
-Qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' });
-// 'a=b;c=d'
+assert.equal(qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }), 'a=b;c=d');
```
Finally, you can use the `filter` option to restrict which keys will be included in the stringified output.
@@ -283,11 +288,11 @@ function filterFunc(prefix, value) {
}
return value;
}
-Qs.stringify({ a: 'b', c: 'd', e: { f: new Date(123), g: [2] } }, { filter: filterFunc })
+qs.stringify({ a: 'b', c: 'd', e: { f: new Date(123), g: [2] } }, { filter: filterFunc });
// 'a=b&c=d&e[f]=123&e[g][0]=4'
-Qs.stringify({ a: 'b', c: 'd', e: 'f' }, { filter: ['a', 'e'] })
+qs.stringify({ a: 'b', c: 'd', e: 'f' }, { filter: ['a', 'e'] });
// 'a=b&e=f'
-Qs.stringify({ a: ['b', 'c', 'd'], e: 'f' }, { filter: ['a', 0, 2] })
+qs.stringify({ a: ['b', 'c', 'd'], e: 'f' }, { filter: ['a', 0, 2] });
// 'a[0]=b&a[2]=d'
```
@@ -296,36 +301,35 @@ Qs.stringify({ a: ['b', 'c', 'd'], e: 'f' }, { filter: ['a', 0, 2] })
By default, `null` values are treated like empty strings:
```javascript
-Qs.stringify({ a: null, b: '' });
-// 'a=&b='
+var withNull = qs.stringify({ a: null, b: '' });
+assert.equal(withNull, 'a=&b=');
```
Parsing does not distinguish between parameters with and without equal signs. Both are converted to empty strings.
```javascript
-Qs.parse('a&b=')
-// { a: '', b: '' }
+var equalsInsensitive = qs.parse('a&b=');
+assert.deepEqual(equalsInsensitive, { a: '', b: '' });
```
To distinguish between `null` values and empty strings use the `strictNullHandling` flag. In the result string the `null`
values have no `=` sign:
```javascript
-Qs.stringify({ a: null, b: '' }, { strictNullHandling: true });
-// 'a&b='
+var strictNull = qs.stringify({ a: null, b: '' }, { strictNullHandling: true });
+assert.equal(strictNull, 'a&b=');
```
To parse values without `=` back to `null` use the `strictNullHandling` flag:
```javascript
-Qs.parse('a&b=', { strictNullHandling: true });
-// { a: null, b: '' }
-
+var parsedStrictNull = qs.parse('a&b=', { strictNullHandling: true });
+assert.deepEqual(parsedStrictNull, { a: null, b: '' });
```
To completely skip rendering keys with `null` values, use the `skipNulls` flag:
```javascript
-qs.stringify({ a: 'b', c: null}, { skipNulls: true })
-// 'a=b'
+var nullsSkipped = qs.stringify({ a: 'b', c: null}, { skipNulls: true });
+assert.equal(nullsSkipped, 'a=b');
```
diff --git a/node_modules/request/node_modules/qs/bower.json b/node_modules/request/node_modules/qs/bower.json
index 53a70d0c9..8b21420a6 100644
--- a/node_modules/request/node_modules/qs/bower.json
+++ b/node_modules/request/node_modules/qs/bower.json
@@ -1,7 +1,7 @@
{
"name": "qs",
"main": "dist/qs.js",
- "version": "5.1.0",
+ "version": "5.2.0",
"homepage": "https://github.com/hapijs/qs",
"authors": [
"Nathan LaFreniere <quitlahok@gmail.com>"
diff --git a/node_modules/request/node_modules/qs/component.json b/node_modules/request/node_modules/qs/component.json
index 1a1f72c7a..fca856a63 100644
--- a/node_modules/request/node_modules/qs/component.json
+++ b/node_modules/request/node_modules/qs/component.json
@@ -2,7 +2,7 @@
"name": "qs",
"repository": "hapijs/qs",
"description": "query-string parser / stringifier with nesting support",
- "version": "5.1.0",
+ "version": "5.2.0",
"keywords": ["querystring", "query", "parser"],
"main": "lib/index.js",
"scripts": [
diff --git a/node_modules/request/node_modules/qs/dist/qs.js b/node_modules/request/node_modules/qs/dist/qs.js
index b72e97682..68433d45a 100644
--- a/node_modules/request/node_modules/qs/dist/qs.js
+++ b/node_modules/request/node_modules/qs/dist/qs.js
@@ -1,28 +1,19 @@
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Qs = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
-// Load modules
+'use strict';
var Stringify = require('./stringify');
var Parse = require('./parse');
-
-// Declare internals
-
-var internals = {};
-
-
module.exports = {
stringify: Stringify,
parse: Parse
};
},{"./parse":2,"./stringify":3}],2:[function(require,module,exports){
-// Load modules
+'use strict';
var Utils = require('./utils');
-
-// Declare internals
-
var internals = {
delimiter: '&',
depth: 5,
@@ -34,13 +25,11 @@ var internals = {
allowDots: false
};
-
internals.parseValues = function (str, options) {
-
var obj = {};
var parts = str.split(options.delimiter, options.parameterLimit === Infinity ? undefined : options.parameterLimit);
- for (var i = 0, il = parts.length; i < il; ++i) {
+ for (var i = 0; i < parts.length; ++i) {
var part = parts[i];
var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1;
@@ -50,16 +39,14 @@ internals.parseValues = function (str, options) {
if (options.strictNullHandling) {
obj[Utils.decode(part)] = null;
}
- }
- else {
+ } else {
var key = Utils.decode(part.slice(0, pos));
var val = Utils.decode(part.slice(pos + 1));
- if (!Object.prototype.hasOwnProperty.call(obj, key)) {
- obj[key] = val;
- }
- else {
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
obj[key] = [].concat(obj[key]).concat(val);
+ } else {
+ obj[key] = val;
}
}
}
@@ -67,9 +54,7 @@ internals.parseValues = function (str, options) {
return obj;
};
-
internals.parseObject = function (chain, val, options) {
-
if (!chain.length) {
return val;
}
@@ -80,23 +65,20 @@ internals.parseObject = function (chain, val, options) {
if (root === '[]') {
obj = [];
obj = obj.concat(internals.parseObject(chain, val, options));
- }
- else {
+ } else {
obj = options.plainObjects ? Object.create(null) : {};
var cleanRoot = root[0] === '[' && root[root.length - 1] === ']' ? root.slice(1, root.length - 1) : root;
var index = parseInt(cleanRoot, 10);
- var indexString = '' + index;
- if (!isNaN(index) &&
+ if (
+ !isNaN(index) &&
root !== cleanRoot &&
- indexString === cleanRoot &&
+ String(index) === cleanRoot &&
index >= 0 &&
- (options.parseArrays &&
- index <= options.arrayLimit)) {
-
+ (options.parseArrays && index <= options.arrayLimit)
+ ) {
obj = [];
obj[index] = internals.parseObject(chain, val, options);
- }
- else {
+ } else {
obj[cleanRoot] = internals.parseObject(chain, val, options);
}
}
@@ -104,18 +86,13 @@ internals.parseObject = function (chain, val, options) {
return obj;
};
-
-internals.parseKeys = function (key, val, options) {
-
- if (!key) {
+internals.parseKeys = function (givenKey, val, options) {
+ if (!givenKey) {
return;
}
// Transform dot notation to bracket notation
-
- if (options.allowDots) {
- key = key.replace(/\.([^\.\[]+)/g, '[$1]');
- }
+ var key = options.allowDots ? givenKey.replace(/\.([^\.\[]+)/g, '[$1]') : givenKey;
// The regex chunks
@@ -132,9 +109,7 @@ internals.parseKeys = function (key, val, options) {
if (segment[1]) {
// If we aren't using plain objects, optionally prefix keys
// that would overwrite object prototype properties
- if (!options.plainObjects &&
- Object.prototype.hasOwnProperty(segment[1])) {
-
+ if (!options.plainObjects && Object.prototype.hasOwnProperty(segment[1])) {
if (!options.allowPrototypes) {
return;
}
@@ -147,11 +122,8 @@ internals.parseKeys = function (key, val, options) {
var i = 0;
while ((segment = child.exec(key)) !== null && i < options.depth) {
-
- ++i;
- if (!options.plainObjects &&
- Object.prototype.hasOwnProperty(segment[1].replace(/\[|\]/g, ''))) {
-
+ i += 1;
+ if (!options.plainObjects && Object.prototype.hasOwnProperty(segment[1].replace(/\[|\]/g, ''))) {
if (!options.allowPrototypes) {
continue;
}
@@ -168,10 +140,8 @@ internals.parseKeys = function (key, val, options) {
return internals.parseObject(keys, val, options);
};
-
-module.exports = function (str, options) {
-
- options = options || {};
+module.exports = function (str, opts) {
+ var options = opts || {};
options.delimiter = typeof options.delimiter === 'string' || Utils.isRegExp(options.delimiter) ? options.delimiter : internals.delimiter;
options.depth = typeof options.depth === 'number' ? options.depth : internals.depth;
options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : internals.arrayLimit;
@@ -182,10 +152,11 @@ module.exports = function (str, options) {
options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : internals.parameterLimit;
options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : internals.strictNullHandling;
- if (str === '' ||
+ if (
+ str === '' ||
str === null ||
- typeof str === 'undefined') {
-
+ typeof str === 'undefined'
+ ) {
return options.plainObjects ? Object.create(null) : {};
}
@@ -195,7 +166,7 @@ module.exports = function (str, options) {
// Iterate over the keys and setup the new object
var keys = Object.keys(tempObj);
- for (var i = 0, il = keys.length; i < il; ++i) {
+ for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var newObj = internals.parseKeys(key, tempObj[key], options);
obj = Utils.merge(obj, newObj, options);
@@ -205,26 +176,20 @@ module.exports = function (str, options) {
};
},{"./utils":4}],3:[function(require,module,exports){
-// Load modules
+'use strict';
var Utils = require('./utils');
-
-// Declare internals
-
var internals = {
delimiter: '&',
arrayPrefixGenerators: {
- brackets: function (prefix, key) {
-
+ brackets: function (prefix) {
return prefix + '[]';
},
indices: function (prefix, key) {
-
return prefix + '[' + key + ']';
},
- repeat: function (prefix, key) {
-
+ repeat: function (prefix) {
return prefix;
}
},
@@ -233,19 +198,15 @@ var internals = {
encode: true
};
-
-internals.stringify = function (obj, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encode, filter) {
-
+internals.stringify = function (object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encode, filter, sort) {
+ var obj = object;
if (typeof filter === 'function') {
obj = filter(prefix, obj);
- }
- else if (Utils.isBuffer(obj)) {
- obj = obj.toString();
- }
- else if (obj instanceof Date) {
+ } else if (Utils.isBuffer(obj)) {
+ obj = String(obj);
+ } else if (obj instanceof Date) {
obj = obj.toISOString();
- }
- else if (obj === null) {
+ } else if (obj === null) {
if (strictNullHandling) {
return encode ? Utils.encode(prefix) : prefix;
}
@@ -253,10 +214,7 @@ internals.stringify = function (obj, prefix, generateArrayPrefix, strictNullHand
obj = '';
}
- if (typeof obj === 'string' ||
- typeof obj === 'number' ||
- typeof obj === 'boolean') {
-
+ if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean') {
if (encode) {
return [Utils.encode(prefix) + '=' + Utils.encode(obj)];
}
@@ -269,20 +227,24 @@ internals.stringify = function (obj, prefix, generateArrayPrefix, strictNullHand
return values;
}
- var objKeys = Array.isArray(filter) ? filter : Object.keys(obj);
- for (var i = 0, il = objKeys.length; i < il; ++i) {
- var key = objKeys[i];
+ var objKeys;
+ if (Array.isArray(filter)) {
+ objKeys = filter;
+ } else {
+ var keys = Object.keys(obj);
+ objKeys = sort ? keys.sort(sort) : keys;
+ }
- if (skipNulls &&
- obj[key] === null) {
+ for (var i = 0; i < objKeys.length; ++i) {
+ var key = objKeys[i];
+ if (skipNulls && obj[key] === null) {
continue;
}
if (Array.isArray(obj)) {
values = values.concat(internals.stringify(obj[key], generateArrayPrefix(prefix, key), generateArrayPrefix, strictNullHandling, skipNulls, encode, filter));
- }
- else {
+ } else {
values = values.concat(internals.stringify(obj[key], prefix + '[' + key + ']', generateArrayPrefix, strictNullHandling, skipNulls, encode, filter));
}
}
@@ -290,40 +252,35 @@ internals.stringify = function (obj, prefix, generateArrayPrefix, strictNullHand
return values;
};
-
-module.exports = function (obj, options) {
-
- options = options || {};
+module.exports = function (object, opts) {
+ var obj = object;
+ var options = opts || {};
var delimiter = typeof options.delimiter === 'undefined' ? internals.delimiter : options.delimiter;
var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : internals.strictNullHandling;
var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : internals.skipNulls;
var encode = typeof options.encode === 'boolean' ? options.encode : internals.encode;
+ var sort = typeof options.sort === 'function' ? options.sort : null;
var objKeys;
var filter;
if (typeof options.filter === 'function') {
filter = options.filter;
obj = filter('', obj);
- }
- else if (Array.isArray(options.filter)) {
+ } else if (Array.isArray(options.filter)) {
objKeys = filter = options.filter;
}
var keys = [];
- if (typeof obj !== 'object' ||
- obj === null) {
-
+ if (typeof obj !== 'object' || obj === null) {
return '';
}
var arrayFormat;
if (options.arrayFormat in internals.arrayPrefixGenerators) {
arrayFormat = options.arrayFormat;
- }
- else if ('indices' in options) {
+ } else if ('indices' in options) {
arrayFormat = options.indices ? 'indices' : 'repeat';
- }
- else {
+ } else {
arrayFormat = 'indices';
}
@@ -333,40 +290,39 @@ module.exports = function (obj, options) {
objKeys = Object.keys(obj);
}
- for (var i = 0, il = objKeys.length; i < il; ++i) {
- var key = objKeys[i];
+ if (sort) {
+ objKeys.sort(sort);
+ }
- if (skipNulls &&
- obj[key] === null) {
+ for (var i = 0; i < objKeys.length; ++i) {
+ var key = objKeys[i];
+ if (skipNulls && obj[key] === null) {
continue;
}
- keys = keys.concat(internals.stringify(obj[key], key, generateArrayPrefix, strictNullHandling, skipNulls, encode, filter));
+ keys = keys.concat(internals.stringify(obj[key], key, generateArrayPrefix, strictNullHandling, skipNulls, encode, filter, sort));
}
return keys.join(delimiter);
};
},{"./utils":4}],4:[function(require,module,exports){
-// Load modules
-
+'use strict';
-// Declare internals
-
-var internals = {};
-internals.hexTable = new Array(256);
-for (var h = 0; h < 256; ++h) {
- internals.hexTable[h] = '%' + ((h < 16 ? '0' : '') + h.toString(16)).toUpperCase();
-}
+var hexTable = (function () {
+ var array = new Array(256);
+ for (var i = 0; i < 256; ++i) {
+ array[i] = '%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase();
+ }
+ return array;
+}());
exports.arrayToObject = function (source, options) {
-
var obj = options.plainObjects ? Object.create(null) : {};
- for (var i = 0, il = source.length; i < il; ++i) {
+ for (var i = 0; i < source.length; ++i) {
if (typeof source[i] !== 'undefined') {
-
obj[i] = source[i];
}
}
@@ -374,9 +330,7 @@ exports.arrayToObject = function (source, options) {
return obj;
};
-
exports.merge = function (target, source, options) {
-
if (!source) {
return target;
}
@@ -384,47 +338,37 @@ exports.merge = function (target, source, options) {
if (typeof source !== 'object') {
if (Array.isArray(target)) {
target.push(source);
- }
- else if (typeof target === 'object') {
+ } else if (typeof target === 'object') {
target[source] = true;
- }
- else {
- target = [target, source];
+ } else {
+ return [target, source];
}
return target;
}
if (typeof target !== 'object') {
- target = [target].concat(source);
- return target;
+ return [target].concat(source);
}
- if (Array.isArray(target) &&
- !Array.isArray(source)) {
-
- target = exports.arrayToObject(target, options);
+ var mergeTarget = target;
+ if (Array.isArray(target) && !Array.isArray(source)) {
+ mergeTarget = exports.arrayToObject(target, options);
}
- var keys = Object.keys(source);
- for (var k = 0, kl = keys.length; k < kl; ++k) {
- var key = keys[k];
+ return Object.keys(source).reduce(function (acc, key) {
var value = source[key];
- if (!Object.prototype.hasOwnProperty.call(target, key)) {
- target[key] = value;
+ if (Object.prototype.hasOwnProperty.call(acc, key)) {
+ acc[key] = exports.merge(acc[key], value, options);
+ } else {
+ acc[key] = value;
}
- else {
- target[key] = exports.merge(target[key], value, options);
- }
- }
-
- return target;
+ return acc;
+ }, mergeTarget);
};
-
exports.decode = function (str) {
-
try {
return decodeURIComponent(str.replace(/\+/g, ' '));
} catch (e) {
@@ -433,65 +377,60 @@ exports.decode = function (str) {
};
exports.encode = function (str) {
-
// This code was originally written by Brian White (mscdex) for the io.js core querystring library.
// It has been adapted here for stricter adherence to RFC 3986
if (str.length === 0) {
return str;
}
- if (typeof str !== 'string') {
- str = '' + str;
- }
+ var string = typeof str === 'string' ? str : String(str);
var out = '';
- for (var i = 0, il = str.length; i < il; ++i) {
- var c = str.charCodeAt(i);
+ for (var i = 0; i < string.length; ++i) {
+ var c = string.charCodeAt(i);
- if (c === 0x2D || // -
+ if (
+ c === 0x2D || // -
c === 0x2E || // .
c === 0x5F || // _
c === 0x7E || // ~
(c >= 0x30 && c <= 0x39) || // 0-9
(c >= 0x41 && c <= 0x5A) || // a-z
- (c >= 0x61 && c <= 0x7A)) { // A-Z
-
- out += str[i];
+ (c >= 0x61 && c <= 0x7A) // A-Z
+ ) {
+ out += string.charAt(i);
continue;
}
if (c < 0x80) {
- out += internals.hexTable[c];
+ out = out + hexTable[c];
continue;
}
if (c < 0x800) {
- out += internals.hexTable[0xC0 | (c >> 6)] + internals.hexTable[0x80 | (c & 0x3F)];
+ out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]);
continue;
}
if (c < 0xD800 || c >= 0xE000) {
- out += internals.hexTable[0xE0 | (c >> 12)] + internals.hexTable[0x80 | ((c >> 6) & 0x3F)] + internals.hexTable[0x80 | (c & 0x3F)];
+ out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);
continue;
}
- ++i;
- c = 0x10000 + (((c & 0x3FF) << 10) | (str.charCodeAt(i) & 0x3FF));
- out += internals.hexTable[0xF0 | (c >> 18)] + internals.hexTable[0x80 | ((c >> 12) & 0x3F)] + internals.hexTable[0x80 | ((c >> 6) & 0x3F)] + internals.hexTable[0x80 | (c & 0x3F)];
+ i += 1;
+ c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));
+ out += (hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);
}
return out;
};
-exports.compact = function (obj, refs) {
-
- if (typeof obj !== 'object' ||
- obj === null) {
-
+exports.compact = function (obj, references) {
+ if (typeof obj !== 'object' || obj === null) {
return obj;
}
- refs = refs || [];
+ var refs = references || [];
var lookup = refs.indexOf(obj);
if (lookup !== -1) {
return refs[lookup];
@@ -502,7 +441,7 @@ exports.compact = function (obj, refs) {
if (Array.isArray(obj)) {
var compacted = [];
- for (var i = 0, il = obj.length; i < il; ++i) {
+ for (var i = 0; i < obj.length; ++i) {
if (typeof obj[i] !== 'undefined') {
compacted.push(obj[i]);
}
@@ -512,32 +451,24 @@ exports.compact = function (obj, refs) {
}
var keys = Object.keys(obj);
- for (i = 0, il = keys.length; i < il; ++i) {
- var key = keys[i];
+ for (var j = 0; j < keys.length; ++j) {
+ var key = keys[j];
obj[key] = exports.compact(obj[key], refs);
}
return obj;
};
-
exports.isRegExp = function (obj) {
-
return Object.prototype.toString.call(obj) === '[object RegExp]';
};
-
exports.isBuffer = function (obj) {
-
- if (obj === null ||
- typeof obj === 'undefined') {
-
+ if (obj === null || typeof obj === 'undefined') {
return false;
}
- return !!(obj.constructor &&
- obj.constructor.isBuffer &&
- obj.constructor.isBuffer(obj));
+ return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
};
},{}]},{},[1])(1)
diff --git a/node_modules/request/node_modules/qs/lib/index.js b/node_modules/request/node_modules/qs/lib/index.js
index 0e094933d..190195902 100644..100755
--- a/node_modules/request/node_modules/qs/lib/index.js
+++ b/node_modules/request/node_modules/qs/lib/index.js
@@ -1,14 +1,8 @@
-// Load modules
+'use strict';
var Stringify = require('./stringify');
var Parse = require('./parse');
-
-// Declare internals
-
-var internals = {};
-
-
module.exports = {
stringify: Stringify,
parse: Parse
diff --git a/node_modules/request/node_modules/qs/lib/parse.js b/node_modules/request/node_modules/qs/lib/parse.js
index 4a2137efa..9b6cbd221 100644..100755
--- a/node_modules/request/node_modules/qs/lib/parse.js
+++ b/node_modules/request/node_modules/qs/lib/parse.js
@@ -1,10 +1,7 @@
-// Load modules
+'use strict';
var Utils = require('./utils');
-
-// Declare internals
-
var internals = {
delimiter: '&',
depth: 5,
@@ -16,13 +13,11 @@ var internals = {
allowDots: false
};
-
internals.parseValues = function (str, options) {
-
var obj = {};
var parts = str.split(options.delimiter, options.parameterLimit === Infinity ? undefined : options.parameterLimit);
- for (var i = 0, il = parts.length; i < il; ++i) {
+ for (var i = 0; i < parts.length; ++i) {
var part = parts[i];
var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1;
@@ -32,16 +27,14 @@ internals.parseValues = function (str, options) {
if (options.strictNullHandling) {
obj[Utils.decode(part)] = null;
}
- }
- else {
+ } else {
var key = Utils.decode(part.slice(0, pos));
var val = Utils.decode(part.slice(pos + 1));
- if (!Object.prototype.hasOwnProperty.call(obj, key)) {
- obj[key] = val;
- }
- else {
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
obj[key] = [].concat(obj[key]).concat(val);
+ } else {
+ obj[key] = val;
}
}
}
@@ -49,9 +42,7 @@ internals.parseValues = function (str, options) {
return obj;
};
-
internals.parseObject = function (chain, val, options) {
-
if (!chain.length) {
return val;
}
@@ -62,23 +53,20 @@ internals.parseObject = function (chain, val, options) {
if (root === '[]') {
obj = [];
obj = obj.concat(internals.parseObject(chain, val, options));
- }
- else {
+ } else {
obj = options.plainObjects ? Object.create(null) : {};
var cleanRoot = root[0] === '[' && root[root.length - 1] === ']' ? root.slice(1, root.length - 1) : root;
var index = parseInt(cleanRoot, 10);
- var indexString = '' + index;
- if (!isNaN(index) &&
+ if (
+ !isNaN(index) &&
root !== cleanRoot &&
- indexString === cleanRoot &&
+ String(index) === cleanRoot &&
index >= 0 &&
- (options.parseArrays &&
- index <= options.arrayLimit)) {
-
+ (options.parseArrays && index <= options.arrayLimit)
+ ) {
obj = [];
obj[index] = internals.parseObject(chain, val, options);
- }
- else {
+ } else {
obj[cleanRoot] = internals.parseObject(chain, val, options);
}
}
@@ -86,18 +74,13 @@ internals.parseObject = function (chain, val, options) {
return obj;
};
-
-internals.parseKeys = function (key, val, options) {
-
- if (!key) {
+internals.parseKeys = function (givenKey, val, options) {
+ if (!givenKey) {
return;
}
// Transform dot notation to bracket notation
-
- if (options.allowDots) {
- key = key.replace(/\.([^\.\[]+)/g, '[$1]');
- }
+ var key = options.allowDots ? givenKey.replace(/\.([^\.\[]+)/g, '[$1]') : givenKey;
// The regex chunks
@@ -114,9 +97,7 @@ internals.parseKeys = function (key, val, options) {
if (segment[1]) {
// If we aren't using plain objects, optionally prefix keys
// that would overwrite object prototype properties
- if (!options.plainObjects &&
- Object.prototype.hasOwnProperty(segment[1])) {
-
+ if (!options.plainObjects && Object.prototype.hasOwnProperty(segment[1])) {
if (!options.allowPrototypes) {
return;
}
@@ -129,11 +110,8 @@ internals.parseKeys = function (key, val, options) {
var i = 0;
while ((segment = child.exec(key)) !== null && i < options.depth) {
-
- ++i;
- if (!options.plainObjects &&
- Object.prototype.hasOwnProperty(segment[1].replace(/\[|\]/g, ''))) {
-
+ i += 1;
+ if (!options.plainObjects && Object.prototype.hasOwnProperty(segment[1].replace(/\[|\]/g, ''))) {
if (!options.allowPrototypes) {
continue;
}
@@ -150,10 +128,8 @@ internals.parseKeys = function (key, val, options) {
return internals.parseObject(keys, val, options);
};
-
-module.exports = function (str, options) {
-
- options = options || {};
+module.exports = function (str, opts) {
+ var options = opts || {};
options.delimiter = typeof options.delimiter === 'string' || Utils.isRegExp(options.delimiter) ? options.delimiter : internals.delimiter;
options.depth = typeof options.depth === 'number' ? options.depth : internals.depth;
options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : internals.arrayLimit;
@@ -164,10 +140,11 @@ module.exports = function (str, options) {
options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : internals.parameterLimit;
options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : internals.strictNullHandling;
- if (str === '' ||
+ if (
+ str === '' ||
str === null ||
- typeof str === 'undefined') {
-
+ typeof str === 'undefined'
+ ) {
return options.plainObjects ? Object.create(null) : {};
}
@@ -177,7 +154,7 @@ module.exports = function (str, options) {
// Iterate over the keys and setup the new object
var keys = Object.keys(tempObj);
- for (var i = 0, il = keys.length; i < il; ++i) {
+ for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var newObj = internals.parseKeys(key, tempObj[key], options);
obj = Utils.merge(obj, newObj, options);
diff --git a/node_modules/request/node_modules/qs/lib/stringify.js b/node_modules/request/node_modules/qs/lib/stringify.js
index d05aa8752..e7b669d3d 100644..100755
--- a/node_modules/request/node_modules/qs/lib/stringify.js
+++ b/node_modules/request/node_modules/qs/lib/stringify.js
@@ -1,23 +1,17 @@
-// Load modules
+'use strict';
var Utils = require('./utils');
-
-// Declare internals
-
var internals = {
delimiter: '&',
arrayPrefixGenerators: {
- brackets: function (prefix, key) {
-
+ brackets: function (prefix) {
return prefix + '[]';
},
indices: function (prefix, key) {
-
return prefix + '[' + key + ']';
},
- repeat: function (prefix, key) {
-
+ repeat: function (prefix) {
return prefix;
}
},
@@ -26,19 +20,15 @@ var internals = {
encode: true
};
-
-internals.stringify = function (obj, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encode, filter, sort) {
-
+internals.stringify = function (object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encode, filter, sort) {
+ var obj = object;
if (typeof filter === 'function') {
obj = filter(prefix, obj);
- }
- else if (Utils.isBuffer(obj)) {
- obj = obj.toString();
- }
- else if (obj instanceof Date) {
+ } else if (Utils.isBuffer(obj)) {
+ obj = String(obj);
+ } else if (obj instanceof Date) {
obj = obj.toISOString();
- }
- else if (obj === null) {
+ } else if (obj === null) {
if (strictNullHandling) {
return encode ? Utils.encode(prefix) : prefix;
}
@@ -46,10 +36,7 @@ internals.stringify = function (obj, prefix, generateArrayPrefix, strictNullHand
obj = '';
}
- if (typeof obj === 'string' ||
- typeof obj === 'number' ||
- typeof obj === 'boolean') {
-
+ if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean') {
if (encode) {
return [Utils.encode(prefix) + '=' + Utils.encode(obj)];
}
@@ -70,19 +57,16 @@ internals.stringify = function (obj, prefix, generateArrayPrefix, strictNullHand
objKeys = sort ? keys.sort(sort) : keys;
}
- for (var i = 0, il = objKeys.length; i < il; ++i) {
+ for (var i = 0; i < objKeys.length; ++i) {
var key = objKeys[i];
- if (skipNulls &&
- obj[key] === null) {
-
+ if (skipNulls && obj[key] === null) {
continue;
}
if (Array.isArray(obj)) {
values = values.concat(internals.stringify(obj[key], generateArrayPrefix(prefix, key), generateArrayPrefix, strictNullHandling, skipNulls, encode, filter));
- }
- else {
+ } else {
values = values.concat(internals.stringify(obj[key], prefix + '[' + key + ']', generateArrayPrefix, strictNullHandling, skipNulls, encode, filter));
}
}
@@ -90,10 +74,9 @@ internals.stringify = function (obj, prefix, generateArrayPrefix, strictNullHand
return values;
};
-
-module.exports = function (obj, options) {
-
- options = options || {};
+module.exports = function (object, opts) {
+ var obj = object;
+ var options = opts || {};
var delimiter = typeof options.delimiter === 'undefined' ? internals.delimiter : options.delimiter;
var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : internals.strictNullHandling;
var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : internals.skipNulls;
@@ -104,27 +87,22 @@ module.exports = function (obj, options) {
if (typeof options.filter === 'function') {
filter = options.filter;
obj = filter('', obj);
- }
- else if (Array.isArray(options.filter)) {
+ } else if (Array.isArray(options.filter)) {
objKeys = filter = options.filter;
}
var keys = [];
- if (typeof obj !== 'object' ||
- obj === null) {
-
+ if (typeof obj !== 'object' || obj === null) {
return '';
}
var arrayFormat;
if (options.arrayFormat in internals.arrayPrefixGenerators) {
arrayFormat = options.arrayFormat;
- }
- else if ('indices' in options) {
+ } else if ('indices' in options) {
arrayFormat = options.indices ? 'indices' : 'repeat';
- }
- else {
+ } else {
arrayFormat = 'indices';
}
@@ -138,12 +116,10 @@ module.exports = function (obj, options) {
objKeys.sort(sort);
}
- for (var i = 0, il = objKeys.length; i < il; ++i) {
+ for (var i = 0; i < objKeys.length; ++i) {
var key = objKeys[i];
- if (skipNulls &&
- obj[key] === null) {
-
+ if (skipNulls && obj[key] === null) {
continue;
}
diff --git a/node_modules/request/node_modules/qs/lib/utils.js b/node_modules/request/node_modules/qs/lib/utils.js
index 88f314732..5d4335603 100644..100755
--- a/node_modules/request/node_modules/qs/lib/utils.js
+++ b/node_modules/request/node_modules/qs/lib/utils.js
@@ -1,21 +1,18 @@
-// Load modules
+'use strict';
+var hexTable = (function () {
+ var array = new Array(256);
+ for (var i = 0; i < 256; ++i) {
+ array[i] = '%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase();
+ }
-// Declare internals
-
-var internals = {};
-internals.hexTable = new Array(256);
-for (var h = 0; h < 256; ++h) {
- internals.hexTable[h] = '%' + ((h < 16 ? '0' : '') + h.toString(16)).toUpperCase();
-}
-
+ return array;
+}());
exports.arrayToObject = function (source, options) {
-
var obj = options.plainObjects ? Object.create(null) : {};
- for (var i = 0, il = source.length; i < il; ++i) {
+ for (var i = 0; i < source.length; ++i) {
if (typeof source[i] !== 'undefined') {
-
obj[i] = source[i];
}
}
@@ -23,9 +20,7 @@ exports.arrayToObject = function (source, options) {
return obj;
};
-
exports.merge = function (target, source, options) {
-
if (!source) {
return target;
}
@@ -33,47 +28,37 @@ exports.merge = function (target, source, options) {
if (typeof source !== 'object') {
if (Array.isArray(target)) {
target.push(source);
- }
- else if (typeof target === 'object') {
+ } else if (typeof target === 'object') {
target[source] = true;
- }
- else {
- target = [target, source];
+ } else {
+ return [target, source];
}
return target;
}
if (typeof target !== 'object') {
- target = [target].concat(source);
- return target;
+ return [target].concat(source);
}
- if (Array.isArray(target) &&
- !Array.isArray(source)) {
-
- target = exports.arrayToObject(target, options);
+ var mergeTarget = target;
+ if (Array.isArray(target) && !Array.isArray(source)) {
+ mergeTarget = exports.arrayToObject(target, options);
}
- var keys = Object.keys(source);
- for (var k = 0, kl = keys.length; k < kl; ++k) {
- var key = keys[k];
+ return Object.keys(source).reduce(function (acc, key) {
var value = source[key];
- if (!Object.prototype.hasOwnProperty.call(target, key)) {
- target[key] = value;
- }
- else {
- target[key] = exports.merge(target[key], value, options);
+ if (Object.prototype.hasOwnProperty.call(acc, key)) {
+ acc[key] = exports.merge(acc[key], value, options);
+ } else {
+ acc[key] = value;
}
- }
-
- return target;
+ return acc;
+ }, mergeTarget);
};
-
exports.decode = function (str) {
-
try {
return decodeURIComponent(str.replace(/\+/g, ' '));
} catch (e) {
@@ -82,65 +67,60 @@ exports.decode = function (str) {
};
exports.encode = function (str) {
-
// This code was originally written by Brian White (mscdex) for the io.js core querystring library.
// It has been adapted here for stricter adherence to RFC 3986
if (str.length === 0) {
return str;
}
- if (typeof str !== 'string') {
- str = '' + str;
- }
+ var string = typeof str === 'string' ? str : String(str);
var out = '';
- for (var i = 0, il = str.length; i < il; ++i) {
- var c = str.charCodeAt(i);
+ for (var i = 0; i < string.length; ++i) {
+ var c = string.charCodeAt(i);
- if (c === 0x2D || // -
+ if (
+ c === 0x2D || // -
c === 0x2E || // .
c === 0x5F || // _
c === 0x7E || // ~
(c >= 0x30 && c <= 0x39) || // 0-9
(c >= 0x41 && c <= 0x5A) || // a-z
- (c >= 0x61 && c <= 0x7A)) { // A-Z
-
- out += str[i];
+ (c >= 0x61 && c <= 0x7A) // A-Z
+ ) {
+ out += string.charAt(i);
continue;
}
if (c < 0x80) {
- out += internals.hexTable[c];
+ out = out + hexTable[c];
continue;
}
if (c < 0x800) {
- out += internals.hexTable[0xC0 | (c >> 6)] + internals.hexTable[0x80 | (c & 0x3F)];
+ out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]);
continue;
}
if (c < 0xD800 || c >= 0xE000) {
- out += internals.hexTable[0xE0 | (c >> 12)] + internals.hexTable[0x80 | ((c >> 6) & 0x3F)] + internals.hexTable[0x80 | (c & 0x3F)];
+ out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);
continue;
}
- ++i;
- c = 0x10000 + (((c & 0x3FF) << 10) | (str.charCodeAt(i) & 0x3FF));
- out += internals.hexTable[0xF0 | (c >> 18)] + internals.hexTable[0x80 | ((c >> 12) & 0x3F)] + internals.hexTable[0x80 | ((c >> 6) & 0x3F)] + internals.hexTable[0x80 | (c & 0x3F)];
+ i += 1;
+ c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));
+ out += (hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);
}
return out;
};
-exports.compact = function (obj, refs) {
-
- if (typeof obj !== 'object' ||
- obj === null) {
-
+exports.compact = function (obj, references) {
+ if (typeof obj !== 'object' || obj === null) {
return obj;
}
- refs = refs || [];
+ var refs = references || [];
var lookup = refs.indexOf(obj);
if (lookup !== -1) {
return refs[lookup];
@@ -151,7 +131,7 @@ exports.compact = function (obj, refs) {
if (Array.isArray(obj)) {
var compacted = [];
- for (var i = 0, il = obj.length; i < il; ++i) {
+ for (var i = 0; i < obj.length; ++i) {
if (typeof obj[i] !== 'undefined') {
compacted.push(obj[i]);
}
@@ -161,30 +141,22 @@ exports.compact = function (obj, refs) {
}
var keys = Object.keys(obj);
- for (i = 0, il = keys.length; i < il; ++i) {
- var key = keys[i];
+ for (var j = 0; j < keys.length; ++j) {
+ var key = keys[j];
obj[key] = exports.compact(obj[key], refs);
}
return obj;
};
-
exports.isRegExp = function (obj) {
-
return Object.prototype.toString.call(obj) === '[object RegExp]';
};
-
exports.isBuffer = function (obj) {
-
- if (obj === null ||
- typeof obj === 'undefined') {
-
+ if (obj === null || typeof obj === 'undefined') {
return false;
}
- return !!(obj.constructor &&
- obj.constructor.isBuffer &&
- obj.constructor.isBuffer(obj));
+ return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
};
diff --git a/node_modules/request/node_modules/qs/package.json b/node_modules/request/node_modules/qs/package.json
index 7e60df700..ed0815b5b 100644
--- a/node_modules/request/node_modules/qs/package.json
+++ b/node_modules/request/node_modules/qs/package.json
@@ -1,59 +1,105 @@
{
- "name": "qs",
- "description": "A querystring parser that supports nesting and arrays, with a depth limit",
- "homepage": "https://github.com/hapijs/qs",
- "version": "5.2.0",
- "repository": {
- "type": "git",
- "url": "git+https://github.com/hapijs/qs.git"
- },
- "main": "lib/index.js",
- "keywords": [
- "querystring",
- "qs"
+ "_args": [
+ [
+ "qs@~6.0.2",
+ "/Users/rebecca/code/npm/node_modules/request"
+ ]
],
- "engines": ">=0.10.40",
- "dependencies": {},
- "devDependencies": {
- "browserify": "^10.2.1",
- "code": "1.x.x",
- "lab": "5.x.x"
+ "_from": "qs@>=6.0.2 <6.1.0",
+ "_id": "qs@6.0.2",
+ "_inCache": true,
+ "_installable": true,
+ "_location": "/request/qs",
+ "_nodeVersion": "5.4.1",
+ "_npmUser": {
+ "email": "ljharb@gmail.com",
+ "name": "ljharb"
},
- "scripts": {
- "test": "lab -a code -t 100 -L",
- "test-tap": "lab -a code -r tap -o tests.tap",
- "test-cov-html": "lab -a code -r html -o coverage.html",
- "dist": "browserify --standalone Qs lib/index.js > dist/qs.js"
+ "_npmVersion": "3.3.12",
+ "_phantomChildren": {},
+ "_requested": {
+ "name": "qs",
+ "raw": "qs@~6.0.2",
+ "rawSpec": "~6.0.2",
+ "scope": null,
+ "spec": ">=6.0.2 <6.1.0",
+ "type": "range"
},
- "license": "BSD-3-Clause",
- "gitHead": "a341cdf2fadba5ede1ce6c95c7051f6f31f37b81",
+ "_requiredBy": [
+ "/request"
+ ],
+ "_resolved": "https://registry.npmjs.org/qs/-/qs-6.0.2.tgz",
+ "_shasum": "88c68d590e8ed56c76c79f352c17b982466abfcd",
+ "_shrinkwrap": null,
+ "_spec": "qs@~6.0.2",
+ "_where": "/Users/rebecca/code/npm/node_modules/request",
"bugs": {
- "url": "https://github.com/hapijs/qs/issues"
+ "url": "https://github.com/ljharb/qs/issues"
},
- "_id": "qs@5.2.0",
- "_shasum": "a9f31142af468cb72b25b30136ba2456834916be",
- "_from": "qs@>=5.2.0 <5.3.0",
- "_npmVersion": "3.3.5",
- "_nodeVersion": "0.10.40",
- "_npmUser": {
- "name": "nlf",
- "email": "quitlahok@gmail.com"
+ "contributors": [
+ {
+ "name": "Jordan Harband",
+ "email": "ljharb@gmail.com",
+ "url": "http://ljharb.codes"
+ }
+ ],
+ "dependencies": {},
+ "description": "A querystring parser that supports nesting and arrays, with a depth limit",
+ "devDependencies": {
+ "@ljharb/eslint-config": "^1.6.1",
+ "browserify": "^12.0.1",
+ "covert": "^1.1.0",
+ "eslint": "^1.10.3",
+ "evalmd": "^0.0.16",
+ "mkdirp": "^0.5.1",
+ "parallelshell": "^2.0.0",
+ "tape": "^4.3.0"
},
+ "directories": {},
"dist": {
- "shasum": "a9f31142af468cb72b25b30136ba2456834916be",
- "tarball": "http://registry.npmjs.org/qs/-/qs-5.2.0.tgz"
+ "shasum": "88c68d590e8ed56c76c79f352c17b982466abfcd",
+ "tarball": "http://registry.npmjs.org/qs/-/qs-6.0.2.tgz"
},
+ "engines": {
+ "node": ">=0.6"
+ },
+ "gitHead": "47dfbd6740b3cc1593847825701c8aa136f636e3",
+ "homepage": "https://github.com/ljharb/qs",
+ "keywords": [
+ "qs",
+ "querystring"
+ ],
+ "license": "BSD-3-Clause",
+ "main": "lib/index.js",
"maintainers": [
{
- "name": "nlf",
- "email": "quitlahok@gmail.com"
+ "name": "hueniverse",
+ "email": "eran@hammer.io"
},
{
- "name": "hueniverse",
- "email": "eran@hueniverse.com"
+ "name": "ljharb",
+ "email": "ljharb@gmail.com"
+ },
+ {
+ "name": "nlf",
+ "email": "quitlahok@gmail.com"
}
],
- "directories": {},
- "_resolved": "https://registry.npmjs.org/qs/-/qs-5.2.0.tgz",
- "readme": "ERROR: No README data found!"
+ "name": "qs",
+ "optionalDependencies": {},
+ "readme": "ERROR: No README data found!",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/ljharb/qs.git"
+ },
+ "scripts": {
+ "coverage": "covert test",
+ "dist": "mkdirp dist && browserify --standalone Qs lib/index.js > dist/qs.js",
+ "lint": "eslint lib/*.js text/*.js",
+ "prepublish": "npm run dist",
+ "readme": "evalmd README.md",
+ "test": "parallelshell 'npm run readme' 'npm run lint' 'npm run coverage'",
+ "tests-only": "node test"
+ },
+ "version": "6.0.2"
}
diff --git a/node_modules/request/node_modules/qs/test/index.js b/node_modules/request/node_modules/qs/test/index.js
new file mode 100644
index 000000000..b6a7d9526
--- /dev/null
+++ b/node_modules/request/node_modules/qs/test/index.js
@@ -0,0 +1,5 @@
+require('./parse');
+
+require('./stringify');
+
+require('./utils');
diff --git a/node_modules/request/node_modules/qs/test/parse.js b/node_modules/request/node_modules/qs/test/parse.js
index 679f19747..5665d074e 100644..100755
--- a/node_modules/request/node_modules/qs/test/parse.js
+++ b/node_modules/request/node_modules/qs/test/parse.js
@@ -1,478 +1,393 @@
-/* eslint no-extend-native:0 */
-// Load modules
-
-var Code = require('code');
-var Lab = require('lab');
-var Qs = require('../');
-
-
-// Declare internals
-
-var internals = {};
-
-
-// Test shortcuts
-
-var lab = exports.lab = Lab.script();
-var expect = Code.expect;
-var describe = lab.experiment;
-var it = lab.test;
-
-
-describe('parse()', function () {
-
- it('parses a simple string', function (done) {
-
- expect(Qs.parse('0=foo')).to.deep.equal({ '0': 'foo' });
- expect(Qs.parse('foo=c++')).to.deep.equal({ foo: 'c ' });
- expect(Qs.parse('a[>=]=23')).to.deep.equal({ a: { '>=': '23' } });
- expect(Qs.parse('a[<=>]==23')).to.deep.equal({ a: { '<=>': '=23' } });
- expect(Qs.parse('a[==]=23')).to.deep.equal({ a: { '==': '23' } });
- expect(Qs.parse('foo', { strictNullHandling: true })).to.deep.equal({ foo: null });
- expect(Qs.parse('foo' )).to.deep.equal({ foo: '' });
- expect(Qs.parse('foo=')).to.deep.equal({ foo: '' });
- expect(Qs.parse('foo=bar')).to.deep.equal({ foo: 'bar' });
- expect(Qs.parse(' foo = bar = baz ')).to.deep.equal({ ' foo ': ' bar = baz ' });
- expect(Qs.parse('foo=bar=baz')).to.deep.equal({ foo: 'bar=baz' });
- expect(Qs.parse('foo=bar&bar=baz')).to.deep.equal({ foo: 'bar', bar: 'baz' });
- expect(Qs.parse('foo2=bar2&baz2=')).to.deep.equal({ foo2: 'bar2', baz2: '' });
- expect(Qs.parse('foo=bar&baz', { strictNullHandling: true })).to.deep.equal({ foo: 'bar', baz: null });
- expect(Qs.parse('foo=bar&baz')).to.deep.equal({ foo: 'bar', baz: '' });
- expect(Qs.parse('cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World')).to.deep.equal({
+'use strict';
+
+var test = require('tape');
+var qs = require('../');
+
+test('parse()', function (t) {
+ t.test('parses a simple string', function (st) {
+ st.deepEqual(qs.parse('0=foo'), { '0': 'foo' });
+ st.deepEqual(qs.parse('foo=c++'), { foo: 'c ' });
+ st.deepEqual(qs.parse('a[>=]=23'), { a: { '>=': '23' } });
+ st.deepEqual(qs.parse('a[<=>]==23'), { a: { '<=>': '=23' } });
+ st.deepEqual(qs.parse('a[==]=23'), { a: { '==': '23' } });
+ st.deepEqual(qs.parse('foo', { strictNullHandling: true }), { foo: null });
+ st.deepEqual(qs.parse('foo'), { foo: '' });
+ st.deepEqual(qs.parse('foo='), { foo: '' });
+ st.deepEqual(qs.parse('foo=bar'), { foo: 'bar' });
+ st.deepEqual(qs.parse(' foo = bar = baz '), { ' foo ': ' bar = baz ' });
+ st.deepEqual(qs.parse('foo=bar=baz'), { foo: 'bar=baz' });
+ st.deepEqual(qs.parse('foo=bar&bar=baz'), { foo: 'bar', bar: 'baz' });
+ st.deepEqual(qs.parse('foo2=bar2&baz2='), { foo2: 'bar2', baz2: '' });
+ st.deepEqual(qs.parse('foo=bar&baz', { strictNullHandling: true }), { foo: 'bar', baz: null });
+ st.deepEqual(qs.parse('foo=bar&baz'), { foo: 'bar', baz: '' });
+ st.deepEqual(qs.parse('cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World'), {
cht: 'p3',
chd: 't:60,40',
chs: '250x100',
chl: 'Hello|World'
});
- done();
+ st.end();
});
- it('allows enabling dot notation', function (done) {
-
- expect(Qs.parse('a.b=c')).to.deep.equal({ 'a.b': 'c' });
- expect(Qs.parse('a.b=c', { allowDots: true })).to.deep.equal({ a: { b: 'c' } });
- done();
+ t.test('allows enabling dot notation', function (st) {
+ st.deepEqual(qs.parse('a.b=c'), { 'a.b': 'c' });
+ st.deepEqual(qs.parse('a.b=c', { allowDots: true }), { a: { b: 'c' } });
+ st.end();
});
- it('parses a single nested string', function (done) {
+ t.deepEqual(qs.parse('a[b]=c'), { a: { b: 'c' } }, 'parses a single nested string');
+ t.deepEqual(qs.parse('a[b][c]=d'), { a: { b: { c: 'd' } } }, 'parses a double nested string');
+ t.deepEqual(
+ qs.parse('a[b][c][d][e][f][g][h]=i'),
+ { a: { b: { c: { d: { e: { f: { '[g][h]': 'i' } } } } } } },
+ 'defaults to a depth of 5'
+ );
- expect(Qs.parse('a[b]=c')).to.deep.equal({ a: { b: 'c' } });
- done();
+ t.test('only parses one level when depth = 1', function (st) {
+ st.deepEqual(qs.parse('a[b][c]=d', { depth: 1 }), { a: { b: { '[c]': 'd' } } });
+ st.deepEqual(qs.parse('a[b][c][d]=e', { depth: 1 }), { a: { b: { '[c][d]': 'e' } } });
+ st.end();
});
- it('parses a double nested string', function (done) {
+ t.deepEqual(qs.parse('a=b&a=c'), { a: ['b', 'c'] }, 'parses a simple array');
- expect(Qs.parse('a[b][c]=d')).to.deep.equal({ a: { b: { c: 'd' } } });
- done();
+ t.test('parses an explicit array', function (st) {
+ st.deepEqual(qs.parse('a[]=b'), { a: ['b'] });
+ st.deepEqual(qs.parse('a[]=b&a[]=c'), { a: ['b', 'c'] });
+ st.deepEqual(qs.parse('a[]=b&a[]=c&a[]=d'), { a: ['b', 'c', 'd'] });
+ st.end();
});
- it('defaults to a depth of 5', function (done) {
-
- expect(Qs.parse('a[b][c][d][e][f][g][h]=i')).to.deep.equal({ a: { b: { c: { d: { e: { f: { '[g][h]': 'i' } } } } } } });
- done();
+ t.test('parses a mix of simple and explicit arrays', function (st) {
+ st.deepEqual(qs.parse('a=b&a[]=c'), { a: ['b', 'c'] });
+ st.deepEqual(qs.parse('a[]=b&a=c'), { a: ['b', 'c'] });
+ st.deepEqual(qs.parse('a[0]=b&a=c'), { a: ['b', 'c'] });
+ st.deepEqual(qs.parse('a=b&a[0]=c'), { a: ['b', 'c'] });
+ st.deepEqual(qs.parse('a[1]=b&a=c'), { a: ['b', 'c'] });
+ st.deepEqual(qs.parse('a=b&a[1]=c'), { a: ['b', 'c'] });
+ st.end();
});
- it('only parses one level when depth = 1', function (done) {
-
- expect(Qs.parse('a[b][c]=d', { depth: 1 })).to.deep.equal({ a: { b: { '[c]': 'd' } } });
- expect(Qs.parse('a[b][c][d]=e', { depth: 1 })).to.deep.equal({ a: { b: { '[c][d]': 'e' } } });
- done();
+ t.test('parses a nested array', function (st) {
+ st.deepEqual(qs.parse('a[b][]=c&a[b][]=d'), { a: { b: ['c', 'd'] } });
+ st.deepEqual(qs.parse('a[>=]=25'), { a: { '>=': '25' } });
+ st.end();
});
- it('parses a simple array', function (done) {
-
- expect(Qs.parse('a=b&a=c')).to.deep.equal({ a: ['b', 'c'] });
- done();
+ t.test('allows to specify array indices', function (st) {
+ st.deepEqual(qs.parse('a[1]=c&a[0]=b&a[2]=d'), { a: ['b', 'c', 'd'] });
+ st.deepEqual(qs.parse('a[1]=c&a[0]=b'), { a: ['b', 'c'] });
+ st.deepEqual(qs.parse('a[1]=c'), { a: ['c'] });
+ st.end();
});
- it('parses an explicit array', function (done) {
-
- expect(Qs.parse('a[]=b')).to.deep.equal({ a: ['b'] });
- expect(Qs.parse('a[]=b&a[]=c')).to.deep.equal({ a: ['b', 'c'] });
- expect(Qs.parse('a[]=b&a[]=c&a[]=d')).to.deep.equal({ a: ['b', 'c', 'd'] });
- done();
+ t.test('limits specific array indices to 20', function (st) {
+ st.deepEqual(qs.parse('a[20]=a'), { a: ['a'] });
+ st.deepEqual(qs.parse('a[21]=a'), { a: { '21': 'a' } });
+ st.end();
});
- it('parses a mix of simple and explicit arrays', function (done) {
+ t.deepEqual(qs.parse('a[12b]=c'), { a: { '12b': 'c' } }, 'supports keys that begin with a number');
- expect(Qs.parse('a=b&a[]=c')).to.deep.equal({ a: ['b', 'c'] });
- expect(Qs.parse('a[]=b&a=c')).to.deep.equal({ a: ['b', 'c'] });
- expect(Qs.parse('a[0]=b&a=c')).to.deep.equal({ a: ['b', 'c'] });
- expect(Qs.parse('a=b&a[0]=c')).to.deep.equal({ a: ['b', 'c'] });
- expect(Qs.parse('a[1]=b&a=c')).to.deep.equal({ a: ['b', 'c'] });
- expect(Qs.parse('a=b&a[1]=c')).to.deep.equal({ a: ['b', 'c'] });
- done();
+ t.test('supports encoded = signs', function (st) {
+ st.deepEqual(qs.parse('he%3Dllo=th%3Dere'), { 'he=llo': 'th=ere' });
+ st.end();
});
- it('parses a nested array', function (done) {
-
- expect(Qs.parse('a[b][]=c&a[b][]=d')).to.deep.equal({ a: { b: ['c', 'd'] } });
- expect(Qs.parse('a[>=]=25')).to.deep.equal({ a: { '>=': '25' } });
- done();
- });
-
- it('allows to specify array indices', function (done) {
-
- expect(Qs.parse('a[1]=c&a[0]=b&a[2]=d')).to.deep.equal({ a: ['b', 'c', 'd'] });
- expect(Qs.parse('a[1]=c&a[0]=b')).to.deep.equal({ a: ['b', 'c'] });
- expect(Qs.parse('a[1]=c')).to.deep.equal({ a: ['c'] });
- done();
- });
-
- it('limits specific array indices to 20', function (done) {
-
- expect(Qs.parse('a[20]=a')).to.deep.equal({ a: ['a'] });
- expect(Qs.parse('a[21]=a')).to.deep.equal({ a: { '21': 'a' } });
- done();
- });
-
- it('supports keys that begin with a number', function (done) {
-
- expect(Qs.parse('a[12b]=c')).to.deep.equal({ a: { '12b': 'c' } });
- done();
- });
-
- it('supports encoded = signs', function (done) {
-
- expect(Qs.parse('he%3Dllo=th%3Dere')).to.deep.equal({ 'he=llo': 'th=ere' });
- done();
- });
-
- it('is ok with url encoded strings', function (done) {
-
- expect(Qs.parse('a[b%20c]=d')).to.deep.equal({ a: { 'b c': 'd' } });
- expect(Qs.parse('a[b]=c%20d')).to.deep.equal({ a: { b: 'c d' } });
- done();
- });
-
- it('allows brackets in the value', function (done) {
-
- expect(Qs.parse('pets=["tobi"]')).to.deep.equal({ pets: '["tobi"]' });
- expect(Qs.parse('operators=[">=", "<="]')).to.deep.equal({ operators: '[">=", "<="]' });
- done();
+ t.test('is ok with url encoded strings', function (st) {
+ st.deepEqual(qs.parse('a[b%20c]=d'), { a: { 'b c': 'd' } });
+ st.deepEqual(qs.parse('a[b]=c%20d'), { a: { b: 'c d' } });
+ st.end();
});
- it('allows empty values', function (done) {
-
- expect(Qs.parse('')).to.deep.equal({});
- expect(Qs.parse(null)).to.deep.equal({});
- expect(Qs.parse(undefined)).to.deep.equal({});
- done();
+ t.test('allows brackets in the value', function (st) {
+ st.deepEqual(qs.parse('pets=["tobi"]'), { pets: '["tobi"]' });
+ st.deepEqual(qs.parse('operators=[">=", "<="]'), { operators: '[">=", "<="]' });
+ st.end();
});
- it('transforms arrays to objects', function (done) {
-
- expect(Qs.parse('foo[0]=bar&foo[bad]=baz')).to.deep.equal({ foo: { '0': 'bar', bad: 'baz' } });
- expect(Qs.parse('foo[bad]=baz&foo[0]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } });
- expect(Qs.parse('foo[bad]=baz&foo[]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } });
- expect(Qs.parse('foo[]=bar&foo[bad]=baz')).to.deep.equal({ foo: { '0': 'bar', bad: 'baz' } });
- expect(Qs.parse('foo[bad]=baz&foo[]=bar&foo[]=foo')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar', '1': 'foo' } });
- expect(Qs.parse('foo[0][a]=a&foo[0][b]=b&foo[1][a]=aa&foo[1][b]=bb')).to.deep.equal({ foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] });
- expect(Qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c')).to.deep.equal({ a: { '0': 'b', t: 'u', c: true } });
- expect(Qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y')).to.deep.equal({ a: { '0': 'b', '1': 'c', x: 'y' } });
- done();
+ t.test('allows empty values', function (st) {
+ st.deepEqual(qs.parse(''), {});
+ st.deepEqual(qs.parse(null), {});
+ st.deepEqual(qs.parse(undefined), {});
+ st.end();
});
- it('transforms arrays to objects (dot notation)', function (done) {
-
- expect(Qs.parse('foo[0].baz=bar&fool.bad=baz', { allowDots: true })).to.deep.equal({ foo: [{ baz: 'bar' }], fool: { bad: 'baz' } });
- expect(Qs.parse('foo[0].baz=bar&fool.bad.boo=baz', { allowDots: true })).to.deep.equal({ foo: [{ baz: 'bar' }], fool: { bad: { boo: 'baz' } } });
- expect(Qs.parse('foo[0][0].baz=bar&fool.bad=baz', { allowDots: true })).to.deep.equal({ foo: [[{ baz: 'bar' }]], fool: { bad: 'baz' } });
- expect(Qs.parse('foo[0].baz[0]=15&foo[0].bar=2', { allowDots: true })).to.deep.equal({ foo: [{ baz: ['15'], bar: '2' }] });
- expect(Qs.parse('foo[0].baz[0]=15&foo[0].baz[1]=16&foo[0].bar=2', { allowDots: true })).to.deep.equal({ foo: [{ baz: ['15', '16'], bar: '2' }] });
- expect(Qs.parse('foo.bad=baz&foo[0]=bar', { allowDots: true })).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } });
- expect(Qs.parse('foo.bad=baz&foo[]=bar', { allowDots: true })).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } });
- expect(Qs.parse('foo[]=bar&foo.bad=baz', { allowDots: true })).to.deep.equal({ foo: { '0': 'bar', bad: 'baz' } });
- expect(Qs.parse('foo.bad=baz&foo[]=bar&foo[]=foo', { allowDots: true })).to.deep.equal({ foo: { bad: 'baz', '0': 'bar', '1': 'foo' } });
- expect(Qs.parse('foo[0].a=a&foo[0].b=b&foo[1].a=aa&foo[1].b=bb', { allowDots: true })).to.deep.equal({ foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] });
- done();
+ t.test('transforms arrays to objects', function (st) {
+ st.deepEqual(qs.parse('foo[0]=bar&foo[bad]=baz'), { foo: { '0': 'bar', bad: 'baz' } });
+ st.deepEqual(qs.parse('foo[bad]=baz&foo[0]=bar'), { foo: { bad: 'baz', '0': 'bar' } });
+ st.deepEqual(qs.parse('foo[bad]=baz&foo[]=bar'), { foo: { bad: 'baz', '0': 'bar' } });
+ st.deepEqual(qs.parse('foo[]=bar&foo[bad]=baz'), { foo: { '0': 'bar', bad: 'baz' } });
+ st.deepEqual(qs.parse('foo[bad]=baz&foo[]=bar&foo[]=foo'), { foo: { bad: 'baz', '0': 'bar', '1': 'foo' } });
+ st.deepEqual(qs.parse('foo[0][a]=a&foo[0][b]=b&foo[1][a]=aa&foo[1][b]=bb'), { foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] });
+ st.deepEqual(qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c'), { a: { '0': 'b', t: 'u', c: true } });
+ st.deepEqual(qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y'), { a: { '0': 'b', '1': 'c', x: 'y' } });
+ st.end();
});
- it('can add keys to objects', function (done) {
-
- expect(Qs.parse('a[b]=c&a=d')).to.deep.equal({ a: { b: 'c', d: true } });
- done();
+ t.test('transforms arrays to objects (dot notation)', function (st) {
+ st.deepEqual(qs.parse('foo[0].baz=bar&fool.bad=baz', { allowDots: true }), { foo: [{ baz: 'bar' }], fool: { bad: 'baz' } });
+ st.deepEqual(qs.parse('foo[0].baz=bar&fool.bad.boo=baz', { allowDots: true }), { foo: [{ baz: 'bar' }], fool: { bad: { boo: 'baz' } } });
+ st.deepEqual(qs.parse('foo[0][0].baz=bar&fool.bad=baz', { allowDots: true }), { foo: [[{ baz: 'bar' }]], fool: { bad: 'baz' } });
+ st.deepEqual(qs.parse('foo[0].baz[0]=15&foo[0].bar=2', { allowDots: true }), { foo: [{ baz: ['15'], bar: '2' }] });
+ st.deepEqual(qs.parse('foo[0].baz[0]=15&foo[0].baz[1]=16&foo[0].bar=2', { allowDots: true }), { foo: [{ baz: ['15', '16'], bar: '2' }] });
+ st.deepEqual(qs.parse('foo.bad=baz&foo[0]=bar', { allowDots: true }), { foo: { bad: 'baz', '0': 'bar' } });
+ st.deepEqual(qs.parse('foo.bad=baz&foo[]=bar', { allowDots: true }), { foo: { bad: 'baz', '0': 'bar' } });
+ st.deepEqual(qs.parse('foo[]=bar&foo.bad=baz', { allowDots: true }), { foo: { '0': 'bar', bad: 'baz' } });
+ st.deepEqual(qs.parse('foo.bad=baz&foo[]=bar&foo[]=foo', { allowDots: true }), { foo: { bad: 'baz', '0': 'bar', '1': 'foo' } });
+ st.deepEqual(qs.parse('foo[0].a=a&foo[0].b=b&foo[1].a=aa&foo[1].b=bb', { allowDots: true }), { foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] });
+ st.end();
});
- it('correctly prunes undefined values when converting an array to an object', function (done) {
+ t.deepEqual(qs.parse('a[b]=c&a=d'), { a: { b: 'c', d: true } }, 'can add keys to objects');
- expect(Qs.parse('a[2]=b&a[99999999]=c')).to.deep.equal({ a: { '2': 'b', '99999999': 'c' } });
- done();
+ t.test('correctly prunes undefined values when converting an array to an object', function (st) {
+ st.deepEqual(qs.parse('a[2]=b&a[99999999]=c'), { a: { '2': 'b', '99999999': 'c' } });
+ st.end();
});
- it('supports malformed uri characters', function (done) {
-
- expect(Qs.parse('{%:%}', { strictNullHandling: true })).to.deep.equal({ '{%:%}': null });
- expect(Qs.parse('{%:%}=')).to.deep.equal({ '{%:%}': '' });
- expect(Qs.parse('foo=%:%}')).to.deep.equal({ foo: '%:%}' });
- done();
+ t.test('supports malformed uri characters', function (st) {
+ st.deepEqual(qs.parse('{%:%}', { strictNullHandling: true }), { '{%:%}': null });
+ st.deepEqual(qs.parse('{%:%}='), { '{%:%}': '' });
+ st.deepEqual(qs.parse('foo=%:%}'), { foo: '%:%}' });
+ st.end();
});
- it('doesn\'t produce empty keys', function (done) {
-
- expect(Qs.parse('_r=1&')).to.deep.equal({ '_r': '1' });
- done();
+ t.test('doesn\'t produce empty keys', function (st) {
+ st.deepEqual(qs.parse('_r=1&'), { '_r': '1' });
+ st.end();
});
- it('cannot access Object prototype', function (done) {
-
- Qs.parse('constructor[prototype][bad]=bad');
- Qs.parse('bad[constructor][prototype][bad]=bad');
- expect(typeof Object.prototype.bad).to.equal('undefined');
- done();
+ t.test('cannot access Object prototype', function (st) {
+ qs.parse('constructor[prototype][bad]=bad');
+ qs.parse('bad[constructor][prototype][bad]=bad');
+ st.equal(typeof Object.prototype.bad, 'undefined');
+ st.end();
});
- it('parses arrays of objects', function (done) {
-
- expect(Qs.parse('a[][b]=c')).to.deep.equal({ a: [{ b: 'c' }] });
- expect(Qs.parse('a[0][b]=c')).to.deep.equal({ a: [{ b: 'c' }] });
- done();
+ t.test('parses arrays of objects', function (st) {
+ st.deepEqual(qs.parse('a[][b]=c'), { a: [{ b: 'c' }] });
+ st.deepEqual(qs.parse('a[0][b]=c'), { a: [{ b: 'c' }] });
+ st.end();
});
- it('allows for empty strings in arrays', function (done) {
-
- expect(Qs.parse('a[]=b&a[]=&a[]=c')).to.deep.equal({ a: ['b', '', 'c'] });
- expect(Qs.parse('a[0]=b&a[1]&a[2]=c&a[19]=', { strictNullHandling: true })).to.deep.equal({ a: ['b', null, 'c', ''] });
- expect(Qs.parse('a[0]=b&a[1]=&a[2]=c&a[19]', { strictNullHandling: true })).to.deep.equal({ a: ['b', '', 'c', null] });
- expect(Qs.parse('a[]=&a[]=b&a[]=c')).to.deep.equal({ a: ['', 'b', 'c'] });
- done();
+ t.test('allows for empty strings in arrays', function (st) {
+ st.deepEqual(qs.parse('a[]=b&a[]=&a[]=c'), { a: ['b', '', 'c'] });
+ st.deepEqual(qs.parse('a[0]=b&a[1]&a[2]=c&a[19]=', { strictNullHandling: true }), { a: ['b', null, 'c', ''] });
+ st.deepEqual(qs.parse('a[0]=b&a[1]=&a[2]=c&a[19]', { strictNullHandling: true }), { a: ['b', '', 'c', null] });
+ st.deepEqual(qs.parse('a[]=&a[]=b&a[]=c'), { a: ['', 'b', 'c'] });
+ st.end();
});
- it('compacts sparse arrays', function (done) {
-
- expect(Qs.parse('a[10]=1&a[2]=2')).to.deep.equal({ a: ['2', '1'] });
- done();
+ t.test('compacts sparse arrays', function (st) {
+ st.deepEqual(qs.parse('a[10]=1&a[2]=2'), { a: ['2', '1'] });
+ st.end();
});
- it('parses semi-parsed strings', function (done) {
-
- expect(Qs.parse({ 'a[b]': 'c' })).to.deep.equal({ a: { b: 'c' } });
- expect(Qs.parse({ 'a[b]': 'c', 'a[d]': 'e' })).to.deep.equal({ a: { b: 'c', d: 'e' } });
- done();
+ t.test('parses semi-parsed strings', function (st) {
+ st.deepEqual(qs.parse({ 'a[b]': 'c' }), { a: { b: 'c' } });
+ st.deepEqual(qs.parse({ 'a[b]': 'c', 'a[d]': 'e' }), { a: { b: 'c', d: 'e' } });
+ st.end();
});
- it('parses buffers correctly', function (done) {
-
+ t.test('parses buffers correctly', function (st) {
var b = new Buffer('test');
- expect(Qs.parse({ a: b })).to.deep.equal({ a: b });
- done();
+ st.deepEqual(qs.parse({ a: b }), { a: b });
+ st.end();
});
- it('continues parsing when no parent is found', function (done) {
-
- expect(Qs.parse('[]=&a=b')).to.deep.equal({ '0': '', a: 'b' });
- expect(Qs.parse('[]&a=b', { strictNullHandling: true })).to.deep.equal({ '0': null, a: 'b' });
- expect(Qs.parse('[foo]=bar')).to.deep.equal({ foo: 'bar' });
- done();
+ t.test('continues parsing when no parent is found', function (st) {
+ st.deepEqual(qs.parse('[]=&a=b'), { '0': '', a: 'b' });
+ st.deepEqual(qs.parse('[]&a=b', { strictNullHandling: true }), { '0': null, a: 'b' });
+ st.deepEqual(qs.parse('[foo]=bar'), { foo: 'bar' });
+ st.end();
});
- it('does not error when parsing a very long array', function (done) {
-
+ t.test('does not error when parsing a very long array', function (st) {
var str = 'a[]=a';
while (Buffer.byteLength(str) < 128 * 1024) {
- str += '&' + str;
+ str = str + '&' + str;
}
- expect(function () {
+ st.doesNotThrow(function () { qs.parse(str); });
- Qs.parse(str);
- }).to.not.throw();
-
- done();
+ st.end();
});
- it('should not throw when a native prototype has an enumerable property', { parallel: false }, function (done) {
-
+ t.test('should not throw when a native prototype has an enumerable property', { parallel: false }, function (st) {
Object.prototype.crash = '';
Array.prototype.crash = '';
- expect(Qs.parse.bind(null, 'a=b')).to.not.throw();
- expect(Qs.parse('a=b')).to.deep.equal({ a: 'b' });
- expect(Qs.parse.bind(null, 'a[][b]=c')).to.not.throw();
- expect(Qs.parse('a[][b]=c')).to.deep.equal({ a: [{ b: 'c' }] });
+ st.doesNotThrow(qs.parse.bind(null, 'a=b'));
+ st.deepEqual(qs.parse('a=b'), { a: 'b' });
+ st.doesNotThrow(qs.parse.bind(null, 'a[][b]=c'));
+ st.deepEqual(qs.parse('a[][b]=c'), { a: [{ b: 'c' }] });
delete Object.prototype.crash;
delete Array.prototype.crash;
- done();
+ st.end();
});
- it('parses a string with an alternative string delimiter', function (done) {
-
- expect(Qs.parse('a=b;c=d', { delimiter: ';' })).to.deep.equal({ a: 'b', c: 'd' });
- done();
+ t.test('parses a string with an alternative string delimiter', function (st) {
+ st.deepEqual(qs.parse('a=b;c=d', { delimiter: ';' }), { a: 'b', c: 'd' });
+ st.end();
});
- it('parses a string with an alternative RegExp delimiter', function (done) {
-
- expect(Qs.parse('a=b; c=d', { delimiter: /[;,] */ })).to.deep.equal({ a: 'b', c: 'd' });
- done();
+ t.test('parses a string with an alternative RegExp delimiter', function (st) {
+ st.deepEqual(qs.parse('a=b; c=d', { delimiter: /[;,] */ }), { a: 'b', c: 'd' });
+ st.end();
});
- it('does not use non-splittable objects as delimiters', function (done) {
-
- expect(Qs.parse('a=b&c=d', { delimiter: true })).to.deep.equal({ a: 'b', c: 'd' });
- done();
+ t.test('does not use non-splittable objects as delimiters', function (st) {
+ st.deepEqual(qs.parse('a=b&c=d', { delimiter: true }), { a: 'b', c: 'd' });
+ st.end();
});
- it('allows overriding parameter limit', function (done) {
-
- expect(Qs.parse('a=b&c=d', { parameterLimit: 1 })).to.deep.equal({ a: 'b' });
- done();
+ t.test('allows overriding parameter limit', function (st) {
+ st.deepEqual(qs.parse('a=b&c=d', { parameterLimit: 1 }), { a: 'b' });
+ st.end();
});
- it('allows setting the parameter limit to Infinity', function (done) {
-
- expect(Qs.parse('a=b&c=d', { parameterLimit: Infinity })).to.deep.equal({ a: 'b', c: 'd' });
- done();
+ t.test('allows setting the parameter limit to Infinity', function (st) {
+ st.deepEqual(qs.parse('a=b&c=d', { parameterLimit: Infinity }), { a: 'b', c: 'd' });
+ st.end();
});
- it('allows overriding array limit', function (done) {
-
- expect(Qs.parse('a[0]=b', { arrayLimit: -1 })).to.deep.equal({ a: { '0': 'b' } });
- expect(Qs.parse('a[-1]=b', { arrayLimit: -1 })).to.deep.equal({ a: { '-1': 'b' } });
- expect(Qs.parse('a[0]=b&a[1]=c', { arrayLimit: 0 })).to.deep.equal({ a: { '0': 'b', '1': 'c' } });
- done();
+ t.test('allows overriding array limit', function (st) {
+ st.deepEqual(qs.parse('a[0]=b', { arrayLimit: -1 }), { a: { '0': 'b' } });
+ st.deepEqual(qs.parse('a[-1]=b', { arrayLimit: -1 }), { a: { '-1': 'b' } });
+ st.deepEqual(qs.parse('a[0]=b&a[1]=c', { arrayLimit: 0 }), { a: { '0': 'b', '1': 'c' } });
+ st.end();
});
- it('allows disabling array parsing', function (done) {
-
- expect(Qs.parse('a[0]=b&a[1]=c', { parseArrays: false })).to.deep.equal({ a: { '0': 'b', '1': 'c' } });
- done();
+ t.test('allows disabling array parsing', function (st) {
+ st.deepEqual(qs.parse('a[0]=b&a[1]=c', { parseArrays: false }), { a: { '0': 'b', '1': 'c' } });
+ st.end();
});
- it('parses an object', function (done) {
-
+ t.test('parses an object', function (st) {
var input = {
'user[name]': { 'pop[bob]': 3 },
'user[email]': null
};
var expected = {
- 'user': {
- 'name': { 'pop[bob]': 3 },
- 'email': null
+ user: {
+ name: { 'pop[bob]': 3 },
+ email: null
}
};
- var result = Qs.parse(input);
+ var result = qs.parse(input);
- expect(result).to.deep.equal(expected);
- done();
+ st.deepEqual(result, expected);
+ st.end();
});
- it('parses an object in dot notation', function (done) {
-
+ t.test('parses an object in dot notation', function (st) {
var input = {
'user.name': { 'pop[bob]': 3 },
'user.email.': null
};
var expected = {
- 'user': {
- 'name': { 'pop[bob]': 3 },
- 'email': null
+ user: {
+ name: { 'pop[bob]': 3 },
+ email: null
}
};
- var result = Qs.parse(input, { allowDots: true });
+ var result = qs.parse(input, { allowDots: true });
- expect(result).to.deep.equal(expected);
- done();
+ st.deepEqual(result, expected);
+ st.end();
});
- it('parses an object and not child values', function (done) {
-
+ t.test('parses an object and not child values', function (st) {
var input = {
'user[name]': { 'pop[bob]': { 'test': 3 } },
'user[email]': null
};
var expected = {
- 'user': {
- 'name': { 'pop[bob]': { 'test': 3 } },
- 'email': null
+ user: {
+ name: { 'pop[bob]': { 'test': 3 } },
+ email: null
}
};
- var result = Qs.parse(input);
+ var result = qs.parse(input);
- expect(result).to.deep.equal(expected);
- done();
+ st.deepEqual(result, expected);
+ st.end();
});
- it('does not blow up when Buffer global is missing', function (done) {
-
+ t.test('does not blow up when Buffer global is missing', function (st) {
var tempBuffer = global.Buffer;
delete global.Buffer;
- var result = Qs.parse('a=b&c=d');
+ var result = qs.parse('a=b&c=d');
global.Buffer = tempBuffer;
- expect(result).to.deep.equal({ a: 'b', c: 'd' });
- done();
+ st.deepEqual(result, { a: 'b', c: 'd' });
+ st.end();
});
- it('does not crash when parsing circular references', function (done) {
-
+ t.test('does not crash when parsing circular references', function (st) {
var a = {};
a.b = a;
var parsed;
- expect(function () {
-
- parsed = Qs.parse({ 'foo[bar]': 'baz', 'foo[baz]': a });
- }).to.not.throw();
+ st.doesNotThrow(function () {
+ parsed = qs.parse({ 'foo[bar]': 'baz', 'foo[baz]': a });
+ });
- expect(parsed).to.contain('foo');
- expect(parsed.foo).to.contain('bar', 'baz');
- expect(parsed.foo.bar).to.equal('baz');
- expect(parsed.foo.baz).to.deep.equal(a);
- done();
+ st.equal('foo' in parsed, true, 'parsed has "foo" property');
+ st.equal('bar' in parsed.foo, true);
+ st.equal('baz' in parsed.foo, true);
+ st.equal(parsed.foo.bar, 'baz');
+ st.deepEqual(parsed.foo.baz, a);
+ st.end();
});
- it('parses plain objects correctly', function (done) {
-
+ t.test('parses plain objects correctly', function (st) {
var a = Object.create(null);
a.b = 'c';
- expect(Qs.parse(a)).to.deep.equal({ b: 'c' });
- var result = Qs.parse({ a: a });
- expect(result).to.contain('a');
- expect(result.a).to.deep.equal(a);
- done();
+ st.deepEqual(qs.parse(a), { b: 'c' });
+ var result = qs.parse({ a: a });
+ st.equal('a' in result, true, 'result has "a" property');
+ st.deepEqual(result.a, a);
+ st.end();
});
- it('parses dates correctly', function (done) {
-
+ t.test('parses dates correctly', function (st) {
var now = new Date();
- expect(Qs.parse({ a: now })).to.deep.equal({ a: now });
- done();
+ st.deepEqual(qs.parse({ a: now }), { a: now });
+ st.end();
});
- it('parses regular expressions correctly', function (done) {
-
+ t.test('parses regular expressions correctly', function (st) {
var re = /^test$/;
- expect(Qs.parse({ a: re })).to.deep.equal({ a: re });
- done();
+ st.deepEqual(qs.parse({ a: re }), { a: re });
+ st.end();
});
- it('can allow overwriting prototype properties', function (done) {
-
- expect(Qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true })).to.deep.equal({ a: { hasOwnProperty: 'b' } }, { prototype: false });
- expect(Qs.parse('hasOwnProperty=b', { allowPrototypes: true })).to.deep.equal({ hasOwnProperty: 'b' }, { prototype: false });
- done();
+ t.test('can allow overwriting prototype properties', function (st) {
+ st.deepEqual(qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true }), { a: { hasOwnProperty: 'b' } }, { prototype: false });
+ st.deepEqual(qs.parse('hasOwnProperty=b', { allowPrototypes: true }), { hasOwnProperty: 'b' }, { prototype: false });
+ st.end();
});
- it('can return plain objects', function (done) {
-
+ t.test('can return plain objects', function (st) {
var expected = Object.create(null);
expected.a = Object.create(null);
expected.a.b = 'c';
expected.a.hasOwnProperty = 'd';
- expect(Qs.parse('a[b]=c&a[hasOwnProperty]=d', { plainObjects: true })).to.deep.equal(expected);
- expect(Qs.parse(null, { plainObjects: true })).to.deep.equal(Object.create(null));
+ st.deepEqual(qs.parse('a[b]=c&a[hasOwnProperty]=d', { plainObjects: true }), expected);
+ st.deepEqual(qs.parse(null, { plainObjects: true }), Object.create(null));
var expectedArray = Object.create(null);
expectedArray.a = Object.create(null);
expectedArray.a['0'] = 'b';
expectedArray.a.c = 'd';
- expect(Qs.parse('a[]=b&a[c]=d', { plainObjects: true })).to.deep.equal(expectedArray);
- done();
+ st.deepEqual(qs.parse('a[]=b&a[c]=d', { plainObjects: true }), expectedArray);
+ st.end();
});
});
diff --git a/node_modules/request/node_modules/qs/test/stringify.js b/node_modules/request/node_modules/qs/test/stringify.js
index 53139ff90..88d22f25e 100644..100755
--- a/node_modules/request/node_modules/qs/test/stringify.js
+++ b/node_modules/request/node_modules/qs/test/stringify.js
@@ -1,293 +1,235 @@
-/* eslint no-extend-native:0 */
-// Load modules
+'use strict';
-var Code = require('code');
-var Lab = require('lab');
-var Qs = require('../');
+var test = require('tape');
+var qs = require('../');
-
-// Declare internals
-
-var internals = {};
-
-
-// Test shortcuts
-
-var lab = exports.lab = Lab.script();
-var expect = Code.expect;
-var describe = lab.experiment;
-var it = lab.test;
-
-
-describe('stringify()', function () {
-
- it('stringifies a querystring object', function (done) {
-
- expect(Qs.stringify({ a: 'b' })).to.equal('a=b');
- expect(Qs.stringify({ a: 1 })).to.equal('a=1');
- expect(Qs.stringify({ a: 1, b: 2 })).to.equal('a=1&b=2');
- expect(Qs.stringify({ a: 'A_Z' })).to.equal('a=A_Z');
- expect(Qs.stringify({ a: '€' })).to.equal('a=%E2%82%AC');
- expect(Qs.stringify({ a: '' })).to.equal('a=%EE%80%80');
- expect(Qs.stringify({ a: 'א' })).to.equal('a=%D7%90');
- expect(Qs.stringify({ a: '𐐷' })).to.equal('a=%F0%90%90%B7');
- done();
+test('stringify()', function (t) {
+ t.test('stringifies a querystring object', function (st) {
+ st.equal(qs.stringify({ a: 'b' }), 'a=b');
+ st.equal(qs.stringify({ a: 1 }), 'a=1');
+ st.equal(qs.stringify({ a: 1, b: 2 }), 'a=1&b=2');
+ st.equal(qs.stringify({ a: 'A_Z' }), 'a=A_Z');
+ st.equal(qs.stringify({ a: '€' }), 'a=%E2%82%AC');
+ st.equal(qs.stringify({ a: '' }), 'a=%EE%80%80');
+ st.equal(qs.stringify({ a: 'א' }), 'a=%D7%90');
+ st.equal(qs.stringify({ a: '𐐷' }), 'a=%F0%90%90%B7');
+ st.end();
});
- it('stringifies a nested object', function (done) {
-
- expect(Qs.stringify({ a: { b: 'c' } })).to.equal('a%5Bb%5D=c');
- expect(Qs.stringify({ a: { b: { c: { d: 'e' } } } })).to.equal('a%5Bb%5D%5Bc%5D%5Bd%5D=e');
- done();
+ t.test('stringifies a nested object', function (st) {
+ st.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c');
+ st.equal(qs.stringify({ a: { b: { c: { d: 'e' } } } }), 'a%5Bb%5D%5Bc%5D%5Bd%5D=e');
+ st.end();
});
- it('stringifies an array value', function (done) {
-
- expect(Qs.stringify({ a: ['b', 'c', 'd'] })).to.equal('a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d');
- done();
+ t.test('stringifies an array value', function (st) {
+ st.equal(qs.stringify({ a: ['b', 'c', 'd'] }), 'a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d');
+ st.end();
});
- it('omits nulls when asked', function (done) {
-
- expect(Qs.stringify({ a: 'b', c: null }, { skipNulls: true })).to.equal('a=b');
- done();
+ t.test('omits nulls when asked', function (st) {
+ st.equal(qs.stringify({ a: 'b', c: null }, { skipNulls: true }), 'a=b');
+ st.end();
});
- it('omits nested nulls when asked', function (done) {
-
- expect(Qs.stringify({ a: { b: 'c', d: null } }, { skipNulls: true })).to.equal('a%5Bb%5D=c');
- done();
+ t.test('omits nested nulls when asked', function (st) {
+ st.equal(qs.stringify({ a: { b: 'c', d: null } }, { skipNulls: true }), 'a%5Bb%5D=c');
+ st.end();
});
- it('omits array indices when asked', function (done) {
-
- expect(Qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false })).to.equal('a=b&a=c&a=d');
- done();
+ t.test('omits array indices when asked', function (st) {
+ st.equal(qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false }), 'a=b&a=c&a=d');
+ st.end();
});
- it('stringifies a nested array value', function (done) {
-
- expect(Qs.stringify({ a: { b: ['c', 'd'] } })).to.equal('a%5Bb%5D%5B0%5D=c&a%5Bb%5D%5B1%5D=d');
- done();
+ t.test('stringifies a nested array value', function (st) {
+ st.equal(qs.stringify({ a: { b: ['c', 'd'] } }), 'a%5Bb%5D%5B0%5D=c&a%5Bb%5D%5B1%5D=d');
+ st.end();
});
- it('stringifies an object inside an array', function (done) {
-
- expect(Qs.stringify({ a: [{ b: 'c' }] })).to.equal('a%5B0%5D%5Bb%5D=c');
- expect(Qs.stringify({ a: [{ b: { c: [1] } }] })).to.equal('a%5B0%5D%5Bb%5D%5Bc%5D%5B0%5D=1');
- done();
+ t.test('stringifies an object inside an array', function (st) {
+ st.equal(qs.stringify({ a: [{ b: 'c' }] }), 'a%5B0%5D%5Bb%5D=c');
+ st.equal(qs.stringify({ a: [{ b: { c: [1] } }] }), 'a%5B0%5D%5Bb%5D%5Bc%5D%5B0%5D=1');
+ st.end();
});
- it('does not omit object keys when indices = false', function (done) {
-
- expect(Qs.stringify({ a: [{ b: 'c' }] }, { indices: false })).to.equal('a%5Bb%5D=c');
- done();
+ t.test('does not omit object keys when indices = false', function (st) {
+ st.equal(qs.stringify({ a: [{ b: 'c' }] }, { indices: false }), 'a%5Bb%5D=c');
+ st.end();
});
- it('uses indices notation for arrays when indices=true', function (done) {
-
- expect(Qs.stringify({ a: ['b', 'c'] }, { indices: true })).to.equal('a%5B0%5D=b&a%5B1%5D=c');
- done();
+ t.test('uses indices notation for arrays when indices=true', function (st) {
+ st.equal(qs.stringify({ a: ['b', 'c'] }, { indices: true }), 'a%5B0%5D=b&a%5B1%5D=c');
+ st.end();
});
- it('uses indices notation for arrays when no arrayFormat is specified', function (done) {
-
- expect(Qs.stringify({ a: ['b', 'c'] })).to.equal('a%5B0%5D=b&a%5B1%5D=c');
- done();
+ t.test('uses indices notation for arrays when no arrayFormat is specified', function (st) {
+ st.equal(qs.stringify({ a: ['b', 'c'] }), 'a%5B0%5D=b&a%5B1%5D=c');
+ st.end();
});
- it('uses indices notation for arrays when no arrayFormat=indices', function (done) {
-
- expect(Qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' })).to.equal('a%5B0%5D=b&a%5B1%5D=c');
- done();
+ t.test('uses indices notation for arrays when no arrayFormat=indices', function (st) {
+ st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' }), 'a%5B0%5D=b&a%5B1%5D=c');
+ st.end();
});
- it('uses repeat notation for arrays when no arrayFormat=repeat', function (done) {
-
- expect(Qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' })).to.equal('a=b&a=c');
- done();
+ t.test('uses repeat notation for arrays when no arrayFormat=repeat', function (st) {
+ st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' }), 'a=b&a=c');
+ st.end();
});
- it('uses brackets notation for arrays when no arrayFormat=brackets', function (done) {
-
- expect(Qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' })).to.equal('a%5B%5D=b&a%5B%5D=c');
- done();
+ t.test('uses brackets notation for arrays when no arrayFormat=brackets', function (st) {
+ st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' }), 'a%5B%5D=b&a%5B%5D=c');
+ st.end();
});
- it('stringifies a complicated object', function (done) {
-
- expect(Qs.stringify({ a: { b: 'c', d: 'e' } })).to.equal('a%5Bb%5D=c&a%5Bd%5D=e');
- done();
+ t.test('stringifies a complicated object', function (st) {
+ st.equal(qs.stringify({ a: { b: 'c', d: 'e' } }), 'a%5Bb%5D=c&a%5Bd%5D=e');
+ st.end();
});
- it('stringifies an empty value', function (done) {
-
- expect(Qs.stringify({ a: '' })).to.equal('a=');
- expect(Qs.stringify({ a: null }, { strictNullHandling: true })).to.equal('a');
+ t.test('stringifies an empty value', function (st) {
+ st.equal(qs.stringify({ a: '' }), 'a=');
+ st.equal(qs.stringify({ a: null }, { strictNullHandling: true }), 'a');
- expect(Qs.stringify({ a: '', b: '' })).to.equal('a=&b=');
- expect(Qs.stringify({ a: null, b: '' }, { strictNullHandling: true })).to.equal('a&b=');
+ st.equal(qs.stringify({ a: '', b: '' }), 'a=&b=');
+ st.equal(qs.stringify({ a: null, b: '' }, { strictNullHandling: true }), 'a&b=');
- expect(Qs.stringify({ a: { b: '' } })).to.equal('a%5Bb%5D=');
- expect(Qs.stringify({ a: { b: null } }, { strictNullHandling: true })).to.equal('a%5Bb%5D');
- expect(Qs.stringify({ a: { b: null } }, { strictNullHandling: false })).to.equal('a%5Bb%5D=');
+ st.equal(qs.stringify({ a: { b: '' } }), 'a%5Bb%5D=');
+ st.equal(qs.stringify({ a: { b: null } }, { strictNullHandling: true }), 'a%5Bb%5D');
+ st.equal(qs.stringify({ a: { b: null } }, { strictNullHandling: false }), 'a%5Bb%5D=');
- done();
+ st.end();
});
- it('stringifies an empty object', function (done) {
-
+ t.test('stringifies an empty object', function (st) {
var obj = Object.create(null);
obj.a = 'b';
- expect(Qs.stringify(obj)).to.equal('a=b');
- done();
+ st.equal(qs.stringify(obj), 'a=b');
+ st.end();
});
- it('returns an empty string for invalid input', function (done) {
-
- expect(Qs.stringify(undefined)).to.equal('');
- expect(Qs.stringify(false)).to.equal('');
- expect(Qs.stringify(null)).to.equal('');
- expect(Qs.stringify('')).to.equal('');
- done();
+ t.test('returns an empty string for invalid input', function (st) {
+ st.equal(qs.stringify(undefined), '');
+ st.equal(qs.stringify(false), '');
+ st.equal(qs.stringify(null), '');
+ st.equal(qs.stringify(''), '');
+ st.end();
});
- it('stringifies an object with an empty object as a child', function (done) {
-
+ t.test('stringifies an object with an empty object as a child', function (st) {
var obj = {
a: Object.create(null)
};
obj.a.b = 'c';
- expect(Qs.stringify(obj)).to.equal('a%5Bb%5D=c');
- done();
+ st.equal(qs.stringify(obj), 'a%5Bb%5D=c');
+ st.end();
});
- it('drops keys with a value of undefined', function (done) {
+ t.test('drops keys with a value of undefined', function (st) {
+ st.equal(qs.stringify({ a: undefined }), '');
- expect(Qs.stringify({ a: undefined })).to.equal('');
-
- expect(Qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: true })).to.equal('a%5Bc%5D');
- expect(Qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: false })).to.equal('a%5Bc%5D=');
- expect(Qs.stringify({ a: { b: undefined, c: '' } })).to.equal('a%5Bc%5D=');
- done();
+ st.equal(qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: true }), 'a%5Bc%5D');
+ st.equal(qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: false }), 'a%5Bc%5D=');
+ st.equal(qs.stringify({ a: { b: undefined, c: '' } }), 'a%5Bc%5D=');
+ st.end();
});
- it('url encodes values', function (done) {
-
- expect(Qs.stringify({ a: 'b c' })).to.equal('a=b%20c');
- done();
+ t.test('url encodes values', function (st) {
+ st.equal(qs.stringify({ a: 'b c' }), 'a=b%20c');
+ st.end();
});
- it('stringifies a date', function (done) {
-
+ t.test('stringifies a date', function (st) {
var now = new Date();
var str = 'a=' + encodeURIComponent(now.toISOString());
- expect(Qs.stringify({ a: now })).to.equal(str);
- done();
+ st.equal(qs.stringify({ a: now }), str);
+ st.end();
});
- it('stringifies the weird object from qs', function (done) {
-
- expect(Qs.stringify({ 'my weird field': '~q1!2"\'w$5&7/z8)?' })).to.equal('my%20weird%20field=~q1%212%22%27w%245%267%2Fz8%29%3F');
- done();
+ t.test('stringifies the weird object from qs', function (st) {
+ st.equal(qs.stringify({ 'my weird field': '~q1!2"\'w$5&7/z8)?' }), 'my%20weird%20field=~q1%212%22%27w%245%267%2Fz8%29%3F');
+ st.end();
});
- it('skips properties that are part of the object prototype', function (done) {
-
+ t.test('skips properties that are part of the object prototype', function (st) {
Object.prototype.crash = 'test';
- expect(Qs.stringify({ a: 'b' })).to.equal('a=b');
- expect(Qs.stringify({ a: { b: 'c' } })).to.equal('a%5Bb%5D=c');
+ st.equal(qs.stringify({ a: 'b' }), 'a=b');
+ st.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c');
delete Object.prototype.crash;
- done();
+ st.end();
});
- it('stringifies boolean values', function (done) {
-
- expect(Qs.stringify({ a: true })).to.equal('a=true');
- expect(Qs.stringify({ a: { b: true } })).to.equal('a%5Bb%5D=true');
- expect(Qs.stringify({ b: false })).to.equal('b=false');
- expect(Qs.stringify({ b: { c: false } })).to.equal('b%5Bc%5D=false');
- done();
+ t.test('stringifies boolean values', function (st) {
+ st.equal(qs.stringify({ a: true }), 'a=true');
+ st.equal(qs.stringify({ a: { b: true } }), 'a%5Bb%5D=true');
+ st.equal(qs.stringify({ b: false }), 'b=false');
+ st.equal(qs.stringify({ b: { c: false } }), 'b%5Bc%5D=false');
+ st.end();
});
- it('stringifies buffer values', function (done) {
-
- expect(Qs.stringify({ a: new Buffer('test') })).to.equal('a=test');
- expect(Qs.stringify({ a: { b: new Buffer('test') } })).to.equal('a%5Bb%5D=test');
- done();
+ t.test('stringifies buffer values', function (st) {
+ st.equal(qs.stringify({ a: new Buffer('test') }), 'a=test');
+ st.equal(qs.stringify({ a: { b: new Buffer('test') } }), 'a%5Bb%5D=test');
+ st.end();
});
- it('stringifies an object using an alternative delimiter', function (done) {
-
- expect(Qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' })).to.equal('a=b;c=d');
- done();
+ t.test('stringifies an object using an alternative delimiter', function (st) {
+ st.equal(qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }), 'a=b;c=d');
+ st.end();
});
- it('doesn\'t blow up when Buffer global is missing', function (done) {
-
+ t.test('doesn\'t blow up when Buffer global is missing', function (st) {
var tempBuffer = global.Buffer;
delete global.Buffer;
- var result = Qs.stringify({ a: 'b', c: 'd' });
+ var result = qs.stringify({ a: 'b', c: 'd' });
global.Buffer = tempBuffer;
- expect(result).to.equal('a=b&c=d');
- done();
+ st.equal(result, 'a=b&c=d');
+ st.end();
});
- it('selects properties when filter=array', function (done) {
-
- expect(Qs.stringify({ a: 'b' }, { filter: ['a'] })).to.equal('a=b');
- expect(Qs.stringify({ a: 1 }, { filter: [] })).to.equal('');
- expect(Qs.stringify({ a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, { filter: ['a', 'b', 0, 2] })).to.equal('a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3');
- done();
-
+ t.test('selects properties when filter=array', function (st) {
+ st.equal(qs.stringify({ a: 'b' }, { filter: ['a'] }), 'a=b');
+ st.equal(qs.stringify({ a: 1 }, { filter: [] }), '');
+ st.equal(qs.stringify({ a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, { filter: ['a', 'b', 0, 2] }), 'a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3');
+ st.end();
});
- it('supports custom representations when filter=function', function (done) {
-
+ t.test('supports custom representations when filter=function', function (st) {
var calls = 0;
var obj = { a: 'b', c: 'd', e: { f: new Date(1257894000000) } };
var filterFunc = function (prefix, value) {
-
calls++;
if (calls === 1) {
- expect(prefix).to.be.empty();
- expect(value).to.equal(obj);
- }
- else if (prefix === 'c') {
+ st.equal(prefix, '', 'prefix is empty');
+ st.equal(value, obj);
+ } else if (prefix === 'c') {
return;
- }
- else if (value instanceof Date) {
- expect(prefix).to.equal('e[f]');
+ } else if (value instanceof Date) {
+ st.equal(prefix, 'e[f]');
return value.getTime();
}
return value;
};
- expect(Qs.stringify(obj, { filter: filterFunc })).to.equal('a=b&e%5Bf%5D=1257894000000');
- expect(calls).to.equal(5);
- done();
-
+ st.equal(qs.stringify(obj, { filter: filterFunc }), 'a=b&e%5Bf%5D=1257894000000');
+ st.equal(calls, 5);
+ st.end();
});
- it('can disable uri encoding', function (done) {
-
- expect(Qs.stringify({ a: 'b' }, { encode: false })).to.equal('a=b');
- expect(Qs.stringify({ a: { b: 'c' } }, { encode: false })).to.equal('a[b]=c');
- expect(Qs.stringify({ a: 'b', c: null }, { strictNullHandling: true, encode: false })).to.equal('a=b&c');
- done();
+ t.test('can disable uri encoding', function (st) {
+ st.equal(qs.stringify({ a: 'b' }, { encode: false }), 'a=b');
+ st.equal(qs.stringify({ a: { b: 'c' } }, { encode: false }), 'a[b]=c');
+ st.equal(qs.stringify({ a: 'b', c: null }, { strictNullHandling: true, encode: false }), 'a=b&c');
+ st.end();
});
- it('can sort the keys', function (done) {
-
- var sort = function alphabeticalSort (a, b) {
-
- return a.localeCompare(b);
- };
-
- expect(Qs.stringify({ a: 'c', z: 'y', b : 'f' }, { sort : sort })).to.equal('a=c&b=f&z=y');
- expect(Qs.stringify({ a: 'c', z: { j: 'a', i:'b' }, b : 'f' }, { sort : sort })).to.equal('a=c&b=f&z%5Bi%5D=b&z%5Bj%5D=a');
- done();
+ t.test('can sort the keys', function (st) {
+ var sort = function (a, b) { return a.localeCompare(b); };
+ st.equal(qs.stringify({ a: 'c', z: 'y', b: 'f' }, { sort: sort }), 'a=c&b=f&z=y');
+ st.equal(qs.stringify({ a: 'c', z: { j: 'a', i: 'b' }, b: 'f' }, { sort: sort }), 'a=c&b=f&z%5Bi%5D=b&z%5Bj%5D=a');
+ st.end();
});
});
diff --git a/node_modules/request/node_modules/qs/test/utils.js b/node_modules/request/node_modules/qs/test/utils.js
index a9a6b520d..4a8d8246c 100644..100755
--- a/node_modules/request/node_modules/qs/test/utils.js
+++ b/node_modules/request/node_modules/qs/test/utils.js
@@ -1,28 +1,9 @@
-// Load modules
+'use strict';
-var Code = require('code');
-var Lab = require('lab');
-var Utils = require('../lib/utils');
+var test = require('tape');
+var utils = require('../lib/utils');
-
-// Declare internals
-
-var internals = {};
-
-
-// Test shortcuts
-
-var lab = exports.lab = Lab.script();
-var expect = Code.expect;
-var describe = lab.experiment;
-var it = lab.test;
-
-
-describe('merge()', function () {
-
- it('can merge two objects with the same key', function (done) {
-
- expect(Utils.merge({ a: 'b' }, { a: 'c' })).to.deep.equal({ a: ['b', 'c'] });
- done();
- });
+test('merge()', function (t) {
+ t.deepEqual(utils.merge({ a: 'b' }, { a: 'c' }), { a: ['b', 'c'] }, 'merges two objects with the same key');
+ t.end();
});
diff --git a/node_modules/request/package.json b/node_modules/request/package.json
index 025c965d4..f3f8cf490 100644
--- a/node_modules/request/package.json
+++ b/node_modules/request/package.json
@@ -1,46 +1,44 @@
{
"_args": [
[
- "request@~2.67.0",
- "/Users/ogd/Documents/projects/npm/npm"
+ "request@latest",
+ "/Users/rebecca/code/npm"
]
],
- "_from": "request@>=2.67.0 <2.68.0",
- "_id": "request@2.67.0",
+ "_from": "request@latest",
+ "_id": "request@2.69.0",
"_inCache": true,
"_installable": true,
"_location": "/request",
- "_nodeVersion": "5.0.0",
+ "_nodeVersion": "4.1.2",
"_npmUser": {
- "email": "simeonvelichkov@gmail.com",
- "name": "simov"
+ "email": "mikeal.rogers@gmail.com",
+ "name": "mikeal"
},
- "_npmVersion": "3.3.12",
+ "_npmVersion": "2.14.4",
"_phantomChildren": {
"ansi-regex": "2.0.0",
- "readable-stream": "2.0.4",
+ "readable-stream": "2.0.5",
"strip-ansi": "3.0.0"
},
"_requested": {
"name": "request",
- "raw": "request@~2.67.0",
- "rawSpec": "~2.67.0",
+ "raw": "request@latest",
+ "rawSpec": "latest",
"scope": null,
- "spec": ">=2.67.0 <2.68.0",
- "type": "range"
+ "spec": "latest",
+ "type": "tag"
},
"_requiredBy": [
"/",
"/node-gyp",
- "/npm-registry-client",
- "/npm-registry-couchapp/couchapp",
- "/npm-registry-couchapp/couchapp/nano"
+ "/npm-registry-client"
],
- "_resolved": "https://registry.npmjs.org/request/-/request-2.67.0.tgz",
- "_shasum": "8af74780e2bf11ea0ae9aa965c11f11afd272742",
+ "_resolved": "https://registry.npmjs.org/request/-/request-2.69.0.tgz",
+ "_shasum": "cf91d2e000752b1217155c005241911991a2346a",
"_shrinkwrap": null,
- "_spec": "request@~2.67.0",
- "_where": "/Users/ogd/Documents/projects/npm/npm",
+ "_spec": "request@latest",
+ "_where": "/Users/rebecca/code/npm",
"author": {
"email": "mikeal.rogers@gmail.com",
"name": "Mikeal Rogers"
@@ -50,13 +48,14 @@
},
"dependencies": {
"aws-sign2": "~0.6.0",
+ "aws4": "^1.2.1",
"bl": "~1.0.0",
"caseless": "~0.11.0",
"combined-stream": "~1.0.5",
"extend": "~3.0.0",
"forever-agent": "~0.6.1",
"form-data": "~1.0.0-rc3",
- "har-validator": "~2.0.2",
+ "har-validator": "~2.0.6",
"hawk": "~3.1.0",
"http-signature": "~1.1.0",
"is-typedarray": "~1.0.0",
@@ -65,7 +64,7 @@
"mime-types": "~2.1.7",
"node-uuid": "~1.4.7",
"oauth-sign": "~0.8.0",
- "qs": "~5.2.0",
+ "qs": "~6.0.2",
"stringstream": "~0.0.4",
"tough-cookie": "~2.2.0",
"tunnel-agent": "~0.4.1"
@@ -73,12 +72,12 @@
"description": "Simplified HTTP request client.",
"devDependencies": {
"bluebird": "^3.0.2",
- "browserify": "^12.0.1",
+ "browserify": "^13.0.0",
"browserify-istanbul": "^0.1.5",
- "buffer-equal": "^0.0.1",
+ "buffer-equal": "^1.0.0",
"codecov.io": "^0.1.6",
"coveralls": "^2.11.4",
- "eslint": "1.9.0",
+ "eslint": "1.10.3",
"function-bind": "^1.0.2",
"istanbul": "^0.4.0",
"karma": "^0.13.10",
@@ -94,13 +93,13 @@
},
"directories": {},
"dist": {
- "shasum": "8af74780e2bf11ea0ae9aa965c11f11afd272742",
- "tarball": "http://registry.npmjs.org/request/-/request-2.67.0.tgz"
+ "shasum": "cf91d2e000752b1217155c005241911991a2346a",
+ "tarball": "http://registry.npmjs.org/request/-/request-2.69.0.tgz"
},
"engines": {
"node": ">=0.8.0"
},
- "gitHead": "76f0655befbe8b37fa246bdca1107cbf57798d9a",
+ "gitHead": "1c2fb40c74efb4f706f350a78dbd5e58fe913af3",
"homepage": "https://github.com/request/request#readme",
"license": "Apache-2.0",
"main": "index.js",
@@ -142,5 +141,5 @@
"util",
"utility"
],
- "version": "2.67.0"
+ "version": "2.69.0"
}
diff --git a/node_modules/request/request.js b/node_modules/request/request.js
index 19c1b92f3..e4a181237 100644
--- a/node_modules/request/request.js
+++ b/node_modules/request/request.js
@@ -8,13 +8,14 @@ var http = require('http')
, zlib = require('zlib')
, bl = require('bl')
, hawk = require('hawk')
- , aws = require('aws-sign2')
+ , aws2 = require('aws-sign2')
, httpSignature = require('http-signature')
, mime = require('mime-types')
, stringstream = require('stringstream')
, caseless = require('caseless')
, ForeverAgent = require('forever-agent')
, FormData = require('form-data')
+ , extend = require('extend')
, isTypedArray = require('is-typedarray').strict
, helpers = require('./lib/helpers')
, cookies = require('./lib/cookies')
@@ -123,7 +124,7 @@ function Request (options) {
var reserved = Object.keys(Request.prototype)
var nonReserved = filterForNonReserved(reserved, options)
- util._extend(self, nonReserved)
+ extend(self, nonReserved)
options = filterOutReservedFunctions(reserved, options)
self.readable = true
@@ -579,7 +580,7 @@ Request.prototype.init = function (options) {
// Before ending the request, we had to compute the length of the whole form, asyncly
self.setHeader(self._form.getHeaders(), true)
self._form.getLength(function (err, length) {
- if (!err) {
+ if (!err && !isNaN(length)) {
self.setHeader('content-length', length)
}
end()
@@ -1044,7 +1045,7 @@ Request.prototype.abort = function () {
self.req.abort()
}
else if (self.response) {
- self.response.abort()
+ self.response.destroy()
}
self.emit('abort')
@@ -1228,29 +1229,52 @@ Request.prototype.aws = function (opts, now) {
self._aws = opts
return self
}
- var date = new Date()
- self.setHeader('date', date.toUTCString())
- var auth =
- { key: opts.key
- , secret: opts.secret
- , verb: self.method.toUpperCase()
- , date: date
- , contentType: self.getHeader('content-type') || ''
- , md5: self.getHeader('content-md5') || ''
- , amazonHeaders: aws.canonicalizeHeaders(self.headers)
+
+ if (opts.sign_version == 4 || opts.sign_version == '4') {
+ var aws4 = require('aws4')
+ // use aws4
+ var options = {
+ host: self.uri.host,
+ path: self.uri.path,
+ method: self.method,
+ headers: {
+ 'content-type': self.getHeader('content-type') || ''
+ },
+ body: self.body
}
- var path = self.uri.path
- if (opts.bucket && path) {
- auth.resource = '/' + opts.bucket + path
- } else if (opts.bucket && !path) {
- auth.resource = '/' + opts.bucket
- } else if (!opts.bucket && path) {
- auth.resource = path
- } else if (!opts.bucket && !path) {
- auth.resource = '/'
- }
- auth.resource = aws.canonicalizeResource(auth.resource)
- self.setHeader('authorization', aws.authorization(auth))
+ var signRes = aws4.sign(options, {
+ accessKeyId: opts.key,
+ secretAccessKey: opts.secret
+ })
+ self.setHeader('authorization', signRes.headers.Authorization)
+ self.setHeader('x-amz-date', signRes.headers['X-Amz-Date'])
+ }
+ else {
+ // default: use aws-sign2
+ var date = new Date()
+ self.setHeader('date', date.toUTCString())
+ var auth =
+ { key: opts.key
+ , secret: opts.secret
+ , verb: self.method.toUpperCase()
+ , date: date
+ , contentType: self.getHeader('content-type') || ''
+ , md5: self.getHeader('content-md5') || ''
+ , amazonHeaders: aws2.canonicalizeHeaders(self.headers)
+ }
+ var path = self.uri.path
+ if (opts.bucket && path) {
+ auth.resource = '/' + opts.bucket + path
+ } else if (opts.bucket && !path) {
+ auth.resource = '/' + opts.bucket
+ } else if (!opts.bucket && path) {
+ auth.resource = path
+ } else if (!opts.bucket && !path) {
+ auth.resource = '/'
+ }
+ auth.resource = aws2.canonicalizeResource(auth.resource)
+ self.setHeader('authorization', aws2.authorization(auth))
+ }
return self
}