create.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. // TODO: This needs to be split into all separate functions.
  2. // Not just everything thrown into 'create'.
  3. var SEA = require('./sea');
  4. var User = require('./user');
  5. var authsettings = require('./settings');
  6. var Gun = SEA.Gun;
  7. var noop = function(){};
  8. // Well first we have to actually create a user. That is what this function does.
  9. User.prototype.create = function(alias, pass, cb, opt){
  10. var gun = this, cat = (gun._), root = gun.back(-1);
  11. cb = cb || noop;
  12. if(cat.ing){
  13. cb({err: Gun.log("User is already being created or authenticated!"), wait: true});
  14. return gun;
  15. }
  16. cat.ing = true;
  17. opt = opt || {};
  18. var act = {}, u;
  19. act.a = function(pubs){
  20. act.pubs = pubs;
  21. if(pubs && !opt.already){
  22. // If we can enforce that a user name is already taken, it might be nice to try, but this is not guaranteed.
  23. var ack = {err: Gun.log('User already created!')};
  24. cat.ing = false;
  25. cb(ack);
  26. gun.leave();
  27. return;
  28. }
  29. act.salt = Gun.text.random(64); // pseudo-randomly create a salt, then use PBKDF2 function to extend the password with it.
  30. SEA.work(pass, act.salt, act.b); // this will take some short amount of time to produce a proof, which slows brute force attacks.
  31. }
  32. act.b = function(proof){
  33. act.proof = proof;
  34. SEA.pair(act.c); // now we have generated a brand new ECDSA key pair for the user account.
  35. }
  36. act.c = function(pair){ var tmp;
  37. act.pair = pair || {};
  38. if(tmp = cat.root.user){
  39. tmp._.sea = pair;
  40. tmp.is = {pub: pair.pub, epub: pair.epub, alias: alias};
  41. }
  42. // the user's public key doesn't need to be signed. But everything else needs to be signed with it! // we have now automated it! clean up these extra steps now!
  43. act.data = {pub: pair.pub};
  44. act.d();
  45. }
  46. act.d = function(){
  47. act.data.alias = alias;
  48. act.e();
  49. }
  50. act.e = function(){
  51. act.data.epub = act.pair.epub;
  52. SEA.encrypt({priv: act.pair.priv, epriv: act.pair.epriv}, act.proof, act.f, {raw:1}); // to keep the private key safe, we AES encrypt it with the proof of work!
  53. }
  54. act.f = function(auth){
  55. act.data.auth = JSON.stringify({ek: auth, s: act.salt});
  56. act.g(act.data.auth);
  57. }
  58. act.g = function(auth){ var tmp;
  59. act.data.auth = act.data.auth || auth;
  60. root.get(tmp = '~'+act.pair.pub).put(act.data); // awesome, now we can actually save the user with their public key as their ID.
  61. root.get('~@'+alias).put(Gun.obj.put({}, tmp, Gun.val.link.ify(tmp))); // next up, we want to associate the alias with the public key. So we add it to the alias list.
  62. setTimeout(function(){ // we should be able to delete this now, right?
  63. cat.ing = false;
  64. cb({ok: 0, pub: act.pair.pub}); // callback that the user has been created. (Note: ok = 0 because we didn't wait for disk to ack)
  65. if(noop === cb){ gun.auth(alias, pass) } // if no callback is passed, auto-login after signing up.
  66. },10);
  67. }
  68. root.get('~@'+alias).once(act.a);
  69. return gun;
  70. }
  71. // now that we have created a user, we want to authenticate them!
  72. User.prototype.auth = function(alias, pass, cb, opt){
  73. var gun = this, cat = (gun._), root = gun.back(-1);
  74. cb = cb || function(){};
  75. if(cat.ing){
  76. cb({err: Gun.log("User is already being created or authenticated!"), wait: true});
  77. return gun;
  78. }
  79. cat.ing = true;
  80. opt = opt || {};
  81. var pair = (alias && (alias.pub || alias.epub))? alias : (pass && (pass.pub || pass.epub))? pass : null;
  82. var act = {}, u;
  83. act.a = function(data){
  84. if(!data){ return act.b() }
  85. if(!data.pub){
  86. var tmp = [];
  87. Gun.node.is(data, function(v){ tmp.push(v) })
  88. return act.b(tmp);
  89. }
  90. if(act.name){ return act.f(data) }
  91. act.c((act.data = data).auth);
  92. }
  93. act.b = function(list){
  94. var get = (act.list = (act.list||[]).concat(list||[])).shift();
  95. if(u === get){
  96. if(act.name){ return act.err('Your user account is not published for dApps to access, please consider syncing it online, or allowing local access by adding your device as a peer.') }
  97. return act.err('Wrong user or password.')
  98. }
  99. root.get(get).once(act.a);
  100. }
  101. act.c = function(auth){
  102. if(u === auth){ return act.b() }
  103. if(Gun.text.is(auth)){ return act.c(Gun.obj.ify(auth)) } // in case of legacy
  104. SEA.work(pass, (act.auth = auth).s, act.d, act.enc); // the proof of work is evidence that we've spent some time/effort trying to log in, this slows brute force.
  105. }
  106. act.d = function(proof){
  107. SEA.decrypt(act.auth.ek, proof, act.e, act.enc);
  108. }
  109. act.e = function(half){
  110. if(u === half){
  111. if(!act.enc){ // try old format
  112. act.enc = {encode: 'utf8'};
  113. return act.c(act.auth);
  114. } act.enc = null; // end backwards
  115. return act.b();
  116. }
  117. act.half = half;
  118. act.f(act.data);
  119. }
  120. act.f = function(data){
  121. if(!data || !data.pub){ return act.b() }
  122. var tmp = act.half || {};
  123. act.g({pub: data.pub, epub: data.epub, priv: tmp.priv, epriv: tmp.epriv});
  124. }
  125. act.g = function(pair){
  126. act.pair = pair;
  127. var user = (root._).user, at = (user._);
  128. var tmp = at.tag;
  129. var upt = at.opt;
  130. at = user._ = root.get('~'+pair.pub)._;
  131. at.opt = upt;
  132. // add our credentials in-memory only to our root user instance
  133. user.is = {pub: pair.pub, epub: pair.epub, alias: alias};
  134. at.sea = act.pair;
  135. cat.ing = false;
  136. try{if(pass && !Gun.obj.has(Gun.obj.ify(cat.root.graph['~'+pair.pub].auth), ':')){ opt.shuffle = opt.change = pass; } }catch(e){} // migrate UTF8 & Shuffle!
  137. opt.change? act.z() : cb(at);
  138. if(SEA.window && ((gun.back('user')._).opt||opt).remember){
  139. // TODO: this needs to be modular.
  140. try{var sS = {};
  141. sS = window.sessionStorage;
  142. sS.recall = true;
  143. sS.alias = alias;
  144. sS.tmp = pass;
  145. }catch(e){}
  146. }
  147. try{
  148. (root._).on('auth', at) // TODO: Deprecate this, emit on user instead! Update docs when you do.
  149. //at.on('auth', at) // Arrgh, this doesn't work without event "merge" code, but "merge" code causes stack overflow and crashes after logging in & trying to write data.
  150. }catch(e){
  151. Gun.log("Your 'auth' callback crashed with:", e);
  152. }
  153. }
  154. act.z = function(){
  155. // password update so encrypt private key using new pwd + salt
  156. act.salt = Gun.text.random(64); // pseudo-random
  157. SEA.work(opt.change, act.salt, act.y);
  158. }
  159. act.y = function(proof){
  160. SEA.encrypt({priv: act.pair.priv, epriv: act.pair.epriv}, proof, act.x, {raw:1});
  161. }
  162. act.x = function(auth){
  163. act.w(JSON.stringify({ek: auth, s: act.salt}));
  164. }
  165. act.w = function(auth){
  166. if(opt.shuffle){ // delete in future!
  167. console.log('migrate core account from UTF8 & shuffle');
  168. var tmp = Gun.obj.to(act.data);
  169. Gun.obj.del(tmp, '_');
  170. tmp.auth = auth;
  171. root.get('~'+act.pair.pub).put(tmp);
  172. } // end delete
  173. root.get('~'+act.pair.pub).get('auth').put(auth, cb);
  174. }
  175. act.err = function(e){
  176. var ack = {err: Gun.log(e || 'User cannot be found!')};
  177. cat.ing = false;
  178. cb(ack);
  179. }
  180. act.plugin = function(name){
  181. if(!(act.name = name)){ return act.err() }
  182. var tmp = [name];
  183. if('~' !== name[0]){
  184. tmp[1] = '~'+name;
  185. tmp[2] = '~@'+name;
  186. }
  187. act.b(tmp);
  188. }
  189. if(pair){
  190. act.g(pair);
  191. } else
  192. if(alias){
  193. root.get('~@'+alias).once(act.a);
  194. } else
  195. if(!alias && !pass){
  196. SEA.name(act.plugin);
  197. }
  198. return gun;
  199. }
  200. User.prototype.pair = function(){
  201. console.log("user.pair() IS DEPRECATED AND WILL BE DELETED!!!");
  202. var user = this;
  203. if(!user.is){ return false }
  204. return user._.sea;
  205. }
  206. User.prototype.leave = function(opt, cb){
  207. var gun = this, user = (gun.back(-1)._).user;
  208. if(user){
  209. delete user.is;
  210. delete user._.is;
  211. delete user._.sea;
  212. }
  213. if(SEA.window){
  214. try{var sS = {};
  215. sS = window.sessionStorage;
  216. delete sS.alias;
  217. delete sS.tmp;
  218. delete sS.recall;
  219. }catch(e){};
  220. }
  221. return gun;
  222. }
  223. // If authenticated user wants to delete his/her account, let's support it!
  224. User.prototype.delete = async function(alias, pass, cb){
  225. var gun = this, root = gun.back(-1), user = gun.back('user');
  226. try {
  227. user.auth(alias, pass, function(ack){
  228. var pub = (user.is||{}).pub;
  229. // Delete user data
  230. user.map().once(function(){ this.put(null) });
  231. // Wipe user data from memory
  232. user.leave();
  233. (cb || noop)({ok: 0});
  234. });
  235. } catch (e) {
  236. Gun.log('User.delete failed! Error:', e);
  237. }
  238. return gun;
  239. }
  240. User.prototype.recall = function(opt, cb){
  241. var gun = this, root = gun.back(-1), tmp;
  242. opt = opt || {};
  243. if(opt && opt.sessionStorage){
  244. if(SEA.window){
  245. try{var sS = {};
  246. sS = window.sessionStorage;
  247. if(sS){
  248. (root._).opt.remember = true;
  249. ((gun.back('user')._).opt||opt).remember = true;
  250. if(sS.recall || (sS.alias && sS.tmp)){
  251. root.user().auth(sS.alias, sS.tmp, cb);
  252. }
  253. }
  254. }catch(e){}
  255. }
  256. return gun;
  257. }
  258. /*
  259. TODO: copy mhelander's expiry code back in.
  260. Although, we should check with community,
  261. should expiry be core or a plugin?
  262. */
  263. return gun;
  264. }
  265. User.prototype.alive = async function(){
  266. const gunRoot = this.back(-1)
  267. try {
  268. // All is good. Should we do something more with actual recalled data?
  269. await authRecall(gunRoot)
  270. return gunRoot._.user._
  271. } catch (e) {
  272. const err = 'No session!'
  273. Gun.log(err)
  274. throw { err }
  275. }
  276. }
  277. User.prototype.trust = async function(user){
  278. // TODO: BUG!!! SEA `node` read listener needs to be async, which means core needs to be async too.
  279. //gun.get('alice').get('age').trust(bob);
  280. if (Gun.is(user)) {
  281. user.get('pub').get((ctx, ev) => {
  282. console.log(ctx, ev)
  283. })
  284. }
  285. }
  286. User.prototype.grant = function(to, cb){
  287. console.log("`.grant` API MAY BE DELETED OR CHANGED OR RENAMED, DO NOT USE!");
  288. var gun = this, user = gun.back(-1).user(), pair = user.pair(), path = '';
  289. gun.back(function(at){ if(at.is){ return } path += (at.get||'') });
  290. (async function(){
  291. var enc, sec = await user.get('trust').get(pair.pub).get(path).then();
  292. sec = await SEA.decrypt(sec, pair);
  293. if(!sec){
  294. sec = SEA.random(16).toString();
  295. enc = await SEA.encrypt(sec, pair);
  296. user.get('trust').get(pair.pub).get(path).put(enc);
  297. }
  298. var pub = to.get('pub').then();
  299. var epub = to.get('epub').then();
  300. pub = await pub; epub = await epub;
  301. var dh = await SEA.secret(epub, pair);
  302. enc = await SEA.encrypt(sec, dh);
  303. user.get('trust').get(pub).get(path).put(enc, cb);
  304. }());
  305. return gun;
  306. }
  307. User.prototype.secret = function(data, cb){
  308. console.log("`.secret` API MAY BE DELETED OR CHANGED OR RENAMED, DO NOT USE!");
  309. var gun = this, user = gun.back(-1).user(), pair = user.pair(), path = '';
  310. gun.back(function(at){ if(at.is){ return } path += (at.get||'') });
  311. (async function(){
  312. var enc, sec = await user.get('trust').get(pair.pub).get(path).then();
  313. sec = await SEA.decrypt(sec, pair);
  314. if(!sec){
  315. sec = SEA.random(16).toString();
  316. enc = await SEA.encrypt(sec, pair);
  317. user.get('trust').get(pair.pub).get(path).put(enc);
  318. }
  319. enc = await SEA.encrypt(data, sec);
  320. gun.put(enc, cb);
  321. }());
  322. return gun;
  323. }
  324. module.exports = User