sea.js 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643
  1. ;(function(){
  2. /* UNBUILD */
  3. var root;
  4. if(typeof window !== "undefined"){ root = window }
  5. if(typeof global !== "undefined"){ root = global }
  6. root = root || {};
  7. var console = root.console || {log: function(){}};
  8. function USE(arg){
  9. return arg.slice? USE[R(arg)] : function(mod, path){
  10. arg(mod = {exports: {}});
  11. USE[R(path)] = mod.exports;
  12. }
  13. function R(p){
  14. return p.split('/').slice(-1).toString().replace('.js','');
  15. }
  16. }
  17. if(typeof module !== "undefined"){ var common = module }
  18. /* UNBUILD */
  19. ;USE(function(module){
  20. // Security, Encryption, and Authorization: SEA.js
  21. // MANDATORY READING: http://gun.js.org/explainers/data/security.html
  22. // THIS IS AN EARLY ALPHA!
  23. function SEA(){}
  24. if(typeof window !== "undefined"){ (SEA.window = window).SEA = SEA }
  25. module.exports = SEA;
  26. })(USE, './root');
  27. ;USE(function(module){
  28. var SEA = USE('./root');
  29. if(SEA.window){
  30. if(location.protocol.indexOf('s') < 0
  31. && location.host.indexOf('localhost') < 0
  32. && location.protocol.indexOf('file:') < 0){
  33. location.protocol = 'https:'; // WebCrypto does NOT work without HTTPS!
  34. }
  35. }
  36. })(USE, './https');
  37. ;USE(function(module){
  38. // This is Array extended to have .toString(['utf8'|'hex'|'base64'])
  39. function SeaArray() {}
  40. Object.assign(SeaArray, { from: Array.from })
  41. SeaArray.prototype = Object.create(Array.prototype)
  42. SeaArray.prototype.toString = function(enc, start, end) { enc = enc || 'utf8'; start = start || 0;
  43. const length = this.length
  44. if (enc === 'hex') {
  45. const buf = new Uint8Array(this)
  46. return [ ...Array(((end && (end + 1)) || length) - start).keys()]
  47. .map((i) => buf[ i + start ].toString(16).padStart(2, '0')).join('')
  48. }
  49. if (enc === 'utf8') {
  50. return Array.from(
  51. { length: (end || length) - start },
  52. (_, i) => String.fromCharCode(this[ i + start])
  53. ).join('')
  54. }
  55. if (enc === 'base64') {
  56. return btoa(this)
  57. }
  58. }
  59. module.exports = SeaArray;
  60. })(USE, './array');
  61. ;USE(function(module){
  62. // This is Buffer implementation used in SEA. Functionality is mostly
  63. // compatible with NodeJS 'safe-buffer' and is used for encoding conversions
  64. // between binary and 'hex' | 'utf8' | 'base64'
  65. // See documentation and validation for safe implementation in:
  66. // https://github.com/feross/safe-buffer#update
  67. var SeaArray = USE('./array');
  68. function SafeBuffer(...props) {
  69. console.warn('new SafeBuffer() is depreciated, please use SafeBuffer.from()')
  70. return SafeBuffer.from(...props)
  71. }
  72. SafeBuffer.prototype = Object.create(Array.prototype)
  73. Object.assign(SafeBuffer, {
  74. // (data, enc) where typeof data === 'string' then enc === 'utf8'|'hex'|'base64'
  75. from() {
  76. if (!Object.keys(arguments).length) {
  77. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  78. }
  79. const input = arguments[0]
  80. let buf
  81. if (typeof input === 'string') {
  82. const enc = arguments[1] || 'utf8'
  83. if (enc === 'hex') {
  84. const bytes = input.match(/([\da-fA-F]{2})/g)
  85. .map((byte) => parseInt(byte, 16))
  86. if (!bytes || !bytes.length) {
  87. throw new TypeError('Invalid first argument for type \'hex\'.')
  88. }
  89. buf = SeaArray.from(bytes)
  90. } else if (enc === 'utf8') {
  91. const length = input.length
  92. const words = new Uint16Array(length)
  93. Array.from({ length: length }, (_, i) => words[i] = input.charCodeAt(i))
  94. buf = SeaArray.from(words)
  95. } else if (enc === 'base64') {
  96. const dec = atob(input)
  97. const length = dec.length
  98. const bytes = new Uint8Array(length)
  99. Array.from({ length: length }, (_, i) => bytes[i] = dec.charCodeAt(i))
  100. buf = SeaArray.from(bytes)
  101. } else if (enc === 'binary') {
  102. buf = SeaArray.from(input)
  103. } else {
  104. console.info('SafeBuffer.from unknown encoding: '+enc)
  105. }
  106. return buf
  107. }
  108. const byteLength = input.byteLength
  109. const length = input.byteLength ? input.byteLength : input.length
  110. if (length) {
  111. let buf
  112. if (input instanceof ArrayBuffer) {
  113. buf = new Uint8Array(input)
  114. }
  115. return SeaArray.from(buf || input)
  116. }
  117. },
  118. // This is 'safe-buffer.alloc' sans encoding support
  119. alloc(length, fill = 0 /*, enc*/ ) {
  120. return SeaArray.from(new Uint8Array(Array.from({ length: length }, () => fill)))
  121. },
  122. // This is normal UNSAFE 'buffer.alloc' or 'new Buffer(length)' - don't use!
  123. allocUnsafe(length) {
  124. return SeaArray.from(new Uint8Array(Array.from({ length : length })))
  125. },
  126. // This puts together array of array like members
  127. concat(arr) { // octet array
  128. if (!Array.isArray(arr)) {
  129. throw new TypeError('First argument must be Array containing ArrayBuffer or Uint8Array instances.')
  130. }
  131. return SeaArray.from(arr.reduce((ret, item) => ret.concat(Array.from(item)), []))
  132. }
  133. })
  134. SafeBuffer.prototype.from = SafeBuffer.from
  135. SafeBuffer.prototype.toString = SeaArray.prototype.toString
  136. module.exports = SafeBuffer;
  137. })(USE, './buffer');
  138. ;USE(function(module){
  139. const Buffer = USE('./buffer')
  140. const api = {Buffer: Buffer}
  141. if (typeof __webpack_require__ === 'function' || typeof window !== 'undefined') {
  142. var crypto = window.crypto || window.msCrypto;
  143. var subtle = crypto.subtle || crypto.webkitSubtle;
  144. const TextEncoder = window.TextEncoder
  145. const TextDecoder = window.TextDecoder
  146. Object.assign(api, {
  147. crypto,
  148. subtle,
  149. TextEncoder,
  150. TextDecoder,
  151. random: (len) => Buffer.from(crypto.getRandomValues(new Uint8Array(Buffer.alloc(len))))
  152. })
  153. } else {
  154. try{
  155. var crypto = require('crypto');
  156. const { subtle } = require('@trust/webcrypto') // All but ECDH
  157. const { TextEncoder, TextDecoder } = require('text-encoding')
  158. Object.assign(api, {
  159. crypto,
  160. subtle,
  161. TextEncoder,
  162. TextDecoder,
  163. random: (len) => Buffer.from(crypto.randomBytes(len))
  164. });
  165. //try{
  166. const WebCrypto = require('node-webcrypto-ossl')
  167. api.ossl = new WebCrypto({directory: 'ossl'}).subtle // ECDH
  168. //}catch(e){
  169. //console.log("node-webcrypto-ossl is optionally needed for ECDH, please install if needed.");
  170. //}
  171. }catch(e){
  172. console.log("@trust/webcrypto and text-encoding are not included by default, you must add it to your package.json!");
  173. 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).");
  174. TRUST_WEBCRYPTO_OR_TEXT_ENCODING_NOT_INSTALLED;
  175. }
  176. }
  177. module.exports = api
  178. })(USE, './shim');
  179. ;USE(function(module){
  180. const Buffer = USE('./buffer')
  181. const settings = {}
  182. // Encryption parameters
  183. const pbkdf2 = { hash: 'SHA-256', iter: 100000, ks: 64 }
  184. const ecdsaSignProps = { name: 'ECDSA', hash: { name: 'SHA-256' } }
  185. const ecdsaKeyProps = { name: 'ECDSA', namedCurve: 'P-256' }
  186. const ecdhKeyProps = { name: 'ECDH', namedCurve: 'P-256' }
  187. const _initial_authsettings = {
  188. validity: 12 * 60 * 60, // internally in seconds : 12 hours
  189. hook: (props) => props // { iat, exp, alias, remember }
  190. // or return new Promise((resolve, reject) => resolve(props)
  191. }
  192. // These are used to persist user's authentication "session"
  193. const authsettings = Object.assign({}, _initial_authsettings)
  194. // This creates Web Cryptography API compliant JWK for sign/verify purposes
  195. const keysToEcdsaJwk = (pub, d) => { // d === priv
  196. //const [ x, y ] = Buffer.from(pub, 'base64').toString('utf8').split(':') // old
  197. const [ x, y ] = pub.split('.') // new
  198. var jwk = { kty: "EC", crv: "P-256", x: x, y: y, ext: true }
  199. jwk.key_ops = d ? ['sign'] : ['verify'];
  200. if(d){ jwk.d = d }
  201. return jwk;
  202. }
  203. Object.assign(settings, {
  204. pbkdf2: pbkdf2,
  205. ecdsa: {
  206. pair: ecdsaKeyProps,
  207. sign: ecdsaSignProps
  208. },
  209. ecdh: ecdhKeyProps,
  210. jwk: keysToEcdsaJwk,
  211. recall: authsettings
  212. })
  213. module.exports = settings
  214. })(USE, './settings');
  215. ;USE(function(module){
  216. module.exports = (props) => {
  217. try {
  218. if(props.slice && 'SEA{' === props.slice(0,4)){
  219. props = props.slice(3);
  220. }
  221. return props.slice ? JSON.parse(props) : props
  222. } catch (e) {} //eslint-disable-line no-empty
  223. return props
  224. }
  225. })(USE, './parse');
  226. ;USE(function(module){
  227. const shim = USE('./shim');
  228. const Buffer = USE('./buffer')
  229. const parse = USE('./parse')
  230. const { pbkdf2 } = USE('./settings')
  231. // This internal func returns SHA-256 hashed data for signing
  232. const sha256hash = async (mm) => {
  233. const m = parse(mm)
  234. const hash = await shim.subtle.digest({name: pbkdf2.hash}, new shim.TextEncoder().encode(m))
  235. return Buffer.from(hash)
  236. }
  237. module.exports = sha256hash
  238. })(USE, './sha256');
  239. ;USE(function(module){
  240. // This internal func returns SHA-1 hashed data for KeyID generation
  241. const __shim = USE('./shim')
  242. const subtle = __shim.subtle
  243. const ossl = __shim.ossl ? __shim.__ossl : subtle
  244. const sha1hash = (b) => ossl.digest({name: 'SHA-1'}, new ArrayBuffer(b))
  245. module.exports = sha1hash
  246. })(USE, './sha1');
  247. ;USE(function(module){
  248. var SEA = USE('./root');
  249. var shim = USE('./shim');
  250. var S = USE('./settings');
  251. var u;
  252. SEA.work = async (data, pair, cb) => { try { // used to be named `proof`
  253. var salt = pair.epub || pair; // epub not recommended, salt should be random!
  254. if(salt instanceof Function){
  255. cb = salt;
  256. salt = u;
  257. }
  258. salt = salt || shim.random(9);
  259. if (SEA.window) {
  260. // For browser subtle works fine
  261. const key = await shim.subtle.importKey(
  262. 'raw', new shim.TextEncoder().encode(data), { name: 'PBKDF2' }, false, ['deriveBits']
  263. )
  264. const result = await shim.subtle.deriveBits({
  265. name: 'PBKDF2',
  266. iterations: S.pbkdf2.iter,
  267. salt: new shim.TextEncoder().encode(salt),
  268. hash: S.pbkdf2.hash,
  269. }, key, S.pbkdf2.ks * 8)
  270. data = shim.random(data.length) // Erase data in case of passphrase
  271. const r = shim.Buffer.from(result, 'binary').toString('utf8')
  272. if(cb){ try{ cb(r) }catch(e){console.log(e)} }
  273. return r;
  274. }
  275. // For NodeJS crypto.pkdf2 rocks
  276. const crypto = shim.crypto;
  277. const hash = crypto.pbkdf2Sync(
  278. data,
  279. new shim.TextEncoder().encode(salt),
  280. S.pbkdf2.iter,
  281. S.pbkdf2.ks,
  282. S.pbkdf2.hash.replace('-', '').toLowerCase()
  283. )
  284. data = shim.random(data.length) // Erase passphrase for app
  285. const r = hash && hash.toString('utf8')
  286. if(cb){ try{ cb(r) }catch(e){console.log(e)} }
  287. return r;
  288. } catch(e) {
  289. SEA.err = e;
  290. if(cb){ cb() }
  291. return;
  292. }}
  293. module.exports = SEA.work;
  294. })(USE, './work');
  295. ;USE(function(module){
  296. var SEA = USE('./root');
  297. var shim = USE('./shim');
  298. var S = USE('./settings');
  299. var Buff = (typeof Buffer !== 'undefined')? Buffer : shim.Buffer;
  300. //SEA.pair = async (data, proof, cb) => { try {
  301. SEA.pair = async (cb) => { try {
  302. const ecdhSubtle = shim.ossl || shim.subtle
  303. // First: ECDSA keys for signing/verifying...
  304. var sa = await shim.subtle.generateKey(S.ecdsa.pair, true, [ 'sign', 'verify' ])
  305. .then(async (keys) => {
  306. // privateKey scope doesn't leak out from here!
  307. //const { d: priv } = await shim.subtle.exportKey('jwk', keys.privateKey)
  308. const key = {};
  309. key.priv = (await shim.subtle.exportKey('jwk', keys.privateKey)).d;
  310. const pub = await shim.subtle.exportKey('jwk', keys.publicKey)
  311. //const pub = Buff.from([ x, y ].join(':')).toString('base64') // old
  312. key.pub = pub.x+'.'+pub.y // new
  313. // x and y are already base64
  314. // pub is UTF8 but filename/URL safe (https://www.ietf.org/rfc/rfc3986.txt)
  315. // but split on a non-base64 letter.
  316. return key;
  317. })
  318. // To include PGPv4 kind of keyId:
  319. // const pubId = await SEA.keyid(keys.pub)
  320. // Next: ECDH keys for encryption/decryption...
  321. try{
  322. var dh = await ecdhSubtle.generateKey(S.ecdh, true, ['deriveKey'])
  323. .then(async (keys) => {
  324. // privateKey scope doesn't leak out from here!
  325. const key = {};
  326. key.epriv = (await ecdhSubtle.exportKey('jwk', keys.privateKey)).d;
  327. const pub = await ecdhSubtle.exportKey('jwk', keys.publicKey)
  328. //const epub = Buff.from([ ex, ey ].join(':')).toString('base64') // old
  329. key.epub = pub.x+'.'+pub.y // new
  330. // ex and ey are already base64
  331. // epub is UTF8 but filename/URL safe (https://www.ietf.org/rfc/rfc3986.txt)
  332. // but split on a non-base64 letter.
  333. return key;
  334. })
  335. }catch(e){
  336. if(SEA.window){ throw e }
  337. if(e == 'Error: ECDH is not a supported algorithm'){ console.log('Ignoring ECDH...') }
  338. else { throw e }
  339. } dh = dh || {};
  340. const r = { pub: sa.pub, priv: sa.priv, /* pubId, */ epub: dh.epub, epriv: dh.epriv }
  341. if(cb){ try{ cb(r) }catch(e){console.log(e)} }
  342. return r;
  343. } catch(e) {
  344. console.log(e);
  345. SEA.err = e;
  346. if(cb){ cb() }
  347. return;
  348. }}
  349. module.exports = SEA.pair;
  350. })(USE, './pair');
  351. ;USE(function(module){
  352. var SEA = USE('./root');
  353. var shim = USE('./shim');
  354. var S = USE('./settings');
  355. var sha256hash = USE('./sha256');
  356. SEA.sign = async (data, pair, cb) => { try {
  357. if(data && data.slice
  358. && 'SEA{' === data.slice(0,4)
  359. && '"m":' === data.slice(4,8)){
  360. // TODO: This would prevent pair2 signing pair1's signature.
  361. // So we may want to change this in the future.
  362. // but for now, we want to prevent duplicate double signature.
  363. if(cb){ try{ cb(data) }catch(e){console.log(e)} }
  364. return data;
  365. }
  366. const pub = pair.pub
  367. const priv = pair.priv
  368. const jwk = S.jwk(pub, priv)
  369. const msg = JSON.stringify(data)
  370. const hash = await sha256hash(msg)
  371. const sig = await (shim.ossl || shim.subtle).importKey('jwk', jwk, S.ecdsa.pair, false, ['sign'])
  372. .then((key) => (shim.ossl || shim.subtle).sign(S.ecdsa.sign, key, new Uint8Array(hash))) // privateKey scope doesn't leak out from here!
  373. const r = 'SEA'+JSON.stringify({m: msg, s: shim.Buffer.from(sig, 'binary').toString('utf8')});
  374. if(cb){ try{ cb(r) }catch(e){console.log(e)} }
  375. return r;
  376. } catch(e) {
  377. console.log(e);
  378. SEA.err = e;
  379. if(cb){ cb() }
  380. return;
  381. }}
  382. module.exports = SEA.sign;
  383. })(USE, './sign');
  384. ;USE(function(module){
  385. var SEA = USE('./root');
  386. var shim = USE('./shim');
  387. var S = USE('./settings');
  388. var sha256hash = USE('./sha256');
  389. var parse = USE('./parse');
  390. var u;
  391. SEA.verify = async (data, pair, cb) => { try {
  392. const json = parse(data)
  393. if(false === pair){ // don't verify!
  394. const raw = (json !== data)?
  395. (json.s && json.m)? parse(json.m) : data
  396. : json;
  397. if(cb){ try{ cb(raw) }catch(e){console.log(e)} }
  398. return raw;
  399. }
  400. const pub = pair.pub || pair
  401. const jwk = S.jwk(pub)
  402. const key = await (shim.ossl || shim.subtle).importKey('jwk', jwk, S.ecdsa.pair, false, ['verify'])
  403. const hash = await sha256hash(json.m)
  404. const sig = new Uint8Array(shim.Buffer.from(json.s, 'utf8'))
  405. const check = await (shim.ossl || shim.subtle).verify(S.ecdsa.sign, key, sig, new Uint8Array(hash))
  406. if(!check){ throw "Signature did not match." }
  407. const r = check? parse(json.m) : u;
  408. if(cb){ try{ cb(r) }catch(e){console.log(e)} }
  409. return r;
  410. } catch(e) {
  411. console.log(e);
  412. SEA.err = e;
  413. if(cb){ cb() }
  414. return;
  415. }}
  416. module.exports = SEA.verify;
  417. })(USE, './verify');
  418. ;USE(function(module){
  419. var shim = USE('./shim');
  420. var sha256hash = USE('./sha256');
  421. const importGen = async (key, salt, opt) => {
  422. //const combo = shim.Buffer.concat([shim.Buffer.from(key, 'utf8'), salt || shim.random(8)]).toString('utf8') // old
  423. var opt = opt || {};
  424. const combo = key + (salt || shim.random(8)).toString('utf8'); // new
  425. const hash = shim.Buffer.from(await sha256hash(combo), 'binary')
  426. return await shim.subtle.importKey('raw', new Uint8Array(hash), opt.name || 'AES-GCM', false, ['encrypt', 'decrypt'])
  427. }
  428. module.exports = importGen;
  429. })(USE, './aeskey');
  430. ;USE(function(module){
  431. var SEA = USE('./root');
  432. var shim = USE('./shim');
  433. var S = USE('./settings');
  434. var aeskey = USE('./aeskey');
  435. SEA.encrypt = async (data, pair, cb, opt) => { try {
  436. var opt = opt || {};
  437. const key = pair.epriv || pair;
  438. const msg = JSON.stringify(data)
  439. const rand = {s: shim.random(8), iv: shim.random(16)};
  440. const ct = await aeskey(key, rand.s, opt)
  441. .then((aes) => shim.subtle.encrypt({ // Keeping the AES key scope as private as possible...
  442. name: opt.name || 'AES-GCM', iv: new Uint8Array(rand.iv)
  443. }, aes, new shim.TextEncoder().encode(msg)))
  444. const r = 'SEA'+JSON.stringify({
  445. ct: shim.Buffer.from(ct, 'binary').toString('utf8'),
  446. iv: rand.iv.toString('utf8'),
  447. s: rand.s.toString('utf8')
  448. });
  449. if(cb){ try{ cb(r) }catch(e){console.log(e)} }
  450. return r;
  451. } catch(e) {
  452. SEA.err = e;
  453. if(cb){ cb() }
  454. return;
  455. }}
  456. module.exports = SEA.encrypt;
  457. })(USE, './encrypt');
  458. ;USE(function(module){
  459. var SEA = USE('./root');
  460. var shim = USE('./shim');
  461. var S = USE('./settings');
  462. var aeskey = USE('./aeskey');
  463. var parse = USE('./parse');
  464. SEA.decrypt = async (data, pair, cb, opt) => { try {
  465. var opt = opt || {};
  466. const key = pair.epriv || pair;
  467. const json = parse(data)
  468. const ct = await aeskey(key, shim.Buffer.from(json.s, 'utf8'), opt)
  469. .then((aes) => shim.subtle.decrypt({ // Keeping aesKey scope as private as possible...
  470. name: opt.name || 'AES-GCM', iv: new Uint8Array(shim.Buffer.from(json.iv, 'utf8'))
  471. }, aes, new Uint8Array(shim.Buffer.from(json.ct, 'utf8'))))
  472. const r = parse(new shim.TextDecoder('utf8').decode(ct))
  473. if(cb){ try{ cb(r) }catch(e){console.log(e)} }
  474. return r;
  475. } catch(e) {
  476. SEA.err = e;
  477. if(cb){ cb() }
  478. return;
  479. }}
  480. module.exports = SEA.decrypt;
  481. })(USE, './decrypt');
  482. ;USE(function(module){
  483. var SEA = USE('./root');
  484. var shim = USE('./shim');
  485. var S = USE('./settings');
  486. // Derive shared secret from other's pub and my epub/epriv
  487. SEA.secret = async (key, pair, cb) => { try {
  488. const pub = key.epub || key
  489. const epub = pair.epub
  490. const epriv = pair.epriv
  491. const ecdhSubtle = shim.ossl || shim.subtle
  492. const pubKeyData = keysToEcdhJwk(pub)
  493. const props = Object.assign(
  494. S.ecdh,
  495. { public: await ecdhSubtle.importKey(...pubKeyData, true, []) }
  496. )
  497. const privKeyData = keysToEcdhJwk(epub, epriv)
  498. const derived = await ecdhSubtle.importKey(...privKeyData, false, ['deriveKey'])
  499. .then(async (privKey) => {
  500. // privateKey scope doesn't leak out from here!
  501. const derivedKey = await ecdhSubtle.deriveKey(props, privKey, { name: 'AES-GCM', length: 256 }, true, [ 'encrypt', 'decrypt' ])
  502. return ecdhSubtle.exportKey('jwk', derivedKey).then(({ k }) => k)
  503. })
  504. const r = derived;
  505. if(cb){ try{ cb(r) }catch(e){console.log(e)} }
  506. return r;
  507. } catch(e) {
  508. SEA.err = e;
  509. if(cb){ cb() }
  510. return;
  511. }}
  512. const keysToEcdhJwk = (pub, d) => { // d === priv
  513. //const [ x, y ] = Buffer.from(pub, 'base64').toString('utf8').split(':') // old
  514. const [ x, y ] = pub.split('.') // new
  515. const jwk = d ? { d: d } : {}
  516. return [ // Use with spread returned value...
  517. 'jwk',
  518. Object.assign(
  519. jwk,
  520. { x: x, y: y, kty: 'EC', crv: 'P-256', ext: true }
  521. ), // ??? refactor
  522. S.ecdh
  523. ]
  524. }
  525. module.exports = SEA.secret;
  526. })(USE, './secret');
  527. ;USE(function(module){
  528. // Old Code...
  529. const __gky10 = USE('./shim')
  530. const crypto = __gky10.crypto
  531. const subtle = __gky10.subtle
  532. const ossl = __gky10.ossl
  533. const TextEncoder = __gky10.TextEncoder
  534. const TextDecoder = __gky10.TextDecoder
  535. const getRandomBytes = __gky10.random
  536. const EasyIndexedDB = USE('./indexed')
  537. const Buffer = USE('./buffer')
  538. var settings = USE('./settings');
  539. const __gky11 = USE('./settings')
  540. const pbKdf2 = __gky11.pbkdf2
  541. const ecdsaKeyProps = __gky11.ecdsa.pair
  542. const ecdsaSignProps = __gky11.ecdsa.sign
  543. const ecdhKeyProps = __gky11.ecdh
  544. const keysToEcdsaJwk = __gky11.jwk
  545. const sha1hash = USE('./sha1')
  546. const sha256hash = USE('./sha256')
  547. const recallCryptoKey = USE('./remember')
  548. const parseProps = USE('./parse')
  549. // Practical examples about usage found from ./test/common.js
  550. const SEA = USE('./root');
  551. SEA.work = USE('./work');
  552. SEA.sign = USE('./sign');
  553. SEA.verify = USE('./verify');
  554. SEA.encrypt = USE('./encrypt');
  555. SEA.decrypt = USE('./decrypt');
  556. SEA.random = getRandomBytes;
  557. // This is easy way to use IndexedDB, all methods are Promises
  558. // Note: Not all SEA interfaces have to support this.
  559. SEA.EasyIndexedDB = EasyIndexedDB;
  560. // This is Buffer used in SEA and usable from Gun/SEA application also.
  561. // For documentation see https://nodejs.org/api/buffer.html
  562. SEA.Buffer = Buffer;
  563. // These SEA functions support now ony Promises or
  564. // async/await (compatible) code, use those like Promises.
  565. //
  566. // Creates a wrapper library around Web Crypto API
  567. // for various AES, ECDSA, PBKDF2 functions we called above.
  568. // Calculate public key KeyID aka PGPv4 (result: 8 bytes as hex string)
  569. SEA.keyid = async (pub) => {
  570. try {
  571. // base64('base64(x):base64(y)') => Buffer(xy)
  572. const pb = Buffer.concat(
  573. Buffer.from(pub, 'base64').toString('utf8').split(':')
  574. .map((t) => Buffer.from(t, 'base64'))
  575. )
  576. // id is PGPv4 compliant raw key
  577. const id = Buffer.concat([
  578. Buffer.from([0x99, pb.length / 0x100, pb.length % 0x100]), pb
  579. ])
  580. const sha1 = await sha1hash(id)
  581. const hash = Buffer.from(sha1, 'binary')
  582. return hash.toString('hex', hash.length - 8) // 16-bit ID as hex
  583. } catch (e) {
  584. console.log(e)
  585. throw e
  586. }
  587. }
  588. // all done!
  589. // Obviously it is missing MANY necessary features. This is only an alpha release.
  590. // Please experiment with it, audit what I've done so far, and complain about what needs to be added.
  591. // SEA should be a full suite that is easy and seamless to use.
  592. // Again, scroll naer the top, where I provide an EXAMPLE of how to create a user and sign in.
  593. // Once logged in, the rest of the code you just read handled automatically signing/validating data.
  594. // But all other behavior needs to be equally easy, like opinionated ways of
  595. // Adding friends (trusted public keys), sending private messages, etc.
  596. // Cheers! Tell me what you think.
  597. var Gun = (SEA.window||{}).Gun || require('./gun');
  598. Gun.SEA = SEA;
  599. SEA.Gun = Gun;
  600. module.exports = SEA
  601. })(USE, './sea');
  602. ;USE(function(module){
  603. var SEA = USE('./sea');
  604. var Gun = SEA.Gun;
  605. // This is internal func queries public key(s) for alias.
  606. const queryGunAliases = (alias, gunRoot) => new Promise((resolve, reject) => {
  607. // load all public keys associated with the username alias we want to log in with.
  608. gunRoot.get('~@'+alias).get((rat, rev) => {
  609. rev.off();
  610. if (!rat.put) {
  611. // if no user, don't do anything.
  612. const err = 'No user!'
  613. Gun.log(err)
  614. return reject({ err })
  615. }
  616. // then figuring out all possible candidates having matching username
  617. const aliases = []
  618. let c = 0
  619. // TODO: how about having real chainable map without callback ?
  620. Gun.obj.map(rat.put, (at, pub) => {
  621. if (!pub.slice || '~' !== pub.slice(0, 1)) {
  622. // TODO: ... this would then be .filter((at, pub))
  623. return
  624. }
  625. ++c
  626. // grab the account associated with this public key.
  627. gunRoot.get(pub).get((at, ev) => {
  628. pub = pub.slice(1)
  629. ev.off()
  630. --c
  631. if (at.put){
  632. aliases.push({ pub, at })
  633. }
  634. if (!c && (c = -1)) {
  635. resolve(aliases)
  636. }
  637. })
  638. })
  639. if (!c) {
  640. reject({ err: 'Public key does not exist!' })
  641. }
  642. })
  643. })
  644. module.exports = queryGunAliases
  645. })(USE, './query');
  646. ;USE(function(module){
  647. var SEA = USE('./sea');
  648. var Gun = SEA.Gun;
  649. const queryGunAliases = USE('./query')
  650. const parseProps = USE('./parse')
  651. // This is internal User authentication func.
  652. const authenticate = async (alias, pass, gunRoot) => {
  653. // load all public keys associated with the username alias we want to log in with.
  654. const aliases = (await queryGunAliases(alias, gunRoot))
  655. .filter(({ pub, at: { put } = {} } = {}) => !!pub && !!put)
  656. // Got any?
  657. if (!aliases.length) {
  658. throw { err: 'Public key does not exist!' }
  659. }
  660. let err
  661. // then attempt to log into each one until we find ours!
  662. // (if two users have the same username AND the same password... that would be bad)
  663. const users = await Promise.all(aliases.map(async ({ at: at, pub: pub }, i) => {
  664. // attempt to PBKDF2 extend the password with the salt. (Verifying the signature gives us the plain text salt.)
  665. const auth = parseProps(at.put.auth)
  666. // NOTE: aliasquery uses `gun.get` which internally SEA.read verifies the data for us, so we do not need to re-verify it here.
  667. // SEA.verify(at.put.auth, pub).then(function(auth){
  668. try {
  669. const proof = await SEA.work(pass, auth.s)
  670. const props = { pub: pub, proof: proof, at: at }
  671. // the proof of work is evidence that we've spent some time/effort trying to log in, this slows brute force.
  672. /*
  673. MARK TO @mhelander : pub vs epub!???
  674. */
  675. const salt = auth.salt
  676. const sea = await SEA.decrypt(auth.ek, proof)
  677. if (!sea) {
  678. err = 'Failed to decrypt secret! ' + i +'/'+aliases.length;
  679. return
  680. }
  681. // now we have AES decrypted the private key, from when we encrypted it with the proof at registration.
  682. // if we were successful, then that meanswe're logged in!
  683. const priv = sea.priv
  684. const epriv = sea.epriv
  685. const epub = at.put.epub
  686. // TODO: 'salt' needed?
  687. err = null
  688. if(typeof window !== 'undefined'){
  689. var tmp = window.sessionStorage;
  690. if(tmp && gunRoot._.opt.remember){
  691. window.sessionStorage.alias = alias;
  692. window.sessionStorage.tmp = pass;
  693. }
  694. }
  695. return Object.assign(props, { priv: priv, salt: salt, epub: epub, epriv: epriv })
  696. } catch (e) {
  697. err = 'Failed to decrypt secret!'
  698. throw { err }
  699. }
  700. }))
  701. var user = Gun.list.map(users, function(acc){ if(acc){ return acc } })
  702. if (!user) {
  703. throw { err: err || 'Public key does not exist!' }
  704. }
  705. return user
  706. }
  707. module.exports = authenticate;
  708. })(USE, './authenticate');
  709. ;USE(function(module){
  710. const authsettings = USE('./settings')
  711. const SEA = USE('./sea');
  712. const Gun = SEA.Gun;
  713. //const { scope: seaIndexedDb } = USE('./indexed')
  714. // This updates sessionStorage & IndexedDB to persist authenticated "session"
  715. const updateStorage = (proof, key, pin) => async (props) => {
  716. if (!Gun.obj.has(props, 'alias')) {
  717. return // No 'alias' - we're done.
  718. }
  719. if (authsettings.validity && proof && Gun.obj.has(props, 'iat')) {
  720. props.proof = proof
  721. delete props.remember // Not stored if present
  722. const alias = props.alias
  723. const id = props.alias
  724. const remember = { alias: alias, pin: pin }
  725. try {
  726. const signed = await SEA.sign(JSON.stringify(remember), key)
  727. sessionStorage.setItem('user', alias)
  728. sessionStorage.setItem('remember', signed)
  729. const encrypted = await SEA.encrypt(props, pin)
  730. if (encrypted) {
  731. const auth = await SEA.sign(encrypted, key)
  732. await seaIndexedDb.wipe() // NO! Do not do this. It ruins other people's sessionStorage code. This is bad/wrong, commenting it out.
  733. await seaIndexedDb.put(id, { auth: auth })
  734. }
  735. return props
  736. } catch (err) {
  737. throw { err: 'Session persisting failed!' }
  738. }
  739. }
  740. // Wiping IndexedDB completely when using random PIN
  741. await seaIndexedDb.wipe() // NO! Do not do this. It ruins other people's sessionStorage code. This is bad/wrong, commenting it out.
  742. // And remove sessionStorage data
  743. sessionStorage.removeItem('user')
  744. sessionStorage.removeItem('remember')
  745. return props
  746. }
  747. module.exports = updateStorage
  748. })(USE, './update');
  749. ;USE(function(module){
  750. const SEA = USE('./sea');
  751. const Gun = SEA.Gun;
  752. const Buffer = USE('./buffer')
  753. const authsettings = USE('./settings')
  754. const updateStorage = USE('./update')
  755. // This internal func persists User authentication if so configured
  756. const authPersist = async (user, proof, opts) => {
  757. // opts = { pin: 'string' }
  758. // no opts.pin then uses random PIN
  759. // How this works:
  760. // called when app bootstraps, with wanted options
  761. // IF authsettings.validity === 0 THEN no remember-me, ever
  762. // IF PIN then signed 'remember' to window.sessionStorage and 'auth' to IndexedDB
  763. const pin = Buffer.from(
  764. (Gun.obj.has(opts, 'pin') && opts.pin) || Gun.text.random(10),
  765. 'utf8'
  766. ).toString('base64')
  767. const alias = user.alias
  768. const exp = authsettings.validity // seconds // @mhelander what is `exp`???
  769. if (proof && alias && exp) {
  770. const iat = Math.ceil(Date.now() / 1000) // seconds
  771. const remember = Gun.obj.has(opts, 'pin') || undefined // for hook - not stored
  772. const props = authsettings.hook({ alias: alias, iat: iat, exp: exp, remember: remember })
  773. const pub = user.pub
  774. const epub = user.epub
  775. const priv = user.sea.priv
  776. const epriv = user.sea.epriv
  777. const key = { pub: pub, priv: priv, epub: epub, epriv: epriv }
  778. if (props instanceof Promise) {
  779. const asyncProps = await props.then()
  780. return await updateStorage(proof, key, pin)(asyncProps)
  781. }
  782. return await updateStorage(proof, key, pin)(props)
  783. }
  784. return await updateStorage()({ alias: 'delete' })
  785. }
  786. module.exports = authPersist
  787. })(USE, './persist');
  788. ;USE(function(module){
  789. const authPersist = USE('./persist')
  790. // This internal func finalizes User authentication
  791. const finalizeLogin = async (alias, key, gunRoot, opts) => {
  792. const user = gunRoot._.user
  793. // add our credentials in-memory only to our root gun instance
  794. //var tmp = user._.tag;
  795. var opt = user._.opt;
  796. user._ = key.at.$._;
  797. user._.opt = opt;
  798. //user._.tag = tmp || user._.tag;
  799. // so that way we can use the credentials to encrypt/decrypt data
  800. // that is input/output through gun (see below)
  801. const pub = key.pub
  802. const priv = key.priv
  803. const epub = key.epub
  804. const epriv = key.epriv
  805. user._.is = user.is = {alias: alias, pub: pub};
  806. Object.assign(user._, { alias: alias, pub: pub, epub: epub, sea: { pub: pub, priv: priv, epub: epub, epriv: epriv } })
  807. //console.log("authorized", user._);
  808. // persist authentication
  809. //await authPersist(user._, key.proof, opts) // temporarily disabled
  810. // emit an auth event, useful for page redirects and stuff.
  811. try {
  812. gunRoot._.on('auth', user._)
  813. } catch (e) {
  814. console.log('Your \'auth\' callback crashed with:', e)
  815. }
  816. // returns success with the user data credentials.
  817. return user._
  818. }
  819. module.exports = finalizeLogin
  820. })(USE, './login');
  821. ;USE(function(module){
  822. const Buffer = USE('./buffer')
  823. const authsettings = USE('./settings')
  824. //const { scope: seaIndexedDb } = USE('./indexed')
  825. const queryGunAliases = USE('./query')
  826. const parseProps = USE('./parse')
  827. const updateStorage = USE('./update')
  828. const SEA = USE('./sea')
  829. const Gun = SEA.Gun;
  830. const finalizeLogin = USE('./login')
  831. // This internal func recalls persisted User authentication if so configured
  832. const authRecall = async (gunRoot, authprops) => {
  833. // window.sessionStorage only holds signed { alias, pin } !!!
  834. const remember = authprops || sessionStorage.getItem('remember')
  835. const { alias = sessionStorage.getItem('user'), pin: pIn } = authprops || {} // @mhelander what is pIn?
  836. const pin = pIn && Buffer.from(pIn, 'utf8').toString('base64')
  837. // Checks for existing proof, matching alias and expiration:
  838. const checkRememberData = async ({ proof, alias: aLias, iat, exp, remember }) => {
  839. if (!!proof && alias === aLias) {
  840. const checkNotExpired = (args) => {
  841. if (Math.floor(Date.now() / 1000) < (iat + args.exp)) {
  842. // No way hook to update 'iat'
  843. return Object.assign(args, { iat: iat, proof: proof })
  844. } else {
  845. Gun.log('Authentication expired!')
  846. }
  847. }
  848. // We're not gonna give proof to hook!
  849. const hooked = authsettings.hook({ alias: alias, iat: iat, exp: exp, remember: remember })
  850. return ((hooked instanceof Promise)
  851. && await hooked.then(checkNotExpired)) || checkNotExpired(hooked)
  852. }
  853. }
  854. const readAndDecrypt = async (data, pub, key) =>
  855. parseProps(await SEA.decrypt(await SEA.verify(data, pub), key))
  856. // Already authenticated?
  857. if (gunRoot._.user
  858. && Gun.obj.has(gunRoot._.user._, 'pub')
  859. && Gun.obj.has(gunRoot._.user._, 'sea')) {
  860. return gunRoot._.user._ // Yes, we're done here.
  861. }
  862. // No, got persisted 'alias'?
  863. if (!alias) {
  864. throw { err: 'No authentication session found!' }
  865. }
  866. // Yes, got persisted 'remember'?
  867. if (!remember) {
  868. throw { // And return proof if for matching alias
  869. err: (await seaIndexedDb.get(alias, 'auth') && authsettings.validity
  870. && 'Missing PIN and alias!') || 'No authentication session found!'
  871. }
  872. }
  873. // Yes, let's get (all?) matching aliases
  874. const aliases = (await queryGunAliases(alias, gunRoot))
  875. .filter(({ pub } = {}) => !!pub)
  876. // Got any?
  877. if (!aliases.length) {
  878. throw { err: 'Public key does not exist!' }
  879. }
  880. let err
  881. // Yes, then attempt to log into each one until we find ours!
  882. // (if two users have the same username AND the same password... that would be bad)
  883. const [ { key, at, proof, pin: newPin } = {} ] = await Promise
  884. .all(aliases.filter(({ at: { put } = {} }) => !!put)
  885. .map(async ({ at: at, pub: pub }) => {
  886. const readStorageData = async (args) => {
  887. const props = args || parseProps(await SEA.verify(remember, pub, true))
  888. let pin = props.pin
  889. let aLias = props.alias
  890. const data = (!pin && alias === aLias)
  891. // No PIN, let's try short-term proof if for matching alias
  892. ? await checkRememberData(props)
  893. // Got PIN so get IndexedDB secret if signature is ok
  894. : await checkRememberData(await readAndDecrypt(await seaIndexedDb.get(alias, 'auth'), pub, pin))
  895. pin = pin || data.pin
  896. delete data.pin
  897. return { pin: pin, data: data }
  898. }
  899. // got pub, try auth with pin & alias :: or unwrap Storage data...
  900. const __gky20 = await readStorageData(pin && { pin, alias })
  901. const data = __gky20.data
  902. const newPin = __gky20.pin
  903. const proof = data.proof
  904. if (!proof) {
  905. if (!data) {
  906. err = 'No valid authentication session found!'
  907. return
  908. }
  909. try { // Wipes IndexedDB silently
  910. await updateStorage()(data)
  911. } catch (e) {} //eslint-disable-line no-empty
  912. err = 'Expired session!'
  913. return
  914. }
  915. try { // auth parsing or decryption fails or returns empty - silently done
  916. const auth= at.put.auth.auth
  917. const sea = await SEA.decrypt(auth, proof)
  918. if (!sea) {
  919. err = 'Failed to decrypt private key!'
  920. return
  921. }
  922. const priv = sea.priv
  923. const epriv = sea.epriv
  924. const epub = at.put.epub
  925. // Success! we've found our private data!
  926. err = null
  927. return { proof: proof, at: at, pin: newPin, key: { pub: pub, priv: priv, epriv: epriv, epub: epub } }
  928. } catch (e) {
  929. err = 'Failed to decrypt private key!'
  930. return
  931. }
  932. }).filter((props) => !!props))
  933. if (!key) {
  934. throw { err: err || 'Public key does not exist!' }
  935. }
  936. // now we have AES decrypted the private key,
  937. // if we were successful, then that means we're logged in!
  938. try {
  939. await updateStorage(proof, key, newPin || pin)(key)
  940. const user = Object.assign(key, { at: at, proof: proof })
  941. const pIN = newPin || pin
  942. const pinProp = pIN && { pin: Buffer.from(pIN, 'base64').toString('utf8') }
  943. return await finalizeLogin(alias, user, gunRoot, pinProp)
  944. } catch (e) { // TODO: right log message ?
  945. Gun.log('Failed to finalize login with new password!')
  946. const { err = '' } = e || {}
  947. throw { err: 'Finalizing new password login failed! Reason: '+err }
  948. }
  949. }
  950. module.exports = authRecall
  951. })(USE, './recall');
  952. ;USE(function(module){
  953. const authPersist = USE('./persist')
  954. const authsettings = USE('./settings')
  955. //const { scope: seaIndexedDb } = USE('./indexed')
  956. // This internal func executes logout actions
  957. const authLeave = async (gunRoot, alias = gunRoot._.user._.alias) => {
  958. var user = gunRoot._.user._ || {};
  959. [ 'get', 'soul', 'ack', 'put', 'is', 'alias', 'pub', 'epub', 'sea' ].map((key) => delete user[key])
  960. if(user.$){
  961. delete user.$.is;
  962. }
  963. // Let's use default
  964. gunRoot.user();
  965. // Removes persisted authentication & CryptoKeys
  966. try {
  967. await authPersist({ alias: alias })
  968. } catch (e) {} //eslint-disable-line no-empty
  969. return { ok: 0 }
  970. }
  971. module.exports = authLeave
  972. })(USE, './leave');
  973. ;USE(function(module){
  974. var Gun = USE('./sea').Gun;
  975. Gun.chain.then = function(cb){
  976. var gun = this, p = (new Promise(function(res, rej){
  977. gun.once(res);
  978. }));
  979. return cb? p.then(cb) : p;
  980. }
  981. })(USE, './then');
  982. ;USE(function(module){
  983. var SEA = USE('./sea');
  984. var Gun = SEA.Gun;
  985. var then = USE('./then');
  986. function User(root){
  987. this._ = {$: this};
  988. }
  989. User.prototype = (function(){ function F(){}; F.prototype = Gun.chain; return new F() }()) // Object.create polyfill
  990. User.prototype.constructor = User;
  991. // let's extend the gun chain with a `user` function.
  992. // only one user can be logged in at a time, per gun instance.
  993. Gun.chain.user = function(pub){
  994. var gun = this, root = gun.back(-1), user;
  995. if(pub){ return root.get('~'+pub) }
  996. if(user = root.back('user')){ return user }
  997. var root = (root._), at = root, uuid = at.opt.uuid || Gun.state.lex;
  998. (at = (user = at.user = gun.chain(new User))._).opt = {};
  999. at.opt.uuid = function(cb){
  1000. var id = uuid(), pub = root.user;
  1001. if(!pub || !(pub = (pub._).sea) || !(pub = pub.pub)){ return id }
  1002. id = id + '~' + pub + '.';
  1003. if(cb && cb.call){ cb(null, id) }
  1004. return id;
  1005. }
  1006. return user;
  1007. }
  1008. Gun.User = User;
  1009. module.exports = User;
  1010. })(USE, './user');
  1011. ;USE(function(module){
  1012. // TODO: This needs to be split into all separate functions.
  1013. // Not just everything thrown into 'create'.
  1014. const SEA = USE('./sea')
  1015. const User = USE('./user')
  1016. const authRecall = USE('./recall')
  1017. const authsettings = USE('./settings')
  1018. const authenticate = USE('./authenticate')
  1019. const finalizeLogin = USE('./login')
  1020. const authLeave = USE('./leave')
  1021. const _initial_authsettings = USE('./settings').recall
  1022. const Gun = SEA.Gun;
  1023. var u;
  1024. // Well first we have to actually create a user. That is what this function does.
  1025. User.prototype.create = function(username, pass, cb, opt){
  1026. // TODO: Needs to be cleaned up!!!
  1027. const gunRoot = this.back(-1)
  1028. var gun = this, cat = (gun._);
  1029. cb = cb || function(){};
  1030. if(cat.ing){
  1031. cb({err: Gun.log("User is already being created or authenticated!"), wait: true});
  1032. return gun;
  1033. }
  1034. cat.ing = true;
  1035. opt = opt || {};
  1036. var resolve = function(){}, reject = resolve;
  1037. // Because more than 1 user might have the same username, we treat the alias as a list of those users.
  1038. if(cb){ resolve = reject = cb }
  1039. gunRoot.get('~@'+username).get(async (at, ev) => {
  1040. ev.off()
  1041. if (at.put && !opt.already) {
  1042. // If we can enforce that a user name is already taken, it might be nice to try, but this is not guaranteed.
  1043. const err = 'User already created!'
  1044. Gun.log(err)
  1045. cat.ing = false;
  1046. gun.leave();
  1047. return reject({ err: err })
  1048. }
  1049. const salt = Gun.text.random(64)
  1050. // pseudo-randomly create a salt, then use CryptoJS's PBKDF2 function to extend the password with it.
  1051. try {
  1052. const proof = await SEA.work(pass, salt)
  1053. // this will take some short amount of time to produce a proof, which slows brute force attacks.
  1054. const pairs = await SEA.pair()
  1055. // now we have generated a brand new ECDSA key pair for the user account.
  1056. const pub = pairs.pub
  1057. const priv = pairs.priv
  1058. const epriv = pairs.epriv
  1059. // the user's public key doesn't need to be signed. But everything else needs to be signed with it!
  1060. const alias = await SEA.sign(username, pairs)
  1061. if(u === alias){ throw SEA.err }
  1062. const epub = await SEA.sign(pairs.epub, pairs)
  1063. if(u === epub){ throw SEA.err }
  1064. // to keep the private key safe, we AES encrypt it with the proof of work!
  1065. const auth = await SEA.encrypt({ priv: priv, epriv: epriv }, proof)
  1066. .then((auth) => // TODO: So signedsalt isn't needed?
  1067. // SEA.sign(salt, pairs).then((signedsalt) =>
  1068. SEA.sign({ek: auth, s: salt}, pairs)
  1069. // )
  1070. ).catch((e) => { Gun.log('SEA.en or SEA.write calls failed!'); cat.ing = false; gun.leave(); reject(e) })
  1071. const user = { alias: alias, pub: pub, epub: epub, auth: auth }
  1072. const tmp = '~'+pairs.pub;
  1073. // awesome, now we can actually save the user with their public key as their ID.
  1074. try{
  1075. gunRoot.get(tmp).put(user)
  1076. }catch(e){console.log(e)}
  1077. // next up, we want to associate the alias with the public key. So we add it to the alias list.
  1078. gunRoot.get('~@'+username).put(Gun.obj.put({}, tmp, Gun.val.link.ify(tmp)))
  1079. // callback that the user has been created. (Note: ok = 0 because we didn't wait for disk to ack)
  1080. 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.
  1081. } catch (e) {
  1082. Gun.log('SEA.create failed!')
  1083. cat.ing = false;
  1084. gun.leave();
  1085. reject(e)
  1086. }
  1087. })
  1088. return gun; // gun chain commands must return gun chains!
  1089. }
  1090. // now that we have created a user, we want to authenticate them!
  1091. User.prototype.auth = function(alias, pass, cb, opt){
  1092. // TODO: Needs to be cleaned up!!!!
  1093. const opts = opt || (typeof cb !== 'function' && cb)
  1094. let pin = opts && opts.pin
  1095. let newpass = opts && opts.newpass
  1096. const gunRoot = this.back(-1)
  1097. cb = typeof cb === 'function' ? cb : () => {}
  1098. newpass = newpass || (opts||{}).change;
  1099. var gun = this, cat = (gun._);
  1100. if(cat.ing){
  1101. cb({err: "User is already being created or authenticated!", wait: true});
  1102. return gun;
  1103. }
  1104. cat.ing = true;
  1105. if (!pass && pin) { (async function(){
  1106. try {
  1107. var r = await authRecall(gunRoot, { alias: alias, pin: pin })
  1108. return cat.ing = false, cb(r), gun;
  1109. } catch (e) {
  1110. var err = { err: 'Auth attempt failed! Reason: No session data for alias & PIN' }
  1111. return cat.ing = false, gun.leave(), cb(err), gun;
  1112. }}())
  1113. return gun;
  1114. }
  1115. const putErr = (msg) => (e) => {
  1116. const { message, err = message || '' } = e
  1117. Gun.log(msg)
  1118. var error = { err: msg+' Reason: '+err }
  1119. return cat.ing = false, gun.leave(), cb(error), gun;
  1120. }
  1121. (async function(){ try {
  1122. const keys = await authenticate(alias, pass, gunRoot)
  1123. if (!keys) {
  1124. return putErr('Auth attempt failed!')({ message: 'No keys' })
  1125. }
  1126. const pub = keys.pub
  1127. const priv = keys.priv
  1128. const epub = keys.epub
  1129. const epriv = keys.epriv
  1130. // we're logged in!
  1131. if (newpass) {
  1132. // password update so encrypt private key using new pwd + salt
  1133. try {
  1134. const salt = Gun.text.random(64);
  1135. const encSigAuth = await SEA.work(newpass, salt)
  1136. .then((key) =>
  1137. SEA.encrypt({ priv: priv, epriv: epriv }, key)
  1138. .then((auth) => SEA.sign({ek: auth, s: salt}, keys))
  1139. )
  1140. const signedEpub = await SEA.sign(epub, keys)
  1141. const signedAlias = await SEA.sign(alias, keys)
  1142. const user = {
  1143. pub: pub,
  1144. alias: signedAlias,
  1145. auth: encSigAuth,
  1146. epub: signedEpub
  1147. }
  1148. // awesome, now we can update the user using public key ID.
  1149. gunRoot.get('~'+user.pub).put(user)
  1150. // then we're done
  1151. const login = finalizeLogin(alias, keys, gunRoot, { pin })
  1152. login.catch(putErr('Failed to finalize login with new password!'))
  1153. return cat.ing = false, cb(await login), gun
  1154. } catch (e) {
  1155. return putErr('Password set attempt failed!')(e)
  1156. }
  1157. } else {
  1158. const login = finalizeLogin(alias, keys, gunRoot, { pin: pin })
  1159. login.catch(putErr('Finalizing login failed!'))
  1160. return cat.ing = false, cb(await login), gun;
  1161. }
  1162. } catch (e) {
  1163. return putErr('Auth attempt failed!')(e)
  1164. } }());
  1165. return gun;
  1166. }
  1167. User.prototype.pair = function(){
  1168. var user = this;
  1169. if(!user.is){ return false }
  1170. return user._.sea;
  1171. }
  1172. User.prototype.leave = async function(){
  1173. var gun = this, user = (gun.back(-1)._).user;
  1174. if(user){
  1175. delete user.is;
  1176. delete user._.is;
  1177. delete user._.sea;
  1178. }
  1179. if(typeof window !== 'undefined'){
  1180. var tmp = window.sessionStorage;
  1181. delete tmp.alias;
  1182. delete tmp.tmp;
  1183. }
  1184. return await authLeave(this.back(-1))
  1185. }
  1186. // If authenticated user wants to delete his/her account, let's support it!
  1187. User.prototype.delete = async function(alias, pass){
  1188. const gunRoot = this.back(-1)
  1189. try {
  1190. const __gky40 = await authenticate(alias, pass, gunRoot)
  1191. const pub = __gky40.pub
  1192. await authLeave(gunRoot, alias)
  1193. // Delete user data
  1194. gunRoot.get('~'+pub).put(null)
  1195. // Wipe user data from memory
  1196. const { user = { _: {} } } = gunRoot._;
  1197. // TODO: is this correct way to 'logout' user from Gun.User ?
  1198. [ 'alias', 'sea', 'pub' ].map((key) => delete user._[key])
  1199. user._.is = user.is = {}
  1200. gunRoot.user()
  1201. return { ok: 0 } // TODO: proper return codes???
  1202. } catch (e) {
  1203. Gun.log('User.delete failed! Error:', e)
  1204. throw e // TODO: proper error codes???
  1205. }
  1206. }
  1207. // If authentication is to be remembered over reloads or browser closing,
  1208. // set validity time in minutes.
  1209. User.prototype.recall = async function(setvalidity, options){
  1210. const gunRoot = this.back(-1)
  1211. let validity
  1212. let opts
  1213. var o = setvalidity;
  1214. if(o && o.sessionStorage){
  1215. if(typeof window !== 'undefined'){
  1216. var tmp = window.sessionStorage;
  1217. if(tmp){
  1218. gunRoot._.opt.remember = true;
  1219. if(tmp.alias && tmp.tmp){
  1220. gunRoot.user().auth(tmp.alias, tmp.tmp);
  1221. }
  1222. }
  1223. }
  1224. return this;
  1225. }
  1226. if (!Gun.val.is(setvalidity)) {
  1227. opts = setvalidity
  1228. validity = _initial_authsettings.validity
  1229. } else {
  1230. opts = options
  1231. validity = setvalidity * 60 // minutes to seconds
  1232. }
  1233. try {
  1234. // opts = { hook: function({ iat, exp, alias, proof }) }
  1235. // iat == Date.now() when issued, exp == seconds to expire from iat
  1236. // How this works:
  1237. // called when app bootstraps, with wanted options
  1238. // IF authsettings.validity === 0 THEN no remember-me, ever
  1239. // IF PIN then signed 'remember' to window.sessionStorage and 'auth' to IndexedDB
  1240. authsettings.validity = typeof validity !== 'undefined'
  1241. ? validity : _initial_authsettings.validity
  1242. authsettings.hook = (Gun.obj.has(opts, 'hook') && typeof opts.hook === 'function')
  1243. ? opts.hook : _initial_authsettings.hook
  1244. // All is good. Should we do something more with actual recalled data?
  1245. return await authRecall(gunRoot)
  1246. } catch (e) {
  1247. const err = 'No session!'
  1248. Gun.log(err)
  1249. // NOTE! It's fine to resolve recall with reason why not successful
  1250. // instead of rejecting...
  1251. return { err: (e && e.err) || err }
  1252. }
  1253. }
  1254. User.prototype.alive = async function(){
  1255. const gunRoot = this.back(-1)
  1256. try {
  1257. // All is good. Should we do something more with actual recalled data?
  1258. await authRecall(gunRoot)
  1259. return gunRoot._.user._
  1260. } catch (e) {
  1261. const err = 'No session!'
  1262. Gun.log(err)
  1263. throw { err }
  1264. }
  1265. }
  1266. User.prototype.trust = async function(user){
  1267. // TODO: BUG!!! SEA `node` read listener needs to be async, which means core needs to be async too.
  1268. //gun.get('alice').get('age').trust(bob);
  1269. if (Gun.is(user)) {
  1270. user.get('pub').get((ctx, ev) => {
  1271. console.log(ctx, ev)
  1272. })
  1273. }
  1274. }
  1275. User.prototype.grant = function(to, cb){
  1276. console.log("`.grant` API MAY BE DELETED OR CHANGED OR RENAMED, DO NOT USE!");
  1277. var gun = this, user = gun.back(-1).user(), pair = user.pair(), path = '';
  1278. gun.back(function(at){ if(at.pub){ return } path += (at.get||'') });
  1279. (async function(){
  1280. var enc, sec = await user.get('trust').get(pair.pub).get(path).then();
  1281. sec = await SEA.decrypt(sec, pair);
  1282. if(!sec){
  1283. sec = SEA.random(16).toString();
  1284. enc = await SEA.encrypt(sec, pair);
  1285. user.get('trust').get(pair.pub).get(path).put(enc);
  1286. }
  1287. var pub = to.get('pub').then();
  1288. var epub = to.get('epub').then();
  1289. pub = await pub; epub = await epub;
  1290. var dh = await SEA.secret(epub, pair);
  1291. enc = await SEA.encrypt(sec, dh);
  1292. user.get('trust').get(pub).get(path).put(enc, cb);
  1293. }());
  1294. return gun;
  1295. }
  1296. User.prototype.secret = function(data, cb){
  1297. console.log("`.secret` API MAY BE DELETED OR CHANGED OR RENAMED, DO NOT USE!");
  1298. var gun = this, user = gun.back(-1).user(), pair = user.pair(), path = '';
  1299. gun.back(function(at){ if(at.pub){ return } path += (at.get||'') });
  1300. (async function(){
  1301. var enc, sec = await user.get('trust').get(pair.pub).get(path).then();
  1302. sec = await SEA.decrypt(sec, pair);
  1303. if(!sec){
  1304. sec = SEA.random(16).toString();
  1305. enc = await SEA.encrypt(sec, pair);
  1306. user.get('trust').get(pair.pub).get(path).put(enc);
  1307. }
  1308. enc = await SEA.encrypt(data, sec);
  1309. gun.put(enc, cb);
  1310. }());
  1311. return gun;
  1312. }
  1313. module.exports = User
  1314. })(USE, './create');
  1315. ;USE(function(module){
  1316. const SEA = USE('./sea')
  1317. const Gun = SEA.Gun;
  1318. // After we have a GUN extension to make user registration/login easy, we then need to handle everything else.
  1319. // We do this with a GUN adapter, we first listen to when a gun instance is created (and when its options change)
  1320. Gun.on('opt', function(at){
  1321. if(!at.sea){ // only add SEA once per instance, on the "at" context.
  1322. at.sea = {own: {}};
  1323. at.on('in', security, at); // now listen to all input data, acting as a firewall.
  1324. at.on('out', signature, at); // and output listeners, to encrypt outgoing data.
  1325. at.on('node', each, at);
  1326. }
  1327. this.to.next(at); // make sure to call the "next" middleware adapter.
  1328. });
  1329. // Alright, this next adapter gets run at the per node level in the graph database.
  1330. // This will let us verify that every property on a node has a value signed by a public key we trust.
  1331. // If the signature does not match, the data is just `undefined` so it doesn't get passed on.
  1332. // If it does match, then we transform the in-memory "view" of the data into its plain value (without the signature).
  1333. // Now NOTE! Some data is "system" data, not user data. Example: List of public keys, aliases, etc.
  1334. // This data is self-enforced (the value can only match its ID), but that is handled in the `security` function.
  1335. // From the self-enforced data, we can see all the edges in the graph that belong to a public key.
  1336. // Example: ~ASDF is the ID of a node with ASDF as its public key, signed alias and salt, and
  1337. // its encrypted private key, but it might also have other signed values on it like `profile = <ID>` edge.
  1338. // Using that directed edge's ID, we can then track (in memory) which IDs belong to which keys.
  1339. // Here is a problem: Multiple public keys can "claim" any node's ID, so this is dangerous!
  1340. // This means we should ONLY trust our "friends" (our key ring) public keys, not any ones.
  1341. // I have not yet added that to SEA yet in this alpha release. That is coming soon, but beware in the meanwhile!
  1342. function each(msg){ // TODO: Warning: Need to switch to `gun.on('node')`! Do not use `Gun.on('node'` in your apps!
  1343. // NOTE: THE SECURITY FUNCTION HAS ALREADY VERIFIED THE DATA!!!
  1344. // WE DO NOT NEED TO RE-VERIFY AGAIN, JUST TRANSFORM IT TO PLAINTEXT.
  1345. var to = this.to, vertex = (msg.$._).put, c = 0, d;
  1346. Gun.node.is(msg.put, function(val, key, node){ c++; // for each property on the node
  1347. // TODO: consider async/await use here...
  1348. SEA.verify(val, false, function(data){ c--; // false just extracts the plain data.
  1349. node[key] = val = data; // transform to plain value.
  1350. if(d && !c && (c = -1)){ to.next(msg) }
  1351. });
  1352. });
  1353. d = true;
  1354. if(d && !c){ to.next(msg) }
  1355. return;
  1356. }
  1357. // signature handles data output, it is a proxy to the security function.
  1358. function signature(msg){
  1359. if(msg.user){
  1360. return this.to.next(msg);
  1361. }
  1362. var ctx = this.as;
  1363. msg.user = ctx.user;
  1364. security.call(this, msg);
  1365. }
  1366. // okay! The security function handles all the heavy lifting.
  1367. // It needs to deal read and write of input and output of system data, account/public key data, and regular data.
  1368. // This is broken down into some pretty clear edge cases, let's go over them:
  1369. function security(msg){
  1370. var at = this.as, sea = at.sea, to = this.to;
  1371. if(msg.get){
  1372. // if there is a request to read data from us, then...
  1373. var soul = msg.get['#'];
  1374. if(soul){ // for now, only allow direct IDs to be read.
  1375. if(soul !== 'string'){ return to.next(msg) } // do not handle lexical cursors.
  1376. if('alias' === soul){ // Allow reading the list of usernames/aliases in the system?
  1377. return to.next(msg); // yes.
  1378. } else
  1379. if('~@' === soul.slice(0,2)){ // Allow reading the list of public keys associated with an alias?
  1380. return to.next(msg); // yes.
  1381. } else { // Allow reading everything?
  1382. return to.next(msg); // yes // TODO: No! Make this a callback/event that people can filter on.
  1383. }
  1384. }
  1385. }
  1386. if(msg.put){
  1387. // potentially parallel async operations!!!
  1388. var check = {}, each = {}, u;
  1389. each.node = function(node, soul){
  1390. if(Gun.obj.empty(node, '_')){ return check['node'+soul] = 0 } // ignore empty updates, don't reject them.
  1391. Gun.obj.map(node, each.way, {soul: soul, node: node});
  1392. };
  1393. each.way = function(val, key){
  1394. var soul = this.soul, node = this.node, tmp;
  1395. if('_' === key){ return } // ignore meta data
  1396. if('~@' === soul){ // special case for shared system data, the list of aliases.
  1397. each.alias(val, key, node, soul); return;
  1398. }
  1399. if('~@' === soul.slice(0,2)){ // special case for shared system data, the list of public keys for an alias.
  1400. each.pubs(val, key, node, soul); return;
  1401. }
  1402. if('~' === soul.slice(0,1) && 2 === (tmp = soul.slice(1)).split('.').length){ // special case, account data for a public key.
  1403. each.pub(val, key, node, soul, tmp, msg.user); return;
  1404. }
  1405. each.any(val, key, node, soul, msg.user); return;
  1406. return each.end({err: "No other data allowed!"});
  1407. };
  1408. each.alias = function(val, key, node, soul){ // Example: {_:#~@, ~@alice: {#~@alice}}
  1409. if(!val){ return each.end({err: "Data must exist!"}) } // data MUST exist
  1410. if('~@'+key === Gun.val.link.is(val)){ return check['alias'+key] = 0 } // in fact, it must be EXACTLY equal to itself
  1411. each.end({err: "Mismatching alias."}); // if it isn't, reject.
  1412. };
  1413. each.pubs = function(val, key, node, soul){ // Example: {_:#~@alice, ~asdf: {#~asdf}}
  1414. if(!val){ return each.end({err: "Alias must exist!"}) } // data MUST exist
  1415. if(key === Gun.val.link.is(val)){ return check['pubs'+soul+key] = 0 } // and the ID must be EXACTLY equal to its property
  1416. each.end({err: "Alias must match!"}); // that way nobody can tamper with the list of public keys.
  1417. };
  1418. each.pub = function(val, key, node, soul, pub, user){ // Example: {_:#~asdf, hello:SEA{'world',fdsa}}
  1419. if('pub' === key){
  1420. if(val === pub){ return (check['pub'+soul+key] = 0) } // the account MUST match `pub` property that equals the ID of the public key.
  1421. return each.end({err: "Account must match!"});
  1422. }
  1423. check['user'+soul+key] = 1;
  1424. if(user && (user = user._) && user.sea && pub === user.pub){
  1425. //var id = Gun.text.random(3);
  1426. SEA.sign(val, user.sea, function(data){ var rel;
  1427. if(u === data){ return each.end({err: SEA.err || 'Pub signature fail.'}) }
  1428. if(rel = Gun.val.link.is(val)){
  1429. (at.sea.own[rel] = at.sea.own[rel] || {})[pub] = true;
  1430. }
  1431. node[key] = data;
  1432. check['user'+soul+key] = 0;
  1433. each.end({ok: 1});
  1434. });
  1435. // TODO: Handle error!!!!
  1436. return;
  1437. }
  1438. SEA.verify(val, pub, function(data){ var rel, tmp;
  1439. if(u === data){ // make sure the signature matches the account it claims to be on.
  1440. return each.end({err: "Unverified data."}); // reject any updates that are signed with a mismatched account.
  1441. }
  1442. if((rel = Gun.val.link.is(data)) && pub === relpub(rel)){
  1443. (at.sea.own[rel] = at.sea.own[rel] || {})[pub] = true;
  1444. }
  1445. check['user'+soul+key] = 0;
  1446. each.end({ok: 1});
  1447. });
  1448. };
  1449. function relpub(s){
  1450. if(!s){ return }
  1451. s = s.split('~');
  1452. if(!s || !(s = s[1])){ return }
  1453. s = s.split('.');
  1454. if(!s || 2 > s.length){ return }
  1455. s = s.slice(0,2).join('.');
  1456. return s;
  1457. }
  1458. each.any = function(val, key, node, soul, user){ var tmp, pub;
  1459. if(!user || !(user = user._) || !(user = user.sea)){
  1460. if(tmp = relpub(soul)){
  1461. check['any'+soul+key] = 1;
  1462. SEA.verify(val, pub = tmp, function(data){ var rel;
  1463. if(!data){ return each.end({err: "Mismatched owner on '" + key + "'."}) }
  1464. if((rel = Gun.val.link.is(data)) && pub === relpub(rel)){
  1465. (at.sea.own[rel] = at.sea.own[rel] || {})[pub] = true;
  1466. }
  1467. check['any'+soul+key] = 0;
  1468. each.end({ok: 1});
  1469. });
  1470. return;
  1471. }
  1472. check['any'+soul+key] = 1;
  1473. at.on('secure', function(msg){ this.off();
  1474. check['any'+soul+key] = 0;
  1475. if(at.opt.secure){ msg = null }
  1476. each.end(msg || {err: "Data cannot be modified."});
  1477. }).on.on('secure', msg);
  1478. //each.end({err: "Data cannot be modified."});
  1479. return;
  1480. }
  1481. if(!(tmp = relpub(soul))){
  1482. if(at.opt.secure){
  1483. each.end({err: "Soul is missing public key at '" + key + "'."});
  1484. return;
  1485. }
  1486. if(val && val.slice && 'SEA{' === (val).slice(0,4)){
  1487. check['any'+soul+key] = 0;
  1488. each.end({ok: 1});
  1489. return;
  1490. }
  1491. //check['any'+soul+key] = 1;
  1492. //SEA.sign(val, user, function(data){
  1493. // if(u === data){ return each.end({err: 'Any signature failed.'}) }
  1494. // node[key] = data;
  1495. check['any'+soul+key] = 0;
  1496. each.end({ok: 1});
  1497. //});
  1498. return;
  1499. }
  1500. var pub = tmp;
  1501. if(pub !== user.pub){
  1502. each.any(val, key, node, soul);
  1503. return;
  1504. }
  1505. /*var other = Gun.obj.map(at.sea.own[soul], function(v, p){
  1506. if(user.pub !== p){ return p }
  1507. });
  1508. if(other){
  1509. each.any(val, key, node, soul);
  1510. return;
  1511. }*/
  1512. check['any'+soul+key] = 1;
  1513. SEA.sign(val, user, function(data){
  1514. if(u === data){ return each.end({err: 'My signature fail.'}) }
  1515. node[key] = data;
  1516. check['any'+soul+key] = 0;
  1517. each.end({ok: 1});
  1518. });
  1519. }
  1520. each.end = function(ctx){ // TODO: Can't you just switch this to each.end = cb?
  1521. if(each.err){ return }
  1522. if((each.err = ctx.err) || ctx.no){
  1523. console.log('NO!', each.err, msg.put);
  1524. return;
  1525. }
  1526. if(!each.end.ed){ return }
  1527. if(Gun.obj.map(check, function(no){
  1528. if(no){ return true }
  1529. })){ return }
  1530. to.next(msg);
  1531. };
  1532. Gun.obj.map(msg.put, each.node);
  1533. each.end({end: each.end.ed = true});
  1534. return; // need to manually call next after async.
  1535. }
  1536. to.next(msg); // pass forward any data we do not know how to handle or process (this allows custom security protocols).
  1537. }
  1538. })(USE, './index');
  1539. }());