Nikolay Suslov 4 år sedan
förälder
incheckning
8a2cab892a

+ 1 - 0
public/lib/gundb/axe.js

@@ -217,6 +217,7 @@
 					}
 					// TODO: PUTs need to only go to subs!
 					if(msg.put){
+						mesh.say(msg, axe.up); // always send gets up! Hope that mesh.say below dedups via DAM's check.
 						var S = (+new Date); // STATS!
 						var routes = axe.routes || (axe.routes = {}); // USE RAD INSTEAD! TMP TESTING!
 						var peers = {};

+ 1 - 1
public/lib/gundb/gun.js

@@ -1636,7 +1636,7 @@
 		}
 		var G = String.fromCharCode(31);
 		function soul(id, as, msg, eve){
-			var as = as.as, path = as.p, ref = as.ref, cat = as.at, pat = []; as = as.as;
+			var as = as.as, path = as.p, ref = as.ref, cat = as.at, pat = [], sat; as = as.as;
 			ref.back(function(at){
 				if(sat = at.soul || at.link || at.dub){ return sat }
 				pat.push(at.has || at.get);

+ 41 - 0
public/lib/gundb/lib/ras.js

@@ -0,0 +1,41 @@
+(function(){
+
+  /**
+  Radix AsyncStorage adapter
+  make sure to pass AsyncStorage instance in opt.AsyncStorage
+  example:
+  import AsyncStorage from 'react-native'
+  const store = Store({AsyncStorage})
+  const gun = new Gun({store,peers:[...]})
+  **/
+  function Store(opt){
+    opt = opt || {};
+    const store = function(){}
+    const as = opt.AsyncStorage;
+    store.put = function(key, data, cb)
+      { 
+        as.setItem(''+key,data)
+          .then(_ => cb(null,1))
+          .then(_ => console.log("ok put"))
+          .catch(_ => {
+            console.error(`failed saving to asyncstorage`,{key, data})
+            cb(null,0)
+          })
+      }
+
+    store.get = (key,cb) => {
+        as.getItem(''+key)
+          .then(data => cb(null,data))
+          .then(_ => console.log("ok get"))
+          .catch(_ => {
+            console.error(`failed fetching from asyncstorage`,{key})
+            cb(null,0)
+          })
+      }
+    
+    return store;
+  }
+
+  module.exports = Store
+
+}());

+ 8 - 0
public/lib/gundb/lib/rfs.js

@@ -73,4 +73,12 @@ function Store(opt){
 	return store;
 }
 
+var Gun = (typeof window !== "undefined")? window.Gun : require('../gun');
+Gun.on('create', function(root){
+	this.to.next(root);
+	var opt = root.opt;
+	if(opt.rfs === false){ return }
+	opt.store = opt.store || (!Gun.window && Store(opt));
+});
+
 module.exports = Store;

+ 1 - 0
public/lib/gundb/lib/server.js

@@ -11,6 +11,7 @@
 	})
 	require('../nts');
 	require('./store');
+	require('./rfs');
 	require('./rs3');
 	require('./wire');
 	try{require('../sea');}catch(e){}

+ 1 - 3
public/lib/gundb/lib/store.js

@@ -7,10 +7,8 @@ Gun.on('create', function(root){
     if(false === opt.radisk){ return }
     var Radisk = (Gun.window && Gun.window.Radisk) || require('./radisk');
     var Radix = Radisk.Radix;
-    var ST = 0;
-    // TODO: BUG! For RN storage, RN does not like the following require:
-    opt.store = opt.store || (!Gun.window && require('./rfs')(opt));
     var dare = Radisk(opt), esc = String.fromCharCode(27);
+    var ST = 0;
  
     root.on('put', function(msg){
         this.to.next(msg);

+ 10 - 4
public/lib/gundb/lib/upload.js

@@ -1,11 +1,15 @@
 ;(function(){
 	function upload(cb, opt){
-		var el = $(this); cb = cb || function(){}; opt = opt || {};
+		var el = $(this); cb = cb || function(){};
+		opt = $.isPlainObject(opt)? opt : {input: opt}; 
 		el.on('drop', function(e){
 			e.preventDefault();
-			upload.drop(((e.originalEvent||{}).dataTransfer||{}).files, 0);
+			upload.drop(((e.originalEvent||{}).dataTransfer||{}).files||[], 0);
 		}).on('dragover', function(e){
-		    e.preventDefault();
+			e.preventDefault();
+		});
+		$(opt.input||el).on('change', function(e){
+			upload.drop((e.target||this||{}).files, 0);
 		});
 		upload.drop = function(files,i){
 			if(opt.max && (files[i].fileSize > opt.max || files[i].size > opt.max)){
@@ -20,11 +24,13 @@
 			};
 			if(files[i]){ reader.readAsDataURL(files[i]) }
 		}
+		return this;
 	}
 	upload.shrink = function(e, cb, w, h){ // via stackoverflow
 		if(!e){ return cb && cb({err: "No file!"}) }
 		if(e.err){ return }
 		var file = (((e.event || e).target || e).result || e), img = new Image();
+		if(!((file||'').split(';')[0].indexOf('image') + 1)){ e.err = "Not an image!"; return cb(e) }
     img.crossOrigin = "Anonymous";
     img.src = file;
     img.onload = function(){
@@ -37,7 +43,7 @@
 	    canvas.width = w;
 	    canvas.height = h;
 	    ctx.drawImage(img, 0, 0, w, h); // draw source image to canvas.
-	    var b64 = e.base64 = canvas.toDataURL(); // base64 the compressed image.
+	    var b64 = e.base64 = canvas.toDataURL(); // base64 the shrunk image.
 	    cb((e.base64 && e) || b64); 
     };
 	}

+ 1 - 2
public/lib/gundb/lib/wire.js

@@ -64,7 +64,7 @@ Gun.on('opt', function(root){
 	// if we DO need an HTTP server, then choose ws specific one or GUN default one.
 	if(!ws.noServer){
 		ws.server = ws.server || opt.web;
-		if(!ws.server){ return }
+		if(!ws.server){ this.to.next(root); return } // ugh, bug fix for @jamierez & unstoppable ryan.
 	}
 	ws.web = ws.web || new opt.WebSocket.Server(ws); // we still need a WS server.
 	ws.web.on('connection', function(wire){ var peer;
@@ -80,6 +80,5 @@ Gun.on('opt', function(root){
 		wire.on('error', function(e){});
 		setTimeout(function heart(){ if(!opt.peers[peer.id]){ return } try{ wire.send("[]") }catch(e){} ;setTimeout(heart, 1000 * 20) }, 1000 * 20); // Some systems, like Heroku, require heartbeats to not time out. // TODO: Make this configurable? // TODO: PERF: Find better approach than try/timeouts?
 	});
-
 	this.to.next(root);
 });

+ 50 - 9
public/lib/gundb/sea.js

@@ -164,7 +164,7 @@
     var o = {};
 
     if(SEA.window){
-      api.crypto = navigator && navigator.product === 'ReactNative' ? require('isomorphic-webcrypto') : window.crypto || window.msCrypto || require('isomorphic-webcrypto');
+      api.crypto = window.crypto || window.msCrypto
       api.subtle = (api.crypto||o).subtle || (api.crypto||o).webkitSubtle;
       api.TextEncoder = window.TextEncoder;
       api.TextDecoder = window.TextDecoder;
@@ -176,17 +176,20 @@
       api.TextDecoder = TextDecoder;
       api.TextEncoder = TextEncoder;
     }
-    if(!api.crypto){try{
+    if(!api.crypto)
+    {
+      try
+      {
       var crypto = USE('crypto', 1);
       Object.assign(api, {
         crypto,
         random: (len) => Buffer.from(crypto.randomBytes(len))
       });      
-      const isocrypto = require('isomorphic-webcrypto');
-      api.ossl = api.subtle = isocrypto.subtle;
-    }catch(e){
+      const { Crypto: WebCrypto } = USE('@peculiar/webcrypto', 1);
+      api.ossl = api.subtle = new WebCrypto({directory: 'ossl'}).subtle // ECDH
+    }
+    catch(e){
       console.log("text-encoding and @peculiar/webcrypto may not be included by default, please add it to your package.json!");
-      TEXT_ENCODING_OR_PECULIAR_WEBCRYPTO_NOT_INSTALLED;
     }}
 
     module.exports = api
@@ -656,7 +659,7 @@
     SEA.verify = USE('./verify');
     SEA.encrypt = USE('./encrypt');
     SEA.decrypt = USE('./decrypt');
-    SEA.opt.aeskey = USE('./aeskey'); // not official!
+    //SEA.opt.aeskey = USE('./aeskey'); // not official! // this causes problems in latest WebCrypto.
 
     SEA.random = SEA.random || shim.random;
 
@@ -707,9 +710,9 @@
 
   ;USE(function(module){
     var Gun = USE('./sea').Gun;
-    Gun.chain.then = function(cb){
+    Gun.chain.then = function(cb, opt){
       var gun = this, p = (new Promise(function(res, rej){
-        gun.once(res);
+        gun.once(res, opt);
       }));
       return cb? p.then(cb) : p;
     }
@@ -1083,6 +1086,44 @@
       }());
       return gun;
     }
+
+    /**
+     * returns the decrypted value, encrypted by secret
+     * @returns {Promise<any>}
+     // Mark needs to review 1st before officially supported
+    User.prototype.decrypt = function(cb) {
+      let gun = this,
+        path = ''
+      gun.back(function(at) {
+        if (at.is) {
+          return
+        }
+        path += at.get || ''
+      })
+      return gun
+        .then(async data => {
+          if (data == null) {
+            return
+          }
+          const user = gun.back(-1).user()
+          const pair = user.pair()
+          let sec = await user
+            .get('trust')
+            .get(pair.pub)
+            .get(path)
+          sec = await SEA.decrypt(sec, pair)
+          if (!sec) {
+            return data
+          }
+          let decrypted = await SEA.decrypt(data, sec)
+          return decrypted
+        })
+        .then(res => {
+          cb && cb(res)
+          return res
+        })
+    }
+    */
     module.exports = User
   })(USE, './create');
 

+ 37 - 0
public/lib/gundb/sea/create.js

@@ -334,5 +334,42 @@
       }());
       return gun;
     }
+
+    /**
+     * returns the decrypted value, encrypted by secret
+     * @returns {Promise<any>}
+     */
+    User.prototype.decrypt = function(cb) {
+      let gun = this,
+        path = ''
+      gun.back(function(at) {
+        if (at.is) {
+          return
+        }
+        path += at.get || ''
+      })
+      return gun
+        .then(async data => {
+          if (data == null) {
+            return
+          }
+          const user = gun.back(-1).user()
+          const pair = user.pair()
+          let sec = await user
+            .get('trust')
+            .get(pair.pub)
+            .get(path)
+          sec = await SEA.decrypt(sec, pair)
+          if (!sec) {
+            return data
+          }
+          let decrypted = await SEA.decrypt(data, sec)
+          return decrypted
+        })
+        .then(res => {
+          cb && cb(res)
+          return res
+        })
+    }
     module.exports = User
   

+ 10 - 7
public/lib/gundb/sea/shim.js

@@ -5,7 +5,7 @@
     var o = {};
 
     if(SEA.window){
-      api.crypto = navigator && navigator.product === 'ReactNative' ? require('isomorphic-webcrypto') : window.crypto || window.msCrypto || require('isomorphic-webcrypto');
+      api.crypto = window.crypto || window.msCrypto
       api.subtle = (api.crypto||o).subtle || (api.crypto||o).webkitSubtle;
       api.TextEncoder = window.TextEncoder;
       api.TextDecoder = window.TextDecoder;
@@ -17,17 +17,20 @@
       api.TextDecoder = TextDecoder;
       api.TextEncoder = TextEncoder;
     }
-    if(!api.crypto){try{
+    if(!api.crypto)
+    {
+      try
+      {
       var crypto = require('crypto', 1);
       Object.assign(api, {
         crypto,
         random: (len) => Buffer.from(crypto.randomBytes(len))
       });      
-      const isocrypto = require('isomorphic-webcrypto');
-      api.ossl = api.subtle = isocrypto.subtle;
-    }catch(e){
-      console.log("text-encoding and @peculiar/webcrypto may not be included by default, please add it to your package.json!");
-      TEXT_ENCODING_OR_PECULIAR_WEBCRYPTO_NOT_INSTALLED;
+      const { Crypto: WebCrypto } = require('@peculiar/webcrypto', 1);
+      api.ossl = api.subtle = new WebCrypto({directory: 'ossl'}).subtle // ECDH
+    }
+    catch(e){
+      console.log("text-encoding and peculiar/nwebcrypto may not be included by default, please add it to your package.json!");
     }}
 
     module.exports = api

+ 3 - 2
public/lib/gundb/sea/then.js

@@ -1,8 +1,9 @@
 
     var Gun = require('./sea').Gun;
-    Gun.chain.then = function(cb){
+    Gun.chain.then = function(cb, opt = {}){
+      opt = {wait: 200, ...opt}
       var gun = this, p = (new Promise(function(res, rej){
-        gun.once(res);
+        gun.once(res, opt);
       }));
       return cb? p.then(cb) : p;
     }

+ 4 - 4
public/luminary.js

@@ -336,11 +336,11 @@ class Luminary {
 
         let self = this;
 
-        let clientDescriptor = { extends: "http://vwf.example.com/client.vwf" };
+        let clientDescriptor = { extends: "proxy/client.vwf" };
         let clientNodeMessage =
         {
             action: "createChild",
-            parameters: ["http://vwf.example.com/clients.vwf", self.clientID, clientDescriptor],
+            parameters: ["proxy/clients.vwf", self.clientID, clientDescriptor],
             time: 'tick'
         }
 
@@ -356,7 +356,7 @@ class Luminary {
         let clientMsg =
             JSON.stringify({
                 action: "createNode",
-                parameters: ["http://vwf.example.com/clients.vwf"],
+                parameters: ["proxy/clients.vwf"],
                 time: 'tick',
                 explicit: self.clientID
             })
@@ -491,7 +491,7 @@ class Luminary {
                         let clientDeleteMessage =
                         {
                             action: "deleteChild",
-                            parameters: ["http://vwf.example.com/clients.vwf", el],
+                            parameters: ["proxy/clients.vwf", el],
                             time: 'tick'
                         };