mirror of
https://github.com/amark/gun.git
synced 2025-06-06 14:16:44 +00:00
I did NOT merge SEA into master!
This commit is contained in:
parent
53ab90c8d3
commit
039d287c9b
17
sea/https.js
Normal file
17
sea/https.js
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
|
||||||
|
/*
|
||||||
|
Security, Encryption, and Authorization: SEA.js
|
||||||
|
*/
|
||||||
|
|
||||||
|
// NECESSARY PRE-REQUISITE: http://gun.js.org/explainers/data/security.html
|
||||||
|
|
||||||
|
/* THIS IS AN EARLY ALPHA!!! */
|
||||||
|
|
||||||
|
if(typeof window !== 'undefined'){
|
||||||
|
if(location.protocol.indexOf('s') < 0
|
||||||
|
&& location.host.indexOf('localhost') < 0
|
||||||
|
&& location.protocol.indexOf('file:') < 0){
|
||||||
|
location.protocol = 'https:';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -46,8 +46,33 @@
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
// This is IndexedDB used by Gun SEA
|
|
||||||
const seaIndexedDb = new EasyIndexedDB('SEA', 'GunDB', 1)
|
let indexedDB
|
||||||
|
let funcsSetter
|
||||||
|
|
||||||
|
if (typeof __webpack_require__ === 'function' || typeof window !== 'undefined') {
|
||||||
|
funcsSetter = () => window
|
||||||
|
indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB
|
||||||
|
} else {
|
||||||
|
funcsSetter = () => {
|
||||||
|
const { TextEncoder, TextDecoder } = require('text-encoding')
|
||||||
|
// Let's have Storage for NodeJS / testing
|
||||||
|
const sessionStorage = new require('node-localstorage').LocalStorage('.sessionStorage')
|
||||||
|
const localStorage = new require('node-localstorage').LocalStorage('.localStorage')
|
||||||
|
return { TextEncoder, TextDecoder, sessionStorage, localStorage }
|
||||||
|
}
|
||||||
|
indexedDB = require('fake-indexeddb')
|
||||||
|
}
|
||||||
|
|
||||||
|
const { TextEncoder, TextDecoder, sessionStorage, localStorage } = funcsSetter()
|
||||||
|
|
||||||
|
if (typeof __webpack_require__ !== 'function' && typeof global !== 'undefined') {
|
||||||
|
global.sessionStorage = sessionStorage
|
||||||
|
global.localStorage = localStorage
|
||||||
|
}
|
||||||
|
|
||||||
|
const seaIndexedDb = new EasyIndexedDB('SEA', 'GunDB', 1) // This is IndexedDB used by Gun SEA
|
||||||
EasyIndexedDB.scope = seaIndexedDb; // for now. This module should not export an instance of itself!
|
EasyIndexedDB.scope = seaIndexedDb; // for now. This module should not export an instance of itself!
|
||||||
|
|
||||||
module.exports = EasyIndexedDB;
|
module.exports = EasyIndexedDB;
|
||||||
|
|
14
sea/leave.js
14
sea/leave.js
@ -5,17 +5,17 @@
|
|||||||
var seaIndexedDb = require('./indexed').scope;
|
var seaIndexedDb = require('./indexed').scope;
|
||||||
// This internal func executes logout actions
|
// This internal func executes logout actions
|
||||||
const authLeave = async (root, alias = root._.user._.alias) => {
|
const authLeave = async (root, alias = root._.user._.alias) => {
|
||||||
const { user = { _: {} } } = root._
|
var user = root._.user._ || {};
|
||||||
root._.user = null
|
[ 'get', 'soul', 'ack', 'put', 'is', 'alias', 'pub', 'epub', 'sea' ].map((key) => delete user[key])
|
||||||
|
if(user.gun){
|
||||||
|
delete user.gun.is;
|
||||||
|
}
|
||||||
|
// Let's use default
|
||||||
|
root.user();
|
||||||
// Removes persisted authentication & CryptoKeys
|
// Removes persisted authentication & CryptoKeys
|
||||||
try {
|
try {
|
||||||
await authPersist({ alias })
|
await authPersist({ alias })
|
||||||
} catch (e) {} //eslint-disable-line no-empty
|
} catch (e) {} //eslint-disable-line no-empty
|
||||||
// TODO: is this correct way to 'logout' user from Gun.User ?
|
|
||||||
[ 'alias', 'sea', 'pub' ].map((key) => delete user._[key])
|
|
||||||
user._.is = user.is = {}
|
|
||||||
// Let's use default
|
|
||||||
root.user();
|
|
||||||
return { ok: 0 }
|
return { ok: 0 }
|
||||||
}
|
}
|
||||||
module.exports = authLeave;
|
module.exports = authLeave;
|
||||||
|
@ -1,6 +1,8 @@
|
|||||||
|
|
||||||
var Buffer = require('./buffer');
|
var Buffer = require('./buffer');
|
||||||
var sha256hash = require('./sha256');
|
var sha256hash = require('./sha256');
|
||||||
|
var wc = require('./webcrypto');
|
||||||
|
var subtle = wc.subtle;
|
||||||
var seaIndexedDb = require('./indexed').scope;
|
var seaIndexedDb = require('./indexed').scope;
|
||||||
var settings = require('./settings');
|
var settings = require('./settings');
|
||||||
var authsettings = settings.recall;
|
var authsettings = settings.recall;
|
||||||
|
16
sea/sea.js
16
sea/sea.js
@ -1,5 +1,9 @@
|
|||||||
|
|
||||||
const Gun = (typeof window !== 'undefined' ? window : global).Gun || require('gun/gun')
|
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 EasyIndexedDB = require('./indexed');
|
||||||
var SafeBuffer = require('./buffer');
|
var SafeBuffer = require('./buffer');
|
||||||
var settings = require('./settings');
|
var settings = require('./settings');
|
||||||
@ -11,15 +15,7 @@
|
|||||||
var sha256hash = require('./sha256');
|
var sha256hash = require('./sha256');
|
||||||
var recallCryptoKey = require('./remember');
|
var recallCryptoKey = require('./remember');
|
||||||
var parseProps = require('./parse');
|
var parseProps = require('./parse');
|
||||||
// THIS WILL BE DEPRECATED IN FAVOR OF `Gun.SEA`!
|
|
||||||
// let's extend the gun chain with a `SEA` function.
|
|
||||||
// maps locally used methods to Gun and returns SEA object.
|
|
||||||
Gun.chain.SEA = function() {
|
|
||||||
const root = this.back(-1)
|
|
||||||
const sea = root._.SEA || (root._.SEA = root.chain()); // create a SEA context
|
|
||||||
Object.keys(SEA).map((method) => sea[method] = SEA[method])
|
|
||||||
return sea
|
|
||||||
}
|
|
||||||
// Practical examples about usage found from ./test/common.js
|
// Practical examples about usage found from ./test/common.js
|
||||||
const SEA = {
|
const SEA = {
|
||||||
// This is easy way to use IndexedDB, all methods are Promises
|
// This is easy way to use IndexedDB, all methods are Promises
|
||||||
@ -85,7 +81,7 @@
|
|||||||
},
|
},
|
||||||
async pair() {
|
async pair() {
|
||||||
try {
|
try {
|
||||||
const ecdhSubtle = subtleossl || subtle
|
const ecdhSubtle = wc.ossl || subtle
|
||||||
// First: ECDSA keys for signing/verifying...
|
// First: ECDSA keys for signing/verifying...
|
||||||
const { pub, priv } = await subtle.generateKey(ecdsaKeyProps, true, [ 'sign', 'verify' ])
|
const { pub, priv } = await subtle.generateKey(ecdsaKeyProps, true, [ 'sign', 'verify' ])
|
||||||
.then(async ({ publicKey, privateKey }) => {
|
.then(async ({ publicKey, privateKey }) => {
|
||||||
|
@ -1,11 +1,14 @@
|
|||||||
|
|
||||||
|
var wc = require('./webcrypto');
|
||||||
|
var subtle = wc.subtle;
|
||||||
|
var getRandomBytes = wc.random;
|
||||||
var Buffer = require('./buffer');
|
var Buffer = require('./buffer');
|
||||||
var parseProps = require('./parse');
|
var parseProps = require('./parse');
|
||||||
var settings = require('./settings');
|
var settings = require('./settings');
|
||||||
var pbKdf2 = settings.pbkdf2;
|
var pbKdf2 = settings.pbkdf2;
|
||||||
// This internal func returns SHA-256 hashed data for signing
|
// This internal func returns SHA-256 hashed data for signing
|
||||||
const sha256hash = async (mm) => {
|
const sha256hash = async (mm) => {
|
||||||
const hashSubtle = subtleossl || subtle
|
const hashSubtle = wc.ossl || subtle
|
||||||
const m = parseProps(mm)
|
const m = parseProps(mm)
|
||||||
const hash = await hashSubtle.digest(pbKdf2.hash, new TextEncoder().encode(m))
|
const hash = await hashSubtle.digest(pbKdf2.hash, new TextEncoder().encode(m))
|
||||||
return Buffer.from(hash)
|
return Buffer.from(hash)
|
||||||
|
49
sea/user.js
49
sea/user.js
@ -6,6 +6,7 @@
|
|||||||
var authRecall = require('./recall');
|
var authRecall = require('./recall');
|
||||||
var authenticate = require('./authenticate');
|
var authenticate = require('./authenticate');
|
||||||
var finalizeLogin = require('./login');
|
var finalizeLogin = require('./login');
|
||||||
|
var authLeave = require('./leave');
|
||||||
// let's extend the gun chain with a `user` function.
|
// let's extend the gun chain with a `user` function.
|
||||||
// only one user can be logged in at a time, per gun instance.
|
// only one user can be logged in at a time, per gun instance.
|
||||||
Gun.chain.user = function() {
|
Gun.chain.user = function() {
|
||||||
@ -26,7 +27,14 @@
|
|||||||
Object.assign(User, {
|
Object.assign(User, {
|
||||||
async create(username, pass, cb) {
|
async create(username, pass, cb) {
|
||||||
const root = this.back(-1)
|
const root = this.back(-1)
|
||||||
return new Promise((resolve, reject) => { // Because no Promises or async
|
var gun = this, cat = (gun._);
|
||||||
|
cb = cb || function(){};
|
||||||
|
if(cat.ing){
|
||||||
|
cb({err: Gun.log("User is already being created or authenticated!"), wait: true});
|
||||||
|
return gun;
|
||||||
|
}
|
||||||
|
cat.ing = true;
|
||||||
|
var p = new Promise((resolve, reject) => { // Because no Promises or async
|
||||||
// Because more than 1 user might have the same username, we treat the alias as a list of those users.
|
// Because more than 1 user might have the same username, we treat the alias as a list of those users.
|
||||||
if(cb){ resolve = reject = cb }
|
if(cb){ resolve = reject = cb }
|
||||||
root.get(`alias/${username}`).get(async (at, ev) => {
|
root.get(`alias/${username}`).get(async (at, ev) => {
|
||||||
@ -35,6 +43,8 @@
|
|||||||
// If we can enforce that a user name is already taken, it might be nice to try, but this is not guaranteed.
|
// 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!'
|
const err = 'User already created!'
|
||||||
Gun.log(err)
|
Gun.log(err)
|
||||||
|
cat.ing = false;
|
||||||
|
gun.leave();
|
||||||
return reject({ err })
|
return reject({ err })
|
||||||
}
|
}
|
||||||
const salt = Gun.text.random(64)
|
const salt = Gun.text.random(64)
|
||||||
@ -54,7 +64,7 @@
|
|||||||
// SEA.write(salt, pairs).then((signedsalt) =>
|
// SEA.write(salt, pairs).then((signedsalt) =>
|
||||||
SEA.write({ salt, auth }, pairs)
|
SEA.write({ salt, auth }, pairs)
|
||||||
// )
|
// )
|
||||||
).catch((e) => { Gun.log('SEA.en or SEA.write calls failed!'); reject(e) })
|
).catch((e) => { Gun.log('SEA.en or SEA.write calls failed!'); cat.ing = false; gun.leave(); reject(e) })
|
||||||
const user = { alias, pub, epub, auth }
|
const user = { alias, pub, epub, auth }
|
||||||
const tmp = `pub/${pairs.pub}`
|
const tmp = `pub/${pairs.pub}`
|
||||||
// awesome, now we can actually save the user with their public key as their ID.
|
// awesome, now we can actually save the user with their public key as their ID.
|
||||||
@ -62,25 +72,38 @@
|
|||||||
// next up, we want to associate the alias with the public key. So we add it to the alias list.
|
// next up, we want to associate the alias with the public key. So we add it to the alias list.
|
||||||
root.get(`alias/${username}`).put(Gun.obj.put({}, tmp, Gun.val.rel.ify(tmp)))
|
root.get(`alias/${username}`).put(Gun.obj.put({}, tmp, Gun.val.rel.ify(tmp)))
|
||||||
// callback that the user has been created. (Note: ok = 0 because we didn't wait for disk to ack)
|
// callback that the user has been created. (Note: ok = 0 because we didn't wait for disk to ack)
|
||||||
setTimeout(() => { resolve({ ok: 0, pub: pairs.pub}) }, 10) // TODO: BUG! If `.auth` happens synchronously after `create` finishes, auth won't work. This setTimeout is a temporary hack until we can properly fix it.
|
setTimeout(() => { cat.ing = false; resolve({ ok: 0, pub: pairs.pub}) }, 10) // TODO: BUG! If `.auth` happens synchronously after `create` finishes, auth won't work. This setTimeout is a temporary hack until we can properly fix it.
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
Gun.log('SEA.create failed!')
|
Gun.log('SEA.create failed!')
|
||||||
|
cat.ing = false;
|
||||||
|
gun.leave();
|
||||||
reject(e)
|
reject(e)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
return gun; // gun chain commands must return gun chains!
|
||||||
},
|
},
|
||||||
// now that we have created a user, we want to authenticate them!
|
// now that we have created a user, we want to authenticate them!
|
||||||
async auth(alias, pass, cb, opts) {
|
async auth(alias, pass, cb, opts) {
|
||||||
if(cb && !(cb instanceof Function)){ opts = cb }
|
if(cb && !(cb instanceof Function)){ opts = cb; cb = function(){} }
|
||||||
const { pin, newpass } = opts || {}
|
const { pin, newpass } = opts || {}
|
||||||
const root = this.back(-1)
|
const root = this.back(-1)
|
||||||
|
cb = cb || function(){};
|
||||||
|
|
||||||
|
var gun = this, cat = (gun._);
|
||||||
|
if(cat.ing){
|
||||||
|
cb({err: "User is already being created or authenticated!", wait: true});
|
||||||
|
return gun;
|
||||||
|
}
|
||||||
|
cat.ing = true;
|
||||||
|
|
||||||
if (!pass && pin) {
|
if (!pass && pin) {
|
||||||
try {
|
try {
|
||||||
return await authRecall(root, { alias, pin })
|
var r = await authRecall(root, { alias, pin })
|
||||||
|
return cat.ing = false, cb(r), gun;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
throw { err: 'Auth attempt failed! Reason: No session data for alias & PIN' }
|
var err = { err: 'Auth attempt failed! Reason: No session data for alias & PIN' }
|
||||||
|
return cat.ing = false, gun.leave(), cb(err), gun;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -88,8 +111,7 @@
|
|||||||
const { message, err = message || '' } = e
|
const { message, err = message || '' } = e
|
||||||
Gun.log(msg)
|
Gun.log(msg)
|
||||||
var error = { err: `${msg} Reason: ${err}` }
|
var error = { err: `${msg} Reason: ${err}` }
|
||||||
if(cb){ cb(error) }
|
return cat.ing = false, gun.leave(), cb(error), gun;
|
||||||
throw error;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@ -121,20 +143,19 @@
|
|||||||
// then we're done
|
// then we're done
|
||||||
var login = finalizeLogin(alias, keys, root, { pin })
|
var login = finalizeLogin(alias, keys, root, { pin })
|
||||||
login.catch(putErr('Failed to finalize login with new password!'))
|
login.catch(putErr('Failed to finalize login with new password!'))
|
||||||
if(cb){ cb(login) }
|
return cat.ing = false, cb(login), gun;
|
||||||
return login;
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
putErr('Password set attempt failed!')(e)
|
return putErr('Password set attempt failed!')(e)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
var login = finalizeLogin(alias, keys, root, { pin })
|
var login = finalizeLogin(alias, keys, root, { pin })
|
||||||
login.catch(putErr('Finalizing login failed!'))
|
login.catch(putErr('Finalizing login failed!'))
|
||||||
if(cb){ cb(login) }
|
return cat.ing = false, cb(login), gun;
|
||||||
return login;
|
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
putErr('Auth attempt failed!')(e)
|
return putErr('Auth attempt failed!')(e)
|
||||||
}
|
}
|
||||||
|
return gun;
|
||||||
},
|
},
|
||||||
async leave() {
|
async leave() {
|
||||||
return await authLeave(this.back(-1))
|
return await authLeave(this.back(-1))
|
||||||
|
25
sea/webcrypto.js
Normal file
25
sea/webcrypto.js
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
|
||||||
|
|
||||||
|
let subtle
|
||||||
|
let subtleossl
|
||||||
|
let getRandomBytes
|
||||||
|
let crypto
|
||||||
|
var Buffer = require('./buffer');
|
||||||
|
var wc;
|
||||||
|
var api = {};
|
||||||
|
|
||||||
|
if (typeof __webpack_require__ === 'function' || typeof window !== 'undefined') {
|
||||||
|
api.crypto = wc = window.crypto || window.msCrypto // STD or M$
|
||||||
|
api.subtle = subtle = wc.subtle || wc.webkitSubtle // STD or iSafari
|
||||||
|
api.random = getRandomBytes = (len) => Buffer.from(wc.getRandomValues(new Uint8Array(Buffer.alloc(len))))
|
||||||
|
} else {
|
||||||
|
api.crypto = crypto = require('crypto')
|
||||||
|
const WebCrypto = require('node-webcrypto-ossl')
|
||||||
|
const webcrypto = new WebCrypto({directory: 'key_storage'})
|
||||||
|
api.ossl = subtleossl = webcrypto.subtle
|
||||||
|
api.subtle = subtle = require('@trust/webcrypto').subtle // All but ECDH
|
||||||
|
api.random = getRandomBytes = (len) => Buffer.from(crypto.randomBytes(len))
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = api;
|
||||||
|
|
@ -24,7 +24,12 @@ var root;
|
|||||||
}
|
}
|
||||||
}(this));
|
}(this));
|
||||||
|
|
||||||
const SEA = Gun.SEA()
|
;(function(){
|
||||||
|
|
||||||
|
const SEA = Gun.SEA
|
||||||
|
|
||||||
|
if(!SEA){ return }
|
||||||
|
|
||||||
const { Buffer, EasyIndexedDB } = SEA
|
const { Buffer, EasyIndexedDB } = SEA
|
||||||
|
|
||||||
const seaIndexedDb = new SEA.EasyIndexedDB('SEA', 'GunDB', 1)
|
const seaIndexedDb = new SEA.EasyIndexedDB('SEA', 'GunDB', 1)
|
||||||
@ -1000,3 +1005,5 @@ Gun().user && describe('Gun', function(){
|
|||||||
Gun.log.off = false;
|
Gun.log.off = false;
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
}());
|
||||||
|
Loading…
x
Reference in New Issue
Block a user