migrate SEA, some improvement, some regression

This commit is contained in:
Mark Nadal 2018-04-07 13:50:53 -07:00
parent f72aba3788
commit be0de5cf56
29 changed files with 606 additions and 629 deletions

2
gun.min.js vendored

File diff suppressed because one or more lines are too long

12
sea/aescbc.js Normal file
View File

@ -0,0 +1,12 @@
var shim = require('./shim');
var sha256hash = require('./sha256');
const importGen = async (key, salt) => {
//const combo = shim.Buffer.concat([shim.Buffer.from(key, 'utf8'), salt || shim.random(8)]).toString('utf8') // old
const combo = key + (salt || shim.random(8)).toString('utf8'); // new
const hash = shim.Buffer.from(await sha256hash(combo), 'binary')
return await shim.subtle.importKey('raw', new Uint8Array(hash), 'AES-CBC', false, ['encrypt', 'decrypt'])
}
module.exports = importGen;

View File

@ -1,13 +1,12 @@
// 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');
var Gun = SEA.Gun;
const queryGunAliases = require('./query')
const parseProps = require('./parse')
// This is internal User authentication func.
const authenticate = async (alias, pass, root) => {
const authenticate = async (alias, pass, gunRoot) => {
// load all public keys associated with the username alias we want to log in with.
const aliases = (await queryGunAliases(alias, root))
const aliases = (await queryGunAliases(alias, gunRoot))
.filter(({ pub, at: { put } = {} } = {}) => !!pub && !!put)
// Got any?
if (!aliases.length) {
@ -20,16 +19,16 @@
// 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){
// SEA.verify(at.put.auth, pub).then(function(auth){
try {
const proof = await SEA.proof(pass, auth.salt)
const proof = await SEA.work(pass, auth.s)
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 })
const sea = await SEA.decrypt(auth.ek, proof)
if (!sea) {
err = 'Failed to decrypt secret!'
return

View File

@ -73,7 +73,5 @@
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;

26
sea/decrypt.js Normal file
View File

@ -0,0 +1,26 @@
var SEA = require('./root');
var shim = require('./shim');
var S = require('./settings');
var aescbckey = require('./aescbc');
var parse = require('./parse');
SEA.decrypt = async (data, pair, cb) => { try {
const key = pair.epriv || pair;
const json = parse(data)
const ct = await aescbckey(key, shim.Buffer.from(json.s, 'utf8'))
.then((aes) => shim.subtle.decrypt({ // Keeping aesKey scope as private as possible...
name: 'AES-CBC', iv: new Uint8Array(shim.Buffer.from(json.iv, 'utf8'))
}, aes, new Uint8Array(shim.Buffer.from(json.ct, 'utf8'))))
const r = parse(new shim.TextDecoder('utf8').decode(ct))
if(cb){ cb(r) }
return r;
} catch(e) {
SEA.err = e;
if(cb){ cb() }
return;
}}
module.exports = SEA.decrypt;

30
sea/encrypt.js Normal file
View File

@ -0,0 +1,30 @@
var SEA = require('./root');
var shim = require('./shim');
var S = require('./settings');
var aescbckey = require('./aescbc');
SEA.encrypt = async (data, pair, cb) => { try {
const key = pair.epriv || pair;
const msg = JSON.stringify(data)
const rand = {s: shim.random(8), iv: shim.random(16)};
const ct = await aescbckey(key, rand.s)
.then((aes) => shim.subtle.encrypt({ // Keeping the AES key scope as private as possible...
name: 'AES-CBC', iv: new Uint8Array(rand.iv)
}, aes, new shim.TextEncoder().encode(msg)))
const r = 'SEA'+JSON.stringify({
ct: shim.Buffer.from(ct, 'binary').toString('utf8'),
iv: rand.iv.toString('utf8'),
s: rand.s.toString('utf8')
});
if(cb){ cb(r) }
return r;
} catch(e) {
SEA.err = e;
if(cb){ cb() }
return;
}}
module.exports = SEA.encrypt;

View File

@ -1,13 +1,6 @@
/*
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'){
var SEA = require('./root');
if(SEA.window){
if(location.protocol.indexOf('s') < 0
&& location.host.indexOf('localhost') < 0
&& location.protocol.indexOf('file:') < 0){

View File

@ -1,6 +1,6 @@
const Gun = (typeof window !== 'undefined' ? window : global).Gun || require('gun/gun')
var SEA = require('./sea');
const 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)
@ -9,12 +9,11 @@
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)});
var id = uuid(), pub = at.user;
if(!pub || !(pub = at.user._.sea) || !(pub = pub.pub)){ return id }
id = id + '~' + pub;
if(cb){ cb(null, id) }
return id;
}
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.
@ -42,7 +41,7 @@
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.
SEA.verify(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) }
});
@ -50,19 +49,6 @@
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.
@ -96,7 +82,7 @@
}
if(msg.put){
// potentially parallel async operations!!!
var check = {}, on = Gun.on(), each = {}, u;
var check = {}, 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});
@ -115,15 +101,6 @@
}
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
@ -142,8 +119,8 @@
}
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;
//var id = Gun.text.random(3);
SEA.sign(val, user.sea).then(function(data){ var rel;
if(rel = Gun.val.rel.is(val)){
(at.sea.own[rel] = at.sea.own[rel] || {})[pub] = true;
}
@ -151,42 +128,33 @@
check['user'+soul+key] = 0;
each.end({ok: 1});
});
// TODO: Handle error!!!!
return;
}
// TODO: consider async/await and drop callback pattern...
SEA.read(val, pub).then(function(data){ var rel, tmp;
SEA.verify(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."}) }
if(pub === tmp[1]){
(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;
each.any = function(val, key, node, soul, user){ var tmp, pub;
if(!user || !(user = user._) || !(user = user.sea)){
if(user = at.sea.own[soul]){
if((tmp = soul.split('~')) && 2 == tmp.length){
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 + "'.", }) }
SEA.verify(val, (pub = tmp[1])).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;
if(pub === tmp[1]){
(at.sea.own[rel] = at.sea.own[rel] || {})[pub] = true;
}
}
check['any'+soul+key] = 0;
each.end({ok: 1});
@ -194,12 +162,6 @@
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."});
@ -208,26 +170,26 @@
return;
}
if(!(tmp = soul.split('~')) || 2 !== tmp.length){
each.end({err: "Soul is not signed at '" + key + "'."});
each.end({err: "Soul is missing public key at '" + key + "'."});
return;
}
var other = Gun.obj.map(at.sea.own[soul], function(v, p){
var pub = tmp[1];
if(pub !== user.pub){
each.any(val, key, node, soul);
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});
});
SEA.sign(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?

View File

@ -1,78 +0,0 @@
// 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])
}
}))
}
})
}
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

@ -1,22 +1,21 @@
var authPersist = require('./persist');
var authsettings = require('./settings');
var seaIndexedDb = require('./indexed').scope;
var seaIndexedDb = require('./indexed').scope;
const authPersist = require('./persist')
const authsettings = require('./settings')
//const { scope: seaIndexedDb } = require('./indexed')
// This internal func executes logout actions
const authLeave = async (root, alias = root._.user._.alias) => {
var user = root._.user._ || {};
const authLeave = async (gunRoot, alias = gunRoot._.user._.alias) => {
var user = gunRoot._.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();
gunRoot.user();
// Removes persisted authentication & CryptoKeys
try {
await authPersist({ alias })
} catch (e) {} //eslint-disable-line no-empty
return { ok: 0 }
}
module.exports = authLeave;
module.exports = authLeave

View File

@ -1,26 +1,33 @@
var authPersist = require('./persist');
const authPersist = require('./persist')
// This internal func finalizes User authentication
const finalizeLogin = async (alias, key, root, opts) => {
const { user } = root._
const finalizeLogin = async (alias, key, gunRoot, opts) => {
const { user } = gunRoot._
// 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
user._.is = user.is = {alias: alias, pub: pub};
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.
//await authPersist(user._, key.proof, opts) // temporarily disabled
// emit an auth event, useful for page redirects and stuff.
if(typeof window !== 'undefined'){
var tmp = window.sessionStorage;
if(tmp && gunRoot._.opt.remember){
window.sessionStorage.alias = alias;
window.sessionStorage.tmp = key;
}
}
try {
root._.on('auth', user._)
gunRoot._.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;
module.exports = finalizeLogin

52
sea/pair.js Normal file
View File

@ -0,0 +1,52 @@
var SEA = require('./root');
var shim = require('./shim');
var S = require('./settings');
var Buff = (typeof Buffer !== 'undefined')? Buffer : shim.Buffer;
//SEA.pair = async (data, proof, cb) => { try {
SEA.pair = async (cb) => { try {
const ecdhSubtle = shim.ossl || shim.subtle
// First: ECDSA keys for signing/verifying...
const { pub, priv } = await shim.subtle.generateKey(S.ecdsa.pair, true, [ 'sign', 'verify' ])
.then(async (keys) => {
// privateKey scope doesn't leak out from here!
const { d: priv } = await shim.subtle.exportKey('jwk', keys.privateKey)
const { x, y } = await shim.subtle.exportKey('jwk', keys.publicKey)
//const pub = Buff.from([ x, y ].join(':')).toString('base64') // old
const pub = x+'.'+y // new
// x and y are already base64
// pub is UTF8 but filename/URL safe (https://www.ietf.org/rfc/rfc3986.txt)
// but split on a non-base64 letter.
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(S.ecdh, true, ['deriveKey'])
.then(async (keys) => {
// privateKey scope doesn't leak out from here!
const { d: epriv } = await ecdhSubtle.exportKey('jwk', keys.privateKey)
const { x, y } = await ecdhSubtle.exportKey('jwk', keys.publicKey)
//const epub = Buff.from([ ex, ey ].join(':')).toString('base64') // old
const epub = x+'.'+y // new
// ex and ey are already base64
// epub is UTF8 but filename/URL safe (https://www.ietf.org/rfc/rfc3986.txt)
// but split on a non-base64 letter.
return { epub, epriv }
})
const r = { pub, priv, /* pubId, */ epub, epriv }
if(cb){ cb(r) }
return r;
} catch(e) {
SEA.err = e;
if(cb){ cb() }
return;
}}
module.exports = SEA.pair;

