create.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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 = async function(setvalidity, options){
  199. const gunRoot = this.back(-1)
  200. let validity
  201. let opts
  202. var o = setvalidity;
  203. if(o && o.sessionStorage){
  204. if(typeof window !== 'undefined'){
  205. var tmp = window.sessionStorage;
  206. if(tmp){
  207. gunRoot._.opt.remember = true;
  208. if(tmp.alias && tmp.tmp){
  209. gunRoot.user().auth(tmp.alias, tmp.tmp);
  210. }
  211. }
  212. }
  213. return this;
  214. }
  215. if (!Gun.val.is(setvalidity)) {
  216. opts = setvalidity
  217. validity = _initial_authsettings.validity
  218. } else {
  219. opts = options
  220. validity = setvalidity * 60 // minutes to seconds
  221. }
  222. try {
  223. // opts = { hook: function({ iat, exp, alias, proof }) }
  224. // iat == Date.now() when issued, exp == seconds to expire from iat
  225. // How this works:
  226. // called when app bootstraps, with wanted options
  227. // IF authsettings.validity === 0 THEN no remember-me, ever
  228. // IF PIN then signed 'remember' to window.sessionStorage and 'auth' to IndexedDB
  229. authsettings.validity = typeof validity !== 'undefined'
  230. ? validity : _initial_authsettings.validity
  231. authsettings.hook = (Gun.obj.has(opts, 'hook') && typeof opts.hook === 'function')
  232. ? opts.hook : _initial_authsettings.hook
  233. // All is good. Should we do something more with actual recalled data?
  234. return await authRecall(gunRoot)
  235. } catch (e) {
  236. const err = 'No session!'
  237. Gun.log(err)
  238. // NOTE! It's fine to resolve recall with reason why not successful
  239. // instead of rejecting...
  240. return { err: (e && e.err) || err }
  241. }
  242. }
  243. User.prototype.alive = async function(){
  244. const gunRoot = this.back(-1)
  245. try {
  246. // All is good. Should we do something more with actual recalled data?
  247. await authRecall(gunRoot)
  248. return gunRoot._.user._
  249. } catch (e) {
  250. const err = 'No session!'
  251. Gun.log(err)
  252. throw { err }
  253. }
  254. }
  255. User.prototype.trust = async function(user){
  256. // TODO: BUG!!! SEA `node` read listener needs to be async, which means core needs to be async too.
  257. //gun.get('alice').get('age').trust(bob);
  258. if (Gun.is(user)) {
  259. user.get('pub').get((ctx, ev) => {
  260. console.log(ctx, ev)
  261. })
  262. }
  263. }
  264. User.prototype.grant = function(to, cb){
  265. console.log("`.grant` API MAY BE DELETED OR CHANGED OR RENAMED, DO NOT USE!");
  266. var gun = this, user = gun.back(-1).user(), pair = user.pair(), path = '';
  267. gun.back(function(at){ if(at.pub){ return } path += (at.get||'') });
  268. (async function(){
  269. var enc, sec = await user.get('trust').get(pair.pub).get(path).then();
  270. sec = await SEA.decrypt(sec, pair);
  271. if(!sec){
  272. sec = SEA.random(16).toString();
  273. enc = await SEA.encrypt(sec, pair);
  274. user.get('trust').get(pair.pub).get(path).put(enc);
  275. }
  276. var pub = to.get('pub').then();
  277. var epub = to.get('epub').then();
  278. pub = await pub; epub = await epub;
  279. var dh = await SEA.secret(epub, pair);
  280. enc = await SEA.encrypt(sec, dh);
  281. user.get('trust').get(pub).get(path).put(enc, cb);
  282. }());
  283. return gun;
  284. }
  285. User.prototype.secret = function(data, cb){
  286. console.log("`.secret` API MAY BE DELETED OR CHANGED OR RENAMED, DO NOT USE!");
  287. var gun = this, user = gun.back(-1).user(), pair = user.pair(), path = '';
  288. gun.back(function(at){ if(at.pub){ return } path += (at.get||'') });
  289. (async function(){
  290. var enc, sec = await user.get('trust').get(pair.pub).get(path).then();
  291. sec = await SEA.decrypt(sec, pair);
  292. if(!sec){
  293. sec = SEA.random(16).toString();
  294. enc = await SEA.encrypt(sec, pair);
  295. user.get('trust').get(pair.pub).get(path).put(enc);
  296. }
  297. enc = await SEA.encrypt(data, sec);
  298. gun.put(enc, cb);
  299. }());
  300. return gun;
  301. }
  302. module.exports = User