您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

publickey.js 20KB

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