View File

@ -1,9 +1,11 @@
const parseProps = (props) => {
module.exports = (props) => {
try {
if(props.slice && 'SEA{' === props.slice(0,4)){
props = props.slice(3);
}
return props.slice ? JSON.parse(props) : props
} catch (e) {} //eslint-disable-line no-empty
return props
}
module.exports = parseProps;

View File

@ -1,8 +1,8 @@
const Gun = (typeof window !== 'undefined' ? window : global).Gun || require('gun/gun')
var Buffer = require('./buffer');
var authsettings = require('./settings');
var updateStorage = require('./update');
const Buffer = require('./buffer')
const authsettings = require('./settings')
const updateStorage = require('./update')
// This internal func persists User authentication if so configured
const authPersist = async (user, proof, opts) => {
// opts = { pin: 'string' }
@ -33,5 +33,5 @@
}
return await updateStorage()({ alias: 'delete' })
}
module.exports = authPersist;
module.exports = authPersist

View File

@ -1,10 +1,11 @@
const Gun = (typeof window !== 'undefined' ? window : global).Gun || require('gun/gun')
var SEA = require('./sea');
var Gun = SEA.Gun;
// This is internal func queries public key(s) for alias.
const queryGunAliases = (alias, root) => new Promise((resolve, reject) => {
const queryGunAliases = (alias, gunRoot) => new Promise((resolve, reject) => {
// load all public keys associated with the username alias we want to log in with.
root.get(`alias/${alias}`).get((rat, rev) => {
rev.off()
gunRoot.get(`alias/${alias}`).get((rat, rev) => {
rev.off();
if (!rat.put) {
// if no user, don't do anything.
const err = 'No user!'
@ -12,7 +13,7 @@
return reject({ err })
}
// then figuring out all possible candidates having matching username
let aliases = []
const aliases = []
let c = 0
// TODO: how about having real chainable map without callback ?
Gun.obj.map(rat.put, (at, pub) => {
@ -22,7 +23,7 @@
}
++c
// grab the account associated with this public key.
root.get(pub).get((at, ev) => {
gunRoot.get(pub).get((at, ev) => {
pub = pub.slice(4)
ev.off()
--c
@ -39,5 +40,5 @@
}
})
})
module.exports = queryGunAliases;
module.exports = queryGunAliases

View File

@ -1,14 +1,18 @@
// TODO: BUG! `SEA` needs to be USED!
// 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');
const Buffer = require('./buffer')
const authsettings = require('./settings')
//const { scope: seaIndexedDb } = require('./indexed')
const queryGunAliases = require('./query')
const parseProps = require('./parse')
const updateStorage = require('./update')
const SEA = require('./sea')
const finalizeLogin = require('./login')
// This internal func recalls persisted User authentication if so configured
const authRecall = async (root, authprops) => {
const authRecall = async (gunRoot, authprops) => {
// window.sessionStorage only holds signed { alias, pin } !!!
const remember = authprops || sessionStorage.getItem('remember')
const { alias = sessionStorage.getItem('user'), pin: pIn } = authprops || {} // @mhelander what is pIn?
@ -31,13 +35,13 @@
}
}
const readAndDecrypt = async (data, pub, key) =>
parseProps(await SEA.dec(await SEA.read(data, pub), key))
parseProps(await SEA.decrypt(await SEA.verify(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.
if (gunRoot._.user
&& Gun.obj.has(gunRoot._.user._, 'pub')
&& Gun.obj.has(gunRoot._.user._, 'sea')) {
return gunRoot._.user._ // Yes, we're done here.
}
// No, got persisted 'alias'?
if (!alias) {
@ -51,7 +55,7 @@
}
}
// Yes, let's get (all?) matching aliases
const aliases = (await queryGunAliases(alias, root))
const aliases = (await queryGunAliases(alias, gunRoot))
.filter(({ pub } = {}) => !!pub)
// Got any?
if (!aliases.length) {
@ -64,7 +68,7 @@
.all(aliases.filter(({ at: { put } = {} }) => !!put)
.map(async ({ at, pub }) => {
const readStorageData = async (args) => {
const props = args || parseProps(await SEA.read(remember, pub, true))
const props = args || parseProps(await SEA.verify(remember, pub, true))
let { pin, alias: aLias } = props
const data = (!pin && alias === aLias)
@ -94,7 +98,7 @@
try { // auth parsing or decryption fails or returns empty - silently done
const { auth } = at.put.auth
const sea = await SEA.dec(auth, proof)
const sea = await SEA.decrypt(auth, proof)
if (!sea) {
err = 'Failed to decrypt private key!'
return
@ -124,12 +128,12 @@
const pinProp = pIN && { pin: Buffer.from(pIN, 'base64').toString('utf8') }
return await finalizeLogin(alias, user, root, pinProp)
return await finalizeLogin(alias, user, gunRoot, pinProp)
} catch (e) { // TODO: right log message ?
Gun.log('Failed to finalize login with new password!')
const { err = '' } = e || {}
throw { err: `Finalizing new password login failed! Reason: ${err}` }
}
}
module.exports = authRecall;
module.exports = authRecall

View File

@ -1,46 +0,0 @@
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;
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;

10
sea/root.js Normal file
View File

@ -0,0 +1,10 @@
// Security, Encryption, and Authorization: SEA.js
// MANDATORY READING: http://gun.js.org/explainers/data/security.html
// THIS IS AN EARLY ALPHA!
function SEA(){}
if(typeof window !== "undefined"){ SEA.window = window }
module.exports = SEA;

View File

@ -1,255 +1,102 @@
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');
// Old Code...
const {
crypto,
subtle,
ossl,
random: getRandomBytes,
TextEncoder,
TextDecoder
} = require('./shim')
const EasyIndexedDB = require('./indexed')
const Buffer = 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');
const {
pbkdf2: pbKdf2,
ecdsa: { pair: ecdsaKeyProps, sign: ecdsaSignProps },
ecdh: ecdhKeyProps,
jwk: keysToEcdsaJwk
} = require('./settings')
const sha1hash = require('./sha1')
const sha256hash = require('./sha256')
const recallCryptoKey = require('./remember')
const parseProps = require('./parse')
// 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 = wc.ossl || 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
}
const SEA = require('./root');
SEA.work = require('./work');
SEA.sign = require('./sign');
SEA.verify = require('./verify');
SEA.encrypt = require('./encrypt');
SEA.decrypt = require('./decrypt');
SEA.random = getRandomBytes;
// This is easy way to use IndexedDB, all methods are Promises
// Note: Not all SEA interfaces have to support this.
SEA.EasyIndexedDB = EasyIndexedDB;
// This is Buffer used in SEA and usable from Gun/SEA application also.
// For documentation see https://nodejs.org/api/buffer.html
SEA.Buffer = Buffer;
// 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.
// Calculate public key KeyID aka PGPv4 (result: 8 bytes as hex string)
SEA.keyid = async (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) {
console.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
// Derive shared secret from other's pub and my epub/epriv
SEA.derive = async (pub, { epub, epriv }) => {
try {
const ecdhSubtle = ossl || subtle
const keysToEcdhJwk = (pub, d) => { // d === priv
const [ x, y ] = Buffer.from(pub, 'base64').toString('utf8').split(':')
const jwk = d ? { d } : {}
return [ // Use with spread returned value...
'jwk',
{ ...jwk, x, y, kty: 'EC', crv: 'P-256', ext: true },
ecdhKeyProps
]
}
const pubKeyData = keysToEcdhJwk(pub)
const props = {
...ecdhKeyProps,
public: await ecdhSubtle.importKey(...pubKeyData, true, [])
}
const privKeyData = keysToEcdhJwk(epub, epriv)
const derived = await ecdhSubtle.importKey(...privKeyData, false, ['deriveKey'])
.then(async (privKey) => {
// privateKey scope doesn't leak out from here!
const derivedKey = await ecdhSubtle.deriveKey(props, privKey, { name: 'AES-CBC', length: 256 }, true, [ 'encrypt', 'decrypt' ])
return ecdhSubtle.exportKey('jwk', derivedKey).then(({ k }) => k)
})
return derived
} catch (e) {
console.log(e)
throw e
}
}
// 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.
@ -259,8 +106,9 @@
// 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 Gun = (SEA.window||{}).Gun || require('./gun');
Gun.SEA = SEA;
SEA.Gun = Gun;
try {
module.exports = SEA
} catch (e) {} //eslint-disable-line no-empty
module.exports = SEA

View File

@ -1,8 +1,8 @@
var Buffer = require('./buffer');
var settings = {};
const Buffer = require('./buffer')
const settings = {}
// Encryption parameters
const pbKdf2 = { hash: 'SHA-256', iter: 50000, ks: 64 }
const pbkdf2 = { hash: 'SHA-256', iter: 100000, ks: 64 }
const ecdsaSignProps = { name: 'ECDSA', hash: { name: 'SHA-256' } }
const ecdsaKeyProps = { name: 'ECDSA', namedCurve: 'P-256' }
@ -16,21 +16,24 @@
// 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 })
]
const keysToEcdsaJwk = (pub, d) => { // d === priv
//const [ x, y ] = Buffer.from(pub, 'base64').toString('utf8').split(':') // old
const [ x, y ] = pub.split('.') // new
var jwk = { kty: "EC", crv: "P-256", x: x, y: y, ext: true }
jwk.key_ops = d ? ['sign'] : ['verify'];
if(d){ jwk.d = d }
return jwk;
}
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;
Object.assign(settings, {
pbkdf2,
ecdsa: {
pair: ecdsaKeyProps,
sign: ecdsaSignProps
},
ecdh: ecdhKeyProps,
jwk: keysToEcdsaJwk,
recall: authsettings
})
module.exports = settings

View File

@ -1,5 +1,6 @@
// 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;
const { subtle, ossl = subtle } = require('./shim')
const sha1hash = (b) => ossl.digest({name: 'SHA-1'}, new ArrayBuffer(b))
module.exports = sha1hash

View File

@ -1,17 +1,15 @@
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;
const {
subtle, ossl = subtle, random: getRandomBytes, TextEncoder, TextDecoder
} = require('./shim')
const Buffer = require('./buffer')
const parse = require('./parse')
const { pbkdf2 } = require('./settings')
// This internal func returns SHA-256 hashed data for signing
const sha256hash = async (mm) => {
const hashSubtle = wc.ossl || subtle
const m = parseProps(mm)
const hash = await hashSubtle.digest(pbKdf2.hash, new TextEncoder().encode(m))
const m = parse(mm)
const hash = await ossl.digest({name: pbkdf2.hash}, new TextEncoder().encode(m))
return Buffer.from(hash)
}
module.exports = sha256hash;
module.exports = sha256hash

38
sea/shim.js Normal file
View File

@ -0,0 +1,38 @@
const Buffer = require('./buffer')
const api = {Buffer: Buffer}
if (typeof __webpack_require__ === 'function' || typeof window !== 'undefined') {
const { msCrypto, crypto = msCrypto } = window // STD or M$
const { webkitSubtle, subtle = webkitSubtle } = crypto // STD or iSafari
const { TextEncoder, TextDecoder } = window
Object.assign(api, {
crypto,
subtle,
TextEncoder,
TextDecoder,
random: (len) => Buffer.from(crypto.getRandomValues(new Uint8Array(Buffer.alloc(len))))
})
} else {
try{
const crypto = require('crypto')
//const WebCrypto = require('node-webcrypto-ossl')
//const { subtle: ossl } = new WebCrypto({directory: 'key_storage'}) // ECDH
const { subtle } = require('@trust/webcrypto') // All but ECDH
const { TextEncoder, TextDecoder } = require('text-encoding')
Object.assign(api, {
crypto,
subtle,
//ossl,
TextEncoder,
TextDecoder,
random: (len) => Buffer.from(crypto.randomBytes(len))
})
}catch(e){
console.log("@trust/webcrypto and text-encoding are not included by default, you must add it to your package.json!");
TRUST_WEBCRYPTO_OR_TEXT_ENCODING_NOT_INSTALLED;
}
}
module.exports = api

35
sea/sign.js Normal file
View File

@ -0,0 +1,35 @@
var SEA = require('./root');
var shim = require('./shim');
var S = require('./settings');
var sha256hash = require('./sha256');
SEA.sign = async (data, pair, cb) => { try {
if(data.slice
&& 'SEA{' === data.slice(0,4)
&& '"m":' === data.slice(4,8)){
// TODO: This would prevent pair2 signing pair1's signature.
// So we may want to change this in the future.
// but for now, we want to prevent duplicate double signature.
if(cb){ cb(data) }
return data;
}
const pub = pair.pub
const priv = pair.priv
const jwk = S.jwk(pub, priv)
const msg = JSON.stringify(data)
const hash = await sha256hash(msg)
const sig = await shim.subtle.importKey('jwk', jwk, S.ecdsa.pair, false, ['sign'])
.then((key) => shim.subtle.sign(S.ecdsa.sign, key, new Uint8Array(hash))) // privateKey scope doesn't leak out from here!
const r = 'SEA'+JSON.stringify({m: msg, s: shim.Buffer.from(sig, 'binary').toString('utf8')});
if(cb){ cb(r) }
return r;
} catch(e) {
SEA.err = e;
if(cb){ cb() }
return;
}}
module.exports = SEA.sign;

View File

@ -1,8 +1,9 @@
// 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;
const authsettings = require('./settings')
const SEA = require('./sea');
//const { scope: seaIndexedDb } = require('./indexed')
// This updates sessionStorage & IndexedDB to persist authenticated "session"
const updateStorage = (proof, key, pin) => async (props) => {
if (!Gun.obj.has(props, 'alias')) {
@ -16,16 +17,16 @@
const remember = { alias, pin }
try {
const signed = await SEA.write(JSON.stringify(remember), key)
const signed = await SEA.sign(JSON.stringify(remember), key)
sessionStorage.setItem('user', alias)
sessionStorage.setItem('remember', signed)
const encrypted = await SEA.enc(props, pin)
const encrypted = await SEA.encrypt(props, pin)
if (encrypted) {
const auth = await SEA.write(encrypted, key)
await seaIndexedDb.wipe()
const auth = await SEA.sign(encrypted, key)
await seaIndexedDb.wipe() // NO! Do not do this. It ruins other people's sessionStorage code. This is bad/wrong, commenting it out.
await seaIndexedDb.put(id, { auth })
}
@ -36,12 +37,12 @@
}
// Wiping IndexedDB completely when using random PIN
await seaIndexedDb.wipe()
await seaIndexedDb.wipe() // NO! Do not do this. It ruins other people's sessionStorage code. This is bad/wrong, commenting it out.
// And remove sessionStorage data
sessionStorage.removeItem('user')
sessionStorage.removeItem('remember')
return props
}
module.exports = updateStorage;
module.exports = updateStorage

View File

@ -1,17 +1,22 @@
// 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');
var authLeave = require('./leave');
//const Gun = (typeof window !== 'undefined' ? window : global).Gun || require('gun/gun')
const SEA = require('./sea')
const authRecall = require('./recall')
const authsettings = require('./settings')
const authenticate = require('./authenticate')
const finalizeLogin = require('./login')
const authLeave = require('./leave')
const { recall: _initial_authsettings } = require('./settings')
const Gun = SEA.Gun;
// 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.
const gunRoot = this.back(-1) // always reference the root gun instance.
const user = gunRoot._.user || (gunRoot._.user = gunRoot.chain()); // create a user context.
// then methods...
[ 'create', // factory
'auth', // login
@ -22,11 +27,12 @@
].map((method)=> user[method] = User[method])
return user // return the user!
}
var u;
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)
const gunRoot = this.back(-1)
var gun = this, cat = (gun._);
cb = cb || function(){};
if(cat.ing){
@ -37,7 +43,7 @@
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) => {
gunRoot.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.
@ -50,27 +56,32 @@
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)
const proof = await SEA.work(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)
const alias = await SEA.sign(username, pairs)
if(u === alias){ throw SEA.err }
const epub = await SEA.sign(pairs.epub, pairs)
if(u === epub){ throw SEA.err }
// 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 })
const auth = await SEA.encrypt({ priv, epriv }, proof)
.then((auth) => // TODO: So signedsalt isn't needed?
// SEA.write(salt, pairs).then((signedsalt) =>
SEA.write({ salt, auth }, pairs)
// SEA.sign(salt, pairs).then((signedsalt) =>
SEA.sign({ek: auth, s: salt}, pairs)
// )
).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.
root.get(tmp).put(user)
try{
gunRoot.get(tmp).put(user)
}catch(e){console.log(e)}
// next up, we want to associate the alias with the public key. So we add it to the alias list.
root.get(`alias/${username}`).put(Gun.obj.put({}, tmp, Gun.val.rel.ify(tmp)))
gunRoot.get(`alias/${username}`).put(Gun.obj.put({}, tmp, Gun.val.rel.ify(tmp)))
// callback that the user has been created. (Note: ok = 0 because we didn't wait for disk to ack)
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) {
@ -81,15 +92,15 @@
}
})
})
return gun; // gun chain commands must return gun chains!
return gun // gun chain commands must return gun chains!
},
// now that we have created a user, we want to authenticate them!
async auth(alias, pass, cb, opts) {
if(cb && !(cb instanceof Function)){ opts = cb; cb = function(){} }
const { pin, newpass } = opts || {}
const root = this.back(-1)
cb = cb || function(){};
async auth(alias, pass, cb, opt) {
const opts = opt || (typeof cb !== 'function' && cb)
let { pin, newpass } = opts || {}
const gunRoot = this.back(-1)
cb = typeof cb === 'function' ? cb : () => {}
newpass = newpass || (opts||{}).change;
var gun = this, cat = (gun._);
if(cat.ing){
cb({err: "User is already being created or authenticated!", wait: true});
@ -99,7 +110,7 @@
if (!pass && pin) {
try {
var r = await authRecall(root, { alias, pin })
var r = await authRecall(gunRoot, { alias, pin })
return cat.ing = false, cb(r), gun;
} catch (e) {
var err = { err: 'Auth attempt failed! Reason: No session data for alias & PIN' }
@ -115,7 +126,7 @@
}
try {
const keys = await authenticate(alias, pass, root)
const keys = await authenticate(alias, pass, gunRoot)
if (!keys) {
return putErr('Auth attempt failed!')({ message: 'No keys' })
}
@ -124,14 +135,14 @@
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)
const salt = Gun.text.random(64);
const encSigAuth = await SEA.work(newpass, salt)
.then((key) =>
SEA.enc({ priv, epriv }, { pub, key, set: true })
.then((auth) => SEA.write({ salt, auth }, keys))
SEA.encrypt({ priv, epriv }, { pub, key, set: true })
.then((auth) => SEA.sign({ salt, auth }, keys))
)
const signedEpub = await SEA.write(epub, keys)
const signedAlias = await SEA.write(alias, keys)
const signedEpub = await SEA.sign(epub, keys)
const signedAlias = await SEA.sign(alias, keys)
const user = {
pub,
alias: signedAlias,
@ -139,18 +150,18 @@
epub: signedEpub
}
// awesome, now we can update the user using public key ID.
root.get(`pub/${user.pub}`).put(user)
gunRoot.get(`pub/${user.pub}`).put(user)
// then we're done
var login = finalizeLogin(alias, keys, root, { pin })
const login = finalizeLogin(alias, keys, gunRoot, { pin })
login.catch(putErr('Failed to finalize login with new password!'))
return cat.ing = false, cb(login), gun;
return cat.ing = false, cb(await login), gun
} catch (e) {
return putErr('Password set attempt failed!')(e)
}
} else {
var login = finalizeLogin(alias, keys, root, { pin })
const login = finalizeLogin(alias, keys, gunRoot, { pin })
login.catch(putErr('Finalizing login failed!'))
return cat.ing = false, cb(login), gun;
return cat.ing = false, cb(await login), gun;
}
} catch (e) {
return putErr('Auth attempt failed!')(e)
@ -162,18 +173,18 @@
},
// If authenticated user wants to delete his/her account, let's support it!
async delete(alias, pass) {
const root = this.back(-1)
const gunRoot = this.back(-1)
try {
const { pub } = await authenticate(alias, pass, root)
await authLeave(root, alias)
const { pub } = await authenticate(alias, pass, gunRoot)
await authLeave(gunRoot, alias)
// Delete user data
root.get(`pub/${pub}`).put(null)
gunRoot.get(`pub/${pub}`).put(null)
// Wipe user data from memory
const { user = { _: {} } } = root._;
const { user = { _: {} } } = gunRoot._;
// 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()
gunRoot.user()
return { ok: 0 } // TODO: proper return codes???
} catch (e) {
Gun.log('User.delete failed! Error:', e)
@ -182,11 +193,25 @@
},
// 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)
async recall(setvalidity, options) {
const gunRoot = this.back(-1)
let validity
let opts
var o = setvalidity;
if(o && o.sessionStorage){
if(typeof window !== 'undefined'){
var tmp = window.sessionStorage;
if(tmp){
gunRoot._.opt.remember = true;
if(tmp.alias && tmp.tmp){
gunRoot.user().auth(tmp.alias, tmp.tmp);
}
}
}
return this;
}
if (!Gun.val.is(setvalidity)) {
opts = setvalidity
@ -208,7 +233,7 @@
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)
return await authRecall(gunRoot)
} catch (e) {
const err = 'No session!'
Gun.log(err)
@ -218,11 +243,11 @@
}
},
async alive() {
const root = this.back(-1)
const gunRoot = this.back(-1)
try {
// All is good. Should we do something more with actual recalled data?
await authRecall(root)
return root._.user._
await authRecall(gunRoot)
return gunRoot._.user._
} catch (e) {
const err = 'No session!'
Gun.log(err)
@ -239,6 +264,5 @@
})
}
}
module.exports = User;
module.exports = User

34
sea/verify.js Normal file
View File

@ -0,0 +1,34 @@
var SEA = require('./root');
var shim = require('./shim');
var S = require('./settings');
var sha256hash = require('./sha256');
var parse = require('./parse');
var u;
SEA.verify = async (data, pair, cb) => { try {
const json = parse(data)
if(false === pair){ // don't verify!
const raw = (json === data)? json : parse(json.m)
if(cb){ cb(raw) }
return raw;
}
const pub = pair.pub || pair
const jwk = S.jwk(pub)
const key = await shim.subtle.importKey('jwk', jwk, S.ecdsa.pair, false, ['verify'])
const hash = await sha256hash(json.m)
const sig = new Uint8Array(shim.Buffer.from(json.s, 'utf8'))
const check = await shim.subtle.verify(S.ecdsa.sign, key, sig, new Uint8Array(hash))
if(!check){ throw "Signature did not match." }
const r = check? parse(json.m) : u;
if(cb){ cb(r) }
return r;
} catch(e) {
SEA.err = e;
if(cb){ cb() }
return;
}}
module.exports = SEA.verify;

View File

@ -1,25 +0,0 @@
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;

49
sea/work.js Normal file
View File

@ -0,0 +1,49 @@
var SEA = require('./root');
var shim = require('./shim');
var S = require('./settings');
var u;
SEA.work = async (data, pair, cb) => { try { // used to be named `proof`
var salt = pair.epub || pair; // epub not recommended, salt should be random!
if(salt instanceof Function){
cb = salt;
salt = u;
}
salt = salt || shim.random(9);
if (SEA.window) {
// For browser subtle works fine
const key = await shim.subtle.importKey(
'raw', new shim.TextEncoder().encode(data), { name: 'PBKDF2' }, false, ['deriveBits']
)
const result = await shim.subtle.deriveBits({
name: 'PBKDF2',
iterations: S.pbkdf2.iter,
salt: new shim.TextEncoder().encode(salt),
hash: S.pbkdf2.hash,
}, key, S.pbkdf2.ks * 8)
data = shim.random(data.length) // Erase data in case of passphrase
const r = shim.Buffer.from(result, 'binary').toString('utf8')
if(cb){ cb(r) }
return r;
}
// For NodeJS crypto.pkdf2 rocks
const hash = crypto.pbkdf2Sync(
data,
new shim.TextEncoder().encode(salt),
S.pbkdf2.iter,
S.pbkdf2.ks,
S.pbkdf2.hash.replace('-', '').toLowerCase()
)
data = shim.random(data.length) // Erase passphrase for app
const r = hash && hash.toString('utf8')
if(cb){ cb(r) }
return r;
} catch(e) {
SEA.err = e;
if(cb){ cb() }
return;
}}
module.exports = SEA.work;