12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643 |
- ;(function(){
-
- 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){
- return 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 }
-
- ;USE(function(module){
-
-
-
- function SEA(){}
- if(typeof window !== "undefined"){ (SEA.window = window).SEA = SEA }
- 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:';
- }
- }
- })(USE, './https');
- ;USE(function(module){
-
- 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){
-
-
-
-
-
- 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, {
-
- 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)
- }
- },
-
- alloc(length, fill = 0 ) {
- return SeaArray.from(new Uint8Array(Array.from({ length: length }, () => fill)))
- },
-
- allocUnsafe(length) {
- return SeaArray.from(new Uint8Array(Array.from({ length : length })))
- },
-
- concat(arr) {
- 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 __webpack_require__ === 'function' || 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 = require('crypto');
- const { subtle } = require('@trust/webcrypto')
- const { TextEncoder, TextDecoder } = require('text-encoding')
- Object.assign(api, {
- crypto,
- subtle,
- TextEncoder,
- TextDecoder,
- random: (len) => Buffer.from(crypto.randomBytes(len))
- });
-
- const WebCrypto = require('node-webcrypto-ossl')
- api.ossl = new WebCrypto({directory: 'ossl'}).subtle
-
-
-
- }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 Buffer = USE('./buffer')
- const settings = {}
-
- 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,
- hook: (props) => props
-
- }
-
- const authsettings = Object.assign({}, _initial_authsettings)
-
- const keysToEcdsaJwk = (pub, d) => {
-
- const [ x, y ] = pub.split('.')
- 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
- })
- 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) {}
- return props
- }
- })(USE, './parse');
- ;USE(function(module){
- const shim = USE('./shim');
- const Buffer = USE('./buffer')
- const parse = USE('./parse')
- const { pbkdf2 } = USE('./settings')
-
- 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){
-
- 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 u;
- SEA.work = async (data, pair, cb) => { try {
- var salt = pair.epub || pair;
- if(salt instanceof Function){
- cb = salt;
- salt = u;
- }
- salt = salt || shim.random(9);
- if (SEA.window) {
-
- const key = await shim.subtle.importKey(
- 'raw', new shim.TextEncoder().encode(data), { name: 'PBKDF2' }, false, ['deriveBits']
- )
- const result = await shim.subtle.deriveBits({
- name: 'PBKDF2',
- iterations: S.pbkdf2.iter,
- salt: new shim.TextEncoder().encode(salt),
- hash: S.pbkdf2.hash,
- }, key, S.pbkdf2.ks * 8)
- data = shim.random(data.length)
- const r = shim.Buffer.from(result, 'binary').toString('utf8')
- if(cb){ try{ cb(r) }catch(e){console.log(e)} }
- return r;
- }
-
- const crypto = shim.crypto;
- const hash = crypto.pbkdf2Sync(
- data,
- new shim.TextEncoder().encode(salt),
- S.pbkdf2.iter,
- S.pbkdf2.ks,
- S.pbkdf2.hash.replace('-', '').toLowerCase()
- )
- data = shim.random(data.length)
- const r = hash && hash.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 (cb) => { try {
- const ecdhSubtle = shim.ossl || shim.subtle
-
- var sa = await shim.subtle.generateKey(S.ecdsa.pair, true, [ 'sign', 'verify' ])
- .then(async (keys) => {
-
-
- const key = {};
- key.priv = (await shim.subtle.exportKey('jwk', keys.privateKey)).d;
- const pub = await shim.subtle.exportKey('jwk', keys.publicKey)
-
- key.pub = pub.x+'.'+pub.y
-
-
-
- return key;
- })
-
-
-
-
- try{
- var dh = await ecdhSubtle.generateKey(S.ecdh, true, ['deriveKey'])
- .then(async (keys) => {
-
- const key = {};
- key.epriv = (await ecdhSubtle.exportKey('jwk', keys.privateKey)).d;
- const pub = await ecdhSubtle.exportKey('jwk', keys.publicKey)
-
- key.epub = pub.x+'.'+pub.y
-
-
-
- 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, 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 = async (data, pair, cb) => { try {
- if(data && data.slice
- && 'SEA{' === data.slice(0,4)
- && '"m":' === data.slice(4,8)){
-
-
-
- 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)))
- 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 = async (data, pair, cb) => { try {
- const json = parse(data)
- if(false === pair){
- 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) => {
-
- var opt = opt || {};
- const combo = key + (salt || shim.random(8)).toString('utf8');
- 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 = 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.subtle.encrypt({
- 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 = 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.subtle.decrypt({
- 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');
-
- 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) => {
-
- 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) => {
-
- const [ x, y ] = pub.split('.')
- const jwk = d ? { d: d } : {}
- return [
- 'jwk',
- Object.assign(
- jwk,
- { x: x, y: y, kty: 'EC', crv: 'P-256', ext: true }
- ),
- S.ecdh
- ]
- }
- module.exports = SEA.secret;
- })(USE, './secret');
- ;USE(function(module){
-
- 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')
-
- 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 = getRandomBytes;
-
-
- SEA.EasyIndexedDB = EasyIndexedDB;
-
-
- SEA.Buffer = Buffer;
-
-
-
-
-
-
- SEA.keyid = async (pub) => {
- try {
-
- const pb = Buffer.concat(
- Buffer.from(pub, 'base64').toString('utf8').split(':')
- .map((t) => Buffer.from(t, 'base64'))
- )
-
- 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)
- } catch (e) {
- console.log(e)
- throw e
- }
- }
-
-
-
-
-
-
-
-
-
- var Gun = (SEA.window||{}).Gun || require('./gun');
- Gun.SEA = SEA;
- SEA.Gun = Gun;
- module.exports = SEA
- })(USE, './sea');
- ;USE(function(module){
- var SEA = USE('./sea');
- var Gun = SEA.Gun;
-
- const queryGunAliases = (alias, gunRoot) => new Promise((resolve, reject) => {
-
- gunRoot.get('~@'+alias).get((rat, rev) => {
- rev.off();
- if (!rat.put) {
-
- const err = 'No user!'
- Gun.log(err)
- return reject({ err })
- }
-
- const aliases = []
- let c = 0
-
- Gun.obj.map(rat.put, (at, pub) => {
- if (!pub.slice || '~' !== pub.slice(0, 1)) {
-
- return
- }
- ++c
-
- gunRoot.get(pub).get((at, ev) => {
- pub = pub.slice(1)
- ev.off()
- --c
- if (at.put){
- aliases.push({ pub, at })
- }
- 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')
-
- const authenticate = async (alias, pass, gunRoot) => {
-
- const aliases = (await queryGunAliases(alias, gunRoot))
- .filter(({ pub, at: { put } = {} } = {}) => !!pub && !!put)
-
- if (!aliases.length) {
- throw { err: 'Public key does not exist!' }
- }
- let err
-
-
- const users = await Promise.all(aliases.map(async ({ at: at, pub: pub }, i) => {
-
- const auth = parseProps(at.put.auth)
-
-
- try {
- const proof = await SEA.work(pass, auth.s)
- const props = { pub: pub, proof: proof, at: at }
-
-
- const salt = auth.salt
- const sea = await SEA.decrypt(auth.ek, proof)
- if (!sea) {
- err = 'Failed to decrypt secret! ' + i +'/'+aliases.length;
- return
- }
-
-
- const priv = sea.priv
- const epriv = sea.epriv
- const epub = at.put.epub
-
- err = null
- if(typeof window !== 'undefined'){
- var tmp = window.sessionStorage;
- if(tmp && gunRoot._.opt.remember){
- window.sessionStorage.alias = alias;
- window.sessionStorage.tmp = pass;
- }
- }
- return Object.assign(props, { priv: priv, 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 updateStorage = (proof, key, pin) => async (props) => {
- if (!Gun.obj.has(props, 'alias')) {
- return
- }
- if (authsettings.validity && proof && Gun.obj.has(props, 'iat')) {
- props.proof = proof
- delete props.remember
- 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()
- await seaIndexedDb.put(id, { auth: auth })
- }
- return props
- } catch (err) {
- throw { err: 'Session persisting failed!' }
- }
- }
-
- await seaIndexedDb.wipe()
-
- 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')
-
- const authPersist = async (user, proof, opts) => {
-
-
-
-
-
-
- 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
- if (proof && alias && exp) {
- const iat = Math.ceil(Date.now() / 1000)
- const remember = Gun.obj.has(opts, 'pin') || undefined
- 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')
-
- const finalizeLogin = async (alias, key, gunRoot, opts) => {
- const user = gunRoot._.user
-
-
- var opt = user._.opt;
- user._ = key.at.$._;
- user._.opt = opt;
-
-
-
- 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 } })
-
-
-
-
- try {
- gunRoot._.on('auth', user._)
- } catch (e) {
- console.log('Your \'auth\' callback crashed with:', e)
- }
-
- return user._
- }
- module.exports = finalizeLogin
- })(USE, './login');
- ;USE(function(module){
- const Buffer = USE('./buffer')
- const authsettings = USE('./settings')
-
- const queryGunAliases = USE('./query')
- const parseProps = USE('./parse')
- const updateStorage = USE('./update')
- const SEA = USE('./sea')
- const Gun = SEA.Gun;
- const finalizeLogin = USE('./login')
-
- const authRecall = async (gunRoot, authprops) => {
-
- const remember = authprops || sessionStorage.getItem('remember')
- const { alias = sessionStorage.getItem('user'), pin: pIn } = authprops || {}
- const pin = pIn && Buffer.from(pIn, 'utf8').toString('base64')
-
- 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)) {
-
- return Object.assign(args, { iat: iat, proof: proof })
- } else {
- Gun.log('Authentication expired!')
- }
- }
-
- 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))
-
- if (gunRoot._.user
- && Gun.obj.has(gunRoot._.user._, 'pub')
- && Gun.obj.has(gunRoot._.user._, 'sea')) {
- return gunRoot._.user._
- }
-
- if (!alias) {
- throw { err: 'No authentication session found!' }
- }
-
- if (!remember) {
- throw {
- err: (await seaIndexedDb.get(alias, 'auth') && authsettings.validity
- && 'Missing PIN and alias!') || 'No authentication session found!'
- }
- }
-
- const aliases = (await queryGunAliases(alias, gunRoot))
- .filter(({ pub } = {}) => !!pub)
-
- if (!aliases.length) {
- throw { err: 'Public key does not exist!' }
- }
- let err
-
-
- 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)
-
- ? await checkRememberData(props)
-
- : await checkRememberData(await readAndDecrypt(await seaIndexedDb.get(alias, 'auth'), pub, pin))
- pin = pin || data.pin
- delete data.pin
- return { pin: pin, data: 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 {
- await updateStorage()(data)
- } catch (e) {}
- err = 'Expired session!'
- return
- }
- try {
- 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
-
- 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!' }
- }
-
-
- 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) {
- 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 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;
- }
-
- gunRoot.user();
-
- try {
- await authPersist({ alias: alias })
- } catch (e) {}
- 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() }())
- User.prototype.constructor = User;
-
-
- 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){
-
-
- 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;
-
- User.prototype.create = function(username, pass, cb, opt){
-
- 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;
-
- if(cb){ resolve = reject = cb }
- gunRoot.get('~@'+username).get(async (at, ev) => {
- ev.off()
- if (at.put && !opt.already) {
-
- const err = 'User already created!'
- Gun.log(err)
- cat.ing = false;
- gun.leave();
- return reject({ err: err })
- }
- const salt = Gun.text.random(64)
-
- try {
- const proof = await SEA.work(pass, salt)
-
- const pairs = await SEA.pair()
-
- const pub = pairs.pub
- const priv = pairs.priv
- const epriv = pairs.epriv
-
- 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 }
-
- const auth = await SEA.encrypt({ priv: priv, epriv: epriv }, proof)
- .then((auth) =>
-
- 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;
-
- try{
- gunRoot.get(tmp).put(user)
- }catch(e){console.log(e)}
-
- gunRoot.get('~@'+username).put(Gun.obj.put({}, tmp, Gun.val.link.ify(tmp)))
-
- setTimeout(() => { cat.ing = false; resolve({ ok: 0, pub: pairs.pub}) }, 10)
- } catch (e) {
- Gun.log('SEA.create failed!')
- cat.ing = false;
- gun.leave();
- reject(e)
- }
- })
- return gun;
- }
-
- User.prototype.auth = function(alias, pass, cb, opt){
-
- 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
-
- if (newpass) {
-
- 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
- }
-
- gunRoot.get('~'+user.pub).put(user)
-
- 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))
- }
-
- 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)
-
- gunRoot.get('~'+pub).put(null)
-
- const { user = { _: {} } } = gunRoot._;
-
- [ 'alias', 'sea', 'pub' ].map((key) => delete user._[key])
- user._.is = user.is = {}
- gunRoot.user()
- return { ok: 0 }
- } catch (e) {
- Gun.log('User.delete failed! Error:', e)
- throw e
- }
- }
-
-
- 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
- }
- try {
-
-
-
-
-
-
- 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
-
- return await authRecall(gunRoot)
- } catch (e) {
- const err = 'No session!'
- Gun.log(err)
-
-
- return { err: (e && e.err) || err }
- }
- }
- User.prototype.alive = async function(){
- const gunRoot = this.back(-1)
- try {
-
- await authRecall(gunRoot)
- return gunRoot._.user._
- } catch (e) {
- const err = 'No session!'
- Gun.log(err)
- throw { err }
- }
- }
- User.prototype.trust = async function(user){
-
-
- 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;
-
-
- Gun.on('opt', function(at){
- if(!at.sea){
- at.sea = {own: {}};
- at.on('in', security, at);
- at.on('out', signature, at);
- at.on('node', each, at);
- }
- this.to.next(at);
- });
-
-
-
-
-
-
-
-
-
-
-
-
-
- function each(msg){
-
-
- var to = this.to, vertex = (msg.$._).put, c = 0, d;
- Gun.node.is(msg.put, function(val, key, node){ c++;
-
- SEA.verify(val, false, function(data){ c--;
- node[key] = val = data;
- if(d && !c && (c = -1)){ to.next(msg) }
- });
- });
- d = true;
- if(d && !c){ to.next(msg) }
- return;
- }
-
- function signature(msg){
- if(msg.user){
- return this.to.next(msg);
- }
- var ctx = this.as;
- msg.user = ctx.user;
- security.call(this, msg);
- }
-
-
-
- function security(msg){
- var at = this.as, sea = at.sea, to = this.to;
- if(msg.get){
-
- var soul = msg.get['#'];
- if(soul){
- if(soul !== 'string'){ return to.next(msg) }
- if('alias' === soul){
- return to.next(msg);
- } else
- if('~@' === soul.slice(0,2)){
- return to.next(msg);
- } else {
- return to.next(msg);
- }
- }
- }
- if(msg.put){
-
- var check = {}, each = {}, u;
- each.node = function(node, soul){
- if(Gun.obj.empty(node, '_')){ return check['node'+soul] = 0 }
- 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 }
- if('~@' === soul){
- each.alias(val, key, node, soul); return;
- }
- if('~@' === soul.slice(0,2)){
- each.pubs(val, key, node, soul); return;
- }
- if('~' === soul.slice(0,1) && 2 === (tmp = soul.slice(1)).split('.').length){
- 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){
- if(!val){ return each.end({err: "Data must exist!"}) }
- if('~@'+key === Gun.val.link.is(val)){ return check['alias'+key] = 0 }
- each.end({err: "Mismatching alias."});
- };
- each.pubs = function(val, key, node, soul){
- if(!val){ return each.end({err: "Alias must exist!"}) }
- if(key === Gun.val.link.is(val)){ return check['pubs'+soul+key] = 0 }
- each.end({err: "Alias must match!"});
- };
- each.pub = function(val, key, node, soul, pub, user){
- if('pub' === key){
- if(val === pub){ return (check['pub'+soul+key] = 0) }
- return each.end({err: "Account must match!"});
- }
- check['user'+soul+key] = 1;
- if(user && (user = user._) && user.sea && pub === user.pub){
-
- 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});
- });
-
- return;
- }
- SEA.verify(val, pub, function(data){ var rel, tmp;
- if(u === data){
- return each.end({err: "Unverified data."});
- }
- 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(!data){ return each.end({err: "Mismatched owner on '" + key + "'."}) }
- 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);
-
- 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] = 0;
- each.end({ok: 1});
-
- return;
- }
- var pub = tmp;
- if(pub !== user.pub){
- 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){
- 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;
- }
- to.next(msg);
- }
- })(USE, './index');
- }());
|