Fixed some bugs & refactored SEA

This commit is contained in:
mhelander 2018-02-10 16:29:29 +02:00
parent 6ac4216fef
commit 5cdffa104d
2 changed files with 177 additions and 174 deletions

2
gun.min.js vendored

File diff suppressed because one or more lines are too long

349
sea.js
View File

@ -7,11 +7,10 @@
;(function(){ // eslint-disable-line no-extra-semi ;(function(){ // eslint-disable-line no-extra-semi
/* UNBUILD */ /* UNBUILD */
var root; const runtimeRoot = typeof window !== 'undefined' ? window
if(typeof window !== "undefined"){ root = window } : typeof global !== 'undefined' ? global
if(typeof global !== "undefined"){ root = global } : {}
root = root || {}; const console = runtimeRoot.console || { log() {} }
var console = root.console || {log: function(){}};
function USE(arg){ function USE(arg){
return arg.slice? USE[R(arg)] : function(mod, path){ return arg.slice? USE[R(arg)] : function(mod, path){
arg(mod = {exports: {}}); arg(mod = {exports: {}});
@ -32,7 +31,7 @@
// NECESSARY PRE-REQUISITE: http://gun.js.org/explainers/data/security.html // NECESSARY PRE-REQUISITE: http://gun.js.org/explainers/data/security.html
/* THIS IS AN EARLY ALPHA!!! */ /* THIS IS AN EARLY ALPHA!!! */
if(typeof window !== 'undefined'){ if(typeof window !== 'undefined'){
if(location.protocol.indexOf('s') < 0 if(location.protocol.indexOf('s') < 0
&& location.host.indexOf('localhost') < 0 && location.host.indexOf('localhost') < 0
@ -148,29 +147,37 @@
})(USE, './buffer'); })(USE, './buffer');
;USE(function(module){ ;USE(function(module){
const Buffer = USE('./buffer')
let subtle const api = {}
let subtleossl
let getRandomBytes
let crypto
var Buffer = USE('./buffer');
var wc;
var api = {};
if (typeof __webpack_require__ === 'function' || typeof window !== 'undefined') { if (typeof __webpack_require__ === 'function' || typeof window !== 'undefined') {
api.crypto = wc = window.crypto || window.msCrypto // STD or M$ const { msCrypto, crypto = msCrypto } = window // STD or M$
api.subtle = subtle = wc.subtle || wc.webkitSubtle // STD or iSafari const { webkitSubtle, subtle = webkitSubtle } = crypto // STD or iSafari
api.random = getRandomBytes = (len) => Buffer.from(wc.getRandomValues(new Uint8Array(Buffer.alloc(len)))) const { TextEncoder, TextDecoder } = window
Object.assign(api, {
crypto,
subtle,
TextEncoder,
TextDecoder,
random: (len) => Buffer.from(crypto.getRandomValues(new Uint8Array(Buffer.alloc(len))))
})
} else { } else {
api.crypto = crypto = require('crypto') const crypto = require('crypto')
const WebCrypto = require('node-webcrypto-ossl') const WebCrypto = require('node-webcrypto-ossl')
const webcrypto = new WebCrypto({directory: 'key_storage'}) const { subtle: ossl } = new WebCrypto({directory: 'key_storage'}) // ECDH
api.ossl = subtleossl = webcrypto.subtle const { subtle } = require('@trust/webcrypto') // All but ECDH
api.subtle = subtle = require('@trust/webcrypto').subtle // All but ECDH const { TextEncoder, TextDecoder } = require('text-encoding')
api.random = getRandomBytes = (len) => Buffer.from(crypto.randomBytes(len)) Object.assign(api, {
crypto,
subtle,
ossl,
TextEncoder,
TextDecoder,
random: (len) => Buffer.from(crypto.randomBytes(len))
})
} }
module.exports = api; module.exports = api
})(USE, './webcrypto'); })(USE, './webcrypto');
;USE(function(module){ ;USE(function(module){
@ -230,16 +237,15 @@
indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB
} else { } else {
funcsSetter = () => { funcsSetter = () => {
const { TextEncoder, TextDecoder } = require('text-encoding')
// Let's have Storage for NodeJS / testing // Let's have Storage for NodeJS / testing
const sessionStorage = new require('node-localstorage').LocalStorage('.sessionStorage') const sessionStorage = new require('node-localstorage').LocalStorage('.sessionStorage')
const localStorage = new require('node-localstorage').LocalStorage('.localStorage') const localStorage = new require('node-localstorage').LocalStorage('.localStorage')
return { TextEncoder, TextDecoder, sessionStorage, localStorage } return { sessionStorage, localStorage }
} }
indexedDB = require('fake-indexeddb') indexedDB = require('fake-indexeddb')
} }
const { TextEncoder, TextDecoder, sessionStorage, localStorage } = funcsSetter() const { sessionStorage, localStorage } = funcsSetter()
if (typeof __webpack_require__ !== 'function' && typeof global !== 'undefined') { if (typeof __webpack_require__ !== 'function' && typeof global !== 'undefined') {
global.sessionStorage = sessionStorage global.sessionStorage = sessionStorage
@ -253,10 +259,10 @@
})(USE, './indexed'); })(USE, './indexed');
;USE(function(module){ ;USE(function(module){
var Buffer = USE('./buffer'); const Buffer = USE('./buffer')
var settings = {}; const settings = {}
// Encryption parameters // Encryption parameters
const pbKdf2 = { hash: 'SHA-256', iter: 50000, ks: 64 } const pbkdf2 = { hash: 'SHA-256', iter: 50000, ks: 64 }
const ecdsaSignProps = { name: 'ECDSA', hash: { name: 'SHA-256' } } const ecdsaSignProps = { name: 'ECDSA', hash: { name: 'SHA-256' } }
const ecdsaKeyProps = { name: 'ECDSA', namedCurve: 'P-256' } const ecdsaKeyProps = { name: 'ECDSA', namedCurve: 'P-256' }
@ -279,14 +285,17 @@
] ]
} }
settings.pbkdf2 = pbKdf2; Object.assign(settings, {
settings.ecdsa = {}; pbkdf2,
settings.ecdsa.pair = ecdsaKeyProps; ecdsa: {
settings.ecdsa.sign = ecdsaSignProps; pair: ecdsaKeyProps,
settings.ecdh = ecdhKeyProps; sign: ecdsaSignProps
settings.jwk = keysToEcdsaJwk; },
settings.recall = authsettings; ecdh: ecdhKeyProps,
module.exports = settings; jwk: keysToEcdsaJwk,
recall: authsettings
})
module.exports = settings
})(USE, './settings'); })(USE, './settings');
;USE(function(module){ ;USE(function(module){
@ -296,41 +305,38 @@
} catch (e) {} //eslint-disable-line no-empty } catch (e) {} //eslint-disable-line no-empty
return props return props
} }
module.exports = parseProps; module.exports = parseProps
})(USE, './parse'); })(USE, './parse');
;USE(function(module){ ;USE(function(module){
var wc = USE('./webcrypto'); const {
var subtle = wc.subtle; subtle, ossl = subtle, random: getRandomBytes, TextEncoder, TextDecoder
var getRandomBytes = wc.random; } = USE('./webcrypto')
var Buffer = USE('./buffer'); const Buffer = USE('./buffer')
var parseProps = USE('./parse'); const parseProps = USE('./parse')
var settings = USE('./settings'); const { pbkdf2 } = USE('./settings')
var pbKdf2 = settings.pbkdf2;
// This internal func returns SHA-256 hashed data for signing // This internal func returns SHA-256 hashed data for signing
const sha256hash = async (mm) => { const sha256hash = async (mm) => {
const hashSubtle = wc.ossl || subtle
const m = parseProps(mm) const m = parseProps(mm)
const hash = await hashSubtle.digest(pbKdf2.hash, new TextEncoder().encode(m)) const hash = await ossl.digest(pbkdf2.hash, new TextEncoder().encode(m))
return Buffer.from(hash) return Buffer.from(hash)
} }
module.exports = sha256hash; module.exports = sha256hash
})(USE, './sha256'); })(USE, './sha256');
;USE(function(module){ ;USE(function(module){
// This internal func returns SHA-1 hashed data for KeyID generation // This internal func returns SHA-1 hashed data for KeyID generation
const sha1hash = (b) => (subtleossl || subtle).digest('SHA-1', new ArrayBuffer(b)) const { ossl = subtle } = USE('./webcrypto')
module.exports = sha1hash; const sha1hash = (b) => ossl.digest('SHA-1', new ArrayBuffer(b))
module.exports = sha1hash
})(USE, './sha1'); })(USE, './sha1');
;USE(function(module){ ;USE(function(module){
var Buffer = USE('./buffer'); const Buffer = USE('./buffer')
var sha256hash = USE('./sha256'); const sha256hash = USE('./sha256')
var wc = USE('./webcrypto'); const { subtle } = USE('./webcrypto')
var subtle = wc.subtle; const { scope: seaIndexedDb } = USE('./indexed')
var seaIndexedDb = USE('./indexed').scope; const { recall: authsettings } = USE('./settings')
var settings = USE('./settings');
var authsettings = settings.recall;
const makeKey = async (p, s) => { const makeKey = async (p, s) => {
const ps = Buffer.concat([Buffer.from(p, 'utf8'), s]).toString('utf8') const ps = Buffer.concat([Buffer.from(p, 'utf8'), s]).toString('utf8')
return Buffer.from(await sha256hash(ps), 'binary') return Buffer.from(await sha256hash(ps), 'binary')
@ -367,35 +373,41 @@
// No secure store usage // No secure store usage
return importKey(p) return importKey(p)
} }
module.exports = recallCryptoKey; module.exports = recallCryptoKey
})(USE, './remember'); })(USE, './remember');
;USE(function(module){ ;USE(function(module){
const Gun = (typeof window !== 'undefined' ? window : global).Gun || USE('gun/gun') const Gun = (typeof window !== 'undefined' ? window : global).Gun || USE('gun/gun')
var wc = USE('./webcrypto'); const {
var subtle = wc.subtle; crypto,
var getRandomBytes = wc.random; subtle,
var EasyIndexedDB = USE('./indexed'); ossl,
var SafeBuffer = USE('./buffer'); random: getRandomBytes,
var Buffer = SafeBuffer; TextEncoder,
TextDecoder
} = USE('./webcrypto')
const EasyIndexedDB = USE('./indexed')
const Buffer = USE('./buffer')
var settings = USE('./settings'); var settings = USE('./settings');
var pbKdf2 = settings.pbkdf2; const {
var ecdsaKeyProps = settings.ecdsa.pair; pbkdf2: pbKdf2,
var ecdhKeyProps = settings.ecdh; ecdsa: { pair: ecdsaKeyProps, sign: ecdsaSignProps },
var keysToEcdsaJwk = settings.jwk; ecdh: ecdhKeyProps,
var ecdsaSignProps = settings.ecdsa.sign; jwk: keysToEcdsaJwk
var sha256hash = USE('./sha256'); } = USE('./settings')
var recallCryptoKey = USE('./remember'); const sha1hash = USE('./sha1')
var parseProps = USE('./parse'); const sha256hash = USE('./sha256')
const recallCryptoKey = USE('./remember')
const parseProps = USE('./parse')
// Practical examples about usage found from ./test/common.js // Practical examples about usage found from ./test/common.js
const SEA = { const SEA = {
// This is easy way to use IndexedDB, all methods are Promises // This is easy way to use IndexedDB, all methods are Promises
indexedDB: EasyIndexedDB, // Note: Not all SEA interfaces have to support this. EasyIndexedDB, // Note: Not all SEA interfaces have to support this.
// This is Buffer used in SEA and usable from Gun/SEA application also. // This is Buffer used in SEA and usable from Gun/SEA application also.
// For documentation see https://nodejs.org/api/buffer.html // For documentation see https://nodejs.org/api/buffer.html
Buffer: SafeBuffer, Buffer,
random: getRandomBytes, random: getRandomBytes,
// These SEA functions support now ony Promises or // These SEA functions support now ony Promises or
// async/await (compatible) code, use those like Promises. // async/await (compatible) code, use those like Promises.
@ -455,7 +467,7 @@
}, },
async pair() { async pair() {
try { try {
const ecdhSubtle = wc.ossl || subtle const ecdhSubtle = ossl || subtle
// First: ECDSA keys for signing/verifying... // First: ECDSA keys for signing/verifying...
const { pub, priv } = await subtle.generateKey(ecdsaKeyProps, true, [ 'sign', 'verify' ]) const { pub, priv } = await subtle.generateKey(ecdsaKeyProps, true, [ 'sign', 'verify' ])
.then(async ({ publicKey, privateKey }) => { .then(async ({ publicKey, privateKey }) => {
@ -485,7 +497,7 @@
// Derive shared secret from other's pub and my epub/epriv // Derive shared secret from other's pub and my epub/epriv
async derive(pub, { epub, epriv }) { async derive(pub, { epub, epriv }) {
try { try {
const { importKey, deriveKey, exportKey } = subtleossl || subtle const { importKey, deriveKey, exportKey } = ossl
const keystoecdhjwk = (pub, priv) => { const keystoecdhjwk = (pub, priv) => {
const [ x, y ] = Buffer.from(pub, 'base64').toString('utf8').split(':') const [ x, y ] = Buffer.from(pub, 'base64').toString('utf8').split(':')
const jwk = priv ? { d: priv, key_ops: ['decrypt'] } : { key_ops: ['encrypt'] } const jwk = priv ? { d: priv, key_ops: ['decrypt'] } : { key_ops: ['encrypt'] }
@ -623,7 +635,7 @@
// const SEA = gun.SEA() // const SEA = gun.SEA()
//Gun.SEA = () => SEA //Gun.SEA = () => SEA
Gun.SEA = SEA Gun.SEA = SEA
// all done! // all done!
// Obviously it is missing MANY necessary features. This is only an alpha release. // Obviously it is missing MANY necessary features. This is only an alpha release.
// Please experiment with it, audit what I've done so far, and complain about what needs to be added. // Please experiment with it, audit what I've done so far, and complain about what needs to be added.
@ -642,9 +654,9 @@
;USE(function(module){ ;USE(function(module){
const Gun = (typeof window !== 'undefined' ? window : global).Gun || USE('gun/gun') const Gun = (typeof window !== 'undefined' ? window : global).Gun || USE('gun/gun')
// This is internal func queries public key(s) for alias. // This is internal func queries public key(s) for alias.
const queryGunAliases = (alias, root) => new Promise((resolve, reject) => { const queryGunAliases = (alias, gunRoot) => new Promise((resolve, reject) => {
// load all public keys associated with the username alias we want to log in with. // load all public keys associated with the username alias we want to log in with.
root.get(`alias/${alias}`).get((rat, rev) => { gunRoot.get(`alias/${alias}`).get((rat, rev) => {
rev.off() rev.off()
if (!rat.put) { if (!rat.put) {
// if no user, don't do anything. // if no user, don't do anything.
@ -653,46 +665,39 @@
return reject({ err }) return reject({ err })
} }
// then figuring out all possible candidates having matching username // then figuring out all possible candidates having matching username
let aliases = [] const aliases = []
let c = 0
// TODO: how about having real chainable map without callback ? // TODO: how about having real chainable map without callback ?
Gun.obj.map(rat.put, (at, pub) => { Gun.obj.map(rat.put, (at, pub) => {
if (!pub.slice || 'pub/' !== pub.slice(0, 4)) { if (!pub.slice || 'pub/' !== pub.slice(0, 4)) {
// TODO: ... this would then be .filter((at, pub)) // TODO: ... this would then be .filter((at, pub))
return return
} }
++c
// grab the account associated with this public key. // grab the account associated with this public key.
root.get(pub).get((at, ev) => { gunRoot.get(pub).get((at, ev) => {
pub = pub.slice(4) pub = pub.slice(4)
ev.off() ev.off()
--c
if (at.put){ if (at.put){
aliases.push({ pub, at }) aliases.push({ pub, at })
} }
if (!c && (c = -1)) {
resolve(aliases)
}
}) })
}) })
if (!c) { return !aliases.length ? reject({ err: 'Public key does not exist!' })
reject({ err: 'Public key does not exist!' }) : resolve(aliases)
}
}) })
}) })
module.exports = queryGunAliases; module.exports = queryGunAliases
})(USE, './query'); })(USE, './query');
;USE(function(module){ ;USE(function(module){
// TODO: BUG! `SEA` needs to be USED! // TODO: BUG! `SEA` needs to be USED!
const Gun = (typeof window !== 'undefined' ? window : global).Gun || USE('gun/gun') const Gun = (typeof window !== 'undefined' ? window : global).Gun || USE('gun/gun')
var SEA = USE('./sea'); const SEA = USE('./sea');
var queryGunAliases = USE('./query'); const queryGunAliases = USE('./query')
var parseProps = USE('./parse'); const parseProps = USE('./parse')
// This is internal User authentication func. // This is internal User authentication func.
const authenticate = async (alias, pass, root) => { const authenticate = async (alias, pass, gunRoot) => {
// load all public keys associated with the username alias we want to log in with. // load all public keys associated with the username alias we want to log in with.
const aliases = (await queryGunAliases(alias, root)) const aliases = (await queryGunAliases(alias, gunRoot))
.filter(({ pub, at: { put } = {} } = {}) => !!pub && !!put) .filter(({ pub, at: { put } = {} } = {}) => !!pub && !!put)
// Got any? // Got any?
if (!aliases.length) { if (!aliases.length) {
@ -743,8 +748,8 @@
;USE(function(module){ ;USE(function(module){
// TODO: BUG! `SEA` needs to be USED! // TODO: BUG! `SEA` needs to be USED!
const Gun = (typeof window !== 'undefined' ? window : global).Gun || USE('gun/gun') const Gun = (typeof window !== 'undefined' ? window : global).Gun || USE('gun/gun')
var authsettings = USE('./settings'); const authsettings = USE('./settings')
var seaIndexedDb = USE('./indexed').scope; const { scope: seaIndexedDb } = USE('./indexed')
// This updates sessionStorage & IndexedDB to persist authenticated "session" // This updates sessionStorage & IndexedDB to persist authenticated "session"
const updateStorage = (proof, key, pin) => async (props) => { const updateStorage = (proof, key, pin) => async (props) => {
if (!Gun.obj.has(props, 'alias')) { if (!Gun.obj.has(props, 'alias')) {
@ -785,14 +790,14 @@
return props return props
} }
module.exports = updateStorage; module.exports = updateStorage
})(USE, './update'); })(USE, './update');
;USE(function(module){ ;USE(function(module){
const Gun = (typeof window !== 'undefined' ? window : global).Gun || USE('gun/gun') const Gun = (typeof window !== 'undefined' ? window : global).Gun || USE('gun/gun')
var Buffer = USE('./buffer'); const Buffer = USE('./buffer')
var authsettings = USE('./settings'); const authsettings = USE('./settings')
var updateStorage = USE('./update'); const updateStorage = USE('./update')
// This internal func persists User authentication if so configured // This internal func persists User authentication if so configured
const authPersist = async (user, proof, opts) => { const authPersist = async (user, proof, opts) => {
// opts = { pin: 'string' } // opts = { pin: 'string' }
@ -823,14 +828,14 @@
} }
return await updateStorage()({ alias: 'delete' }) return await updateStorage()({ alias: 'delete' })
} }
module.exports = authPersist; module.exports = authPersist
})(USE, './persist'); })(USE, './persist');
;USE(function(module){ ;USE(function(module){
var authPersist = USE('./persist'); const authPersist = USE('./persist')
// This internal func finalizes User authentication // This internal func finalizes User authentication
const finalizeLogin = async (alias, key, root, opts) => { const finalizeLogin = async (alias, key, gunRoot, opts) => {
const { user } = root._ const { user } = gunRoot._
// add our credentials in-memory only to our root gun instance // add our credentials in-memory only to our root gun instance
user._ = key.at.gun._ user._ = key.at.gun._
// so that way we can use the credentials to encrypt/decrypt data // so that way we can use the credentials to encrypt/decrypt data
@ -843,27 +848,29 @@
await authPersist(user._, key.proof, opts) await authPersist(user._, key.proof, opts)
// emit an auth event, useful for page redirects and stuff. // emit an auth event, useful for page redirects and stuff.
try { try {
root._.on('auth', user._) gunRoot._.on('auth', user._)
} catch (e) { } catch (e) {
console.log('Your \'auth\' callback crashed with:', e) console.log('Your \'auth\' callback crashed with:', e)
} }
// returns success with the user data credentials. // returns success with the user data credentials.
return user._ return user._
} }
module.exports = finalizeLogin; module.exports = finalizeLogin
})(USE, './login'); })(USE, './login');
;USE(function(module){ ;USE(function(module){
// TODO: BUG! `SEA` needs to be USED! // TODO: BUG! `SEA` needs to be USEd!
const Gun = (typeof window !== 'undefined' ? window : global).Gun || USE('gun/gun') const Gun = (typeof window !== 'undefined' ? window : global).Gun || USE('gun/gun')
var Buffer = USE('./buffer');
var authsettings = USE('./settings'); const Buffer = USE('./buffer')
var seaIndexedDb = USE('./indexed').scope; const authsettings = USE('./settings')
var queryGunAliases = USE('./query'); const { scope: seaIndexedDb } = USE('./indexed')
var parseProps = USE('./parse'); const queryGunAliases = USE('./query')
var updateStorage = USE('./update'); const parseProps = USE('./parse')
const updateStorage = USE('./update')
// This internal func recalls persisted User authentication if so configured // This internal func recalls persisted User authentication if so configured
const authRecall = async (root, authprops) => { const authRecall = async (gunRoot, authprops) => {
// window.sessionStorage only holds signed { alias, pin } !!! // window.sessionStorage only holds signed { alias, pin } !!!
const remember = authprops || sessionStorage.getItem('remember') const remember = authprops || sessionStorage.getItem('remember')
const { alias = sessionStorage.getItem('user'), pin: pIn } = authprops || {} // @mhelander what is pIn? const { alias = sessionStorage.getItem('user'), pin: pIn } = authprops || {} // @mhelander what is pIn?
@ -889,10 +896,10 @@
parseProps(await SEA.dec(await SEA.read(data, pub), key)) parseProps(await SEA.dec(await SEA.read(data, pub), key))
// Already authenticated? // Already authenticated?
if (root._.user if (gunRoot._.user
&& Gun.obj.has(root._.user._, 'pub') && Gun.obj.has(gunRoot._.user._, 'pub')
&& Gun.obj.has(root._.user._, 'sea')) { && Gun.obj.has(gunRoot._.user._, 'sea')) {
return root._.user._ // Yes, we're done here. return gunRoot._.user._ // Yes, we're done here.
} }
// No, got persisted 'alias'? // No, got persisted 'alias'?
if (!alias) { if (!alias) {
@ -906,7 +913,7 @@
} }
} }
// Yes, let's get (all?) matching aliases // Yes, let's get (all?) matching aliases
const aliases = (await queryGunAliases(alias, root)) const aliases = (await queryGunAliases(alias, gunRoot))
.filter(({ pub } = {}) => !!pub) .filter(({ pub } = {}) => !!pub)
// Got any? // Got any?
if (!aliases.length) { if (!aliases.length) {
@ -979,53 +986,53 @@
const pinProp = pIN && { pin: Buffer.from(pIN, 'base64').toString('utf8') } const pinProp = pIN && { pin: Buffer.from(pIN, 'base64').toString('utf8') }
return await finalizeLogin(alias, user, root, pinProp) return await finalizeLogin(alias, user, gunRoot, pinProp)
} catch (e) { // TODO: right log message ? } catch (e) { // TODO: right log message ?
Gun.log('Failed to finalize login with new password!') Gun.log('Failed to finalize login with new password!')
const { err = '' } = e || {} const { err = '' } = e || {}
throw { err: `Finalizing new password login failed! Reason: ${err}` } throw { err: `Finalizing new password login failed! Reason: ${err}` }
} }
} }
module.exports = authRecall; module.exports = authRecall
})(USE, './recall'); })(USE, './recall');
;USE(function(module){ ;USE(function(module){
var authPersist = USE('./persist'); const authPersist = USE('./persist')
var authsettings = USE('./settings'); const authsettings = USE('./settings')
var seaIndexedDb = USE('./indexed').scope; const { scope: seaIndexedDb } = USE('./indexed')
var seaIndexedDb = USE('./indexed').scope;
// This internal func executes logout actions // This internal func executes logout actions
const authLeave = async (root, alias = root._.user._.alias) => { const authLeave = async (gunRoot, alias = gunRoot._.user._.alias) => {
var user = root._.user._ || {}; var user = gunRoot._.user._ || {};
[ 'get', 'soul', 'ack', 'put', 'is', 'alias', 'pub', 'epub', 'sea' ].map((key) => delete user[key]) [ 'get', 'soul', 'ack', 'put', 'is', 'alias', 'pub', 'epub', 'sea' ].map((key) => delete user[key])
if(user.gun){ if(user.gun){
delete user.gun.is; delete user.gun.is;
} }
// Let's use default // Let's use default
root.user(); gunRoot.user();
// Removes persisted authentication & CryptoKeys // Removes persisted authentication & CryptoKeys
try { try {
await authPersist({ alias }) await authPersist({ alias })
} catch (e) {} //eslint-disable-line no-empty } catch (e) {} //eslint-disable-line no-empty
return { ok: 0 } return { ok: 0 }
} }
module.exports = authLeave; module.exports = authLeave
})(USE, './leave'); })(USE, './leave');
;USE(function(module){ ;USE(function(module){
// How does it work? // How does it work?
// TODO: Bug! Need to include SEA! // TODO: Bug! Need to include SEA!
const Gun = (typeof window !== 'undefined' ? window : global).Gun || USE('gun/gun') const Gun = (typeof window !== 'undefined' ? window : global).Gun || USE('gun/gun')
var SEA = USE('./sea');
var authRecall = USE('./recall'); const SEA = USE('./sea')
var authenticate = USE('./authenticate'); const authRecall = USE('./recall')
var finalizeLogin = USE('./login'); const authenticate = USE('./authenticate')
var authLeave = USE('./leave'); const finalizeLogin = USE('./login')
const authLeave = USE('./leave')
// let's extend the gun chain with a `user` function. // let's extend the gun chain with a `user` function.
// only one user can be logged in at a time, per gun instance. // only one user can be logged in at a time, per gun instance.
Gun.chain.user = function() { Gun.chain.user = function() {
const root = this.back(-1) // always reference the root gun instance. const gunRoot = this.back(-1) // always reference the root gun instance.
let user = root._.user || (root._.user = root.chain()); // create a user context. const user = gunRoot._.user || (gunRoot._.user = gunRoot.chain()); // create a user context.
// then methods... // then methods...
[ 'create', // factory [ 'create', // factory
'auth', // login 'auth', // login
@ -1040,7 +1047,7 @@
// Well first we have to actually create a user. That is what this function does. // Well first we have to actually create a user. That is what this function does.
Object.assign(User, { Object.assign(User, {
async create(username, pass, cb) { async create(username, pass, cb) {
const root = this.back(-1) const gunRoot = this.back(-1)
var gun = this, cat = (gun._); var gun = this, cat = (gun._);
cb = cb || function(){}; cb = cb || function(){};
if(cat.ing){ if(cat.ing){
@ -1051,7 +1058,7 @@
var p = new Promise((resolve, reject) => { // Because no Promises or async var p = new Promise((resolve, reject) => { // Because no Promises or async
// Because more than 1 user might have the same username, we treat the alias as a list of those users. // Because more than 1 user might have the same username, we treat the alias as a list of those users.
if(cb){ resolve = reject = cb } if(cb){ resolve = reject = cb }
root.get(`alias/${username}`).get(async (at, ev) => { gunRoot.get(`alias/${username}`).get(async (at, ev) => {
ev.off() ev.off()
if (at.put) { if (at.put) {
// If we can enforce that a user name is already taken, it might be nice to try, but this is not guaranteed. // If we can enforce that a user name is already taken, it might be nice to try, but this is not guaranteed.
@ -1082,9 +1089,9 @@
const user = { alias, pub, epub, auth } const user = { alias, pub, epub, auth }
const tmp = `pub/${pairs.pub}` const tmp = `pub/${pairs.pub}`
// awesome, now we can actually save the user with their public key as their ID. // awesome, now we can actually save the user with their public key as their ID.
root.get(tmp).put(user) gunRoot.get(tmp).put(user)
// next up, we want to associate the alias with the public key. So we add it to the alias list. // next up, we want to associate the alias with the public key. So we add it to the alias list.
root.get(`alias/${username}`).put(Gun.obj.put({}, tmp, Gun.val.rel.ify(tmp))) gunRoot.get(`alias/${username}`).put(Gun.obj.put({}, tmp, Gun.val.rel.ify(tmp)))
// callback that the user has been created. (Note: ok = 0 because we didn't wait for disk to ack) // callback that the user has been created. (Note: ok = 0 because we didn't wait for disk to ack)
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. 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.
} catch (e) { } catch (e) {
@ -1095,14 +1102,14 @@
} }
}) })
}) })
return gun; // gun chain commands must return gun chains! return gun // gun chain commands must return gun chains!
}, },
// now that we have created a user, we want to authenticate them! // now that we have created a user, we want to authenticate them!
async auth(alias, pass, cb, opts) { async auth(alias, pass, cb, opt) {
if(cb && !(cb instanceof Function)){ opts = cb; cb = function(){} } const opts = opt || (typeof cb !== 'function' && cb)
const { pin, newpass } = opts || {} const { pin, newpass } = opts || {}
const root = this.back(-1) const gunRoot = this.back(-1)
cb = cb || function(){}; cb = typeof cb === 'function' ? cb : () => {}
var gun = this, cat = (gun._); var gun = this, cat = (gun._);
if(cat.ing){ if(cat.ing){
@ -1113,7 +1120,7 @@
if (!pass && pin) { if (!pass && pin) {
try { try {
var r = await authRecall(root, { alias, pin }) var r = await authRecall(gunRoot, { alias, pin })
return cat.ing = false, cb(r), gun; return cat.ing = false, cb(r), gun;
} catch (e) { } catch (e) {
var err = { err: 'Auth attempt failed! Reason: No session data for alias & PIN' } var err = { err: 'Auth attempt failed! Reason: No session data for alias & PIN' }
@ -1129,7 +1136,7 @@
} }
try { try {
const keys = await authenticate(alias, pass, root) const keys = await authenticate(alias, pass, gunRoot)
if (!keys) { if (!keys) {
return putErr('Auth attempt failed!')({ message: 'No keys' }) return putErr('Auth attempt failed!')({ message: 'No keys' })
} }
@ -1153,20 +1160,18 @@
epub: signedEpub epub: signedEpub
} }
// awesome, now we can update the user using public key ID. // awesome, now we can update the user using public key ID.
root.get(`pub/${user.pub}`).put(user) gunRoot.get(`pub/${user.pub}`).put(user)
// then we're done // then we're done
var login = finalizeLogin(alias, keys, root, { pin }) const login = finalizeLogin(alias, keys, gunRoot, { pin })
login.catch(putErr('Failed to finalize login with new password!')) login.catch(putErr('Failed to finalize login with new password!'))
login = await login; return cat.ing = false, cb(await login), gun
return cat.ing = false, cb(login), gun;
} catch (e) { } catch (e) {
return putErr('Password set attempt failed!')(e) return putErr('Password set attempt failed!')(e)
} }
} else { } else {
var login = finalizeLogin(alias, keys, root, { pin }) const login = finalizeLogin(alias, keys, gunRoot, { pin })
login.catch(putErr('Finalizing login failed!')) login.catch(putErr('Finalizing login failed!'))
login = await login; return cat.ing = false, cb(await login), gun;
return cat.ing = false, cb(login), gun;
} }
} catch (e) { } catch (e) {
return putErr('Auth attempt failed!')(e) return putErr('Auth attempt failed!')(e)
@ -1178,18 +1183,18 @@
}, },
// If authenticated user wants to delete his/her account, let's support it! // If authenticated user wants to delete his/her account, let's support it!
async delete(alias, pass) { async delete(alias, pass) {
const root = this.back(-1) const gunRoot = this.back(-1)
try { try {
const { pub } = await authenticate(alias, pass, root) const { pub } = await authenticate(alias, pass, gunRoot)
await authLeave(root, alias) await authLeave(gunRoot, alias)
// Delete user data // Delete user data
root.get(`pub/${pub}`).put(null) gunRoot.get(`pub/${pub}`).put(null)
// Wipe user data from memory // Wipe user data from memory
const { user = { _: {} } } = root._; const { user = { _: {} } } = gunRoot._;
// TODO: is this correct way to 'logout' user from Gun.User ? // TODO: is this correct way to 'logout' user from Gun.User ?
[ 'alias', 'sea', 'pub' ].map((key) => delete user._[key]) [ 'alias', 'sea', 'pub' ].map((key) => delete user._[key])
user._.is = user.is = {} user._.is = user.is = {}
root.user() gunRoot.user()
return { ok: 0 } // TODO: proper return codes??? return { ok: 0 } // TODO: proper return codes???
} catch (e) { } catch (e) {
Gun.log('User.delete failed! Error:', e) Gun.log('User.delete failed! Error:', e)
@ -1199,7 +1204,7 @@
// If authentication is to be remembered over reloads or browser closing, // If authentication is to be remembered over reloads or browser closing,
// set validity time in minutes. // set validity time in minutes.
async recall(setvalidity, options) { async recall(setvalidity, options) {
const root = this.back(-1) const gunRoot = this.back(-1)
let validity let validity
let opts let opts
@ -1224,7 +1229,7 @@
authsettings.hook = (Gun.obj.has(opts, 'hook') && typeof opts.hook === 'function') authsettings.hook = (Gun.obj.has(opts, 'hook') && typeof opts.hook === 'function')
? opts.hook : _initial_authsettings.hook ? opts.hook : _initial_authsettings.hook
// All is good. Should we do something more with actual recalled data? // All is good. Should we do something more with actual recalled data?
return await authRecall(root) return await authRecall(gunRoot)
} catch (e) { } catch (e) {
const err = 'No session!' const err = 'No session!'
Gun.log(err) Gun.log(err)
@ -1234,11 +1239,11 @@
} }
}, },
async alive() { async alive() {
const root = this.back(-1) const gunRoot = this.back(-1)
try { try {
// All is good. Should we do something more with actual recalled data? // All is good. Should we do something more with actual recalled data?
await authRecall(root) await authRecall(gunRoot)
return root._.user._ return gunRoot._.user._
} catch (e) { } catch (e) {
const err = 'No session!' const err = 'No session!'
Gun.log(err) Gun.log(err)
@ -1255,13 +1260,12 @@
}) })
} }
} }
module.exports = User
module.exports = User;
})(USE, './user'); })(USE, './user');
;USE(function(module){ ;USE(function(module){
const Gun = (typeof window !== 'undefined' ? window : global).Gun || USE('gun/gun') const Gun = (typeof window !== 'undefined' ? window : global).Gun || USE('gun/gun')
var SEA = USE('./sea'); const SEA = USE('./sea')
// After we have a GUN extension to make user registration/login easy, we then need to handle everything else. // After we have a GUN extension to make user registration/login easy, we then need to handle everything else.
// We do this with a GUN adapter, we first listen to when a gun instance is created (and when its options change) // We do this with a GUN adapter, we first listen to when a gun instance is created (and when its options change)
@ -1511,5 +1515,4 @@
} }
})(USE, './index'); })(USE, './index');
}());
}());