1 var crypto = require('crypto')
2 , qs = require('querystring')
5 function sha1 (key, body) {
6 return crypto.createHmac('sha1', key).update(body).digest('base64')
9 function rsa (key, body) {
10 return crypto.createSign("RSA-SHA1").update(body).sign(key, 'base64');
13 function rfc3986 (str) {
14 return encodeURIComponent(str)
23 // Maps object to bi-dimensional array
24 // Converts { foo: 'A', bar: [ 'b', 'B' ]} to
25 // [ ['foo', 'A'], ['bar', 'b'], ['bar', 'B'] ]
27 var key, val, arr = []
30 if (Array.isArray(val))
31 for (var i = 0; i < val.length; i++)
32 arr.push([key, val[i]])
33 else if (typeof val === "object")
35 arr.push([key + '[' + prop + ']', val[prop]]);
42 // Compare function for sort
43 function compare (a, b) {
44 return a > b ? 1 : a < b ? -1 : 0
47 function generateBase (httpMethod, base_uri, params) {
48 // adapted from https://dev.twitter.com/docs/auth/oauth and
49 // https://dev.twitter.com/docs/auth/creating-signature
51 // Parameter normalization
52 // http://tools.ietf.org/html/rfc5849#section-3.4.1.3.2
53 var normalized = map(params)
54 // 1. First, the name and value of each parameter are encoded
56 return [ rfc3986(p[0]), rfc3986(p[1] || '') ]
58 // 2. The parameters are sorted by name, using ascending byte value
59 // ordering. If two or more parameters share the same name, they
60 // are sorted by their value.
61 .sort(function (a, b) {
62 return compare(a[0], b[0]) || compare(a[1], b[1])
64 // 3. The name of each parameter is concatenated to its corresponding
65 // value using an "=" character (ASCII code 61) as a separator, even
66 // if the value is empty.
67 .map(function (p) { return p.join('=') })
68 // 4. The sorted name/value pairs are concatenated together into a
69 // single string by using an "&" character (ASCII code 38) as
74 rfc3986(httpMethod ? httpMethod.toUpperCase() : 'GET'),
82 function hmacsign (httpMethod, base_uri, params, consumer_secret, token_secret) {
83 var base = generateBase(httpMethod, base_uri, params)
85 consumer_secret || '',
87 ].map(rfc3986).join('&')
89 return sha1(key, base)
92 function rsasign (httpMethod, base_uri, params, private_key, token_secret) {
93 var base = generateBase(httpMethod, base_uri, params)
94 var key = private_key || ''
99 function plaintext (consumer_secret, token_secret) {
101 consumer_secret || '',
103 ].map(rfc3986).join('&')
108 function sign (signMethod, httpMethod, base_uri, params, consumer_secret, token_secret) {
112 switch (signMethod) {
124 throw new Error("Signature method not supported: " + signMethod)
127 return method.apply(null, [].slice.call(arguments, skipArgs))
130 exports.hmacsign = hmacsign
131 exports.rsasign = rsasign
132 exports.plaintext = plaintext
134 exports.rfc3986 = rfc3986
135 exports.generateBase = generateBase