diff --git a/lib/unbuild.js b/lib/unbuild.js index 6cef1067..ef51e1bb 100644 --- a/lib/unbuild.js +++ b/lib/unbuild.js @@ -53,7 +53,7 @@ var next = function(start, end){ return code.t; } -var path = function(){ +var path = function(p){ var code = next(',', ')'); var path; try{path = eval(code); @@ -62,7 +62,7 @@ var path = function(){ if('.js' !== path.slice(-3)){ path += '.js'; } - return nodePath.join('./src', path); + return nodePath.join('./'+(p||'src'), path); } var undent = function(code, n){ @@ -75,22 +75,33 @@ var undent = function(code, n){ ;(function(){ - rm('./src'); - mk('./src'); - mk('./src/polyfill'); - mk('./src/adapters'); + var arg = process.argv[2] || 'gun'; - var gun = read('gun.js'); - var code = next(gun); + if('gun' === arg){ + rm('./src'); + mk('./src'); + mk('./src/polyfill'); + mk('./src/adapters'); + } else { + rm('./'+arg); + mk('./'+arg); + } + + var f = read(arg+'.js'); + var code = next(f); code = next("/* UNBUILD */"); - write('src/polyfill/unbuild.js', undent(code, 1)); + + if('gun' === arg){ + write('src/polyfill/unbuild.js', undent(code, 1)); + arg = ''; + } (function recurse(c){ code = next(";USE(function(module){", "})(USE"); if(!code){ return } - var file = path(); + var file = path(arg); if(!file){ return } code = code.replace(/\bUSE\(/g, 'require('); write(file, undent(code)); diff --git a/sea.js b/sea.js index d320b67c..e9c80bb0 100644 --- a/sea.js +++ b/sea.js @@ -5,6 +5,9 @@ /*eslint node/no-deprecated-api: [error, {ignoreModuleItems: ["new buffer.Buffer()"]}] */ ;(function(){ // eslint-disable-line no-extra-semi + + /* UNBUILD */ + /* Security, Encryption, and Authorization: SEA.js */ @@ -13,1306 +16,1454 @@ /* THIS IS AN EARLY ALPHA!!! */ - var Gun = (typeof window !== 'undefined' ? window : global).Gun || require('./gun'); + var root; + if(typeof window !== "undefined"){ root = window } + if(typeof global !== "undefined"){ root = global } + root = root || {}; + var console = root.console || {log: function(){}}; + function USE(arg){ + return arg.slice? USE[R(arg)] : function(mod, path){ + arg(mod = {exports: {}}); + USE[R(path)] = mod.exports; + } + function R(p){ + return p.split('/').slice(-1).toString().replace('.js',''); + } + } + if(typeof module !== "undefined"){ var common = module } + - var subtle, subtleossl, TextEncoder, TextDecoder, getRandomBytes; - var sessionStorage, localStorage, indexedDB; + const Gun = (typeof window !== 'undefined' ? window : global).Gun || require('./gun') - if(typeof window !== 'undefined'){ - var wc = window.crypto || window.msCrypto; // STD or M$ - subtle = wc.subtle || wc.webkitSubtle; // STD or iSafari - getRandomBytes = function(len){ - return Buffer.from(wc.getRandomValues(new Uint8Array(Buffer.alloc(len)))); - }; - TextEncoder = window.TextEncoder; - TextDecoder = window.TextDecoder; - sessionStorage = window.sessionStorage; - localStorage = window.localStorage; + let subtle + let subtleossl + let getRandomBytes + let indexedDB + let crypto + let funcsSetter + /* UNBUILD */ + + if (typeof __webpack_require__ === 'function' || typeof window !== 'undefined') { + const wc = window.crypto || window.msCrypto // STD or M$ + subtle = wc.subtle || wc.webkitSubtle // STD or iSafari + getRandomBytes = (len) => Buffer.from(wc.getRandomValues(new Uint8Array(Buffer.alloc(len)))) + funcsSetter = () => window indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB - || window.msIndexedDB || window.shimIndexedDB; + || window.msIndexedDB || window.shimIndexedDB } else { - var crypto = require('crypto'); - var WebCrypto = require('node-webcrypto-ossl'); - var webcrypto = new WebCrypto({directory: 'key_storage'}); - subtleossl = webcrypto.subtle; - subtle = require('@trust/webcrypto').subtle; // All but ECDH - getRandomBytes = function(len){ return Buffer.from(crypto.randomBytes(len)) }; - TextEncoder = require('text-encoding').TextEncoder; - TextDecoder = require('text-encoding').TextDecoder; - // Let's have Storage for NodeJS / testing - sessionStorage = new require('node-localstorage').LocalStorage('.sessionStorage'); - localStorage = new require('node-localstorage').LocalStorage('.localStorage'); - indexedDB = require("fake-indexeddb"); - if(typeof global !== 'undefined'){ - global.sessionStorage = sessionStorage; - global.localStorage = localStorage; + crypto = require('crypto') + const WebCrypto = require('node-webcrypto-ossl') + const webcrypto = new WebCrypto({directory: 'key_storage'}) + subtleossl = webcrypto.subtle + subtle = require('@trust/webcrypto').subtle // All but ECDH + getRandomBytes = (len) => Buffer.from(crypto.randomBytes(len)) + funcsSetter = () => { + const { TextEncoder, TextDecoder } = require('text-encoding') + // Let's have Storage for NodeJS / testing + const sessionStorage = new require('node-localstorage').LocalStorage('.sessionStorage') + const localStorage = new require('node-localstorage').LocalStorage('.localStorage') + return { TextEncoder, TextDecoder, sessionStorage, localStorage } } + indexedDB = require('fake-indexeddb') + } + const { TextEncoder, TextDecoder, sessionStorage, localStorage } = funcsSetter() + + if (typeof __webpack_require__ !== 'function' && typeof global !== 'undefined') { + global.sessionStorage = sessionStorage + global.localStorage = localStorage } - // This is Array extended to have .toString(['utf8'|'hex'|'base64']) - function SeaArray() {} - Object.assign(SeaArray, { from: Array.from }) - SeaArray.prototype = Object.create(Array.prototype) - SeaArray.prototype.toString = function(enc = 'utf8', start = 0, end) { - const { length } = this - if (enc === 'hex') { - const buf = new Uint8Array(this) - return [ ...Array(((end && (end + 1)) || length) - start).keys()] - .map((i) => buf[ i + start ].toString(16).padStart(2, '0')).join('') - } - if (enc === 'utf8') { - return Array.from( - { length: (end || length) - start }, - (_, i) => String.fromCharCode(this[ i + start]) - ).join('') - } - if (enc === 'base64') { - return btoa(this) - } - } - - // This is Buffer implementation used in SEA: - function SafeBuffer(...props) { - console.warn('new SafeBuffer() is depreciated, please use SafeBuffer.from()') - return SafeBuffer.from(...props) - } - SafeBuffer.prototype = Object.create(Array.prototype) - Object.assign(SafeBuffer, { - // (data, enc) where typeof data === 'string' then enc === 'utf8'|'hex'|'base64' - from() { - if (!Object.keys(arguments).length) { - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + ;USE(function(module){ + // This is Array extended to have .toString(['utf8'|'hex'|'base64']) + function SeaArray() {} + Object.assign(SeaArray, { from: Array.from }) + SeaArray.prototype = Object.create(Array.prototype) + SeaArray.prototype.toString = function(enc = 'utf8', start = 0, end) { + const { length } = this + if (enc === 'hex') { + const buf = new Uint8Array(this) + return [ ...Array(((end && (end + 1)) || length) - start).keys()] + .map((i) => buf[ i + start ].toString(16).padStart(2, '0')).join('') } - const input = arguments[0] - let buf - if (typeof input === 'string') { - const enc = arguments[1] || 'utf8' - if (enc === 'hex') { - const bytes = input.match(/([\da-fA-F]{2})/g) - .map((byte) => parseInt(byte, 16)) - if (!bytes || !bytes.length) { - throw new TypeError('Invalid first argument for type \'hex\'.') - } - buf = SeaArray.from(bytes) - } else if (enc === 'utf8') { - const { length } = input - const words = new Uint16Array(length) - Array.from({ length }, (_, i) => words[i] = input.charCodeAt(i)) - buf = SeaArray.from(words) - } else if (enc === 'base64') { - const dec = atob(input) - const { length } = dec - const bytes = new Uint8Array(length) - Array.from({ length }, (_, i) => bytes[i] = dec.charCodeAt(i)) - buf = SeaArray.from(bytes) - } else if (enc === 'binary') { - buf = SeaArray.from(input) - } else { - console.info(`SafeBuffer.from unknown encoding: '${enc}'`) + if (enc === 'utf8') { + return Array.from( + { length: (end || length) - start }, + (_, i) => String.fromCharCode(this[ i + start]) + ).join('') + } + if (enc === 'base64') { + return btoa(this) + } + } + module.exports = SeaArray; + })(USE, './array'); + + ;USE(function(module){ + // This is Buffer implementation used in SEA. Functionality is mostly + // compatible with NodeJS 'safe-buffer' and is used for encoding conversions + // between binary and 'hex' | 'utf8' | 'base64' + // See documentation and validation for safe implementation in: + // https://github.com/feross/safe-buffer#update + var SeaArray = USE('./array'); + function SafeBuffer(...props) { + console.warn('new SafeBuffer() is depreciated, please use SafeBuffer.from()') + return SafeBuffer.from(...props) + } + SafeBuffer.prototype = Object.create(Array.prototype) + Object.assign(SafeBuffer, { + // (data, enc) where typeof data === 'string' then enc === 'utf8'|'hex'|'base64' + from() { + if (!Object.keys(arguments).length) { + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') } - return buf - } - const { byteLength, length = byteLength } = input - if (length) { + const input = arguments[0] let buf - if (input instanceof ArrayBuffer) { - buf = new Uint8Array(input) - } - return SeaArray.from(buf || input) - } - }, - - alloc(length, fill = 0 /*, enc*/ ) { - return SeaArray.from(new Uint8Array(Array.from({ length }, () => fill))) - }, - - allocUnsafe(length) { - return SeaArray.from(new Uint8Array(Array.from({ length }))) - }, - - concat(arr) { // octet array - if (!Array.isArray(arr)) { - throw new TypeError('First argument must be Array containing ArrayBuffer or Uint8Array instances.') - } - return SeaArray.from(arr.reduce((ret, item) => ret.concat(Array.from(item)), [])) - } - }) - SafeBuffer.prototype.from = SafeBuffer.from - SafeBuffer.prototype.toString = SeaArray.prototype.toString - - const Buffer = SafeBuffer - - // Encryption parameters - var pbkdf2 = { - hash: 'SHA-256', - iter: 50000, - ks: 64 - }; - - var ecdsasignprops = {name: 'ECDSA', hash: {name: 'SHA-256'}}; - var ecdsakeyprops = {name: 'ECDSA', namedCurve: 'P-256'}; - var ecdhkeyprops = {name: 'ECDH', namedCurve: 'P-256'}; - - var _initial_authsettings = { - validity: 12 * 60 * 60, // internally in seconds : 12 hours - hook: function(props){ return props } // { iat, exp, alias, remember } - // or return new Promise(function(resolve, reject){(resolve(props))}) - }; - // These are used to persist user's authentication "session" - var authsettings = { - validity: _initial_authsettings.validity, - hook: _initial_authsettings.hook - }; - // This creates Web Cryptography API compliant JWK for sign/verify purposes - function keystoecdsajwk(pub,priv){ - var pubkey = Buffer.from(pub, 'base64').toString('utf8').split(':'); - var jwk = priv ? {d: priv, key_ops: ['sign']} : {key_ops: ['verify']}; - return Object.assign(jwk, { - kty: 'EC', - crv: 'P-256', - x: pubkey[0], - y: pubkey[1], - ext: false - }); - } - - // let's extend the gun chain with a `user` function. - // only one user can be logged in at a time, per gun instance. - Gun.chain.user = function(){ - var root = this.back(-1); // always reference the root gun instance. - var user = root._.user || (root._.user = root.chain()); // create a user context. - // then methods... - [ 'create', // factory - 'auth', // login - 'leave', // logout - 'delete', // account delete - 'recall', // existing auth boostrap - 'alive' // keep/check auth validity - ].forEach(function(method){ - user[method] = User[method]; - }); - return user; // return the user! - }; - - // Practical examples about usage found from ./test/common.js - - // This is internal func queries public key(s) for alias. - function querygunaliases(alias,root){ - return new Promise(function(resolve, reject){ - // load all public keys associated with the username alias we want to log in with. - root.get('alias/'+alias).get(function(rat, rev){ - rev.off(); - if(!rat.put){ - // if no user, don't do anything. - var err = 'No user!'; - Gun.log(err); - return reject(err); - } - // then figuring out all possible candidates having matching username - var aliases = [], c = 0; - Gun.obj.map(rat.put, function(at, pub){ - if(!pub.slice || 'pub/' !== pub.slice(0,4)){ return } - c++; - // grab the account associated with this public key. - root.get(pub).get(function(at, ev){ - pub = pub.slice(4); - ev.off(); c--; - if(at.put){ - aliases.push({pub: pub, at: at}); + if (typeof input === 'string') { + const enc = arguments[1] || 'utf8' + if (enc === 'hex') { + const bytes = input.match(/([\da-fA-F]{2})/g) + .map((byte) => parseInt(byte, 16)) + if (!bytes || !bytes.length) { + throw new TypeError('Invalid first argument for type \'hex\'.') } - if(!c && (c = -1)){ resolve(aliases) } - }); - }); - if(!c){ reject('Public key does not exist!') } - }); - }); - } - // This is internal User authentication func. - function authenticate(alias,pass,root){ - return new Promise(function(resolve, reject){ - // load all public keys associated with the username alias we want to log in with. - querygunaliases(alias, root).then(function(aliases){ - // TODO: BUG! Occasionally returns [], need to add line to auto-requery! - // then attempt to log into each one until we find ours! - // (if two users have the same username AND the same password... that would be bad) - aliases.forEach(function(one, index){ - var at = one.at, pub = one.pub; - var remaining = (aliases.length - index) > 1; - if(!at.put){ - return !remaining && reject({err: 'Public key does not exist!'}); + buf = SeaArray.from(bytes) + } else if (enc === 'utf8') { + const { length } = input + const words = new Uint16Array(length) + Array.from({ length }, (_, i) => words[i] = input.charCodeAt(i)) + buf = SeaArray.from(words) + } else if (enc === 'base64') { + const dec = atob(input) + const { length } = dec + const bytes = new Uint8Array(length) + Array.from({ length }, (_, i) => bytes[i] = dec.charCodeAt(i)) + buf = SeaArray.from(bytes) + } else if (enc === 'binary') { + buf = SeaArray.from(input) + } else { + console.info(`SafeBuffer.from unknown encoding: '${enc}'`) } - // attempt to PBKDF2 extend the password with the salt. (Verifying the signature gives us the plain text salt.) - var auth = at.put.auth; // SEA.read(at.put.auth, pub).then(function(auth){ // NOTE: aliasquery uses `gun.get` which internally SEA.read verifies the data for us, so we do not need to re-verify it here. - auth = auth.slice ? JSON.parse(auth) : auth; - return SEA.proof(pass, auth.salt) - .catch(function(e){ reject({err: 'Failed to create proof!'}) }) - .then(function(proof){ - var user = {pub: pub, proof: proof, at: at}; - // the proof of work is evidence that we've spent some time/effort trying to log in, this slows brute force. - /* - MARK TO @mhelander : pub vs epub!??? - */ - SEA.dec(auth.auth, {pub: pub, key: proof}) - .catch(function(e){ reject({err: 'Failed to decrypt secret!'}) }) - .then(function(sea){ - // now we have AES decrypted the private key, from when we encrypted it with the proof at registration. - // if we were successful, then that meanswe're logged in! - if(sea){ - user.priv = sea.priv; - user.salt = auth.salt; // TODO: needed? - var epub = at.put.epub; //SEA.read(at.put.epub, pub).then(function(epub){ // NOTE: see above "NOTE"! - Object.assign(user, {epub: epub, epriv: sea.epriv}); - resolve(user); - //}).catch(function(){ return !remaining && reject({err: 'Public key does not exist!'}) }); - } else if(!remaining){ - reject({err: 'Public key does not exist!'}); - } - // return remaining ? undefined // Not done yet - // : priv ? resolve({pub: pub, priv: priv, at: at, proof: proof}) - // // Or else we failed to log in... - // : reject({err: 'Failed to decrypt private key!'}); - }).catch(function(e){ reject({err: 'Failed read secret!'})} ); - }); - //}).catch(function(e){ reject({err: 'Failed to create proof!'}) }); - }); - }).catch(function(e){ reject({err: e}) }); - }); - } - // This internal func finalizes User authentication - function finalizelogin(alias,key,root,opts){ - var user = root._.user; - // add our credentials in-memory only to our root gun instance - user._ = key.at.gun._; - // so that way we can use the credentials to encrypt/decrypt data - user._.is = user.is = {}; - // that is input/output through gun (see below) - user._.alias = alias; - user._.sea = {priv: key.priv, epriv: key.epriv, pub: key.pub, epub: key.epub}; - user._.pub = key.pub; - user._.epub = key.epub; - //console.log("authorized", user._); - // persist authentication - return authpersist(user._, key.proof, opts).then(function(){ - // emit an auth event, useful for page redirects and stuff. - try{root._.on('auth', user._); - }catch(e){console.log("Your 'auth' callback crashed with:", e)} - // returns success with the user data credentials. - return user._; - }); - } - // This updates sessionStorage & IndexedDB to persist authenticated "session" - function updatestorage(proof,key,pin){ - return function(props){ - return new Promise(function(resolve, reject){ - if(!Gun.obj.has(props, 'alias')){ return resolve() } - if(authsettings.validity && proof && Gun.obj.has(props, 'iat')){ - props.proof = proof; - delete props.remember; // Not stored if present - - var remember = {alias: props.alias, pin: pin}; - var persist = props; - - return SEA.write(JSON.stringify(remember), key).then(function(signed){ - sessionStorage.setItem('user', props.alias); - sessionStorage.setItem('remember', signed); - }).then(function(){ - return !persist || SEA.enc(persist, pin).then(function(encrypted){ - return encrypted && SEA.write(encrypted, key).then(function(signed){ - return new Promise(function(resolve){ - SEA._callonstore_(function(store) { // Wipe IndexedDB completedy! - var act = store.clear(); - act.onsuccess = function(){}; - }, function(){ // Then set encrypted auth props - SEA._callonstore_(function(store){ - store.put({id: props.alias, auth: signed}); - }, function(){ resolve() }); - }); - }); - }).catch(reject); - }).catch(reject); - }).then(function(){ resolve(props) }) - .catch(function(e){ reject({err: 'Session persisting failed!'}) }); + return buf } - // Wiping IndexedDB completely when using random PIN - return new Promise(function(resolve){ - SEA._callonstore_(function(store) { - var act = store.clear(); - act.onsuccess = function(){}; - }, function(){ resolve() }); - }).then(function(){ - sessionStorage.removeItem('user'); - sessionStorage.removeItem('remember'); - resolve(props); - }); - }); - }; - } - - // This internal func persists User authentication if so configured - function authpersist(user,proof,opts){ - // opts = { pin: 'string' } - // no opts.pin then uses random PIN - // How this works: - // called when app bootstraps, with wanted options - // IF authsettings.validity === 0 THEN no remember-me, ever - // IF PIN then signed 'remember' to window.sessionStorage and 'auth' to IndexedDB - var pin = (Gun.obj.has(opts, 'pin') && opts.pin) || Gun.text.random(10); - pin = Buffer.from(pin, 'utf8').toString('base64'); - - if(proof && user && user.alias && authsettings.validity){ - var args = {alias: user.alias}; - args.iat = Math.ceil(Date.now() / 1000); // seconds - args.exp = authsettings.validity; // seconds - if(Gun.obj.has(opts, 'pin')){ - args.remember = true; // for hook - not stored + const { byteLength, length = byteLength } = input + if (length) { + let buf + if (input instanceof ArrayBuffer) { + buf = new Uint8Array(input) + } + return SeaArray.from(buf || input) + } + }, + // This is 'safe-buffer.alloc' sans encoding support + alloc(length, fill = 0 /*, enc*/ ) { + return SeaArray.from(new Uint8Array(Array.from({ length }, () => fill))) + }, + // This is normal UNSAFE 'buffer.alloc' or 'new Buffer(length)' - don't use! + allocUnsafe(length) { + return SeaArray.from(new Uint8Array(Array.from({ length }))) + }, + // This puts together array of array like members + concat(arr) { // octet array + if (!Array.isArray(arr)) { + throw new TypeError('First argument must be Array containing ArrayBuffer or Uint8Array instances.') + } + return SeaArray.from(arr.reduce((ret, item) => ret.concat(Array.from(item)), [])) } - var props = authsettings.hook(args); - var key = { - pub: user.pub, priv: user.sea.priv, epub: user.epub, epriv: user.sea.epriv - }; - if(props instanceof Promise){ - return props.then(updatestorage(proof, key, pin)); - } - return updatestorage(proof, key, pin)(props); + }) + SafeBuffer.prototype.from = SafeBuffer.from + SafeBuffer.prototype.toString = SeaArray.prototype.toString + + const Buffer = SafeBuffer + if(typeof window !== 'undefined'){ window.Buffer = window.Buffer || Buffer } + module.exports = SafeBuffer; + })(USE, './buffer'); + + ;USE(function(module){ + // This is safe class to operate with IndexedDB data - all methods are Promise + function EasyIndexedDB(objectStoreName, dbName = 'GunDB', dbVersion = 1) { + // Private internals, including constructor props + const runTransaction = (fn_) => new Promise((resolve, reject) => { + const open = indexedDB.open(dbName, dbVersion) // Open (or create) the DB + open.onerror = (e) => { + reject(new Error('IndexedDB error:', e)) + } + open.onupgradeneeded = () => { + const db = open.result // Create the schema; props === current version + db.createObjectStore(objectStoreName, { keyPath: 'id' }) + } + let result + open.onsuccess = () => { // Start a new transaction + const db = open.result + const tx = db.transaction(objectStoreName, 'readwrite') + const store = tx.objectStore(objectStoreName) + tx.oncomplete = () => { + db.close() // Close the db when the transaction is done + resolve(result) // Resolves result returned by action function fn_ + } + result = fn_(store) + } + }) + + Object.assign(this, { + async wipe() { // Wipe IndexedDB completedy! + return runTransaction((store) => { + const act = store.clear() + act.onsuccess = () => {} + }) + }, + async put(id, props) { + const data = Object.assign({}, props, { id }) + return runTransaction((store) => { store.put(data) }) + }, + async get(id, prop) { + return runTransaction((store) => new Promise((resolve) => { + const getData = store.get(id) + getData.onsuccess = () => { + const { result = {} } = getData + resolve(result[prop]) + } + })) + } + }) } - return updatestorage()({alias: 'delete'}); - } - // This internal func recalls persisted User authentication if so configured - function authrecall(root,authprops){ - return new Promise(function(resolve, reject){ - // window.sessionStorage only holds signed { alias, pin } !!! - var remember = authprops || sessionStorage.getItem('remember'); - var alias = Gun.obj.has(authprops, 'alias') && authprops.alias - || sessionStorage.getItem('user'); - var pin = Gun.obj.has(authprops, 'pin') - && Buffer.from(authprops.pin, 'utf8').toString('base64'); + // This is IndexedDB used by Gun SEA + const seaIndexedDb = new EasyIndexedDB('SEA', 'GunDB', 1) + EasyIndexedDB.scope = seaIndexedDb; // for now. This module should not export an instance of itself! + module.exports = EasyIndexedDB; + })(USE, './indexed'); - var checkRememberData = function(decr){ - if(Gun.obj.has(decr, 'proof') - && Gun.obj.has(decr, 'alias') && decr.alias === alias){ - var proof = decr.proof; - var iat = decr.iat; // No way hook to update this - delete decr.proof; // We're not gonna give proof to hook! - var checkNotExpired = function(args){ - if(Math.floor(Date.now() / 1000) < (iat + args.exp)){ - args.iat = iat; - args.proof = proof; - return args; - } else { Gun.log('Authentication expired!') } - }; - var hooked = authsettings.hook(decr); - return ((hooked instanceof Promise) - && hooked.then(checkNotExpired)) || checkNotExpired(hooked); - } - }; - var readAndDecrypt = function(data, pub, key){ - return SEA.read(data, pub).then(function(encrypted){ - return SEA.dec(encrypted, key); - }).then(function(decrypted){ - try{ return decrypted.slice ? JSON.parse(decrypted) : decrypted }catch(e){} //eslint-disable-line no-empty - return decrypted; - }); - }; + ;USE(function(module){ + var Buffer = USE('./buffer'); + var settings = {}; + // Encryption parameters + const pbKdf2 = { hash: 'SHA-256', iter: 50000, ks: 64 } - // Already authenticated? - if(root._.user && Gun.obj.has(root._.user._, 'pub') && Gun.obj.has(root._.user._, 'sea')){ - return resolve(root._.user._); - } - // No, got alias? - if(alias && remember){ - return querygunaliases(alias, root).then(function(aliases){ - return new Promise(function(resolve, reject){ - // then attempt to log into each one until we find ours! - // (if two users have the same username AND the same password... that would be bad) - aliases.forEach(function(one, index){ - var at = one.at, pub = one.pub; - var remaining = (aliases.length - index) > 1; - if(!at.put){ - return !remaining && reject({err: 'Public key does not exist!'}); - } - // got pub, time to try auth with alias & PIN... - return ((pin && Promise.resolve({pin: pin, alias: alias})) - // or just unwrap Storage data... - || SEA.read(remember, pub, true)).then(function(props){ - try{ props = props.slice ? JSON.parse(props) : props }catch(e){} //eslint-disable-line no-empty - if(Gun.obj.has(props, 'pin') && Gun.obj.has(props, 'alias') - && props.alias === alias){ - pin = props.pin; // Got PIN so get IndexedDB secret if signature is ok - return new Promise(function(resolve){ - var remember; - SEA._callonstore_(function(store) { - var getData = store.get(alias); - getData.onsuccess = function(){ - remember = getData.result && getData.result.auth; - }; - }, function(){ // And return proof if for matching alias - return readAndDecrypt(remember, pub, pin) - .then(checkRememberData).then(resolve) - .catch(function(){ resolve() }); - }); - }); - } - // No PIN, let's try short-term proof if for matching alias - return checkRememberData(props); - }).then(function(args){ - var proof = args && args.proof; - if(!proof){ - return (!args && reject({err: 'No valid authentication session found!'})) - || updatestorage()(args).then(function(){ - reject({err: 'Expired session!'}); - }).catch(function(){ - reject({err: 'Expired session!'}); - }); - } - var auth = JSON.parse(at.put.auth).auth; - return SEA.dec(auth, proof).catch(function(e){ - return !remaining && reject({err: 'Failed to decrypt private key!'}); - }).then(function(sea){ - if(!sea){ return } - var epub = at.put.epub; //return SEA.read(at.put.epub, pub).then(function(epub){ // NOTE: queryalias uses `gun.get` which internally verifies data with `SEA.read` so we do not need to do it again. - return {pub: pub, priv: sea.priv, epriv: sea.epriv, epub: epub}; - //}); - }).then(function(key){ - // now we have AES decrypted the private key, - // if we were successful, then that means we're logged in! - return updatestorage(proof, key, pin)(args).then(function(){ - return remaining ? undefined // Not done yet - : key ? resolve(Object.assign(key, {at: at, proof: proof})) - // Or else we failed to log in... - : reject({err: 'Failed to decrypt private key!'}); - }).catch(function(e){ reject({err: 'Failed to store credentials!'}) }); - }).catch(function(e){ reject({err: 'Failed read secret!'}) }); - }).catch(function(e){ reject({err: 'Failed to access stored credentials!'}) }); - }); - }); - }).then(function(user){ - pin = pin && {pin: pin}; - finalizelogin(alias, user, root, pin).then(resolve).catch(function(e){ - Gun.log('Failed to finalize login with new password!'); - reject({ - err: 'Finalizing new password login failed! Reason: '+(e && e.err) || e || '' - }); - }); - }).catch(function(e){ - reject({err: 'No authentication session found!'}); - }); - } - if(!alias){ - return reject({err: 'No authentication session found!'}); - } - var gotRemember; - SEA._callonstore_(function(store) { - var getData = store.get(alias); - getData.onsuccess = function(){ - gotRemember = getData.result && getData.result.auth; - }; - }, function(){ // And return proof if for matching alias - reject({ - err: (gotRemember && authsettings.validity && 'Missing PIN and alias!') - || 'No authentication session found!'}); - }); - }); - } + const ecdsaSignProps = { name: 'ECDSA', hash: { name: 'SHA-256' } } + const ecdsaKeyProps = { name: 'ECDSA', namedCurve: 'P-256' } + const ecdhKeyProps = { name: 'ECDH', namedCurve: 'P-256' } - // This internal func executes logout actions - function authleave(root, alias){ - return function(resolve, reject){ - var user = root._.user || {_:{}}; - root._.user = null; - alias = alias || user._.alias; - var doIt = function(){ - // TODO: is this correct way to 'logout' user from Gun.User ? - [ 'alias', 'sea', 'pub' ].forEach(function(key){ - delete user._[key]; - }); - user._.is = user.is = {}; - // Let's use default - root.user(); - resolve({ok: 0}); - }; - // Removes persisted authentication & CryptoKeys - authpersist(alias && {alias: alias}).then(doIt).catch(doIt); - }; - } - // This recalls Web Cryptography API CryptoKeys from IndexedDB or creates & stores - function recallCryptoKey(p,s,o){ // {pub, key}|proof, salt, optional:['sign'] - o = o || ['encrypt', 'decrypt']; // Default operations - var importKey = function(key){ - return makeKey((Gun.obj.has(key, 'key') && key.key) || key, s || getRandomBytes(8)) - .then(function(hashedKey){ - return subtle.importKey( + const _initial_authsettings = { + validity: 12 * 60 * 60, // internally in seconds : 12 hours + hook: (props) => props // { iat, exp, alias, remember } + // or return new Promise((resolve, reject) => resolve(props) + } + // These are used to persist user's authentication "session" + const authsettings = Object.assign({}, _initial_authsettings) + // This creates Web Cryptography API compliant JWK for sign/verify purposes + const keysToEcdsaJwk = (pub, priv) => { + const [ x, y ] = Buffer.from(pub, 'base64').toString('utf8').split(':') + const jwk = priv ? { d: priv, key_ops: ['sign'] } : { key_ops: ['verify'] } + return [ // Use with spread returned value... + 'jwk', + Object.assign(jwk, { x, y, kty: 'EC', crv: 'P-256', ext: false }) + ] + } + + settings.pbkdf2 = pbKdf2; + settings.ecdsa = {}; + settings.ecdsa.pair = ecdsaKeyProps; + settings.ecdsa.sign = ecdsaSignProps; + settings.ecdh = ecdhKeyProps; + settings.jwk = keysToEcdsaJwk; + settings.recall = authsettings; + module.exports = settings; + })(USE, './settings'); + + ;USE(function(module){ + const parseProps = (props) => { + try { + return props.slice ? JSON.parse(props) : props + } catch (e) {} //eslint-disable-line no-empty + return props + } + module.exports = parseProps; + })(USE, './parse'); + + ;USE(function(module){ + var Buffer = USE('./buffer'); + var parseProps = USE('./parse'); + var settings = USE('./settings'); + var pbKdf2 = settings.pbkdf2; + // This internal func returns SHA-256 hashed data for signing + const sha256hash = async (mm) => { + const hashSubtle = subtleossl || subtle + const m = parseProps(mm) + const hash = await hashSubtle.digest(pbKdf2.hash, new TextEncoder().encode(m)) + return Buffer.from(hash) + } + module.exports = sha256hash; + })(USE, './sha256'); + + ;USE(function(module){ + // This internal func returns SHA-1 hashed data for KeyID generation + const sha1hash = (b) => (subtleossl || subtle).digest('SHA-1', new ArrayBuffer(b)) + module.exports = sha1hash; + })(USE, './sha1'); + + ;USE(function(module){ + var Buffer = USE('./buffer'); + var sha256hash = USE('./sha256'); + var seaIndexedDb = USE('./indexed').scope; + var settings = USE('./settings'); + var authsettings = settings.recall; + const makeKey = async (p, s) => { + const ps = Buffer.concat([Buffer.from(p, 'utf8'), s]).toString('utf8') + return Buffer.from(await sha256hash(ps), 'binary') + } + // This recalls Web Cryptography API CryptoKeys from IndexedDB or creates & stores + // {pub, key}|proof, salt, optional:['sign'] + const recallCryptoKey = async (p, s, o = [ 'encrypt', 'decrypt' ]) => { + const importKey = async (key) => { + const hashedKey = await makeKey((Gun.obj.has(key, 'key') && key.key) || key, s || getRandomBytes(8)) + return await subtle.importKey( 'raw', new Uint8Array(hashedKey), 'AES-CBC', false, o - ); - }); - }; - return new Promise(function(resolve){ - if(authsettings.validity && typeof window !== 'undefined' - && Gun.obj.has(p, 'pub') && Gun.obj.has(p, 'key')){ - var importAndStoreKey = function(){ // Creates new CryptoKey & stores it - importKey(p).then(function(key){ SEA._callonstore_(function(store){ - store.put({id: p.pub, key: key}); - }, function(){ resolve(key) }); }); - }; - if(Gun.obj.has(p, 'set')){ return importAndStoreKey() } // proof update so overwrite - var aesKey; - SEA._callonstore_(function(store) { - var getData = store.get(p.pub); - getData.onsuccess = function(){ aesKey = getData.result && getData.result.key }; - }, function(){ return aesKey ? resolve(aesKey) : importAndStoreKey() }); - } else { // No secure store usage - importKey(p).then(function(aesKey){ resolve(aesKey) }); + ) } - }); - } - // This internal func returns SHA-256 hashed data for signing - function sha256hash(m){ - var hashSubtle = subtleossl || subtle; - try{ m = m.slice ? m : JSON.stringify(m) }catch(e){} //eslint-disable-line no-empty - return hashSubtle.digest(pbkdf2.hash, new TextEncoder().encode(m)) - .then(function(hash){ return Buffer.from(hash) }); - } - // This internal func returns SHA-1 hashed data for KeyID generation - function sha1hash(b){ - var hashSubtle = subtleossl || subtle; - return hashSubtle.digest('SHA-1', new ArrayBuffer(b)); - } - // How does it work? - function User(){} - // Well first we have to actually create a user. That is what this function does. - User.create = function(alias, pass, cb){ - var root = this.back(-1); - var doIt = function(resolve, reject){ - // Because more than 1 user might have the same username, we treat the alias as a list of those users. - root.get('alias/'+alias).get(function(at, ev){ - ev.off(); - 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. - var err = 'User already created!'; - Gun.log(err); - return reject({err: err}); + if (authsettings.validity && typeof window !== 'undefined' + && Gun.obj.has(p, 'pub') && Gun.obj.has(p, 'key')) { + const { pub: id } = p + const importAndStoreKey = async () => { + const key = await importKey(p) + await seaIndexedDb.put(id, { key }) + return key } - var salt = Gun.text.random(64); - // pseudo-randomly create a salt, then use CryptoJS's PBKDF2 function to extend the password with it. - SEA.proof(pass, salt).then(function(proof){ - // this will take some short amount of time to produce a proof, which slows brute force attacks. - SEA.pair().then(function(pairs){ - // now we have generated a brand new ECDSA key pair for the user account. - var user = {pub: pairs.pub}; - // the user's public key doesn't need to be signed. But everything else needs to be signed with it! - SEA.write(alias, pairs).then(function(signedalias){ - user.alias = signedalias; - return SEA.write(pairs.epub, pairs); - }).then(function(signedepub){ - user.epub = signedepub; - // to keep the private key safe, we AES encrypt it with the proof of work! - return SEA.enc({ - priv: pairs.priv, epriv: pairs.epriv - }, {pub: pairs.epub, key: proof}); - }).then(function(encryptedprivs){ - return SEA.write(salt, pairs).then(function(signedsalt){ - return SEA.write({salt: salt, auth: encryptedprivs}, pairs); - }); - }).then(function(encsigauth){ - user.auth = encsigauth; - var tmp = 'pub/'+pairs.pub; - //console.log("create", user, pair.pub); - // awesome, now we can actually save the user with their public key as their ID. - root.get(tmp).put(user); - // next up, we want to associate the alias with the public key. So we add it to the alias list. - root.get('alias/'+alias).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) - setTimeout(function(){ 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(function(e){ Gun.log('SEA.en or SEA.write calls failed!'); reject(e) }); - }).catch(function(e){ Gun.log('SEA.pair call failed!'); reject(e) }); - }); - }); - }; - if(cb){doIt(cb, cb)} else { return new Promise(doIt) } - }; - // now that we have created a user, we want to authenticate them! - User.auth = function(alias,pass,cb,opt){ - var opts = opt || (typeof cb !== 'function' && cb); - var root = this.back(-1); - cb = typeof cb === 'function' && cb; - - var doIt = function(resolve, reject){ - if(!pass && Gun.obj.has(opts, 'pin')){ - return authrecall(root, {alias: alias, pin: opts.pin}).then(function(props){ - resolve(props); - }).catch(function(e){ - reject({err: 'Auth attempt failed! Reason: No session data for alias & PIN'}); - }); - } - authenticate(alias, pass, root).then(function(keys){ - // we're logged in! - var pin = Gun.obj.has(opts, 'pin') && {pin: opts.pin}; - if(Gun.obj.has(opts, 'newpass')){ - // password update so encrypt private key using new pwd + salt - var newsalt = Gun.text.random(64); - SEA.proof(opts.newpass, newsalt).then(function(newproof){ - return SEA.enc({ - priv: keys.priv, epriv: keys.epriv - }, {pub: keys.pub, key: newproof, set: true}) - .then(function(encryptedpriv){ - return SEA.write({salt: newsalt, auth: encryptedpriv}, keys); - }); - }).then(function(encsigauth){ - return SEA.write(keys.epub, keys).then(function(signedepub){ - return SEA.write(alias, keys).then(function(signedalias){ - return { - alias: signedalias, - auth: encsigauth, - epub: signedepub, - pub: keys.pub - }; - }); - }); - }).then(function(user){ - var tmp = 'pub/'+user.pub; - // awesome, now we can update the user using public key ID. - // root.get(tmp).put(null); - root.get(tmp).put(user); - // then we're done - finalizelogin(alias, keys, root, pin).then(resolve).catch(function(e){ - Gun.log('Failed to finalize login with new password!'); - reject({ - err: 'Finalizing new password login failed! Reason: '+(e && e.err) || e || '' - }); - }); - }).catch(function(e){ - Gun.log('Failed encrypt private key using new password!'); - reject({err: 'Password set attempt failed! Reason: ' + (e && e.err) || e || ''}); - }); - } else { - finalizelogin(alias, keys, root, pin).then(resolve).catch(function(e){ - Gun.log('Failed to finalize login!'); - reject({err: 'Finalizing login failed! Reason: ' + (e && e.err) || e || ''}); - }); + if (Gun.obj.has(p, 'set')) { + return importAndStoreKey() // proof update so overwrite } - }).catch(function(e){ - Gun.log('Failed to sign in!'); - reject({err: 'Auth attempt failed! Reason: ' + (e && e.err) || e || ''}); - }); - }; - if(cb){doIt(cb, cb)} else { return new Promise(doIt) } - }; - Gun.chain.trust = function(user){ - // TODO: BUG!!! SEA `node` read listener needs to be async, which means core needs to be async too. - //gun.get('alice').get('age').trust(bob); - if(Gun.is(user)){ - user.get('pub').get(function(ctx, ev){ - console.log(ctx, ev); - }); + const aesKey = await seaIndexedDb.get(id, 'key') + return aesKey ? aesKey : importAndStoreKey() + } + + // No secure store usage + return importKey(p) } - }; - User.leave = function(cb){ - var root = this.back(-1); - if(cb){authleave(root)(cb, cb)} else { return new Promise(authleave(root)) } - }; - // If authenticated user wants to delete his/her account, let's support it! - User.delete = function(alias,pass,cb){ - var root = this.back(-1); - var doIt = function(resolve, reject){ - authenticate(alias, pass, root).then(function(key){ - new Promise(authleave(root, alias)).catch(function(){}) - .then(function(){ - // Delete user data - root.get('pub/'+key.pub).put(null); - // Wipe user data from memory - var user = root._.user || {_: {}}; - // TODO: is this correct way to 'logout' user from Gun.User ? - [ 'alias', 'sea', 'pub' ].forEach(function(key){ - delete user._[key]; - }); - user._.is = user.is = {}; - root.user(); - resolve({ok: 0}); - }).catch(function(e){ - Gun.log('User.delete failed! Error:', e); - reject({err: 'Delete attempt failed! Reason: ' + (e && e.err) || e || ''}); - }); - }).catch(function(e){ - Gun.log('User.delete authentication failed! Error:', e); - reject({err: 'Delete attempt failed! Reason: ' + (e && e.err) || e || ''}); - }); - }; - if(cb){doIt(cb, cb)} else { return new Promise(doIt) } - }; - // If authentication is to be remembered over reloads or browser closing, - // set validity time in minutes. - User.recall = function(v,cb,o){ - var root = this.back(-1); - var validity, callback, opts; - if(!o && typeof cb !== 'function' && !Gun.val.is(cb)){ - opts = cb; - } else { - callback = cb; + module.exports = recallCryptoKey; + })(USE, './remember'); + + ;USE(function(module){ + const Gun = (typeof window !== 'undefined' ? window : global).Gun || require('gun/gun') + var EasyIndexedDB = USE('./indexed'); + var SafeBuffer = USE('./buffer'); + var settings = USE('./settings'); + var pbKdf2 = settings.pbkdf2; + var ecdsaKeyProps = settings.ecdsa.pair; + var ecdhKeyProps = settings.ecdh; + var keysToEcdsaJwk = settings.jwk; + var ecdsaSignProps = settings.ecdsa.sign; + var sha256hash = USE('./sha256'); + var recallCryptoKey = USE('./remember'); + var parseProps = USE('./parse'); + // THIS WILL BE DEPRECATED IN FAVOR OF `Gun.SEA`! + // let's extend the gun chain with a `SEA` function. + // maps locally used methods to Gun and returns SEA object. + Gun.chain.SEA = function() { + const root = this.back(-1) + const sea = root._.SEA || (root._.SEA = root.chain()); // create a SEA context + Object.keys(SEA).map((method) => sea[method] = SEA[method]) + return sea } - if(!callback){ - if(typeof v === 'function'){ - callback = v; - validity = _initial_authsettings.validity; - } else if(!Gun.val.is(v)){ - opts = v; - validity = _initial_authsettings.validity; - } else { - validity = v * 60; // minutes to seconds + // Practical examples about usage found from ./test/common.js + const SEA = { + // This is easy way to use IndexedDB, all methods are Promises + EasyIndexedDB, + // This is Buffer used in SEA and usable from Gun/SEA application also. + // For documentation see https://nodejs.org/api/buffer.html + Buffer: SafeBuffer, + // These SEA functions support now ony Promises or + // async/await (compatible) code, use those like Promises. + // + // Creates a wrapper library around Web Crypto API + // for various AES, ECDSA, PBKDF2 functions we called above. + async proof(pass, salt) { + try { + if (typeof window !== 'undefined') { + // For browser subtle works fine + const key = await subtle.importKey( + 'raw', new TextEncoder().encode(pass), { name: 'PBKDF2' }, false, ['deriveBits'] + ) + const result = await subtle.deriveBits({ + name: 'PBKDF2', + iterations: pbKdf2.iter, + salt: new TextEncoder().encode(salt), + hash: pbKdf2.hash, + }, key, pbKdf2.ks * 8) + pass = getRandomBytes(pass.length) // Erase passphrase for app + return Buffer.from(result, 'binary').toString('base64') + } + // For NodeJS crypto.pkdf2 rocks + const hash = crypto.pbkdf2Sync( + pass, + new TextEncoder().encode(salt), + pbKdf2.iter, + pbKdf2.ks, + pbKdf2.hash.replace('-', '').toLowerCase() + ) + pass = getRandomBytes(pass.length) // Erase passphrase for app + return hash && hash.toString('base64') + } catch (e) { + Gun.log(e) + throw e + } + }, + // Calculate public key KeyID aka PGPv4 (result: 8 bytes as hex string) + async keyid(pub) { + try { + // base64('base64(x):base64(y)') => Buffer(xy) + const pb = Buffer.concat( + Buffer.from(pub, 'base64').toString('utf8').split(':') + .map((t) => Buffer.from(t, 'base64')) + ) + // id is PGPv4 compliant raw key + const id = Buffer.concat([ + Buffer.from([0x99, pb.length / 0x100, pb.length % 0x100]), pb + ]) + const sha1 = await sha1hash(id) + const hash = Buffer.from(sha1, 'binary') + return hash.toString('hex', hash.length - 8) // 16-bit ID as hex + } catch (e) { + Gun.log(e) + throw e + } + }, + async pair() { + try { + const ecdhSubtle = subtleossl || subtle + // First: ECDSA keys for signing/verifying... + const { pub, priv } = await subtle.generateKey(ecdsaKeyProps, true, [ 'sign', 'verify' ]) + .then(async ({ publicKey, privateKey }) => { + const { d: priv } = await subtle.exportKey('jwk', privateKey) + // privateKey scope doesn't leak out from here! + const { x, y } = await subtle.exportKey('jwk', publicKey) + const pub = Buffer.from([ x, y ].join(':')).toString('base64') + return { pub, priv } + }) + // To include PGPv4 kind of keyId: + // const pubId = await SEA.keyid(keys.pub) + // Next: ECDH keys for encryption/decryption... + const { epub, epriv } = await ecdhSubtle.generateKey(ecdhKeyProps, true, ['deriveKey']) + .then(async ({ publicKey, privateKey }) => { + // privateKey scope doesn't leak out from here! + const { d: epriv } = await ecdhSubtle.exportKey('jwk', privateKey) + const { x, y } = await ecdhSubtle.exportKey('jwk', publicKey) + const epub = Buffer.from([ x, y ].join(':')).toString('base64') + return { epub, epriv } + }) + return { pub, priv, /* pubId, */ epub, epriv } + } catch (e) { + Gun.log(e) + throw e + } + }, + // Derive shared secret from other's pub and my epub/epriv + async derive(pub, { epub, epriv }) { + try { + const { importKey, deriveKey, exportKey } = subtleossl || subtle + const keystoecdhjwk = (pub, priv) => { + const [ x, y ] = Buffer.from(pub, 'base64').toString('utf8').split(':') + const jwk = priv ? { d: priv, key_ops: ['decrypt'] } : { key_ops: ['encrypt'] } + return Object.assign(jwk, { + kty: 'EC', + crv: 'P-256', + ext: false, + x, + y + }) + } + const pubLic = await importKey('jwk', keystoecdhjwk(pub), ecdhKeyProps, false, ['deriveKey']) + const props = Object.assign({}, ecdhKeyProps, { public: pubLic }) + const derived = await importKey('jwk', keystoecdhjwk(epub, epriv), ecdhKeyProps, false, ['deriveKey']) + .then(async (privKey) => { + // privateKey scope doesn't leak out from here! + const derivedKey = await deriveKey(props, privKey, { name: 'AES-CBC', length: 256 }, true, [ 'encrypt', 'decrypt' ]) + return exportKey('jwk', derivedKey).then(({ k }) => k) + }) + return derived + } catch (e) { + Gun.log(e) + throw e + } + }, + async sign(data, { pub, priv }) { + try { + const jwk = keysToEcdsaJwk(pub, priv) + const hash = await sha256hash(data) + // privateKey scope doesn't leak out from here! + const binSig = await subtle.importKey(...jwk, ecdsaKeyProps, false, ['sign']) + .then((privKey) => subtle.sign(ecdsaSignProps, privKey, new Uint8Array(hash))) + return Buffer.from(binSig, 'binary').toString('base64') + } catch (e) { + Gun.log(e) + throw e + } + }, + async verify(data, pub, sig) { + try { + const jwk = keysToEcdsaJwk(pub) + const key = await subtle.importKey(...jwk, ecdsaKeyProps, false, ['verify']) + const hash = await sha256hash(data) + const ss = new Uint8Array(Buffer.from(sig, 'base64')) + return await subtle.verify(ecdsaSignProps, key, ss, new Uint8Array(hash)) + } catch (e) { + Gun.log(e) + throw e + } + }, + async enc(data, priv) { + try { + const rands = { s: getRandomBytes(8), iv: getRandomBytes(16) } + const r = Object.keys(rands) + .reduce((obj, key) => Object.assign(obj, { [key]: rands[key].toString('hex') }), {}) + try { + data = (data.slice && data) || JSON.stringify(data) + } catch(e) {} //eslint-disable-line no-empty + const ct = await recallCryptoKey(priv, rands.s) + .then((aesKey) => subtle.encrypt({ // Keeping aesKey scope as private as possible... + name: 'AES-CBC', iv: new Uint8Array(rands.iv) + }, aesKey, new TextEncoder().encode(data))) + Object.assign(r, { ct: Buffer.from(ct, 'binary').toString('base64') }) + return JSON.stringify(r) + } catch (e) { + Gun.log(e) + throw e + } + }, + async dec(data, priv) { + try { + const { s, iv, ct } = parseProps(data) + const mm = { s, iv, ct } + const rands = [ 'iv', 's' ].reduce((obj, key) => Object.assign(obj, { + [key]: new Uint8Array(Buffer.from(mm[key], 'hex')) + }), {}) + const binCt = await recallCryptoKey(priv, rands.s) + .then((aesKey) => subtle.decrypt({ // Keeping aesKey scope as private as possible... + name: 'AES-CBC', iv: rands.iv + }, aesKey, new Uint8Array(Buffer.from(mm.ct, 'base64')))) + return parseProps(new TextDecoder('utf8').decode(binCt)) + } catch (e) { + Gun.log(e) + throw e + } + }, + async write(data, keys) { + try { + // TODO: something's bugging double 'SEA[]' treatment to mm... + let m = data + if (m && m.slice && 'SEA[' === m.slice(0, 4)) { + return m + } + if (data && data.slice) { + // Needs to remove previous signature envelope + while ('SEA[' === m.slice(0, 4)) { + try { + m = JSON.parse(m.slice(3))[0] + } catch (e){ + break + } + } + } + m = (m && m.slice) ? m : JSON.stringify(m) + const signature = await SEA.sign(m, keys) + return `SEA${JSON.stringify([ m, signature ])}` + } catch (e) { + Gun.log(e) + throw e + } + }, + async read(data, pub) { + try { + let d + if (!data) { + return false === pub ? data : undefined + } + if (!data.slice || 'SEA[' !== data.slice(0, 4)) { + return false === pub ? data : undefined + } + let m = parseProps(data.slice(3)) || '' + d = parseProps(m[0]) + if (false === pub) { + return d + } + return (await SEA.verify(m[0], pub, m[1])) ? d : undefined + } catch (e) { + Gun.log(e) + throw e + } } } + // Usage of the SEA object changed! Now use like this: + // const gun = new Gun() + // const SEA = gun.SEA() + //Gun.SEA = () => SEA + Gun.SEA = SEA + + // all done! + // 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. + // SEA should be a full suite that is easy and seamless to use. + // Again, scroll naer the top, where I provide an EXAMPLE of how to create a user and sign in. + // Once logged in, the rest of the code you just read handled automatically signing/validating data. + // But all other behavior needs to be equally easy, like opinionated ways of + // Adding friends (trusted public keys), sending private messages, etc. + // Cheers! Tell me what you think. - var doIt = function(resolve, reject){ - // opts = { hook: function({ iat, exp, alias, proof }) } - // iat == Date.now() when issued, exp == seconds to expire from iat + try { + module.exports = SEA + } catch (e) {} //eslint-disable-line no-empty + })(USE, './sea'); + + ;USE(function(module){ + const Gun = (typeof window !== 'undefined' ? window : global).Gun || require('gun/gun') + // This is internal func queries public key(s) for alias. + const queryGunAliases = (alias, root) => new Promise((resolve, reject) => { + // load all public keys associated with the username alias we want to log in with. + root.get(`alias/${alias}`).get((rat, rev) => { + rev.off() + if (!rat.put) { + // if no user, don't do anything. + const err = 'No user!' + Gun.log(err) + return reject({ err }) + } + // then figuring out all possible candidates having matching username + let aliases = [] + let c = 0 + // TODO: how about having real chainable map without callback ? + Gun.obj.map(rat.put, (at, pub) => { + if (!pub.slice || 'pub/' !== pub.slice(0, 4)) { + // TODO: ... this would then be .filter((at, pub)) + return + } + ++c + // grab the account associated with this public key. + root.get(pub).get((at, ev) => { + pub = pub.slice(4) + ev.off() + --c + if (at.put){ + aliases.push({ pub, at }) + } + if (!c && (c = -1)) { + resolve(aliases) + } + }) + }) + if (!c) { + reject({ err: 'Public key does not exist!' }) + } + }) + }) + module.exports = queryGunAliases; + })(USE, './query'); + + ;USE(function(module){ + // TODO: BUG! `SEA` needs to be USED! + const Gun = (typeof window !== 'undefined' ? window : global).Gun || require('gun/gun') + var SEA = USE('./sea'); + var queryGunAliases = USE('./query'); + var parseProps = USE('./parse'); + // This is internal User authentication func. + const authenticate = async (alias, pass, root) => { + // load all public keys associated with the username alias we want to log in with. + const aliases = (await queryGunAliases(alias, root)) + .filter(({ pub, at: { put } = {} } = {}) => !!pub && !!put) + // Got any? + if (!aliases.length) { + throw { err: 'Public key does not exist!' } + } + let err + // then attempt to log into each one until we find ours! + // (if two users have the same username AND the same password... that would be bad) + const [ user ] = await Promise.all(aliases.map(async ({ at, pub }) => { + // attempt to PBKDF2 extend the password with the salt. (Verifying the signature gives us the plain text salt.) + const auth = parseProps(at.put.auth) + // NOTE: aliasquery uses `gun.get` which internally SEA.read verifies the data for us, so we do not need to re-verify it here. + // SEA.read(at.put.auth, pub).then(function(auth){ + try { + const proof = await SEA.proof(pass, auth.salt) + const props = { pub, proof, at } + // the proof of work is evidence that we've spent some time/effort trying to log in, this slows brute force. + /* + MARK TO @mhelander : pub vs epub!??? + */ + const { salt } = auth + const sea = await SEA.dec(auth.auth, { pub, key: proof }) + if (!sea) { + err = 'Failed to decrypt secret!' + return + } + // now we have AES decrypted the private key, from when we encrypted it with the proof at registration. + // if we were successful, then that meanswe're logged in! + const { priv, epriv } = sea + const { epub } = at.put + // TODO: 'salt' needed? + err = null + return Object.assign(props, { priv, salt, epub, epriv }) + } catch (e) { + err = 'Failed to decrypt secret!' + throw { err } + } + })) + + if (!user) { + throw { err: err || 'Public key does not exist!' } + } + return user + } + module.exports = authenticate; + })(USE, './authenticate'); + + ;USE(function(module){ + // TODO: BUG! `SEA` needs to be USED! + const Gun = (typeof window !== 'undefined' ? window : global).Gun || require('gun/gun') + var authsettings = USE('./settings'); + var seaIndexedDb = USE('./indexed').scope; + // This updates sessionStorage & IndexedDB to persist authenticated "session" + const updateStorage = (proof, key, pin) => async (props) => { + if (!Gun.obj.has(props, 'alias')) { + return // No 'alias' - we're done. + } + if (authsettings.validity && proof && Gun.obj.has(props, 'iat')) { + props.proof = proof + delete props.remember // Not stored if present + + const { alias, alias: id } = props + const remember = { alias, pin } + + try { + const signed = await SEA.write(JSON.stringify(remember), key) + + sessionStorage.setItem('user', alias) + sessionStorage.setItem('remember', signed) + + const encrypted = await SEA.enc(props, pin) + + if (encrypted) { + const auth = await SEA.write(encrypted, key) + await seaIndexedDb.wipe() + await seaIndexedDb.put(id, { auth }) + } + + return props + } catch (err) { + throw { err: 'Session persisting failed!' } + } + } + + // Wiping IndexedDB completely when using random PIN + await seaIndexedDb.wipe() + // And remove sessionStorage data + sessionStorage.removeItem('user') + sessionStorage.removeItem('remember') + + return props + } + module.exports = updateStorage; + })(USE, './update'); + + ;USE(function(module){ + const Gun = (typeof window !== 'undefined' ? window : global).Gun || require('gun/gun') + var Buffer = USE('./buffer'); + var authsettings = USE('./settings'); + var updateStorage = USE('./update'); + // This internal func persists User authentication if so configured + const authPersist = async (user, proof, opts) => { + // opts = { pin: 'string' } + // no opts.pin then uses random PIN // How this works: // called when app bootstraps, with wanted options // IF authsettings.validity === 0 THEN no remember-me, ever // IF PIN then signed 'remember' to window.sessionStorage and 'auth' to IndexedDB - authsettings.validity = typeof validity !== 'undefined' ? validity - : _initial_authsettings.validity; - authsettings.hook = (Gun.obj.has(opts, 'hook') && typeof opts.hook === 'function') - ? opts.hook : _initial_authsettings.hook; - // All is good. Should we do something more with actual recalled data? - authrecall(root).then(resolve).catch(function(e){ - var err = 'No session!'; - Gun.log(err); - resolve({err: (e && e.err) || err}); - }); - }; - if(callback){doIt(callback, callback)} else { return new Promise(doIt) } - }; - User.alive = function(cb){ - var root = this.back(-1); - var doIt = function(resolve, reject){ - authrecall(root).then(function(){ - // All is good. Should we do something more with actual recalled data? - resolve(root._.user._); - }).catch(function(e){ - var err = 'No session!'; - Gun.log(err); - reject({err: err}); - }); - }; - if(cb){doIt(cb, cb)} else { return new Promise(doIt) } - }; + const pin = Buffer.from( + (Gun.obj.has(opts, 'pin') && opts.pin) || Gun.text.random(10), + 'utf8' + ).toString('base64') - // After we have a GUN extension to make user registration/login easy, we then need to handle everything else. + const { alias } = user || {} + const { validity: exp } = authsettings // seconds // @mhelander what is `exp`??? - // We do this with a GUN adapter, we first listen to when a gun instance is created (and when its options change) - Gun.on('opt', function(at){ - if(!at.sea){ // only add SEA once per instance, on the "at" context. - at.sea = {own: {}}; - var uuid = at.opt.uuid || Gun.state.lex; - at.opt.uuid = function(cb){ - if(!cb){ return } - var id = uuid(), pair = at.user && (at.user._).sea; - if(!pair){ return id } - SEA.sign(id, pair).then(function(sig){ - cb(null, id + '~' + sig); - }).catch(function(e){cb(e)}); + if (proof && alias && exp) { + const iat = Math.ceil(Date.now() / 1000) // seconds + const remember = Gun.obj.has(opts, 'pin') || undefined // for hook - not stored + const props = authsettings.hook({ alias, iat, exp, remember }) + const { pub, epub, sea: { priv, epriv } } = user + const key = { pub, priv, epub, epriv } + if (props instanceof Promise) { + const asyncProps = await props.then() + return await updateStorage(proof, key, pin)(asyncProps) + } + return await updateStorage(proof, key, pin)(props) } - at.on('in', security, at); // now listen to all input data, acting as a firewall. - at.on('out', signature, at); // and output listeners, to encrypt outgoing data. - at.on('node', each, at); + return await updateStorage()({ alias: 'delete' }) } - this.to.next(at); // make sure to call the "next" middleware adapter. - }); + module.exports = authPersist; + })(USE, './persist'); - // Alright, this next adapter gets run at the per node level in the graph database. - // This will let us verify that every property on a node has a value signed by a public key we trust. - // If the signature does not match, the data is just `undefined` so it doesn't get passed on. - // If it does match, then we transform the in-memory "view" of the data into its plain value (without the signature). - // Now NOTE! Some data is "system" data, not user data. Example: List of public keys, aliases, etc. - // This data is self-enforced (the value can only match its ID), but that is handled in the `security` function. - // From the self-enforced data, we can see all the edges in the graph that belong to a public key. - // Example: pub/ASDF is the ID of a node with ASDF as its public key, signed alias and salt, and - // its encrypted private key, but it might also have other signed values on it like `profile = ` edge. - // Using that directed edge's ID, we can then track (in memory) which IDs belong to which keys. - // Here is a problem: Multiple public keys can "claim" any node's ID, so this is dangerous! - // This means we should ONLY trust our "friends" (our key ring) public keys, not any ones. - // I have not yet added that to SEA yet in this alpha release. That is coming soon, but beware in the meanwhile! - function each(msg){ // TODO: Warning: Need to switch to `gun.on('node')`! Do not use `Gun.on('node'` in your apps! - // NOTE: THE SECURITY FUNCTION HAS ALREADY VERIFIED THE DATA!!! - // WE DO NOT NEED TO RE-VERIFY AGAIN, JUST TRANSFORM IT TO PLAINTEXT. - var to = this.to, vertex = (msg.gun._).put, c = 0, d; - Gun.node.is(msg.put, function(val, key, node){ c++; // for each property on the node - SEA.read(val, false).then(function(data){ c--; // false just extracts the plain data. - node[key] = val = data; // transform to plain value. - if(d && !c && (c = -1)){ to.next(msg) } - }); - }); - d = true; - if(d && !c){ to.next(msg) } - return; - /*var to = this.to, ctx = this.as; - var own = ctx.sea.own, soul = msg.get, c = 0; - var pub = own[soul] || soul.slice(4), vertex = (msg.gun._).put; - Gun.node.is(msg.put, function(val, key, node){ c++; // for each property on the node. - SEA.read(val, pub).then(function(data){ c--; - vertex[key] = node[key] = val = data; // verify signature and get plain value. - if(val && val['#'] && (key = Gun.val.rel.is(val))){ // if it is a relation / edge - if('alias/' !== soul.slice(0,6)){ own[key] = pub; } // associate the public key with a node if it is itself - } - if(!c && (c = -1)){ to.next(msg) } - }); - }); - if(!c){ to.next(msg) }*/ - } - - // signature handles data output, it is a proxy to the security function. - function signature(msg){ - if(msg.user){ - return this.to.next(msg); - } - var ctx = this.as; - msg.user = ctx.user; - security.call(this, msg); - } - - // okay! The security function handles all the heavy lifting. - // It needs to deal read and write of input and output of system data, account/public key data, and regular data. - // This is broken down into some pretty clear edge cases, let's go over them: - function security(msg){ - var at = this.as, sea = at.sea, to = this.to; - if(msg.get){ - // if there is a request to read data from us, then... - var soul = msg.get['#']; - if(soul){ // for now, only allow direct IDs to be read. - if('alias' === soul){ // Allow reading the list of usernames/aliases in the system? - return to.next(msg); // yes. - } else - if('alias/' === soul.slice(0,6)){ // Allow reading the list of public keys associated with an alias? - return to.next(msg); // yes. - } else { // Allow reading everything? - return to.next(msg); // yes // TODO: No! Make this a callback/event that people can filter on. - } + ;USE(function(module){ + var authPersist = USE('./persist'); + // This internal func finalizes User authentication + const finalizeLogin = async (alias, key, root, opts) => { + const { user } = root._ + // add our credentials in-memory only to our root gun instance + user._ = key.at.gun._ + // so that way we can use the credentials to encrypt/decrypt data + user._.is = user.is = {} + // that is input/output through gun (see below) + const { pub, priv, epub, epriv } = key + Object.assign(user._, { alias, pub, epub, sea: { pub, priv, epub, epriv } }) + //console.log("authorized", user._); + // persist authentication + await authPersist(user._, key.proof, opts) + // emit an auth event, useful for page redirects and stuff. + try { + root._.on('auth', user._) + } catch (e) { + console.log('Your \'auth\' callback crashed with:', e) } + // returns success with the user data credentials. + return user._ } - if(msg.put){ - // potentially parallel async operations!!! - var check = {}, on = Gun.on(), each = {}, u; - each.node = function(node, soul){ - if(Gun.obj.empty(node, '_')){ return check['node'+soul] = 0 } // ignore empty updates, don't reject them. - Gun.obj.map(node, each.way, {soul: soul, node: node}); - }; - each.way = function(val, key){ - var soul = this.soul, node = this.node, tmp; - if('_' === key){ return } // ignore meta data - if('alias' === soul){ // special case for shared system data, the list of aliases. - each.alias(val, key, node, soul); return; - } - if('alias/' === soul.slice(0,6)){ // special case for shared system data, the list of public keys for an alias. - each.pubs(val, key, node, soul); return; - } - if('pub/' === soul.slice(0,4)){ // special case, account data for a public key. - each.pub(val, key, node, soul, soul.slice(4), msg.user); return; - } - each.any(val, key, node, soul, msg.user); return; - return each.end({err: "No other data allowed!"}); - /*if(!(tmp = at.user)){ return } - if(soul.slice(4) === (tmp = tmp._).pub){ // not a special case, if we are logged in and have outbound data on us. - each.user(val, key, node, soul, { - pub: tmp.pub, priv: tmp.sea.priv, epub: tmp.sea.epub, epriv: tmp.sea.epriv - }); - } - if((tmp = sea.own[soul])){ // not special case, if we receive an update on an ID associated with a public key, then - each.own(val, key, node, soul, tmp); - }*/ - }; - each.alias = function(val, key, node, soul){ // Example: {_:#alias, alias/alice: {#alias/alice}} - if(!val){ return each.end({err: "Data must exist!"}) } // data MUST exist - if('alias/'+key === Gun.val.rel.is(val)){ return check['alias'+key] = 0 } // in fact, it must be EXACTLY equal to itself - each.end({err: "Mismatching alias."}); // if it isn't, reject. - }; - each.pubs = function(val, key, node, soul){ // Example: {_:#alias/alice, pub/asdf: {#pub/asdf}} - if(!val){ return each.end({err: "Alias must exist!"}) } // data MUST exist - if(key === Gun.val.rel.is(val)){ return check['pubs'+soul+key] = 0 } // and the ID must be EXACTLY equal to its property - each.end({err: "Alias must match!"}); // that way nobody can tamper with the list of public keys. - }; - each.pub = function(val, key, node, soul, pub, user){ // Example: {_:#pub/asdf, hello:SEA['world',fdsa]} - if('pub' === key){ - if(val === pub){ return (check['pub'+soul+key] = 0) } // the account MUST match `pub` property that equals the ID of the public key. - return each.end({err: "Account must match!"}); - } - check['user'+soul+key] = 1; - if(user && (user = user._) && user.sea && pub === user.pub){ - var id = Gun.text.random(3); - SEA.write(val, Gun.obj.to(user.sea, {pub: user.pub, epub: user.epub}), function(data){ var rel; - if(rel = Gun.val.rel.is(val)){ - (at.sea.own[rel] = at.sea.own[rel] || {})[pub] = true; + module.exports = finalizeLogin; + })(USE, './login'); + + ;USE(function(module){ + // TODO: BUG! `SEA` needs to be USED! + const Gun = (typeof window !== 'undefined' ? window : global).Gun || require('gun/gun') + var Buffer = USE('./buffer'); + var authsettings = USE('./settings'); + var seaIndexedDb = USE('./indexed').scope; + var queryGunAliases = USE('./query'); + var parseProps = USE('./parse'); + var updateStorage = USE('./update'); + // This internal func recalls persisted User authentication if so configured + const authRecall = async (root, authprops) => { + // window.sessionStorage only holds signed { alias, pin } !!! + const remember = authprops || sessionStorage.getItem('remember') + const { alias = sessionStorage.getItem('user'), pin: pIn } = authprops || {} // @mhelander what is pIn? + const pin = pIn && Buffer.from(pIn, 'utf8').toString('base64') + // Checks for existing proof, matching alias and expiration: + const checkRememberData = async ({ proof, alias: aLias, iat, exp, remember }) => { + if (!!proof && alias === aLias) { + const checkNotExpired = (args) => { + if (Math.floor(Date.now() / 1000) < (iat + args.exp)) { + // No way hook to update 'iat' + return Object.assign(args, { iat, proof }) + } else { + Gun.log('Authentication expired!') } - node[key] = data; - check['user'+soul+key] = 0; - each.end({ok: 1}); - }); - return; - } - SEA.read(val, pub).then(function(data){ var rel, tmp; - if(u === data){ // make sure the signature matches the account it claims to be on. - return each.end({err: "Unverified data."}); // reject any updates that are signed with a mismatched account. } - if((rel = Gun.val.rel.is(data)) && (tmp = rel.split('~')) && 2 === tmp.length){ - SEA.verify(tmp[0], pub, tmp[1], function(ok){ - if(!ok){ return each.end({err: "Signature did not match account."}) } - (at.sea.own[rel] = at.sea.own[rel] || {})[pub] = true; + // We're not gonna give proof to hook! + const hooked = authsettings.hook({ alias, iat, exp, remember }) + return ((hooked instanceof Promise) + && await hooked.then(checkNotExpired)) || checkNotExpired(hooked) + } + } + const readAndDecrypt = async (data, pub, key) => + parseProps(await SEA.dec(await SEA.read(data, pub), key)) + + // Already authenticated? + if (root._.user + && Gun.obj.has(root._.user._, 'pub') + && Gun.obj.has(root._.user._, 'sea')) { + return root._.user._ // Yes, we're done here. + } + // No, got persisted 'alias'? + if (!alias) { + throw { err: 'No authentication session found!' } + } + // Yes, got persisted 'remember'? + if (!remember) { + throw { // And return proof if for matching alias + err: (await seaIndexedDb.get(alias, 'auth') && authsettings.validity + && 'Missing PIN and alias!') || 'No authentication session found!' + } + } + // Yes, let's get (all?) matching aliases + const aliases = (await queryGunAliases(alias, root)) + .filter(({ pub } = {}) => !!pub) + // Got any? + if (!aliases.length) { + throw { err: 'Public key does not exist!' } + } + let err + // Yes, then attempt to log into each one until we find ours! + // (if two users have the same username AND the same password... that would be bad) + const [ { key, at, proof, pin: newPin } = {} ] = await Promise + .all(aliases.filter(({ at: { put } = {} }) => !!put) + .map(async ({ at, pub }) => { + const readStorageData = async (args) => { + const props = args || parseProps(await SEA.read(remember, pub, true)) + let { pin, alias: aLias } = props + + const data = (!pin && alias === aLias) + // No PIN, let's try short-term proof if for matching alias + ? await checkRememberData(props) + // Got PIN so get IndexedDB secret if signature is ok + : await checkRememberData(await readAndDecrypt(await seaIndexedDb.get(alias, 'auth'), pub, pin)) + pin = pin || data.pin + delete data.pin + return { pin, data } + } + // got pub, try auth with pin & alias :: or unwrap Storage data... + const { data, pin: newPin } = await readStorageData(pin && { pin, alias }) + const { proof } = data || {} + + if (!proof) { + if (!data) { + err = 'No valid authentication session found!' + return + } + try { // Wipes IndexedDB silently + await updateStorage()(data) + } catch (e) {} //eslint-disable-line no-empty + err = 'Expired session!' + return + } + + try { // auth parsing or decryption fails or returns empty - silently done + const { auth } = at.put.auth + const sea = await SEA.dec(auth, proof) + if (!sea) { + err = 'Failed to decrypt private key!' + return + } + const { priv, epriv } = sea + const { epub } = at.put + // Success! we've found our private data! + err = null + return { proof, at, pin: newPin, key: { pub, priv, epriv, epub } } + } catch (e) { + err = 'Failed to decrypt private key!' + return + } + }).filter((props) => !!props)) + + if (!key) { + throw { err: err || 'Public key does not exist!' } + } + + // now we have AES decrypted the private key, + // if we were successful, then that means we're logged in! + try { + await updateStorage(proof, key, newPin || pin)(key) + + const user = Object.assign(key, { at, proof }) + const pIN = newPin || pin + + const pinProp = pIN && { pin: Buffer.from(pIN, 'base64').toString('utf8') } + + return await finalizeLogin(alias, user, root, pinProp) + } catch (e) { // TODO: right log message ? + Gun.log('Failed to finalize login with new password!') + const { err = '' } = e || {} + throw { err: `Finalizing new password login failed! Reason: ${err}` } + } + } + module.exports = authRecall; + })(USE, './recall'); + + ;USE(function(module){ + var authPersist = USE('./persist'); + var authsettings = USE('./settings'); + var seaIndexedDb = USE('./indexed').scope; + var seaIndexedDb = USE('./indexed').scope; + // This internal func executes logout actions + const authLeave = async (root, alias = root._.user._.alias) => { + const { user = { _: {} } } = root._ + root._.user = null + // Removes persisted authentication & CryptoKeys + try { + await authPersist({ alias }) + } catch (e) {} //eslint-disable-line no-empty + // TODO: is this correct way to 'logout' user from Gun.User ? + [ 'alias', 'sea', 'pub' ].map((key) => delete user._[key]) + user._.is = user.is = {} + // Let's use default + root.user(); + return { ok: 0 } + } + module.exports = authLeave; + })(USE, './leave'); + + ;USE(function(module){ + // How does it work? + // TODO: Bug! Need to include SEA! + const Gun = (typeof window !== 'undefined' ? window : global).Gun || require('gun/gun') + var SEA = USE('./sea'); + var authRecall = USE('./recall'); + var authenticate = USE('./authenticate'); + var finalizeLogin = USE('./login'); + // let's extend the gun chain with a `user` function. + // only one user can be logged in at a time, per gun instance. + Gun.chain.user = function() { + const root = this.back(-1) // always reference the root gun instance. + let user = root._.user || (root._.user = root.chain()); // create a user context. + // then methods... + [ 'create', // factory + 'auth', // login + 'leave', // logout + 'delete', // account delete + 'recall', // existing auth boostrap + 'alive' // keep/check auth validity + ].map((method)=> user[method] = User[method]) + return user // return the user! + } + function User(){} + // Well first we have to actually create a user. That is what this function does. + Object.assign(User, { + async create(username, pass, cb) { + const root = this.back(-1) + return 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. + if(cb){ resolve = reject = cb } + root.get(`alias/${username}`).get(async (at, ev) => { + ev.off() + 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. + const err = 'User already created!' + Gun.log(err) + return reject({ err }) + } + const salt = Gun.text.random(64) + // pseudo-randomly create a salt, then use CryptoJS's PBKDF2 function to extend the password with it. + try { + const proof = await SEA.proof(pass, salt) + // this will take some short amount of time to produce a proof, which slows brute force attacks. + const pairs = await SEA.pair() + // now we have generated a brand new ECDSA key pair for the user account. + const { pub, priv, epriv } = pairs + // the user's public key doesn't need to be signed. But everything else needs to be signed with it! + const alias = await SEA.write(username, pairs) + const epub = await SEA.write(pairs.epub, pairs) + // to keep the private key safe, we AES encrypt it with the proof of work! + const auth = await SEA.enc({ priv, epriv }, { pub: pairs.epub, key: proof }) + .then((auth) => // TODO: So signedsalt isn't needed? + // SEA.write(salt, pairs).then((signedsalt) => + SEA.write({ salt, auth }, pairs) + // ) + ).catch((e) => { Gun.log('SEA.en or SEA.write calls failed!'); reject(e) }) + const user = { alias, pub, epub, auth } + const tmp = `pub/${pairs.pub}` + // awesome, now we can actually save the user with their public key as their ID. + root.get(tmp).put(user) + // 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))) + // callback that the user has been created. (Note: ok = 0 because we didn't wait for disk to ack) + setTimeout(() => { 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) { + Gun.log('SEA.create failed!') + reject(e) + } + }) + }) + }, + // now that we have created a user, we want to authenticate them! + async auth(alias, pass, cb, opts) { + if(cb && !(cb instanceof Function)){ opts = cb } + const { pin, newpass } = opts || {} + const root = this.back(-1) + + if (!pass && pin) { + try { + return await authRecall(root, { alias, pin }) + } catch (e) { + throw { err: 'Auth attempt failed! Reason: No session data for alias & PIN' } + } + } + + const putErr = (msg) => (e) => { + const { message, err = message || '' } = e + Gun.log(msg) + var error = { err: `${msg} Reason: ${err}` } + if(cb){ cb(error) } + throw error; + } + + try { + const keys = await authenticate(alias, pass, root) + if (!keys) { + return putErr('Auth attempt failed!')({ message: 'No keys' }) + } + const { pub, priv, epub, epriv } = keys + // we're logged in! + if (newpass) { + // password update so encrypt private key using new pwd + salt + try { + const salt = Gun.text.random(64) + const encSigAuth = await SEA.proof(newpass, salt) + .then((key) => + SEA.enc({ priv, epriv }, { pub, key, set: true }) + .then((auth) => SEA.write({ salt, auth }, keys)) + ) + const signedEpub = await SEA.write(epub, keys) + const signedAlias = await SEA.write(alias, keys) + const user = { + pub, + alias: signedAlias, + auth: encSigAuth, + epub: signedEpub + } + // awesome, now we can update the user using public key ID. + root.get(`pub/${user.pub}`).put(user) + // then we're done + var login = finalizeLogin(alias, keys, root, { pin }) + login.catch(putErr('Failed to finalize login with new password!')) + if(cb){ cb(login) } + return login; + } catch (e) { + putErr('Password set attempt failed!')(e) + } + } else { + var login = finalizeLogin(alias, keys, root, { pin }) + login.catch(putErr('Finalizing login failed!')) + if(cb){ cb(login) } + return login; + } + } catch (e) { + putErr('Auth attempt failed!')(e) + } + }, + async leave() { + return await authLeave(this.back(-1)) + }, + // If authenticated user wants to delete his/her account, let's support it! + async delete(alias, pass) { + const root = this.back(-1) + try { + const { pub } = await authenticate(alias, pass, root) + await authLeave(root, alias) + // Delete user data + root.get(`pub/${pub}`).put(null) + // Wipe user data from memory + const { user = { _: {} } } = root._; + // TODO: is this correct way to 'logout' user from Gun.User ? + [ 'alias', 'sea', 'pub' ].map((key) => delete user._[key]) + user._.is = user.is = {} + root.user() + return { ok: 0 } // TODO: proper return codes??? + } catch (e) { + Gun.log('User.delete failed! Error:', e) + throw e // TODO: proper error codes??? + } + }, + // If authentication is to be remembered over reloads or browser closing, + // set validity time in minutes. + async recall(setvalidity, options) { + const root = this.back(-1) + + let validity + let opts + + if (!Gun.val.is(setvalidity)) { + opts = setvalidity + validity = _initial_authsettings.validity + } else { + opts = options + validity = setvalidity * 60 // minutes to seconds + } + + try { + // opts = { hook: function({ iat, exp, alias, proof }) } + // iat == Date.now() when issued, exp == seconds to expire from iat + // How this works: + // called when app bootstraps, with wanted options + // IF authsettings.validity === 0 THEN no remember-me, ever + // IF PIN then signed 'remember' to window.sessionStorage and 'auth' to IndexedDB + authsettings.validity = typeof validity !== 'undefined' + ? validity : _initial_authsettings.validity + authsettings.hook = (Gun.obj.has(opts, 'hook') && typeof opts.hook === 'function') + ? opts.hook : _initial_authsettings.hook + // All is good. Should we do something more with actual recalled data? + return await authRecall(root) + } catch (e) { + const err = 'No session!' + Gun.log(err) + // NOTE! It's fine to resolve recall with reason why not successful + // instead of rejecting... + return { err: (e && e.err) || err } + } + }, + async alive() { + const root = this.back(-1) + try { + // All is good. Should we do something more with actual recalled data? + await authRecall(root) + return root._.user._ + } catch (e) { + const err = 'No session!' + Gun.log(err) + throw { err } + } + } + }) + Gun.chain.trust = function(user) { + // TODO: BUG!!! SEA `node` read listener needs to be async, which means core needs to be async too. + //gun.get('alice').get('age').trust(bob); + if (Gun.is(user)) { + user.get('pub').get((ctx, ev) => { + console.log(ctx, ev) + }) + } + } + + module.exports = User; + })(USE, './user'); + + ;USE(function(module){ + const Gun = (typeof window !== 'undefined' ? window : global).Gun || require('gun/gun') + var SEA = USE('./sea'); + // 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) + Gun.on('opt', function(at){ + if(!at.sea){ // only add SEA once per instance, on the "at" context. + at.sea = {own: {}}; + var uuid = at.opt.uuid || Gun.state.lex; + at.opt.uuid = function(cb){ // TODO: consider async/await and drop callback pattern... + if(!cb){ return } + var id = uuid(), pair = at.user && (at.user._).sea; + if(!pair){ return id } + SEA.sign(id, pair).then(function(sig){ + cb(null, id + '~' + sig); + }).catch(function(e){cb(e)}); + } + at.on('in', security, at); // now listen to all input data, acting as a firewall. + at.on('out', signature, at); // and output listeners, to encrypt outgoing data. + at.on('node', each, at); + } + this.to.next(at); // make sure to call the "next" middleware adapter. + }); + + // Alright, this next adapter gets run at the per node level in the graph database. + // This will let us verify that every property on a node has a value signed by a public key we trust. + // If the signature does not match, the data is just `undefined` so it doesn't get passed on. + // If it does match, then we transform the in-memory "view" of the data into its plain value (without the signature). + // Now NOTE! Some data is "system" data, not user data. Example: List of public keys, aliases, etc. + // This data is self-enforced (the value can only match its ID), but that is handled in the `security` function. + // From the self-enforced data, we can see all the edges in the graph that belong to a public key. + // Example: pub/ASDF is the ID of a node with ASDF as its public key, signed alias and salt, and + // its encrypted private key, but it might also have other signed values on it like `profile = ` edge. + // Using that directed edge's ID, we can then track (in memory) which IDs belong to which keys. + // Here is a problem: Multiple public keys can "claim" any node's ID, so this is dangerous! + // This means we should ONLY trust our "friends" (our key ring) public keys, not any ones. + // I have not yet added that to SEA yet in this alpha release. That is coming soon, but beware in the meanwhile! + function each(msg){ // TODO: Warning: Need to switch to `gun.on('node')`! Do not use `Gun.on('node'` in your apps! + // NOTE: THE SECURITY FUNCTION HAS ALREADY VERIFIED THE DATA!!! + // WE DO NOT NEED TO RE-VERIFY AGAIN, JUST TRANSFORM IT TO PLAINTEXT. + var to = this.to, vertex = (msg.gun._).put, c = 0, d; + Gun.node.is(msg.put, function(val, key, node){ c++; // for each property on the node + // TODO: consider async/await use here... + SEA.read(val, false).then(function(data){ c--; // false just extracts the plain data. + node[key] = val = data; // transform to plain value. + if(d && !c && (c = -1)){ to.next(msg) } + }); + }); + d = true; + if(d && !c){ to.next(msg) } + return; + /*var to = this.to, ctx = this.as; + var own = ctx.sea.own, soul = msg.get, c = 0; + var pub = own[soul] || soul.slice(4), vertex = (msg.gun._).put; + Gun.node.is(msg.put, function(val, key, node){ c++; // for each property on the node. + SEA.read(val, pub).then(function(data){ c--; + vertex[key] = node[key] = val = data; // verify signature and get plain value. + if(val && val['#'] && (key = Gun.val.rel.is(val))){ // if it is a relation / edge + if('alias/' !== soul.slice(0,6)){ own[key] = pub; } // associate the public key with a node if it is itself + } + if(!c && (c = -1)){ to.next(msg) } + }); + }); + if(!c){ to.next(msg) }*/ + } + + // signature handles data output, it is a proxy to the security function. + function signature(msg){ + if(msg.user){ + return this.to.next(msg); + } + var ctx = this.as; + msg.user = ctx.user; + security.call(this, msg); + } + + // okay! The security function handles all the heavy lifting. + // It needs to deal read and write of input and output of system data, account/public key data, and regular data. + // This is broken down into some pretty clear edge cases, let's go over them: + function security(msg){ + var at = this.as, sea = at.sea, to = this.to; + if(msg.get){ + // if there is a request to read data from us, then... + var soul = msg.get['#']; + if(soul){ // for now, only allow direct IDs to be read. + if('alias' === soul){ // Allow reading the list of usernames/aliases in the system? + return to.next(msg); // yes. + } else + if('alias/' === soul.slice(0,6)){ // Allow reading the list of public keys associated with an alias? + return to.next(msg); // yes. + } else { // Allow reading everything? + return to.next(msg); // yes // TODO: No! Make this a callback/event that people can filter on. + } + } + } + if(msg.put){ + // potentially parallel async operations!!! + var check = {}, on = Gun.on(), each = {}, u; + each.node = function(node, soul){ + if(Gun.obj.empty(node, '_')){ return check['node'+soul] = 0 } // ignore empty updates, don't reject them. + Gun.obj.map(node, each.way, {soul: soul, node: node}); + }; + each.way = function(val, key){ + var soul = this.soul, node = this.node, tmp; + if('_' === key){ return } // ignore meta data + if('alias' === soul){ // special case for shared system data, the list of aliases. + each.alias(val, key, node, soul); return; + } + if('alias/' === soul.slice(0,6)){ // special case for shared system data, the list of public keys for an alias. + each.pubs(val, key, node, soul); return; + } + if('pub/' === soul.slice(0,4)){ // special case, account data for a public key. + each.pub(val, key, node, soul, soul.slice(4), msg.user); return; + } + each.any(val, key, node, soul, msg.user); return; + return each.end({err: "No other data allowed!"}); + /*if(!(tmp = at.user)){ return } + if(soul.slice(4) === (tmp = tmp._).pub){ // not a special case, if we are logged in and have outbound data on us. + each.user(val, key, node, soul, { + pub: tmp.pub, priv: tmp.sea.priv, epub: tmp.sea.epub, epriv: tmp.sea.epriv + }); + } + if((tmp = sea.own[soul])){ // not special case, if we receive an update on an ID associated with a public key, then + each.own(val, key, node, soul, tmp); + }*/ + }; + each.alias = function(val, key, node, soul){ // Example: {_:#alias, alias/alice: {#alias/alice}} + if(!val){ return each.end({err: "Data must exist!"}) } // data MUST exist + if('alias/'+key === Gun.val.rel.is(val)){ return check['alias'+key] = 0 } // in fact, it must be EXACTLY equal to itself + each.end({err: "Mismatching alias."}); // if it isn't, reject. + }; + each.pubs = function(val, key, node, soul){ // Example: {_:#alias/alice, pub/asdf: {#pub/asdf}} + if(!val){ return each.end({err: "Alias must exist!"}) } // data MUST exist + if(key === Gun.val.rel.is(val)){ return check['pubs'+soul+key] = 0 } // and the ID must be EXACTLY equal to its property + each.end({err: "Alias must match!"}); // that way nobody can tamper with the list of public keys. + }; + each.pub = function(val, key, node, soul, pub, user){ // Example: {_:#pub/asdf, hello:SEA['world',fdsa]} + if('pub' === key){ + if(val === pub){ return (check['pub'+soul+key] = 0) } // the account MUST match `pub` property that equals the ID of the public key. + return each.end({err: "Account must match!"}); + } + check['user'+soul+key] = 1; + if(user && (user = user._) && user.sea && pub === user.pub){ + var id = Gun.text.random(3); + SEA.write(val, Gun.obj.to(user.sea, {pub: user.pub, epub: user.epub})).then(function(data){ var rel; + if(rel = Gun.val.rel.is(val)){ + (at.sea.own[rel] = at.sea.own[rel] || {})[pub] = true; + } + node[key] = data; check['user'+soul+key] = 0; each.end({ok: 1}); }); return; } - check['user'+soul+key] = 0; - each.end({ok: 1}); - }); - }; - each.any = function(val, key, node, soul, user){ var tmp; - if(!user || !(user = user._) || !(user = user.sea)){ - if(user = at.sea.own[soul]){ + // TODO: consider async/await and drop callback pattern... + SEA.read(val, pub).then(function(data){ var rel, tmp; + if(u === data){ // make sure the signature matches the account it claims to be on. + return each.end({err: "Unverified data."}); // reject any updates that are signed with a mismatched account. + } + if((rel = Gun.val.rel.is(data)) && (tmp = rel.split('~')) && 2 === tmp.length){ + SEA.verify(tmp[0], pub, tmp[1]).then(function(ok){ + if(!ok){ return each.end({err: "Signature did not match account."}) } + (at.sea.own[rel] = at.sea.own[rel] || {})[pub] = true; + check['user'+soul+key] = 0; + each.end({ok: 1}); + }); + return; + } + check['user'+soul+key] = 0; + each.end({ok: 1}); + }); + }; + each.any = function(val, key, node, soul, user){ var tmp; + if(!user || !(user = user._) || !(user = user.sea)){ + if(user = at.sea.own[soul]){ + check['any'+soul+key] = 1; + user = Gun.obj.map(user, function(a,b){ return b }); + // TODO: consider async/await and drop callback pattern... + SEA.read(val, user).then(function(data){ var rel; + if(!data){ return each.end({err: "Mismatched owner on '" + key + "'.", }) } + if((rel = Gun.val.rel.is(data)) && (tmp = rel.split('~')) && 2 === tmp.length){ + SEA.verify(tmp[0], user, tmp[1]).then(function(ok){ + if(!ok){ return each.end({err: "Signature did not match account."}) } + (at.sea.own[rel] = at.sea.own[rel] || {})[user] = true; + check['any'+soul+key] = 0; + each.end({ok: 1}); + }); + return; + } + check['any'+soul+key] = 0; + each.end({ok: 1}); + }); + return; + } check['any'+soul+key] = 1; - user = Gun.obj.map(user, function(a,b){ return b }); - SEA.read(val, user, function(data){ var rel; - if(!data){ return each.end({err: "Mismatched owner on '" + key + "'.", }) } - if((rel = Gun.val.rel.is(data)) && (tmp = rel.split('~')) && 2 === tmp.length){ - SEA.verify(tmp[0], user, tmp[1], function(ok){ - if(!ok){ return each.end({err: "Signature did not match account."}) } - (at.sea.own[rel] = at.sea.own[rel] || {})[user] = true; - check['any'+soul+key] = 0; - each.end({ok: 1}); - }); - return; - } + if((tmp = soul.split('~')) && 2 == tmp.length){ + setTimeout(function(){ // hacky idea, what would be better? + each.any(val, key, node, soul); + },1); + return; + } + at.on('secure', function(msg){ this.off(); check['any'+soul+key] = 0; - each.end({ok: 1}); - }); + each.end(msg || {err: "Data cannot be modified."}); + }).on.on('secure', msg); + //each.end({err: "Data cannot be modified."}); + return; + } + if(!(tmp = soul.split('~')) || 2 !== tmp.length){ + each.end({err: "Soul is not signed at '" + key + "'."}); + return; + } + var other = Gun.obj.map(at.sea.own[soul], function(v, p){ + if(user.pub !== p){ return p } + }); + if(other){ + each.any(val, key, node, soul); return; } check['any'+soul+key] = 1; - if((tmp = soul.split('~')) && 2 == tmp.length){ - setTimeout(function(){ // hacky idea, what would be better? - each.any(val, key, node, soul); - },1); + // TODO: consider async/await and drop callback pattern... + SEA.verify(tmp[0], user.pub, tmp[1]).then(function(ok){ + if(!ok){ return each.end({err: "Signature did not match account at '" + key + "'."}) } + (at.sea.own[soul] = at.sea.own[soul] || {})[user.pub] = true; + SEA.write(val, user).then(function(data){ + node[key] = data; + check['any'+soul+key] = 0; + each.end({ok: 1}); + }); + }); + } + each.end = function(ctx){ // TODO: Can't you just switch this to each.end = cb? + if(each.err){ return } + if((each.err = ctx.err) || ctx.no){ + console.log('NO!', each.err, msg.put); return; } - at.on('secure', function(msg){ this.off(); - check['any'+soul+key] = 0; - each.end(msg || {err: "Data cannot be modified."}); - }).on.on('secure', msg); - //each.end({err: "Data cannot be modified."}); - return; - } - if(!(tmp = soul.split('~')) || 2 !== tmp.length){ - each.end({err: "Soul is not signed at '" + key + "'."}); - return; - } - var other = Gun.obj.map(at.sea.own[soul], function(v, p){ - if(user.pub !== p){ return p } - }); - if(other){ - each.any(val, key, node, soul); - return; - } - check['any'+soul+key] = 1; - SEA.verify(tmp[0], user.pub, tmp[1], function(ok){ - if(!ok){ return each.end({err: "Signature did not match account at '" + key + "'."}) } - (at.sea.own[soul] = at.sea.own[soul] || {})[user.pub] = true; - SEA.write(val, user, function(data){ - node[key] = data; - check['any'+soul+key] = 0; - each.end({ok: 1}); - }); - }); + if(!each.end.ed){ return } + if(Gun.obj.map(check, function(no){ + if(no){ return true } + })){ return } + to.next(msg); + }; + Gun.obj.map(msg.put, each.node); + each.end({end: each.end.ed = true}); + return; // need to manually call next after async. } - each.end = function(ctx){ // TODO: Can't you just switch this to each.end = cb? - if(each.err){ return } - if((each.err = ctx.err) || ctx.no){ - console.log('NO!', each.err, msg.put); - return; - } - if(!each.end.ed){ return } - if(Gun.obj.map(check, function(no){ - if(no){ return true } - })){ return } - to.next(msg); - }; - Gun.obj.map(msg.put, each.node); - each.end({end: each.end.ed = true}); - return; // need to manually call next after async. + to.next(msg); // pass forward any data we do not know how to handle or process (this allows custom security protocols). } - to.next(msg); // pass forward any data we do not know how to handle or process (this allows custom security protocols). - } - function makeKey(p,s){ - var ps = Buffer.concat([Buffer.from(p, 'utf8'), s]); - return sha256hash(ps.toString('utf8')).then(function(s){ - return Buffer.from(s, 'binary'); - }); - } + })(USE, './index'); - var SEA = {}; - // This is Buffer used in SEA and usable from Gun/SEA application also. - // For documentation see https://nodejs.org/api/buffer.html - SEA.Buffer = SafeBuffer; - // These SEA functions support both callback AND Promises - // create a wrapper library around Web Crypto API. - // now wrap the various AES, ECDSA, PBKDF2 functions we called above. - SEA.proof = function(pass,salt,cb){ - var doIt = (typeof window !== 'undefined' && function(resolve, reject){ - subtle.importKey( // For browser subtle works fine - 'raw', new TextEncoder().encode(pass), {name: 'PBKDF2'}, false, ['deriveBits'] - ).then(function(key){ - return subtle.deriveBits({ - name: 'PBKDF2', - iterations: pbkdf2.iter, - salt: new TextEncoder().encode(salt), - hash: pbkdf2.hash, - }, key, pbkdf2.ks*8); - }).then(function(result){ - pass = getRandomBytes(pass.length); - return Buffer.from(result, 'binary').toString('base64'); - }).then(resolve).catch(function(e){ Gun.log(e); reject(e) }); - }) || function(resolve, reject){ // For NodeJS crypto.pkdf2 rocks - try{ - var hash = crypto.pbkdf2Sync( - pass, - new TextEncoder().encode(salt), - pbkdf2.iter, - pbkdf2.ks, - pbkdf2.hash.replace('-', '').toLowerCase() - ); - pass = getRandomBytes(pass.length); - resolve(hash && hash.toString('base64')); - }catch(e){ reject(e) } - }; - if(cb){ doIt(cb, function(){cb()}) } else { return new Promise(doIt) } - }; - // Calculate public key KeyID aka PGPv4 (result: 8 bytes as hex string) - SEA.keyid = function(p,cb){ - var doIt = function(resolve, reject){ - // base64('base64(x):base64(y)') => Buffer(xy) - var pb = Buffer.concat(Buffer.from(p, 'base64').toString('utf8').split(':') - .map(function(t){ return Buffer.from(t, 'base64') })); - // id is PGPv4 compliant raw key - var id = Buffer.concat([Buffer.from([0x99, pb.length/0x100, pb.length%0x100]), pb]); - sha1hash(id).then(function(sha1){ - var hash = Buffer.from(sha1, 'binary'); - resolve(hash.toString('hex', hash.length-8)); // 16-bit ID as hex - }); - }; - if(cb){ doIt(cb, function(){cb()}) } else { return new Promise(doIt) } - }; - SEA.pair = function(cb){ - var doIt = function(resolve, reject){ - // First: ECDSA keys for signing/verifying... - return subtle.generateKey(ecdsakeyprops, true, ['sign', 'verify']) - .then(function(key){ // privateKey scope doesn't leak out from here! - var pubkey = key.publicKey; - return subtle.exportKey('jwk', key.privateKey).then(function(k){ - return {priv: k.d}; - }).then(function(keys){ - return subtle.exportKey('jwk', pubkey).then(function(k){ - keys.pub = Buffer.from([k.x, k.y].join(':')).toString('base64'); - // return SEA.keyid(keys.pub).then(function(id){ - // keys.pubId = id; - // return keys; - // }); - return keys; - }); - }).catch(function(e){ Gun.log(e); reject(e) }); - }).then(function(keys){ - // Next: ECDH keys for encryption/decryption... - var ecdhSubtle = subtleossl || subtle; - return ecdhSubtle.generateKey(ecdhkeyprops, true, ['deriveKey']) - .then(function(key){ - var pubkey = key.publicKey; - return ecdhSubtle.exportKey('jwk', key.privateKey).then(function(k){ - keys.epriv = k.d; - return keys; - }).then(function(keys){ - return ecdhSubtle.exportKey('jwk', pubkey).then(function(k){ - keys.epub = Buffer.from([k.x, k.y].join(':')).toString('base64'); - return keys; - }); - }).catch(function(e){ Gun.log(e); reject(e) }); - }).catch(function(e){ Gun.log(e); reject(e) }); - }).then(resolve) - .catch(function(e){ Gun.log(e); reject(e) }); - }; - if(cb){ doIt(cb, function(){cb()}) } else { return new Promise(doIt) } - }; - SEA.derive = function(m,p,cb){ - var ecdhSubtle = subtleossl || subtle; - var keystoecdhjwk = function(pub, priv){ - var pubkey = Buffer.from(pub, 'base64').toString('utf8').split(':'); - var jwk = priv ? {d: priv, key_ops: ['decrypt']} : {key_ops: ['encrypt']}; - var ret = Object.assign(jwk, { - kty: 'EC', - crv: 'P-256', - x: pubkey[0], - y: pubkey[1], - ext: false - }); - return ret; - }; - var doIt = function(resolve, reject){ - ecdhSubtle.importKey('jwk', keystoecdhjwk(m), ecdhkeyprops, false, ['deriveKey']) - .then(function(pub){ - var pubkey = pub; - ecdhSubtle.importKey( - 'jwk', keystoecdhjwk(p.epub, p.epriv), ecdhkeyprops, false, ['deriveKey'] - ).then(function(privkey){ - var props = Object.assign({}, ecdhkeyprops); - props.public = pubkey; - ecdhSubtle.deriveKey( - props, privkey, {name: 'AES-CBC', length: 256}, true, ['encrypt', 'decrypt'] - ).then(function(derivedkey){ - ecdhSubtle.exportKey('jwk', derivedkey).then(function(key){ - resolve(key.k); - }); - }).catch(function(e){ Gun.log(e); reject(e) }); - }).catch(function(e){ Gun.log(e); reject(e) }); - }).catch(function(e){ Gun.log(e); reject(e) }); - }; - if(cb){ doIt(cb, function(){cb()}) } else { return new Promise(doIt) } - }; - SEA.sign = function(m,p,cb){ - var doIt = function(resolve, reject){ - var jwk = keystoecdsajwk(p.pub, p.priv); - sha256hash(m.slice ? m : JSON.stringify(m)).then(function(mm){ - subtle.importKey('jwk', jwk, ecdsakeyprops, false, ['sign']).then(function(key){ - subtle.sign(ecdsasignprops, key, new Uint8Array(mm)) - .then(function(s){ resolve(Buffer.from(s, 'binary').toString('base64')) }) - .catch(function(e){ Gun.log(e); reject(e) }); - }).catch(function(e){ Gun.log(e); reject(e) }); - }); - }; - if(cb){doIt(cb, function(){cb()})} else { return new Promise(doIt) } - }; - SEA.verify = function(m, p, s, cb){ - var doIt = function(resolve, reject){ - subtle.importKey('jwk', keystoecdsajwk(p), ecdsakeyprops, false, ['verify']) - .then(function(key){ - sha256hash(m).then(function(mm){ - subtle.verify(ecdsasignprops, key, new Uint8Array(Buffer.from(s, 'base64')), new Uint8Array(mm)) - .then(function(v){ resolve(v) }) - .catch(function(e){ Gun.log(e); reject(e) }); - }); - }).catch(function(e){ Gun.log(e); reject(e) }); - }; - if(cb){doIt(cb, function(){cb()})} else { return new Promise(doIt) } - }; - SEA.enc = function(m,p,cb){ - var doIt = function(resolve, reject){ - var s = getRandomBytes(8); - var iv = getRandomBytes(16); - var r = {iv: iv.toString('hex'), s: s.toString('hex')}; - m = (m.slice && m) || JSON.stringify(m); - recallCryptoKey(p, s).then(function(aesKey){ - subtle.encrypt({ - name: 'AES-CBC', iv: new Uint8Array(iv) - }, aesKey, new TextEncoder().encode(m)).then(function(ct){ - aesKey = getRandomBytes(32); - r.ct = Buffer.from(ct, 'binary').toString('base64'); - return JSON.stringify(r); - }).then(resolve).catch(function(e){ Gun.log(e); reject(e) }); - }).catch(function(e){ Gun.log(e); reject(e)} ); - }; - if(cb){ doIt(cb, function(){cb()}) } else { return new Promise(doIt) } - }; - SEA.dec = function(m,p,cb){ - var doIt = function(resolve, reject){ - try{ m = m.slice ? JSON.parse(m) : m }catch(e){} //eslint-disable-line no-empty - var iv = new Uint8Array(Buffer.from(m.iv, 'hex')); - var s = new Uint8Array(Buffer.from(m.s, 'hex')); - recallCryptoKey(p, s).then(function(aesKey){ - subtle.decrypt({ - name: 'AES-CBC', iv: iv - }, aesKey, new Uint8Array(Buffer.from(m.ct, 'base64'))).then(function(ct){ - aesKey = getRandomBytes(32); - var ctUtf8 = new TextDecoder('utf8').decode(ct); - try{ return ctUtf8.slice ? JSON.parse(ctUtf8) : ctUtf8; - }catch(e){ return ctUtf8 } - }).then(resolve).catch(function(e){Gun.log(e); reject(e)}); - }).catch(function(e){Gun.log(e); reject(e)}); - }; - if(cb){ doIt(cb, function(){cb()}) } else { return new Promise(doIt) } - }; - SEA.write = function(mm,p,cb){ - var doIt = function(resolve, reject) { - // TODO: something's bugging double 'SEA[]' treatment to mm... - var m = mm; - if(m && m.slice && 'SEA[' === m.slice(0,4)){ return resolve(m) } - if(mm && mm.slice){ - // Needs to remove previous signature envelope - while('SEA[' === m.slice(0,4)){ - try{ m = JSON.parse(m.slice(3))[0]; - }catch(e){ break } - } - } - m = (m && m.slice) ? m : JSON.stringify(m); - SEA.sign(m, p).then(function(signature){ - resolve('SEA'+JSON.stringify([m,signature])); - }).catch(function(e){Gun.log(e); reject(e)}); - }; - if(cb){ doIt(cb, function(){cb()}) } else { return new Promise(doIt) } - }; - SEA.read = function(m,p,cb){ - var doIt = function(resolve, reject){ var d; - if(!m){ if(false === p){ return resolve(m) } - return resolve(); - } - if(!m.slice || 'SEA[' !== m.slice(0,4)){ - if(false === p){ return resolve(m) } - return resolve() - } - m = m.slice(3); - try{ m = m.slice ? JSON.parse(m) : m; - }catch(e){ return reject(e) } - m = m || ''; - d = m[0]; - try{ d = d.slice ? JSON.parse(d) : d }catch(e){} - if(false === p){ resolve(d) } - SEA.verify(m[0], p, m[1]).then(function(ok){ - if(!ok){ return resolve() } - resolve(d); - }).catch(function(e){reject(e)}); - }; - if(cb && typeof cb === 'function'){ - doIt(cb, function(){cb()}); - } else { return new Promise(doIt) } - }; - // Internal helper for IndexedDB use - SEA._callonstore_ = function(fn_, resolve_){ - var open = indexedDB.open('GunDB', 1); // Open (or create) the database; 1 === 'version' - open.onupgradeneeded = function(){ // Create the schema; props === current version - var db = open.result; - db.createObjectStore('SEA', {keyPath: 'id'}); - }; - open.onsuccess = function(){ // Start a new transaction - var db = open.result; - var tx = db.transaction('SEA', 'readwrite'); - var store = tx.objectStore('SEA'); - fn_(store); - tx.oncomplete = function(){ // Close the db when the transaction is done - db.close(); - if(typeof resolve_ === 'function'){ resolve_() } - }; - }; - }; - - Gun.SEA = SEA; - - // all done! - // 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. - // SEA should be a full suite that is easy and seamless to use. - // Again, scroll naer the top, where I provide an EXAMPLE of how to create a user and sign in. - // Once logged in, the rest of the code you just read handled automatically signing/validating data. - // But all other behavior needs to be equally easy, like opinionated ways of - // Adding friends (trusted public keys), sending private messages, etc. - // Cheers! Tell me what you think. - - try{module.exports = SEA}catch(e){} //eslint-disable-line no-empty -}()); +}()); \ No newline at end of file diff --git a/sea/array.js b/sea/array.js new file mode 100644 index 00000000..2e6e0c25 --- /dev/null +++ b/sea/array.js @@ -0,0 +1,24 @@ + + // This is Array extended to have .toString(['utf8'|'hex'|'base64']) + function SeaArray() {} + Object.assign(SeaArray, { from: Array.from }) + SeaArray.prototype = Object.create(Array.prototype) + SeaArray.prototype.toString = function(enc = 'utf8', start = 0, end) { + const { length } = this + if (enc === 'hex') { + const buf = new Uint8Array(this) + return [ ...Array(((end && (end + 1)) || length) - start).keys()] + .map((i) => buf[ i + start ].toString(16).padStart(2, '0')).join('') + } + if (enc === 'utf8') { + return Array.from( + { length: (end || length) - start }, + (_, i) => String.fromCharCode(this[ i + start]) + ).join('') + } + if (enc === 'base64') { + return btoa(this) + } + } + module.exports = SeaArray; + \ No newline at end of file diff --git a/sea/authenticate.js b/sea/authenticate.js new file mode 100644 index 00000000..00312a02 --- /dev/null +++ b/sea/authenticate.js @@ -0,0 +1,56 @@ + + // TODO: BUG! `SEA` needs to be USED! + const Gun = (typeof window !== 'undefined' ? window : global).Gun || require('gun/gun') + var SEA = require('./sea'); + var queryGunAliases = require('./query'); + var parseProps = require('./parse'); + // This is internal User authentication func. + const authenticate = async (alias, pass, root) => { + // load all public keys associated with the username alias we want to log in with. + const aliases = (await queryGunAliases(alias, root)) + .filter(({ pub, at: { put } = {} } = {}) => !!pub && !!put) + // Got any? + if (!aliases.length) { + throw { err: 'Public key does not exist!' } + } + let err + // then attempt to log into each one until we find ours! + // (if two users have the same username AND the same password... that would be bad) + const [ user ] = await Promise.all(aliases.map(async ({ at, pub }) => { + // attempt to PBKDF2 extend the password with the salt. (Verifying the signature gives us the plain text salt.) + const auth = parseProps(at.put.auth) + // NOTE: aliasquery uses `gun.get` which internally SEA.read verifies the data for us, so we do not need to re-verify it here. + // SEA.read(at.put.auth, pub).then(function(auth){ + try { + const proof = await SEA.proof(pass, auth.salt) + const props = { pub, proof, at } + // the proof of work is evidence that we've spent some time/effort trying to log in, this slows brute force. + /* + MARK TO @mhelander : pub vs epub!??? + */ + const { salt } = auth + const sea = await SEA.dec(auth.auth, { pub, key: proof }) + if (!sea) { + err = 'Failed to decrypt secret!' + return + } + // now we have AES decrypted the private key, from when we encrypted it with the proof at registration. + // if we were successful, then that meanswe're logged in! + const { priv, epriv } = sea + const { epub } = at.put + // TODO: 'salt' needed? + err = null + return Object.assign(props, { priv, salt, epub, epriv }) + } catch (e) { + err = 'Failed to decrypt secret!' + throw { err } + } + })) + + if (!user) { + throw { err: err || 'Public key does not exist!' } + } + return user + } + module.exports = authenticate; + \ No newline at end of file diff --git a/sea/buffer.js b/sea/buffer.js new file mode 100644 index 00000000..e798a233 --- /dev/null +++ b/sea/buffer.js @@ -0,0 +1,79 @@ + + // This is Buffer implementation used in SEA. Functionality is mostly + // compatible with NodeJS 'safe-buffer' and is used for encoding conversions + // between binary and 'hex' | 'utf8' | 'base64' + // See documentation and validation for safe implementation in: + // https://github.com/feross/safe-buffer#update + var SeaArray = require('./array'); + function SafeBuffer(...props) { + console.warn('new SafeBuffer() is depreciated, please use SafeBuffer.from()') + return SafeBuffer.from(...props) + } + SafeBuffer.prototype = Object.create(Array.prototype) + Object.assign(SafeBuffer, { + // (data, enc) where typeof data === 'string' then enc === 'utf8'|'hex'|'base64' + from() { + if (!Object.keys(arguments).length) { + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + const input = arguments[0] + let buf + if (typeof input === 'string') { + const enc = arguments[1] || 'utf8' + if (enc === 'hex') { + const bytes = input.match(/([\da-fA-F]{2})/g) + .map((byte) => parseInt(byte, 16)) + if (!bytes || !bytes.length) { + throw new TypeError('Invalid first argument for type \'hex\'.') + } + buf = SeaArray.from(bytes) + } else if (enc === 'utf8') { + const { length } = input + const words = new Uint16Array(length) + Array.from({ length }, (_, i) => words[i] = input.charCodeAt(i)) + buf = SeaArray.from(words) + } else if (enc === 'base64') { + const dec = atob(input) + const { length } = dec + const bytes = new Uint8Array(length) + Array.from({ length }, (_, i) => bytes[i] = dec.charCodeAt(i)) + buf = SeaArray.from(bytes) + } else if (enc === 'binary') { + buf = SeaArray.from(input) + } else { + console.info(`SafeBuffer.from unknown encoding: '${enc}'`) + } + return buf + } + const { byteLength, length = byteLength } = input + if (length) { + let buf + if (input instanceof ArrayBuffer) { + buf = new Uint8Array(input) + } + return SeaArray.from(buf || input) + } + }, + // This is 'safe-buffer.alloc' sans encoding support + alloc(length, fill = 0 /*, enc*/ ) { + return SeaArray.from(new Uint8Array(Array.from({ length }, () => fill))) + }, + // This is normal UNSAFE 'buffer.alloc' or 'new Buffer(length)' - don't use! + allocUnsafe(length) { + return SeaArray.from(new Uint8Array(Array.from({ length }))) + }, + // This puts together array of array like members + concat(arr) { // octet array + if (!Array.isArray(arr)) { + throw new TypeError('First argument must be Array containing ArrayBuffer or Uint8Array instances.') + } + return SeaArray.from(arr.reduce((ret, item) => ret.concat(Array.from(item)), [])) + } + }) + SafeBuffer.prototype.from = SafeBuffer.from + SafeBuffer.prototype.toString = SeaArray.prototype.toString + + const Buffer = SafeBuffer + if(typeof window !== 'undefined'){ window.Buffer = window.Buffer || Buffer } + module.exports = SafeBuffer; + \ No newline at end of file diff --git a/sea/index.js b/sea/index.js new file mode 100644 index 00000000..e8398f44 --- /dev/null +++ b/sea/index.js @@ -0,0 +1,252 @@ + + const Gun = (typeof window !== 'undefined' ? window : global).Gun || require('gun/gun') + var SEA = require('./sea'); + // 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) + Gun.on('opt', function(at){ + if(!at.sea){ // only add SEA once per instance, on the "at" context. + at.sea = {own: {}}; + var uuid = at.opt.uuid || Gun.state.lex; + at.opt.uuid = function(cb){ // TODO: consider async/await and drop callback pattern... + if(!cb){ return } + var id = uuid(), pair = at.user && (at.user._).sea; + if(!pair){ return id } + SEA.sign(id, pair).then(function(sig){ + cb(null, id + '~' + sig); + }).catch(function(e){cb(e)}); + } + at.on('in', security, at); // now listen to all input data, acting as a firewall. + at.on('out', signature, at); // and output listeners, to encrypt outgoing data. + at.on('node', each, at); + } + this.to.next(at); // make sure to call the "next" middleware adapter. + }); + + // Alright, this next adapter gets run at the per node level in the graph database. + // This will let us verify that every property on a node has a value signed by a public key we trust. + // If the signature does not match, the data is just `undefined` so it doesn't get passed on. + // If it does match, then we transform the in-memory "view" of the data into its plain value (without the signature). + // Now NOTE! Some data is "system" data, not user data. Example: List of public keys, aliases, etc. + // This data is self-enforced (the value can only match its ID), but that is handled in the `security` function. + // From the self-enforced data, we can see all the edges in the graph that belong to a public key. + // Example: pub/ASDF is the ID of a node with ASDF as its public key, signed alias and salt, and + // its encrypted private key, but it might also have other signed values on it like `profile = ` edge. + // Using that directed edge's ID, we can then track (in memory) which IDs belong to which keys. + // Here is a problem: Multiple public keys can "claim" any node's ID, so this is dangerous! + // This means we should ONLY trust our "friends" (our key ring) public keys, not any ones. + // I have not yet added that to SEA yet in this alpha release. That is coming soon, but beware in the meanwhile! + function each(msg){ // TODO: Warning: Need to switch to `gun.on('node')`! Do not use `Gun.on('node'` in your apps! + // NOTE: THE SECURITY FUNCTION HAS ALREADY VERIFIED THE DATA!!! + // WE DO NOT NEED TO RE-VERIFY AGAIN, JUST TRANSFORM IT TO PLAINTEXT. + var to = this.to, vertex = (msg.gun._).put, c = 0, d; + Gun.node.is(msg.put, function(val, key, node){ c++; // for each property on the node + // TODO: consider async/await use here... + SEA.read(val, false).then(function(data){ c--; // false just extracts the plain data. + node[key] = val = data; // transform to plain value. + if(d && !c && (c = -1)){ to.next(msg) } + }); + }); + d = true; + if(d && !c){ to.next(msg) } + return; + /*var to = this.to, ctx = this.as; + var own = ctx.sea.own, soul = msg.get, c = 0; + var pub = own[soul] || soul.slice(4), vertex = (msg.gun._).put; + Gun.node.is(msg.put, function(val, key, node){ c++; // for each property on the node. + SEA.read(val, pub).then(function(data){ c--; + vertex[key] = node[key] = val = data; // verify signature and get plain value. + if(val && val['#'] && (key = Gun.val.rel.is(val))){ // if it is a relation / edge + if('alias/' !== soul.slice(0,6)){ own[key] = pub; } // associate the public key with a node if it is itself + } + if(!c && (c = -1)){ to.next(msg) } + }); + }); + if(!c){ to.next(msg) }*/ + } + + // signature handles data output, it is a proxy to the security function. + function signature(msg){ + if(msg.user){ + return this.to.next(msg); + } + var ctx = this.as; + msg.user = ctx.user; + security.call(this, msg); + } + + // okay! The security function handles all the heavy lifting. + // It needs to deal read and write of input and output of system data, account/public key data, and regular data. + // This is broken down into some pretty clear edge cases, let's go over them: + function security(msg){ + var at = this.as, sea = at.sea, to = this.to; + if(msg.get){ + // if there is a request to read data from us, then... + var soul = msg.get['#']; + if(soul){ // for now, only allow direct IDs to be read. + if('alias' === soul){ // Allow reading the list of usernames/aliases in the system? + return to.next(msg); // yes. + } else + if('alias/' === soul.slice(0,6)){ // Allow reading the list of public keys associated with an alias? + return to.next(msg); // yes. + } else { // Allow reading everything? + return to.next(msg); // yes // TODO: No! Make this a callback/event that people can filter on. + } + } + } + if(msg.put){ + // potentially parallel async operations!!! + var check = {}, on = Gun.on(), each = {}, u; + each.node = function(node, soul){ + if(Gun.obj.empty(node, '_')){ return check['node'+soul] = 0 } // ignore empty updates, don't reject them. + Gun.obj.map(node, each.way, {soul: soul, node: node}); + }; + each.way = function(val, key){ + var soul = this.soul, node = this.node, tmp; + if('_' === key){ return } // ignore meta data + if('alias' === soul){ // special case for shared system data, the list of aliases. + each.alias(val, key, node, soul); return; + } + if('alias/' === soul.slice(0,6)){ // special case for shared system data, the list of public keys for an alias. + each.pubs(val, key, node, soul); return; + } + if('pub/' === soul.slice(0,4)){ // special case, account data for a public key. + each.pub(val, key, node, soul, soul.slice(4), msg.user); return; + } + each.any(val, key, node, soul, msg.user); return; + return each.end({err: "No other data allowed!"}); + /*if(!(tmp = at.user)){ return } + if(soul.slice(4) === (tmp = tmp._).pub){ // not a special case, if we are logged in and have outbound data on us. + each.user(val, key, node, soul, { + pub: tmp.pub, priv: tmp.sea.priv, epub: tmp.sea.epub, epriv: tmp.sea.epriv + }); + } + if((tmp = sea.own[soul])){ // not special case, if we receive an update on an ID associated with a public key, then + each.own(val, key, node, soul, tmp); + }*/ + }; + each.alias = function(val, key, node, soul){ // Example: {_:#alias, alias/alice: {#alias/alice}} + if(!val){ return each.end({err: "Data must exist!"}) } // data MUST exist + if('alias/'+key === Gun.val.rel.is(val)){ return check['alias'+key] = 0 } // in fact, it must be EXACTLY equal to itself + each.end({err: "Mismatching alias."}); // if it isn't, reject. + }; + each.pubs = function(val, key, node, soul){ // Example: {_:#alias/alice, pub/asdf: {#pub/asdf}} + if(!val){ return each.end({err: "Alias must exist!"}) } // data MUST exist + if(key === Gun.val.rel.is(val)){ return check['pubs'+soul+key] = 0 } // and the ID must be EXACTLY equal to its property + each.end({err: "Alias must match!"}); // that way nobody can tamper with the list of public keys. + }; + each.pub = function(val, key, node, soul, pub, user){ // Example: {_:#pub/asdf, hello:SEA['world',fdsa]} + if('pub' === key){ + if(val === pub){ return (check['pub'+soul+key] = 0) } // the account MUST match `pub` property that equals the ID of the public key. + return each.end({err: "Account must match!"}); + } + check['user'+soul+key] = 1; + if(user && (user = user._) && user.sea && pub === user.pub){ + var id = Gun.text.random(3); + SEA.write(val, Gun.obj.to(user.sea, {pub: user.pub, epub: user.epub})).then(function(data){ var rel; + if(rel = Gun.val.rel.is(val)){ + (at.sea.own[rel] = at.sea.own[rel] || {})[pub] = true; + } + node[key] = data; + check['user'+soul+key] = 0; + each.end({ok: 1}); + }); + return; + } + // TODO: consider async/await and drop callback pattern... + SEA.read(val, pub).then(function(data){ var rel, tmp; + if(u === data){ // make sure the signature matches the account it claims to be on. + return each.end({err: "Unverified data."}); // reject any updates that are signed with a mismatched account. + } + if((rel = Gun.val.rel.is(data)) && (tmp = rel.split('~')) && 2 === tmp.length){ + SEA.verify(tmp[0], pub, tmp[1]).then(function(ok){ + if(!ok){ return each.end({err: "Signature did not match account."}) } + (at.sea.own[rel] = at.sea.own[rel] || {})[pub] = true; + check['user'+soul+key] = 0; + each.end({ok: 1}); + }); + return; + } + check['user'+soul+key] = 0; + each.end({ok: 1}); + }); + }; + each.any = function(val, key, node, soul, user){ var tmp; + if(!user || !(user = user._) || !(user = user.sea)){ + if(user = at.sea.own[soul]){ + check['any'+soul+key] = 1; + user = Gun.obj.map(user, function(a,b){ return b }); + // TODO: consider async/await and drop callback pattern... + SEA.read(val, user).then(function(data){ var rel; + if(!data){ return each.end({err: "Mismatched owner on '" + key + "'.", }) } + if((rel = Gun.val.rel.is(data)) && (tmp = rel.split('~')) && 2 === tmp.length){ + SEA.verify(tmp[0], user, tmp[1]).then(function(ok){ + if(!ok){ return each.end({err: "Signature did not match account."}) } + (at.sea.own[rel] = at.sea.own[rel] || {})[user] = true; + check['any'+soul+key] = 0; + each.end({ok: 1}); + }); + return; + } + check['any'+soul+key] = 0; + each.end({ok: 1}); + }); + return; + } + check['any'+soul+key] = 1; + if((tmp = soul.split('~')) && 2 == tmp.length){ + setTimeout(function(){ // hacky idea, what would be better? + each.any(val, key, node, soul); + },1); + return; + } + at.on('secure', function(msg){ this.off(); + check['any'+soul+key] = 0; + each.end(msg || {err: "Data cannot be modified."}); + }).on.on('secure', msg); + //each.end({err: "Data cannot be modified."}); + return; + } + if(!(tmp = soul.split('~')) || 2 !== tmp.length){ + each.end({err: "Soul is not signed at '" + key + "'."}); + return; + } + var other = Gun.obj.map(at.sea.own[soul], function(v, p){ + if(user.pub !== p){ return p } + }); + if(other){ + each.any(val, key, node, soul); + return; + } + check['any'+soul+key] = 1; + // TODO: consider async/await and drop callback pattern... + SEA.verify(tmp[0], user.pub, tmp[1]).then(function(ok){ + if(!ok){ return each.end({err: "Signature did not match account at '" + key + "'."}) } + (at.sea.own[soul] = at.sea.own[soul] || {})[user.pub] = true; + SEA.write(val, user).then(function(data){ + node[key] = data; + check['any'+soul+key] = 0; + each.end({ok: 1}); + }); + }); + } + each.end = function(ctx){ // TODO: Can't you just switch this to each.end = cb? + if(each.err){ return } + if((each.err = ctx.err) || ctx.no){ + console.log('NO!', each.err, msg.put); + return; + } + if(!each.end.ed){ return } + if(Gun.obj.map(check, function(no){ + if(no){ return true } + })){ return } + to.next(msg); + }; + Gun.obj.map(msg.put, each.node); + each.end({end: each.end.ed = true}); + return; // need to manually call next after async. + } + to.next(msg); // pass forward any data we do not know how to handle or process (this allows custom security protocols). + } + + \ No newline at end of file diff --git a/sea/indexed.js b/sea/indexed.js new file mode 100644 index 00000000..3a41f3b5 --- /dev/null +++ b/sea/indexed.js @@ -0,0 +1,53 @@ + + // This is safe class to operate with IndexedDB data - all methods are Promise + function EasyIndexedDB(objectStoreName, dbName = 'GunDB', dbVersion = 1) { + // Private internals, including constructor props + const runTransaction = (fn_) => new Promise((resolve, reject) => { + const open = indexedDB.open(dbName, dbVersion) // Open (or create) the DB + open.onerror = (e) => { + reject(new Error('IndexedDB error:', e)) + } + open.onupgradeneeded = () => { + const db = open.result // Create the schema; props === current version + db.createObjectStore(objectStoreName, { keyPath: 'id' }) + } + let result + open.onsuccess = () => { // Start a new transaction + const db = open.result + const tx = db.transaction(objectStoreName, 'readwrite') + const store = tx.objectStore(objectStoreName) + tx.oncomplete = () => { + db.close() // Close the db when the transaction is done + resolve(result) // Resolves result returned by action function fn_ + } + result = fn_(store) + } + }) + + Object.assign(this, { + async wipe() { // Wipe IndexedDB completedy! + return runTransaction((store) => { + const act = store.clear() + act.onsuccess = () => {} + }) + }, + async put(id, props) { + const data = Object.assign({}, props, { id }) + return runTransaction((store) => { store.put(data) }) + }, + async get(id, prop) { + return runTransaction((store) => new Promise((resolve) => { + const getData = store.get(id) + getData.onsuccess = () => { + const { result = {} } = getData + resolve(result[prop]) + } + })) + } + }) + } + // This is IndexedDB used by Gun SEA + const seaIndexedDb = new EasyIndexedDB('SEA', 'GunDB', 1) + EasyIndexedDB.scope = seaIndexedDb; // for now. This module should not export an instance of itself! + module.exports = EasyIndexedDB; + \ No newline at end of file diff --git a/sea/leave.js b/sea/leave.js new file mode 100644 index 00000000..b34f83ad --- /dev/null +++ b/sea/leave.js @@ -0,0 +1,22 @@ + + var authPersist = require('./persist'); + var authsettings = require('./settings'); + var seaIndexedDb = require('./indexed').scope; + var seaIndexedDb = require('./indexed').scope; + // This internal func executes logout actions + const authLeave = async (root, alias = root._.user._.alias) => { + const { user = { _: {} } } = root._ + root._.user = null + // Removes persisted authentication & CryptoKeys + try { + await authPersist({ alias }) + } catch (e) {} //eslint-disable-line no-empty + // TODO: is this correct way to 'logout' user from Gun.User ? + [ 'alias', 'sea', 'pub' ].map((key) => delete user._[key]) + user._.is = user.is = {} + // Let's use default + root.user(); + return { ok: 0 } + } + module.exports = authLeave; + \ No newline at end of file diff --git a/sea/login.js b/sea/login.js new file mode 100644 index 00000000..1a391258 --- /dev/null +++ b/sea/login.js @@ -0,0 +1,26 @@ + + var authPersist = require('./persist'); + // This internal func finalizes User authentication + const finalizeLogin = async (alias, key, root, opts) => { + const { user } = root._ + // add our credentials in-memory only to our root gun instance + user._ = key.at.gun._ + // so that way we can use the credentials to encrypt/decrypt data + user._.is = user.is = {} + // that is input/output through gun (see below) + const { pub, priv, epub, epriv } = key + Object.assign(user._, { alias, pub, epub, sea: { pub, priv, epub, epriv } }) + //console.log("authorized", user._); + // persist authentication + await authPersist(user._, key.proof, opts) + // emit an auth event, useful for page redirects and stuff. + try { + root._.on('auth', user._) + } catch (e) { + console.log('Your \'auth\' callback crashed with:', e) + } + // returns success with the user data credentials. + return user._ + } + module.exports = finalizeLogin; + \ No newline at end of file diff --git a/sea/parse.js b/sea/parse.js new file mode 100644 index 00000000..a4599367 --- /dev/null +++ b/sea/parse.js @@ -0,0 +1,9 @@ + + const parseProps = (props) => { + try { + return props.slice ? JSON.parse(props) : props + } catch (e) {} //eslint-disable-line no-empty + return props + } + module.exports = parseProps; + \ No newline at end of file diff --git a/sea/persist.js b/sea/persist.js new file mode 100644 index 00000000..6ddb73a1 --- /dev/null +++ b/sea/persist.js @@ -0,0 +1,37 @@ + + const Gun = (typeof window !== 'undefined' ? window : global).Gun || require('gun/gun') + var Buffer = require('./buffer'); + var authsettings = require('./settings'); + var updateStorage = require('./update'); + // This internal func persists User authentication if so configured + const authPersist = async (user, proof, opts) => { + // opts = { pin: 'string' } + // no opts.pin then uses random PIN + // How this works: + // called when app bootstraps, with wanted options + // IF authsettings.validity === 0 THEN no remember-me, ever + // IF PIN then signed 'remember' to window.sessionStorage and 'auth' to IndexedDB + const pin = Buffer.from( + (Gun.obj.has(opts, 'pin') && opts.pin) || Gun.text.random(10), + 'utf8' + ).toString('base64') + + const { alias } = user || {} + const { validity: exp } = authsettings // seconds // @mhelander what is `exp`??? + + if (proof && alias && exp) { + const iat = Math.ceil(Date.now() / 1000) // seconds + const remember = Gun.obj.has(opts, 'pin') || undefined // for hook - not stored + const props = authsettings.hook({ alias, iat, exp, remember }) + const { pub, epub, sea: { priv, epriv } } = user + const key = { pub, priv, epub, epriv } + if (props instanceof Promise) { + const asyncProps = await props.then() + return await updateStorage(proof, key, pin)(asyncProps) + } + return await updateStorage(proof, key, pin)(props) + } + return await updateStorage()({ alias: 'delete' }) + } + module.exports = authPersist; + \ No newline at end of file diff --git a/sea/query.js b/sea/query.js new file mode 100644 index 00000000..34d0b053 --- /dev/null +++ b/sea/query.js @@ -0,0 +1,43 @@ + + const Gun = (typeof window !== 'undefined' ? window : global).Gun || require('gun/gun') + // This is internal func queries public key(s) for alias. + const queryGunAliases = (alias, root) => new Promise((resolve, reject) => { + // load all public keys associated with the username alias we want to log in with. + root.get(`alias/${alias}`).get((rat, rev) => { + rev.off() + if (!rat.put) { + // if no user, don't do anything. + const err = 'No user!' + Gun.log(err) + return reject({ err }) + } + // then figuring out all possible candidates having matching username + let aliases = [] + let c = 0 + // TODO: how about having real chainable map without callback ? + Gun.obj.map(rat.put, (at, pub) => { + if (!pub.slice || 'pub/' !== pub.slice(0, 4)) { + // TODO: ... this would then be .filter((at, pub)) + return + } + ++c + // grab the account associated with this public key. + root.get(pub).get((at, ev) => { + pub = pub.slice(4) + ev.off() + --c + if (at.put){ + aliases.push({ pub, at }) + } + if (!c && (c = -1)) { + resolve(aliases) + } + }) + }) + if (!c) { + reject({ err: 'Public key does not exist!' }) + } + }) + }) + module.exports = queryGunAliases; + \ No newline at end of file diff --git a/sea/recall.js b/sea/recall.js new file mode 100644 index 00000000..258740c2 --- /dev/null +++ b/sea/recall.js @@ -0,0 +1,135 @@ + + // TODO: BUG! `SEA` needs to be USED! + const Gun = (typeof window !== 'undefined' ? window : global).Gun || require('gun/gun') + var Buffer = require('./buffer'); + var authsettings = require('./settings'); + var seaIndexedDb = require('./indexed').scope; + var queryGunAliases = require('./query'); + var parseProps = require('./parse'); + var updateStorage = require('./update'); + // This internal func recalls persisted User authentication if so configured + const authRecall = async (root, authprops) => { + // window.sessionStorage only holds signed { alias, pin } !!! + const remember = authprops || sessionStorage.getItem('remember') + const { alias = sessionStorage.getItem('user'), pin: pIn } = authprops || {} // @mhelander what is pIn? + const pin = pIn && Buffer.from(pIn, 'utf8').toString('base64') + // Checks for existing proof, matching alias and expiration: + const checkRememberData = async ({ proof, alias: aLias, iat, exp, remember }) => { + if (!!proof && alias === aLias) { + const checkNotExpired = (args) => { + if (Math.floor(Date.now() / 1000) < (iat + args.exp)) { + // No way hook to update 'iat' + return Object.assign(args, { iat, proof }) + } else { + Gun.log('Authentication expired!') + } + } + // We're not gonna give proof to hook! + const hooked = authsettings.hook({ alias, iat, exp, remember }) + return ((hooked instanceof Promise) + && await hooked.then(checkNotExpired)) || checkNotExpired(hooked) + } + } + const readAndDecrypt = async (data, pub, key) => + parseProps(await SEA.dec(await SEA.read(data, pub), key)) + + // Already authenticated? + if (root._.user + && Gun.obj.has(root._.user._, 'pub') + && Gun.obj.has(root._.user._, 'sea')) { + return root._.user._ // Yes, we're done here. + } + // No, got persisted 'alias'? + if (!alias) { + throw { err: 'No authentication session found!' } + } + // Yes, got persisted 'remember'? + if (!remember) { + throw { // And return proof if for matching alias + err: (await seaIndexedDb.get(alias, 'auth') && authsettings.validity + && 'Missing PIN and alias!') || 'No authentication session found!' + } + } + // Yes, let's get (all?) matching aliases + const aliases = (await queryGunAliases(alias, root)) + .filter(({ pub } = {}) => !!pub) + // Got any? + if (!aliases.length) { + throw { err: 'Public key does not exist!' } + } + let err + // Yes, then attempt to log into each one until we find ours! + // (if two users have the same username AND the same password... that would be bad) + const [ { key, at, proof, pin: newPin } = {} ] = await Promise + .all(aliases.filter(({ at: { put } = {} }) => !!put) + .map(async ({ at, pub }) => { + const readStorageData = async (args) => { + const props = args || parseProps(await SEA.read(remember, pub, true)) + let { pin, alias: aLias } = props + + const data = (!pin && alias === aLias) + // No PIN, let's try short-term proof if for matching alias + ? await checkRememberData(props) + // Got PIN so get IndexedDB secret if signature is ok + : await checkRememberData(await readAndDecrypt(await seaIndexedDb.get(alias, 'auth'), pub, pin)) + pin = pin || data.pin + delete data.pin + return { pin, data } + } + // got pub, try auth with pin & alias :: or unwrap Storage data... + const { data, pin: newPin } = await readStorageData(pin && { pin, alias }) + const { proof } = data || {} + + if (!proof) { + if (!data) { + err = 'No valid authentication session found!' + return + } + try { // Wipes IndexedDB silently + await updateStorage()(data) + } catch (e) {} //eslint-disable-line no-empty + err = 'Expired session!' + return + } + + try { // auth parsing or decryption fails or returns empty - silently done + const { auth } = at.put.auth + const sea = await SEA.dec(auth, proof) + if (!sea) { + err = 'Failed to decrypt private key!' + return + } + const { priv, epriv } = sea + const { epub } = at.put + // Success! we've found our private data! + err = null + return { proof, at, pin: newPin, key: { pub, priv, epriv, epub } } + } catch (e) { + err = 'Failed to decrypt private key!' + return + } + }).filter((props) => !!props)) + + if (!key) { + throw { err: err || 'Public key does not exist!' } + } + + // now we have AES decrypted the private key, + // if we were successful, then that means we're logged in! + try { + await updateStorage(proof, key, newPin || pin)(key) + + const user = Object.assign(key, { at, proof }) + const pIN = newPin || pin + + const pinProp = pIN && { pin: Buffer.from(pIN, 'base64').toString('utf8') } + + return await finalizeLogin(alias, user, root, pinProp) + } catch (e) { // TODO: right log message ? + Gun.log('Failed to finalize login with new password!') + const { err = '' } = e || {} + throw { err: `Finalizing new password login failed! Reason: ${err}` } + } + } + module.exports = authRecall; + \ No newline at end of file diff --git a/sea/remember.js b/sea/remember.js new file mode 100644 index 00000000..8d954f6d --- /dev/null +++ b/sea/remember.js @@ -0,0 +1,44 @@ + + var Buffer = require('./buffer'); + var sha256hash = require('./sha256'); + var seaIndexedDb = require('./indexed').scope; + var settings = require('./settings'); + var authsettings = settings.recall; + const makeKey = async (p, s) => { + const ps = Buffer.concat([Buffer.from(p, 'utf8'), s]).toString('utf8') + return Buffer.from(await sha256hash(ps), 'binary') + } + // This recalls Web Cryptography API CryptoKeys from IndexedDB or creates & stores + // {pub, key}|proof, salt, optional:['sign'] + const recallCryptoKey = async (p, s, o = [ 'encrypt', 'decrypt' ]) => { + const importKey = async (key) => { + const hashedKey = await makeKey((Gun.obj.has(key, 'key') && key.key) || key, s || getRandomBytes(8)) + return await subtle.importKey( + 'raw', + new Uint8Array(hashedKey), + 'AES-CBC', + false, + o + ) + } + + if (authsettings.validity && typeof window !== 'undefined' + && Gun.obj.has(p, 'pub') && Gun.obj.has(p, 'key')) { + const { pub: id } = p + const importAndStoreKey = async () => { + const key = await importKey(p) + await seaIndexedDb.put(id, { key }) + return key + } + if (Gun.obj.has(p, 'set')) { + return importAndStoreKey() // proof update so overwrite + } + const aesKey = await seaIndexedDb.get(id, 'key') + return aesKey ? aesKey : importAndStoreKey() + } + + // No secure store usage + return importKey(p) + } + module.exports = recallCryptoKey; + \ No newline at end of file diff --git a/sea/sea.js b/sea/sea.js new file mode 100644 index 00000000..86d3a2f8 --- /dev/null +++ b/sea/sea.js @@ -0,0 +1,270 @@ + + const Gun = (typeof window !== 'undefined' ? window : global).Gun || require('gun/gun') + var EasyIndexedDB = require('./indexed'); + var SafeBuffer = require('./buffer'); + var settings = require('./settings'); + var pbKdf2 = settings.pbkdf2; + var ecdsaKeyProps = settings.ecdsa.pair; + var ecdhKeyProps = settings.ecdh; + var keysToEcdsaJwk = settings.jwk; + var ecdsaSignProps = settings.ecdsa.sign; + var sha256hash = require('./sha256'); + var recallCryptoKey = require('./remember'); + var parseProps = require('./parse'); + // THIS WILL BE DEPRECATED IN FAVOR OF `Gun.SEA`! + // let's extend the gun chain with a `SEA` function. + // maps locally used methods to Gun and returns SEA object. + Gun.chain.SEA = function() { + const root = this.back(-1) + const sea = root._.SEA || (root._.SEA = root.chain()); // create a SEA context + Object.keys(SEA).map((method) => sea[method] = SEA[method]) + return sea + } + // Practical examples about usage found from ./test/common.js + const SEA = { + // This is easy way to use IndexedDB, all methods are Promises + EasyIndexedDB, + // This is Buffer used in SEA and usable from Gun/SEA application also. + // For documentation see https://nodejs.org/api/buffer.html + Buffer: SafeBuffer, + // These SEA functions support now ony Promises or + // async/await (compatible) code, use those like Promises. + // + // Creates a wrapper library around Web Crypto API + // for various AES, ECDSA, PBKDF2 functions we called above. + async proof(pass, salt) { + try { + if (typeof window !== 'undefined') { + // For browser subtle works fine + const key = await subtle.importKey( + 'raw', new TextEncoder().encode(pass), { name: 'PBKDF2' }, false, ['deriveBits'] + ) + const result = await subtle.deriveBits({ + name: 'PBKDF2', + iterations: pbKdf2.iter, + salt: new TextEncoder().encode(salt), + hash: pbKdf2.hash, + }, key, pbKdf2.ks * 8) + pass = getRandomBytes(pass.length) // Erase passphrase for app + return Buffer.from(result, 'binary').toString('base64') + } + // For NodeJS crypto.pkdf2 rocks + const hash = crypto.pbkdf2Sync( + pass, + new TextEncoder().encode(salt), + pbKdf2.iter, + pbKdf2.ks, + pbKdf2.hash.replace('-', '').toLowerCase() + ) + pass = getRandomBytes(pass.length) // Erase passphrase for app + return hash && hash.toString('base64') + } catch (e) { + Gun.log(e) + throw e + } + }, + // Calculate public key KeyID aka PGPv4 (result: 8 bytes as hex string) + async keyid(pub) { + try { + // base64('base64(x):base64(y)') => Buffer(xy) + const pb = Buffer.concat( + Buffer.from(pub, 'base64').toString('utf8').split(':') + .map((t) => Buffer.from(t, 'base64')) + ) + // id is PGPv4 compliant raw key + const id = Buffer.concat([ + Buffer.from([0x99, pb.length / 0x100, pb.length % 0x100]), pb + ]) + const sha1 = await sha1hash(id) + const hash = Buffer.from(sha1, 'binary') + return hash.toString('hex', hash.length - 8) // 16-bit ID as hex + } catch (e) { + Gun.log(e) + throw e + } + }, + async pair() { + try { + const ecdhSubtle = subtleossl || subtle + // First: ECDSA keys for signing/verifying... + const { pub, priv } = await subtle.generateKey(ecdsaKeyProps, true, [ 'sign', 'verify' ]) + .then(async ({ publicKey, privateKey }) => { + const { d: priv } = await subtle.exportKey('jwk', privateKey) + // privateKey scope doesn't leak out from here! + const { x, y } = await subtle.exportKey('jwk', publicKey) + const pub = Buffer.from([ x, y ].join(':')).toString('base64') + return { pub, priv } + }) + // To include PGPv4 kind of keyId: + // const pubId = await SEA.keyid(keys.pub) + // Next: ECDH keys for encryption/decryption... + const { epub, epriv } = await ecdhSubtle.generateKey(ecdhKeyProps, true, ['deriveKey']) + .then(async ({ publicKey, privateKey }) => { + // privateKey scope doesn't leak out from here! + const { d: epriv } = await ecdhSubtle.exportKey('jwk', privateKey) + const { x, y } = await ecdhSubtle.exportKey('jwk', publicKey) + const epub = Buffer.from([ x, y ].join(':')).toString('base64') + return { epub, epriv } + }) + return { pub, priv, /* pubId, */ epub, epriv } + } catch (e) { + Gun.log(e) + throw e + } + }, + // Derive shared secret from other's pub and my epub/epriv + async derive(pub, { epub, epriv }) { + try { + const { importKey, deriveKey, exportKey } = subtleossl || subtle + const keystoecdhjwk = (pub, priv) => { + const [ x, y ] = Buffer.from(pub, 'base64').toString('utf8').split(':') + const jwk = priv ? { d: priv, key_ops: ['decrypt'] } : { key_ops: ['encrypt'] } + return Object.assign(jwk, { + kty: 'EC', + crv: 'P-256', + ext: false, + x, + y + }) + } + const pubLic = await importKey('jwk', keystoecdhjwk(pub), ecdhKeyProps, false, ['deriveKey']) + const props = Object.assign({}, ecdhKeyProps, { public: pubLic }) + const derived = await importKey('jwk', keystoecdhjwk(epub, epriv), ecdhKeyProps, false, ['deriveKey']) + .then(async (privKey) => { + // privateKey scope doesn't leak out from here! + const derivedKey = await deriveKey(props, privKey, { name: 'AES-CBC', length: 256 }, true, [ 'encrypt', 'decrypt' ]) + return exportKey('jwk', derivedKey).then(({ k }) => k) + }) + return derived + } catch (e) { + Gun.log(e) + throw e + } + }, + async sign(data, { pub, priv }) { + try { + const jwk = keysToEcdsaJwk(pub, priv) + const hash = await sha256hash(data) + // privateKey scope doesn't leak out from here! + const binSig = await subtle.importKey(...jwk, ecdsaKeyProps, false, ['sign']) + .then((privKey) => subtle.sign(ecdsaSignProps, privKey, new Uint8Array(hash))) + return Buffer.from(binSig, 'binary').toString('base64') + } catch (e) { + Gun.log(e) + throw e + } + }, + async verify(data, pub, sig) { + try { + const jwk = keysToEcdsaJwk(pub) + const key = await subtle.importKey(...jwk, ecdsaKeyProps, false, ['verify']) + const hash = await sha256hash(data) + const ss = new Uint8Array(Buffer.from(sig, 'base64')) + return await subtle.verify(ecdsaSignProps, key, ss, new Uint8Array(hash)) + } catch (e) { + Gun.log(e) + throw e + } + }, + async enc(data, priv) { + try { + const rands = { s: getRandomBytes(8), iv: getRandomBytes(16) } + const r = Object.keys(rands) + .reduce((obj, key) => Object.assign(obj, { [key]: rands[key].toString('hex') }), {}) + try { + data = (data.slice && data) || JSON.stringify(data) + } catch(e) {} //eslint-disable-line no-empty + const ct = await recallCryptoKey(priv, rands.s) + .then((aesKey) => subtle.encrypt({ // Keeping aesKey scope as private as possible... + name: 'AES-CBC', iv: new Uint8Array(rands.iv) + }, aesKey, new TextEncoder().encode(data))) + Object.assign(r, { ct: Buffer.from(ct, 'binary').toString('base64') }) + return JSON.stringify(r) + } catch (e) { + Gun.log(e) + throw e + } + }, + async dec(data, priv) { + try { + const { s, iv, ct } = parseProps(data) + const mm = { s, iv, ct } + const rands = [ 'iv', 's' ].reduce((obj, key) => Object.assign(obj, { + [key]: new Uint8Array(Buffer.from(mm[key], 'hex')) + }), {}) + const binCt = await recallCryptoKey(priv, rands.s) + .then((aesKey) => subtle.decrypt({ // Keeping aesKey scope as private as possible... + name: 'AES-CBC', iv: rands.iv + }, aesKey, new Uint8Array(Buffer.from(mm.ct, 'base64')))) + return parseProps(new TextDecoder('utf8').decode(binCt)) + } catch (e) { + Gun.log(e) + throw e + } + }, + async write(data, keys) { + try { + // TODO: something's bugging double 'SEA[]' treatment to mm... + let m = data + if (m && m.slice && 'SEA[' === m.slice(0, 4)) { + return m + } + if (data && data.slice) { + // Needs to remove previous signature envelope + while ('SEA[' === m.slice(0, 4)) { + try { + m = JSON.parse(m.slice(3))[0] + } catch (e){ + break + } + } + } + m = (m && m.slice) ? m : JSON.stringify(m) + const signature = await SEA.sign(m, keys) + return `SEA${JSON.stringify([ m, signature ])}` + } catch (e) { + Gun.log(e) + throw e + } + }, + async read(data, pub) { + try { + let d + if (!data) { + return false === pub ? data : undefined + } + if (!data.slice || 'SEA[' !== data.slice(0, 4)) { + return false === pub ? data : undefined + } + let m = parseProps(data.slice(3)) || '' + d = parseProps(m[0]) + if (false === pub) { + return d + } + return (await SEA.verify(m[0], pub, m[1])) ? d : undefined + } catch (e) { + Gun.log(e) + throw e + } + } + } + // Usage of the SEA object changed! Now use like this: + // const gun = new Gun() + // const SEA = gun.SEA() + //Gun.SEA = () => SEA + Gun.SEA = SEA + + // all done! + // 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. + // SEA should be a full suite that is easy and seamless to use. + // Again, scroll naer the top, where I provide an EXAMPLE of how to create a user and sign in. + // Once logged in, the rest of the code you just read handled automatically signing/validating data. + // But all other behavior needs to be equally easy, like opinionated ways of + // Adding friends (trusted public keys), sending private messages, etc. + // Cheers! Tell me what you think. + + try { + module.exports = SEA + } catch (e) {} //eslint-disable-line no-empty + \ No newline at end of file diff --git a/sea/settings.js b/sea/settings.js new file mode 100644 index 00000000..d908b95f --- /dev/null +++ b/sea/settings.js @@ -0,0 +1,36 @@ + + var Buffer = require('./buffer'); + var settings = {}; + // Encryption parameters + const pbKdf2 = { hash: 'SHA-256', iter: 50000, ks: 64 } + + const ecdsaSignProps = { name: 'ECDSA', hash: { name: 'SHA-256' } } + const ecdsaKeyProps = { name: 'ECDSA', namedCurve: 'P-256' } + const ecdhKeyProps = { name: 'ECDH', namedCurve: 'P-256' } + + const _initial_authsettings = { + validity: 12 * 60 * 60, // internally in seconds : 12 hours + hook: (props) => props // { iat, exp, alias, remember } + // or return new Promise((resolve, reject) => resolve(props) + } + // These are used to persist user's authentication "session" + const authsettings = Object.assign({}, _initial_authsettings) + // This creates Web Cryptography API compliant JWK for sign/verify purposes + const keysToEcdsaJwk = (pub, priv) => { + const [ x, y ] = Buffer.from(pub, 'base64').toString('utf8').split(':') + const jwk = priv ? { d: priv, key_ops: ['sign'] } : { key_ops: ['verify'] } + return [ // Use with spread returned value... + 'jwk', + Object.assign(jwk, { x, y, kty: 'EC', crv: 'P-256', ext: false }) + ] + } + + settings.pbkdf2 = pbKdf2; + settings.ecdsa = {}; + settings.ecdsa.pair = ecdsaKeyProps; + settings.ecdsa.sign = ecdsaSignProps; + settings.ecdh = ecdhKeyProps; + settings.jwk = keysToEcdsaJwk; + settings.recall = authsettings; + module.exports = settings; + \ No newline at end of file diff --git a/sea/sha1.js b/sea/sha1.js new file mode 100644 index 00000000..cc2c35a0 --- /dev/null +++ b/sea/sha1.js @@ -0,0 +1,5 @@ + + // This internal func returns SHA-1 hashed data for KeyID generation + const sha1hash = (b) => (subtleossl || subtle).digest('SHA-1', new ArrayBuffer(b)) + module.exports = sha1hash; + \ No newline at end of file diff --git a/sea/sha256.js b/sea/sha256.js new file mode 100644 index 00000000..cb431caf --- /dev/null +++ b/sea/sha256.js @@ -0,0 +1,14 @@ + + var Buffer = require('./buffer'); + var parseProps = require('./parse'); + var settings = require('./settings'); + var pbKdf2 = settings.pbkdf2; + // This internal func returns SHA-256 hashed data for signing + const sha256hash = async (mm) => { + const hashSubtle = subtleossl || subtle + const m = parseProps(mm) + const hash = await hashSubtle.digest(pbKdf2.hash, new TextEncoder().encode(m)) + return Buffer.from(hash) + } + module.exports = sha256hash; + \ No newline at end of file diff --git a/sea/update.js b/sea/update.js new file mode 100644 index 00000000..9b319cdd --- /dev/null +++ b/sea/update.js @@ -0,0 +1,47 @@ + + // TODO: BUG! `SEA` needs to be USED! + const Gun = (typeof window !== 'undefined' ? window : global).Gun || require('gun/gun') + var authsettings = require('./settings'); + var seaIndexedDb = require('./indexed').scope; + // This updates sessionStorage & IndexedDB to persist authenticated "session" + const updateStorage = (proof, key, pin) => async (props) => { + if (!Gun.obj.has(props, 'alias')) { + return // No 'alias' - we're done. + } + if (authsettings.validity && proof && Gun.obj.has(props, 'iat')) { + props.proof = proof + delete props.remember // Not stored if present + + const { alias, alias: id } = props + const remember = { alias, pin } + + try { + const signed = await SEA.write(JSON.stringify(remember), key) + + sessionStorage.setItem('user', alias) + sessionStorage.setItem('remember', signed) + + const encrypted = await SEA.enc(props, pin) + + if (encrypted) { + const auth = await SEA.write(encrypted, key) + await seaIndexedDb.wipe() + await seaIndexedDb.put(id, { auth }) + } + + return props + } catch (err) { + throw { err: 'Session persisting failed!' } + } + } + + // Wiping IndexedDB completely when using random PIN + await seaIndexedDb.wipe() + // And remove sessionStorage data + sessionStorage.removeItem('user') + sessionStorage.removeItem('remember') + + return props + } + module.exports = updateStorage; + \ No newline at end of file diff --git a/sea/user.js b/sea/user.js new file mode 100644 index 00000000..c6674a05 --- /dev/null +++ b/sea/user.js @@ -0,0 +1,223 @@ + + // How does it work? + // TODO: Bug! Need to include SEA! + const Gun = (typeof window !== 'undefined' ? window : global).Gun || require('gun/gun') + var SEA = require('./sea'); + var authRecall = require('./recall'); + var authenticate = require('./authenticate'); + var finalizeLogin = require('./login'); + // let's extend the gun chain with a `user` function. + // only one user can be logged in at a time, per gun instance. + Gun.chain.user = function() { + const root = this.back(-1) // always reference the root gun instance. + let user = root._.user || (root._.user = root.chain()); // create a user context. + // then methods... + [ 'create', // factory + 'auth', // login + 'leave', // logout + 'delete', // account delete + 'recall', // existing auth boostrap + 'alive' // keep/check auth validity + ].map((method)=> user[method] = User[method]) + return user // return the user! + } + function User(){} + // Well first we have to actually create a user. That is what this function does. + Object.assign(User, { + async create(username, pass, cb) { + const root = this.back(-1) + return 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. + if(cb){ resolve = reject = cb } + root.get(`alias/${username}`).get(async (at, ev) => { + ev.off() + 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. + const err = 'User already created!' + Gun.log(err) + return reject({ err }) + } + const salt = Gun.text.random(64) + // pseudo-randomly create a salt, then use CryptoJS's PBKDF2 function to extend the password with it. + try { + const proof = await SEA.proof(pass, salt) + // this will take some short amount of time to produce a proof, which slows brute force attacks. + const pairs = await SEA.pair() + // now we have generated a brand new ECDSA key pair for the user account. + const { pub, priv, epriv } = pairs + // the user's public key doesn't need to be signed. But everything else needs to be signed with it! + const alias = await SEA.write(username, pairs) + const epub = await SEA.write(pairs.epub, pairs) + // to keep the private key safe, we AES encrypt it with the proof of work! + const auth = await SEA.enc({ priv, epriv }, { pub: pairs.epub, key: proof }) + .then((auth) => // TODO: So signedsalt isn't needed? + // SEA.write(salt, pairs).then((signedsalt) => + SEA.write({ salt, auth }, pairs) + // ) + ).catch((e) => { Gun.log('SEA.en or SEA.write calls failed!'); reject(e) }) + const user = { alias, pub, epub, auth } + const tmp = `pub/${pairs.pub}` + // awesome, now we can actually save the user with their public key as their ID. + root.get(tmp).put(user) + // 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))) + // callback that the user has been created. (Note: ok = 0 because we didn't wait for disk to ack) + setTimeout(() => { 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) { + Gun.log('SEA.create failed!') + reject(e) + } + }) + }) + }, + // now that we have created a user, we want to authenticate them! + async auth(alias, pass, cb, opts) { + if(cb && !(cb instanceof Function)){ opts = cb } + const { pin, newpass } = opts || {} + const root = this.back(-1) + + if (!pass && pin) { + try { + return await authRecall(root, { alias, pin }) + } catch (e) { + throw { err: 'Auth attempt failed! Reason: No session data for alias & PIN' } + } + } + + const putErr = (msg) => (e) => { + const { message, err = message || '' } = e + Gun.log(msg) + var error = { err: `${msg} Reason: ${err}` } + if(cb){ cb(error) } + throw error; + } + + try { + const keys = await authenticate(alias, pass, root) + if (!keys) { + return putErr('Auth attempt failed!')({ message: 'No keys' }) + } + const { pub, priv, epub, epriv } = keys + // we're logged in! + if (newpass) { + // password update so encrypt private key using new pwd + salt + try { + const salt = Gun.text.random(64) + const encSigAuth = await SEA.proof(newpass, salt) + .then((key) => + SEA.enc({ priv, epriv }, { pub, key, set: true }) + .then((auth) => SEA.write({ salt, auth }, keys)) + ) + const signedEpub = await SEA.write(epub, keys) + const signedAlias = await SEA.write(alias, keys) + const user = { + pub, + alias: signedAlias, + auth: encSigAuth, + epub: signedEpub + } + // awesome, now we can update the user using public key ID. + root.get(`pub/${user.pub}`).put(user) + // then we're done + var login = finalizeLogin(alias, keys, root, { pin }) + login.catch(putErr('Failed to finalize login with new password!')) + if(cb){ cb(login) } + return login; + } catch (e) { + putErr('Password set attempt failed!')(e) + } + } else { + var login = finalizeLogin(alias, keys, root, { pin }) + login.catch(putErr('Finalizing login failed!')) + if(cb){ cb(login) } + return login; + } + } catch (e) { + putErr('Auth attempt failed!')(e) + } + }, + async leave() { + return await authLeave(this.back(-1)) + }, + // If authenticated user wants to delete his/her account, let's support it! + async delete(alias, pass) { + const root = this.back(-1) + try { + const { pub } = await authenticate(alias, pass, root) + await authLeave(root, alias) + // Delete user data + root.get(`pub/${pub}`).put(null) + // Wipe user data from memory + const { user = { _: {} } } = root._; + // TODO: is this correct way to 'logout' user from Gun.User ? + [ 'alias', 'sea', 'pub' ].map((key) => delete user._[key]) + user._.is = user.is = {} + root.user() + return { ok: 0 } // TODO: proper return codes??? + } catch (e) { + Gun.log('User.delete failed! Error:', e) + throw e // TODO: proper error codes??? + } + }, + // If authentication is to be remembered over reloads or browser closing, + // set validity time in minutes. + async recall(setvalidity, options) { + const root = this.back(-1) + + let validity + let opts + + if (!Gun.val.is(setvalidity)) { + opts = setvalidity + validity = _initial_authsettings.validity + } else { + opts = options + validity = setvalidity * 60 // minutes to seconds + } + + try { + // opts = { hook: function({ iat, exp, alias, proof }) } + // iat == Date.now() when issued, exp == seconds to expire from iat + // How this works: + // called when app bootstraps, with wanted options + // IF authsettings.validity === 0 THEN no remember-me, ever + // IF PIN then signed 'remember' to window.sessionStorage and 'auth' to IndexedDB + authsettings.validity = typeof validity !== 'undefined' + ? validity : _initial_authsettings.validity + authsettings.hook = (Gun.obj.has(opts, 'hook') && typeof opts.hook === 'function') + ? opts.hook : _initial_authsettings.hook + // All is good. Should we do something more with actual recalled data? + return await authRecall(root) + } catch (e) { + const err = 'No session!' + Gun.log(err) + // NOTE! It's fine to resolve recall with reason why not successful + // instead of rejecting... + return { err: (e && e.err) || err } + } + }, + async alive() { + const root = this.back(-1) + try { + // All is good. Should we do something more with actual recalled data? + await authRecall(root) + return root._.user._ + } catch (e) { + const err = 'No session!' + Gun.log(err) + throw { err } + } + } + }) + Gun.chain.trust = function(user) { + // TODO: BUG!!! SEA `node` read listener needs to be async, which means core needs to be async too. + //gun.get('alice').get('age').trust(bob); + if (Gun.is(user)) { + user.get('pub').get((ctx, ev) => { + console.log(ctx, ev) + }) + } + } + + module.exports = User; + \ No newline at end of file diff --git a/test/sea.js b/test/sea.js index 92e409da..2f80eb24 100644 --- a/test/sea.js +++ b/test/sea.js @@ -24,31 +24,34 @@ var root; } }(this)); -if(typeof Buffer === 'undefined'){ - var Buffer = require('buffer').Buffer; +const SEA = Gun.SEA() +const { Buffer, EasyIndexedDB } = SEA + +const seaIndexedDb = new SEA.EasyIndexedDB('SEA', 'GunDB', 1) + +const checkIndexedDB = (key, prop, resolve_) => { + const doIt = (resolve, reject) => seaIndexedDb.get(key, prop) + .then(resolve).catch(reject) + + if (resolve_) { + doIt(resolve_, (e) => { throw e }) + } else { + return new Promise(doIt) + } } -function checkIndexedDB(key, prop, resolve_){ - var result; - Gun.SEA._callonstore_(function(store) { - var getData = store.get(key); - getData.onsuccess = function(){ - result = getData.result && getData.result[prop]; - }; - }, function(){ - resolve_(result); - }); +const setIndexedDB = (key, auth, resolve_) => { + const doIt = (resolve, reject) => seaIndexedDb.put(key, { auth }) + .then(resolve).catch(reject) + + if (resolve_) { + doIt(resolve_, (e) => { throw e }) + } else { + return new Promise(doIt) + } } -function setIndexedDB(key, prop, resolve_){ - Gun.SEA._callonstore_(function(store){ - store.put({id: key, auth: prop}); - }, function(){ - resolve_(); - }); -} - -Gun.SEA && describe('SEA', function(){ +SEA && describe('SEA', function(){ console.log('TODO: SEA! THIS IS AN EARLY ALPHA!!!'); var alias = 'dude'; var pass = 'my secret password'; @@ -56,212 +59,169 @@ Gun.SEA && describe('SEA', function(){ var clearText = 'My precious secret!'; var encKeys = ['ct', 'iv', 's']; - ['callback', 'Promise'].forEach(function(type){ - describe(type+':', function(){ - it('proof', function(done){ - var check = function(proof){ - expect(proof).to.not.be(undefined); - expect(proof).to.not.be(''); - done(); - }; - // proof - generates PBKDF2 hash from user's alias and password - // which is then used to decrypt user's auth record - if(type === 'callback'){ - Gun.SEA.proof(pass, Gun.text.random(64), check); - } else { - Gun.SEA.proof(pass, Gun.text.random(64)).then(check).catch(done); - } - }); + const type = 'Promise' // TODO: this is leftover... + it('proof', function(done){ + var check = function(proof){ + expect(proof).to.not.be(undefined); + expect(proof).to.not.be(''); + done(); + }; + // proof - generates PBKDF2 hash from user's alias and password + // which is then used to decrypt user's auth record + SEA.proof(pass, Gun.text.random(64)).then(check).catch(done); + }); - it('pair', function(done){ - var check = function(key){ - expect(key).to.not.be(undefined); - expect(key).to.not.be(''); - expect(key).to.have.keys(userKeys); - userKeys.map(function(fld){ - expect(key[fld]).to.not.be(undefined); - expect(key[fld]).to.not.be(''); - }); - done(); - }; - // pair - generates ECDH key pair (for new user when created) - if(type === 'callback'){ - Gun.SEA.pair(check); - } else { - Gun.SEA.pair().then(check).catch(done); - } + it('pair', function(done){ + var check = function(key){ + expect(key).to.not.be(undefined); + expect(key).to.not.be(''); + expect(key).to.have.keys(userKeys); + userKeys.map(function(fld){ + expect(key[fld]).to.not.be(undefined); + expect(key[fld]).to.not.be(''); }); + done(); + }; + // pair - generates ECDH key pair (for new user when created) + SEA.pair().then(check).catch(done); + }); - it('keyid', function(done){ - Gun.SEA.pair().then(function(key){ - var check = function(keyid){ - expect(keyid).to.not.be(undefined); - expect(keyid).to.not.be(''); - expect(keyid.length).to.eql(16); - done(); - }; - // keyid - creates 8 byte KeyID from public key - if(type === 'callback'){ - Gun.SEA.keyid(key.pub, check); - } else { - Gun.SEA.keyid(key.pub).then(check); - } - }).catch(function(e){done(e)}); + it('keyid', function(done){ + SEA.pair().then(function(key){ + var check = function(keyid){ + expect(keyid).to.not.be(undefined); + expect(keyid).to.not.be(''); + expect(keyid.length).to.eql(16); + done(); + }; + // keyid - creates 8 byte KeyID from public key + SEA.keyid(key.pub).then(check); + }).catch(function(e){done(e)}); + }); + + it('enc', function(done){ + SEA.pair().then(function(key){ + var check = function(jsonSecret){ + expect(jsonSecret).to.not.be(undefined); + expect(jsonSecret).to.not.be(''); + expect(jsonSecret).to.not.eql(clearText); + var objSecret = JSON.parse(jsonSecret); + expect(objSecret).to.have.keys(encKeys); + encKeys.map(function(key){ + expect(objSecret[key]).to.not.be(undefined); + expect(objSecret[key]).to.not.be(''); + }); + done(); + }; + // en - encrypts JSON data using user's private or derived ECDH key + SEA.enc(clearText, key.priv).then(check); + }).catch(function(e){done(e)}); + }); + + it('sign', function(done){ + SEA.pair().then(function(key){ + var check = function(signature){ + expect(signature).to.not.be(undefined); + expect(signature).to.not.be(''); + expect(signature).to.not.eql(key.pub); + done(); + }; + // sign - calculates signature for data using user's private ECDH key + SEA.sign(key.pub, key).then(check); + }).catch(function(e){done(e)}); + }); + + it('verify', function(done){ + SEA.pair().then(function(key){ + var check = function(ok){ + expect(ok).to.not.be(undefined); + expect(ok).to.not.be(''); + expect(ok).to.be(true); + done(); + }; + // sign - calculates signature for data using user's private ECDH key + SEA.sign(key.pub, key).then(function(signature){ + SEA.verify(key.pub, key.pub, signature).then(check); }); + }).catch(function(e){done(e)}); + }); - it('enc', function(done){ - Gun.SEA.pair().then(function(key){ - var check = function(jsonSecret){ - expect(jsonSecret).to.not.be(undefined); - expect(jsonSecret).to.not.be(''); - expect(jsonSecret).to.not.eql(clearText); - var objSecret = JSON.parse(jsonSecret); - expect(objSecret).to.have.keys(encKeys); - encKeys.map(function(key){ - expect(objSecret[key]).to.not.be(undefined); - expect(objSecret[key]).to.not.be(''); - }); - done(); - }; - // en - encrypts JSON data using user's private or derived ECDH key - if(type === 'callback'){ - Gun.SEA.enc(clearText, key.priv, check); - } else { - Gun.SEA.enc(clearText, key.priv).then(check); - } - }).catch(function(e){done(e)}); + it('dec', function(done){ + SEA.pair().then(function(key){ + var check = function(decText){ + expect(decText).to.not.be(undefined); + expect(decText).to.not.be(''); + expect(decText).to.be.eql(clearText); + done(); + }; + SEA.enc(clearText, key.priv).then(function(jsonSecret){ + // de - decrypts JSON data using user's private or derived ECDH key + SEA.dec(jsonSecret, key.priv).then(check); }); + }).catch(function(e){done(e)}); + }); - it('sign', function(done){ - Gun.SEA.pair().then(function(key){ - var check = function(signature){ - expect(signature).to.not.be(undefined); - expect(signature).to.not.be(''); - expect(signature).to.not.eql(key.pub); - done(); - }; - // sign - calculates signature for data using user's private ECDH key - if(type === 'callback'){ - Gun.SEA.sign(key.pub, key, check); - } else { - Gun.SEA.sign(key.pub, key).then(check); - } - }).catch(function(e){done(e)}); + it('derive', function(done){ + SEA.pair().then(function(txKey){ + return SEA.pair().then(function(rxKey){ + return {tx: txKey, rx: rxKey}; }); + }).then(function(keys){ + var check = function(shared){ + expect(shared).to.not.be(undefined); + expect(shared).to.not.be(''); + [keys.rx.pub, keys.rx.priv, keys.tx.pub, keys.tx.priv] + .map(function(val){ + expect(shared).to.not.eql(val); + }); + done(); + }; + // derive - provides shared secret for both receiver and sender + // which can be used to encrypt or sign data + SEA.derive(keys.rx.pub, keys.tx).then(check); + }).catch(function(e){done(e)}); + }); - it('verify', function(done){ - Gun.SEA.pair().then(function(key){ - var check = function(ok){ - expect(ok).to.not.be(undefined); - expect(ok).to.not.be(''); - expect(ok).to.be(true); - done(); - }; - // sign - calculates signature for data using user's private ECDH key - Gun.SEA.sign(key.pub, key).then(function(signature){ - if(type === 'callback'){ - Gun.SEA.verify(key.pub, key.pub, signature, check); - } else { - Gun.SEA.verify(key.pub, key.pub, signature).then(check); - } - }); - }).catch(function(e){done(e)}); - }); - - it('dec', function(done){ - Gun.SEA.pair().then(function(key){ - var check = function(decText){ - expect(decText).to.not.be(undefined); - expect(decText).to.not.be(''); - expect(decText).to.be.eql(clearText); - done(); - }; - Gun.SEA.enc(clearText, key.priv).then(function(jsonSecret){ - // de - decrypts JSON data using user's private or derived ECDH key - if(type === 'callback'){ - Gun.SEA.dec(jsonSecret, key.priv, check); - } else { - Gun.SEA.dec(jsonSecret, key.priv).then(check); - } - }); - }).catch(function(e){done(e)}); - }); - - it('derive', function(done){ - Gun.SEA.pair().then(function(txKey){ - return Gun.SEA.pair().then(function(rxKey){ - return {tx: txKey, rx: rxKey}; - }); - }).then(function(keys){ - var check = function(shared){ - expect(shared).to.not.be(undefined); - expect(shared).to.not.be(''); - [keys.rx.pub, keys.rx.priv, keys.tx.pub, keys.tx.priv] - .map(function(val){ - expect(shared).to.not.eql(val); - }); - done(); - }; - // derive - provides shared secret for both receiver and sender - // which can be used to encrypt or sign data - if(type === 'callback'){ - Gun.SEA.derive(keys.rx.pub, keys.tx, check); - } else { - Gun.SEA.derive(keys.rx.pub, keys.tx).then(check); - } - }).catch(function(e){done(e)}); - }); - - it('write', function(done){ - Gun.SEA.pair().then(function(key){ - Gun.SEA.sign(key.pub, key).then(function(signature){ - var check = function(result){ - var parts; - try{ - expect(result).to.not.be(undefined); - expect(result).to.not.be(''); - expect(result.slice(0, 4)).to.eql('SEA['); - parts = JSON.parse(result.slice(3)); - expect(parts).to.not.be(undefined); - expect(parts[0]).to.be.eql(key.pub); - // expect(parts[1]).to.be.eql(signature); - }catch(e){ return done(e) } - Gun.SEA.verify(key.pub, key.pub, parts[1]).then(function(flag){ - expect(flag).to.be.true; - done(); - }); - }; - // write - wraps data to 'SEA["data","signature"]' - if(type === 'callback'){ - Gun.SEA.write(key.pub, key, check); - } else { - Gun.SEA.write(key.pub, key).then(check); - } - }); - }).catch(function(e){done(e)}); - }); - - it('read', function(done){ - Gun.SEA.pair().then(function(key){ - var check = function(result){ + it('write', function(done){ + SEA.pair().then(function(key){ + SEA.sign(key.pub, key).then(function(signature){ + var check = function(result){ + var parts; + try{ expect(result).to.not.be(undefined); expect(result).to.not.be(''); - expect(result).to.be.equal(key.pub); + expect(result.slice(0, 4)).to.eql('SEA['); + parts = JSON.parse(result.slice(3)); + expect(parts).to.not.be(undefined); + expect(parts[0]).to.be.eql(key.pub); + // expect(parts[1]).to.be.eql(signature); + }catch(e){ return done(e) } + SEA.verify(key.pub, key.pub, parts[1]).then(function(flag){ + expect(flag).to.be.true; done(); - }; - Gun.SEA.sign(key.pub, key).then(function(signature){ - Gun.SEA.write(key.pub, key).then(function(signed){ - // read - unwraps data from 'SEA["data","signature"]' - if(type === 'callback'){ - Gun.SEA.read(signed, key.pub, check); - } else { - Gun.SEA.read(signed, key.pub).then(check); - } - }); }); - }).catch(function(e){done(e)}); + }; + // write - wraps data to 'SEA["data","signature"]' + SEA.write(key.pub, key).then(check); }); - }); + }).catch(function(e){done(e)}); + }); + + it('read', function(done){ + SEA.pair().then(function(key){ + var check = function(result){ + expect(result).to.not.be(undefined); + expect(result).to.not.be(''); + expect(result).to.be.equal(key.pub); + done(); + }; + SEA.sign(key.pub, key).then(function(signature){ + SEA.write(key.pub, key).then(function(signed){ + // read - unwraps data from 'SEA["data","signature"]' + SEA.read(signed, key.pub).then(check); + }); + }); + }).catch(function(e){done(e)}); }); }); @@ -274,7 +234,7 @@ Gun().user && describe('Gun', function(){ var user = gun.user(); Gun.log.off = true; // Supress all console logging - var throwOutUser = function(wipeStorageData){ + const throwOutUser = (wipeStorageData, done) => { // Get rid of authenticated Gun user var user = gun.back(-1)._.user; // TODO: is this correct way to 'logout' user from Gun.User ? @@ -287,826 +247,748 @@ Gun().user && describe('Gun', function(){ // ... and persisted session sessionStorage.removeItem('remember'); sessionStorage.removeItem('alias'); - Gun.SEA._callonstore_(function(store) { - var act = store.clear(); // Wipes whole IndexedDB - act.onsuccess = function(){}; - }); + if (typeof done === 'function') { + seaIndexedDb.wipe().then(done) + return + } else { + return seaIndexedDb.wipe() + } } - }; + return Promise.resolve() + } - ['callback', 'Promise'].forEach(function(type){ - describe(type+':', function(){ - beforeEach(function(done){ - // Simulate browser reload - throwOutUser(true); + const type = 'Promise' // TODO: this is leftover... + // Simulate browser reload + beforeEach((done) => { throwOutUser(true, done) }) + + describe('create', function(){ + + it('new', function(done){ + var check = function(ack){ + try{ + expect(ack).to.not.be(undefined); + expect(ack).to.not.be(''); + expect(ack).to.have.keys([ 'ok', 'pub' ]); + }catch(e){ done(e); return } done(); + }; + // Gun.user.create - creates new user + user.create(alias+type, pass).then(check).catch(done); + }); + + it('conflict', function(done){ + Gun.log.off = true; // Supress all console logging + var check = function(ack){ + try{ + expect(ack).to.not.be(undefined); + expect(ack).to.not.be(''); + expect(ack).to.have.key('err'); + expect(ack.err).not.to.be(undefined); + expect(ack.err).not.to.be(''); + expect(ack.err.toLowerCase().indexOf('already created')).not.to.be(-1); + }catch(e){ done(e); return } + done(); + }; + // Gun.user.create - fails to create existing user + user.create(alias+type, pass).then(function(ack){ + done('Failed to decline creating existing user!'); + }).catch(check); + }); + }); + + describe('auth', function(){ + const checkStorage = (done, notStored) => () => { + const checkValue = (data, val) => { + if (notStored) { + expect(typeof data !== 'undefined' && data !== null && data !== '') + .to.not.eql(true) + } else { + expect(data).to.not.be(undefined) + expect(data).to.not.be('') + if (val) { + expect(data).to.eql(val) + } + } + } + const alias = root.sessionStorage.getItem('user') + checkValue(alias) + checkValue(root.sessionStorage.getItem('remember')) + if (alias) { + checkIndexedDB(alias, 'auth').then((auth) => { + checkValue(auth) + done() + }).catch(done) + } else { + done() + } + } + + it('login', function(done){ + var check = function(ack){ + try{ + expect(ack).to.not.be(undefined); + expect(ack).to.not.be(''); + expect(ack).to.not.have.key('err'); + }catch(e){ done(e); return } + done(); + }; + // Gun.user.auth - authenticates existing user + user.auth(alias+type, pass).then(check).catch(done); + }); + + it('wrong password', function(done){ + var check = function(ack){ + try{ + expect(ack).to.not.be(undefined); + expect(ack).to.not.be(''); + expect(ack).to.have.key('err'); + expect(ack.err).to.not.be(undefined); + expect(ack.err).to.not.be(''); + expect(ack.err.toLowerCase().indexOf('failed to decrypt secret')) + .not.to.be(-1); + }catch(e){ done(e); return } + done(); + }; + user.auth(alias+type, pass+'not').then(function(ack){ + done('Unexpected login success!'); + }).catch(check); + }); + + it('unknown alias', function(done){ + var check = function(ack){ + try{ + expect(ack).to.not.be(undefined); + expect(ack).to.not.be(''); + expect(ack).to.have.key('err'); + expect(ack.err).to.not.be(undefined); + expect(ack.err).to.not.be(''); + expect(ack.err.toLowerCase().indexOf('no user')).not.to.be(-1); + }catch(e){ done(e); return } + done(); + }; + user.auth(alias+type+'not', pass).then(function(ack){ + done('Unexpected login success!'); + }).catch(check); + }); + + it('new password', function(done){ + var check = function(ack){ + try{ + expect(ack).to.not.be(undefined); + expect(ack).to.not.be(''); + expect(ack).to.not.have.key('err'); + }catch(e){ done(e); return } + done(); + }; + // Gun.user.auth - with newpass props sets new password + user.auth(alias+type, pass, {newpass: pass+' new'}).then(check) + .catch(done); + }); + + it('failed new password', function(done){ + var check = function(ack){ + try{ + expect(ack).to.not.be(undefined); + expect(ack).to.not.be(''); + expect(ack).to.have.key('err'); + expect(ack.err).to.not.be(undefined); + expect(ack.err).to.not.be(''); + expect(ack.err.toLowerCase().indexOf('failed to decrypt secret')) + .not.to.be(-1); + }catch(e){ done(e); return } + done(); + }; + user.auth(alias+type, pass+'not', {newpass: pass+' new'}) + .then(function(ack){ + done('Unexpected password change success!'); + }).catch(check); + }); + + it('without PIN auth session stored', function(done){ + user.auth(alias+type, pass+' new').then(checkStorage(done)).catch(done); + }); + + it('with PIN auth session stored', function(done){ + user.auth(alias+type, pass+' new', { pin: 'PIN' }) + .then(checkStorage(done)).catch(done) + }) + + it('without PIN and zero validity no auth session storing', function(done){ + user.recall(0).then(function(){ + user.auth(alias+type, pass+' new') + .then(checkStorage(done, true)).catch(done); }); + }); - describe('create', function(){ - - it('new', function(done){ - var check = function(ack){ - try{ - expect(ack).to.not.be(undefined); - expect(ack).to.not.be(''); - expect(ack).to.have.keys([ 'ok', 'pub' ]); - }catch(e){ done(e); return } - done(); - }; - // Gun.user.create - creates new user - if(type === 'callback'){ - user.create(alias+type, pass, check); - } else { - user.create(alias+type, pass).then(check).catch(done); - } - }); - - it('conflict', function(done){ - Gun.log.off = true; // Supress all console logging - var check = function(ack){ - try{ - expect(ack).to.not.be(undefined); - expect(ack).to.not.be(''); - expect(ack).to.have.key('err'); - expect(ack.err).not.to.be(undefined); - expect(ack.err).not.to.be(''); - expect(ack.err.toLowerCase().indexOf('already created')).not.to.be(-1); - }catch(e){ done(e); return } - done(); - }; - // Gun.user.create - fails to create existing user - if(type === 'callback'){ - user.create(alias+type, pass, check); - } else { - user.create(alias+type, pass).then(function(ack){ - done('Failed to decline creating existing user!'); - }).catch(check); - } - }); + it('with PIN and zero validity no auth session storing', function(done){ + user.recall(0).then(function(){ + user.auth(alias+type, pass+' new', {pin: 'PIN'}) + .then(checkStorage(done, true)).catch(done); }); + }); + }); - describe('auth', function(){ - var checkStorage = function(done, notStored){ - return function(){ - var checkValue = function(data, val){ - if(notStored){ - expect(typeof data !== 'undefined' && data !== null && data !== '') - .to.not.eql(true); - } else { - expect(data).to.not.be(undefined); - expect(data).to.not.be(''); - if(val){ expect(data).to.eql(val) } - } - }; - var alias = root.sessionStorage.getItem('user'); - checkValue(alias); - checkValue(root.sessionStorage.getItem('remember')); - if(alias){ - checkIndexedDB(alias, 'auth', function(auth){ - checkValue(auth); - done(); - }); - } else { - done(); - } - }; - }; + describe('leave', function(){ + it('valid session', function(done){ + var check = function(ack){ + try{ + expect(ack).to.not.be(undefined); + expect(ack).to.not.be(''); + expect(ack).to.not.have.key('err'); + expect(ack).to.have.key('ok'); + expect(gun.back(-1)._.user._).to.not.have.keys([ 'sea', 'pub' ]); + // expect(gun.back(-1)._.user).to.not.be.ok(); + }catch(e){ done(e); return } + done(); + }; + var usr = alias+type+'leave'; + user.create(usr, pass).then(function(ack){ + expect(ack).to.not.be(undefined); + expect(ack).to.not.be(''); + expect(ack).to.have.keys([ 'ok', 'pub' ]); + user.auth(usr, pass).then(function(usr){ + try{ + expect(usr).to.not.be(undefined); + expect(usr).to.not.be(''); + expect(usr).to.not.have.key('err'); + expect(usr).to.have.key('put'); + }catch(e){ done(e); return } + // Gun.user.leave - performs logout for authenticated user + user.leave().then(check).catch(done); + }).catch(done); + }).catch(done); + }); - it('login', function(done){ - var check = function(ack){ - try{ - expect(ack).to.not.be(undefined); - expect(ack).to.not.be(''); - expect(ack).to.not.have.key('err'); - }catch(e){ done(e); return } - done(); - }; - // Gun.user.auth - authenticates existing user - if(type === 'callback'){ - user.auth(alias+type, pass, check); - } else { - user.auth(alias+type, pass).then(check).catch(done); - } - }); + it('no session', function(done){ + var check = function(ack){ + try{ + expect(ack).to.not.be(undefined); + expect(ack).to.not.be(''); + expect(ack).to.not.have.key('err'); + expect(ack).to.have.key('ok'); + }catch(e){ done(e); return } + done(); + }; + expect(gun.back(-1)._.user).to.not.have.keys([ 'sea', 'pub' ]); + user.leave().then(check).catch(done); + }); + }); - it('wrong password', function(done){ - var check = function(ack){ - try{ - expect(ack).to.not.be(undefined); - expect(ack).to.not.be(''); - expect(ack).to.have.key('err'); - expect(ack.err).to.not.be(undefined); - expect(ack.err).to.not.be(''); - expect(ack.err.toLowerCase().indexOf('failed to decrypt secret')) - .not.to.be(-1); - }catch(e){ done(e); return } - done(); - }; - if(type === 'callback'){ - user.auth(alias+type, pass+'not', check); - } else { - user.auth(alias+type, pass+'not').then(function(ack){ - done('Unexpected login success!'); - }).catch(check); - } - }); + describe('delete', function(){ + var usr = alias+type+'del'; - it('unknown alias', function(done){ - var check = function(ack){ - try{ - expect(ack).to.not.be(undefined); - expect(ack).to.not.be(''); - expect(ack).to.have.key('err'); - expect(ack.err).to.not.be(undefined); - expect(ack.err).to.not.be(''); - expect(ack.err.toLowerCase().indexOf('no user')).not.to.be(-1); - }catch(e){ done(e); return } - done(); - }; - if(type === 'callback'){ - user.auth(alias+type+'not', pass, check); - } else { - user.auth(alias+type+'not', pass).then(function(ack){ - done('Unexpected login success!'); - }).catch(check); - } - }); - - it('new password', function(done){ - var check = function(ack){ - try{ - expect(ack).to.not.be(undefined); - expect(ack).to.not.be(''); - expect(ack).to.not.have.key('err'); - }catch(e){ done(e); return } - done(); - }; - // Gun.user.auth - with newpass props sets new password - if(type === 'callback'){ - user.auth(alias+type, pass, check, {newpass: pass+' new'}); - } else { - user.auth(alias+type, pass, {newpass: pass+' new'}).then(check) - .catch(done); - } - }); - - it('failed new password', function(done){ - var check = function(ack){ - try{ - expect(ack).to.not.be(undefined); - expect(ack).to.not.be(''); - expect(ack).to.have.key('err'); - expect(ack.err).to.not.be(undefined); - expect(ack.err).to.not.be(''); - expect(ack.err.toLowerCase().indexOf('failed to decrypt secret')) - .not.to.be(-1); - }catch(e){ done(e); return } - done(); - }; - if(type === 'callback'){ - user.auth(alias+type, pass+'not', check, {newpass: pass+' new'}); - } else { - user.auth(alias+type, pass+'not', {newpass: pass+' new'}) - .then(function(ack){ - done('Unexpected password change success!'); - }).catch(check); - } - }); - - it('without PIN auth session stored', function(done){ - user.auth(alias+type, pass+' new').then(checkStorage(done)).catch(done); - }); - - it('with PIN auth session stored', function(done){ - if(type === 'callback'){ - user.auth(alias+type, pass+' new', checkStorage(done), {pin: 'PIN'}); - } else { - user.auth(alias+type, pass+' new', {pin: 'PIN'}) - .then(checkStorage(done)).catch(done); - } - }); - - it('without PIN and zero validity no auth session storing', function(done){ - user.recall(0).then(function(){ - user.auth(alias+type, pass+' new') - .then(checkStorage(done, true)).catch(done); - }); - }); - - it('with PIN and zero validity no auth session storing', function(done){ - user.recall(0).then(function(){ - user.auth(alias+type, pass+' new', {pin: 'PIN'}) - .then(checkStorage(done, true)).catch(done); - }); - }); + var createUser = function(a, p){ + return user.create(a, p).then(function(ack){ + expect(ack).to.not.be(undefined); + expect(ack).to.not.be(''); + expect(ack).to.have.keys([ 'ok', 'pub' ]); + return ack; }); - - describe('leave', function(){ - it('valid session', function(done){ - var check = function(ack){ - try{ - expect(ack).to.not.be(undefined); - expect(ack).to.not.be(''); - expect(ack).to.not.have.key('err'); - expect(ack).to.have.key('ok'); - expect(gun.back(-1)._.user._).to.not.have.keys([ 'sea', 'pub' ]); - // expect(gun.back(-1)._.user).to.not.be.ok(); - }catch(e){ done(e); return } - done(); - }; - var usr = alias+type+'leave'; - user.create(usr, pass).then(function(ack){ - expect(ack).to.not.be(undefined); - expect(ack).to.not.be(''); - expect(ack).to.have.keys([ 'ok', 'pub' ]); - user.auth(usr, pass).then(function(usr){ - try{ - expect(usr).to.not.be(undefined); - expect(usr).to.not.be(''); - expect(usr).to.not.have.key('err'); - expect(usr).to.have.key('put'); - }catch(e){ done(e); return } - // Gun.user.leave - performs logout for authenticated user - if(type === 'callback'){ - user.leave(check); - } else { - user.leave().then(check).catch(done); - } - }).catch(done); - }).catch(done); - }); - - it('no session', function(done){ - var check = function(ack){ - try{ - expect(ack).to.not.be(undefined); - expect(ack).to.not.be(''); - expect(ack).to.not.have.key('err'); - expect(ack).to.have.key('ok'); - }catch(e){ done(e); return } - done(); - }; + }; + var check = function(done){ + return function(ack){ + try{ + expect(ack).to.not.be(undefined); + expect(ack).to.not.be(''); + expect(ack).to.not.have.key('err'); + expect(ack).to.have.key('ok'); expect(gun.back(-1)._.user).to.not.have.keys([ 'sea', 'pub' ]); - if(type === 'callback'){ - user.leave(check); - } else { - user.leave().then(check).catch(done); - } - }); - }); + }catch(e){ done(e); return } + done(); + }; + }; - describe('delete', function(){ - var usr = alias+type+'del'; - - var createUser = function(a, p){ - return user.create(a, p).then(function(ack){ + it('existing authenticated user', function(done){ + createUser(usr, pass).then(function(){ + user.auth(usr, pass).then(function(ack){ + try{ expect(ack).to.not.be(undefined); expect(ack).to.not.be(''); - expect(ack).to.have.keys([ 'ok', 'pub' ]); - return ack; - }); - }; - var check = function(done){ - return function(ack){ - try{ - expect(ack).to.not.be(undefined); - expect(ack).to.not.be(''); - expect(ack).to.not.have.key('err'); - expect(ack).to.have.key('ok'); - expect(gun.back(-1)._.user).to.not.have.keys([ 'sea', 'pub' ]); - }catch(e){ done(e); return } - done(); - }; - }; + expect(ack).to.not.have.key('err'); + expect(ack).to.have.key('put'); + }catch(e){ done(e); return } + // Gun.user.delete - deletes existing user account + user.delete(usr, pass).then(check(done)).catch(done); + }).catch(done); + }).catch(done); + }); - it('existing authenticated user', function(done){ - createUser(usr, pass).then(function(){ - user.auth(usr, pass).then(function(ack){ - try{ - expect(ack).to.not.be(undefined); - expect(ack).to.not.be(''); - expect(ack).to.not.have.key('err'); - expect(ack).to.have.key('put'); - }catch(e){ done(e); return } - // Gun.user.delete - deletes existing user account - if(type === 'callback'){ - user.delete(usr, pass, check(done)); - } else { - user.delete(usr, pass).then(check(done)).catch(done); - } - }).catch(done); - }).catch(done); - }); + it('unauthenticated existing user', function(done){ + createUser(usr, pass).catch(function(){}) + .then(function(){ + user.delete(usr, pass).then(check(done)).catch(done); + }); + }); - it('unauthenticated existing user', function(done){ - createUser(usr, pass).catch(function(){}) - .then(function(){ - if(type === 'callback'){ - user.delete(usr, pass, check(done)); - } else { - user.delete(usr, pass).then(check(done)).catch(done); + it('non-existing user', function(done){ + var notFound = function(ack){ + try{ + expect(ack).to.not.be(undefined); + expect(ack).to.not.be(''); + expect(ack).to.not.have.key('put'); + expect(ack).to.have.key('err'); + expect(ack.err.toLowerCase().indexOf('no user')).not.to.be(-1); + }catch(e){ done(e); return } + done(); + }; + user.delete('someone', 'password guess').then(function(){ + done('Unexpectedly deleted guessed user!'); + }).catch(notFound); + }); + }); + + describe('recall (from IndexedDB)', function(){ + var doCheck = function(done, hasPin, wantAck){ + expect(typeof done).to.be('function'); + return function(ack){ + var user = root.sessionStorage.getItem('user'); + var sRemember = root.sessionStorage.getItem('remember'); + expect(user).to.not.be(undefined); + expect(user).to.not.be(''); + expect(sRemember).to.not.be(undefined); + expect(sRemember).to.not.be(''); + + var ret; + if(wantAck && ack){ + ['err', 'pub', 'sea', 'alias', 'put'].forEach(function(key){ + if(typeof ack[key] !== 'undefined'){ + (ret = ret || {})[key] = ack[key]; } }); + } + // NOTE: done can be Promise returning function + return !hasPin || !wantAck || !ack ? done(ret) + : new Promise(function(resolve){ + checkIndexedDB(ack.alias, 'auth', function(auth){ + expect(auth).to.not.be(undefined); + expect(auth).to.not.be(''); + resolve(done(wantAck && Object.assign(ret || {}, {auth: auth}))); + }); }); - - it('non-existing user', function(done){ - var notFound = function(ack){ - try{ - expect(ack).to.not.be(undefined); - expect(ack).to.not.be(''); - expect(ack).to.not.have.key('put'); - expect(ack).to.have.key('err'); - expect(ack.err.toLowerCase().indexOf('no user')).not.to.be(-1); - }catch(e){ done(e); return } - done(); - }; - if(type === 'callback'){ - user.delete('someone', 'password guess', notFound); - } else { - user.delete('someone', 'password guess').then(function(){ - done('Unexpectedly deleted guessed user!'); - }).catch(notFound); - } + }; + }; + // This re-constructs 'remember-me' data modified by manipulate func + var manipulateStorage = function(manipulate, pin){ + expect(typeof manipulate).to.be('function'); + // We'll use Gun internal User data + var usr = gun.back(-1)._.user; + expect(usr).to.not.be(undefined); + expect(usr).to.have.key('_'); + expect(usr._).to.have.keys(['pub', 'sea']); + // ... to validate 'remember' data + pin = pin && Buffer.from(pin, 'utf8').toString('base64'); + return !pin ? Promise.resolve(sessionStorage.getItem('remember')) + : new Promise(function(resolve){ + checkIndexedDB(usr._.alias, 'auth', resolve); + }).then(function(remember){ + return SEA.read(remember, usr._.pub).then(function(props){ + return !pin ? props + : SEA.dec(props, pin); + }); + }).then(function(props){ + try{ props && (props = JSON.parse(props)) }catch(e){} //eslint-disable-line no-empty + return props; + }).then(manipulate).then(function(props){ + expect(props).to.not.be(undefined); + expect(props).to.not.be(''); + var keys = {pub: usr._.pub, priv: usr._.sea.priv}; + return SEA.write(JSON.stringify(props), keys) + .then(function(remember){ + return !pin ? sessionStorage.setItem('remember', remember) + : SEA.enc(remember, pin).then(function(encauth){ + return new Promise(function(resolve){ + setIndexedDB(usr._.alias, encauth, resolve); + }); + }); }); }); + }; - describe('recall (from IndexedDB)', function(){ - var doCheck = function(done, hasPin, wantAck){ - expect(typeof done).to.be('function'); - return function(ack){ - var user = root.sessionStorage.getItem('user'); - var sRemember = root.sessionStorage.getItem('remember'); - expect(user).to.not.be(undefined); - expect(user).to.not.be(''); - expect(sRemember).to.not.be(undefined); - expect(sRemember).to.not.be(''); + it('with PIN auth session stores', function(done){ + var doAction = function(){ + user.auth(alias+type, pass+' new', {pin: 'PIN'}) + .then(doCheck(done, true)).catch(done); + }; + user.recall().then(doAction).catch(done); + }); - var ret; - if(wantAck && ack){ - ['err', 'pub', 'sea', 'alias', 'put'].forEach(function(key){ - if(typeof ack[key] !== 'undefined'){ - (ret = ret || {})[key] = ack[key]; - } - }); - } - // NOTE: done can be Promise returning function - return !hasPin || !wantAck || !ack ? done(ret) - : new Promise(function(resolve){ - checkIndexedDB(ack.alias, 'auth', function(auth){ - expect(auth).to.not.be(undefined); - expect(auth).to.not.be(''); - resolve(done(wantAck && Object.assign(ret || {}, {auth: auth}))); - }); - }); - }; - }; - // This re-constructs 'remember-me' data modified by manipulate func - var manipulateStorage = function(manipulate, pin){ - expect(typeof manipulate).to.be('function'); - // We'll use Gun internal User data - var usr = gun.back(-1)._.user; + it('without PIN auth session stores', function(done){ + var doAction = function(){ + user.auth(alias+type, pass+' new').then(doCheck(done)); + }; + user.leave().then(function(){ + user.recall().then(doAction).catch(done); + }).catch(done); + }); + + it('no validity no session storing', function(done){ + var doAction = function(){ + user.auth(alias+type, pass+' new').then(doCheck(done)).catch(done); + }; + user.recall(0).then(doAction).catch(done); + }); + + it('with validity but no PIN stores using random PIN', function(done){ + var doAction = function(){ + user.auth(alias+type, pass+' new').then(doCheck(done)).catch(done); + }; + user.recall(12 * 60).then(doAction) + .catch(done); + }); + + it('validity and auth with PIN but storage empty', function(done){ + user.auth(alias+type, pass+' new').then(function(usr){ + var sUser; + var sRemember; + try{ expect(usr).to.not.be(undefined); - expect(usr).to.have.key('_'); - expect(usr._).to.have.keys(['pub', 'sea']); - // ... to validate 'remember' data - pin = pin && new Buffer(pin, 'utf8').toString('base64'); - return !pin ? Promise.resolve(sessionStorage.getItem('remember')) - : new Promise(function(resolve){ - checkIndexedDB(usr._.alias, 'auth', resolve); - }).then(function(remember){ - return Gun.SEA.read(remember, usr._.pub).then(function(props){ - return !pin ? props - : Gun.SEA.dec(props, pin); + expect(usr).to.not.be(''); + expect(usr).to.not.have.key('err'); + expect(usr).to.have.key('put'); + + sUser = root.sessionStorage.getItem('user'); + expect(sUser).to.be(alias+type); + + sRemember = root.sessionStorage.getItem('remember'); + expect(sRemember).to.not.be(undefined); + expect(sRemember).to.not.be(''); + }catch(e){ done(e); return } + user.leave().then(function(ack){ + try{ + expect(ack).to.have.key('ok'); + expect(gun.back(-1)._.user).to.not.have.keys([ 'sea', 'pub' ]); + expect(root.sessionStorage.getItem('user')).to.not.be(sUser); + expect(root.sessionStorage.getItem('remember')).to.not.be(sRemember); + }catch(e){ done(e); return } + // Restore but leave IndexedDB empty + root.sessionStorage.setItem('user', sUser); + root.sessionStorage.setItem('remember', sRemember); + + user.recall(12 * 60).then( + doCheck(function(ack){ + expect(ack).to.have.key('err'); + expect(ack.err.toLowerCase().indexOf('no session')).to.not.be(-1); + checkIndexedDB(alias+type, 'auth', function(auth){ + expect((typeof auth !== 'undefined' && auth !== null && auth !== '')) + .to.not.eql(true); + done(); + }); + }, false, true)) + .catch(done); + }).catch(done); + }).catch(done); + }); + + it('valid session bootstrap', function(done){ + var sUser; + var sRemember; + var iAuth; + user.auth(alias+type, pass+' new', {pin: 'PIN'}).then(function(usr){ + try{ + expect(usr).to.not.be(undefined); + expect(usr).to.not.be(''); + expect(usr).to.not.have.key('err'); + expect(usr).to.have.key('put'); + expect(root.sessionStorage.getItem('user')).to.be(alias+type); + expect(root.sessionStorage.getItem('remember')).to.not.be(undefined); + expect(root.sessionStorage.getItem('remember')).to.not.be(''); + + sUser = root.sessionStorage.getItem('user'); + sRemember = root.sessionStorage.getItem('remember'); + }catch(e){ done(e); return } + + return new Promise(function(resolve){ + checkIndexedDB(sUser, 'auth', function(auth){ resolve(iAuth = auth) }); + }); + }).then(function(){ + return user.leave().then(function(ack){ + try{ + expect(ack).to.have.key('ok'); + expect(gun.back(-1)._.user).to.not.have.keys([ 'sea', 'pub' ]); + expect(root.sessionStorage.getItem('user')).to.not.be(sUser); + expect(root.sessionStorage.getItem('remember')).to.not.be(sRemember); + }catch(e){ done(e); return } + + return new Promise(function(resolve){ + checkIndexedDB(sUser, 'auth', function(auth){ + expect(auth).to.not.be(iAuth); + resolve(); }); - }).then(function(props){ - try{ props && (props = JSON.parse(props)) }catch(e){} //eslint-disable-line no-empty - return props; - }).then(manipulate).then(function(props){ + }); + }).then(function(){ + root.sessionStorage.setItem('user', sUser); + root.sessionStorage.setItem('remember', sRemember); + + return new Promise(function(resolve){ + setIndexedDB(sUser, iAuth, resolve); + }); + }).then(function(){ + user.recall(12 * 60).then(doCheck(done)) + .catch(done); + }).catch(done); + }).catch(done); + }); + + it('valid session bootstrap using alias & PIN', function(done){ + let sRemember + user.recall(12 * 60).then(function(){ + return user.auth(alias+type, pass+' new', {pin: 'PIN'}); + }).then(doCheck(function(ack){ + // Let's save remember props + var sUser = root.sessionStorage.getItem('user'); + sRemember = root.sessionStorage.getItem('remember') + var iAuth = ack.auth; + return new Promise(function(resolve){ + checkIndexedDB(sUser, 'auth', function(auth){ + iAuth = auth; + resolve(user.leave()); // Then logout user + }); + }).then(function(ack){ + try{ + expect(ack).to.have.key('ok'); + expect(gun.back(-1)._.user).to.not.have.keys([ 'sea', 'pub' ]); + expect(root.sessionStorage.getItem('user')).to.not.be(sUser); + expect(root.sessionStorage.getItem('remember')).to.not.be(sRemember); + }catch(e){ done(e); return } + return new Promise(function(resolve){ + checkIndexedDB(sUser, 'auth', function(auth){ + try{ expect(auth).to.not.be(iAuth) }catch(e){ done(e) } + // Then restore IndexedDB but skip sessionStorage remember + setIndexedDB(sUser, iAuth, function(){ + root.sessionStorage.setItem('user', sUser); + resolve(ack); + }); + }); + }); + }); + }, true, true)).then(function(){ + // Then try to recall authentication + return user.recall(12 * 60).then(function(props){ + try{ expect(props).to.not.be(undefined); expect(props).to.not.be(''); - var keys = {pub: usr._.pub, priv: usr._.sea.priv}; - return Gun.SEA.write(JSON.stringify(props), keys) - .then(function(remember){ - return !pin ? sessionStorage.setItem('remember', remember) - : Gun.SEA.enc(remember, pin).then(function(encauth){ - return new Promise(function(resolve){ - setIndexedDB(usr._.alias, encauth, resolve); - }); + expect(props).to.have.key('err'); + // Which fails to missing PIN + expect(props.err.toLowerCase() + .indexOf('missing pin')).not.to.be(-1); + }catch(e){ done(e); return } + root.sessionStorage.setItem('remember', sRemember) + // Ok, time to try auth with alias & PIN + return user.auth(alias+type, undefined, {pin: 'PIN'}); + }); + }).then(doCheck(function(usr){ + try{ + expect(usr).to.not.be(undefined); + expect(usr).to.not.be(''); + expect(usr).to.not.have.key('err'); + expect(usr).to.have.key('put'); + }catch(e){ done(e); return } + // We've recalled authenticated session using alias & PIN! + done(); + }, true, true)).catch(done); + }); + + it('valid session fails to bootstrap with alias & wrong PIN', + function(done){ + user.recall(12 * 60).then(function(){ + return user.auth(alias+type, pass+' new', {pin: 'PIN'}); + }).then(doCheck(function(ack){ + var sUser = root.sessionStorage.getItem('user'); + var sRemember = root.sessionStorage.getItem('remember'); + var iAuth = ack.auth; + return new Promise(function(resolve){ + checkIndexedDB(sUser, 'auth', function(auth){ + iAuth = auth; + resolve(user.leave()); // Then logout user + }); + }).then(function(ack){ + try{ + expect(ack).to.have.key('ok'); + expect(gun.back(-1)._.user).to.not.have.keys([ 'sea', 'pub' ]); + expect(root.sessionStorage.getItem('user')).to.not.be(sUser); + expect(root.sessionStorage.getItem('remember')).to.not.be(sRemember); + }catch(e){ done(e); return } + return new Promise(function(resolve){ + checkIndexedDB(sUser, 'auth', function(auth){ + try{ expect(auth).to.not.be(iAuth) }catch(e){ done(e) } + // Then restore IndexedDB auth data, skip sessionStorage + setIndexedDB(sUser, iAuth, function(){ + root.sessionStorage.setItem('user', sUser); + resolve(ack); }); }); }); - }; - - it('with PIN auth session stores', function(done){ - var doAction = function(){ - user.auth(alias+type, pass+' new', {pin: 'PIN'}) - .then(doCheck(done, true)).catch(done); - }; - if(type === 'callback'){ - user.recall(doAction); - } else { - user.recall().then(doAction).catch(done); - } }); + }, true, true)).then(function(){ + // Ok, time to try auth with alias & PIN + return user.auth(alias+type, undefined, {pin: 'PiN'}); + }).then(function(){ + done('Unexpected login success!'); + }).catch(function(ack){ + try{ + expect(ack).to.not.be(undefined); + expect(ack).to.not.be(''); + expect(ack).to.have.key('err'); + expect(ack.err.toLowerCase() + .indexOf('no session data for alias & pin')).not.to.be(-1); + }catch(e){ done(e); return } + // We've recalled authenticated session using alias & PIN! + done(); + }); + }); - it('without PIN auth session stores', function(done){ - var doAction = function(){ - user.auth(alias+type, pass+' new').then(doCheck(done)); - }; - user.leave().then(function(){ - if(type === 'callback'){ - user.recall(doAction); - } else { - user.recall().then(doAction).catch(done); - } - }).catch(done); + it('expired session fails to bootstrap', function(done){ + var pin = 'PIN'; + user.recall(60).then(function(){ + return user.auth(alias+type, pass+' new', {pin: pin}); + }).then(doCheck(function(){ + // Storage data OK, let's back up time of auth to exp + 65 seconds + return manipulateStorage(function(props){ + var ret = Object.assign({}, props, {iat: props.iat - 65 - props.exp}); + return ret; + }, pin); + })).then(() => throwOutUser(false)) // Simulate browser reload + .then(() => user.recall(60).then((ack) => { + expect(ack).to.not.be(undefined) + expect(ack).to.not.be('') + expect(ack).to.not.have.keys([ 'pub', 'sea' ]) + expect(ack).to.have.key('err') + expect(ack.err).to.not.be(undefined) + expect(ack.err).to.not.be('') + expect(ack.err.toLowerCase() + .indexOf('no session')).not.to.be(-1) + done() + })).catch(done) + }); + + it('changed password', function(done){ + var pin = 'PIN'; + var sUser; + var sRemember; + var iAuth; + user.recall(60).then(function(){ + return user.auth(alias+type, pass+' new', {pin: pin}); + }).then(function(usr){ + try{ + expect(usr).to.not.be(undefined); + expect(usr).to.not.be(''); + expect(usr).to.not.have.key('err'); + expect(usr).to.have.key('put'); + + sUser = root.sessionStorage.getItem('user'); + expect(sUser).to.be(alias+type); + + sRemember = root.sessionStorage.getItem('remember'); + expect(sRemember).to.not.be(undefined); + expect(sRemember).to.not.be(''); + }catch(e){ done(e); return } + + return new Promise(function(resolve){ + checkIndexedDB(sUser, 'auth', function(auth){ resolve(iAuth = auth) }); }); + }).then(function(){ + return user.leave().then(function(ack){ + try{ expect(ack).to.have.key('ok') }catch(e){ done(e); return } - it('no validity no session storing', function(done){ - var doAction = function(){ - user.auth(alias+type, pass+' new').then(doCheck(done)).catch(done); - }; - if(type === 'callback'){ - user.recall(0, doAction); - } else { - user.recall(0).then(doAction).catch(done); - } - }); - - it('with validity but no PIN stores using random PIN', function(done){ - var doAction = function(){ - user.auth(alias+type, pass+' new').then(doCheck(done)).catch(done); - }; - if(type === 'callback'){ - user.recall(12 * 60, doAction); - } else { - user.recall(12 * 60).then(doAction) - .catch(done); - } - }); - - it('validity and auth with PIN but storage empty', function(done){ - user.auth(alias+type, pass+' new').then(function(usr){ - var sUser; - var sRemember; - try{ - expect(usr).to.not.be(undefined); - expect(usr).to.not.be(''); - expect(usr).to.not.have.key('err'); - expect(usr).to.have.key('put'); - - sUser = root.sessionStorage.getItem('user'); - expect(sUser).to.be(alias+type); - - sRemember = root.sessionStorage.getItem('remember'); - expect(sRemember).to.not.be(undefined); - expect(sRemember).to.not.be(''); - }catch(e){ done(e); return } - user.leave().then(function(ack){ - try{ - expect(ack).to.have.key('ok'); - expect(gun.back(-1)._.user).to.not.have.keys([ 'sea', 'pub' ]); - expect(root.sessionStorage.getItem('user')).to.not.be(sUser); - expect(root.sessionStorage.getItem('remember')).to.not.be(sRemember); - }catch(e){ done(e); return } - // Restore but leave IndexedDB empty - root.sessionStorage.setItem('user', sUser); - root.sessionStorage.setItem('remember', sRemember); - - user.recall(12 * 60).then( - doCheck(function(ack){ - expect(ack).to.have.key('err'); - expect(ack.err.toLowerCase().indexOf('no authentication')).to.not.be(-1); - checkIndexedDB(alias+type, 'auth', function(auth){ - expect((typeof auth !== 'undefined' && auth !== null && auth !== '')) - .to.not.eql(true); - done(); - }); - }, false, true)) - .catch(done); - }).catch(done); - }).catch(done); - }); - - it('valid session bootstrap', function(done){ - var sUser; - var sRemember; - var iAuth; - user.auth(alias+type, pass+' new', {pin: 'PIN'}).then(function(usr){ - try{ - expect(usr).to.not.be(undefined); - expect(usr).to.not.be(''); - expect(usr).to.not.have.key('err'); - expect(usr).to.have.key('put'); - expect(root.sessionStorage.getItem('user')).to.be(alias+type); - expect(root.sessionStorage.getItem('remember')).to.not.be(undefined); - expect(root.sessionStorage.getItem('remember')).to.not.be(''); - - sUser = root.sessionStorage.getItem('user'); - sRemember = root.sessionStorage.getItem('remember'); - }catch(e){ done(e); return } - - return new Promise(function(resolve){ - checkIndexedDB(sUser, 'auth', function(auth){ resolve(iAuth = auth) }); - }); - }).then(function(){ - return user.leave().then(function(ack){ - try{ - expect(ack).to.have.key('ok'); - expect(gun.back(-1)._.user).to.not.have.keys([ 'sea', 'pub' ]); - expect(root.sessionStorage.getItem('user')).to.not.be(sUser); - expect(root.sessionStorage.getItem('remember')).to.not.be(sRemember); - }catch(e){ done(e); return } - - return new Promise(function(resolve){ - checkIndexedDB(sUser, 'auth', function(auth){ - expect(auth).to.not.be(iAuth); - resolve(); - }); - }); - }).then(function(){ - root.sessionStorage.setItem('user', sUser); - root.sessionStorage.setItem('remember', sRemember); - - return new Promise(function(resolve){ - setIndexedDB(sUser, iAuth, resolve); - }); - }).then(function(){ - user.recall(12 * 60).then(doCheck(done)) - .catch(done); - }).catch(done); - }).catch(done); - }); - - it('valid session bootstrap using alias & PIN', function(done){ - user.recall(12 * 60).then(function(){ - return user.auth(alias+type, pass+' new', {pin: 'PIN'}); - }).then(doCheck(function(ack){ - // Let's save remember props - var sUser = root.sessionStorage.getItem('user'); - var sRemember = root.sessionStorage.getItem('remember'); - var iAuth = ack.auth; - return new Promise(function(resolve){ - checkIndexedDB(sUser, 'auth', function(auth){ - iAuth = auth; - resolve(user.leave()); // Then logout user - }); - }).then(function(ack){ - try{ - expect(ack).to.have.key('ok'); - expect(gun.back(-1)._.user).to.not.have.keys([ 'sea', 'pub' ]); - expect(root.sessionStorage.getItem('user')).to.not.be(sUser); - expect(root.sessionStorage.getItem('remember')).to.not.be(sRemember); - }catch(e){ done(e); return } - return new Promise(function(resolve){ - checkIndexedDB(sUser, 'auth', function(auth){ - try{ expect(auth).to.not.be(iAuth) }catch(e){ done(e) } - // Then restore IndexedDB but skip sessionStorage remember - setIndexedDB(sUser, iAuth, function(){ - root.sessionStorage.setItem('user', sUser); - resolve(ack); - }); - }); - }); - }); - }, true, true)).then(function(){ - // Then try to recall authentication - return user.recall(12 * 60).then(function(props){ - try{ - expect(props).to.not.be(undefined); - expect(props).to.not.be(''); - expect(props).to.have.key('err'); - // Which fails to missing PIN - expect(props.err.toLowerCase() - .indexOf('missing pin')).not.to.be(-1); - }catch(e){ done(e); return } - // Ok, time to try auth with alias & PIN - return user.auth(alias+type, undefined, {pin: 'PIN'}); - }); - }).then(doCheck(function(usr){ - try{ - expect(usr).to.not.be(undefined); - expect(usr).to.not.be(''); - expect(usr).to.not.have.key('err'); - expect(usr).to.have.key('put'); - }catch(e){ done(e); return } - // We've recalled authenticated session using alias & PIN! - done(); - }, true, true)).catch(done); - }); - - it('valid session fails to bootstrap with alias & wrong PIN', - function(done){ - user.recall(12 * 60).then(function(){ - return user.auth(alias+type, pass+' new', {pin: 'PIN'}); - }).then(doCheck(function(ack){ - var sUser = root.sessionStorage.getItem('user'); - var sRemember = root.sessionStorage.getItem('remember'); - var iAuth = ack.auth; - return new Promise(function(resolve){ - checkIndexedDB(sUser, 'auth', function(auth){ - iAuth = auth; - resolve(user.leave()); // Then logout user - }); - }).then(function(ack){ - try{ - expect(ack).to.have.key('ok'); - expect(gun.back(-1)._.user).to.not.have.keys([ 'sea', 'pub' ]); - expect(root.sessionStorage.getItem('user')).to.not.be(sUser); - expect(root.sessionStorage.getItem('remember')).to.not.be(sRemember); - }catch(e){ done(e); return } - return new Promise(function(resolve){ - checkIndexedDB(sUser, 'auth', function(auth){ - try{ expect(auth).to.not.be(iAuth) }catch(e){ done(e) } - // Then restore IndexedDB auth data, skip sessionStorage - setIndexedDB(sUser, iAuth, function(){ - root.sessionStorage.setItem('user', sUser); - resolve(ack); - }); - }); - }); - }); - }, true, true)).then(function(){ - // Ok, time to try auth with alias & PIN - return user.auth(alias+type, undefined, {pin: 'PiN'}); - }).then(function(){ - done('Unexpected login success!'); - }).catch(function(ack){ - try{ - expect(ack).to.not.be(undefined); - expect(ack).to.not.be(''); - expect(ack).to.have.key('err'); - expect(ack.err.toLowerCase() - .indexOf('no session data for alias & pin')).not.to.be(-1); - }catch(e){ done(e); return } - // We've recalled authenticated session using alias & PIN! - done(); + return user.auth(alias+type, pass+' new', {newpass: pass, pin: pin}) + .then(function(usr){ expect(usr).to.not.have.key('err') }); + }).then(() => user.leave().then((ack) => { + try { + expect(ack).to.have.key('ok') + } catch (e) { done(e); return } + return throwOutUser(false) + })).then(function(){ + // Simulate browser reload + // Call back pre-update remember... + root.sessionStorage.setItem('user', sUser); + root.sessionStorage.setItem('remember', sRemember); + // ... and IndexedDB auth + return new Promise(function(resolve){ + setIndexedDB(sUser, iAuth, resolve); }); - }); - - it('expired session fails to bootstrap', function(done){ - var pin = 'PIN'; - user.recall(60).then(function(){ - return user.auth(alias+type, pass+' new', {pin: pin}); - }).then(doCheck(function(){ - // Storage data OK, let's back up time of auth to exp + 65 seconds - return manipulateStorage(function(props){ - var ret = Object.assign({}, props, {iat: props.iat - 65 - props.exp}); - return ret; - }, pin); - })).then(function(){ - // Simulate browser reload - throwOutUser(); - user.recall(60).then(function(ack){ - expect(ack).to.not.be(undefined); - expect(ack).to.not.be(''); - expect(ack).to.not.have.keys([ 'pub', 'sea' ]); - expect(ack).to.have.key('err'); - expect(ack.err).to.not.be(undefined); - expect(ack.err).to.not.be(''); - expect(ack.err.toLowerCase() - .indexOf('no authentication session')).not.to.be(-1); - done(); - }).catch(done); - }).catch(done); - }); - - it('changed password', function(done){ - var pin = 'PIN'; - var sUser; - var sRemember; - var iAuth; - user.recall(60).then(function(){ - return user.auth(alias+type, pass+' new', {pin: pin}); - }).then(function(usr){ - try{ - expect(usr).to.not.be(undefined); - expect(usr).to.not.be(''); - expect(usr).to.not.have.key('err'); - expect(usr).to.have.key('put'); - - sUser = root.sessionStorage.getItem('user'); - expect(sUser).to.be(alias+type); - - sRemember = root.sessionStorage.getItem('remember'); - expect(sRemember).to.not.be(undefined); - expect(sRemember).to.not.be(''); - }catch(e){ done(e); return } - - return new Promise(function(resolve){ - checkIndexedDB(sUser, 'auth', function(auth){ resolve(iAuth = auth) }); - }); - }).then(function(){ - return user.leave().then(function(ack){ - try{ expect(ack).to.have.key('ok') }catch(e){ done(e); return } - - return user.auth(alias+type, pass+' new', {newpass: pass, pin: pin}) - .then(function(usr){ expect(usr).to.not.have.key('err') }); - }).then(function(){ - return user.leave().then(function(ack){ - try{ - expect(ack).to.have.key('ok'); - }catch(e){ done(e); return } - throwOutUser(); - }); - }).then(function(){ - // Simulate browser reload - // Call back pre-update remember... - root.sessionStorage.setItem('user', sUser); - root.sessionStorage.setItem('remember', sRemember); - // ... and IndexedDB auth - return new Promise(function(resolve){ - setIndexedDB(sUser, iAuth, resolve); - }); - }).then(function(){ - user.recall(60).then(function(props){ - expect(props).to.not.be(undefined); - expect(props).to.not.be(''); - expect(props).to.have.key('err'); - expect(props.err).to.not.be(undefined); - expect(props.err).to.not.be(''); - expect(props.err.toLowerCase() - .indexOf('no authentication session')).not.to.be(-1); - done(); - }).catch(done); - }).catch(done); - }).catch(done); - }); - - it('recall hook session manipulation', function(done){ - var pin = 'PIN'; - var exp; - var hookFunc = function(props){ - exp = props.exp * 2; // Doubles session expiration time - var ret = Object.assign({}, props, {exp: exp}); - return (type === 'callback' && ret) || new Promise(function(resolve){ - resolve(ret); // Both callback & Promise methods here - }); - }; - user.recall(60, {hook: hookFunc}).then(function(){ - return user.auth(alias+type, pass, {pin: pin}); - }).then(function(){ - return manipulateStorage(function(props){ - expect(props).to.not.be(undefined); - expect(props).to.have.key('exp'); - expect(props.exp).to.be(exp); - return props; - }, pin); - }).then(done).catch(done); - }); - }); - - describe('alive', function(){ - it('valid session', function(done){ - var check = function(ack){ - try{ - expect(ack).to.not.be(undefined); - expect(ack).to.not.be(''); - expect(ack).to.not.have.key('err'); - expect(ack).to.have.keys([ 'sea', 'pub' ]); - }catch(e){ done(e); return } + }).then(function(){ + user.recall(60).then(function(props){ + expect(props).to.not.be(undefined); + expect(props).to.not.be(''); + expect(props).to.have.key('err'); + expect(props.err).to.not.be(undefined); + expect(props.err).to.not.be(''); + expect(props.err.toLowerCase() + .indexOf('failed to decrypt')).not.to.be(-1); done(); - }; - var aliveUser = alias+type+'alive'; - user.create(aliveUser, pass).then(function(ack){ - expect(ack).to.not.be(undefined); - expect(ack).to.not.be(''); - expect(ack).to.have.keys([ 'ok', 'pub' ]); - user.auth(aliveUser, pass, {pin: 'PIN'}).then(function(usr){ - try{ - expect(usr).to.not.be(undefined); - expect(usr).to.not.be(''); - expect(usr).to.not.have.key('err'); - expect(usr).to.have.key('put'); - }catch(e){ done(e); return } - // Gun.user.alive - keeps/checks User authentiation state - if(type === 'callback'){ - user.alive(check); - } else { - user.alive().then(check).catch(done); - } - }).catch(done); }).catch(done); - }); + }).catch(done); + }).catch(done); + }); - it('expired session', function(done){ - var check = function(ack){ - try{ - expect(ack).to.not.be(undefined); - expect(ack).to.not.be(''); - expect(ack).to.not.have.keys([ 'sea', 'pub' ]); - expect(ack).to.have.key('err'); - expect(ack.err.toLowerCase().indexOf('no session')).not.to.be(-1); - }catch(e){ done(e); return } - done(); - }; - user.leave().catch(function(){}).then(function(){ - user.alive().then(function(){ - done('Unexpected alive session!'); - }).catch(check); - }).catch(done); + it('recall hook session manipulation', function(done){ + var pin = 'PIN'; + var exp; + var hookFunc = function(props){ + exp = props.exp * 2; // Doubles session expiration time + var ret = Object.assign({}, props, {exp: exp}); + return new Promise(function(resolve){ + resolve(ret); // Both callback & Promise methods here }); - }); + }; + user.recall(60, {hook: hookFunc}).then(function(){ + return user.auth(alias+type, pass, {pin: pin}); + }).then(function(){ + return manipulateStorage(function(props){ + expect(props).to.not.be(undefined); + expect(props).to.have.key('exp'); + expect(props.exp).to.be(exp); + return props; + }, pin); + }).then(done).catch(done); + }); + }); + + describe('alive', function(){ + it('valid session', function(done){ + var check = function(ack){ + try{ + expect(ack).to.not.be(undefined); + expect(ack).to.not.be(''); + expect(ack).to.not.have.key('err'); + expect(ack).to.have.keys([ 'sea', 'pub' ]); + }catch(e){ done(e); return } + done(); + }; + var aliveUser = alias+type+'alive'; + user.create(aliveUser, pass).then(function(ack){ + expect(ack).to.not.be(undefined); + expect(ack).to.not.be(''); + expect(ack).to.have.keys([ 'ok', 'pub' ]); + user.auth(aliveUser, pass, {pin: 'PIN'}).then(function(usr){ + try{ + expect(usr).to.not.be(undefined); + expect(usr).to.not.be(''); + expect(usr).to.not.have.key('err'); + expect(usr).to.have.key('put'); + }catch(e){ done(e); return } + // Gun.user.alive - keeps/checks User authentiation state + user.alive().then(check).catch(done); + }).catch(done); + }).catch(done); + }); + + it('expired session', function(done){ + var check = function(ack){ + try{ + expect(ack).to.not.be(undefined); + expect(ack).to.not.be(''); + expect(ack).to.not.have.keys([ 'sea', 'pub' ]); + expect(ack).to.have.key('err'); + expect(ack.err.toLowerCase().indexOf('no session')).not.to.be(-1); + }catch(e){ done(e); return } + done(); + }; + user.leave().catch(function(){}).then(function(){ + user.alive().then(function(){ + done('Unexpected alive session!'); + }).catch(check); + }).catch(done); }); }); diff --git a/test/user.html b/test/user.html new file mode 100644 index 00000000..3f425aeb --- /dev/null +++ b/test/user.html @@ -0,0 +1,50 @@ +

User

+ +
+ + + + +
+ +
    + +
    + + +
    + + + + + + \ No newline at end of file