123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665 |
- ;(function(){
- /* UNBUILD */
- var root;
- if(typeof window !== "undefined"){ root = window }
- if(typeof global !== "undefined"){ root = global }
- root = root || {};
- var console = root.console || {log: function(){}};
- function USE(arg, req){
- return req? require(arg) : arg.slice? USE[R(arg)] : function(mod, path){
- arg(mod = {exports: {}});
- USE[R(path)] = mod.exports;
- }
- function R(p){
- return p.split('/').slice(-1).toString().replace('.js','');
- }
- }
- if(typeof module !== "undefined"){ var common = module }
- /* UNBUILD */
- ;USE(function(module){
- // Security, Encryption, and Authorization: SEA.js
- // MANDATORY READING: https://gun.eco/explainers/data/security.html
- // IT IS IMPLEMENTED IN A POLYFILL/SHIM APPROACH.
- // THIS IS AN EARLY ALPHA!
- if(typeof window !== "undefined"){ module.window = window }
- var tmp = module.window || module;
- var SEA = tmp.SEA || function(){};
- if(SEA.window = module.window){ try{
- SEA.window.SEA = SEA;
- tmp = document.createEvent('CustomEvent');
- tmp.initCustomEvent('extension', false, false, {type: "SEA"});
- (window.dispatchEvent || window.fireEvent)(tmp);
- window.postMessage({type: "SEA"}, '*');
- } catch(e){} }
- try{ if(typeof common !== "undefined"){ common.exports = SEA } }catch(e){}
- module.exports = SEA;
- })(USE, './root');
- ;USE(function(module){
- var SEA = USE('./root');
- if(SEA.window){
- if(location.protocol.indexOf('s') < 0
- && location.host.indexOf('localhost') < 0
- && location.protocol.indexOf('file:') < 0){
- location.protocol = 'https:'; // WebCrypto does NOT work without HTTPS!
- }
- }
- })(USE, './https');
- ;USE(function(module){
- // This is Array extended to have .toString(['utf8'|'hex'|'base64'])
- function SeaArray() {}
- Object.assign(SeaArray, { from: Array.from })
- SeaArray.prototype = Object.create(Array.prototype)
- SeaArray.prototype.toString = function(enc, 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()]
- .map((i) => buf[ i + start ].toString(16).padStart(2, '0')).join('')
- }
- if (enc === 'utf8') {
- return Array.from(
- { length: (end || length) - start },
- (_, i) => String.fromCharCode(this[ i + start])
- ).join('')
- }
- if (enc === 'base64') {
- return btoa(this)
- }
- }
- module.exports = SeaArray;
- })(USE, './array');
- ;USE(function(module){
- // This is Buffer implementation used in SEA. Functionality is mostly
- // compatible with NodeJS 'safe-buffer' and is used for encoding conversions
- // between binary and 'hex' | 'utf8' | 'base64'
- // See documentation and validation for safe implementation in:
- // https://github.com/feross/safe-buffer#update
- var SeaArray = USE('./array');
- function SafeBuffer(...props) {
- console.warn('new SafeBuffer() is depreciated, please use SafeBuffer.from()')
- return SafeBuffer.from(...props)
- }
- SafeBuffer.prototype = Object.create(Array.prototype)
- Object.assign(SafeBuffer, {
- // (data, enc) where typeof data === 'string' then enc === 'utf8'|'hex'|'base64'
- from() {
- if (!Object.keys(arguments).length) {
- throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
- }
- const input = arguments[0]
- let buf
- if (typeof input === 'string') {
- const enc = arguments[1] || 'utf8'
- if (enc === 'hex') {
- const bytes = input.match(/([\da-fA-F]{2})/g)
- .map((byte) => parseInt(byte, 16))
- if (!bytes || !bytes.length) {
- throw new TypeError('Invalid first argument for type \'hex\'.')
- }
- buf = SeaArray.from(bytes)
- } else if (enc === 'utf8') {
- const length = input.length
- const words = new Uint16Array(length)
- 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.length
- const bytes = new Uint8Array(length)
- 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)
- }
- return buf
- }
- const byteLength = input.byteLength
- const length = input.byteLength ? input.byteLength : input.length
- if (length) {
- let buf
- if (input instanceof ArrayBuffer) {
- buf = new Uint8Array(input)
- }
- return SeaArray.from(buf || input)
- }
- },
- // This is 'safe-buffer.alloc' sans encoding support
- alloc(length, fill = 0 /*, enc*/ ) {
- return SeaArray.from(new Uint8Array(Array.from({ length: 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 : length })))
- },
- // This puts together array of array like members
- concat(arr) { // octet array
- if (!Array.isArray(arr)) {
- throw new TypeError('First argument must be Array containing ArrayBuffer or Uint8Array instances.')
- }
- return SeaArray.from(arr.reduce((ret, item) => ret.concat(Array.from(item)), []))
- }
- })
- SafeBuffer.prototype.from = SafeBuffer.from
- SafeBuffer.prototype.toString = SeaArray.prototype.toString
- module.exports = SafeBuffer;
- })(USE, './buffer');
- ;USE(function(module){
- const Buffer = USE('./buffer')
- const api = {Buffer: Buffer}
- if (typeof window !== 'undefined') {
- 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,
- TextEncoder,
- TextDecoder,
- random: (len) => Buffer.from(crypto.getRandomValues(new Uint8Array(Buffer.alloc(len))))
- })
- } else {
- try{
- var crypto = USE('crypto', 1);
- const { subtle } = USE('@trust/webcrypto', 1) // All but ECDH
- const { TextEncoder, TextDecoder } = USE('text-encoding', 1)
- Object.assign(api, {
- crypto,
- subtle,
- TextEncoder,
- TextDecoder,
- random: (len) => Buffer.from(crypto.randomBytes(len))
- });
- //try{
- const WebCrypto = USE('node-webcrypto-ossl', 1)
- api.ossl = new WebCrypto({directory: 'ossl'}).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!");
- console.log("node-webcrypto-ossl is temporarily needed for ECDSA signature verification, and optionally needed for ECDH, please install if needed (currently necessary so add them to your package.json for now).");
- TRUST_WEBCRYPTO_OR_TEXT_ENCODING_NOT_INSTALLED;
- }
- }
- module.exports = api
- })(USE, './shim');
- ;USE(function(module){
- const SEA = USE('./root');
- const Buffer = USE('./buffer')
- const settings = {}
- // Encryption parameters
- const pbkdf2 = { hash: 'SHA-256', iter: 100000, ks: 64 }
- const ecdsaSignProps = { name: 'ECDSA', hash: { name: 'SHA-256' } }
- const ecdsaKeyProps = { name: 'ECDSA', namedCurve: 'P-256' }
- const ecdhKeyProps = { name: 'ECDH', namedCurve: 'P-256' }
- const _initial_authsettings = {
- validity: 12 * 60 * 60, // internally in seconds : 12 hours
- hook: (props) => props // { iat, exp, alias, remember }
- // or return new Promise((resolve, reject) => resolve(props)
- }
- // These are used to persist user's authentication "session"
- const authsettings = Object.assign({}, _initial_authsettings)
- // This creates Web Cryptography API compliant JWK for sign/verify purposes
- const keysToEcdsaJwk = (pub, 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;
- }
- Object.assign(settings, {
- pbkdf2: pbkdf2,
- ecdsa: {
- pair: ecdsaKeyProps,
- sign: ecdsaSignProps
- },
- ecdh: ecdhKeyProps,
- jwk: keysToEcdsaJwk,
- recall: authsettings
- })
- SEA.opt = settings;
- module.exports = settings
- })(USE, './settings');
- ;USE(function(module){
- 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
- }
- })(USE, './parse');
- ;USE(function(module){
- const shim = USE('./shim');
- const Buffer = USE('./buffer')
- const parse = USE('./parse')
- const { pbkdf2 } = USE('./settings')
- // This internal func returns SHA-256 hashed data for signing
- const sha256hash = async (mm) => {
- const m = parse(mm)
- const hash = await shim.subtle.digest({name: pbkdf2.hash}, new shim.TextEncoder().encode(m))
- return Buffer.from(hash)
- }
- module.exports = sha256hash
- })(USE, './sha256');
- ;USE(function(module){
- // This internal func returns SHA-1 hashed data for KeyID generation
- const __shim = USE('./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
- })(USE, './sha1');
- ;USE(function(module){
- var SEA = USE('./root');
- var shim = USE('./shim');
- var S = USE('./settings');
- var sha = USE('./sha256');
- var u;
- SEA.work = SEA.work || (async (data, pair, cb, opt) => { try { // used to be named `proof`
- var salt = (pair||{}).epub || pair; // epub not recommended, salt should be random!
- var opt = opt || {};
- if(salt instanceof Function){
- cb = salt;
- salt = u;
- }
- salt = salt || shim.random(9);
- if('SHA-256' === opt.name){
- var rsha = shim.Buffer.from(await sha(data), 'binary').toString('utf8')
- if(cb){ try{ cb(rsha) }catch(e){console.log(e)} }
- return rsha;
- }
- const key = await (shim.ossl || shim.subtle).importKey(
- 'raw', new shim.TextEncoder().encode(data), { name: opt.name || 'PBKDF2' }, false, ['deriveBits']
- )
- const result = await (shim.ossl || shim.subtle).deriveBits({
- name: opt.name || 'PBKDF2',
- iterations: opt.iterations || S.pbkdf2.iter,
- salt: new shim.TextEncoder().encode(opt.salt || salt),
- hash: opt.hash || S.pbkdf2.hash,
- }, key, opt.length || (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){ try{ cb(r) }catch(e){console.log(e)} }
- return r;
- } catch(e) {
- SEA.err = e;
- if(cb){ cb() }
- return;
- }});
- module.exports = SEA.work;
- })(USE, './work');
- ;USE(function(module){
- var SEA = USE('./root');
- var shim = USE('./shim');
- var S = USE('./settings');
- var Buff = (typeof Buffer !== 'undefined')? Buffer : shim.Buffer;
- //SEA.pair = async (data, proof, cb) => { try {
- SEA.pair = SEA.pair || (async (cb) => { try {
- const ecdhSubtle = shim.ossl || shim.subtle
- // First: ECDSA keys for signing/verifying...
- 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 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
- 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 key;
- })
-
- // To include PGPv4 kind of keyId:
- // const pubId = await SEA.keyid(keys.pub)
- // Next: ECDH keys for encryption/decryption...
- try{
- var dh = await ecdhSubtle.generateKey(S.ecdh, true, ['deriveKey'])
- .then(async (keys) => {
- // privateKey scope doesn't leak out from here!
- 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
- 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 key;
- })
- }catch(e){
- if(SEA.window){ throw e }
- if(e == 'Error: ECDH is not a supported algorithm'){ console.log('Ignoring ECDH...') }
- else { throw e }
- } dh = dh || {};
- const r = { pub: sa.pub, priv: sa.priv, /* pubId, */ epub: dh.epub, epriv: dh.epriv }
- if(cb){ try{ cb(r) }catch(e){console.log(e)} }
- return r;
- } catch(e) {
- console.log(e);
- SEA.err = e;
- if(cb){ cb() }
- return;
- }});
- module.exports = SEA.pair;
- })(USE, './pair');
- ;USE(function(module){
- var SEA = USE('./root');
- var shim = USE('./shim');
- var S = USE('./settings');
- var sha256hash = USE('./sha256');
- SEA.sign = SEA.sign || (async (data, pair, cb) => { try {
- if(data && 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){ try{ cb(data) }catch(e){console.log(e)} }
- 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.ossl || shim.subtle).importKey('jwk', jwk, S.ecdsa.pair, false, ['sign'])
- .then((key) => (shim.ossl || 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){ try{ cb(r) }catch(e){console.log(e)} }
- return r;
- } catch(e) {
- console.log(e);
- SEA.err = e;
- if(cb){ cb() }
- return;
- }});
- module.exports = SEA.sign;
- })(USE, './sign');
- ;USE(function(module){
- var SEA = USE('./root');
- var shim = USE('./shim');
- var S = USE('./settings');
- var sha256hash = USE('./sha256');
- var parse = USE('./parse');
- var u;
- SEA.verify = SEA.verify || (async (data, pair, cb) => { try {
- const json = parse(data)
- if(false === pair){ // don't verify!
- const raw = (json !== data)?
- (json.s && json.m)? parse(json.m) : data
- : json;
- if(cb){ try{ cb(raw) }catch(e){console.log(e)} }
- return raw;
- }
- const pub = pair.pub || pair
- const jwk = S.jwk(pub)
- const key = await (shim.ossl || 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.ossl || 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){ try{ cb(r) }catch(e){console.log(e)} }
- return r;
- } catch(e) {
- console.log(e);
- SEA.err = e;
- if(cb){ cb() }
- return;
- }});
- module.exports = SEA.verify;
- })(USE, './verify');
- ;USE(function(module){
- var shim = USE('./shim');
- var sha256hash = USE('./sha256');
- const importGen = async (key, salt, opt) => {
- //const combo = shim.Buffer.concat([shim.Buffer.from(key, 'utf8'), salt || shim.random(8)]).toString('utf8') // old
- var opt = opt || {};
- 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), opt.name || 'AES-GCM', false, ['encrypt', 'decrypt'])
- }
- module.exports = importGen;
- })(USE, './aeskey');
- ;USE(function(module){
- var SEA = USE('./root');
- var shim = USE('./shim');
- var S = USE('./settings');
- var aeskey = USE('./aeskey');
- SEA.encrypt = SEA.encrypt || (async (data, pair, cb, opt) => { try {
- var opt = opt || {};
- const key = pair.epriv || pair;
- const msg = JSON.stringify(data)
- const rand = {s: shim.random(8), iv: shim.random(16)};
- const ct = await aeskey(key, rand.s, opt)
- .then((aes) => (/*shim.ossl ||*/ shim.subtle).encrypt({ // Keeping the AES key scope as private as possible...
- name: opt.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'),
- iv: rand.iv.toString('utf8'),
- s: rand.s.toString('utf8')
- });
- if(cb){ try{ cb(r) }catch(e){console.log(e)} }
- return r;
- } catch(e) {
- SEA.err = e;
- if(cb){ cb() }
- return;
- }});
- module.exports = SEA.encrypt;
- })(USE, './encrypt');
- ;USE(function(module){
- var SEA = USE('./root');
- var shim = USE('./shim');
- var S = USE('./settings');
- var aeskey = USE('./aeskey');
- var parse = USE('./parse');
- SEA.decrypt = SEA.decrypt || (async (data, pair, cb, opt) => { try {
- var opt = opt || {};
- const key = pair.epriv || pair;
- const json = parse(data)
- const ct = await aeskey(key, shim.Buffer.from(json.s, 'utf8'), opt)
- .then((aes) => (/*shim.ossl ||*/ shim.subtle).decrypt({ // Keeping aesKey scope as private as possible...
- name: opt.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))
- if(cb){ try{ cb(r) }catch(e){console.log(e)} }
- return r;
- } catch(e) {
- SEA.err = e;
- if(cb){ cb() }
- return;
- }});
- module.exports = SEA.decrypt;
- })(USE, './decrypt');
- ;USE(function(module){
- var SEA = USE('./root');
- var shim = USE('./shim');
- var S = USE('./settings');
- // Derive shared secret from other's pub and my epub/epriv
- SEA.secret = SEA.secret || (async (key, pair, cb) => { try {
- const pub = key.epub || key
- const epub = pair.epub
- const epriv = pair.epriv
- const ecdhSubtle = shim.ossl || shim.subtle
- const pubKeyData = keysToEcdhJwk(pub)
- 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-GCM', length: 256 }, true, [ 'encrypt', 'decrypt' ])
- return ecdhSubtle.exportKey('jwk', derivedKey).then(({ k }) => k)
- })
- const r = derived;
- if(cb){ try{ cb(r) }catch(e){console.log(e)} }
- return r;
- } catch(e) {
- SEA.err = e;
- if(cb){ cb() }
- return;
- }});
- 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: d } : {}
- return [ // Use with spread returned value...
- 'jwk',
- Object.assign(
- jwk,
- { x: x, y: y, kty: 'EC', crv: 'P-256', ext: true }
- ), // ??? refactor
- S.ecdh
- ]
- }
- module.exports = SEA.secret;
- })(USE, './secret');
- ;USE(function(module){
- // Old Code...
- const __gky10 = USE('./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 = USE('./indexed')
- const Buffer = USE('./buffer')
- var settings = USE('./settings');
- const __gky11 = USE('./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 = USE('./sha1')
- const sha256hash = USE('./sha256')
- const recallCryptoKey = USE('./remember')
- const parseProps = USE('./parse')
- // Practical examples about usage found from ./test/common.js
- const SEA = USE('./root');
- SEA.work = USE('./work');
- SEA.sign = USE('./sign');
- SEA.verify = USE('./verify');
- SEA.encrypt = USE('./encrypt');
- SEA.decrypt = USE('./decrypt');
- SEA.random = 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 = 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 = 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
- }
- });
- // all done!
- // Obviously it is missing MANY necessary features. This is only an alpha release.
- // Please experiment with it, audit what I've done so far, and complain about what needs to be added.
- // SEA should be a full suite that is easy and seamless to use.
- // Again, scroll naer the top, where I provide an EXAMPLE of how to create a user and sign in.
- // Once logged in, the rest of the code you just read handled automatically signing/validating data.
- // But all other behavior needs to be equally easy, like opinionated ways of
- // Adding friends (trusted public keys), sending private messages, etc.
- // Cheers! Tell me what you think.
- var Gun = (SEA.window||{}).Gun || USE('./gun', 1);
- Gun.SEA = SEA;
- SEA.Gun = Gun;
- module.exports = SEA
- })(USE, './sea');
- ;USE(function(module){
- var SEA = USE('./sea');
- var Gun = SEA.Gun;
- // 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).once((data, key) => {
- //rev.off();
- if (!data) {
- // if no user, don't do anything.
- const err = 'No user!'
- Gun.log(err)
- return reject({ err })
- }
- // then figuring out all possible candidates having matching username
- const aliases = []
- let c = 0
- // TODO: how about having real chainable map without callback ?
- Gun.obj.map(data, (at, pub) => {
- 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).once(data => {
- pub = pub.slice(1)
- --c
- if (data){
- aliases.push({ pub, put: data })
- }
- if (!c && (c = -1)) {
- resolve(aliases)
- }
- })
- })
- if (!c) {
- reject({ err: 'Public key does not exist!' })
- }
- })
- })
- module.exports = queryGunAliases
- })(USE, './query');
- ;USE(function(module){
- var SEA = USE('./sea');
- var Gun = SEA.Gun;
- const queryGunAliases = USE('./query')
- const parseProps = USE('./parse')
- // This is internal User authentication func.
- 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, gunRoot))
- .filter(a => !!a.pub && !!a.put)
- // Got any?
- if (!aliases.length) {
- throw { err: 'Public key does not exist!' }
- }
- let err
- // then attempt to log into each one until we find ours!
- // (if two users have the same username AND the same password... that would be bad)
- const users = await Promise.all(aliases.map(async (a, i) => {
- // attempt to PBKDF2 extend the password with the salt. (Verifying the signature gives us the plain text salt.)
- const auth = parseProps(a.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: 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.salt
- const sea = await SEA.decrypt(auth.ek, proof)
- if (!sea) {
- err = 'Failed to decrypt secret! ' + (i+1) +'/'+aliases.length;
- return
- }
- // now we have AES decrypted the private key, from when we encrypted it with the proof at registration.
- // if we were successful, then that meanswe're logged in!
- const priv = sea.priv
- const epriv = sea.epriv
- const epub = a.put.epub
- // TODO: 'salt' needed?
- err = null
- if(SEA.window){
- var tmp = SEA.window.sessionStorage;
- if(tmp && gunRoot._.opt.remember){
- SEA.window.sessionStorage.alias = alias;
- SEA.window.sessionStorage.tmp = pass;
- }
- }
- return {priv: priv, pub: a.put.pub, salt: salt, epub: epub, epriv: epriv };
- } catch (e) {
- err = 'Failed to decrypt secret!'
- throw { err }
- }
- }))
- var user = Gun.list.map(users, function(acc){ if(acc){ return acc } })
- if (!user) {
- throw { err: err || 'Public key does not exist!' }
- }
- return user
- }
- module.exports = authenticate;
- })(USE, './authenticate');
- ;USE(function(module){
- const authsettings = USE('./settings')
- const SEA = USE('./sea');
- const Gun = SEA.Gun;
- //const { scope: seaIndexedDb } = USE('./indexed')
- // This updates sessionStorage & IndexedDB to persist authenticated "session"
- const updateStorage = (proof, key, pin) => async (props) => {
- if (!Gun.obj.has(props, 'alias')) {
- return // No 'alias' - we're done.
- }
- if (authsettings.validity && proof && Gun.obj.has(props, 'iat')) {
- props.proof = proof
- delete props.remember // Not stored if present
- const alias = props.alias
- const id = props.alias
- const remember = { alias: alias, pin: pin }
- try {
- const signed = await SEA.sign(JSON.stringify(remember), key)
- sessionStorage.setItem('user', alias)
- sessionStorage.setItem('remember', signed)
- const encrypted = await SEA.encrypt(props, pin)
- 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: auth })
- }
- return props
- } catch (err) {
- throw { err: 'Session persisting failed!' }
- }
- }
- // Wiping IndexedDB completely when using random PIN
- 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
- })(USE, './update');
- ;USE(function(module){
- const SEA = USE('./sea');
- const Gun = SEA.Gun;
- const Buffer = USE('./buffer')
- const authsettings = USE('./settings')
- const updateStorage = USE('./update')
- // This internal func persists User authentication if so configured
- const authPersist = async (user, proof, opts) => {
- // opts = { pin: 'string' }
- // no opts.pin then uses random PIN
- // How this works:
- // called when app bootstraps, with wanted options
- // IF authsettings.validity === 0 THEN no remember-me, ever
- // IF PIN then signed 'remember' to window.sessionStorage and 'auth' to IndexedDB
- const pin = Buffer.from(
- (Gun.obj.has(opts, 'pin') && opts.pin) || Gun.text.random(10),
- 'utf8'
- ).toString('base64')
- 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: 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)
- }
- return await updateStorage(proof, key, pin)(props)
- }
- return await updateStorage()({ alias: 'delete' })
- }
- module.exports = authPersist
- })(USE, './persist');
- ;USE(function(module){
- const authPersist = USE('./persist')
- // This internal func finalizes User authentication
- const finalizeLogin = async (alias, key, gunRoot, opts) => {
- const user = gunRoot._.user
- // add our credentials in-memory only to our root gun instance
- var tmp = user._.tag;
- var opt = user._.opt;
- user._ = gunRoot.get('~'+key.pub)._;
- user._.opt = opt;
- var tags = user._.tag;
- /*Object.values && Object.values(tmp).forEach(function(tag){
- // TODO: This is ugly & buggy code, it needs to be refactored & tested into a event "merge" utility.
- var t = tags[tag.tag];
- console.log("hm??", tag, t);
- if(!t){
- tags[tag.tag] = tag;
- return;
- }
- if(tag.last){
- tag.last.to = t.to;
- t.last = tag.last = t.last || tag.last;
- }
- t.to = tag.to;
- })*/
- //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 = 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: 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
- // emit an auth event, useful for page redirects and stuff.
- try {
- gunRoot._.on('auth', user._) // TODO: Deprecate this, emit on user instead! Update docs when you do.
- //user._.on('auth', user._) // Arrgh, this doesn't work without event "merge" code, but "merge" code causes stack overflow and crashes after logging in & trying to write data.
- } catch (e) {
- console.log('Your \'auth\' callback crashed with:', e)
- }
- // returns success with the user data credentials.
- return user._
- }
- module.exports = finalizeLogin
- })(USE, './login');
- ;USE(function(module){
- const Buffer = USE('./buffer')
- const authsettings = USE('./settings')
- //const { scope: seaIndexedDb } = USE('./indexed')
- const queryGunAliases = USE('./query')
- const parseProps = USE('./parse')
- const updateStorage = USE('./update')
- const SEA = USE('./sea')
- const Gun = SEA.Gun;
- const finalizeLogin = USE('./login')
- // This internal func recalls persisted User authentication if so configured
- 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?
- const pin = pIn && Buffer.from(pIn, 'utf8').toString('base64')
- // Checks for existing proof, matching alias and expiration:
- const checkRememberData = async ({ proof, alias: aLias, iat, exp, remember }) => {
- if (!!proof && alias === aLias) {
- const checkNotExpired = (args) => {
- if (Math.floor(Date.now() / 1000) < (iat + args.exp)) {
- // No way hook to update 'iat'
- return Object.assign(args, { iat: iat, proof: proof })
- } else {
- Gun.log('Authentication expired!')
- }
- }
- // We're not gonna give proof to hook!
- const hooked = authsettings.hook({ alias: alias, iat: iat, exp: exp, remember: remember })
- return ((hooked instanceof Promise)
- && await hooked.then(checkNotExpired)) || checkNotExpired(hooked)
- }
- }
- const readAndDecrypt = async (data, pub, key) =>
- parseProps(await SEA.decrypt(await SEA.verify(data, pub), key))
- // Already authenticated?
- 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) {
- throw { err: 'No authentication session found!' }
- }
- // Yes, got persisted 'remember'?
- if (!remember) {
- throw { // And return proof if for matching alias
- err: (await seaIndexedDb.get(alias, 'auth') && authsettings.validity
- && 'Missing PIN and alias!') || 'No authentication session found!'
- }
- }
- // Yes, let's get (all?) matching aliases
- const aliases = (await queryGunAliases(alias, gunRoot))
- .filter(({ pub } = {}) => !!pub)
- // Got any?
- if (!aliases.length) {
- throw { err: 'Public key does not exist!' }
- }
- let err
- // Yes, then attempt to log into each one until we find ours!
- // (if two users have the same username AND the same password... that would be bad)
- const [ { key, at, proof, pin: newPin } = {} ] = await Promise
- .all(aliases.filter(({ at: { put } = {} }) => !!put)
- .map(async ({ at: at, pub: pub }) => {
- const readStorageData = async (args) => {
- const props = args || parseProps(await SEA.verify(remember, pub, true))
- 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
- ? await checkRememberData(props)
- // Got PIN so get IndexedDB secret if signature is ok
- : await checkRememberData(await readAndDecrypt(await seaIndexedDb.get(alias, 'auth'), pub, pin))
- pin = pin || data.pin
- delete data.pin
- return { pin: pin, data: data }
- }
- // got pub, try auth with pin & alias :: or unwrap Storage data...
- const __gky20 = await readStorageData(pin && { pin, alias })
- const data = __gky20.data
- const newPin = __gky20.pin
- const proof = data.proof
- if (!proof) {
- if (!data) {
- err = 'No valid authentication session found!'
- return
- }
- try { // Wipes IndexedDB silently
- await updateStorage()(data)
- } catch (e) {} //eslint-disable-line no-empty
- err = 'Expired session!'
- return
- }
- try { // auth parsing or decryption fails or returns empty - silently done
- const auth= at.put.auth.auth
- const sea = await SEA.decrypt(auth, proof)
- if (!sea) {
- err = 'Failed to decrypt private key!'
- return
- }
- const priv = sea.priv
- const epriv = sea.epriv
- const epub = at.put.epub
- // Success! we've found our private data!
- err = null
- 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
- }
- }).filter((props) => !!props))
- if (!key) {
- throw { err: err || 'Public key does not exist!' }
- }
- // now we have AES decrypted the private key,
- // if we were successful, then that means we're logged in!
- try {
- await updateStorage(proof, key, newPin || pin)(key)
- const user = Object.assign(key, { at: at, proof: proof })
- const pIN = newPin || pin
- const pinProp = pIN && { pin: Buffer.from(pIN, 'base64').toString('utf8') }
- 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
- })(USE, './recall');
- ;USE(function(module){
- const authPersist = USE('./persist')
- const authsettings = USE('./settings')
- //const { scope: seaIndexedDb } = USE('./indexed')
- // This internal func executes logout actions
- 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.$){
- delete user.$.is;
- }
- // Let's use default
- gunRoot.user();
- // Removes persisted authentication & CryptoKeys
- try {
- await authPersist({ alias: alias })
- } catch (e) {} //eslint-disable-line no-empty
- return { ok: 0 }
- }
- module.exports = authLeave
- })(USE, './leave');
- ;USE(function(module){
- var Gun = USE('./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;
- }
- })(USE, './then');
- ;USE(function(module){
- var SEA = USE('./sea');
- var Gun = SEA.Gun;
- var then = USE('./then');
- function User(root){
- this._ = {$: this};
- }
- 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(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 user;
- }
- Gun.User = User;
- module.exports = User;
- })(USE, './user');
- ;USE(function(module){
- // TODO: This needs to be split into all separate functions.
- // Not just everything thrown into 'create'.
- const SEA = USE('./sea')
- const User = USE('./user')
- const authRecall = USE('./recall')
- const authsettings = USE('./settings')
- const authenticate = USE('./authenticate')
- const finalizeLogin = USE('./login')
- const authLeave = USE('./leave')
- const _initial_authsettings = USE('./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, opt){
- // 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;
- opt = opt || {};
- 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 && !opt.already) {
- // 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.link.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(){
- var gun = this, user = (gun.back(-1)._).user;
- if(user){
- delete user.is;
- delete user._.is;
- delete user._.sea;
- }
- if(typeof window !== 'undefined'){
- var tmp = window.sessionStorage;
- delete tmp.alias;
- delete tmp.tmp;
- }
- 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 = function(setvalidity, options){
- var gun = this;
- 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 gun;
- }
- 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?
- (async function(){ await authRecall(gunRoot) }());
- return gun;
- } 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 }
- return gun;
- }
- }
- 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
- })(USE, './create');
- ;USE(function(module){
- const SEA = USE('./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: {}};
- at.on('in', security, at); // now listen to all input data, acting as a firewall.
- at.on('out', signature, at); // and output listeners, to encrypt outgoing data.
- at.on('node', each, at);
- }
- this.to.next(at); // make sure to call the "next" middleware adapter.
- });
- // Alright, this next adapter gets run at the per node level in the graph database.
- // This will let us verify that every property on a node has a value signed by a public key we trust.
- // If the signature does not match, the data is just `undefined` so it doesn't get passed on.
- // If it does match, then we transform the in-memory "view" of the data into its plain value (without the signature).
- // Now NOTE! Some data is "system" data, not user data. Example: List of public keys, aliases, etc.
- // This data is self-enforced (the value can only match its ID), but that is handled in the `security` function.
- // From the self-enforced data, we can see all the edges in the graph that belong to a public key.
- // Example: ~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!
- // This means we should ONLY trust our "friends" (our key ring) public keys, not any ones.
- // I have not yet added that to SEA yet in this alpha release. That is coming soon, but beware in the meanwhile!
- function each(msg){ // TODO: Warning: Need to switch to `gun.on('node')`! Do not use `Gun.on('node'` in your apps!
- // NOTE: THE SECURITY FUNCTION HAS ALREADY VERIFIED THE DATA!!!
- // WE DO NOT NEED TO RE-VERIFY AGAIN, JUST TRANSFORM IT TO PLAINTEXT.
- var to = this.to, vertex = (msg.$._).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, function(data){ c--; // false just extracts the plain data.
- node[key] = val = data; // transform to plain value.
- if(d && !c && (c = -1)){ to.next(msg) }
- });
- });
- d = true;
- if(d && !c){ to.next(msg) }
- return;
- }
- // signature handles data output, it is a proxy to the security function.
- function signature(msg){
- if(msg.user){
- return this.to.next(msg);
- }
- var ctx = this.as;
- msg.user = ctx.user;
- security.call(this, msg);
- }
- // okay! The security function handles all the heavy lifting.
- // It needs to deal read and write of input and output of system data, account/public key data, and regular data.
- // This is broken down into some pretty clear edge cases, let's go over them:
- function security(msg){
- var at = this.as, sea = at.sea, to = this.to;
- if(msg.get){
- // if there is a request to read data from us, then...
- var soul = msg.get['#'];
- if(soul){ // for now, only allow direct IDs to be read.
- if(soul !== 'string'){ return to.next(msg) } // do not handle lexical cursors.
- if('alias' === soul){ // Allow reading the list of usernames/aliases in the system?
- return to.next(msg); // yes.
- } else
- 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.
- }
- }
- }
- if(msg.put){
- // potentially parallel async operations!!!
- 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});
- };
- each.way = function(val, key){
- var soul = this.soul, node = this.node, tmp;
- if('_' === key){ return } // ignore meta data
- if('~@' === soul){ // special case for shared system data, the list of aliases.
- each.alias(val, key, node, soul); return;
- }
- 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('~' === 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: {_:#~@, ~@alice: {#~@alice}}
- if(!val){ return each.end({err: "Data must exist!"}) } // data MUST exist
- if('~@'+key === Gun.val.link.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: {_:#~@alice, ~asdf: {#~asdf}}
- if(!val){ return each.end({err: "Alias must exist!"}) } // data MUST exist
- if(key === Gun.val.link.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: {_:#~asdf, hello:SEA{'world',fdsa}}
- if('pub' === key){
- if(val === pub){ return (check['pub'+soul+key] = 0) } // the account MUST match `pub` property that equals the ID of the public key.
- return each.end({err: "Account must match!"});
- }
- check['user'+soul+key] = 1;
- if(user && (user = user._) && user.sea && pub === user.pub){
- //var id = Gun.text.random(3);
- SEA.sign(val, user.sea, function(data){ var rel;
- if(u === data){ return each.end({err: SEA.err || 'Pub signature fail.'}) }
- if(rel = Gun.val.link.is(val)){
- (at.sea.own[rel] = at.sea.own[rel] || {})[pub] = true;
- }
- node[key] = data;
- check['user'+soul+key] = 0;
- each.end({ok: 1});
- });
- // TODO: Handle error!!!!
- return;
- }
- 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.link.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 = relpub(soul)){
- check['any'+soul+key] = 1;
- SEA.verify(val, pub = tmp, function(data){ var rel;
- if(u === data){ return each.end({err: "Mismatched owner on '" + key + "'."}) } // thanks @rogowski !
- if((rel = Gun.val.link.is(data)) && pub === relpub(rel)){
- (at.sea.own[rel] = at.sea.own[rel] || {})[pub] = true;
- }
- check['any'+soul+key] = 0;
- each.end({ok: 1});
- });
- return;
- }
- 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 = 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;
- 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;
- 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});
- });
- }
- each.end = function(ctx){ // TODO: Can't you just switch this to each.end = cb?
- if(each.err){ return }
- if((each.err = ctx.err) || ctx.no){
- console.log('NO!', each.err, msg.put);
- return;
- }
- if(!each.end.ed){ return }
- if(Gun.obj.map(check, function(no){
- if(no){ return true }
- })){ return }
- to.next(msg);
- };
- Gun.obj.map(msg.put, each.node);
- each.end({end: each.end.ed = true});
- return; // need to manually call next after async.
- }
- to.next(msg); // pass forward any data we do not know how to handle or process (this allows custom security protocols).
- }
- })(USE, './index');
- }());
|