gun-eth 1.4.21 → 1.4.23

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,14 +1,1530 @@
1
1
  import Gun from 'gun';
2
2
  export { default } from 'gun';
3
- import SEA from 'gun/sea.js';
4
3
  import { ethers } from 'ethers';
5
4
 
6
- var STEALTH_ANNOUNCER_ADDRESS$1 = "";
7
- var PROOF_OF_INTEGRITY_ADDRESS = "";
8
- var require$$0 = {
9
- STEALTH_ANNOUNCER_ADDRESS: STEALTH_ANNOUNCER_ADDRESS$1,
10
- PROOF_OF_INTEGRITY_ADDRESS: PROOF_OF_INTEGRITY_ADDRESS
11
- };
5
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
6
+
7
+ function getDefaultExportFromCjs (x) {
8
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
9
+ }
10
+
11
+ function commonjsRequire(path) {
12
+ throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
13
+ }
14
+
15
+ var sea = {exports: {}};
16
+
17
+ sea.exports;
18
+
19
+ (function (module) {
20
+ (function(){
21
+
22
+ /* UNBUILD */
23
+ function USE(arg, req){
24
+ return req? commonjsRequire(arg) : arg.slice? USE[R(arg)] : function(mod, path){
25
+ arg(mod = {exports: {}});
26
+ USE[R(path)] = mod.exports;
27
+ }
28
+ function R(p){
29
+ return p.split('/').slice(-1).toString().replace('.js','');
30
+ }
31
+ }
32
+ { var MODULE = module; }
33
+ USE(function(module){
34
+ // Security, Encryption, and Authorization: SEA.js
35
+ // MANDATORY READING: https://gun.eco/explainers/data/security.html
36
+ // IT IS IMPLEMENTED IN A POLYFILL/SHIM APPROACH.
37
+ // THIS IS AN EARLY ALPHA!
38
+
39
+ if(typeof self !== "undefined"){ module.window = self; } // should be safe for at least browser/worker/nodejs, need to check other envs like RN etc.
40
+ if(typeof window !== "undefined"){ module.window = window; }
41
+
42
+ var tmp = module.window || module, u;
43
+ var SEA = tmp.SEA || {};
44
+
45
+ if(SEA.window = module.window){ SEA.window.SEA = SEA; }
46
+
47
+ try{ if(u+'' !== typeof MODULE){ MODULE.exports = SEA; } }catch(e){}
48
+ module.exports = SEA;
49
+ })(USE, './root');
50
+ USE(function(module){
51
+ var SEA = USE('./root');
52
+ try{ if(SEA.window){
53
+ if(location.protocol.indexOf('s') < 0
54
+ && location.host.indexOf('localhost') < 0
55
+ && ! /^127\.\d+\.\d+\.\d+$/.test(location.hostname)
56
+ && location.protocol.indexOf('file:') < 0){
57
+ console.warn('HTTPS needed for WebCrypto in SEA, redirecting...');
58
+ location.protocol = 'https:'; // WebCrypto does NOT work without HTTPS!
59
+ }
60
+ } }catch(e){}
61
+ })(USE, './https');
62
+ USE(function(module){
63
+ var u;
64
+ if(u+''== typeof btoa){
65
+ if(u+'' == typeof Buffer){
66
+ try{ commonjsGlobal.Buffer = USE("buffer", 1).Buffer; }catch(e){ console.log("Please `npm install buffer` or add it to your package.json !"); }
67
+ }
68
+ commonjsGlobal.btoa = function(data){ return Buffer.from(data, "binary").toString("base64") };
69
+ commonjsGlobal.atob = function(data){ return Buffer.from(data, "base64").toString("binary") };
70
+ }
71
+ })(USE, './base64');
72
+ USE(function(module){
73
+ USE('./base64');
74
+ // This is Array extended to have .toString(['utf8'|'hex'|'base64'])
75
+ function SeaArray() {}
76
+ Object.assign(SeaArray, { from: Array.from });
77
+ SeaArray.prototype = Object.create(Array.prototype);
78
+ SeaArray.prototype.toString = function(enc, start, end) { enc = enc || 'utf8'; start = start || 0;
79
+ const length = this.length;
80
+ if (enc === 'hex') {
81
+ const buf = new Uint8Array(this);
82
+ return [ ...Array(((end && (end + 1)) || length) - start).keys()]
83
+ .map((i) => buf[ i + start ].toString(16).padStart(2, '0')).join('')
84
+ }
85
+ if (enc === 'utf8') {
86
+ return Array.from(
87
+ { length: (end || length) - start },
88
+ (_, i) => String.fromCharCode(this[ i + start])
89
+ ).join('')
90
+ }
91
+ if (enc === 'base64') {
92
+ return btoa(this)
93
+ }
94
+ };
95
+ module.exports = SeaArray;
96
+ })(USE, './array');
97
+ USE(function(module){
98
+ USE('./base64');
99
+ // This is Buffer implementation used in SEA. Functionality is mostly
100
+ // compatible with NodeJS 'safe-buffer' and is used for encoding conversions
101
+ // between binary and 'hex' | 'utf8' | 'base64'
102
+ // See documentation and validation for safe implementation in:
103
+ // https://github.com/feross/safe-buffer#update
104
+ var SeaArray = USE('./array');
105
+ function SafeBuffer(...props) {
106
+ console.warn('new SafeBuffer() is depreciated, please use SafeBuffer.from()');
107
+ return SafeBuffer.from(...props)
108
+ }
109
+ SafeBuffer.prototype = Object.create(Array.prototype);
110
+ Object.assign(SafeBuffer, {
111
+ // (data, enc) where typeof data === 'string' then enc === 'utf8'|'hex'|'base64'
112
+ from() {
113
+ if (!Object.keys(arguments).length || arguments[0]==null) {
114
+ throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
115
+ }
116
+ const input = arguments[0];
117
+ let buf;
118
+ if (typeof input === 'string') {
119
+ const enc = arguments[1] || 'utf8';
120
+ if (enc === 'hex') {
121
+ const bytes = input.match(/([\da-fA-F]{2})/g)
122
+ .map((byte) => parseInt(byte, 16));
123
+ if (!bytes || !bytes.length) {
124
+ throw new TypeError('Invalid first argument for type \'hex\'.')
125
+ }
126
+ buf = SeaArray.from(bytes);
127
+ } else if (enc === 'utf8' || 'binary' === enc) { // EDIT BY MARK: I think this is safe, tested it against a couple "binary" strings. This lets SafeBuffer match NodeJS Buffer behavior more where it safely btoas regular strings.
128
+ const length = input.length;
129
+ const words = new Uint16Array(length);
130
+ Array.from({ length: length }, (_, i) => words[i] = input.charCodeAt(i));
131
+ buf = SeaArray.from(words);
132
+ } else if (enc === 'base64') {
133
+ const dec = atob(input);
134
+ const length = dec.length;
135
+ const bytes = new Uint8Array(length);
136
+ Array.from({ length: length }, (_, i) => bytes[i] = dec.charCodeAt(i));
137
+ buf = SeaArray.from(bytes);
138
+ } else if (enc === 'binary') { // deprecated by above comment
139
+ buf = SeaArray.from(input); // some btoas were mishandled.
140
+ } else {
141
+ console.info('SafeBuffer.from unknown encoding: '+enc);
142
+ }
143
+ return buf
144
+ }
145
+ input.byteLength; // what is going on here? FOR MARTTI
146
+ const length = input.byteLength ? input.byteLength : input.length;
147
+ if (length) {
148
+ let buf;
149
+ if (input instanceof ArrayBuffer) {
150
+ buf = new Uint8Array(input);
151
+ }
152
+ return SeaArray.from(buf || input)
153
+ }
154
+ },
155
+ // This is 'safe-buffer.alloc' sans encoding support
156
+ alloc(length, fill = 0 /*, enc*/ ) {
157
+ return SeaArray.from(new Uint8Array(Array.from({ length: length }, () => fill)))
158
+ },
159
+ // This is normal UNSAFE 'buffer.alloc' or 'new Buffer(length)' - don't use!
160
+ allocUnsafe(length) {
161
+ return SeaArray.from(new Uint8Array(Array.from({ length : length })))
162
+ },
163
+ // This puts together array of array like members
164
+ concat(arr) { // octet array
165
+ if (!Array.isArray(arr)) {
166
+ throw new TypeError('First argument must be Array containing ArrayBuffer or Uint8Array instances.')
167
+ }
168
+ return SeaArray.from(arr.reduce((ret, item) => ret.concat(Array.from(item)), []))
169
+ }
170
+ });
171
+ SafeBuffer.prototype.from = SafeBuffer.from;
172
+ SafeBuffer.prototype.toString = SeaArray.prototype.toString;
173
+
174
+ module.exports = SafeBuffer;
175
+ })(USE, './buffer');
176
+ USE(function(module){
177
+ const SEA = USE('./root');
178
+ const api = {Buffer: USE('./buffer')};
179
+ var o = {}, u;
180
+
181
+ // ideally we can move away from JSON entirely? unlikely due to compatibility issues... oh well.
182
+ JSON.parseAsync = JSON.parseAsync || function(t,cb,r){ var u; try{ cb(u, JSON.parse(t,r)); }catch(e){ cb(e); } };
183
+ JSON.stringifyAsync = JSON.stringifyAsync || function(v,cb,r,s){ var u; try{ cb(u, JSON.stringify(v,r,s)); }catch(e){ cb(e); } };
184
+
185
+ api.parse = function(t,r){ return new Promise(function(res, rej){
186
+ JSON.parseAsync(t,function(err, raw){ err? rej(err) : res(raw); },r);
187
+ })};
188
+ api.stringify = function(v,r,s){ return new Promise(function(res, rej){
189
+ JSON.stringifyAsync(v,function(err, raw){ err? rej(err) : res(raw); },r,s);
190
+ })};
191
+
192
+ if(SEA.window){
193
+ api.crypto = SEA.window.crypto || SEA.window.msCrypto;
194
+ api.subtle = (api.crypto||o).subtle || (api.crypto||o).webkitSubtle;
195
+ api.TextEncoder = SEA.window.TextEncoder;
196
+ api.TextDecoder = SEA.window.TextDecoder;
197
+ api.random = (len) => api.Buffer.from(api.crypto.getRandomValues(new Uint8Array(api.Buffer.alloc(len))));
198
+ }
199
+ if(!api.TextDecoder)
200
+ {
201
+ const { TextEncoder, TextDecoder } = USE((u+'' == typeof MODULE?'.':'')+'./lib/text-encoding', 1);
202
+ api.TextDecoder = TextDecoder;
203
+ api.TextEncoder = TextEncoder;
204
+ }
205
+ if(!api.crypto)
206
+ {
207
+ try
208
+ {
209
+ var crypto = USE('crypto', 1);
210
+ Object.assign(api, {
211
+ crypto,
212
+ random: (len) => api.Buffer.from(crypto.randomBytes(len))
213
+ });
214
+ const { Crypto: WebCrypto } = USE('@peculiar/webcrypto', 1);
215
+ api.ossl = api.subtle = new WebCrypto({directory: 'ossl'}).subtle; // ECDH
216
+ }
217
+ catch(e){
218
+ console.log("Please `npm install @peculiar/webcrypto` or add it to your package.json !");
219
+ }}
220
+
221
+ module.exports = api;
222
+ })(USE, './shim');
223
+ USE(function(module){
224
+ var SEA = USE('./root');
225
+ var shim = USE('./shim');
226
+ var s = {};
227
+ s.pbkdf2 = {hash: {name : 'SHA-256'}, iter: 100000, ks: 64};
228
+ s.ecdsa = {
229
+ pair: {name: 'ECDSA', namedCurve: 'P-256'},
230
+ sign: {name: 'ECDSA', hash: {name: 'SHA-256'}}
231
+ };
232
+ s.ecdh = {name: 'ECDH', namedCurve: 'P-256'};
233
+
234
+ // This creates Web Cryptography API compliant JWK for sign/verify purposes
235
+ s.jwk = function(pub, d){ // d === priv
236
+ pub = pub.split('.');
237
+ var x = pub[0], y = pub[1];
238
+ var jwk = {kty: "EC", crv: "P-256", x: x, y: y, ext: true};
239
+ jwk.key_ops = d ? ['sign'] : ['verify'];
240
+ if(d){ jwk.d = d; }
241
+ return jwk;
242
+ };
243
+
244
+ s.keyToJwk = function(keyBytes) {
245
+ const keyB64 = keyBytes.toString('base64');
246
+ const k = keyB64.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');
247
+ return { kty: 'oct', k: k, ext: false, alg: 'A256GCM' };
248
+ };
249
+
250
+ s.recall = {
251
+ validity: 12 * 60 * 60, // internally in seconds : 12 hours
252
+ hook: function(props){ return props } // { iat, exp, alias, remember } // or return new Promise((resolve, reject) => resolve(props)
253
+ };
254
+
255
+ s.check = function(t){ return (typeof t == 'string') && ('SEA{' === t.slice(0,4)) };
256
+ s.parse = async function p(t){ try {
257
+ var yes = (typeof t == 'string');
258
+ if(yes && 'SEA{' === t.slice(0,4)){ t = t.slice(3); }
259
+ return yes ? await shim.parse(t) : t;
260
+ } catch (e) {}
261
+ return t;
262
+ };
263
+
264
+ SEA.opt = s;
265
+ module.exports = s;
266
+ })(USE, './settings');
267
+ USE(function(module){
268
+ var shim = USE('./shim');
269
+ module.exports = async function(d, o){
270
+ var t = (typeof d == 'string')? d : await shim.stringify(d);
271
+ var hash = await shim.subtle.digest({name: o||'SHA-256'}, new shim.TextEncoder().encode(t));
272
+ return shim.Buffer.from(hash);
273
+ };
274
+ })(USE, './sha256');
275
+ USE(function(module){
276
+ // This internal func returns SHA-1 hashed data for KeyID generation
277
+ const __shim = USE('./shim');
278
+ const subtle = __shim.subtle;
279
+ const ossl = __shim.ossl ? __shim.ossl : subtle;
280
+ const sha1hash = (b) => ossl.digest({name: 'SHA-1'}, new ArrayBuffer(b));
281
+ module.exports = sha1hash;
282
+ })(USE, './sha1');
283
+ USE(function(module){
284
+ var SEA = USE('./root');
285
+ var shim = USE('./shim');
286
+ var S = USE('./settings');
287
+ var sha = USE('./sha256');
288
+ var u;
289
+
290
+ SEA.work = SEA.work || (async (data, pair, cb, opt) => { try { // used to be named `proof`
291
+ var salt = (pair||{}).epub || pair; // epub not recommended, salt should be random!
292
+ opt = opt || {};
293
+ if(salt instanceof Function){
294
+ cb = salt;
295
+ salt = u;
296
+ }
297
+ data = (typeof data == 'string')? data : await shim.stringify(data);
298
+ if('sha' === (opt.name||'').toLowerCase().slice(0,3)){
299
+ var rsha = shim.Buffer.from(await sha(data, opt.name), 'binary').toString(opt.encode || 'base64');
300
+ if(cb){ try{ cb(rsha); }catch(e){console.log(e);} }
301
+ return rsha;
302
+ }
303
+ salt = salt || shim.random(9);
304
+ var key = await (shim.ossl || shim.subtle).importKey('raw', new shim.TextEncoder().encode(data), {name: opt.name || 'PBKDF2'}, false, ['deriveBits']);
305
+ var work = await (shim.ossl || shim.subtle).deriveBits({
306
+ name: opt.name || 'PBKDF2',
307
+ iterations: opt.iterations || S.pbkdf2.iter,
308
+ salt: new shim.TextEncoder().encode(opt.salt || salt),
309
+ hash: opt.hash || S.pbkdf2.hash,
310
+ }, key, opt.length || (S.pbkdf2.ks * 8));
311
+ data = shim.random(data.length); // Erase data in case of passphrase
312
+ var r = shim.Buffer.from(work, 'binary').toString(opt.encode || 'base64');
313
+ if(cb){ try{ cb(r); }catch(e){console.log(e);} }
314
+ return r;
315
+ } catch(e) {
316
+ console.log(e);
317
+ SEA.err = e;
318
+ if(SEA.throw){ throw e }
319
+ if(cb){ cb(); }
320
+ return;
321
+ }});
322
+
323
+ module.exports = SEA.work;
324
+ })(USE, './work');
325
+ USE(function(module){
326
+ var SEA = USE('./root');
327
+ var shim = USE('./shim');
328
+ USE('./settings');
329
+
330
+ SEA.name = SEA.name || (async (cb, opt) => { try {
331
+ if(cb){ try{ cb(); }catch(e){console.log(e);} }
332
+ return;
333
+ } catch(e) {
334
+ console.log(e);
335
+ SEA.err = e;
336
+ if(SEA.throw){ throw e }
337
+ if(cb){ cb(); }
338
+ return;
339
+ }});
340
+
341
+ //SEA.pair = async (data, proof, cb) => { try {
342
+ SEA.pair = SEA.pair || (async (cb, opt) => { try {
343
+
344
+ var ecdhSubtle = shim.ossl || shim.subtle;
345
+ // First: ECDSA keys for signing/verifying...
346
+ var sa = await shim.subtle.generateKey({name: 'ECDSA', namedCurve: 'P-256'}, true, [ 'sign', 'verify' ])
347
+ .then(async (keys) => {
348
+ // privateKey scope doesn't leak out from here!
349
+ //const { d: priv } = await shim.subtle.exportKey('jwk', keys.privateKey)
350
+ var key = {};
351
+ key.priv = (await shim.subtle.exportKey('jwk', keys.privateKey)).d;
352
+ var pub = await shim.subtle.exportKey('jwk', keys.publicKey);
353
+ //const pub = Buff.from([ x, y ].join(':')).toString('base64') // old
354
+ key.pub = pub.x+'.'+pub.y; // new
355
+ // x and y are already base64
356
+ // pub is UTF8 but filename/URL safe (https://www.ietf.org/rfc/rfc3986.txt)
357
+ // but split on a non-base64 letter.
358
+ return key;
359
+ });
360
+
361
+ // To include PGPv4 kind of keyId:
362
+ // const pubId = await SEA.keyid(keys.pub)
363
+ // Next: ECDH keys for encryption/decryption...
364
+
365
+ try{
366
+ var dh = await ecdhSubtle.generateKey({name: 'ECDH', namedCurve: 'P-256'}, true, ['deriveKey'])
367
+ .then(async (keys) => {
368
+ // privateKey scope doesn't leak out from here!
369
+ var key = {};
370
+ key.epriv = (await ecdhSubtle.exportKey('jwk', keys.privateKey)).d;
371
+ var pub = await ecdhSubtle.exportKey('jwk', keys.publicKey);
372
+ //const epub = Buff.from([ ex, ey ].join(':')).toString('base64') // old
373
+ key.epub = pub.x+'.'+pub.y; // new
374
+ // ex and ey are already base64
375
+ // epub is UTF8 but filename/URL safe (https://www.ietf.org/rfc/rfc3986.txt)
376
+ // but split on a non-base64 letter.
377
+ return key;
378
+ });
379
+ }catch(e){
380
+ if(SEA.window){ throw e }
381
+ if(e == 'Error: ECDH is not a supported algorithm'){ console.log('Ignoring ECDH...'); }
382
+ else { throw e }
383
+ } dh = dh || {};
384
+
385
+ var r = { pub: sa.pub, priv: sa.priv, /* pubId, */ epub: dh.epub, epriv: dh.epriv };
386
+ if(cb){ try{ cb(r); }catch(e){console.log(e);} }
387
+ return r;
388
+ } catch(e) {
389
+ console.log(e);
390
+ SEA.err = e;
391
+ if(SEA.throw){ throw e }
392
+ if(cb){ cb(); }
393
+ return;
394
+ }});
395
+
396
+ module.exports = SEA.pair;
397
+ })(USE, './pair');
398
+ USE(function(module){
399
+ var SEA = USE('./root');
400
+ var shim = USE('./shim');
401
+ var S = USE('./settings');
402
+ var sha = USE('./sha256');
403
+ var u;
404
+
405
+ SEA.sign = SEA.sign || (async (data, pair, cb, opt) => { try {
406
+ opt = opt || {};
407
+ if(!(pair||opt).priv){
408
+ if(!SEA.I){ throw 'No signing key.' }
409
+ pair = await SEA.I(null, {what: data, how: 'sign', why: opt.why});
410
+ }
411
+ if(u === data){ throw '`undefined` not allowed.' }
412
+ var json = await S.parse(data);
413
+ var check = opt.check = opt.check || json;
414
+ if(SEA.verify && (SEA.opt.check(check) || (check && check.s && check.m))
415
+ && u !== await SEA.verify(check, pair)){ // don't sign if we already signed it.
416
+ var r = await S.parse(check);
417
+ if(!opt.raw){ r = 'SEA' + await shim.stringify(r); }
418
+ if(cb){ try{ cb(r); }catch(e){console.log(e);} }
419
+ return r;
420
+ }
421
+ var pub = pair.pub;
422
+ var priv = pair.priv;
423
+ var jwk = S.jwk(pub, priv);
424
+ var hash = await sha(json);
425
+ var sig = await (shim.ossl || shim.subtle).importKey('jwk', jwk, {name: 'ECDSA', namedCurve: 'P-256'}, false, ['sign'])
426
+ .then((key) => (shim.ossl || shim.subtle).sign({name: 'ECDSA', hash: {name: 'SHA-256'}}, key, new Uint8Array(hash))); // privateKey scope doesn't leak out from here!
427
+ var r = {m: json, s: shim.Buffer.from(sig, 'binary').toString(opt.encode || 'base64')};
428
+ if(!opt.raw){ r = 'SEA' + await shim.stringify(r); }
429
+
430
+ if(cb){ try{ cb(r); }catch(e){console.log(e);} }
431
+ return r;
432
+ } catch(e) {
433
+ console.log(e);
434
+ SEA.err = e;
435
+ if(SEA.throw){ throw e }
436
+ if(cb){ cb(); }
437
+ return;
438
+ }});
439
+
440
+ module.exports = SEA.sign;
441
+ })(USE, './sign');
442
+ USE(function(module){
443
+ var SEA = USE('./root');
444
+ var shim = USE('./shim');
445
+ var S = USE('./settings');
446
+ var sha = USE('./sha256');
447
+ var u;
448
+
449
+ SEA.verify = SEA.verify || (async (data, pair, cb, opt) => { try {
450
+ var json = await S.parse(data);
451
+ if(false === pair){ // don't verify!
452
+ var raw = await S.parse(json.m);
453
+ if(cb){ try{ cb(raw); }catch(e){console.log(e);} }
454
+ return raw;
455
+ }
456
+ opt = opt || {};
457
+ // SEA.I // verify is free! Requires no user permission.
458
+ var pub = pair.pub || pair;
459
+ var key = SEA.opt.slow_leak? await SEA.opt.slow_leak(pub) : await (shim.ossl || shim.subtle).importKey('jwk', S.jwk(pub), {name: 'ECDSA', namedCurve: 'P-256'}, false, ['verify']);
460
+ var hash = await sha(json.m);
461
+ var buf, sig, check, tmp; try{
462
+ buf = shim.Buffer.from(json.s, opt.encode || 'base64'); // NEW DEFAULT!
463
+ sig = new Uint8Array(buf);
464
+ check = await (shim.ossl || shim.subtle).verify({name: 'ECDSA', hash: {name: 'SHA-256'}}, key, sig, new Uint8Array(hash));
465
+ if(!check){ throw "Signature did not match." }
466
+ }catch(e){
467
+ if(SEA.opt.fallback){
468
+ return await SEA.opt.fall_verify(data, pair, cb, opt);
469
+ }
470
+ }
471
+ var r = check? await S.parse(json.m) : u;
472
+
473
+ if(cb){ try{ cb(r); }catch(e){console.log(e);} }
474
+ return r;
475
+ } catch(e) {
476
+ console.log(e); // mismatched owner FOR MARTTI
477
+ SEA.err = e;
478
+ if(SEA.throw){ throw e }
479
+ if(cb){ cb(); }
480
+ return;
481
+ }});
482
+
483
+ module.exports = SEA.verify;
484
+ // legacy & ossl memory leak mitigation:
485
+
486
+ var knownKeys = {};
487
+ SEA.opt.slow_leak = pair => {
488
+ if (knownKeys[pair]) return knownKeys[pair];
489
+ var jwk = S.jwk(pair);
490
+ knownKeys[pair] = (shim.ossl || shim.subtle).importKey("jwk", jwk, {name: 'ECDSA', namedCurve: 'P-256'}, false, ["verify"]);
491
+ return knownKeys[pair];
492
+ };
493
+
494
+ var O = SEA.opt;
495
+ SEA.opt.fall_verify = async function(data, pair, cb, opt, f){
496
+ if(f === SEA.opt.fallback){ throw "Signature did not match" } f = f || 1;
497
+ var tmp = data||'';
498
+ data = SEA.opt.unpack(data) || data;
499
+ var json = await S.parse(data), pub = pair.pub || pair, key = await SEA.opt.slow_leak(pub);
500
+ var hash = (f <= SEA.opt.fallback)? shim.Buffer.from(await shim.subtle.digest({name: 'SHA-256'}, new shim.TextEncoder().encode(await S.parse(json.m)))) : await sha(json.m); // this line is old bad buggy code but necessary for old compatibility.
501
+ var buf; var sig; var check; try{
502
+ buf = shim.Buffer.from(json.s, opt.encode || 'base64'); // NEW DEFAULT!
503
+ sig = new Uint8Array(buf);
504
+ check = await (shim.ossl || shim.subtle).verify({name: 'ECDSA', hash: {name: 'SHA-256'}}, key, sig, new Uint8Array(hash));
505
+ if(!check){ throw "Signature did not match." }
506
+ }catch(e){ try{
507
+ buf = shim.Buffer.from(json.s, 'utf8'); // AUTO BACKWARD OLD UTF8 DATA!
508
+ sig = new Uint8Array(buf);
509
+ check = await (shim.ossl || shim.subtle).verify({name: 'ECDSA', hash: {name: 'SHA-256'}}, key, sig, new Uint8Array(hash));
510
+ }catch(e){
511
+ if(!check){ throw "Signature did not match." }
512
+ }
513
+ }
514
+ var r = check? await S.parse(json.m) : u;
515
+ O.fall_soul = tmp['#']; O.fall_key = tmp['.']; O.fall_val = data; O.fall_state = tmp['>'];
516
+ if(cb){ try{ cb(r); }catch(e){console.log(e);} }
517
+ return r;
518
+ };
519
+ SEA.opt.fallback = 2;
520
+
521
+ })(USE, './verify');
522
+ USE(function(module){
523
+ var shim = USE('./shim');
524
+ var S = USE('./settings');
525
+ var sha256hash = USE('./sha256');
526
+
527
+ const importGen = async (key, salt, opt) => {
528
+ const combo = key + (salt || shim.random(8)).toString('utf8'); // new
529
+ const hash = shim.Buffer.from(await sha256hash(combo), 'binary');
530
+
531
+ const jwkKey = S.keyToJwk(hash);
532
+ return await shim.subtle.importKey('jwk', jwkKey, {name:'AES-GCM'}, false, ['encrypt', 'decrypt'])
533
+ };
534
+ module.exports = importGen;
535
+ })(USE, './aeskey');
536
+ USE(function(module){
537
+ var SEA = USE('./root');
538
+ var shim = USE('./shim');
539
+ USE('./settings');
540
+ var aeskey = USE('./aeskey');
541
+ var u;
542
+
543
+ SEA.encrypt = SEA.encrypt || (async (data, pair, cb, opt) => { try {
544
+ opt = opt || {};
545
+ var key = (pair||opt).epriv || pair;
546
+ if(u === data){ throw '`undefined` not allowed.' }
547
+ if(!key){
548
+ if(!SEA.I){ throw 'No encryption key.' }
549
+ pair = await SEA.I(null, {what: data, how: 'encrypt', why: opt.why});
550
+ key = pair.epriv || pair;
551
+ }
552
+ var msg = (typeof data == 'string')? data : await shim.stringify(data);
553
+ var rand = {s: shim.random(9), iv: shim.random(15)}; // consider making this 9 and 15 or 18 or 12 to reduce == padding.
554
+ var ct = await aeskey(key, rand.s, opt).then((aes) => (/*shim.ossl ||*/ shim.subtle).encrypt({ // Keeping the AES key scope as private as possible...
555
+ name: opt.name || 'AES-GCM', iv: new Uint8Array(rand.iv)
556
+ }, aes, new shim.TextEncoder().encode(msg)));
557
+ var r = {
558
+ ct: shim.Buffer.from(ct, 'binary').toString(opt.encode || 'base64'),
559
+ iv: rand.iv.toString(opt.encode || 'base64'),
560
+ s: rand.s.toString(opt.encode || 'base64')
561
+ };
562
+ if(!opt.raw){ r = 'SEA' + await shim.stringify(r); }
563
+
564
+ if(cb){ try{ cb(r); }catch(e){console.log(e);} }
565
+ return r;
566
+ } catch(e) {
567
+ console.log(e);
568
+ SEA.err = e;
569
+ if(SEA.throw){ throw e }
570
+ if(cb){ cb(); }
571
+ return;
572
+ }});
573
+
574
+ module.exports = SEA.encrypt;
575
+ })(USE, './encrypt');
576
+ USE(function(module){
577
+ var SEA = USE('./root');
578
+ var shim = USE('./shim');
579
+ var S = USE('./settings');
580
+ var aeskey = USE('./aeskey');
581
+
582
+ SEA.decrypt = SEA.decrypt || (async (data, pair, cb, opt) => { try {
583
+ opt = opt || {};
584
+ var key = (pair||opt).epriv || pair;
585
+ if(!key){
586
+ if(!SEA.I){ throw 'No decryption key.' }
587
+ pair = await SEA.I(null, {what: data, how: 'decrypt', why: opt.why});
588
+ key = pair.epriv || pair;
589
+ }
590
+ var json = await S.parse(data);
591
+ var buf, bufiv, bufct; try{
592
+ buf = shim.Buffer.from(json.s, opt.encode || 'base64');
593
+ bufiv = shim.Buffer.from(json.iv, opt.encode || 'base64');
594
+ bufct = shim.Buffer.from(json.ct, opt.encode || 'base64');
595
+ var ct = await aeskey(key, buf, opt).then((aes) => (/*shim.ossl ||*/ shim.subtle).decrypt({ // Keeping aesKey scope as private as possible...
596
+ name: opt.name || 'AES-GCM', iv: new Uint8Array(bufiv), tagLength: 128
597
+ }, aes, new Uint8Array(bufct)));
598
+ }catch(e){
599
+ if('utf8' === opt.encode){ throw "Could not decrypt" }
600
+ if(SEA.opt.fallback){
601
+ opt.encode = 'utf8';
602
+ return await SEA.decrypt(data, pair, cb, opt);
603
+ }
604
+ }
605
+ var r = await S.parse(new shim.TextDecoder('utf8').decode(ct));
606
+ if(cb){ try{ cb(r); }catch(e){console.log(e);} }
607
+ return r;
608
+ } catch(e) {
609
+ console.log(e);
610
+ SEA.err = e;
611
+ if(SEA.throw){ throw e }
612
+ if(cb){ cb(); }
613
+ return;
614
+ }});
615
+
616
+ module.exports = SEA.decrypt;
617
+ })(USE, './decrypt');
618
+ USE(function(module){
619
+ var SEA = USE('./root');
620
+ var shim = USE('./shim');
621
+ USE('./settings');
622
+ // Derive shared secret from other's pub and my epub/epriv
623
+ SEA.secret = SEA.secret || (async (key, pair, cb, opt) => { try {
624
+ opt = opt || {};
625
+ if(!pair || !pair.epriv || !pair.epub){
626
+ if(!SEA.I){ throw 'No secret mix.' }
627
+ pair = await SEA.I(null, {what: key, how: 'secret', why: opt.why});
628
+ }
629
+ var pub = key.epub || key;
630
+ var epub = pair.epub;
631
+ var epriv = pair.epriv;
632
+ var ecdhSubtle = shim.ossl || shim.subtle;
633
+ var pubKeyData = keysToEcdhJwk(pub);
634
+ var props = Object.assign({ public: await ecdhSubtle.importKey(...pubKeyData, true, []) },{name: 'ECDH', namedCurve: 'P-256'}); // Thanks to @sirpy !
635
+ var privKeyData = keysToEcdhJwk(epub, epriv);
636
+ var derived = await ecdhSubtle.importKey(...privKeyData, false, ['deriveBits']).then(async (privKey) => {
637
+ // privateKey scope doesn't leak out from here!
638
+ var derivedBits = await ecdhSubtle.deriveBits(props, privKey, 256);
639
+ var rawBits = new Uint8Array(derivedBits);
640
+ var derivedKey = await ecdhSubtle.importKey('raw', rawBits,{ name: 'AES-GCM', length: 256 }, true, [ 'encrypt', 'decrypt' ]);
641
+ return ecdhSubtle.exportKey('jwk', derivedKey).then(({ k }) => k);
642
+ });
643
+ var r = derived;
644
+ if(cb){ try{ cb(r); }catch(e){console.log(e);} }
645
+ return r;
646
+ } catch(e) {
647
+ console.log(e);
648
+ SEA.err = e;
649
+ if(SEA.throw){ throw e }
650
+ if(cb){ cb(); }
651
+ return;
652
+ }});
653
+
654
+ // can this be replaced with settings.jwk?
655
+ var keysToEcdhJwk = (pub, d) => { // d === priv
656
+ //var [ x, y ] = shim.Buffer.from(pub, 'base64').toString('utf8').split(':') // old
657
+ var [ x, y ] = pub.split('.'); // new
658
+ var jwk = d ? { d: d } : {};
659
+ return [ // Use with spread returned value...
660
+ 'jwk',
661
+ Object.assign(
662
+ jwk,
663
+ { x: x, y: y, kty: 'EC', crv: 'P-256', ext: true }
664
+ ), // ??? refactor
665
+ {name: 'ECDH', namedCurve: 'P-256'}
666
+ ]
667
+ };
668
+
669
+ module.exports = SEA.secret;
670
+ })(USE, './secret');
671
+ USE(function(module){
672
+ var SEA = USE('./root');
673
+ // This is to certify that a group of "certificants" can "put" anything at a group of matched "paths" to the certificate authority's graph
674
+ SEA.certify = SEA.certify || (async (certificants, policy = {}, authority, cb, opt = {}) => { try {
675
+ /*
676
+ The Certify Protocol was made out of love by a Vietnamese code enthusiast. Vietnamese people around the world deserve respect!
677
+ IMPORTANT: A Certificate is like a Signature. No one knows who (authority) created/signed a cert until you put it into their graph.
678
+ "certificants": '*' or a String (Bob.pub) || an Object that contains "pub" as a key || an array of [object || string]. These people will have the rights.
679
+ "policy": A string ('inbox'), or a RAD/LEX object {'*': 'inbox'}, or an Array of RAD/LEX objects or strings. RAD/LEX object can contain key "?" with indexOf("*") > -1 to force key equals certificant pub. This rule is used to check against soul+'/'+key using Gun.text.match or String.match.
680
+ "authority": Key pair or priv of the certificate authority.
681
+ "cb": A callback function after all things are done.
682
+ "opt": If opt.expiry (a timestamp) is set, SEA won't sync data after opt.expiry. If opt.block is set, SEA will look for block before syncing.
683
+ */
684
+ console.log('SEA.certify() is an early experimental community supported method that may change API behavior without warning in any future version.');
685
+
686
+ certificants = (() => {
687
+ var data = [];
688
+ if (certificants) {
689
+ if ((typeof certificants === 'string' || Array.isArray(certificants)) && certificants.indexOf('*') > -1) return '*'
690
+ if (typeof certificants === 'string') return certificants
691
+ if (Array.isArray(certificants)) {
692
+ if (certificants.length === 1 && certificants[0]) return typeof certificants[0] === 'object' && certificants[0].pub ? certificants[0].pub : typeof certificants[0] === 'string' ? certificants[0] : null
693
+ certificants.map(certificant => {
694
+ if (typeof certificant ==='string') data.push(certificant);
695
+ else if (typeof certificant === 'object' && certificant.pub) data.push(certificant.pub);
696
+ });
697
+ }
698
+
699
+ if (typeof certificants === 'object' && certificants.pub) return certificants.pub
700
+ return data.length > 0 ? data : null
701
+ }
702
+ return
703
+ })();
704
+
705
+ if (!certificants) return console.log("No certificant found.")
706
+
707
+ const expiry = opt.expiry && (typeof opt.expiry === 'number' || typeof opt.expiry === 'string') ? parseFloat(opt.expiry) : null;
708
+ const readPolicy = (policy || {}).read ? policy.read : null;
709
+ const writePolicy = (policy || {}).write ? policy.write : typeof policy === 'string' || Array.isArray(policy) || policy["+"] || policy["#"] || policy["."] || policy["="] || policy["*"] || policy[">"] || policy["<"] ? policy : null;
710
+ // The "blacklist" feature is now renamed to "block". Why ? BECAUSE BLACK LIVES MATTER!
711
+ // We can now use 3 keys: block, blacklist, ban
712
+ const block = (opt || {}).block || (opt || {}).blacklist || (opt || {}).ban || {};
713
+ const readBlock = block.read && (typeof block.read === 'string' || (block.read || {})['#']) ? block.read : null;
714
+ const writeBlock = typeof block === 'string' ? block : block.write && (typeof block.write === 'string' || block.write['#']) ? block.write : null;
715
+
716
+ if (!readPolicy && !writePolicy) return console.log("No policy found.")
717
+
718
+ // reserved keys: c, e, r, w, rb, wb
719
+ const data = JSON.stringify({
720
+ c: certificants,
721
+ ...(expiry ? {e: expiry} : {}), // inject expiry if possible
722
+ ...(readPolicy ? {r: readPolicy } : {}), // "r" stands for read, which means read permission.
723
+ ...(writePolicy ? {w: writePolicy} : {}), // "w" stands for write, which means write permission.
724
+ ...(readBlock ? {rb: readBlock} : {}), // inject READ block if possible
725
+ ...(writeBlock ? {wb: writeBlock} : {}), // inject WRITE block if possible
726
+ });
727
+
728
+ const certificate = await SEA.sign(data, authority, null, {raw:1});
729
+
730
+ var r = certificate;
731
+ if(!opt.raw){ r = 'SEA'+JSON.stringify(r); }
732
+ if(cb){ try{ cb(r); }catch(e){console.log(e);} }
733
+ return r;
734
+ } catch(e) {
735
+ SEA.err = e;
736
+ if(SEA.throw){ throw e }
737
+ if(cb){ cb(); }
738
+ return;
739
+ }});
740
+
741
+ module.exports = SEA.certify;
742
+ })(USE, './certify');
743
+ USE(function(module){
744
+ var shim = USE('./shim');
745
+ // Practical examples about usage found in tests.
746
+ var SEA = USE('./root');
747
+ SEA.work = USE('./work');
748
+ SEA.sign = USE('./sign');
749
+ SEA.verify = USE('./verify');
750
+ SEA.encrypt = USE('./encrypt');
751
+ SEA.decrypt = USE('./decrypt');
752
+ SEA.certify = USE('./certify');
753
+ //SEA.opt.aeskey = USE('./aeskey'); // not official! // this causes problems in latest WebCrypto.
754
+
755
+ SEA.random = SEA.random || shim.random;
756
+
757
+ // This is Buffer used in SEA and usable from Gun/SEA application also.
758
+ // For documentation see https://nodejs.org/api/buffer.html
759
+ SEA.Buffer = SEA.Buffer || USE('./buffer');
760
+
761
+ // These SEA functions support now ony Promises or
762
+ // async/await (compatible) code, use those like Promises.
763
+ //
764
+ // Creates a wrapper library around Web Crypto API
765
+ // for various AES, ECDSA, PBKDF2 functions we called above.
766
+ // Calculate public key KeyID aka PGPv4 (result: 8 bytes as hex string)
767
+ SEA.keyid = SEA.keyid || (async (pub) => {
768
+ try {
769
+ // base64('base64(x):base64(y)') => shim.Buffer(xy)
770
+ const pb = shim.Buffer.concat(
771
+ pub.replace(/-/g, '+').replace(/_/g, '/').split('.')
772
+ .map((t) => shim.Buffer.from(t, 'base64'))
773
+ );
774
+ // id is PGPv4 compliant raw key
775
+ const id = shim.Buffer.concat([
776
+ shim.Buffer.from([0x99, pb.length / 0x100, pb.length % 0x100]), pb
777
+ ]);
778
+ const sha1 = await sha1hash(id);
779
+ const hash = shim.Buffer.from(sha1, 'binary');
780
+ return hash.toString('hex', hash.length - 8) // 16-bit ID as hex
781
+ } catch (e) {
782
+ console.log(e);
783
+ throw e
784
+ }
785
+ });
786
+ // all done!
787
+ // Obviously it is missing MANY necessary features. This is only an alpha release.
788
+ // Please experiment with it, audit what I've done so far, and complain about what needs to be added.
789
+ // SEA should be a full suite that is easy and seamless to use.
790
+ // Again, scroll naer the top, where I provide an EXAMPLE of how to create a user and sign in.
791
+ // Once logged in, the rest of the code you just read handled automatically signing/validating data.
792
+ // But all other behavior needs to be equally easy, like opinionated ways of
793
+ // Adding friends (trusted public keys), sending private messages, etc.
794
+ // Cheers! Tell me what you think.
795
+ ((SEA.window||{}).GUN||{}).SEA = SEA;
796
+
797
+ module.exports = SEA;
798
+ // -------------- END SEA MODULES --------------------
799
+ // -- BEGIN SEA+GUN MODULES: BUNDLED BY DEFAULT UNTIL OTHERS USE SEA ON OWN -------
800
+ })(USE, './sea');
801
+ USE(function(module){
802
+ var SEA = USE('./sea'), Gun, u;
803
+ if(SEA.window){
804
+ Gun = SEA.window.GUN || {chain:{}};
805
+ } else {
806
+ Gun = USE((u+'' == typeof MODULE?'.':'')+'./gun', 1);
807
+ }
808
+ SEA.GUN = Gun;
809
+
810
+ function User(root){
811
+ this._ = {$: this};
812
+ }
813
+ User.prototype = (function(){ function F(){} F.prototype = Gun.chain; return new F() }()); // Object.create polyfill
814
+ User.prototype.constructor = User;
815
+
816
+ // let's extend the gun chain with a `user` function.
817
+ // only one user can be logged in at a time, per gun instance.
818
+ Gun.chain.user = function(pub){
819
+ var gun = this, root = gun.back(-1), user;
820
+ if(pub){
821
+ pub = SEA.opt.pub((pub._||'')['#']) || pub;
822
+ return root.get('~'+pub);
823
+ }
824
+ if(user = root.back('user')){ return user }
825
+ var root = (root._), at = root, uuid = at.opt.uuid || lex;
826
+ (at = (user = at.user = gun.chain(new User))._).opt = {};
827
+ at.opt.uuid = function(cb){
828
+ var id = uuid(), pub = root.user;
829
+ if(!pub || !(pub = pub.is) || !(pub = pub.pub)){ return id }
830
+ id = '~' + pub + '/' + id;
831
+ if(cb && cb.call){ cb(null, id); }
832
+ return id;
833
+ };
834
+ return user;
835
+ };
836
+ function lex(){ return Gun.state().toString(36).replace('.','') }
837
+ Gun.User = User;
838
+ User.GUN = Gun;
839
+ User.SEA = Gun.SEA = SEA;
840
+ module.exports = User;
841
+ })(USE, './user');
842
+ USE(function(module){
843
+ var u, Gun = (''+u != typeof GUN)? (GUN||{chain:{}}) : USE((''+u === typeof MODULE?'.':'')+'./gun', 1);
844
+ Gun.chain.then = function(cb, opt){
845
+ var gun = this, p = (new Promise(function(res, rej){
846
+ gun.once(res, opt);
847
+ }));
848
+ return cb? p.then(cb) : p;
849
+ };
850
+ })(USE, './then');
851
+ USE(function(module){
852
+ var User = USE('./user'), SEA = User.SEA, Gun = User.GUN, noop = function(){};
853
+
854
+ // Well first we have to actually create a user. That is what this function does.
855
+ User.prototype.create = function(...args){
856
+ var pair = typeof args[0] === 'object' && (args[0].pub || args[0].epub) ? args[0] : typeof args[1] === 'object' && (args[1].pub || args[1].epub) ? args[1] : null;
857
+ var alias = pair && (pair.pub || pair.epub) ? pair.pub : typeof args[0] === 'string' ? args[0] : null;
858
+ var pass = pair && (pair.pub || pair.epub) ? pair : alias && typeof args[1] === 'string' ? args[1] : null;
859
+ var cb = args.filter(arg => typeof arg === 'function')[0] || null; // cb now can stand anywhere, after alias/pass or pair
860
+ var opt = args && args.length > 1 && typeof args[args.length-1] === 'object' ? args[args.length-1] : {}; // opt is always the last parameter which typeof === 'object' and stands after cb
861
+
862
+ var gun = this, cat = (gun._), root = gun.back(-1);
863
+ cb = cb || noop;
864
+ opt = opt || {};
865
+ if(false !== opt.check){
866
+ var err;
867
+ if(!alias){ err = "No user."; }
868
+ if((pass||'').length < 8){ err = "Password too short!"; }
869
+ if(err){
870
+ cb({err: Gun.log(err)});
871
+ return gun;
872
+ }
873
+ }
874
+ if(cat.ing){
875
+ (cb || noop)({err: Gun.log("User is already being created or authenticated!"), wait: true});
876
+ return gun;
877
+ }
878
+ cat.ing = true;
879
+ var act = {};
880
+ act.a = function(pubs){
881
+ act.pubs = pubs;
882
+ if(pubs && !opt.already){
883
+ // If we can enforce that a user name is already taken, it might be nice to try, but this is not guaranteed.
884
+ var ack = {err: Gun.log('User already created!')};
885
+ cat.ing = false;
886
+ (cb || noop)(ack);
887
+ gun.leave();
888
+ return;
889
+ }
890
+ act.salt = String.random(64); // pseudo-randomly create a salt, then use PBKDF2 function to extend the password with it.
891
+ SEA.work(pass, act.salt, act.b); // this will take some short amount of time to produce a proof, which slows brute force attacks.
892
+ };
893
+ act.b = function(proof){
894
+ act.proof = proof;
895
+ pair ? act.c(pair) : SEA.pair(act.c); // generate a brand new key pair or use the existing.
896
+ };
897
+ act.c = function(pair){
898
+ var tmp;
899
+ act.pair = pair || {};
900
+ if(tmp = cat.root.user){
901
+ tmp._.sea = pair;
902
+ tmp.is = {pub: pair.pub, epub: pair.epub, alias: alias};
903
+ }
904
+ // the user's public key doesn't need to be signed. But everything else needs to be signed with it! // we have now automated it! clean up these extra steps now!
905
+ act.data = {pub: pair.pub};
906
+ act.d();
907
+ };
908
+ act.d = function(){
909
+ act.data.alias = alias;
910
+ act.e();
911
+ };
912
+ act.e = function(){
913
+ act.data.epub = act.pair.epub;
914
+ SEA.encrypt({priv: act.pair.priv, epriv: act.pair.epriv}, act.proof, act.f, {raw:1}); // to keep the private key safe, we AES encrypt it with the proof of work!
915
+ };
916
+ act.f = function(auth){
917
+ act.data.auth = JSON.stringify({ek: auth, s: act.salt});
918
+ act.g(act.data.auth);
919
+ };
920
+ act.g = function(auth){ var tmp;
921
+ act.data.auth = act.data.auth || auth;
922
+ root.get(tmp = '~'+act.pair.pub).put(act.data).on(act.h); // awesome, now we can actually save the user with their public key as their ID.
923
+ var link = {}; link[tmp] = {'#': tmp}; root.get('~@'+alias).put(link).get(tmp).on(act.i); // next up, we want to associate the alias with the public key. So we add it to the alias list.
924
+ };
925
+ act.h = function(data, key, msg, eve){
926
+ eve.off(); act.h.ok = 1; act.i();
927
+ };
928
+ act.i = function(data, key, msg, eve){
929
+ if(eve){ act.i.ok = 1; eve.off(); }
930
+ if(!act.h.ok || !act.i.ok){ return }
931
+ cat.ing = false;
932
+ cb({ok: 0, pub: act.pair.pub}); // callback that the user has been created. (Note: ok = 0 because we didn't wait for disk to ack)
933
+ if(noop === cb){ pair ? gun.auth(pair) : gun.auth(alias, pass); } // if no callback is passed, auto-login after signing up.
934
+ };
935
+ root.get('~@'+alias).once(act.a);
936
+ return gun;
937
+ };
938
+ User.prototype.leave = function(opt, cb){
939
+ var gun = this, user = (gun.back(-1)._).user;
940
+ if(user){
941
+ delete user.is;
942
+ delete user._.is;
943
+ delete user._.sea;
944
+ }
945
+ if(SEA.window){
946
+ try{var sS = {};
947
+ sS = SEA.window.sessionStorage;
948
+ delete sS.recall;
949
+ delete sS.pair;
950
+ }catch(e){} }
951
+ return gun;
952
+ };
953
+ })(USE, './create');
954
+ USE(function(module){
955
+ var User = USE('./user'), SEA = User.SEA, Gun = User.GUN, noop = function(){};
956
+ // now that we have created a user, we want to authenticate them!
957
+ User.prototype.auth = function(...args){ // TODO: this PR with arguments need to be cleaned up / refactored.
958
+ var pair = typeof args[0] === 'object' && (args[0].pub || args[0].epub) ? args[0] : typeof args[1] === 'object' && (args[1].pub || args[1].epub) ? args[1] : null;
959
+ var alias = !pair && typeof args[0] === 'string' ? args[0] : null;
960
+ var pass = (alias || (pair && !(pair.priv && pair.epriv))) && typeof args[1] === 'string' ? args[1] : null;
961
+ var cb = args.filter(arg => typeof arg === 'function')[0] || null; // cb now can stand anywhere, after alias/pass or pair
962
+ var opt = args && args.length > 1 && typeof args[args.length-1] === 'object' ? args[args.length-1] : {}; // opt is always the last parameter which typeof === 'object' and stands after cb
963
+
964
+ var gun = this, cat = (gun._), root = gun.back(-1);
965
+
966
+ if(cat.ing){
967
+ (cb || noop)({err: Gun.log("User is already being created or authenticated!"), wait: true});
968
+ return gun;
969
+ }
970
+ cat.ing = true;
971
+
972
+ var act = {}, u, tries = 9;
973
+ act.a = function(data){
974
+ if(!data){ return act.b() }
975
+ if(!data.pub){
976
+ var tmp = []; Object.keys(data).forEach(function(k){ if('_'==k){ return } tmp.push(data[k]); });
977
+ return act.b(tmp);
978
+ }
979
+ if(act.name){ return act.f(data) }
980
+ act.c((act.data = data).auth);
981
+ };
982
+ act.b = function(list){
983
+ var get = (act.list = (act.list||[]).concat(list||[])).shift();
984
+ if(u === get){
985
+ if(act.name){ return act.err('Your user account is not published for dApps to access, please consider syncing it online, or allowing local access by adding your device as a peer.') }
986
+ if(alias && tries--){
987
+ root.get('~@'+alias).once(act.a);
988
+ return;
989
+ }
990
+ return act.err('Wrong user or password.')
991
+ }
992
+ root.get(get).once(act.a);
993
+ };
994
+ act.c = function(auth){
995
+ if(u === auth){ return act.b() }
996
+ if('string' == typeof auth){ return act.c(obj_ify(auth)) } // in case of legacy
997
+ SEA.work(pass, (act.auth = auth).s, act.d, act.enc); // the proof of work is evidence that we've spent some time/effort trying to log in, this slows brute force.
998
+ };
999
+ act.d = function(proof){
1000
+ SEA.decrypt(act.auth.ek, proof, act.e, act.enc);
1001
+ };
1002
+ act.e = function(half){
1003
+ if(u === half){
1004
+ if(!act.enc){ // try old format
1005
+ act.enc = {encode: 'utf8'};
1006
+ return act.c(act.auth);
1007
+ } act.enc = null; // end backwards
1008
+ return act.b();
1009
+ }
1010
+ act.half = half;
1011
+ act.f(act.data);
1012
+ };
1013
+ act.f = function(pair){
1014
+ var half = act.half || {}, data = act.data || {};
1015
+ act.g(act.lol = {pub: pair.pub || data.pub, epub: pair.epub || data.epub, priv: pair.priv || half.priv, epriv: pair.epriv || half.epriv});
1016
+ };
1017
+ act.g = function(pair){
1018
+ if(!pair || !pair.pub || !pair.epub){ return act.b() }
1019
+ act.pair = pair;
1020
+ var user = (root._).user, at = (user._);
1021
+ at.tag;
1022
+ var upt = at.opt;
1023
+ at = user._ = root.get('~'+pair.pub)._;
1024
+ at.opt = upt;
1025
+ // add our credentials in-memory only to our root user instance
1026
+ user.is = {pub: pair.pub, epub: pair.epub, alias: alias || pair.pub};
1027
+ at.sea = act.pair;
1028
+ cat.ing = false;
1029
+ try{if(pass && u == (obj_ify(cat.root.graph['~'+pair.pub].auth)||'')[':']){ opt.shuffle = opt.change = pass; } }catch(e){} // migrate UTF8 & Shuffle!
1030
+ opt.change? act.z() : (cb || noop)(at);
1031
+ if(SEA.window && ((gun.back('user')._).opt||opt).remember){
1032
+ // TODO: this needs to be modular.
1033
+ try{var sS = {};
1034
+ sS = SEA.window.sessionStorage; // TODO: FIX BUG putting on `.is`!
1035
+ sS.recall = true;
1036
+ sS.pair = JSON.stringify(pair); // auth using pair is more reliable than alias/pass
1037
+ }catch(e){}
1038
+ }
1039
+ try{
1040
+ if(root._.tag.auth){ // auth handle might not be registered yet
1041
+ (root._).on('auth', at); // TODO: Deprecate this, emit on user instead! Update docs when you do.
1042
+ } else { setTimeout(function(){ (root._).on('auth', at); },1); } // if not, hackily add a timeout.
1043
+ //at.on('auth', at) // Arrgh, this doesn't work without event "merge" code, but "merge" code causes stack overflow and crashes after logging in & trying to write data.
1044
+ }catch(e){
1045
+ Gun.log("Your 'auth' callback crashed with:", e);
1046
+ }
1047
+ };
1048
+ act.h = function(data){
1049
+ if(!data){ return act.b() }
1050
+ alias = data.alias;
1051
+ if(!alias)
1052
+ alias = data.alias = "~" + pair.pub;
1053
+ if(!data.auth){
1054
+ return act.g(pair);
1055
+ }
1056
+ pair = null;
1057
+ act.c((act.data = data).auth);
1058
+ };
1059
+ act.z = function(){
1060
+ // password update so encrypt private key using new pwd + salt
1061
+ act.salt = String.random(64); // pseudo-random
1062
+ SEA.work(opt.change, act.salt, act.y);
1063
+ };
1064
+ act.y = function(proof){
1065
+ SEA.encrypt({priv: act.pair.priv, epriv: act.pair.epriv}, proof, act.x, {raw:1});
1066
+ };
1067
+ act.x = function(auth){
1068
+ act.w(JSON.stringify({ek: auth, s: act.salt}));
1069
+ };
1070
+ act.w = function(auth){
1071
+ if(opt.shuffle){ // delete in future!
1072
+ console.log('migrate core account from UTF8 & shuffle');
1073
+ var tmp = {}; Object.keys(act.data).forEach(function(k){ tmp[k] = act.data[k]; });
1074
+ delete tmp._;
1075
+ tmp.auth = auth;
1076
+ root.get('~'+act.pair.pub).put(tmp);
1077
+ } // end delete
1078
+ root.get('~'+act.pair.pub).get('auth').put(auth, cb || noop);
1079
+ };
1080
+ act.err = function(e){
1081
+ var ack = {err: Gun.log(e || 'User cannot be found!')};
1082
+ cat.ing = false;
1083
+ (cb || noop)(ack);
1084
+ };
1085
+ act.plugin = function(name){
1086
+ if(!(act.name = name)){ return act.err() }
1087
+ var tmp = [name];
1088
+ if('~' !== name[0]){
1089
+ tmp[1] = '~'+name;
1090
+ tmp[2] = '~@'+name;
1091
+ }
1092
+ act.b(tmp);
1093
+ };
1094
+ if(pair){
1095
+ if(pair.priv && pair.epriv)
1096
+ act.g(pair);
1097
+ else
1098
+ root.get('~'+pair.pub).once(act.h);
1099
+ } else
1100
+ if(alias){
1101
+ root.get('~@'+alias).once(act.a);
1102
+ } else
1103
+ if(!alias && !pass){
1104
+ SEA.name(act.plugin);
1105
+ }
1106
+ return gun;
1107
+ };
1108
+ function obj_ify(o){
1109
+ if('string' != typeof o){ return o }
1110
+ try{o = JSON.parse(o);
1111
+ }catch(e){o={};} return o;
1112
+ }
1113
+ })(USE, './auth');
1114
+ USE(function(module){
1115
+ var User = USE('./user'), SEA = User.SEA; User.GUN;
1116
+ User.prototype.recall = function(opt, cb){
1117
+ var gun = this, root = gun.back(-1);
1118
+ opt = opt || {};
1119
+ if(opt && opt.sessionStorage){
1120
+ if(SEA.window){
1121
+ try{
1122
+ var sS = {};
1123
+ sS = SEA.window.sessionStorage; // TODO: FIX BUG putting on `.is`!
1124
+ if(sS){
1125
+ (root._).opt.remember = true;
1126
+ ((gun.back('user')._).opt||opt).remember = true;
1127
+ if(sS.recall || sS.pair) root.user().auth(JSON.parse(sS.pair), cb); // pair is more reliable than alias/pass
1128
+ }
1129
+ }catch(e){}
1130
+ }
1131
+ return gun;
1132
+ }
1133
+ /*
1134
+ TODO: copy mhelander's expiry code back in.
1135
+ Although, we should check with community,
1136
+ should expiry be core or a plugin?
1137
+ */
1138
+ return gun;
1139
+ };
1140
+ })(USE, './recall');
1141
+ USE(function(module){
1142
+ var User = USE('./user'), SEA = User.SEA, Gun = User.GUN, noop = function(){};
1143
+ User.prototype.pair = function(){
1144
+ var user = this, proxy; // undeprecated, hiding with proxies.
1145
+ try{ proxy = new Proxy({DANGER:'\u2620'}, {get: function(t,p,r){
1146
+ if(!user.is || !(user._||'').sea){ return }
1147
+ return user._.sea[p];
1148
+ }});}catch(e){}
1149
+ return proxy;
1150
+ };
1151
+ // If authenticated user wants to delete his/her account, let's support it!
1152
+ User.prototype.delete = async function(alias, pass, cb){
1153
+ console.log("user.delete() IS DEPRECATED AND WILL BE MOVED TO A MODULE!!!");
1154
+ var gun = this; gun.back(-1); var user = gun.back('user');
1155
+ try {
1156
+ user.auth(alias, pass, function(ack){
1157
+ var pub = (user.is||{}).pub;
1158
+ // Delete user data
1159
+ user.map().once(function(){ this.put(null); });
1160
+ // Wipe user data from memory
1161
+ user.leave();
1162
+ (cb || noop)({ok: 0});
1163
+ });
1164
+ } catch (e) {
1165
+ Gun.log('User.delete failed! Error:', e);
1166
+ }
1167
+ return gun;
1168
+ };
1169
+ User.prototype.alive = async function(){
1170
+ console.log("user.alive() IS DEPRECATED!!!");
1171
+ const gunRoot = this.back(-1);
1172
+ try {
1173
+ // All is good. Should we do something more with actual recalled data?
1174
+ await authRecall(gunRoot);
1175
+ return gunRoot._.user._
1176
+ } catch (e) {
1177
+ const err = 'No session!';
1178
+ Gun.log(err);
1179
+ throw { err }
1180
+ }
1181
+ };
1182
+ User.prototype.trust = async function(user){
1183
+ console.log("`.trust` API MAY BE DELETED OR CHANGED OR RENAMED, DO NOT USE!");
1184
+ // TODO: BUG!!! SEA `node` read listener needs to be async, which means core needs to be async too.
1185
+ //gun.get('alice').get('age').trust(bob);
1186
+ if (Gun.is(user)) {
1187
+ user.get('pub').get((ctx, ev) => {
1188
+ console.log(ctx, ev);
1189
+ });
1190
+ }
1191
+ user.get('trust').get(path).put(theirPubkey);
1192
+
1193
+ // do a lookup on this gun chain directly (that gets bob's copy of the data)
1194
+ // do a lookup on the metadata trust table for this path (that gets all the pubkeys allowed to write on this path)
1195
+ // do a lookup on each of those pubKeys ON the path (to get the collab data "layers")
1196
+ // THEN you perform Jachen's mix operation
1197
+ // and return the result of that to...
1198
+ };
1199
+ User.prototype.grant = function(to, cb){
1200
+ console.log("`.grant` API MAY BE DELETED OR CHANGED OR RENAMED, DO NOT USE!");
1201
+ var gun = this, user = gun.back(-1).user(), pair = user._.sea, path = '';
1202
+ gun.back(function(at){ if(at.is){ return } path += (at.get||''); });
1203
+ (async function(){
1204
+ var enc, sec = await user.get('grant').get(pair.pub).get(path).then();
1205
+ sec = await SEA.decrypt(sec, pair);
1206
+ if(!sec){
1207
+ sec = SEA.random(16).toString();
1208
+ enc = await SEA.encrypt(sec, pair);
1209
+ user.get('grant').get(pair.pub).get(path).put(enc);
1210
+ }
1211
+ var pub = to.get('pub').then();
1212
+ var epub = to.get('epub').then();
1213
+ pub = await pub; epub = await epub;
1214
+ var dh = await SEA.secret(epub, pair);
1215
+ enc = await SEA.encrypt(sec, dh);
1216
+ user.get('grant').get(pub).get(path).put(enc, cb);
1217
+ }());
1218
+ return gun;
1219
+ };
1220
+ User.prototype.secret = function(data, cb){
1221
+ console.log("`.secret` API MAY BE DELETED OR CHANGED OR RENAMED, DO NOT USE!");
1222
+ var gun = this, user = gun.back(-1).user(), pair = user.pair(), path = '';
1223
+ gun.back(function(at){ if(at.is){ return } path += (at.get||''); });
1224
+ (async function(){
1225
+ var enc, sec = await user.get('trust').get(pair.pub).get(path).then();
1226
+ sec = await SEA.decrypt(sec, pair);
1227
+ if(!sec){
1228
+ sec = SEA.random(16).toString();
1229
+ enc = await SEA.encrypt(sec, pair);
1230
+ user.get('trust').get(pair.pub).get(path).put(enc);
1231
+ }
1232
+ enc = await SEA.encrypt(data, sec);
1233
+ gun.put(enc, cb);
1234
+ }());
1235
+ return gun;
1236
+ };
1237
+
1238
+ /**
1239
+ * returns the decrypted value, encrypted by secret
1240
+ * @returns {Promise<any>}
1241
+ // Mark needs to review 1st before officially supported
1242
+ User.prototype.decrypt = function(cb) {
1243
+ let gun = this,
1244
+ path = ''
1245
+ gun.back(function(at) {
1246
+ if (at.is) {
1247
+ return
1248
+ }
1249
+ path += at.get || ''
1250
+ })
1251
+ return gun
1252
+ .then(async data => {
1253
+ if (data == null) {
1254
+ return
1255
+ }
1256
+ const user = gun.back(-1).user()
1257
+ const pair = user.pair()
1258
+ let sec = await user
1259
+ .get('trust')
1260
+ .get(pair.pub)
1261
+ .get(path)
1262
+ sec = await SEA.decrypt(sec, pair)
1263
+ if (!sec) {
1264
+ return data
1265
+ }
1266
+ let decrypted = await SEA.decrypt(data, sec)
1267
+ return decrypted
1268
+ })
1269
+ .then(res => {
1270
+ cb && cb(res)
1271
+ return res
1272
+ })
1273
+ }
1274
+ */
1275
+ module.exports = User;
1276
+ })(USE, './share');
1277
+ USE(function(module){
1278
+ var SEA = USE('./sea'), S = USE('./settings'), u;
1279
+ var Gun = (SEA.window||'').GUN || USE((''+u === typeof MODULE?'.':'')+'./gun', 1);
1280
+ // After we have a GUN extension to make user registration/login easy, we then need to handle everything else.
1281
+
1282
+ // We do this with a GUN adapter, we first listen to when a gun instance is created (and when its options change)
1283
+ Gun.on('opt', function(at){
1284
+ if(!at.sea){ // only add SEA once per instance, on the "at" context.
1285
+ at.sea = {own: {}};
1286
+ at.on('put', check, at); // SEA now runs its firewall on HAM diffs, not all i/o.
1287
+ }
1288
+ this.to.next(at); // make sure to call the "next" middleware adapter.
1289
+ });
1290
+
1291
+ // Alright, this next adapter gets run at the per node level in the graph database.
1292
+ // correction: 2020 it gets run on each key/value pair in a node upon a HAM diff.
1293
+ // This will let us verify that every property on a node has a value signed by a public key we trust.
1294
+ // If the signature does not match, the data is just `undefined` so it doesn't get passed on.
1295
+ // If it does match, then we transform the in-memory "view" of the data into its plain value (without the signature).
1296
+ // Now NOTE! Some data is "system" data, not user data. Example: List of public keys, aliases, etc.
1297
+ // This data is self-enforced (the value can only match its ID), but that is handled in the `security` function.
1298
+ // From the self-enforced data, we can see all the edges in the graph that belong to a public key.
1299
+ // Example: ~ASDF is the ID of a node with ASDF as its public key, signed alias and salt, and
1300
+ // its encrypted private key, but it might also have other signed values on it like `profile = <ID>` edge.
1301
+ // Using that directed edge's ID, we can then track (in memory) which IDs belong to which keys.
1302
+ // Here is a problem: Multiple public keys can "claim" any node's ID, so this is dangerous!
1303
+ // This means we should ONLY trust our "friends" (our key ring) public keys, not any ones.
1304
+ // I have not yet added that to SEA yet in this alpha release. That is coming soon, but beware in the meanwhile!
1305
+
1306
+ function check(msg){ // REVISE / IMPROVE, NO NEED TO PASS MSG/EVE EACH SUB?
1307
+ var eve = this, at = eve.as, put = msg.put, soul = put['#'], key = put['.'], val = put[':'], state = put['>'], id = msg['#'], tmp;
1308
+ if(!soul || !key){ return }
1309
+ if((msg._||'').faith && (at.opt||'').faith && 'function' == typeof msg._){
1310
+ SEA.opt.pack(put, function(raw){
1311
+ SEA.verify(raw, false, function(data){ // this is synchronous if false
1312
+ put['='] = SEA.opt.unpack(data);
1313
+ eve.to.next(msg);
1314
+ });});
1315
+ return
1316
+ }
1317
+ var no = function(why){ at.on('in', {'@': id, err: msg.err = why}); }; // exploit internal relay stun for now, maybe violates spec, but testing for now. // Note: this may be only the sharded message, not original batch.
1318
+ //var no = function(why){ msg.ack(why) };
1319
+ (msg._||'').DBG && ((msg._||'').DBG.c = +new Date);
1320
+ if(0 <= soul.indexOf('<?')){ // special case for "do not sync data X old" forget
1321
+ // 'a~pub.key/b<?9'
1322
+ tmp = parseFloat(soul.split('<?')[1]||'');
1323
+ if(tmp && (state < (Gun.state() - (tmp * 1000)))){ // sec to ms
1324
+ (tmp = msg._) && (tmp.stun) && (tmp.stun--); // THIS IS BAD CODE! It assumes GUN internals do something that will probably change in future, but hacking in now.
1325
+ return; // omit!
1326
+ }
1327
+ }
1328
+
1329
+ if('~@' === soul){ // special case for shared system data, the list of aliases.
1330
+ check.alias(eve, msg, val, key, soul, at, no); return;
1331
+ }
1332
+ if('~@' === soul.slice(0,2)){ // special case for shared system data, the list of public keys for an alias.
1333
+ check.pubs(eve, msg, val, key, soul, at, no); return;
1334
+ }
1335
+ //if('~' === soul.slice(0,1) && 2 === (tmp = soul.slice(1)).split('.').length){ // special case, account data for a public key.
1336
+ if(tmp = SEA.opt.pub(soul)){ // special case, account data for a public key.
1337
+ check.pub(eve, msg, val, key, soul, at, no, at.user||'', tmp); return;
1338
+ }
1339
+ if(0 <= soul.indexOf('#')){ // special case for content addressing immutable hashed data.
1340
+ check.hash(eve, msg, val, key, soul, at, no); return;
1341
+ }
1342
+ check.any(eve, msg, val, key, soul, at, no, at.user||''); return;
1343
+ }
1344
+ check.hash = function(eve, msg, val, key, soul, at, no){ // mark unbuilt @i001962 's epic hex contrib!
1345
+ SEA.work(val, null, function(data){
1346
+ function hexToBase64(hexStr) {
1347
+ let base64 = "";
1348
+ for(let i = 0; i < hexStr.length; i++) {
1349
+ base64 += !(i - 1 & 1) ? String.fromCharCode(parseInt(hexStr.substring(i - 1, i + 1), 16)) : "";}
1350
+ return btoa(base64);}
1351
+ if(data && data === key.split('#').slice(-1)[0]){ return eve.to.next(msg) }
1352
+ else if (data && data === hexToBase64(key.split('#').slice(-1)[0])){
1353
+ return eve.to.next(msg) }
1354
+ no("Data hash not same as hash!");
1355
+ }, {name: 'SHA-256'});
1356
+ };
1357
+ check.alias = function(eve, msg, val, key, soul, at, no){ // Example: {_:#~@, ~@alice: {#~@alice}}
1358
+ if(!val){ return no("Data must exist!") } // data MUST exist
1359
+ if('~@'+key === link_is(val)){ return eve.to.next(msg) } // in fact, it must be EXACTLY equal to itself
1360
+ no("Alias not same!"); // if it isn't, reject.
1361
+ };
1362
+ check.pubs = function(eve, msg, val, key, soul, at, no){ // Example: {_:#~@alice, ~asdf: {#~asdf}}
1363
+ if(!val){ return no("Alias must exist!") } // data MUST exist
1364
+ if(key === link_is(val)){ return eve.to.next(msg) } // and the ID must be EXACTLY equal to its property
1365
+ no("Alias not same!"); // that way nobody can tamper with the list of public keys.
1366
+ };
1367
+ check.pub = async function(eve, msg, val, key, soul, at, no, user, pub){ var tmp; // Example: {_:#~asdf, hello:'world'~fdsa}}
1368
+ const raw = await S.parse(val) || {};
1369
+ const verify = (certificate, certificant, cb) => {
1370
+ if (certificate.m && certificate.s && certificant && pub)
1371
+ // now verify certificate
1372
+ return SEA.verify(certificate, pub, data => { // check if "pub" (of the graph owner) really issued this cert
1373
+ if (u !== data && u !== data.e && msg.put['>'] && msg.put['>'] > parseFloat(data.e)) return no("Certificate expired.") // certificate expired
1374
+ // "data.c" = a list of certificants/certified users
1375
+ // "data.w" = lex WRITE permission, in the future, there will be "data.r" which means lex READ permission
1376
+ if (u !== data && data.c && data.w && (data.c === certificant || data.c.indexOf('*' ) > -1)) {
1377
+ // ok, now "certificant" is in the "certificants" list, but is "path" allowed? Check path
1378
+ let path = soul.indexOf('/') > -1 ? soul.replace(soul.substring(0, soul.indexOf('/') + 1), '') : '';
1379
+ String.match = String.match || Gun.text.match;
1380
+ const w = Array.isArray(data.w) ? data.w : typeof data.w === 'object' || typeof data.w === 'string' ? [data.w] : [];
1381
+ for (const lex of w) {
1382
+ if ((String.match(path, lex['#']) && String.match(key, lex['.'])) || (!lex['.'] && String.match(path, lex['#'])) || (!lex['#'] && String.match(key, lex['.'])) || String.match((path ? path + '/' + key : key), lex['#'] || lex)) {
1383
+ // is Certificant forced to present in Path
1384
+ if (lex['+'] && lex['+'].indexOf('*') > -1 && path && path.indexOf(certificant) == -1 && key.indexOf(certificant) == -1) return no(`Path "${path}" or key "${key}" must contain string "${certificant}".`)
1385
+ // path is allowed, but is there any WRITE block? Check it out
1386
+ if (data.wb && (typeof data.wb === 'string' || ((data.wb || {})['#']))) { // "data.wb" = path to the WRITE block
1387
+ var root = eve.as.root.$.back(-1);
1388
+ if (typeof data.wb === 'string' && '~' !== data.wb.slice(0, 1)) root = root.get('~' + pub);
1389
+ return root.get(data.wb).get(certificant).once(value => { // TODO: INTENT TO DEPRECATE.
1390
+ if (value && (value === 1 || value === true)) return no(`Certificant ${certificant} blocked.`)
1391
+ return cb(data)
1392
+ })
1393
+ }
1394
+ return cb(data)
1395
+ }
1396
+ }
1397
+ return no("Certificate verification fail.")
1398
+ }
1399
+ })
1400
+ return
1401
+ };
1402
+
1403
+ if ('pub' === key && '~' + pub === soul) {
1404
+ if (val === pub) return eve.to.next(msg) // the account MUST match `pub` property that equals the ID of the public key.
1405
+ return no("Account not same!")
1406
+ }
1407
+
1408
+ if ((tmp = user.is) && tmp.pub && !raw['*'] && !raw['+'] && (pub === tmp.pub || (pub !== tmp.pub && ((msg._.msg || {}).opt || {}).cert))){
1409
+ SEA.opt.pack(msg.put, packed => {
1410
+ SEA.sign(packed, (user._).sea, async function(data) {
1411
+ if (u === data) return no(SEA.err || 'Signature fail.')
1412
+ msg.put[':'] = {':': tmp = SEA.opt.unpack(data.m), '~': data.s};
1413
+ msg.put['='] = tmp;
1414
+
1415
+ // if writing to own graph, just allow it
1416
+ if (pub === user.is.pub) {
1417
+ if (tmp = link_is(val)) (at.sea.own[tmp] = at.sea.own[tmp] || {})[pub] = 1;
1418
+ JSON.stringifyAsync(msg.put[':'], function(err,s){
1419
+ if(err){ return no(err || "Stringify error.") }
1420
+ msg.put[':'] = s;
1421
+ return eve.to.next(msg);
1422
+ });
1423
+ return
1424
+ }
1425
+
1426
+ // if writing to other's graph, check if cert exists then try to inject cert into put, also inject self pub so that everyone can verify the put
1427
+ if (pub !== user.is.pub && ((msg._.msg || {}).opt || {}).cert) {
1428
+ const cert = await S.parse(msg._.msg.opt.cert);
1429
+ // even if cert exists, we must verify it
1430
+ if (cert && cert.m && cert.s)
1431
+ verify(cert, user.is.pub, _ => {
1432
+ msg.put[':']['+'] = cert; // '+' is a certificate
1433
+ msg.put[':']['*'] = user.is.pub; // '*' is pub of the user who puts
1434
+ JSON.stringifyAsync(msg.put[':'], function(err,s){
1435
+ if(err){ return no(err || "Stringify error.") }
1436
+ msg.put[':'] = s;
1437
+ return eve.to.next(msg);
1438
+ });
1439
+ return
1440
+ });
1441
+ }
1442
+ }, {raw: 1});
1443
+ });
1444
+ return;
1445
+ }
1446
+
1447
+ SEA.opt.pack(msg.put, packed => {
1448
+ SEA.verify(packed, raw['*'] || pub, function(data){ var tmp;
1449
+ data = SEA.opt.unpack(data);
1450
+ if (u === data) return no("Unverified data.") // make sure the signature matches the account it claims to be on. // reject any updates that are signed with a mismatched account.
1451
+ if ((tmp = link_is(data)) && pub === SEA.opt.pub(tmp)) (at.sea.own[tmp] = at.sea.own[tmp] || {})[pub] = 1;
1452
+
1453
+ // check if cert ('+') and putter's pub ('*') exist
1454
+ if (raw['+'] && raw['+']['m'] && raw['+']['s'] && raw['*'])
1455
+ // now verify certificate
1456
+ verify(raw['+'], raw['*'], _ => {
1457
+ msg.put['='] = data;
1458
+ return eve.to.next(msg);
1459
+ });
1460
+ else {
1461
+ msg.put['='] = data;
1462
+ return eve.to.next(msg);
1463
+ }
1464
+ });
1465
+ });
1466
+ return
1467
+ };
1468
+ check.any = function(eve, msg, val, key, soul, at, no, user){ if(at.opt.secure){ return no("Soul missing public key at '" + key + "'.") }
1469
+ // TODO: Ask community if should auto-sign non user-graph data.
1470
+ at.on('secure', function(msg){ this.off();
1471
+ if(!at.opt.secure){ return eve.to.next(msg) }
1472
+ no("Data cannot be changed.");
1473
+ }).on.on('secure', msg);
1474
+ return;
1475
+ };
1476
+
1477
+ var valid = Gun.valid, link_is = function(d,l){ return 'string' == typeof (l = valid(d)) && l }; (Gun.state||'').ify;
1478
+
1479
+ var pubcut = /[^\w_-]/; // anything not alphanumeric or _ -
1480
+ SEA.opt.pub = function(s){
1481
+ if(!s){ return }
1482
+ s = s.split('~');
1483
+ if(!s || !(s = s[1])){ return }
1484
+ s = s.split(pubcut).slice(0,2);
1485
+ if(!s || 2 != s.length){ return }
1486
+ if('@' === (s[0]||'')[0]){ return }
1487
+ s = s.slice(0,2).join('.');
1488
+ return s;
1489
+ };
1490
+ SEA.opt.stringy = function(t){
1491
+ // TODO: encrypt etc. need to check string primitive. Make as breaking change.
1492
+ };
1493
+ SEA.opt.pack = function(d,cb,k, n,s){ var tmp, f; // pack for verifying
1494
+ if(SEA.opt.check(d)){ return cb(d) }
1495
+ if(d && d['#'] && d['.'] && d['>']){ tmp = d[':']; f = 1; }
1496
+ JSON.parseAsync(f? tmp : d, function(err, meta){
1497
+ var sig = ((u !== (meta||'')[':']) && (meta||'')['~']); // or just ~ check?
1498
+ if(!sig){ cb(d); return }
1499
+ cb({m: {'#':s||d['#'],'.':k||d['.'],':':(meta||'')[':'],'>':d['>']||Gun.state.is(n, k)}, s: sig});
1500
+ });
1501
+ };
1502
+ var O = SEA.opt;
1503
+ SEA.opt.unpack = function(d, k, n){ var tmp;
1504
+ if(u === d){ return }
1505
+ if(d && (u !== (tmp = d[':']))){ return tmp }
1506
+ k = k || O.fall_key; if(!n && O.fall_val){ n = {}; n[k] = O.fall_val; }
1507
+ if(!k || !n){ return }
1508
+ if(d === n[k]){ return d }
1509
+ if(!SEA.opt.check(n[k])){ return d }
1510
+ var soul = (n && n._ && n._['#']) || O.fall_soul, s = Gun.state.is(n, k) || O.fall_state;
1511
+ if(d && 4 === d.length && soul === d[0] && k === d[1] && fl(s) === fl(d[3])){
1512
+ return d[2];
1513
+ }
1514
+ if(s < SEA.opt.shuffle_attack){
1515
+ return d;
1516
+ }
1517
+ };
1518
+ SEA.opt.shuffle_attack = 1546329600000; // Jan 1, 2019
1519
+ var fl = Math.floor; // TODO: Still need to fix inconsistent state issue.
1520
+ // TODO: Potential bug? If pub/priv key starts with `-`? IDK how possible.
1521
+
1522
+ })(USE, './index');
1523
+ }());
1524
+ } (sea));
1525
+
1526
+ var seaExports = sea.exports;
1527
+ var SEA = /*@__PURE__*/getDefaultExportFromCjs(seaExports);
12
1528
 
