create.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. // TODO: This needs to be split into all separate functions.
  2. // Not just everything thrown into 'create'.
  3. const SEA = require('./sea')
  4. const User = require('./user')
  5. const authRecall = require('./recall')
  6. const authsettings = require('./settings')
  7. const authenticate = require('./authenticate')
  8. const finalizeLogin = require('./login')
  9. const authLeave = require('./leave')
  10. const _initial_authsettings = require('./settings').recall
  11. const Gun = SEA.Gun;
  12. var u;
  13. // Well first we have to actually create a user. That is what this function does.
  14. User.prototype.create = function(username, pass, cb, opt){
  15. // TODO: Needs to be cleaned up!!!
  16. const gunRoot = this.back(-1)
  17. var gun = this, cat = (gun._);
  18. cb = cb || function(){};
  19. if(cat.ing){
  20. cb({err: Gun.log("User is already being created or authenticated!"), wait: true});
  21. return gun;
  22. }
  23. cat.ing = true;
  24. opt = opt || {};
  25. var resolve = function(){}, reject = resolve;
  26. // Because more than 1 user might have the same username, we treat the alias as a list of those users.
  27. if(cb){ resolve = reject = cb }
  28. gunRoot.get('~@'+username).get(async (at, ev) => {
  29. ev.off()
  30. if (at.put && !opt.already) {
  31. // If we can enforce that a user name is already taken, it might be nice to try, but this is not guaranteed.
  32. const err = 'User already created!'
  33. Gun.log(err)
  34. cat.ing = false;
  35. gun.leave();
  36. return reject({ err: err })
  37. }
  38. const salt = Gun.text.random(64)
  39. // pseudo-randomly create a salt, then use CryptoJS's PBKDF2 function to extend the password with it.
  40. try {
  41. const proof = await SEA.work(pass, salt)
  42. // this will take some short amount of time to produce a proof, which slows brute force attacks.
  43. const pairs = await SEA.pair()
  44. // now we have generated a brand new ECDSA key pair for the user account.
  45. const pub = pairs.pub
  46. const priv = pairs.priv
  47. const epriv = pairs.epriv
  48. // the user's public key doesn't need to be signed. But everything else needs to be signed with it!
  49. const alias = await SEA.sign(username, pairs)
  50. if(u === alias){ throw SEA.err }
  51. const epub = await SEA.sign(pairs.epub, pairs)
  52. if(u === epub){ throw SEA.err }
  53. // to keep the private key safe, we AES encrypt it with the proof of work!
  54. const auth = await SEA.encrypt({ priv: priv, epriv: epriv }, proof)
  55. .then((auth) => // TODO: So signedsalt isn't needed?
  56. // SEA.sign(salt, pairs).then((signedsalt) =>
  57. SEA.sign({ek: auth, s: salt}, pairs)
  58. // )
  59. ).catch((e) => { Gun.log('SEA.en or SEA.write calls failed!'); cat.ing = false; gun.leave(); reject(e) })
  60. const user = { alias: alias, pub: pub, epub: epub, auth: auth }
  61. const tmp = '~'+pairs.pub;
  62. // awesome, now we can actually save the user with their public key as their ID.
  63. try{
  64. gunRoot.get(tmp).put(user)
  65. }catch(e){console.log(e)}
  66. // next up, we want to associate the alias with the public key. So we add it to the alias list.
  67. gunRoot.get('~@'+username).put(Gun.obj.put({}, tmp, Gun.val.link.ify(tmp)))
  68. // callback that the user has been created. (Note: ok = 0 because we didn't wait for disk to ack)
  69. setTimeout(() => { cat.ing = false; resolve({ ok: 0, pub: pairs.pub}) }, 10) // TODO: BUG! If `.auth` happens synchronously after `create` finishes, auth won't work. This setTimeout is a temporary hack until we can properly fix it.
  70. } catch (e) {
  71. Gun.log('SEA.create failed!')
  72. cat.ing = false;
  73. gun.leave();
  74. reject(e)
  75. }
  76. })
  77. return gun; // gun chain commands must return gun chains!
  78. }
  79. // now that we have created a user, we want to authenticate them!
  80. User.prototype.auth = function(alias, pass, cb, opt){
  81. // TODO: Needs to be cleaned up!!!!
  82. const opts = opt || (typeof cb !== 'function' && cb)
  83. let pin = opts && opts.pin
  84. let newpass = opts && opts.newpass
  85. const gunRoot = this.back(-1)
  86. cb = typeof cb === 'function' ? cb : () => {}
  87. newpass = newpass || (opts||{}).change;
  88. var gun = this, cat = (gun._);
  89. if(cat.ing){
  90. cb({err: "User is already being created or authenticated!", wait: true});
  91. return gun;
  92. }
  93. cat.ing = true;
  94. if (!pass && pin) { (async function(){
  95. try {
  96. var r = await authRecall(gunRoot, { alias: alias, pin: pin })
  97. return cat.ing = false, cb(r), gun;
  98. } catch (e) {
  99. var err = { err: 'Auth attempt failed! Reason: No session data for alias & PIN' }
  100. return cat.ing = false, gun.leave(), cb(err), gun;
  101. }}())
  102. return gun;
  103. }
  104. const putErr = (msg) => (e) => {
  105. const { message, err = message || '' } = e
  106. Gun.log(msg)
  107. var error = { err: msg+' Reason: '+err }
  108. return cat.ing = false, gun.leave(), cb(error), gun;
  109. }
  110. (async function(){ try {
  111. const keys = await authenticate(alias, pass, gunRoot)
  112. if (!keys) {
  113. return putErr('Auth attempt failed!')({ message: 'No keys' })
  114. }
  115. const pub = keys.pub
  116. const priv = keys.priv
  117. const epub = keys.epub
  118. const epriv = keys.epriv
  119. // we're logged in!
  120. if (newpass) {
  121. // password update so encrypt private key using new pwd + salt
  122. try {
  123. const salt = Gun.text.random(64);
  124. const encSigAuth = await SEA.work(newpass, salt)
  125. .then((key) =>
  126. SEA.encrypt({ priv: priv, epriv: epriv }, key)
  127. .then((auth) => SEA.sign({ek: auth, s: salt}, keys))
  128. )
  129. const signedEpub = await SEA.sign(epub, keys)
  130. const signedAlias = await SEA.sign(alias, keys)
  131. const user = {
  132. pub: pub,
  133. alias: signedAlias,
  134. auth: encSigAuth,
  135. epub: signedEpub
  136. }
  137. // awesome, now we can update the user using public key ID.
  138. gunRoot.get('~'+user.pub).put(user)
  139. // then we're done
  140. const login = finalizeLogin(alias, keys, gunRoot, { pin })
  141. login.catch(putErr('Failed to finalize login with new password!'))
  142. return cat.ing = false, cb(await login), gun
  143. } catch (e) {
  144. return putErr('Password set attempt failed!')(e)
  145. }
  146. } else {
  147. const login = finalizeLogin(alias, keys, gunRoot, { pin: pin })
  148. login.catch(putErr('Finalizing login failed!'))
  149. return cat.ing = false, cb(await login), gun;
  150. }
  151. } catch (e) {
  152. return putErr('Auth attempt failed!')(e)
  153. } }());
  154. return gun;
  155. }
  156. User.prototype.pair = function(){
  157. var user = this;
  158. if(!user.is){ return false }
  159. return user._.sea;
  160. }
  161. User.prototype.leave = async function(){
  162. var gun = this, user = (gun.back(-1)._).user;
  163. if(user){
  164. delete user.is;
  165. delete user._.is;
  166. delete user._.sea;
  167. }
  168. if(typeof window !== 'undefined'){
  169. var tmp = window.sessionStorage;
  170. delete tmp.alias;
  171. delete tmp.tmp;
  172. }
  173. return await authLeave(this.back(-1))
  174. }
  175. // If authenticated user wants to delete his/her account, let's support it!
  176. User.prototype.delete = async function(alias, pass){
  177. const gunRoot = this.back(-1)
  178. try {
  179. const __gky40 = await authenticate(alias, pass, gunRoot)
  180. const pub = __gky40.pub
  181. await authLeave(gunRoot, alias)
  182. // Delete user data
  183. gunRoot.get('~'+pub).put(null)
  184. // Wipe user data from memory
  185. const { user = { _: {} } } = gunRoot._;
  186. // TODO: is this correct way to 'logout' user from Gun.User ?
  187. [ 'alias', 'sea', 'pub' ].map((key) => delete user._[key])
  188. user._.is = user.is = {}
  189. gunRoot.user()
  190. return { ok: 0 } // TODO: proper return codes???
  191. } catch (e) {
  192. Gun.log('User.delete failed! Error:', e)
  193. throw e // TODO: proper error codes???
  194. }
  195. }
  196. // If authentication is to be remembered over reloads or browser closing,
  197. // set validity time in minutes.
  198. User.prototype.recall = function(setvalidity, options){
  199. var gun = this;
  200. const gunRoot = this.back(-1)
  201. let validity
  202. let opts
  203. var o = setvalidity;
  204. if(o && o.sessionStorage){
  205. if(typeof window !== 'undefined'){
  206. var tmp = window.sessionStorage;
  207. if(tmp){
  208. gunRoot._.opt.remember = true;
  209. if(tmp.alias && tmp.tmp){
  210. gunRoot.user().auth(tmp.alias, tmp.tmp);
  211. }
  212. }
  213. }
  214. return gun;
  215. }
  216. if (!Gun.val.is(setvalidity)) {
  217. opts = setvalidity
  218. validity = _initial_authsettings.validity
  219. } else {
  220. opts = options
  221. validity = setvalidity * 60 // minutes to seconds
  222. }
  223. try {
  224. // opts = { hook: function({ iat, exp, alias, proof }) }
  225. // iat == Date.now() when issued, exp == seconds to expire from iat
  226. // How this works:
  227. // called when app bootstraps, with wanted options
  228. // IF authsettings.validity === 0 THEN no remember-me, ever
  229. // IF PIN then signed 'remember' to window.sessionStorage and 'auth' to IndexedDB
  230. authsettings.validity = typeof validity !== 'undefined'
  231. ? validity : _initial_authsettings.validity
  232. authsettings.hook = (Gun.obj.has(opts, 'hook') && typeof opts.hook === 'function')
  233. ? opts.hook : _initial_authsettings.hook
  234. // All is good. Should we do something more with actual recalled data?
  235. (async function(){ await authRecall(gunRoot) }());
  236. return gun;
  237. } catch (e) {
  238. const err = 'No session!'
  239. Gun.log(err)
  240. // NOTE! It's fine to resolve recall with reason why not successful
  241. // instead of rejecting...
  242. //return { err: (e && e.err) || err }
  243. return gun;
  244. }
  245. }
  246. User.prototype.alive = async function(){
  247. const gunRoot = this.back(-1)
  248. try {
  249. // All is good. Should we do something more with actual recalled data?
  250. await authRecall(gunRoot)
  251. return gunRoot._.user._
  252. } catch (e) {
  253. const err = 'No session!'
  254. Gun.log(err)
  255. throw { err }
  256. }
  257. }
  258. User.prototype.trust = async function(user){
  259. // TODO: BUG!!! SEA `node` read listener needs to be async, which means core needs to be async too.
  260. //gun.get('alice').get('age').trust(bob);
  261. if (Gun.is(user)) {
  262. user.get('pub').get((ctx, ev) => {
  263. console.log(ctx, ev)
  264. })
  265. }
  266. }
  267. User.prototype.grant = function(to, cb){
  268. console.log("`.grant` API MAY BE DELETED OR CHANGED OR RENAMED, DO NOT USE!");
  269. var gun = this, user = gun.back(-1).user(), pair = user.pair(), path = '';
  270. gun.back(function(at){ if(at.pub){ return } path += (at.get||'') });
  271. (async function(){
  272. var enc, sec = await user.get('trust').get(pair.pub).get(path).then();
  273. sec = await SEA.decrypt(sec, pair);
  274. if(!sec){
  275. sec = SEA.random(16).toString();
  276. enc = await SEA.encrypt(sec, pair);
  277. user.get('trust').get(pair.pub).get(path).put(enc);
  278. }
  279. var pub = to.get('pub').then();
  280. var epub = to.get('epub').then();
  281. pub = await pub; epub = await epub;
  282. var dh = await SEA.secret(epub, pair);
  283. enc = await SEA.encrypt(sec, dh);
  284. user.get('trust').get(pub).get(path).put(enc, cb);
  285. }());
  286. return gun;
  287. }
  288. User.prototype.secret = function(data, cb){
  289. console.log("`.secret` API MAY BE DELETED OR CHANGED OR RENAMED, DO NOT USE!");
  290. var gun = this, user = gun.back(-1).user(), pair = user.pair(), path = '';
  291. gun.back(function(at){ if(at.pub){ return } path += (at.get||'') });
  292. (async function(){
  293. var enc, sec = await user.get('trust').get(pair.pub).get(path).then();
  294. sec = await SEA.decrypt(sec, pair);
  295. if(!sec){
  296. sec = SEA.random(16).toString();
  297. enc = await SEA.encrypt(sec, pair);
  298. user.get('trust').get(pair.pub).get(path).put(enc);
  299. }
  300. enc = await SEA.encrypt(data, sec);
  301. gun.put(enc, cb);
  302. }());
  303. return gun;
  304. }
  305. module.exports = User