mirror of
https://github.com/amark/gun.git
synced 2025-03-30 15:08:33 +00:00
BREAKING SEA CHANGES: AES-GCM !AES-CBC
This commit is contained in:
parent
d40c156338
commit
a24febc7a4
@ -6,7 +6,7 @@
|
||||
//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'])
|
||||
return await shim.subtle.importKey('raw', new Uint8Array(hash), 'AES-GCM', false, ['encrypt', 'decrypt'])
|
||||
}
|
||||
module.exports = importGen;
|
||||
|
@ -3,8 +3,8 @@
|
||||
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
|
||||
SeaArray.prototype.toString = function(enc, start, end) { enc = enc || 'utf8'; start = start || 0;
|
||||
const length = this.length
|
||||
if (enc === 'hex') {
|
||||
const buf = new Uint8Array(this)
|
||||
return [ ...Array(((end && (end + 1)) || length) - start).keys()]
|
||||
|
@ -15,19 +15,19 @@
|
||||
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 }) => {
|
||||
const [ user ] = await Promise.all(aliases.map(async ({ at: at, pub: 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.verify(at.put.auth, pub).then(function(auth){
|
||||
try {
|
||||
const proof = await SEA.work(pass, auth.s)
|
||||
const props = { pub, proof, at }
|
||||
const props = { 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!???
|
||||
*/
|
||||
const { salt } = auth
|
||||
const salt = auth.salt
|
||||
const sea = await SEA.decrypt(auth.ek, proof)
|
||||
if (!sea) {
|
||||
err = 'Failed to decrypt secret!'
|
||||
@ -35,8 +35,9 @@
|
||||
}
|
||||
// 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
|
||||
const priv = sea.priv
|
||||
const epriv = sea.epriv
|
||||
const epub = at.put.epub
|
||||
// TODO: 'salt' needed?
|
||||
err = null
|
||||
if(typeof window !== 'undefined'){
|
||||
@ -46,7 +47,7 @@
|
||||
window.sessionStorage.tmp = pass;
|
||||
}
|
||||
}
|
||||
return Object.assign(props, { priv, salt, epub, epriv })
|
||||
return Object.assign(props, { priv: priv, salt: salt, epub: epub, epriv: epriv })
|
||||
} catch (e) {
|
||||
err = 'Failed to decrypt secret!'
|
||||
throw { err }
|
||||
|
@ -28,24 +28,25 @@
|
||||
}
|
||||
buf = SeaArray.from(bytes)
|
||||
} else if (enc === 'utf8') {
|
||||
const { length } = input
|
||||
const length = input.length
|
||||
const words = new Uint16Array(length)
|
||||
Array.from({ length }, (_, i) => words[i] = input.charCodeAt(i))
|
||||
Array.from({ length: length }, (_, i) => words[i] = input.charCodeAt(i))
|
||||
buf = SeaArray.from(words)
|
||||
} else if (enc === 'base64') {
|
||||
const dec = atob(input)
|
||||
const { length } = dec
|
||||
const length = dec.length
|
||||
const bytes = new Uint8Array(length)
|
||||
Array.from({ length }, (_, i) => bytes[i] = dec.charCodeAt(i))
|
||||
Array.from({ length: 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}'`)
|
||||
console.info('SafeBuffer.from unknown encoding: '+enc)
|
||||
}
|
||||
return buf
|
||||
}
|
||||
const { byteLength, length = byteLength } = input
|
||||
const byteLength = input.byteLength
|
||||
const length = input.byteLength ? input.byteLength : input.length
|
||||
if (length) {
|
||||
let buf
|
||||
if (input instanceof ArrayBuffer) {
|
||||
@ -56,11 +57,11 @@
|
||||
},
|
||||
// This is 'safe-buffer.alloc' sans encoding support
|
||||
alloc(length, fill = 0 /*, enc*/ ) {
|
||||
return SeaArray.from(new Uint8Array(Array.from({ length }, () => fill)))
|
||||
return SeaArray.from(new Uint8Array(Array.from({ length: 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 })))
|
||||
return SeaArray.from(new Uint8Array(Array.from({ length : length })))
|
||||
},
|
||||
// This puts together array of array like members
|
||||
concat(arr) { // octet array
|
||||
|
302
sea/create.js
Normal file
302
sea/create.js
Normal file
@ -0,0 +1,302 @@
|
||||
|
||||
// TODO: This needs to be split into all separate functions.
|
||||
// Not just everything thrown into 'create'.
|
||||
|
||||
const SEA = require('./sea')
|
||||
const User = require('./user')
|
||||
const authRecall = require('./recall')
|
||||
const authsettings = require('./settings')
|
||||
const authenticate = require('./authenticate')
|
||||
const finalizeLogin = require('./login')
|
||||
const authLeave = require('./leave')
|
||||
const _initial_authsettings = require('./settings').recall
|
||||
const Gun = SEA.Gun;
|
||||
|
||||
var u;
|
||||
// Well first we have to actually create a user. That is what this function does.
|
||||
User.prototype.create = function(username, pass, cb){
|
||||
// TODO: Needs to be cleaned up!!!
|
||||
const gunRoot = this.back(-1)
|
||||
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 resolve = function(){}, reject = resolve;
|
||||
// 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 }
|
||||
gunRoot.get('~@'+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)
|
||||
cat.ing = false;
|
||||
gun.leave();
|
||||
return reject({ err: 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.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 = pairs.pub
|
||||
const priv = pairs.priv
|
||||
const epriv = pairs.epriv
|
||||
// the user's public key doesn't need to be signed. But everything else needs to be signed with it!
|
||||
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.encrypt({ priv: priv, epriv: epriv }, proof)
|
||||
.then((auth) => // TODO: So signedsalt isn't needed?
|
||||
// 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: alias, pub: pub, epub: epub, auth: auth }
|
||||
const tmp = '~'+pairs.pub;
|
||||
// awesome, now we can actually save the user with their public key as their ID.
|
||||
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.
|
||||
gunRoot.get('~@'+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) {
|
||||
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!
|
||||
User.prototype.auth = function(alias, pass, cb, opt){
|
||||
// TODO: Needs to be cleaned up!!!!
|
||||
const opts = opt || (typeof cb !== 'function' && cb)
|
||||
let pin = opts && opts.pin
|
||||
let newpass = opts && opts.newpass
|
||||
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});
|
||||
return gun;
|
||||
}
|
||||
cat.ing = true;
|
||||
|
||||
if (!pass && pin) { (async function(){
|
||||
try {
|
||||
var r = await authRecall(gunRoot, { alias: alias, pin: pin })
|
||||
return cat.ing = false, cb(r), gun;
|
||||
} catch (e) {
|
||||
var err = { err: 'Auth attempt failed! Reason: No session data for alias & PIN' }
|
||||
return cat.ing = false, gun.leave(), cb(err), gun;
|
||||
}}())
|
||||
return gun;
|
||||
}
|
||||
|
||||
const putErr = (msg) => (e) => {
|
||||
const { message, err = message || '' } = e
|
||||
Gun.log(msg)
|
||||
var error = { err: msg+' Reason: '+err }
|
||||
return cat.ing = false, gun.leave(), cb(error), gun;
|
||||
}
|
||||
|
||||
(async function(){ try {
|
||||
const keys = await authenticate(alias, pass, gunRoot)
|
||||
if (!keys) {
|
||||
return putErr('Auth attempt failed!')({ message: 'No keys' })
|
||||
}
|
||||
const pub = keys.pub
|
||||
const priv = keys.priv
|
||||
const epub = keys.epub
|
||||
const epriv = keys.epriv
|
||||
// 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.work(newpass, salt)
|
||||
.then((key) =>
|
||||
SEA.encrypt({ priv: priv, epriv: epriv }, key)
|
||||
.then((auth) => SEA.sign({ek: auth, s: salt}, keys))
|
||||
)
|
||||
const signedEpub = await SEA.sign(epub, keys)
|
||||
const signedAlias = await SEA.sign(alias, keys)
|
||||
const user = {
|
||||
pub: pub,
|
||||
alias: signedAlias,
|
||||
auth: encSigAuth,
|
||||
epub: signedEpub
|
||||
}
|
||||
// awesome, now we can update the user using public key ID.
|
||||
gunRoot.get('~'+user.pub).put(user)
|
||||
// then we're done
|
||||
const login = finalizeLogin(alias, keys, gunRoot, { pin })
|
||||
login.catch(putErr('Failed to finalize login with new password!'))
|
||||
return cat.ing = false, cb(await login), gun
|
||||
} catch (e) {
|
||||
return putErr('Password set attempt failed!')(e)
|
||||
}
|
||||
} else {
|
||||
const login = finalizeLogin(alias, keys, gunRoot, { pin: pin })
|
||||
login.catch(putErr('Finalizing login failed!'))
|
||||
return cat.ing = false, cb(await login), gun;
|
||||
}
|
||||
} catch (e) {
|
||||
return putErr('Auth attempt failed!')(e)
|
||||
} }());
|
||||
return gun;
|
||||
}
|
||||
User.prototype.pair = function(){
|
||||
var user = this;
|
||||
if(!user.is){ return false }
|
||||
return user._.sea;
|
||||
}
|
||||
User.prototype.leave = async function(){
|
||||
return await authLeave(this.back(-1))
|
||||
}
|
||||
// If authenticated user wants to delete his/her account, let's support it!
|
||||
User.prototype.delete = async function(alias, pass){
|
||||
const gunRoot = this.back(-1)
|
||||
try {
|
||||
const __gky40 = await authenticate(alias, pass, gunRoot)
|
||||
const pub = __gky40.pub
|
||||
await authLeave(gunRoot, alias)
|
||||
// Delete user data
|
||||
gunRoot.get('~'+pub).put(null)
|
||||
// Wipe user data from memory
|
||||
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 = {}
|
||||
gunRoot.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.
|
||||
User.prototype.recall = async function(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
|
||||
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(gunRoot)
|
||||
} 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 }
|
||||
}
|
||||
}
|
||||
User.prototype.alive = async function(){
|
||||
const gunRoot = this.back(-1)
|
||||
try {
|
||||
// All is good. Should we do something more with actual recalled data?
|
||||
await authRecall(gunRoot)
|
||||
return gunRoot._.user._
|
||||
} catch (e) {
|
||||
const err = 'No session!'
|
||||
Gun.log(err)
|
||||
throw { err }
|
||||
}
|
||||
}
|
||||
User.prototype.trust = async 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)
|
||||
})
|
||||
}
|
||||
}
|
||||
User.prototype.grant = function(to, cb){
|
||||
console.log("`.grant` API MAY BE DELETED OR CHANGED OR RENAMED, DO NOT USE!");
|
||||
var gun = this, user = gun.back(-1).user(), pair = user.pair(), path = '';
|
||||
gun.back(function(at){ if(at.pub){ return } path += (at.get||'') });
|
||||
(async function(){
|
||||
var enc, sec = await user.get('trust').get(pair.pub).get(path).then();
|
||||
sec = await SEA.decrypt(sec, pair);
|
||||
if(!sec){
|
||||
sec = SEA.random(16).toString();
|
||||
enc = await SEA.encrypt(sec, pair);
|
||||
user.get('trust').get(pair.pub).get(path).put(enc);
|
||||
}
|
||||
var pub = to.get('pub').then();
|
||||
var epub = to.get('epub').then();
|
||||
pub = await pub; epub = await epub;
|
||||
var dh = await SEA.secret(epub, pair);
|
||||
enc = await SEA.encrypt(sec, dh);
|
||||
user.get('trust').get(pub).get(path).put(enc, cb);
|
||||
}());
|
||||
return gun;
|
||||
}
|
||||
User.prototype.secret = function(data, cb){
|
||||
console.log("`.secret` API MAY BE DELETED OR CHANGED OR RENAMED, DO NOT USE!");
|
||||
var gun = this, user = gun.back(-1).user(), pair = user.pair(), path = '';
|
||||
gun.back(function(at){ if(at.pub){ return } path += (at.get||'') });
|
||||
(async function(){
|
||||
var enc, sec = await user.get('trust').get(pair.pub).get(path).then();
|
||||
sec = await SEA.decrypt(sec, pair);
|
||||
if(!sec){
|
||||
sec = SEA.random(16).toString();
|
||||
enc = await SEA.encrypt(sec, pair);
|
||||
user.get('trust').get(pair.pub).get(path).put(enc);
|
||||
}
|
||||
enc = await SEA.encrypt(data, sec);
|
||||
gun.put(enc, cb);
|
||||
}());
|
||||
return gun;
|
||||
}
|
||||
module.exports = User
|
||||
|
@ -10,7 +10,7 @@
|
||||
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'))
|
||||
name: 'AES-GCM', 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))
|
||||
|
||||
|
@ -10,7 +10,7 @@
|
||||
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)
|
||||
name: 'AES-GCM', iv: new Uint8Array(rand.iv)
|
||||
}, aes, new shim.TextEncoder().encode(msg)))
|
||||
const r = 'SEA'+JSON.stringify({
|
||||
ct: shim.Buffer.from(ct, 'binary').toString('utf8'),
|
||||
|
88
sea/index.js
88
sea/index.js
@ -1,20 +1,12 @@
|
||||
|
||||
const Gun = (typeof window !== 'undefined' ? window : global).Gun || require('gun/gun')
|
||||
const SEA = require('./sea')
|
||||
const Gun = SEA.Gun;
|
||||
// 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...
|
||||
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.
|
||||
at.on('node', each, at);
|
||||
@ -29,7 +21,7 @@
|
||||
// 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
|
||||
// Example: ~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 = <ID>` 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!
|
||||
@ -41,7 +33,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.verify(val, false).then(function(data){ c--; // false just extracts the plain data.
|
||||
SEA.verify(val, false, 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) }
|
||||
});
|
||||
@ -73,7 +65,7 @@
|
||||
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?
|
||||
if('~@' === soul.slice(0,2)){ // 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.
|
||||
@ -90,29 +82,29 @@
|
||||
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.
|
||||
if('~@' === 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.
|
||||
if('~@' === soul.slice(0,2)){ // 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;
|
||||
if('~' === soul.slice(0,1) && 2 === (tmp = soul.slice(1)).split('.').length){ // special case, account data for a public key.
|
||||
each.pub(val, key, node, soul, tmp, msg.user); return;
|
||||
}
|
||||
each.any(val, key, node, soul, msg.user); return;
|
||||
return each.end({err: "No other data allowed!"});
|
||||
};
|
||||
each.alias = function(val, key, node, soul){ // Example: {_:#alias, alias/alice: {#alias/alice}}
|
||||
each.alias = function(val, key, node, soul){ // Example: {_:#~@, ~@alice: {#~@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
|
||||
if('~@'+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}}
|
||||
each.pubs = function(val, key, node, soul){ // Example: {_:#~@alice, ~asdf: {#~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]}
|
||||
each.pub = function(val, key, node, soul, pub, user){ // Example: {_:#~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!"});
|
||||
@ -120,7 +112,8 @@
|
||||
check['user'+soul+key] = 1;
|
||||
if(user && (user = user._) && user.sea && pub === user.pub){
|
||||
//var id = Gun.text.random(3);
|
||||
SEA.sign(val, user.sea).then(function(data){ var rel;
|
||||
SEA.sign(val, user.sea, function(data){ var rel;
|
||||
if(u === data){ return each.end({err: SEA.err || 'Pub signature fail.'}) }
|
||||
if(rel = Gun.val.rel.is(val)){
|
||||
(at.sea.own[rel] = at.sea.own[rel] || {})[pub] = true;
|
||||
}
|
||||
@ -131,30 +124,34 @@
|
||||
// TODO: Handle error!!!!
|
||||
return;
|
||||
}
|
||||
// TODO: consider async/await and drop callback pattern...
|
||||
SEA.verify(val, pub).then(function(data){ var rel, tmp;
|
||||
SEA.verify(val, pub, 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){
|
||||
if(pub === tmp[1]){
|
||||
(at.sea.own[rel] = at.sea.own[rel] || {})[pub] = true;
|
||||
}
|
||||
if((rel = Gun.val.rel.is(data)) && pub === relpub(rel)){
|
||||
(at.sea.own[rel] = at.sea.own[rel] || {})[pub] = true;
|
||||
}
|
||||
check['user'+soul+key] = 0;
|
||||
each.end({ok: 1});
|
||||
});
|
||||
};
|
||||
function relpub(s){
|
||||
if(!s){ return }
|
||||
s = s.split('~');
|
||||
if(!s || !(s = s[1])){ return }
|
||||
s = s.split('.');
|
||||
if(!s || 2 > s.length){ return }
|
||||
s = s.slice(0,2).join('.');
|
||||
return s;
|
||||
}
|
||||
each.any = function(val, key, node, soul, user){ var tmp, pub;
|
||||
if(!user || !(user = user._) || !(user = user.sea)){
|
||||
if((tmp = soul.split('~')) && 2 == tmp.length){
|
||||
if(tmp = relpub(soul)){
|
||||
check['any'+soul+key] = 1;
|
||||
SEA.verify(val, (pub = tmp[1])).then(function(data){ var rel;
|
||||
SEA.verify(val, pub = tmp, 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){
|
||||
if(pub === tmp[1]){
|
||||
(at.sea.own[rel] = at.sea.own[rel] || {})[pub] = true;
|
||||
}
|
||||
if((rel = Gun.val.rel.is(data)) && pub === relpub(rel)){
|
||||
(at.sea.own[rel] = at.sea.own[rel] || {})[pub] = true;
|
||||
}
|
||||
check['any'+soul+key] = 0;
|
||||
each.end({ok: 1});
|
||||
@ -164,16 +161,32 @@
|
||||
check['any'+soul+key] = 1;
|
||||
at.on('secure', function(msg){ this.off();
|
||||
check['any'+soul+key] = 0;
|
||||
if(at.opt.secure){ msg = null }
|
||||
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 missing public key at '" + key + "'."});
|
||||
if(!(tmp = relpub(soul))){
|
||||
if(at.opt.secure){
|
||||
each.end({err: "Soul is missing public key at '" + key + "'."});
|
||||
return;
|
||||
}
|
||||
if(val && val.slice && 'SEA{' === (val).slice(0,4)){
|
||||
check['any'+soul+key] = 0;
|
||||
each.end({ok: 1});
|
||||
return;
|
||||
}
|
||||
//check['any'+soul+key] = 1;
|
||||
//SEA.sign(val, user, function(data){
|
||||
// if(u === data){ return each.end({err: 'Any signature failed.'}) }
|
||||
// node[key] = data;
|
||||
check['any'+soul+key] = 0;
|
||||
each.end({ok: 1});
|
||||
//});
|
||||
return;
|
||||
}
|
||||
var pub = tmp[1];
|
||||
var pub = tmp;
|
||||
if(pub !== user.pub){
|
||||
each.any(val, key, node, soul);
|
||||
return;
|
||||
@ -186,7 +199,8 @@
|
||||
return;
|
||||
}*/
|
||||
check['any'+soul+key] = 1;
|
||||
SEA.sign(val, user).then(function(data){
|
||||
SEA.sign(val, user, function(data){
|
||||
if(u === data){ return each.end({err: 'My signature fail.'}) }
|
||||
node[key] = data;
|
||||
check['any'+soul+key] = 0;
|
||||
each.end({ok: 1});
|
||||
|
@ -13,7 +13,7 @@
|
||||
gunRoot.user();
|
||||
// Removes persisted authentication & CryptoKeys
|
||||
try {
|
||||
await authPersist({ alias })
|
||||
await authPersist({ alias: alias })
|
||||
} catch (e) {} //eslint-disable-line no-empty
|
||||
return { ok: 0 }
|
||||
}
|
||||
|
15
sea/login.js
15
sea/login.js
@ -2,14 +2,21 @@
|
||||
const authPersist = require('./persist')
|
||||
// This internal func finalizes User authentication
|
||||
const finalizeLogin = async (alias, key, gunRoot, opts) => {
|
||||
const { user } = gunRoot._
|
||||
const user = gunRoot._.user
|
||||
// add our credentials in-memory only to our root gun instance
|
||||
user._ = key.at.gun._
|
||||
//var tmp = user._.tag;
|
||||
var opt = user._.opt;
|
||||
user._ = key.at.gun._;
|
||||
user._.opt = opt;
|
||||
//user._.tag = tmp || user._.tag;
|
||||
// so that way we can use the credentials to encrypt/decrypt data
|
||||
// that is input/output through gun (see below)
|
||||
const { pub, priv, epub, epriv } = key
|
||||
const pub = key.pub
|
||||
const priv = key.priv
|
||||
const epub = key.epub
|
||||
const epriv = key.epriv
|
||||
user._.is = user.is = {alias: alias, pub: pub};
|
||||
Object.assign(user._, { alias, pub, epub, sea: { pub, priv, epub, epriv } })
|
||||
Object.assign(user._, { alias: alias, pub: pub, epub: epub, sea: { pub: pub, priv: priv, epub: epub, epriv: epriv } })
|
||||
//console.log("authorized", user._);
|
||||
// persist authentication
|
||||
//await authPersist(user._, key.proof, opts) // temporarily disabled
|
||||
|
31
sea/pair.js
31
sea/pair.js
@ -9,37 +9,46 @@
|
||||
|
||||
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' ])
|
||||
var sa = 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 { d: priv } = await shim.subtle.exportKey('jwk', keys.privateKey)
|
||||
const key = {};
|
||||
key.priv = (await shim.subtle.exportKey('jwk', keys.privateKey)).d;
|
||||
const pub = await shim.subtle.exportKey('jwk', keys.publicKey)
|
||||
//const pub = Buff.from([ x, y ].join(':')).toString('base64') // old
|
||||
const pub = x+'.'+y // new
|
||||
key.pub = pub.x+'.'+pub.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 }
|
||||
return key;
|
||||
})
|
||||
|
||||
// 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'])
|
||||
try{
|
||||
var dh = 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 key = {};
|
||||
key.epriv = (await ecdhSubtle.exportKey('jwk', keys.privateKey)).d;
|
||||
const pub = await ecdhSubtle.exportKey('jwk', keys.publicKey)
|
||||
//const epub = Buff.from([ ex, ey ].join(':')).toString('base64') // old
|
||||
const epub = x+'.'+y // new
|
||||
key.epub = pub.x+'.'+pub.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 }
|
||||
return key;
|
||||
})
|
||||
}catch(e){
|
||||
if(SEA.window){ throw e }
|
||||
if(e == 'Error: ECDH is not a supported algorithm'){ console.log(e) }
|
||||
else { throw e }
|
||||
} dh = dh || {};
|
||||
|
||||
const r = { pub, priv, /* pubId, */ epub, epriv }
|
||||
const r = { pub: sa.pub, priv: sa.priv, /* pubId, */ epub: dh.epub, epriv: dh.epriv }
|
||||
if(cb){ cb(r) }
|
||||
return r;
|
||||
} catch(e) {
|
||||
|
@ -1,5 +1,6 @@
|
||||
|
||||
const Gun = (typeof window !== 'undefined' ? window : global).Gun || require('gun/gun')
|
||||
const SEA = require('./sea');
|
||||
const Gun = SEA.Gun;
|
||||
const Buffer = require('./buffer')
|
||||
const authsettings = require('./settings')
|
||||
const updateStorage = require('./update')
|
||||
@ -16,15 +17,18 @@
|
||||
'utf8'
|
||||
).toString('base64')
|
||||
|
||||
const { alias } = user || {}
|
||||
const { validity: exp } = authsettings // seconds // @mhelander what is `exp`???
|
||||
const alias = user.alias
|
||||
const exp = authsettings.validity // 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 }
|
||||
const props = authsettings.hook({ alias: alias, iat: iat, exp: exp, remember: remember })
|
||||
const pub = user.pub
|
||||
const epub = user.epub
|
||||
const priv = user.sea.priv
|
||||
const epriv = user.sea.epriv
|
||||
const key = { pub: pub, priv: priv, epub: epub, epriv: epriv }
|
||||
if (props instanceof Promise) {
|
||||
const asyncProps = await props.then()
|
||||
return await updateStorage(proof, key, pin)(asyncProps)
|
||||
|
@ -4,7 +4,7 @@
|
||||
// This is internal func queries public key(s) for alias.
|
||||
const queryGunAliases = (alias, gunRoot) => new Promise((resolve, reject) => {
|
||||
// load all public keys associated with the username alias we want to log in with.
|
||||
gunRoot.get(`alias/${alias}`).get((rat, rev) => {
|
||||
gunRoot.get('~@'+alias).get((rat, rev) => {
|
||||
rev.off();
|
||||
if (!rat.put) {
|
||||
// if no user, don't do anything.
|
||||
@ -17,14 +17,14 @@
|
||||
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)) {
|
||||
if (!pub.slice || '~' !== pub.slice(0, 1)) {
|
||||
// TODO: ... this would then be .filter((at, pub))
|
||||
return
|
||||
}
|
||||
++c
|
||||
// grab the account associated with this public key.
|
||||
gunRoot.get(pub).get((at, ev) => {
|
||||
pub = pub.slice(4)
|
||||
pub = pub.slice(1)
|
||||
ev.off()
|
||||
--c
|
||||
if (at.put){
|
||||
|
@ -1,7 +1,4 @@
|
||||
|
||||
// TODO: BUG! `SEA` needs to be USEd!
|
||||
const Gun = (typeof window !== 'undefined' ? window : global).Gun || require('gun/gun')
|
||||
|
||||
const Buffer = require('./buffer')
|
||||
const authsettings = require('./settings')
|
||||
//const { scope: seaIndexedDb } = require('./indexed')
|
||||
@ -9,6 +6,7 @@
|
||||
const parseProps = require('./parse')
|
||||
const updateStorage = require('./update')
|
||||
const SEA = require('./sea')
|
||||
const Gun = SEA.Gun;
|
||||
const finalizeLogin = require('./login')
|
||||
|
||||
// This internal func recalls persisted User authentication if so configured
|
||||
@ -23,13 +21,13 @@
|
||||
const checkNotExpired = (args) => {
|
||||
if (Math.floor(Date.now() / 1000) < (iat + args.exp)) {
|
||||
// No way hook to update 'iat'
|
||||
return Object.assign(args, { iat, proof })
|
||||
return Object.assign(args, { iat: iat, proof: proof })
|
||||
} else {
|
||||
Gun.log('Authentication expired!')
|
||||
}
|
||||
}
|
||||
// We're not gonna give proof to hook!
|
||||
const hooked = authsettings.hook({ alias, iat, exp, remember })
|
||||
const hooked = authsettings.hook({ alias: alias, iat: iat, exp: exp, remember: remember })
|
||||
return ((hooked instanceof Promise)
|
||||
&& await hooked.then(checkNotExpired)) || checkNotExpired(hooked)
|
||||
}
|
||||
@ -66,10 +64,11 @@
|
||||
// (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 }) => {
|
||||
.map(async ({ at: at, pub: pub }) => {
|
||||
const readStorageData = async (args) => {
|
||||
const props = args || parseProps(await SEA.verify(remember, pub, true))
|
||||
let { pin, alias: aLias } = props
|
||||
let pin = props.pin
|
||||
let aLias = props.alias
|
||||
|
||||
const data = (!pin && alias === aLias)
|
||||
// No PIN, let's try short-term proof if for matching alias
|
||||
@ -78,11 +77,13 @@
|
||||
: await checkRememberData(await readAndDecrypt(await seaIndexedDb.get(alias, 'auth'), pub, pin))
|
||||
pin = pin || data.pin
|
||||
delete data.pin
|
||||
return { pin, data }
|
||||
return { pin: pin, data: data }
|
||||
}
|
||||
// got pub, try auth with pin & alias :: or unwrap Storage data...
|
||||
const { data, pin: newPin } = await readStorageData(pin && { pin, alias })
|
||||
const { proof } = data || {}
|
||||
const __gky20 = await readStorageData(pin && { pin, alias })
|
||||
const data = __gky20.data
|
||||
const newPin = __gky20.pin
|
||||
const proof = data.proof
|
||||
|
||||
if (!proof) {
|
||||
if (!data) {
|
||||
@ -97,17 +98,18 @@
|
||||
}
|
||||
|
||||
try { // auth parsing or decryption fails or returns empty - silently done
|
||||
const { auth } = at.put.auth
|
||||
const auth= at.put.auth.auth
|
||||
const sea = await SEA.decrypt(auth, proof)
|
||||
if (!sea) {
|
||||
err = 'Failed to decrypt private key!'
|
||||
return
|
||||
}
|
||||
const { priv, epriv } = sea
|
||||
const { epub } = at.put
|
||||
const priv = sea.priv
|
||||
const epriv = sea.epriv
|
||||
const epub = at.put.epub
|
||||
// Success! we've found our private data!
|
||||
err = null
|
||||
return { proof, at, pin: newPin, key: { pub, priv, epriv, epub } }
|
||||
return { proof: proof, at: at, pin: newPin, key: { pub: pub, priv: priv, epriv: epriv, epub: epub } }
|
||||
} catch (e) {
|
||||
err = 'Failed to decrypt private key!'
|
||||
return
|
||||
@ -123,7 +125,7 @@
|
||||
try {
|
||||
await updateStorage(proof, key, newPin || pin)(key)
|
||||
|
||||
const user = Object.assign(key, { at, proof })
|
||||
const user = Object.assign(key, { at: at, proof: proof })
|
||||
const pIN = newPin || pin
|
||||
|
||||
const pinProp = pIN && { pin: Buffer.from(pIN, 'base64').toString('utf8') }
|
||||
@ -132,7 +134,7 @@
|
||||
} 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}` }
|
||||
throw { err: 'Finalizing new password login failed! Reason: '+err }
|
||||
}
|
||||
}
|
||||
module.exports = authRecall
|
||||
|
27
sea/sea.js
27
sea/sea.js
@ -1,22 +1,21 @@
|
||||
|
||||
// Old Code...
|
||||
const {
|
||||
crypto,
|
||||
subtle,
|
||||
ossl,
|
||||
random: getRandomBytes,
|
||||
TextEncoder,
|
||||
TextDecoder
|
||||
} = require('./shim')
|
||||
const __gky10 = require('./shim')
|
||||
const crypto = __gky10.crypto
|
||||
const subtle = __gky10.subtle
|
||||
const ossl = __gky10.ossl
|
||||
const TextEncoder = __gky10.TextEncoder
|
||||
const TextDecoder = __gky10.TextDecoder
|
||||
const getRandomBytes = __gky10.random
|
||||
const EasyIndexedDB = require('./indexed')
|
||||
const Buffer = require('./buffer')
|
||||
var settings = require('./settings');
|
||||
const {
|
||||
pbkdf2: pbKdf2,
|
||||
ecdsa: { pair: ecdsaKeyProps, sign: ecdsaSignProps },
|
||||
ecdh: ecdhKeyProps,
|
||||
jwk: keysToEcdsaJwk
|
||||
} = require('./settings')
|
||||
const __gky11 = require('./settings')
|
||||
const pbKdf2 = __gky11.pbkdf2
|
||||
const ecdsaKeyProps = __gky11.ecdsa.pair
|
||||
const ecdsaSignProps = __gky11.ecdsa.sign
|
||||
const ecdhKeyProps = __gky11.ecdh
|
||||
const keysToEcdsaJwk = __gky11.jwk
|
||||
const sha1hash = require('./sha1')
|
||||
const sha256hash = require('./sha256')
|
||||
const recallCryptoKey = require('./remember')
|
||||
|
@ -9,15 +9,15 @@
|
||||
const epriv = pair.epriv
|
||||
const ecdhSubtle = shim.ossl || shim.subtle
|
||||
const pubKeyData = keysToEcdhJwk(pub)
|
||||
const props = {
|
||||
...S.ecdh,
|
||||
public: await ecdhSubtle.importKey(...pubKeyData, true, [])
|
||||
}
|
||||
const props = Object.assign(
|
||||
S.ecdh,
|
||||
{ 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' ])
|
||||
const derivedKey = await ecdhSubtle.deriveKey(props, privKey, { name: 'AES-GCM', length: 256 }, true, [ 'encrypt', 'decrypt' ])
|
||||
return ecdhSubtle.exportKey('jwk', derivedKey).then(({ k }) => k)
|
||||
})
|
||||
const r = derived;
|
||||
@ -32,10 +32,13 @@
|
||||
const keysToEcdhJwk = (pub, d) => { // d === priv
|
||||
//const [ x, y ] = Buffer.from(pub, 'base64').toString('utf8').split(':') // old
|
||||
const [ x, y ] = pub.split('.') // new
|
||||
const jwk = d ? { d } : {}
|
||||
const jwk = d ? { d: d } : {}
|
||||
return [ // Use with spread returned value...
|
||||
'jwk',
|
||||
{ ...jwk, x, y, kty: 'EC', crv: 'P-256', ext: true }, // ??? refactor
|
||||
Object.assign(
|
||||
jwk,
|
||||
{ x: x, y: y, kty: 'EC', crv: 'P-256', ext: true }
|
||||
), // ??? refactor
|
||||
S.ecdh
|
||||
]
|
||||
}
|
||||
|
@ -26,7 +26,7 @@
|
||||
}
|
||||
|
||||
Object.assign(settings, {
|
||||
pbkdf2,
|
||||
pbkdf2: pbkdf2,
|
||||
ecdsa: {
|
||||
pair: ecdsaKeyProps,
|
||||
sign: ecdsaSignProps
|
||||
|
@ -1,6 +1,8 @@
|
||||
|
||||
// This internal func returns SHA-1 hashed data for KeyID generation
|
||||
const { subtle, ossl = subtle } = require('./shim')
|
||||
const __shim = require('./shim')
|
||||
const subtle = __shim.subtle
|
||||
const ossl = __shim.ossl ? __shim.__ossl : subtle
|
||||
const sha1hash = (b) => ossl.digest({name: 'SHA-1'}, new ArrayBuffer(b))
|
||||
module.exports = sha1hash
|
||||
|
36
sea/shim.js
36
sea/shim.js
@ -3,9 +3,10 @@
|
||||
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
|
||||
var crypto = window.crypto || window.msCrypto;
|
||||
var subtle = crypto.subtle || crypto.webkitSubtle;
|
||||
const TextEncoder = window.TextEncoder
|
||||
const TextDecoder = window.TextDecoder
|
||||
Object.assign(api, {
|
||||
crypto,
|
||||
subtle,
|
||||
@ -15,19 +16,22 @@
|
||||
})
|
||||
} 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))
|
||||
})
|
||||
var crypto = require('crypto');
|
||||
const { subtle } = require('@trust/webcrypto') // All but ECDH
|
||||
const { TextEncoder, TextDecoder } = require('text-encoding')
|
||||
Object.assign(api, {
|
||||
crypto,
|
||||
subtle,
|
||||
TextEncoder,
|
||||
TextDecoder,
|
||||
random: (len) => Buffer.from(crypto.randomBytes(len))
|
||||
});
|
||||
try{
|
||||
const WebCrypto = require('node-webcrypto-ossl')
|
||||
api.ossl = new WebCrypto({directory: 'key_storage'}).subtle // ECDH
|
||||
}catch(e){
|
||||
console.log("node-webcrypto-ossl is optionally needed for ECDH, please install if needed.");
|
||||
}
|
||||
}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;
|
||||
|
9
sea/then.js
Normal file
9
sea/then.js
Normal file
@ -0,0 +1,9 @@
|
||||
|
||||
var Gun = require('./sea').Gun;
|
||||
Gun.chain.then = function(cb){
|
||||
var gun = this, p = (new Promise(function(res, rej){
|
||||
gun.once(res);
|
||||
}));
|
||||
return cb? p.then(cb) : p;
|
||||
}
|
||||
|
@ -1,8 +1,7 @@
|
||||
|
||||
// TODO: BUG! `SEA` needs to be USED!
|
||||
const Gun = (typeof window !== 'undefined' ? window : global).Gun || require('gun/gun')
|
||||
const authsettings = require('./settings')
|
||||
const SEA = require('./sea');
|
||||
const Gun = SEA.Gun;
|
||||
//const { scope: seaIndexedDb } = require('./indexed')
|
||||
// This updates sessionStorage & IndexedDB to persist authenticated "session"
|
||||
const updateStorage = (proof, key, pin) => async (props) => {
|
||||
@ -13,8 +12,9 @@
|
||||
props.proof = proof
|
||||
delete props.remember // Not stored if present
|
||||
|
||||
const { alias, alias: id } = props
|
||||
const remember = { alias, pin }
|
||||
const alias = props.alias
|
||||
const id = props.alias
|
||||
const remember = { alias: alias, pin: pin }
|
||||
|
||||
try {
|
||||
const signed = await SEA.sign(JSON.stringify(remember), key)
|
||||
@ -27,7 +27,7 @@
|
||||
if (encrypted) {
|
||||
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 })
|
||||
await seaIndexedDb.put(id, { auth: auth })
|
||||
}
|
||||
|
||||
return props
|
||||
|
283
sea/user.js
283
sea/user.js
@ -1,268 +1,31 @@
|
||||
|
||||
// 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 Gun = SEA.Gun;
|
||||
var then = require('./then');
|
||||
|
||||
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;
|
||||
function User(){
|
||||
this._ = {gun: this}
|
||||
Gun.call()
|
||||
}
|
||||
User.prototype = (function(){ function F(){}; F.prototype = Gun.chain; return new F() }()) // Object.create polyfill
|
||||
User.prototype.constructor = User;
|
||||
|
||||
// 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 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
|
||||
'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!
|
||||
}
|
||||
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 gunRoot = this.back(-1)
|
||||
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 }
|
||||
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.
|
||||
const err = 'User already created!'
|
||||
Gun.log(err)
|
||||
cat.ing = false;
|
||||
gun.leave();
|
||||
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.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.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.encrypt({ priv, epriv }, proof)
|
||||
.then((auth) => // TODO: So signedsalt isn't needed?
|
||||
// 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.
|
||||
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.
|
||||
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) {
|
||||
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, 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});
|
||||
return gun;
|
||||
}
|
||||
cat.ing = true;
|
||||
|
||||
if (!pass && pin) {
|
||||
try {
|
||||
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' }
|
||||
return cat.ing = false, gun.leave(), cb(err), gun;
|
||||
}
|
||||
}
|
||||
|
||||
const putErr = (msg) => (e) => {
|
||||
const { message, err = message || '' } = e
|
||||
Gun.log(msg)
|
||||
var error = { err: `${msg} Reason: ${err}` }
|
||||
return cat.ing = false, gun.leave(), cb(error), gun;
|
||||
}
|
||||
|
||||
try {
|
||||
const keys = await authenticate(alias, pass, gunRoot)
|
||||
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.work(newpass, salt)
|
||||
.then((key) =>
|
||||
SEA.encrypt({ priv, epriv }, key)
|
||||
.then((auth) => SEA.sign({ek: auth, s: salt}, keys))
|
||||
)
|
||||
const signedEpub = await SEA.sign(epub, keys)
|
||||
const signedAlias = await SEA.sign(alias, keys)
|
||||
const user = {
|
||||
pub,
|
||||
alias: signedAlias,
|
||||
auth: encSigAuth,
|
||||
epub: signedEpub
|
||||
}
|
||||
// awesome, now we can update the user using public key ID.
|
||||
gunRoot.get(`pub/${user.pub}`).put(user)
|
||||
// then we're done
|
||||
const login = finalizeLogin(alias, keys, gunRoot, { pin })
|
||||
login.catch(putErr('Failed to finalize login with new password!'))
|
||||
return cat.ing = false, cb(await login), gun
|
||||
} catch (e) {
|
||||
return putErr('Password set attempt failed!')(e)
|
||||
}
|
||||
} else {
|
||||
const login = finalizeLogin(alias, keys, gunRoot, { pin })
|
||||
login.catch(putErr('Finalizing login failed!'))
|
||||
return cat.ing = false, cb(await login), gun;
|
||||
}
|
||||
} catch (e) {
|
||||
return putErr('Auth attempt failed!')(e)
|
||||
}
|
||||
return gun;
|
||||
},
|
||||
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 gunRoot = this.back(-1)
|
||||
try {
|
||||
const { pub } = await authenticate(alias, pass, gunRoot)
|
||||
await authLeave(gunRoot, alias)
|
||||
// Delete user data
|
||||
gunRoot.get(`pub/${pub}`).put(null)
|
||||
// Wipe user data from memory
|
||||
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 = {}
|
||||
gunRoot.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 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);
|
||||
}
|
||||
}
|
||||
Gun.chain.user = function(pub){
|
||||
var gun = this, root = gun.back(-1), user;
|
||||
if(pub){ return root.get('~'+pub) }
|
||||
if(user = root.back('user')){ return user }
|
||||
var root = (root._), at = root, uuid = at.opt.uuid || Gun.state.lex;
|
||||
(at = (user = at.user = gun.chain(new User))._).opt = {};
|
||||
at.opt.uuid = function(cb){
|
||||
var id = uuid(), pub = root.user;
|
||||
if(!pub || !(pub = (pub._).sea) || !(pub = pub.pub)){ return id }
|
||||
id = id + '~' + pub + '.';
|
||||
if(cb && cb.call){ cb(null, id) }
|
||||
return id;
|
||||
}
|
||||
return this;
|
||||
return user;
|
||||
}
|
||||
|
||||
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(gunRoot)
|
||||
} 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 gunRoot = this.back(-1)
|
||||
try {
|
||||
// All is good. Should we do something more with actual recalled data?
|
||||
await authRecall(gunRoot)
|
||||
return gunRoot._.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
|
||||
module.exports = User;
|
||||
|
@ -9,7 +9,9 @@
|
||||
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)
|
||||
const raw = (json !== data)?
|
||||
(json.s && json.m)? parse(json.m) : data
|
||||
: json;
|
||||
if(cb){ cb(raw) }
|
||||
return raw;
|
||||
}
|
||||
|
@ -28,6 +28,7 @@
|
||||
return r;
|
||||
}
|
||||
// For NodeJS crypto.pkdf2 rocks
|
||||
const crypto = shim.crypto;
|
||||
const hash = crypto.pbkdf2Sync(
|
||||
data,
|
||||
new shim.TextEncoder().encode(salt),
|
||||
|
@ -42,7 +42,7 @@ State.ify = function(n, k, s, v, soul){ // put a key's state on a node.
|
||||
return n;
|
||||
}
|
||||
State.to = function(from, k, to){
|
||||
var val = from[k];
|
||||
var val = from[k]; // BUGGY!
|
||||
if(obj_is(val)){
|
||||
val = obj_copy(val);
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user