index.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. const SEA = require('./sea')
  2. const Gun = SEA.Gun;
  3. // After we have a GUN extension to make user registration/login easy, we then need to handle everything else.
  4. // We do this with a GUN adapter, we first listen to when a gun instance is created (and when its options change)
  5. Gun.on('opt', function(at){
  6. if(!at.sea){ // only add SEA once per instance, on the "at" context.
  7. at.sea = {own: {}};
  8. at.on('in', security, at); // now listen to all input data, acting as a firewall.
  9. at.on('out', signature, at); // and output listeners, to encrypt outgoing data.
  10. at.on('node', each, at);
  11. }
  12. this.to.next(at); // make sure to call the "next" middleware adapter.
  13. });
  14. // Alright, this next adapter gets run at the per node level in the graph database.
  15. // This will let us verify that every property on a node has a value signed by a public key we trust.
  16. // If the signature does not match, the data is just `undefined` so it doesn't get passed on.
  17. // If it does match, then we transform the in-memory "view" of the data into its plain value (without the signature).
  18. // Now NOTE! Some data is "system" data, not user data. Example: List of public keys, aliases, etc.
  19. // This data is self-enforced (the value can only match its ID), but that is handled in the `security` function.
  20. // From the self-enforced data, we can see all the edges in the graph that belong to a public key.
  21. // Example: ~ASDF is the ID of a node with ASDF as its public key, signed alias and salt, and
  22. // its encrypted private key, but it might also have other signed values on it like `profile = <ID>` edge.
  23. // Using that directed edge's ID, we can then track (in memory) which IDs belong to which keys.
  24. // Here is a problem: Multiple public keys can "claim" any node's ID, so this is dangerous!
  25. // This means we should ONLY trust our "friends" (our key ring) public keys, not any ones.
  26. // I have not yet added that to SEA yet in this alpha release. That is coming soon, but beware in the meanwhile!
  27. function each(msg){ // TODO: Warning: Need to switch to `gun.on('node')`! Do not use `Gun.on('node'` in your apps!
  28. // NOTE: THE SECURITY FUNCTION HAS ALREADY VERIFIED THE DATA!!!
  29. // WE DO NOT NEED TO RE-VERIFY AGAIN, JUST TRANSFORM IT TO PLAINTEXT.
  30. var to = this.to, vertex = (msg.$._).put, c = 0, d;
  31. Gun.node.is(msg.put, function(val, key, node){ c++; // for each property on the node
  32. // TODO: consider async/await use here...
  33. SEA.verify(val, false, function(data){ c--; // false just extracts the plain data.
  34. node[key] = val = data; // transform to plain value.
  35. if(d && !c && (c = -1)){ to.next(msg) }
  36. });
  37. });
  38. d = true;
  39. if(d && !c){ to.next(msg) }
  40. return;
  41. }
  42. // signature handles data output, it is a proxy to the security function.
  43. function signature(msg){
  44. if(msg.user){
  45. return this.to.next(msg);
  46. }
  47. var ctx = this.as;
  48. msg.user = ctx.user;
  49. security.call(this, msg);
  50. }
  51. // okay! The security function handles all the heavy lifting.
  52. // It needs to deal read and write of input and output of system data, account/public key data, and regular data.
  53. // This is broken down into some pretty clear edge cases, let's go over them:
  54. function security(msg){
  55. var at = this.as, sea = at.sea, to = this.to;
  56. if(msg.get){
  57. // if there is a request to read data from us, then...
  58. var soul = msg.get['#'];
  59. if(soul){ // for now, only allow direct IDs to be read.
  60. if('alias' === soul){ // Allow reading the list of usernames/aliases in the system?
  61. return to.next(msg); // yes.
  62. } else
  63. if('~@' === soul.slice(0,2)){ // Allow reading the list of public keys associated with an alias?
  64. return to.next(msg); // yes.
  65. } else { // Allow reading everything?
  66. return to.next(msg); // yes // TODO: No! Make this a callback/event that people can filter on.
  67. }
  68. }
  69. }
  70. if(msg.put){
  71. // potentially parallel async operations!!!
  72. var check = {}, each = {}, u;
  73. each.node = function(node, soul){
  74. if(Gun.obj.empty(node, '_')){ return check['node'+soul] = 0 } // ignore empty updates, don't reject them.
  75. Gun.obj.map(node, each.way, {soul: soul, node: node});
  76. };
  77. each.way = function(val, key){
  78. var soul = this.soul, node = this.node, tmp;
  79. if('_' === key){ return } // ignore meta data
  80. if('~@' === soul){ // special case for shared system data, the list of aliases.
  81. each.alias(val, key, node, soul); return;
  82. }
  83. if('~@' === soul.slice(0,2)){ // special case for shared system data, the list of public keys for an alias.
  84. each.pubs(val, key, node, soul); return;
  85. }
  86. if('~' === soul.slice(0,1) && 2 === (tmp = soul.slice(1)).split('.').length){ // special case, account data for a public key.
  87. each.pub(val, key, node, soul, tmp, msg.user); return;
  88. }
  89. each.any(val, key, node, soul, msg.user); return;
  90. return each.end({err: "No other data allowed!"});
  91. };
  92. each.alias = function(val, key, node, soul){ // Example: {_:#~@, ~@alice: {#~@alice}}
  93. if(!val){ return each.end({err: "Data must exist!"}) } // data MUST exist
  94. if('~@'+key === Gun.val.link.is(val)){ return check['alias'+key] = 0 } // in fact, it must be EXACTLY equal to itself
  95. each.end({err: "Mismatching alias."}); // if it isn't, reject.
  96. };
  97. each.pubs = function(val, key, node, soul){ // Example: {_:#~@alice, ~asdf: {#~asdf}}
  98. if(!val){ return each.end({err: "Alias must exist!"}) } // data MUST exist
  99. if(key === Gun.val.link.is(val)){ return check['pubs'+soul+key] = 0 } // and the ID must be EXACTLY equal to its property
  100. each.end({err: "Alias must match!"}); // that way nobody can tamper with the list of public keys.
  101. };
  102. each.pub = function(val, key, node, soul, pub, user){ // Example: {_:#~asdf, hello:SEA{'world',fdsa}}
  103. if('pub' === key){
  104. if(val === pub){ return (check['pub'+soul+key] = 0) } // the account MUST match `pub` property that equals the ID of the public key.
  105. return each.end({err: "Account must match!"});
  106. }
  107. check['user'+soul+key] = 1;
  108. if(user && (user = user._) && user.sea && pub === user.pub){
  109. //var id = Gun.text.random(3);
  110. SEA.sign(val, user.sea, function(data){ var rel;
  111. if(u === data){ return each.end({err: SEA.err || 'Pub signature fail.'}) }
  112. if(rel = Gun.val.link.is(val)){
  113. (at.sea.own[rel] = at.sea.own[rel] || {})[pub] = true;
  114. }
  115. node[key] = data;
  116. check['user'+soul+key] = 0;
  117. each.end({ok: 1});
  118. });
  119. // TODO: Handle error!!!!
  120. return;
  121. }
  122. SEA.verify(val, pub, function(data){ var rel, tmp;
  123. if(u === data){ // make sure the signature matches the account it claims to be on.
  124. return each.end({err: "Unverified data."}); // reject any updates that are signed with a mismatched account.
  125. }
  126. if((rel = Gun.val.link.is(data)) && pub === relpub(rel)){
  127. (at.sea.own[rel] = at.sea.own[rel] || {})[pub] = true;
  128. }
  129. check['user'+soul+key] = 0;
  130. each.end({ok: 1});
  131. });
  132. };
  133. function relpub(s){
  134. if(!s){ return }
  135. s = s.split('~');
  136. if(!s || !(s = s[1])){ return }
  137. s = s.split('.');
  138. if(!s || 2 > s.length){ return }
  139. s = s.slice(0,2).join('.');
  140. return s;
  141. }
  142. each.any = function(val, key, node, soul, user){ var tmp, pub;
  143. if(!user || !(user = user._) || !(user = user.sea)){
  144. if(tmp = relpub(soul)){
  145. check['any'+soul+key] = 1;
  146. SEA.verify(val, pub = tmp, function(data){ var rel;
  147. if(!data){ return each.end({err: "Mismatched owner on '" + key + "'."}) }
  148. if((rel = Gun.val.link.is(data)) && pub === relpub(rel)){
  149. (at.sea.own[rel] = at.sea.own[rel] || {})[pub] = true;
  150. }
  151. check['any'+soul+key] = 0;
  152. each.end({ok: 1});
  153. });
  154. return;
  155. }
  156. check['any'+soul+key] = 1;
  157. at.on('secure', function(msg){ this.off();
  158. check['any'+soul+key] = 0;
  159. if(at.opt.secure){ msg = null }
  160. each.end(msg || {err: "Data cannot be modified."});
  161. }).on.on('secure', msg);
  162. //each.end({err: "Data cannot be modified."});
  163. return;
  164. }
  165. if(!(tmp = relpub(soul))){
  166. if(at.opt.secure){
  167. each.end({err: "Soul is missing public key at '" + key + "'."});
  168. return;
  169. }
  170. if(val && val.slice && 'SEA{' === (val).slice(0,4)){
  171. check['any'+soul+key] = 0;
  172. each.end({ok: 1});
  173. return;
  174. }
  175. //check['any'+soul+key] = 1;
  176. //SEA.sign(val, user, function(data){
  177. // if(u === data){ return each.end({err: 'Any signature failed.'}) }
  178. // node[key] = data;
  179. check['any'+soul+key] = 0;
  180. each.end({ok: 1});
  181. //});
  182. return;
  183. }
  184. var pub = tmp;
  185. if(pub !== user.pub){
  186. each.any(val, key, node, soul);
  187. return;
  188. }
  189. /*var other = Gun.obj.map(at.sea.own[soul], function(v, p){
  190. if(user.pub !== p){ return p }
  191. });
  192. if(other){
  193. each.any(val, key, node, soul);
  194. return;
  195. }*/
  196. check['any'+soul+key] = 1;
  197. SEA.sign(val, user, function(data){
  198. if(u === data){ return each.end({err: 'My signature fail.'}) }
  199. node[key] = data;
  200. check['any'+soul+key] = 0;
  201. each.end({ok: 1});
  202. });
  203. }
  204. each.end = function(ctx){ // TODO: Can't you just switch this to each.end = cb?
  205. if(each.err){ return }
  206. if((each.err = ctx.err) || ctx.no){
  207. console.log('NO!', each.err, msg.put);
  208. return;
  209. }
  210. if(!each.end.ed){ return }
  211. if(Gun.obj.map(check, function(no){
  212. if(no){ return true }
  213. })){ return }
  214. to.next(msg);
  215. };
  216. Gun.obj.map(msg.put, each.node);
  217. each.end({end: each.end.ed = true});
  218. return; // need to manually call next after async.
  219. }
  220. to.next(msg); // pass forward any data we do not know how to handle or process (this allows custom security protocols).
  221. }