PageRenderTime 44ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/share/www/script/oauth.js

http://github.com/apache/couchdb
JavaScript | 511 lines | 397 code | 12 blank | 102 comment | 122 complexity | 52865413379df90062d84af0045cb809 MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0
  1. /*
  2. * Copyright 2008 Netflix, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. /* Here's some JavaScript software for implementing OAuth.
  17. This isn't as useful as you might hope. OAuth is based around
  18. allowing tools and websites to talk to each other. However,
  19. JavaScript running in web browsers is hampered by security
  20. restrictions that prevent code running on one website from
  21. accessing data stored or served on another.
  22. Before you start hacking, make sure you understand the limitations
  23. posed by cross-domain XMLHttpRequest.
  24. On the bright side, some platforms use JavaScript as their
  25. language, but enable the programmer to access other web sites.
  26. Examples include Google Gadgets, and Microsoft Vista Sidebar.
  27. For those platforms, this library should come in handy.
  28. */
  29. // The HMAC-SHA1 signature method calls b64_hmac_sha1, defined by
  30. // http://pajhome.org.uk/crypt/md5/sha1.js
  31. /* An OAuth message is represented as an object like this:
  32. {method: "GET", action: "http://server.com/path", parameters: ...}
  33. The parameters may be either a map {name: value, name2: value2}
  34. or an Array of name-value pairs [[name, value], [name2, value2]].
  35. The latter representation is more powerful: it supports parameters
  36. in a specific sequence, or several parameters with the same name;
  37. for example [["a", 1], ["b", 2], ["a", 3]].
  38. Parameter names and values are NOT percent-encoded in an object.
  39. They must be encoded before transmission and decoded after reception.
  40. For example, this message object:
  41. {method: "GET", action: "http://server/path", parameters: {p: "x y"}}
  42. ... can be transmitted as an HTTP request that begins:
  43. GET /path?p=x%20y HTTP/1.0
  44. (This isn't a valid OAuth request, since it lacks a signature etc.)
  45. Note that the object "x y" is transmitted as x%20y. To encode
  46. parameters, you can call OAuth.addToURL, OAuth.formEncode or
  47. OAuth.getAuthorization.
  48. This message object model harmonizes with the browser object model for
  49. input elements of an form, whose value property isn't percent encoded.
  50. The browser encodes each value before transmitting it. For example,
  51. see consumer.setInputs in example/consumer.js.
  52. */
  53. var OAuth; if (OAuth == null) OAuth = {};
  54. OAuth.setProperties = function setProperties(into, from) {
  55. if (into != null && from != null) {
  56. for (var key in from) {
  57. into[key] = from[key];
  58. }
  59. }
  60. return into;
  61. }
  62. OAuth.setProperties(OAuth, // utility functions
  63. {
  64. percentEncode: function percentEncode(s) {
  65. if (s == null) {
  66. return "";
  67. }
  68. if (s instanceof Array) {
  69. var e = "";
  70. for (var i = 0; i < s.length; ++i) {
  71. if (e != "") e += '&';
  72. e += percentEncode(s[i]);
  73. }
  74. return e;
  75. }
  76. s = encodeURIComponent(s);
  77. // Now replace the values which encodeURIComponent doesn't do
  78. // encodeURIComponent ignores: - _ . ! ~ * ' ( )
  79. // OAuth dictates the only ones you can ignore are: - _ . ~
  80. // Source: http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Functions:encodeURIComponent
  81. s = s.replace(/\!/g, "%21");
  82. s = s.replace(/\*/g, "%2A");
  83. s = s.replace(/\'/g, "%27");
  84. s = s.replace(/\(/g, "%28");
  85. s = s.replace(/\)/g, "%29");
  86. return s;
  87. }
  88. ,
  89. decodePercent: function decodePercent(s) {
  90. if (s != null) {
  91. // Handle application/x-www-form-urlencoded, which is defined by
  92. // http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1
  93. s = s.replace(/\+/g, " ");
  94. }
  95. return decodeURIComponent(s);
  96. }
  97. ,
  98. /** Convert the given parameters to an Array of name-value pairs. */
  99. getParameterList: function getParameterList(parameters) {
  100. if (parameters == null) {
  101. return [];
  102. }
  103. if (typeof parameters != "object") {
  104. return decodeForm(parameters + "");
  105. }
  106. if (parameters instanceof Array) {
  107. return parameters;
  108. }
  109. var list = [];
  110. for (var p in parameters) {
  111. list.push([p, parameters[p]]);
  112. }
  113. return list;
  114. }
  115. ,
  116. /** Convert the given parameters to a map from name to value. */
  117. getParameterMap: function getParameterMap(parameters) {
  118. if (parameters == null) {
  119. return {};
  120. }
  121. if (typeof parameters != "object") {
  122. return getParameterMap(decodeForm(parameters + ""));
  123. }
  124. if (parameters instanceof Array) {
  125. var map = {};
  126. for (var p = 0; p < parameters.length; ++p) {
  127. var key = parameters[p][0];
  128. if (map[key] === undefined) { // first value wins
  129. map[key] = parameters[p][1];
  130. }
  131. }
  132. return map;
  133. }
  134. return parameters;
  135. }
  136. ,
  137. getParameter: function getParameter(parameters, name) {
  138. if (parameters instanceof Array) {
  139. for (var p = 0; p < parameters.length; ++p) {
  140. if (parameters[p][0] == name) {
  141. return parameters[p][1]; // first value wins
  142. }
  143. }
  144. } else {
  145. return OAuth.getParameterMap(parameters)[name];
  146. }
  147. return null;
  148. }
  149. ,
  150. formEncode: function formEncode(parameters) {
  151. var form = "";
  152. var list = OAuth.getParameterList(parameters);
  153. for (var p = 0; p < list.length; ++p) {
  154. var value = list[p][1];
  155. if (value == null) value = "";
  156. if (form != "") form += '&';
  157. form += OAuth.percentEncode(list[p][0])
  158. +'='+ OAuth.percentEncode(value);
  159. }
  160. return form;
  161. }
  162. ,
  163. decodeForm: function decodeForm(form) {
  164. var list = [];
  165. var nvps = form.split('&');
  166. for (var n = 0; n < nvps.length; ++n) {
  167. var nvp = nvps[n];
  168. if (nvp == "") {
  169. continue;
  170. }
  171. var equals = nvp.indexOf('=');
  172. var name;
  173. var value;
  174. if (equals < 0) {
  175. name = OAuth.decodePercent(nvp);
  176. value = null;
  177. } else {
  178. name = OAuth.decodePercent(nvp.substring(0, equals));
  179. value = OAuth.decodePercent(nvp.substring(equals + 1));
  180. }
  181. list.push([name, value]);
  182. }
  183. return list;
  184. }
  185. ,
  186. setParameter: function setParameter(message, name, value) {
  187. var parameters = message.parameters;
  188. if (parameters instanceof Array) {
  189. for (var p = 0; p < parameters.length; ++p) {
  190. if (parameters[p][0] == name) {
  191. if (value === undefined) {
  192. parameters.splice(p, 1);
  193. } else {
  194. parameters[p][1] = value;
  195. value = undefined;
  196. }
  197. }
  198. }
  199. if (value !== undefined) {
  200. parameters.push([name, value]);
  201. }
  202. } else {
  203. parameters = OAuth.getParameterMap(parameters);
  204. parameters[name] = value;
  205. message.parameters = parameters;
  206. }
  207. }
  208. ,
  209. setParameters: function setParameters(message, parameters) {
  210. var list = OAuth.getParameterList(parameters);
  211. for (var i = 0; i < list.length; ++i) {
  212. OAuth.setParameter(message, list[i][0], list[i][1]);
  213. }
  214. }
  215. ,
  216. /** Fill in parameters to help construct a request message.
  217. This function doesn't fill in every parameter.
  218. The accessor object should be like:
  219. {consumerKey:'foo', consumerSecret:'bar', accessorSecret:'nurn', token:'krelm', tokenSecret:'blah'}
  220. The accessorSecret property is optional.
  221. */
  222. completeRequest: function completeRequest(message, accessor) {
  223. if (message.method == null) {
  224. message.method = "GET";
  225. }
  226. var map = OAuth.getParameterMap(message.parameters);
  227. if (map.oauth_consumer_key == null) {
  228. OAuth.setParameter(message, "oauth_consumer_key", accessor.consumerKey || "");
  229. }
  230. if (map.oauth_token == null && accessor.token != null) {
  231. OAuth.setParameter(message, "oauth_token", accessor.token);
  232. }
  233. if (map.oauth_version == null) {
  234. OAuth.setParameter(message, "oauth_version", "1.0");
  235. }
  236. if (map.oauth_timestamp == null) {
  237. OAuth.setParameter(message, "oauth_timestamp", OAuth.timestamp());
  238. }
  239. if (map.oauth_nonce == null) {
  240. OAuth.setParameter(message, "oauth_nonce", OAuth.nonce(6));
  241. }
  242. OAuth.SignatureMethod.sign(message, accessor);
  243. }
  244. ,
  245. setTimestampAndNonce: function setTimestampAndNonce(message) {
  246. OAuth.setParameter(message, "oauth_timestamp", OAuth.timestamp());
  247. OAuth.setParameter(message, "oauth_nonce", OAuth.nonce(6));
  248. }
  249. ,
  250. addToURL: function addToURL(url, parameters) {
  251. newURL = url;
  252. if (parameters != null) {
  253. var toAdd = OAuth.formEncode(parameters);
  254. if (toAdd.length > 0) {
  255. var q = url.indexOf('?');
  256. if (q < 0) newURL += '?';
  257. else newURL += '&';
  258. newURL += toAdd;
  259. }
  260. }
  261. return newURL;
  262. }
  263. ,
  264. /** Construct the value of the Authorization header for an HTTP request. */
  265. getAuthorizationHeader: function getAuthorizationHeader(realm, parameters) {
  266. var header = 'OAuth realm="' + OAuth.percentEncode(realm) + '"';
  267. var list = OAuth.getParameterList(parameters);
  268. for (var p = 0; p < list.length; ++p) {
  269. var parameter = list[p];
  270. var name = parameter[0];
  271. if (name.indexOf("oauth_") == 0) {
  272. header += ',' + OAuth.percentEncode(name) + '="' + OAuth.percentEncode(parameter[1]) + '"';
  273. }
  274. }
  275. return header;
  276. }
  277. ,
  278. timestamp: function timestamp() {
  279. var d = new Date();
  280. return Math.floor(d.getTime()/1000);
  281. }
  282. ,
  283. nonce: function nonce(length) {
  284. var chars = OAuth.nonce.CHARS;
  285. var result = "";
  286. for (var i = 0; i < length; ++i) {
  287. var rnum = Math.floor(Math.random() * chars.length);
  288. result += chars.substring(rnum, rnum+1);
  289. }
  290. return result;
  291. }
  292. });
  293. OAuth.nonce.CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
  294. /** Define a constructor function,
  295. without causing trouble to anyone who was using it as a namespace.
  296. That is, if parent[name] already existed and had properties,
  297. copy those properties into the new constructor.
  298. */
  299. OAuth.declareClass = function declareClass(parent, name, newConstructor) {
  300. var previous = parent[name];
  301. parent[name] = newConstructor;
  302. if (newConstructor != null && previous != null) {
  303. for (var key in previous) {
  304. if (key != "prototype") {
  305. newConstructor[key] = previous[key];
  306. }
  307. }
  308. }
  309. return newConstructor;
  310. }
  311. /** An abstract algorithm for signing messages. */
  312. OAuth.declareClass(OAuth, "SignatureMethod", function OAuthSignatureMethod(){});
  313. OAuth.setProperties(OAuth.SignatureMethod.prototype, // instance members
  314. {
  315. /** Add a signature to the message. */
  316. sign: function sign(message) {
  317. var baseString = OAuth.SignatureMethod.getBaseString(message);
  318. var signature = this.getSignature(baseString);
  319. OAuth.setParameter(message, "oauth_signature", signature);
  320. return signature; // just in case someone's interested
  321. }
  322. ,
  323. /** Set the key string for signing. */
  324. initialize: function initialize(name, accessor) {
  325. var consumerSecret;
  326. if (accessor.accessorSecret != null
  327. && name.length > 9
  328. && name.substring(name.length-9) == "-Accessor")
  329. {
  330. consumerSecret = accessor.accessorSecret;
  331. } else {
  332. consumerSecret = accessor.consumerSecret;
  333. }
  334. this.key = OAuth.percentEncode(consumerSecret)
  335. +"&"+ OAuth.percentEncode(accessor.tokenSecret);
  336. }
  337. });
  338. /* SignatureMethod expects an accessor object to be like this:
  339. {tokenSecret: "lakjsdflkj...", consumerSecret: "QOUEWRI..", accessorSecret: "xcmvzc..."}
  340. The accessorSecret property is optional.
  341. */
  342. // Class members:
  343. OAuth.setProperties(OAuth.SignatureMethod, // class members
  344. {
  345. sign: function sign(message, accessor) {
  346. var name = OAuth.getParameterMap(message.parameters).oauth_signature_method;
  347. if (name == null || name == "") {
  348. name = "HMAC-SHA1";
  349. OAuth.setParameter(message, "oauth_signature_method", name);
  350. }
  351. OAuth.SignatureMethod.newMethod(name, accessor).sign(message);
  352. }
  353. ,
  354. /** Instantiate a SignatureMethod for the given method name. */
  355. newMethod: function newMethod(name, accessor) {
  356. var impl = OAuth.SignatureMethod.REGISTERED[name];
  357. if (impl != null) {
  358. var method = new impl();
  359. method.initialize(name, accessor);
  360. return method;
  361. }
  362. var err = new Error("signature_method_rejected");
  363. var acceptable = "";
  364. for (var r in OAuth.SignatureMethod.REGISTERED) {
  365. if (acceptable != "") acceptable += '&';
  366. acceptable += OAuth.percentEncode(r);
  367. }
  368. err.oauth_acceptable_signature_methods = acceptable;
  369. throw err;
  370. }
  371. ,
  372. /** A map from signature method name to constructor. */
  373. REGISTERED : {}
  374. ,
  375. /** Subsequently, the given constructor will be used for the named methods.
  376. The constructor will be called with no parameters.
  377. The resulting object should usually implement getSignature(baseString).
  378. You can easily define such a constructor by calling makeSubclass, below.
  379. */
  380. registerMethodClass: function registerMethodClass(names, classConstructor) {
  381. for (var n = 0; n < names.length; ++n) {
  382. OAuth.SignatureMethod.REGISTERED[names[n]] = classConstructor;
  383. }
  384. }
  385. ,
  386. /** Create a subclass of OAuth.SignatureMethod, with the given getSignature function. */
  387. makeSubclass: function makeSubclass(getSignatureFunction) {
  388. var superClass = OAuth.SignatureMethod;
  389. var subClass = function() {
  390. superClass.call(this);
  391. };
  392. subClass.prototype = new superClass();
  393. // Delete instance variables from prototype:
  394. // delete subclass.prototype... There aren't any.
  395. subClass.prototype.getSignature = getSignatureFunction;
  396. subClass.prototype.constructor = subClass;
  397. return subClass;
  398. }
  399. ,
  400. getBaseString: function getBaseString(message) {
  401. var URL = message.action;
  402. var q = URL.indexOf('?');
  403. var parameters;
  404. if (q < 0) {
  405. parameters = message.parameters;
  406. } else {
  407. // Combine the URL query string with the other parameters:
  408. parameters = OAuth.decodeForm(URL.substring(q + 1));
  409. var toAdd = OAuth.getParameterList(message.parameters);
  410. for (var a = 0; a < toAdd.length; ++a) {
  411. parameters.push(toAdd[a]);
  412. }
  413. }
  414. return OAuth.percentEncode(message.method.toUpperCase())
  415. +'&'+ OAuth.percentEncode(OAuth.SignatureMethod.normalizeUrl(URL))
  416. +'&'+ OAuth.percentEncode(OAuth.SignatureMethod.normalizeParameters(parameters));
  417. }
  418. ,
  419. normalizeUrl: function normalizeUrl(url) {
  420. var uri = OAuth.SignatureMethod.parseUri(url);
  421. var scheme = uri.protocol.toLowerCase();
  422. var authority = uri.authority.toLowerCase();
  423. var dropPort = (scheme == "http" && uri.port == 80)
  424. || (scheme == "https" && uri.port == 443);
  425. if (dropPort) {
  426. // find the last : in the authority
  427. var index = authority.lastIndexOf(":");
  428. if (index >= 0) {
  429. authority = authority.substring(0, index);
  430. }
  431. }
  432. var path = uri.path;
  433. if (!path) {
  434. path = "/"; // conforms to RFC 2616 section 3.2.2
  435. }
  436. // we know that there is no query and no fragment here.
  437. return scheme + "://" + authority + path;
  438. }
  439. ,
  440. parseUri: function parseUri (str) {
  441. /* This function was adapted from parseUri 1.2.1
  442. http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
  443. */
  444. var o = {key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
  445. parser: {strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/ }};
  446. var m = o.parser.strict.exec(str);
  447. var uri = {};
  448. var i = 14;
  449. while (i--) uri[o.key[i]] = m[i] || "";
  450. return uri;
  451. }
  452. ,
  453. normalizeParameters: function normalizeParameters(parameters) {
  454. if (parameters == null) {
  455. return "";
  456. }
  457. var list = OAuth.getParameterList(parameters);
  458. var sortable = [];
  459. for (var p = 0; p < list.length; ++p) {
  460. var nvp = list[p];
  461. if (nvp[0] != "oauth_signature") {
  462. sortable.push([ OAuth.percentEncode(nvp[0])
  463. + " " // because it comes before any character that can appear in a percentEncoded string.
  464. + OAuth.percentEncode(nvp[1])
  465. , nvp]);
  466. }
  467. }
  468. sortable.sort(function(a,b) {
  469. if (a[0] < b[0]) return -1;
  470. if (a[0] > b[0]) return 1;
  471. return 0;
  472. });
  473. var sorted = [];
  474. for (var s = 0; s < sortable.length; ++s) {
  475. sorted.push(sortable[s][1]);
  476. }
  477. return OAuth.formEncode(sorted);
  478. }
  479. });
  480. OAuth.SignatureMethod.registerMethodClass(["PLAINTEXT", "PLAINTEXT-Accessor"],
  481. OAuth.SignatureMethod.makeSubclass(
  482. function getSignature(baseString) {
  483. return this.key;
  484. }
  485. ));
  486. OAuth.SignatureMethod.registerMethodClass(["HMAC-SHA1", "HMAC-SHA1-Accessor"],
  487. OAuth.SignatureMethod.makeSubclass(
  488. function getSignature(baseString) {
  489. b64pad = '=';
  490. var signature = b64_hmac_sha1(this.key, baseString);
  491. return signature;
  492. }
  493. ));