index.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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(soul !== 'string'){ return to.next(msg) } // do not handle lexical cursors.
  61. if('alias' === soul){ // Allow reading the list of usernames/aliases in the system?
  62. return to.next(msg); // yes.
  63. } else
  64. if('~@' === soul.slice(0,2)){ // Allow reading the list of public keys associated with an alias?
  65. return to.next(msg); // yes.
  66. } else { // Allow reading everything?
  67. return to.next(msg); // yes // TODO: No! Make this a callback/event that people can filter on.
  68. }
  69. }
  70. }
  71. if(msg.put){
  72. // potentially parallel async operations!!!
  73. var check = {}, each = {}, u;
  74. each.node = function(node, soul){
  75. if(Gun.obj.empty(node, '_')){ return check['node'+soul] = 0 } // ignore empty updates, don't reject them.
  76. Gun.obj.map(node, each.way, {soul: soul, node: node});
  77. };
  78. each.way = function(val, key){
  79. var soul = this.soul, node = this.node, tmp;
  80. if('_' === key){ return } // ignore meta data
  81. if('~@' === soul){ // special case for shared system data, the list of aliases.
  82. each.alias(val, key, node, soul); return;
  83. }
  84. if('~@' === soul.slice(0,2)){ // special case for shared system data, the list of public keys for an alias.
  85. each.pubs(val, key, node, soul); return;
  86. }
  87. if('~' === soul.slice(0,1) && 2 === (tmp = soul.slice(1)).split('.').length){ // special case, account data for a public key.
  88. each.pub(val, key, node, soul, tmp, msg.user); return;
  89. }
  90. each.any(val, key, node, soul, msg.user); return;
  91. return each.end({err: "No other data allowed!"});
  92. };
  93. each.alias = function(val, key, node, soul){ // Example: {_:#~@, ~@alice: {#~@alice}}
  94. if(!val){ return each.end({err: "Data must exist!"}) } // data MUST exist
  95. if('~@'+key === Gun.val.link.is(val)){ return check['alias'+key] = 0 } // in fact, it must be EXACTLY equal to itself
  96. each.end({err: "Mismatching alias."}); // if it isn't, reject.
  97. };
  98. each.pubs = function(val, key, node, soul){ // Example: {_:#~@alice, ~asdf: {#~asdf}}
  99. if(!val){ return each.end({err: "Alias must exist!"}) } // data MUST exist
  100. if(key === Gun.val.link.is(val)){ return check['pubs'+soul+key] = 0 } // and the ID must be EXACTLY equal to its property
  101. each.end({err: "Alias must match!"}); // that way nobody can tamper with the list of public keys.
  102. };
  103. each.pub = function(val, key, node, soul, pub, user){ // Example: {_:#~asdf, hello:SEA{'world',fdsa}}
  104. if('pub' === key){
  105. if(val === pub){ return (check['pub'+soul+key] = 0) } // the account MUST match `pub` property that equals the ID of the public key.
  106. return each.end({err: "Account must match!"});
  107. }
  108. check['user'+soul+key] = 1;
  109. if(user && (user = user._) && user.sea && pub === user.pub){
  110. //var id = Gun.text.random(3);
  111. SEA.sign(val, user.sea, function(data){ var rel;
  112. if(u === data){ return each.end({err: SEA.err || 'Pub signature fail.'}) }
  113. if(rel = Gun.val.link.is(val)){
  114. (at.sea.own[rel] = at.sea.own[rel] || {})[pub] = true;
  115. }
  116. node[key] = data;
  117. check['user'+soul+key] = 0;
  118. each.end({ok: 1});
  119. });
  120. // TODO: Handle error!!!!
  121. return;
  122. }
  123. SEA.verify(val, pub, function(data){ var rel, tmp;
  124. if(u === data){ // make sure the signature matches the account it claims to be on.
  125. return each.end({err: "Unverified data."}); // reject any updates that are signed with a mismatched account.
  126. }
  127. if((rel = Gun.val.link.is(data)) && pub === relpub(rel)){
  128. (at.sea.own[rel] = at.sea.own[rel] || {})[pub] = true;
  129. }
  130. check['user'+soul+key] = 0;
  131. each.end({ok: 1});
  132. });
  133. };
  134. function relpub(s){
  135. if(!s){ return }
  136. s = s.split('~');
  137. if(!s || !(s = s[1])){ return }
  138. s = s.split('.');
  139. if(!s || 2 > s.length){ return }
  140. s = s.slice(0,2).join('.');
  141. return s;
  142. }
  143. each.any = function(val, key, node, soul, user){ var tmp, pub;
  144. if(!user || !(user = user._) || !(user = user.sea)){
  145. if(tmp = relpub(soul)){
  146. check['any'+soul+key] = 1;
  147. SEA.verify(val, pub = tmp, function(data){ var rel;
  148. if(u === data){ return each.end({err: "Mismatched owner on '" + key + "'."}) } // thanks @rogowski !
  149. if((rel = Gun.val.link.is(data)) && pub === relpub(rel)){
  150. (at.sea.own[rel] = at.sea.own[rel] || {})[pub] = true;
  151. }
  152. check['any'+soul+key] = 0;
  153. each.end({ok: 1});
  154. });
  155. return;
  156. }
  157. check['any'+soul+key] = 1;
  158. at.on('secure', function(msg){ this.off();
  159. check['any'+soul+key] = 0;
  160. if(at.opt.secure){ msg = null }
  161. each.end(msg || {err: "Data cannot be modified."});
  162. }).on.on('secure', msg);
  163. //each.end({err: "Data cannot be modified."});
  164. return;
  165. }
  166. if(!(tmp = relpub(soul))){
  167. if(at.opt.secure){
  168. each.end({err: "Soul is missing public key at '" + key + "'."});
  169. return;
  170. }
  171. if(val && val.slice && 'SEA{' === (val).slice(0,4)){
  172. check['any'+soul+key] = 0;
  173. each.end({ok: 1});
  174. return;
  175. }
  176. //check['any'+soul+key] = 1;
  177. //SEA.sign(val, user, function(data){
  178. // if(u === data){ return each.end({err: 'Any signature failed.'}) }
  179. // node[key] = data;
  180. check['any'+soul+key] = 0;
  181. each.end({ok: 1});
  182. //});
  183. return;
  184. }
  185. var pub = tmp;
  186. if(pub !== user.pub){
  187. each.any(val, key, node, soul);
  188. return;
  189. }
  190. /*var other = Gun.obj.map(at.sea.own[soul], function(v, p){
  191. if(user.pub !== p){ return p }
  192. });
  193. if(other){
  194. each.any(val, key, node, soul);
  195. return;
  196. }*/
  197. check['any'+soul+key] = 1;
  198. SEA.sign(val, user, function(data){
  199. if(u === data){ return each.end({err: 'My signature fail.'}) }
  200. node[key] = data;
  201. check['any'+soul+key] = 0;
  202. each.end({ok: 1});
  203. });
  204. }
  205. each.end = function(ctx){ // TODO: Can't you just switch this to each.end = cb?
  206. if(each.err){ return }
  207. if((each.err = ctx.err) || ctx.no){
  208. console.log('NO!', each.err, msg.put);
  209. return;
  210. }
  211. if(!each.end.ed){ return }
  212. if(Gun.obj.map(check, function(no){
  213. if(no){ return true }
  214. })){ return }
  215. to.next(msg);
  216. };
  217. Gun.obj.map(msg.put, each.node);
  218. each.end({end: each.end.ed = true});
  219. return; // need to manually call next after async.
  220. }
  221. to.next(msg); // pass forward any data we do not know how to handle or process (this allows custom security protocols).
  222. }