I did NOT merge SEA into master!

This commit is contained in:
Mark Nadal 2018-02-06 04:08:54 -08:00
parent 53ab90c8d3
commit 039d287c9b
9 changed files with 131 additions and 35 deletions

17
sea/https.js Normal file
View File

@ -0,0 +1,17 @@
/*
Security, Encryption, and Authorization: SEA.js
*/
// NECESSARY PRE-REQUISITE: http://gun.js.org/explainers/data/security.html
/* THIS IS AN EARLY ALPHA!!! */
if(typeof window !== 'undefined'){
if(location.protocol.indexOf('s') < 0
&& location.host.indexOf('localhost') < 0
&& location.protocol.indexOf('file:') < 0){
location.protocol = 'https:';
}
}

View File

@ -46,8 +46,33 @@
}
})
}
// This is IndexedDB used by Gun SEA
const seaIndexedDb = new EasyIndexedDB('SEA', 'GunDB', 1)
let indexedDB
let funcsSetter
if (typeof __webpack_require__ === 'function' || typeof window !== 'undefined') {
funcsSetter = () => window
indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB
} else {
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
}
const seaIndexedDb = new EasyIndexedDB('SEA', 'GunDB', 1) // This is IndexedDB used by Gun SEA
EasyIndexedDB.scope = seaIndexedDb; // for now. This module should not export an instance of itself!
module.exports = EasyIndexedDB;

View File

@ -5,17 +5,17 @@
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
var user = root._.user._ || {};
[ 'get', 'soul', 'ack', 'put', 'is', 'alias', 'pub', 'epub', 'sea' ].map((key) => delete user[key])
if(user.gun){
delete user.gun.is;
}
// Let's use default
root.user();
// 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;

View File

@ -1,6 +1,8 @@
var Buffer = require('./buffer');
var sha256hash = require('./sha256');
var wc = require('./webcrypto');
var subtle = wc.subtle;
var seaIndexedDb = require('./indexed').scope;
var settings = require('./settings');
var authsettings = settings.recall;

View File