13
1529
  let contractAddresses$1 = {
14
1530
  PROOF_OF_INTEGRITY_ADDRESS: "0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512",
@@ -16,15 +1532,15 @@ let contractAddresses$1 = {
16
1532
  };
17
1533
 
18
1534
  if (typeof window === 'undefined') {
19
- const { fileURLToPath } = require('url');
20
- const { dirname } = require('path');
21
- const { readFileSync } = require('fs');
22
- const { join } = require('path');
23
-
24
1535
  try {
1536
+ const { fileURLToPath } = require('url');
1537
+ const { dirname, join } = require('path');
1538
+ const { readFileSync } = require('fs');
1539
+
25
1540
  const __filename = fileURLToPath(import.meta.url);
26
1541
  const __dirname = dirname(__filename);
27
- const rawdata = readFileSync(join(__dirname, 'contract-address.json'), 'utf8');
1542
+
1543
+ const rawdata = readFileSync(join(__dirname, 'contract-address.json'));
28
1544
  contractAddresses$1 = JSON.parse(rawdata);
29
1545
  console.log("Loaded contract addresses:", contractAddresses$1);
30
1546
  } catch (error) {
@@ -40,56 +1556,6 @@ const LOCAL_CONFIG = {
40
1556
  GUN_PEER: "http://localhost:8765/gun"
41
1557
  };
42
1558
 
43
- // Indirizzi di produzione per diverse chain
44
- const CHAIN_CONFIG = {
45
- optimismSepolia: {
46
- STEALTH_ANNOUNCER_ADDRESS: "",
47
- PROOF_OF_INTEGRITY_ADDRESS: "",
48
- RPC_URL: "https://sepolia.optimism.io",
49
- CHAIN_ID: 11155420
50
- },
51
- arbitrumSepolia: {
52
- STEALTH_ANNOUNCER_ADDRESS: "",
53
- PROOF_OF_INTEGRITY_ADDRESS: "",
54
- RPC_URL: "https://sepolia-rollup.arbitrum.io/rpc",
55
- CHAIN_ID: 421614
56
- },
57
- localhost: {
58
- RPC_URL: "http://127.0.0.1:8545",
59
- CHAIN_ID: 1337
60
- }
61
- };
62
-
63
- // Funzione per ottenere gli indirizzi corretti
64
- function getAddressesForChain(chainName) {
65
- let config;
66
-
67
- // Se è localhost, prova a caricare gli indirizzi locali
68
- if (chainName === 'localhost') {
69
- try {
70
- // Carica gli indirizzi dal file generato dal deploy locale
71
- const localAddresses = require$$0;
72
- config = {
73
- ...CHAIN_CONFIG.localhost,
74
- ...localAddresses
75
- };
76
- console.log("Using local addresses:", config);
77
- return config;
78
- } catch (err) {
79
- console.warn('No local addresses found');
80
- throw new Error('No local addresses found. Did you run local deployment?');
81
- }
82
- }
83
-
84
- // Altrimenti usa gli indirizzi di produzione
85
- config = CHAIN_CONFIG[chainName];
86
- if (!config) {
87
- throw new Error(`Chain ${chainName} not supported. Supported chains: ${Object.keys(CHAIN_CONFIG).join(', ')}`);
88
- }
89
-
90
- return config;
91
- }
92
-
93
1559
  const STEALTH_ANNOUNCER_ABI = [
94
1560
  {
95
1561
  "inputs": [
@@ -421,12 +1887,12 @@ const PROOF_OF_INTEGRITY_ABI = [
421
1887
  "stateMutability": "view",
422
1888
  "type": "function"
423
1889
  }
424
- ];
1890
+ ];
1891
+ const STEALTH_ANNOUNCER_ADDRESS = "...";
425
1892
 
426
- // Ottieni gli indirizzi corretti per la chain
427
- const chainConfig = getAddressesForChain('optimismSepolia'); // o la chain desiderata
428
- const STEALTH_ANNOUNCER_ADDRESS = chainConfig.STEALTH_ANNOUNCER_ADDRESS;
429
- chainConfig.PROOF_OF_INTEGRITY_ADDRESS;
1893
+ // =============================================
1894
+ // IMPORTS AND GLOBAL VARIABLES
1895
+ // =============================================
430
1896
 
431
1897
  let PROOF_CONTRACT_ADDRESS;
432
1898
  let rpcUrl = "";