Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

publickey.js 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. "use strict";
  2. /**
  3. * PublicKey.js
  4. * https://github.com/diafygi/publickeyjs
  5. *
  6. * A simple javascript library that allows you to search for PGP
  7. * public keys on SKS keyservers and Keybase. The API and results
  8. * are similar to specifications described in HTTP Keyserver Protocol.
  9. *
  10. * @licstart The following is the entire license notice for the
  11. * JavaScript code in this file.
  12. *
  13. * Copyright (c) 2015 Daniel Roesler
  14. *
  15. * The JavaScript code in this page is free software: you can
  16. * redistribute it and/or modify it under the terms of the GNU
  17. * General Public License (GNU GPL) as published by the Free Software
  18. * Foundation, either version 3 of the License, or (at your option)
  19. * any later version. The code is distributed WITHOUT ANY WARRANTY;
  20. * without even the implied warranty of MERCHANTABILITY or FITNESS
  21. * FOR A PARTICULAR PURPOSE. See the GNU GPL for more details.
  22. *
  23. * As additional permission under GNU GPL version 3 section 7, you
  24. * may distribute non-source (e.g., minimized or compacted) forms of
  25. * that code without the copy of the GNU GPL normally required by
  26. * section 4, provided you include this license notice and a URL
  27. * through which recipients can access the Corresponding Source.
  28. *
  29. * @licend The above is the entire license notice
  30. * for the JavaScript code in this file.
  31. *
  32. * @author Daniel Roesler (diafygi)
  33. */
  34. (function(context){
  35. /*
  36. Default keyservers (HTTPS and CORS enabled)
  37. */
  38. var DEFAULT_KEYSERVERS = [
  39. "https://keys.fedoraproject.org/",
  40. "https://keybase.io/"
  41. ];
  42. /*
  43. Initialization to create an PublicKey object.
  44. Arguments:
  45. * keyservers - Array of keyserver domains, default is:
  46. ["https://keys.fedoraproject.org/", "https://keybase.io/"]
  47. Examples:
  48. //Initialize with the default keyservers
  49. var hkp = new PublicKey();
  50. //Initialize only with a specific keyserver
  51. var hkp = new PublicKey(["https://key.ip6.li/"]);
  52. */
  53. var PublicKey = function(keyservers){
  54. this.keyservers = keyservers || DEFAULT_KEYSERVERS;
  55. };
  56. /*
  57. Get a public key from any keyserver based on keyId.
  58. Arguments:
  59. * keyId - String key id of the public key (this is usually a fingerprint)
  60. * callback - Function that is called when finished. Two arguments are
  61. passed to the callback: publicKey and errorCode. publicKey is
  62. an ASCII armored OpenPGP public key. errorCode is the error code
  63. (either HTTP status code or keybase error code) returned by the
  64. last keyserver that was tried. If a publicKey was found,
  65. errorCode is null. If no publicKey was found, publicKey is null
  66. and errorCode is not null.
  67. Examples:
  68. //Get a valid public key
  69. var hkp = new PublicKey();
  70. hkp.get("F75BE4E6EF6E9DD203679E94E7F6FAD172EFEE3D", function(publicKey, errorCode){
  71. errorCode !== null ? console.log(errorCode) : console.log(publicKey);
  72. });
  73. //Try to get an invalid public key
  74. var hkp = new PublicKey();
  75. hkp.get("bogus_id", function(publicKey, errorCode){
  76. errorCode !== null ? console.log(errorCode) : console.log(publicKey);
  77. });
  78. */
  79. PublicKey.prototype.get = function(keyId, callback, keyserverIndex, err){
  80. //default starting point is at the first keyserver
  81. if(keyserverIndex === undefined){
  82. keyserverIndex = 0;
  83. }
  84. //no more keyservers to check, so no key found
  85. if(keyserverIndex >= this.keyservers.length){
  86. return callback(null, err || 404);
  87. }
  88. //set the keyserver to try next
  89. var ks = this.keyservers[keyserverIndex];
  90. var _this = this;
  91. //special case for keybase
  92. if(ks.indexOf("https://keybase.io/") === 0){
  93. //don't need 0x prefix for keybase searches
  94. if(keyId.indexOf("0x") === 0){
  95. keyId = keyId.substr(2);
  96. }
  97. //request the public key from keybase
  98. var xhr = new XMLHttpRequest();
  99. xhr.open("get", "https://keybase.io/_/api/1.0/user/lookup.json" +
  100. "?fields=public_keys&key_fingerprint=" + keyId);
  101. xhr.onload = function(){
  102. if(xhr.status === 200){
  103. var result = JSON.parse(xhr.responseText);
  104. //keybase error returns HTTP 200 status, which is silly
  105. if(result['status']['code'] !== 0){
  106. return _this.get(keyId, callback, keyserverIndex + 1, result['status']['code']);
  107. }
  108. //no public key found
  109. if(result['them'].length === 0){
  110. return _this.get(keyId, callback, keyserverIndex + 1, 404);
  111. }
  112. //found the public key
  113. var publicKey = result['them'][0]['public_keys']['primary']['bundle'];
  114. return callback(publicKey, null);
  115. }
  116. else{
  117. return _this.get(keyId, callback, keyserverIndex + 1, xhr.status);
  118. }
  119. };
  120. xhr.send();
  121. }
  122. //normal HKP keyserver
  123. else{
  124. //add the 0x prefix if absent
  125. if(keyId.indexOf("0x") !== 0){
  126. keyId = "0x" + keyId;
  127. }
  128. //request the public key from the hkp server
  129. var xhr = new XMLHttpRequest();
  130. xhr.open("get", ks + "pks/lookup?op=get&options=mr&search=" + keyId);
  131. xhr.onload = function(){
  132. if(xhr.status === 200){
  133. return callback(xhr.responseText, null);
  134. }
  135. else{
  136. return _this.get(keyId, callback, keyserverIndex + 1, xhr.status);
  137. }
  138. };
  139. xhr.send();
  140. }
  141. };
  142. /*
  143. Search for a public key in the keyservers.
  144. Arguments:
  145. * query - String to search for (usually an email, name, or username).
  146. * callback - Function that is called when finished. Two arguments are
  147. passed to the callback: results and errorCode. results is an
  148. Array of users that were returned by the search. errorCode is
  149. the error code (either HTTP status code or keybase error code)
  150. returned by the last keyserver that was tried. If any results
  151. were found, errorCode is null. If no results are found, results
  152. is null and errorCode is not null.
  153. Examples:
  154. //Search for diafygi's key id
  155. var hkp = new PublicKey();
  156. hkp.search("diafygi", function(results, errorCode){
  157. errorCode !== null ? console.log(errorCode) : console.log(results);
  158. });
  159. //Search for a nonexistent key id
  160. var hkp = new PublicKey();
  161. hkp.search("doesntexist123", function(results, errorCode){
  162. errorCode !== null ? console.log(errorCode) : console.log(results);
  163. });
  164. */
  165. PublicKey.prototype.search = function(query, callback, keyserverIndex, results, err){
  166. //default starting point is at the first keyserver
  167. if(keyserverIndex === undefined){
  168. keyserverIndex = 0;
  169. }
  170. //initialize the results array
  171. if(results === undefined){
  172. results = [];
  173. }
  174. //no more keyservers to check
  175. if(keyserverIndex >= this.keyservers.length){
  176. //return error if no results
  177. if(results.length === 0){
  178. return callback(null, err || 404);
  179. }
  180. //return results
  181. else{
  182. //merge duplicates
  183. var merged = {};
  184. for(var i = 0; i < results.length; i++){
  185. var k = results[i];
  186. //see if there's duplicate key ids to merge
  187. if(merged[k['keyid']] !== undefined){
  188. for(var u = 0; u < k['uids'].length; u++){
  189. var has_this_uid = false;
  190. for(var m = 0; m < merged[k['keyid']]['uids'].length; m++){
  191. if(merged[k['keyid']]['uids'][m]['uid'] === k['uids'][u]){
  192. has_this_uid = true;
  193. break;
  194. }
  195. }
  196. if(!has_this_uid){
  197. merged[k['keyid']]['uids'].push(k['uids'][u])
  198. }
  199. }
  200. }
  201. //no duplicate found, so add it to the dict
  202. else{
  203. merged[k['keyid']] = k;
  204. }
  205. }
  206. //return a list of the merged results in the same order
  207. var merged_list = [];
  208. for(var i = 0; i < results.length; i++){
  209. var k = results[i];
  210. if(merged[k['keyid']] !== undefined){
  211. merged_list.push(merged[k['keyid']]);
  212. delete(merged[k['keyid']]);
  213. }
  214. }
  215. return callback(merged_list, null);
  216. }
  217. }
  218. //set the keyserver to try next
  219. var ks = this.keyservers[keyserverIndex];
  220. var _this = this;
  221. //special case for keybase
  222. if(ks.indexOf("https://keybase.io/") === 0){
  223. //request a list of users from keybase
  224. var xhr = new XMLHttpRequest();
  225. xhr.open("get", "https://keybase.io/_/api/1.0/user/autocomplete.json?q=" + encodeURIComponent(query));
  226. xhr.onload = function(){
  227. if(xhr.status === 200){
  228. var kb_json = JSON.parse(xhr.responseText);
  229. //keybase error returns HTTP 200 status, which is silly
  230. if(kb_json['status']['code'] !== 0){
  231. return _this.search(query, callback, keyserverIndex + 1, results, kb_json['status']['code']);
  232. }
  233. //no public key found
  234. if(kb_json['completions'].length === 0){
  235. return _this.search(query, callback, keyserverIndex + 1, results, 404);
  236. }
  237. //compose keybase user results
  238. var kb_results = [];
  239. for(var i = 0; i < kb_json['completions'].length; i++){
  240. var user = kb_json['completions'][i]['components'];
  241. //skip if no public key fingerprint
  242. if(user['key_fingerprint'] === undefined){
  243. continue;
  244. }
  245. //build keybase user result
  246. var kb_result = {
  247. "keyid": user['key_fingerprint']['val'].toUpperCase(),
  248. "href": "https://keybase.io/" + user['username']['val'] + "/key.asc",
  249. "info": "https://keybase.io/" + user['username']['val'],
  250. "algo": user['key_fingerprint']['algo'],
  251. "keylen": user['key_fingerprint']['nbits'],
  252. "creationdate": null,
  253. "expirationdate": null,
  254. "revoked": false,
  255. "disabled": false,
  256. "expired": false,
  257. "uids": [{
  258. "uid": user['username']['val'] +
  259. " on Keybase <https://keybase.io/" +
  260. user['username']['val'] + ">",
  261. "creationdate": null,
  262. "expirationdate": null,
  263. "revoked": false,
  264. "disabled": false,
  265. "expired": false
  266. }]
  267. };
  268. //add full name
  269. if(user['full_name'] !== undefined){
  270. kb_result['uids'].push({
  271. "uid": "Full Name: " + user['full_name']['val'],
  272. "creationdate": null,
  273. "expirationdate": null,
  274. "revoked": false,
  275. "disabled": false,
  276. "expired": false
  277. });
  278. }
  279. //add twitter
  280. if(user['twitter'] !== undefined){
  281. kb_result['uids'].push({
  282. "uid": user['twitter']['val'] +
  283. " on Twitter <https://twitter.com/" +
  284. user['twitter']['val'] + ">",
  285. "creationdate": null,
  286. "expirationdate": null,
  287. "revoked": false,
  288. "disabled": false,
  289. "expired": false
  290. });
  291. }
  292. //add github
  293. if(user['github'] !== undefined){
  294. kb_result['uids'].push({
  295. "uid": user['github']['val'] +
  296. " on Github <https://github.com/" +
  297. user['github']['val'] + ">",
  298. "creationdate": null,
  299. "expirationdate": null,
  300. "revoked": false,
  301. "disabled": false,
  302. "expired": false
  303. });
  304. }
  305. //add reddit
  306. if(user['reddit'] !== undefined){
  307. kb_result['uids'].push({
  308. "uid": user['reddit']['val'] +
  309. " on Github <https://reddit.com/u/" +
  310. user['reddit']['val'] + ">",
  311. "creationdate": null,
  312. "expirationdate": null,
  313. "revoked": false,
  314. "disabled": false,
  315. "expired": false
  316. });
  317. }
  318. //add hackernews
  319. if(user['hackernews'] !== undefined){
  320. kb_result['uids'].push({
  321. "uid": user['hackernews']['val'] +
  322. " on Hacker News <https://news.ycombinator.com/user?id=" +
  323. user['hackernews']['val'] + ">",
  324. "creationdate": null,
  325. "expirationdate": null,
  326. "revoked": false,
  327. "disabled": false,
  328. "expired": false
  329. });
  330. }
  331. //add coinbase
  332. if(user['coinbase'] !== undefined){
  333. kb_result['uids'].push({
  334. "uid": user['coinbase']['val'] +
  335. " on Coinbase <https://www.coinbase.com/" +
  336. user['coinbase']['val'] + ">",
  337. "creationdate": null,
  338. "expirationdate": null,
  339. "revoked": false,
  340. "disabled": false,
  341. "expired": false
  342. });
  343. }
  344. //add websites
  345. if(user['websites'] !== undefined){
  346. for(var w = 0; w < user['websites'].length; w++){
  347. kb_result['uids'].push({
  348. "uid": "Owns " + user['websites'][w]['val'],
  349. "creationdate": null,
  350. "expirationdate": null,
  351. "revoked": false,
  352. "disabled": false,
  353. "expired": false
  354. });
  355. }
  356. }
  357. kb_results.push(kb_result);
  358. }
  359. results = results.concat(kb_results);
  360. return _this.search(query, callback, keyserverIndex + 1, results, null);
  361. }
  362. else{
  363. return _this.search(query, callback, keyserverIndex + 1, results, xhr.status);
  364. }
  365. };
  366. xhr.send();
  367. }
  368. //normal HKP keyserver
  369. else{
  370. var xhr = new XMLHttpRequest();
  371. xhr.open("get", ks + "pks/lookup?op=index&options=mr&fingerprint=on&search=" + encodeURIComponent(query));
  372. xhr.onload = function(){
  373. if(xhr.status === 200){
  374. var ks_results = [];
  375. var raw = xhr.responseText.split("\n");
  376. var curKey = undefined;
  377. for(var i = 0; i < raw.length; i++){
  378. var line = raw[i].trim();
  379. //pub:<keyid>:<algo>:<keylen>:<creationdate>:<expirationdate>:<flags>
  380. if(line.indexOf("pub:") == 0){
  381. if(curKey !== undefined){
  382. ks_results.push(curKey);
  383. }
  384. var vals = line.split(":");
  385. curKey = {
  386. "keyid": vals[1],
  387. "href": ks + "pks/lookup?op=get&options=mr&search=0x" + vals[1],
  388. "info": ks + "pks/lookup?op=vindex&search=0x" + vals[1],
  389. "algo": vals[2] === "" ? null : parseInt(vals[2]),
  390. "keylen": vals[3] === "" ? null : parseInt(vals[3]),
  391. "creationdate": vals[4] === "" ? null : parseInt(vals[4]),
  392. "expirationdate": vals[5] === "" ? null : parseInt(vals[5]),
  393. "revoked": vals[6].indexOf("r") !== -1,
  394. "disabled": vals[6].indexOf("d") !== -1,
  395. "expired": vals[6].indexOf("e") !== -1,
  396. "uids": []
  397. }
  398. }
  399. //uid:<escaped uid string>:<creationdate>:<expirationdate>:<flags>
  400. if(line.indexOf("uid:") == 0){
  401. var vals = line.split(":");
  402. curKey['uids'].push({
  403. "uid": decodeURIComponent(vals[1]),
  404. "creationdate": vals[2] === "" ? null : parseInt(vals[2]),
  405. "expirationdate": vals[3] === "" ? null : parseInt(vals[3]),
  406. "revoked": vals[4].indexOf("r") !== -1,
  407. "disabled": vals[4].indexOf("d") !== -1,
  408. "expired": vals[4].indexOf("e") !== -1
  409. });
  410. }
  411. }
  412. ks_results.push(curKey);
  413. results = results.concat(ks_results);
  414. return _this.search(query, callback, keyserverIndex + 1, results, null);
  415. }
  416. else{
  417. return _this.search(query, callback, keyserverIndex + 1, results, xhr.status);
  418. }
  419. };
  420. xhr.send();
  421. }
  422. };
  423. context.PublicKey = PublicKey;
  424. })(typeof exports === "undefined" ? this : exports);