-
Notifications
You must be signed in to change notification settings - Fork 0
/
sea.js
1525 lines (1422 loc) · 64.2 KB
/
sea.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;(function(){
/* UNBUILD */
function USE(arg, req){
return req? require(arg) : arg.slice? USE[R(arg)] : function(mod, path){
arg(mod = {exports: {}});
USE[R(path)] = mod.exports;
}
function R(p){
return p.split('/').slice(-1).toString().replace('.js','');
}
}
if(typeof module !== "undefined"){ var MODULE = module }
/* UNBUILD */
;USE(function(module){
// Security, Encryption, and Authorization: SEA.js
// MANDATORY READING: https://gun.eco/explainers/data/security.html
// IT IS IMPLEMENTED IN A POLYFILL/SHIM APPROACH.
// THIS IS AN EARLY ALPHA!
if(typeof window !== "undefined"){ module.window = window }
var tmp = module.window || module, u;
var SEA = tmp.SEA || {};
if(SEA.window = module.window){ SEA.window.SEA = SEA }
try{ if(u+'' !== typeof MODULE){ MODULE.exports = SEA } }catch(e){}
module.exports = SEA;
})(USE, './root');
;USE(function(module){
var SEA = USE('./root');
try{ if(SEA.window){
if(location.protocol.indexOf('s') < 0
&& location.host.indexOf('localhost') < 0
&& ! /^127\.\d+\.\d+\.\d+$/.test(location.hostname)
&& location.protocol.indexOf('file:') < 0){
console.warn('HTTPS needed for WebCrypto in SEA, redirecting...');
location.protocol = 'https:'; // WebCrypto does NOT work without HTTPS!
}
} }catch(e){}
})(USE, './https');
;USE(function(module){
var u;
if(u+''== typeof btoa){
if(u+'' == typeof Buffer){
try{ global.Buffer = USE("buffer", 1).Buffer }catch(e){ console.log("Please `npm install buffer` or add it to your package.json !") }
}
global.btoa = function(data){ return Buffer.from(data, "binary").toString("base64") };
global.atob = function(data){ return Buffer.from(data, "base64").toString("binary") };
}
})(USE, './base64');
;USE(function(module){
USE('./base64');
// This is Array extended to have .toString(['utf8'|'hex'|'base64'])
function SeaArray() {}
Object.assign(SeaArray, { from: Array.from })
SeaArray.prototype = Object.create(Array.prototype)
SeaArray.prototype.toString = function(enc, start, end) { enc = enc || 'utf8'; start = start || 0;
const length = this.length
if (enc === 'hex') {
const buf = new Uint8Array(this)
return [ ...Array(((end && (end + 1)) || length) - start).keys()]
.map((i) => buf[ i + start ].toString(16).padStart(2, '0')).join('')
}
if (enc === 'utf8') {
return Array.from(
{ length: (end || length) - start },
(_, i) => String.fromCharCode(this[ i + start])
).join('')
}
if (enc === 'base64') {
return btoa(this)
}
}
module.exports = SeaArray;
})(USE, './array');
;USE(function(module){
USE('./base64');
// This is Buffer implementation used in SEA. Functionality is mostly
// compatible with NodeJS 'safe-buffer' and is used for encoding conversions
// between binary and 'hex' | 'utf8' | 'base64'
// See documentation and validation for safe implementation in:
// https://github.com/feross/safe-buffer#update
var SeaArray = USE('./array');
function SafeBuffer(...props) {
console.warn('new SafeBuffer() is depreciated, please use SafeBuffer.from()')
return SafeBuffer.from(...props)
}
SafeBuffer.prototype = Object.create(Array.prototype)
Object.assign(SafeBuffer, {
// (data, enc) where typeof data === 'string' then enc === 'utf8'|'hex'|'base64'
from() {
if (!Object.keys(arguments).length || arguments[0]==null) {
throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
}
const input = arguments[0]
let buf
if (typeof input === 'string') {
const enc = arguments[1] || 'utf8'
if (enc === 'hex') {
const bytes = input.match(/([\da-fA-F]{2})/g)
.map((byte) => parseInt(byte, 16))
if (!bytes || !bytes.length) {
throw new TypeError('Invalid first argument for type \'hex\'.')
}
buf = SeaArray.from(bytes)
} 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.
const length = input.length
const words = new Uint16Array(length)
Array.from({ length: length }, (_, i) => words[i] = input.charCodeAt(i))
buf = SeaArray.from(words)
} else if (enc === 'base64') {
const dec = atob(input)
const length = dec.length
const bytes = new Uint8Array(length)
Array.from({ length: length }, (_, i) => bytes[i] = dec.charCodeAt(i))
buf = SeaArray.from(bytes)
} else if (enc === 'binary') { // deprecated by above comment
buf = SeaArray.from(input) // some btoas were mishandled.
} else {
console.info('SafeBuffer.from unknown encoding: '+enc)
}
return buf
}
const byteLength = input.byteLength // what is going on here? FOR MARTTI
const length = input.byteLength ? input.byteLength : input.length
if (length) {
let buf
if (input instanceof ArrayBuffer) {
buf = new Uint8Array(input)
}
return SeaArray.from(buf || input)
}
},
// This is 'safe-buffer.alloc' sans encoding support
alloc(length, fill = 0 /*, enc*/ ) {
return SeaArray.from(new Uint8Array(Array.from({ length: length }, () => fill)))
},
// This is normal UNSAFE 'buffer.alloc' or 'new Buffer(length)' - don't use!
allocUnsafe(length) {
return SeaArray.from(new Uint8Array(Array.from({ length : length })))
},
// This puts together array of array like members
concat(arr) { // octet array
if (!Array.isArray(arr)) {
throw new TypeError('First argument must be Array containing ArrayBuffer or Uint8Array instances.')
}
return SeaArray.from(arr.reduce((ret, item) => ret.concat(Array.from(item)), []))
}
})
SafeBuffer.prototype.from = SafeBuffer.from
SafeBuffer.prototype.toString = SeaArray.prototype.toString
module.exports = SafeBuffer;
})(USE, './buffer');
;USE(function(module){
const SEA = USE('./root')
const api = {Buffer: USE('./buffer')}
var o = {}, u;
// ideally we can move away from JSON entirely? unlikely due to compatibility issues... oh well.
JSON.parseAsync = JSON.parseAsync || function(t,cb,r){ var u; try{ cb(u, JSON.parse(t,r)) }catch(e){ cb(e) } }
JSON.stringifyAsync = JSON.stringifyAsync || function(v,cb,r,s){ var u; try{ cb(u, JSON.stringify(v,r,s)) }catch(e){ cb(e) } }
api.parse = function(t,r){ return new Promise(function(res, rej){
JSON.parseAsync(t,function(err, raw){ err? rej(err) : res(raw) },r);
})}
api.stringify = function(v,r,s){ return new Promise(function(res, rej){
JSON.stringifyAsync(v,function(err, raw){ err? rej(err) : res(raw) },r,s);
})}
if(SEA.window){
api.crypto = window.crypto || window.msCrypto
api.subtle = (api.crypto||o).subtle || (api.crypto||o).webkitSubtle;
api.TextEncoder = window.TextEncoder;
api.TextDecoder = window.TextDecoder;
api.random = (len) => api.Buffer.from(api.crypto.getRandomValues(new Uint8Array(api.Buffer.alloc(len))));
}
if(!api.TextDecoder)
{
const { TextEncoder, TextDecoder } = USE((u+'' == typeof MODULE?'.':'')+'./lib/text-encoding', 1);
api.TextDecoder = TextDecoder;
api.TextEncoder = TextEncoder;
}
if(!api.crypto)
{
try
{
var crypto = USE('crypto', 1);
Object.assign(api, {
crypto,
random: (len) => api.Buffer.from(crypto.randomBytes(len))
});
const { Crypto: WebCrypto } = USE('@peculiar/webcrypto', 1);
api.ossl = api.subtle = new WebCrypto({directory: 'ossl'}).subtle // ECDH
}
catch(e){
console.log("Please `npm install @peculiar/webcrypto` or add it to your package.json !");
}}
module.exports = api
})(USE, './shim');
;USE(function(module){
var SEA = USE('./root');
var shim = USE('./shim');
var s = {};
s.pbkdf2 = {hash: {name : 'SHA-256'}, iter: 100000, ks: 64};
s.ecdsa = {
pair: {name: 'ECDSA', namedCurve: 'P-256'},
sign: {name: 'ECDSA', hash: {name: 'SHA-256'}}
};
s.ecdh = {name: 'ECDH', namedCurve: 'P-256'};
// This creates Web Cryptography API compliant JWK for sign/verify purposes
s.jwk = function(pub, d){ // d === priv
pub = pub.split('.');
var x = pub[0], y = pub[1];
var jwk = {kty: "EC", crv: "P-256", x: x, y: y, ext: true};
jwk.key_ops = d ? ['sign'] : ['verify'];
if(d){ jwk.d = d }
return jwk;
};
s.keyToJwk = function(keyBytes) {
const keyB64 = keyBytes.toString('base64');
const k = keyB64.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');
return { kty: 'oct', k: k, ext: false, alg: 'A256GCM' };
}
s.recall = {
validity: 12 * 60 * 60, // internally in seconds : 12 hours
hook: function(props){ return props } // { iat, exp, alias, remember } // or return new Promise((resolve, reject) => resolve(props)
};
s.check = function(t){ return (typeof t == 'string') && ('SEA{' === t.slice(0,4)) }
s.parse = async function p(t){ try {
var yes = (typeof t == 'string');
if(yes && 'SEA{' === t.slice(0,4)){ t = t.slice(3) }
return yes ? await shim.parse(t) : t;
} catch (e) {}
return t;
}
SEA.opt = s;
module.exports = s
})(USE, './settings');
;USE(function(module){
var shim = USE('./shim');
module.exports = async function(d, o){
var t = (typeof d == 'string')? d : await shim.stringify(d);
var hash = await shim.subtle.digest({name: o||'SHA-256'}, new shim.TextEncoder().encode(t));
return shim.Buffer.from(hash);
}
})(USE, './sha256');
;USE(function(module){
// This internal func returns SHA-1 hashed data for KeyID generation
const __shim = USE('./shim')
const subtle = __shim.subtle
const ossl = __shim.ossl ? __shim.ossl : subtle
const sha1hash = (b) => ossl.digest({name: 'SHA-1'}, new ArrayBuffer(b))
module.exports = sha1hash
})(USE, './sha1');
;USE(function(module){
var SEA = USE('./root');
var shim = USE('./shim');
var S = USE('./settings');
var sha = USE('./sha256');
var u;
SEA.work = SEA.work || (async (data, pair, cb, opt) => { try { // used to be named `proof`
var salt = (pair||{}).epub || pair; // epub not recommended, salt should be random!
opt = opt || {};
if(salt instanceof Function){
cb = salt;
salt = u;
}
data = (typeof data == 'string')? data : await shim.stringify(data);
if('sha' === (opt.name||'').toLowerCase().slice(0,3)){
var rsha = shim.Buffer.from(await sha(data, opt.name), 'binary').toString(opt.encode || 'base64')
if(cb){ try{ cb(rsha) }catch(e){console.log(e)} }
return rsha;
}
salt = salt || shim.random(9);
var key = await (shim.ossl || shim.subtle).importKey('raw', new shim.TextEncoder().encode(data), {name: opt.name || 'PBKDF2'}, false, ['deriveBits']);
var work = await (shim.ossl || shim.subtle).deriveBits({
name: opt.name || 'PBKDF2',
iterations: opt.iterations || S.pbkdf2.iter,
salt: new shim.TextEncoder().encode(opt.salt || salt),
hash: opt.hash || S.pbkdf2.hash,
}, key, opt.length || (S.pbkdf2.ks * 8))
data = shim.random(data.length) // Erase data in case of passphrase
var r = shim.Buffer.from(work, 'binary').toString(opt.encode || 'base64')
if(cb){ try{ cb(r) }catch(e){console.log(e)} }
return r;
} catch(e) {
console.log(e);
SEA.err = e;
if(SEA.throw){ throw e }
if(cb){ cb() }
return;
}});
module.exports = SEA.work;
})(USE, './work');
;USE(function(module){
var SEA = USE('./root');
var shim = USE('./shim');
var S = USE('./settings');
SEA.name = SEA.name || (async (cb, opt) => { try {
if(cb){ try{ cb() }catch(e){console.log(e)} }
return;
} catch(e) {
console.log(e);
SEA.err = e;
if(SEA.throw){ throw e }
if(cb){ cb() }
return;
}});
//SEA.pair = async (data, proof, cb) => { try {
SEA.pair = SEA.pair || (async (cb, opt) => { try {
var ecdhSubtle = shim.ossl || shim.subtle;
// First: ECDSA keys for signing/verifying...
var sa = await shim.subtle.generateKey({name: 'ECDSA', namedCurve: 'P-256'}, true, [ 'sign', 'verify' ])
.then(async (keys) => {
// privateKey scope doesn't leak out from here!
//const { d: priv } = await shim.subtle.exportKey('jwk', keys.privateKey)
var key = {};
key.priv = (await shim.subtle.exportKey('jwk', keys.privateKey)).d;
var pub = await shim.subtle.exportKey('jwk', keys.publicKey);
//const pub = Buff.from([ x, y ].join(':')).toString('base64') // old
key.pub = pub.x+'.'+pub.y; // new
// x and y are already base64
// pub is UTF8 but filename/URL safe (https://www.ietf.org/rfc/rfc3986.txt)
// but split on a non-base64 letter.
return key;
})
// To include PGPv4 kind of keyId:
// const pubId = await SEA.keyid(keys.pub)
// Next: ECDH keys for encryption/decryption...
try{
var dh = await ecdhSubtle.generateKey({name: 'ECDH', namedCurve: 'P-256'}, true, ['deriveKey'])
.then(async (keys) => {
// privateKey scope doesn't leak out from here!
var key = {};
key.epriv = (await ecdhSubtle.exportKey('jwk', keys.privateKey)).d;
var pub = await ecdhSubtle.exportKey('jwk', keys.publicKey);
//const epub = Buff.from([ ex, ey ].join(':')).toString('base64') // old
key.epub = pub.x+'.'+pub.y; // new
// ex and ey are already base64
// epub is UTF8 but filename/URL safe (https://www.ietf.org/rfc/rfc3986.txt)
// but split on a non-base64 letter.
return key;
})
}catch(e){
if(SEA.window){ throw e }
if(e == 'Error: ECDH is not a supported algorithm'){ console.log('Ignoring ECDH...') }
else { throw e }
} dh = dh || {};
var r = { pub: sa.pub, priv: sa.priv, /* pubId, */ epub: dh.epub, epriv: dh.epriv }
if(cb){ try{ cb(r) }catch(e){console.log(e)} }
return r;
} catch(e) {
console.log(e);
SEA.err = e;
if(SEA.throw){ throw e }
if(cb){ cb() }
return;
}});
module.exports = SEA.pair;
})(USE, './pair');
;USE(function(module){
var SEA = USE('./root');
var shim = USE('./shim');
var S = USE('./settings');
var sha = USE('./sha256');
var u;
SEA.sign = SEA.sign || (async (data, pair, cb, opt) => { try {
opt = opt || {};
if(!(pair||opt).priv){
if(!SEA.I){ throw 'No signing key.' }
pair = await SEA.I(null, {what: data, how: 'sign', why: opt.why});
}
if(u === data){ throw '`undefined` not allowed.' }
var json = await S.parse(data);
var check = opt.check = opt.check || json;
if(SEA.verify && (SEA.opt.check(check) || (check && check.s && check.m))
&& u !== await SEA.verify(check, pair)){ // don't sign if we already signed it.
var r = await S.parse(check);
if(!opt.raw){ r = 'SEA' + await shim.stringify(r) }
if(cb){ try{ cb(r) }catch(e){console.log(e)} }
return r;
}
var pub = pair.pub;
var priv = pair.priv;
var jwk = S.jwk(pub, priv);
var hash = await sha(json);
var sig = await (shim.ossl || shim.subtle).importKey('jwk', jwk, {name: 'ECDSA', namedCurve: 'P-256'}, false, ['sign'])
.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!
var r = {m: json, s: shim.Buffer.from(sig, 'binary').toString(opt.encode || 'base64')}
if(!opt.raw){ r = 'SEA' + await shim.stringify(r) }
if(cb){ try{ cb(r) }catch(e){console.log(e)} }
return r;
} catch(e) {
console.log(e);
SEA.err = e;
if(SEA.throw){ throw e }
if(cb){ cb() }
return;
}});
module.exports = SEA.sign;
})(USE, './sign');
;USE(function(module){
var SEA = USE('./root');
var shim = USE('./shim');
var S = USE('./settings');
var sha = USE('./sha256');
var u;
SEA.verify = SEA.verify || (async (data, pair, cb, opt) => { try {
var json = await S.parse(data);
if(false === pair){ // don't verify!
var raw = await S.parse(json.m);
if(cb){ try{ cb(raw) }catch(e){console.log(e)} }
return raw;
}
opt = opt || {};
// SEA.I // verify is free! Requires no user permission.
var pub = pair.pub || pair;
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']);
var hash = await sha(json.m);
var buf, sig, check, tmp; try{
buf = shim.Buffer.from(json.s, opt.encode || 'base64'); // NEW DEFAULT!
sig = new Uint8Array(buf);
check = await (shim.ossl || shim.subtle).verify({name: 'ECDSA', hash: {name: 'SHA-256'}}, key, sig, new Uint8Array(hash));
if(!check){ throw "Signature did not match." }
}catch(e){
if(SEA.opt.fallback){
return await SEA.opt.fall_verify(data, pair, cb, opt);
}
}
var r = check? await S.parse(json.m) : u;
if(cb){ try{ cb(r) }catch(e){console.log(e)} }
return r;
} catch(e) {
console.log(e); // mismatched owner FOR MARTTI
SEA.err = e;
if(SEA.throw){ throw e }
if(cb){ cb() }
return;
}});
module.exports = SEA.verify;
// legacy & ossl memory leak mitigation:
var knownKeys = {};
var keyForPair = SEA.opt.slow_leak = pair => {
if (knownKeys[pair]) return knownKeys[pair];
var jwk = S.jwk(pair);
knownKeys[pair] = (shim.ossl || shim.subtle).importKey("jwk", jwk, {name: 'ECDSA', namedCurve: 'P-256'}, false, ["verify"]);
return knownKeys[pair];
};
var O = SEA.opt;
SEA.opt.fall_verify = async function(data, pair, cb, opt, f){
if(f === SEA.opt.fallback){ throw "Signature did not match" } f = f || 1;
var tmp = data||'';
data = SEA.opt.unpack(data) || data;
var json = await S.parse(data), pub = pair.pub || pair, key = await SEA.opt.slow_leak(pub);
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.
var buf; var sig; var check; try{
buf = shim.Buffer.from(json.s, opt.encode || 'base64') // NEW DEFAULT!
sig = new Uint8Array(buf)
check = await (shim.ossl || shim.subtle).verify({name: 'ECDSA', hash: {name: 'SHA-256'}}, key, sig, new Uint8Array(hash))
if(!check){ throw "Signature did not match." }
}catch(e){ try{
buf = shim.Buffer.from(json.s, 'utf8') // AUTO BACKWARD OLD UTF8 DATA!
sig = new Uint8Array(buf)
check = await (shim.ossl || shim.subtle).verify({name: 'ECDSA', hash: {name: 'SHA-256'}}, key, sig, new Uint8Array(hash))
}catch(e){
if(!check){ throw "Signature did not match." }
}
}
var r = check? await S.parse(json.m) : u;
O.fall_soul = tmp['#']; O.fall_key = tmp['.']; O.fall_val = data; O.fall_state = tmp['>'];
if(cb){ try{ cb(r) }catch(e){console.log(e)} }
return r;
}
SEA.opt.fallback = 2;
})(USE, './verify');
;USE(function(module){
var shim = USE('./shim');
var S = USE('./settings');
var sha256hash = USE('./sha256');
const importGen = async (key, salt, opt) => {
//const combo = shim.Buffer.concat([shim.Buffer.from(key, 'utf8'), salt || shim.random(8)]).toString('utf8') // old
opt = opt || {};
const combo = key + (salt || shim.random(8)).toString('utf8'); // new
const hash = shim.Buffer.from(await sha256hash(combo), 'binary')
const jwkKey = S.keyToJwk(hash)
return await shim.subtle.importKey('jwk', jwkKey, {name:'AES-GCM'}, false, ['encrypt', 'decrypt'])
}
module.exports = importGen;
})(USE, './aeskey');
;USE(function(module){
var SEA = USE('./root');
var shim = USE('./shim');
var S = USE('./settings');
var aeskey = USE('./aeskey');
var u;
SEA.encrypt = SEA.encrypt || (async (data, pair, cb, opt) => { try {
opt = opt || {};
var key = (pair||opt).epriv || pair;
if(u === data){ throw '`undefined` not allowed.' }
if(!key){
if(!SEA.I){ throw 'No encryption key.' }
pair = await SEA.I(null, {what: data, how: 'encrypt', why: opt.why});
key = pair.epriv || pair;
}
var msg = (typeof data == 'string')? data : await shim.stringify(data);
var rand = {s: shim.random(9), iv: shim.random(15)}; // consider making this 9 and 15 or 18 or 12 to reduce == padding.
var ct = await aeskey(key, rand.s, opt).then((aes) => (/*shim.ossl ||*/ shim.subtle).encrypt({ // Keeping the AES key scope as private as possible...
name: opt.name || 'AES-GCM', iv: new Uint8Array(rand.iv)
}, aes, new shim.TextEncoder().encode(msg)));
var r = {
ct: shim.Buffer.from(ct, 'binary').toString(opt.encode || 'base64'),
iv: rand.iv.toString(opt.encode || 'base64'),
s: rand.s.toString(opt.encode || 'base64')
}
if(!opt.raw){ r = 'SEA' + await shim.stringify(r) }
if(cb){ try{ cb(r) }catch(e){console.log(e)} }
return r;
} catch(e) {
console.log(e);
SEA.err = e;
if(SEA.throw){ throw e }
if(cb){ cb() }
return;
}});
module.exports = SEA.encrypt;
})(USE, './encrypt');
;USE(function(module){
var SEA = USE('./root');
var shim = USE('./shim');
var S = USE('./settings');
var aeskey = USE('./aeskey');
SEA.decrypt = SEA.decrypt || (async (data, pair, cb, opt) => { try {
opt = opt || {};
var key = (pair||opt).epriv || pair;
if(!key){
if(!SEA.I){ throw 'No decryption key.' }
pair = await SEA.I(null, {what: data, how: 'decrypt', why: opt.why});
key = pair.epriv || pair;
}
var json = await S.parse(data);
var buf, bufiv, bufct; try{
buf = shim.Buffer.from(json.s, opt.encode || 'base64');
bufiv = shim.Buffer.from(json.iv, opt.encode || 'base64');
bufct = shim.Buffer.from(json.ct, opt.encode || 'base64');
var ct = await aeskey(key, buf, opt).then((aes) => (/*shim.ossl ||*/ shim.subtle).decrypt({ // Keeping aesKey scope as private as possible...
name: opt.name || 'AES-GCM', iv: new Uint8Array(bufiv), tagLength: 128
}, aes, new Uint8Array(bufct)));
}catch(e){
if('utf8' === opt.encode){ throw "Could not decrypt" }
if(SEA.opt.fallback){
opt.encode = 'utf8';
return await SEA.decrypt(data, pair, cb, opt);
}
}
var r = await S.parse(new shim.TextDecoder('utf8').decode(ct));
if(cb){ try{ cb(r) }catch(e){console.log(e)} }
return r;
} catch(e) {
console.log(e);
SEA.err = e;
if(SEA.throw){ throw e }
if(cb){ cb() }
return;
}});
module.exports = SEA.decrypt;
})(USE, './decrypt');
;USE(function(module){
var SEA = USE('./root');
var shim = USE('./shim');
var S = USE('./settings');
// Derive shared secret from other's pub and my epub/epriv
SEA.secret = SEA.secret || (async (key, pair, cb, opt) => { try {
opt = opt || {};
if(!pair || !pair.epriv || !pair.epub){
if(!SEA.I){ throw 'No secret mix.' }
pair = await SEA.I(null, {what: key, how: 'secret', why: opt.why});
}
var pub = key.epub || key;
var epub = pair.epub;
var epriv = pair.epriv;
var ecdhSubtle = shim.ossl || shim.subtle;
var pubKeyData = keysToEcdhJwk(pub);
var props = Object.assign({ public: await ecdhSubtle.importKey(...pubKeyData, true, []) },{name: 'ECDH', namedCurve: 'P-256'}); // Thanks to @sirpy !
var privKeyData = keysToEcdhJwk(epub, epriv);
var derived = await ecdhSubtle.importKey(...privKeyData, false, ['deriveBits']).then(async (privKey) => {
// privateKey scope doesn't leak out from here!
var derivedBits = await ecdhSubtle.deriveBits(props, privKey, 256);
var rawBits = new Uint8Array(derivedBits);
var derivedKey = await ecdhSubtle.importKey('raw', rawBits,{ name: 'AES-GCM', length: 256 }, true, [ 'encrypt', 'decrypt' ]);
return ecdhSubtle.exportKey('jwk', derivedKey).then(({ k }) => k);
})
var r = derived;
if(cb){ try{ cb(r) }catch(e){console.log(e)} }
return r;
} catch(e) {
console.log(e);
SEA.err = e;
if(SEA.throw){ throw e }
if(cb){ cb() }
return;
}});
// can this be replaced with settings.jwk?
var keysToEcdhJwk = (pub, d) => { // d === priv
//var [ x, y ] = shim.Buffer.from(pub, 'base64').toString('utf8').split(':') // old
var [ x, y ] = pub.split('.') // new
var jwk = d ? { d: d } : {}
return [ // Use with spread returned value...
'jwk',
Object.assign(
jwk,
{ x: x, y: y, kty: 'EC', crv: 'P-256', ext: true }
), // ??? refactor
{name: 'ECDH', namedCurve: 'P-256'}
]
}
module.exports = SEA.secret;
})(USE, './secret');
;USE(function(module){
var SEA = USE('./root');
// This is to certify that a group of "certificants" can "put" anything at a group of matched "paths" to the certificate authority's graph
SEA.certify = SEA.certify || (async (certificants, policy = {}, authority, cb, opt = {}) => { try {
/*
The Certify Protocol was made out of love by a Vietnamese code enthusiast. Vietnamese people around the world deserve respect!
IMPORTANT: A Certificate is like a Signature. No one knows who (authority) created/signed a cert until you put it into their graph.
"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.
"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.
"authority": Key pair or priv of the certificate authority.
"cb": A callback function after all things are done.
"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.
*/
console.log('SEA.certify() is an early experimental community supported method that may change API behavior without warning in any future version.')
certificants = (() => {
var data = []
if (certificants) {
if ((typeof certificants === 'string' || Array.isArray(certificants)) && certificants.indexOf('*') > -1) return '*'
if (typeof certificants === 'string') return certificants
if (Array.isArray(certificants)) {
if (certificants.length === 1 && certificants[0]) return typeof certificants[0] === 'object' && certificants[0].pub ? certificants[0].pub : typeof certificants[0] === 'string' ? certificants[0] : null
certificants.map(certificant => {
if (typeof certificant ==='string') data.push(certificant)
else if (typeof certificant === 'object' && certificant.pub) data.push(certificant.pub)
})
}
if (typeof certificants === 'object' && certificants.pub) return certificants.pub
return data.length > 0 ? data : null
}
return
})()
if (!certificants) return console.log("No certificant found.")
const expiry = opt.expiry && (typeof opt.expiry === 'number' || typeof opt.expiry === 'string') ? parseFloat(opt.expiry) : null
const readPolicy = (policy || {}).read ? policy.read : null
const writePolicy = (policy || {}).write ? policy.write : typeof policy === 'string' || Array.isArray(policy) || policy["+"] || policy["#"] || policy["."] || policy["="] || policy["*"] || policy[">"] || policy["<"] ? policy : null
// The "blacklist" feature is now renamed to "block". Why ? BECAUSE BLACK LIVES MATTER!
// We can now use 3 keys: block, blacklist, ban
const block = (opt || {}).block || (opt || {}).blacklist || (opt || {}).ban || {}
const readBlock = block.read && (typeof block.read === 'string' || (block.read || {})['#']) ? block.read : null
const writeBlock = typeof block === 'string' ? block : block.write && (typeof block.write === 'string' || block.write['#']) ? block.write : null
if (!readPolicy && !writePolicy) return console.log("No policy found.")
// reserved keys: c, e, r, w, rb, wb
const data = JSON.stringify({
c: certificants,
...(expiry ? {e: expiry} : {}), // inject expiry if possible
...(readPolicy ? {r: readPolicy } : {}), // "r" stands for read, which means read permission.
...(writePolicy ? {w: writePolicy} : {}), // "w" stands for write, which means write permission.
...(readBlock ? {rb: readBlock} : {}), // inject READ block if possible
...(writeBlock ? {wb: writeBlock} : {}), // inject WRITE block if possible
})
const certificate = await SEA.sign(data, authority, null, {raw:1})
var r = certificate
if(!opt.raw){ r = 'SEA'+JSON.stringify(r) }
if(cb){ try{ cb(r) }catch(e){console.log(e)} }
return r;
} catch(e) {
SEA.err = e;
if(SEA.throw){ throw e }
if(cb){ cb() }
return;
}});
module.exports = SEA.certify;
})(USE, './certify');
;USE(function(module){
var shim = USE('./shim');
// Practical examples about usage found in tests.
var SEA = USE('./root');
SEA.work = USE('./work');
SEA.sign = USE('./sign');
SEA.verify = USE('./verify');
SEA.encrypt = USE('./encrypt');
SEA.decrypt = USE('./decrypt');
SEA.certify = USE('./certify');
//SEA.opt.aeskey = USE('./aeskey'); // not official! // this causes problems in latest WebCrypto.
SEA.random = SEA.random || shim.random;
// This is Buffer used in SEA and usable from Gun/SEA application also.
// For documentation see https://nodejs.org/api/buffer.html
SEA.Buffer = SEA.Buffer || USE('./buffer');
// These SEA functions support now ony Promises or
// async/await (compatible) code, use those like Promises.
//
// Creates a wrapper library around Web Crypto API
// for various AES, ECDSA, PBKDF2 functions we called above.
// Calculate public key KeyID aka PGPv4 (result: 8 bytes as hex string)
SEA.keyid = SEA.keyid || (async (pub) => {
try {
// base64('base64(x):base64(y)') => shim.Buffer(xy)
const pb = shim.Buffer.concat(
pub.replace(/-/g, '+').replace(/_/g, '/').split('.')
.map((t) => shim.Buffer.from(t, 'base64'))
)
// id is PGPv4 compliant raw key
const id = shim.Buffer.concat([
shim.Buffer.from([0x99, pb.length / 0x100, pb.length % 0x100]), pb
])
const sha1 = await sha1hash(id)
const hash = shim.Buffer.from(sha1, 'binary')
return hash.toString('hex', hash.length - 8) // 16-bit ID as hex
} catch (e) {
console.log(e)
throw e
}
});
// all done!
// Obviously it is missing MANY necessary features. This is only an alpha release.
// Please experiment with it, audit what I've done so far, and complain about what needs to be added.
// SEA should be a full suite that is easy and seamless to use.
// Again, scroll naer the top, where I provide an EXAMPLE of how to create a user and sign in.
// Once logged in, the rest of the code you just read handled automatically signing/validating data.
// But all other behavior needs to be equally easy, like opinionated ways of
// Adding friends (trusted public keys), sending private messages, etc.
// Cheers! Tell me what you think.
((SEA.window||{}).GUN||{}).SEA = SEA;
module.exports = SEA
// -------------- END SEA MODULES --------------------
// -- BEGIN SEA+GUN MODULES: BUNDLED BY DEFAULT UNTIL OTHERS USE SEA ON OWN -------
})(USE, './sea');
;USE(function(module){
var SEA = USE('./sea'), Gun, u;
if(SEA.window){
Gun = SEA.window.GUN || {chain:{}};
} else {
Gun = USE((u+'' == typeof MODULE?'.':'')+'./gun', 1);
}
SEA.GUN = Gun;
function User(root){
this._ = {$: this};
}
User.prototype = (function(){ function F(){}; F.prototype = Gun.chain; return new F() }()) // Object.create polyfill
User.prototype.constructor = User;
// let's extend the gun chain with a `user` function.
// only one user can be logged in at a time, per gun instance.
Gun.chain.user = function(pub){
var gun = this, root = gun.back(-1), user;
if(pub){
pub = SEA.opt.pub((pub._||'')['#']) || pub;
return root.get('~'+pub);
}
if(user = root.back('user')){ return user }
var root = (root._), at = root, uuid = at.opt.uuid || lex;
(at = (user = at.user = gun.chain(new User))._).opt = {};
at.opt.uuid = function(cb){
var id = uuid(), pub = root.user;
if(!pub || !(pub = pub.is) || !(pub = pub.pub)){ return id }
id = '~' + pub + '/' + id;
if(cb && cb.call){ cb(null, id) }
return id;
}
return user;
}
function lex(){ return Gun.state().toString(36).replace('.','') }
Gun.User = User;
User.GUN = Gun;
User.SEA = Gun.SEA = SEA;
module.exports = User;
})(USE, './user');
;USE(function(module){
var u, Gun = (''+u != typeof window)? (window.Gun||{chain:{}}) : USE((''+u === typeof MODULE?'.':'')+'./gun', 1);
Gun.chain.then = function(cb, opt){
var gun = this, p = (new Promise(function(res, rej){
gun.once(res, opt);
}));
return cb? p.then(cb) : p;
}
})(USE, './then');
;USE(function(module){
var User = USE('./user'), SEA = User.SEA, Gun = User.GUN, noop = function(){};
// Well first we have to actually create a user. That is what this function does.
User.prototype.create = function(...args){
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;
var alias = pair && (pair.pub || pair.epub) ? pair.pub : typeof args[0] === 'string' ? args[0] : null;
var pass = pair && (pair.pub || pair.epub) ? pair : alias && typeof args[1] === 'string' ? args[1] : null;
var cb = args.filter(arg => typeof arg === 'function')[0] || null; // cb now can stand anywhere, after alias/pass or pair
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
var gun = this, cat = (gun._), root = gun.back(-1);
cb = cb || noop;
opt = opt || {};
if(false !== opt.check){
var err;
if(!alias){ err = "No user." }
if((pass||'').length < 8){ err = "Password too short!" }
if(err){
cb({err: Gun.log(err)});
return gun;
}
}
if(cat.ing){
(cb || noop)({err: Gun.log("User is already being created or authenticated!"), wait: true});
return gun;
}
cat.ing = true;
var act = {}, u;
act.a = function(pubs){
act.pubs = pubs;
if(pubs && !opt.already){
// If we can enforce that a user name is already taken, it might be nice to try, but this is not guaranteed.
var ack = {err: Gun.log('User already created!')};
cat.ing = false;
(cb || noop)(ack);
gun.leave();
return;
}
act.salt = String.random(64); // pseudo-randomly create a salt, then use PBKDF2 function to extend the password with it.
SEA.work(pass, act.salt, act.b); // this will take some short amount of time to produce a proof, which slows brute force attacks.
}
act.b = function(proof){
act.proof = proof;
pair ? act.c(pair) : SEA.pair(act.c) // generate a brand new key pair or use the existing.
}
act.c = function(pair){
var tmp
act.pair = pair || {};
if(tmp = cat.root.user){
tmp._.sea = pair;
tmp.is = {pub: pair.pub, epub: pair.epub, alias: alias};
}
// 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!
act.data = {pub: pair.pub};
act.d();
}
act.d = function(){
act.data.alias = alias;
act.e();
}
act.e = function(){
act.data.epub = act.pair.epub;
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!
}
act.f = function(auth){
act.data.auth = JSON.stringify({ek: auth, s: act.salt});
act.g(act.data.auth);
}
act.g = function(auth){ var tmp;
act.data.auth = act.data.auth || auth;
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.
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.
}
act.h = function(data, key, msg, eve){
eve.off(); act.h.ok = 1; act.i();
}
act.i = function(data, key, msg, eve){
if(eve){ act.i.ok = 1; eve.off() }
if(!act.h.ok || !act.i.ok){ return }
cat.ing = false;
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)
if(noop === cb){ pair ? gun.auth(pair) : gun.auth(alias, pass) } // if no callback is passed, auto-login after signing up.
}
root.get('~@'+alias).once(act.a);
return gun;
}
User.prototype.leave = function(opt, cb){
var gun = this, user = (gun.back(-1)._).user;
if(user){
delete user.is;
delete user._.is;
delete user._.sea;
}
if(SEA.window){
try{var sS = {};
sS = window.sessionStorage;
delete sS.recall;
delete sS.pair;
}catch(e){};
}
return gun;
}
})(USE, './create');
;USE(function(module){
var User = USE('./user'), SEA = User.SEA, Gun = User.GUN, noop = function(){};
// now that we have created a user, we want to authenticate them!
User.prototype.auth = function(...args){ // TODO: this PR with arguments need to be cleaned up / refactored.
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;
var alias = !pair && typeof args[0] === 'string' ? args[0] : null;
var pass = (alias || (pair && !(pair.priv && pair.epriv))) && typeof args[1] === 'string' ? args[1] : null;
var cb = args.filter(arg => typeof arg === 'function')[0] || null; // cb now can stand anywhere, after alias/pass or pair
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
var gun = this, cat = (gun._), root = gun.back(-1);
if(cat.ing){
(cb || noop)({err: Gun.log("User is already being created or authenticated!"), wait: true});
return gun;
}
cat.ing = true;
var act = {}, u;
act.a = function(data){
if(!data){ return act.b() }
if(!data.pub){
var tmp = []; Object.keys(data).forEach(function(k){ if('_'==k){ return } tmp.push(data[k]) })
return act.b(tmp);
}
if(act.name){ return act.f(data) }
act.c((act.data = data).auth);
}
act.b = function(list){
var get = (act.list = (act.list||[]).concat(list||[])).shift();
if(u === get){
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.') }
return act.err('Wrong user or password.')
}
root.get(get).once(act.a);
}
act.c = function(auth){
if(u === auth){ return act.b() }
if('string' == typeof auth){ return act.c(obj_ify(auth)) } // in case of legacy
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.