@ -1,5 +1,9 @@
const Gun = (typeof window !== 'undefined' ? window : global).Gun || require('gun/gun')
var wc = require('./webcrypto');
var subtle = wc.subtle;
var getRandomBytes = wc.random;
var EasyIndexedDB = require('./indexed');
var SafeBuffer = require('./buffer');
var settings = require('./settings');
@ -11,15 +15,7 @@
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
@ -85,7 +81,7 @@
},
async pair() {
try {
const ecdhSubtle = subtleossl || subtle
const ecdhSubtle = wc.ossl || subtle
// First: ECDSA keys for signing/verifying...
const { pub, priv } = await subtle.generateKey(ecdsaKeyProps, true, [ 'sign', 'verify' ])
.then(async ({ publicKey, privateKey }) => {

View File

@ -1,11 +1,14 @@
var wc = require('./webcrypto');
var subtle = wc.subtle;
var getRandomBytes = wc.random;
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 hashSubtle = wc.ossl || subtle
const m = parseProps(mm)
const hash = await hashSubtle.digest(pbKdf2.hash, new TextEncoder().encode(m))
return Buffer.from(hash)

View File

@ -6,6 +6,7 @@
var authRecall = require('./recall');
var authenticate = require('./authenticate');
var finalizeLogin = require('./login');
var authLeave = require('./leave');
// 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() {
@ -26,7 +27,14 @@
Object.assign(User, {
async create(username, pass, cb) {
const root = this.back(-1)
return new Promise((resolve, reject) => { // Because no Promises or async
var gun = this, cat = (gun._);
cb = cb || function(){};
if(cat.ing){
cb({err: Gun.log("User is already being created or authenticated!"), wait: true});
return gun;
}
cat.ing = true;
var p = new Promise((resolve, reject) => { // Because no Promises or async
// Because more than 1 user might have the same username, we treat the alias as a list of those users.
if(cb){ resolve = reject = cb }
root.get(`alias/${username}`).get(async (at, ev) => {
@ -35,6 +43,8 @@
// 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)
cat.ing = false;
gun.leave();
return reject({ err })
}
const salt = Gun.text.random(64)
@ -54,7 +64,7 @@
// SEA.write(salt, pairs).then((signedsalt) =>
SEA.write({ salt, auth }, pairs)
// )
).catch((e) => { Gun.log('SEA.en or SEA.write calls failed!'); reject(e) })
).catch((e) => { Gun.log('SEA.en or SEA.write calls failed!'); cat.ing = false; gun.leave(); 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.
@ -62,25 +72,38 @@
// 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.
setTimeout(() => { cat.ing = false; resolve({ ok: 0, pub: pairs.pub}) }, 10) // TODO: BUG! If `.auth` happens synchronously after `create` finishes, auth won't work. This setTimeout is a temporary hack until we can properly fix it.
} catch (e) {
Gun.log('SEA.create failed!')
cat.ing = false;
gun.leave();
reject(e)
}
})
})
return gun; // gun chain commands must return gun chains!
},
// 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 }
if(cb && !(cb instanceof Function)){ opts = cb; cb = function(){} }
const { pin, newpass } = opts || {}
const root = this.back(-1)
cb = cb || function(){};
var gun = this, cat = (gun._);
if(cat.ing){
cb({err: "User is already being created or authenticated!", wait: true});
return gun;
}
cat.ing = true;
if (!pass && pin) {
try {
return await authRecall(root, { alias, pin })
var r = await authRecall(root, { alias, pin })
return cat.ing = false, cb(r), gun;
} catch (e) {
throw { err: 'Auth attempt failed! Reason: No session data for alias & PIN' }
var err = { err: 'Auth attempt failed! Reason: No session data for alias & PIN' }
return cat.ing = false, gun.leave(), cb(err), gun;
}
}
@ -88,8 +111,7 @@
const { message, err = message || '' } = e
Gun.log(msg)
var error = { err: `${msg} Reason: ${err}` }
if(cb){ cb(error) }
throw error;
return cat.ing = false, gun.leave(), cb(error), gun;
}
try {
@ -121,20 +143,19 @@
// 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;
return cat.ing = false, cb(login), gun;
} catch (e) {
putErr('Password set attempt failed!')(e)
return 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;
return cat.ing = false, cb(login), gun;
}
} catch (e) {
putErr('Auth attempt failed!')(e)
return putErr('Auth attempt failed!')(e)
}
return gun;
},
async leave() {
return await authLeave(this.back(-1))

25
sea/webcrypto.js Normal file
View File

@ -0,0 +1,25 @@
let subtle
let subtleossl
let getRandomBytes
let crypto
var Buffer = require('./buffer');
var wc;
var api = {};
if (typeof __webpack_require__ === 'function' || typeof window !== 'undefined') {
api.crypto = wc = window.crypto || window.msCrypto // STD or M$
api.subtle = subtle = wc.subtle || wc.webkitSubtle // STD or iSafari
api.random = getRandomBytes = (len) => Buffer.from(wc.getRandomValues(new Uint8Array(Buffer.alloc(len))))
} else {
api.crypto = crypto = require('crypto')
const WebCrypto = require('node-webcrypto-ossl')
const webcrypto = new WebCrypto({directory: 'key_storage'})
api.ossl = subtleossl = webcrypto.subtle
api.subtle = subtle = require('@trust/webcrypto').subtle // All but ECDH
api.random = getRandomBytes = (len) => Buffer.from(crypto.randomBytes(len))
}
module.exports = api;

View File

@ -24,7 +24,12 @@ var root;
}
}(this));
const SEA = Gun.SEA()
;(function(){
const SEA = Gun.SEA
if(!SEA){ return }
const { Buffer, EasyIndexedDB } = SEA
const seaIndexedDb = new SEA.EasyIndexedDB('SEA', 'GunDB', 1)
@ -1000,3 +1005,5 @@ Gun().user && describe('Gun', function(){
Gun.log.off = false;
});
});
}());