-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsea.js
1581 lines (1475 loc) · 60.5 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 */
var root;
if(typeof window !== "undefined"){ root = window }
if(typeof global !== "undefined"){ root = global }
root = root || {};
var console = root.console || {log: function(){}};
function USE(arg){
return 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 common = module }
/* UNBUILD */
;USE(function(module){
// Security, Encryption, and Authorization: SEA.js
// MANDATORY READING: http://gun.js.org/explainers/data/security.html
// THIS IS AN EARLY ALPHA!
function SEA(){}
if(typeof window !== "undefined"){ SEA.window = window }
module.exports = SEA;
})(USE, './root');
;USE(function(module){
var SEA = USE('./root');
if(SEA.window){
if(location.protocol.indexOf('s') < 0
&& location.host.indexOf('localhost') < 0
&& location.protocol.indexOf('file:') < 0){
location.protocol = 'https:';
}
}
})(USE, './https');
;USE(function(module){
// 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 = 'utf8', start = 0, end) {
const { length } = this
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){
// 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) {
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') {
const { length } = input
const words = new Uint16Array(length)
Array.from({ length }, (_, i) => words[i] = input.charCodeAt(i))
buf = SeaArray.from(words)
} else if (enc === 'base64') {
const dec = atob(input)
const { length } = dec
const bytes = new Uint8Array(length)
Array.from({ length }, (_, i) => bytes[i] = dec.charCodeAt(i))
buf = SeaArray.from(bytes)
} else if (enc === 'binary') {
buf = SeaArray.from(input)
} else {
console.info(`SafeBuffer.from unknown encoding: '${enc}'`)
}
return buf
}
const { byteLength, length = byteLength } = input
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 }, () => fill)))
},
// This is normal UNSAFE 'buffer.alloc' or 'new Buffer(length)' - don't use!
allocUnsafe(length) {
return SeaArray.from(new Uint8Array(Array.from({ 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 Buffer = USE('./buffer')
const api = {Buffer: Buffer}
if (typeof __webpack_require__ === 'function' || typeof window !== 'undefined') {
const { msCrypto, crypto = msCrypto } = window // STD or M$
const { webkitSubtle, subtle = webkitSubtle } = crypto // STD or iSafari
const { TextEncoder, TextDecoder } = window
Object.assign(api, {
crypto,
subtle,
TextEncoder,
TextDecoder,
random: (len) => Buffer.from(crypto.getRandomValues(new Uint8Array(Buffer.alloc(len))))
})
} else {
try{
const crypto = require('crypto')
//const WebCrypto = require('node-webcrypto-ossl')
//const { subtle: ossl } = new WebCrypto({directory: 'key_storage'}) // ECDH
const { subtle } = require('@trust/webcrypto') // All but ECDH
const { TextEncoder, TextDecoder } = require('text-encoding')
Object.assign(api, {
crypto,
subtle,
//ossl,
TextEncoder,
TextDecoder,
random: (len) => Buffer.from(crypto.randomBytes(len))
})
}catch(e){
console.log("@trust/webcrypto and text-encoding are not included by default, you must add it to your package.json!");
TRUST_WEBCRYPTO_OR_TEXT_ENCODING_NOT_INSTALLED;
}
}
module.exports = api
})(USE, './shim');
;USE(function(module){
const Buffer = USE('./buffer')
const settings = {}
// Encryption parameters
const pbkdf2 = { hash: 'SHA-256', iter: 100000, ks: 64 }
const ecdsaSignProps = { name: 'ECDSA', hash: { name: 'SHA-256' } }
const ecdsaKeyProps = { name: 'ECDSA', namedCurve: 'P-256' }
const ecdhKeyProps = { name: 'ECDH', namedCurve: 'P-256' }
const _initial_authsettings = {
validity: 12 * 60 * 60, // internally in seconds : 12 hours
hook: (props) => props // { iat, exp, alias, remember }
// or return new Promise((resolve, reject) => resolve(props)
}
// These are used to persist user's authentication "session"
const authsettings = Object.assign({}, _initial_authsettings)
// This creates Web Cryptography API compliant JWK for sign/verify purposes
const keysToEcdsaJwk = (pub, d) => { // d === priv
//const [ x, y ] = Buffer.from(pub, 'base64').toString('utf8').split(':') // old
const [ x, y ] = pub.split('.') // new
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;
}
Object.assign(settings, {
pbkdf2,
ecdsa: {
pair: ecdsaKeyProps,
sign: ecdsaSignProps
},
ecdh: ecdhKeyProps,
jwk: keysToEcdsaJwk,
recall: authsettings
})
module.exports = settings
})(USE, './settings');
;USE(function(module){
module.exports = (props) => {
try {
if(props.slice && 'SEA{' === props.slice(0,4)){
props = props.slice(3);
}
return props.slice ? JSON.parse(props) : props
} catch (e) {} //eslint-disable-line no-empty
return props
}
})(USE, './parse');
;USE(function(module){
const {
subtle, ossl = subtle, random: getRandomBytes, TextEncoder, TextDecoder
} = USE('./shim')
const Buffer = USE('./buffer')
const parse = USE('./parse')
const { pbkdf2 } = USE('./settings')
// This internal func returns SHA-256 hashed data for signing
const sha256hash = async (mm) => {
const m = parse(mm)
const hash = await ossl.digest({name: pbkdf2.hash}, new TextEncoder().encode(m))
return Buffer.from(hash)
}
module.exports = sha256hash
})(USE, './sha256');
;USE(function(module){
// This internal func returns SHA-1 hashed data for KeyID generation
const { subtle, ossl = subtle } = USE('./shim')
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 u;
SEA.work = async (data, pair, cb) => { try { // used to be named `proof`
var salt = pair.epub || pair; // epub not recommended, salt should be random!
if(salt instanceof Function){
cb = salt;
salt = u;
}
salt = salt || shim.random(9);
if (SEA.window) {
// For browser subtle works fine
const key = await shim.subtle.importKey(
'raw', new shim.TextEncoder().encode(data), { name: 'PBKDF2' }, false, ['deriveBits']
)
const result = await shim.subtle.deriveBits({
name: 'PBKDF2',
iterations: S.pbkdf2.iter,
salt: new shim.TextEncoder().encode(salt),
hash: S.pbkdf2.hash,
}, key, S.pbkdf2.ks * 8)
data = shim.random(data.length) // Erase data in case of passphrase
const r = shim.Buffer.from(result, 'binary').toString('utf8')
if(cb){ cb(r) }
return r;
}
// For NodeJS crypto.pkdf2 rocks
const hash = crypto.pbkdf2Sync(
data,
new shim.TextEncoder().encode(salt),
S.pbkdf2.iter,
S.pbkdf2.ks,
S.pbkdf2.hash.replace('-', '').toLowerCase()
)
data = shim.random(data.length) // Erase passphrase for app
const r = hash && hash.toString('utf8')
if(cb){ cb(r) }
return r;
} catch(e) {
SEA.err = 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');
var Buff = (typeof Buffer !== 'undefined')? Buffer : shim.Buffer;
//SEA.pair = async (data, proof, cb) => { try {
SEA.pair = async (cb) => { try {
const ecdhSubtle = shim.ossl || shim.subtle
// First: ECDSA keys for signing/verifying...
const { pub, priv } = await shim.subtle.generateKey(S.ecdsa.pair, true, [ 'sign', 'verify' ])
.then(async (keys) => {
// privateKey scope doesn't leak out from here!
const { d: priv } = await shim.subtle.exportKey('jwk', keys.privateKey)
const { x, y } = await shim.subtle.exportKey('jwk', keys.publicKey)
//const pub = Buff.from([ x, y ].join(':')).toString('base64') // old
const pub = x+'.'+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 { pub, priv }
})
// To include PGPv4 kind of keyId:
// const pubId = await SEA.keyid(keys.pub)
// Next: ECDH keys for encryption/decryption...
const { epub, epriv } = await ecdhSubtle.generateKey(S.ecdh, true, ['deriveKey'])
.then(async (keys) => {
// privateKey scope doesn't leak out from here!
const { d: epriv } = await ecdhSubtle.exportKey('jwk', keys.privateKey)
const { x, y } = await ecdhSubtle.exportKey('jwk', keys.publicKey)
//const epub = Buff.from([ ex, ey ].join(':')).toString('base64') // old
const epub = x+'.'+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 { epub, epriv }
})
const r = { pub, priv, /* pubId, */ epub, epriv }
if(cb){ cb(r) }
return r;
} catch(e) {
SEA.err = 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 sha256hash = USE('./sha256');
SEA.sign = async (data, pair, cb) => { try {
if(data.slice
&& 'SEA{' === data.slice(0,4)
&& '"m":' === data.slice(4,8)){
// TODO: This would prevent pair2 signing pair1's signature.
// So we may want to change this in the future.
// but for now, we want to prevent duplicate double signature.
if(cb){ cb(data) }
return data;
}
const pub = pair.pub
const priv = pair.priv
const jwk = S.jwk(pub, priv)
const msg = JSON.stringify(data)
const hash = await sha256hash(msg)
const sig = await shim.subtle.importKey('jwk', jwk, S.ecdsa.pair, false, ['sign'])
.then((key) => shim.subtle.sign(S.ecdsa.sign, key, new Uint8Array(hash))) // privateKey scope doesn't leak out from here!
const r = 'SEA'+JSON.stringify({m: msg, s: shim.Buffer.from(sig, 'binary').toString('utf8')});
if(cb){ cb(r) }
return r;
} catch(e) {
SEA.err = 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 sha256hash = USE('./sha256');
var parse = USE('./parse');
var u;
SEA.verify = async (data, pair, cb) => { try {
const json = parse(data)
if(false === pair){ // don't verify!
const raw = (json !== data)?
(json.s && json.m)? parse(json.m) : data
: json;
if(cb){ cb(raw) }
return raw;
}
const pub = pair.pub || pair
const jwk = S.jwk(pub)
const key = await shim.subtle.importKey('jwk', jwk, S.ecdsa.pair, false, ['verify'])
const hash = await sha256hash(json.m)
const sig = new Uint8Array(shim.Buffer.from(json.s, 'utf8'))
const check = await shim.subtle.verify(S.ecdsa.sign, key, sig, new Uint8Array(hash))
if(!check){ throw "Signature did not match." }
const r = check? parse(json.m) : u;
if(cb){ cb(r) }
return r;
} catch(e) {
SEA.err = e;
if(cb){ cb() }
return;
}}
module.exports = SEA.verify;
})(USE, './verify');
;USE(function(module){
var shim = USE('./shim');
var sha256hash = USE('./sha256');
const importGen = async (key, salt) => {
//const combo = shim.Buffer.concat([shim.Buffer.from(key, 'utf8'), salt || shim.random(8)]).toString('utf8') // old
const combo = key + (salt || shim.random(8)).toString('utf8'); // new
const hash = shim.Buffer.from(await sha256hash(combo), 'binary')
return await shim.subtle.importKey('raw', new Uint8Array(hash), 'AES-CBC', false, ['encrypt', 'decrypt'])
}
module.exports = importGen;
})(USE, './aescbc');
;USE(function(module){
var SEA = USE('./root');
var shim = USE('./shim');
var S = USE('./settings');
var aescbckey = USE('./aescbc');
SEA.encrypt = async (data, pair, cb) => { try {
const key = pair.epriv || pair;
const msg = JSON.stringify(data)
const rand = {s: shim.random(8), iv: shim.random(16)};
const ct = await aescbckey(key, rand.s)
.then((aes) => shim.subtle.encrypt({ // Keeping the AES key scope as private as possible...
name: 'AES-CBC', iv: new Uint8Array(rand.iv)
}, aes, new shim.TextEncoder().encode(msg)))
const r = 'SEA'+JSON.stringify({
ct: shim.Buffer.from(ct, 'binary').toString('utf8'),
iv: rand.iv.toString('utf8'),
s: rand.s.toString('utf8')
});
if(cb){ cb(r) }
return r;
} catch(e) {
SEA.err = 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 aescbckey = USE('./aescbc');
var parse = USE('./parse');
SEA.decrypt = async (data, pair, cb) => { try {
const key = pair.epriv || pair;
const json = parse(data)
const ct = await aescbckey(key, shim.Buffer.from(json.s, 'utf8'))
.then((aes) => shim.subtle.decrypt({ // Keeping aesKey scope as private as possible...
name: 'AES-CBC', iv: new Uint8Array(shim.Buffer.from(json.iv, 'utf8'))
}, aes, new Uint8Array(shim.Buffer.from(json.ct, 'utf8'))))
const r = parse(new shim.TextDecoder('utf8').decode(ct))
if(cb){ cb(r) }
return r;
} catch(e) {
SEA.err = 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 = async (key, pair, cb) => { try {
const pub = key.epub || key
const epub = pair.epub
const epriv = pair.epriv
const ecdhSubtle = shim.ossl || shim.subtle
const pubKeyData = keysToEcdhJwk(pub)
const props = {
...S.ecdh,
public: await ecdhSubtle.importKey(...pubKeyData, true, [])
}
const privKeyData = keysToEcdhJwk(epub, epriv)
const derived = await ecdhSubtle.importKey(...privKeyData, false, ['deriveKey'])
.then(async (privKey) => {
// privateKey scope doesn't leak out from here!
const derivedKey = await ecdhSubtle.deriveKey(props, privKey, { name: 'AES-CBC', length: 256 }, true, [ 'encrypt', 'decrypt' ])
return ecdhSubtle.exportKey('jwk', derivedKey).then(({ k }) => k)
})
const r = derived;
if(cb){ cb(r) }
return r;
} catch(e) {
SEA.err = e;
if(cb){ cb() }
return;
}}
const keysToEcdhJwk = (pub, d) => { // d === priv
//const [ x, y ] = Buffer.from(pub, 'base64').toString('utf8').split(':') // old
const [ x, y ] = pub.split('.') // new
const jwk = d ? { d } : {}
return [ // Use with spread returned value...
'jwk',
{ ...jwk, x, y, kty: 'EC', crv: 'P-256', ext: true }, // ??? refactor
S.ecdh
]
}
module.exports = SEA.secret;
})(USE, './secret');
;USE(function(module){
// Old Code...
const {
crypto,
subtle,
ossl,
random: getRandomBytes,
TextEncoder,
TextDecoder
} = USE('./shim')
const EasyIndexedDB = USE('./indexed')
const Buffer = USE('./buffer')
var settings = USE('./settings');
const {
pbkdf2: pbKdf2,
ecdsa: { pair: ecdsaKeyProps, sign: ecdsaSignProps },
ecdh: ecdhKeyProps,
jwk: keysToEcdsaJwk
} = USE('./settings')
const sha1hash = USE('./sha1')
const sha256hash = USE('./sha256')
const recallCryptoKey = USE('./remember')
const parseProps = USE('./parse')
// Practical examples about usage found from ./test/common.js
const SEA = USE('./root');
SEA.work = USE('./work');
SEA.sign = USE('./sign');
SEA.verify = USE('./verify');
SEA.encrypt = USE('./encrypt');
SEA.decrypt = USE('./decrypt');
SEA.random = getRandomBytes;
// This is easy way to use IndexedDB, all methods are Promises
// Note: Not all SEA interfaces have to support this.
SEA.EasyIndexedDB = EasyIndexedDB;
// This is Buffer used in SEA and usable from Gun/SEA application also.
// For documentation see https://nodejs.org/api/buffer.html
SEA.Buffer = 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 = async (pub) => {
try {
// base64('base64(x):base64(y)') => Buffer(xy)
const pb = Buffer.concat(
Buffer.from(pub, 'base64').toString('utf8').split(':')
.map((t) => Buffer.from(t, 'base64'))
)
// id is PGPv4 compliant raw key
const id = Buffer.concat([
Buffer.from([0x99, pb.length / 0x100, pb.length % 0x100]), pb
])
const sha1 = await sha1hash(id)
const hash = 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.
var Gun = (SEA.window||{}).Gun || require('./gun');
Gun.SEA = SEA;
SEA.Gun = Gun;
module.exports = SEA
})(USE, './sea');
;USE(function(module){
var SEA = USE('./sea');
var Gun = SEA.Gun;
// This is internal func queries public key(s) for alias.
const queryGunAliases = (alias, gunRoot) => new Promise((resolve, reject) => {
// load all public keys associated with the username alias we want to log in with.
gunRoot.get(`alias/${alias}`).get((rat, rev) => {
rev.off();
if (!rat.put) {
// if no user, don't do anything.
const err = 'No user!'
Gun.log(err)
return reject({ err })
}
// then figuring out all possible candidates having matching username
const aliases = []
let c = 0
// TODO: how about having real chainable map without callback ?
Gun.obj.map(rat.put, (at, pub) => {
if (!pub.slice || 'pub/' !== pub.slice(0, 4)) {
// TODO: ... this would then be .filter((at, pub))
return
}
++c
// grab the account associated with this public key.
gunRoot.get(pub).get((at, ev) => {
pub = pub.slice(4)
ev.off()
--c
if (at.put){
aliases.push({ pub, at })
}
if (!c && (c = -1)) {
resolve(aliases)
}
})
})
if (!c) {
reject({ err: 'Public key does not exist!' })
}
})
})
module.exports = queryGunAliases
})(USE, './query');
;USE(function(module){
var SEA = USE('./sea');
var Gun = SEA.Gun;
const queryGunAliases = USE('./query')
const parseProps = USE('./parse')
// This is internal User authentication func.
const authenticate = async (alias, pass, gunRoot) => {
// load all public keys associated with the username alias we want to log in with.
const aliases = (await queryGunAliases(alias, gunRoot))
.filter(({ pub, at: { put } = {} } = {}) => !!pub && !!put)
// Got any?
if (!aliases.length) {
throw { err: 'Public key does not exist!' }
}
let err
// then attempt to log into each one until we find ours!
// (if two users have the same username AND the same password... that would be bad)
const [ user ] = await Promise.all(aliases.map(async ({ at, pub }) => {
// attempt to PBKDF2 extend the password with the salt. (Verifying the signature gives us the plain text salt.)
const auth = parseProps(at.put.auth)
// NOTE: aliasquery uses `gun.get` which internally SEA.read verifies the data for us, so we do not need to re-verify it here.
// SEA.verify(at.put.auth, pub).then(function(auth){
try {
const proof = await SEA.work(pass, auth.s)
const props = { pub, proof, at }
// the proof of work is evidence that we've spent some time/effort trying to log in, this slows brute force.
/*
MARK TO @mhelander : pub vs epub!???
*/
const { salt } = auth
const sea = await SEA.decrypt(auth.ek, proof)
if (!sea) {
err = 'Failed to decrypt secret!'
return
}
// now we have AES decrypted the private key, from when we encrypted it with the proof at registration.
// if we were successful, then that meanswe're logged in!
const { priv, epriv } = sea
const { epub } = at.put
// TODO: 'salt' needed?
err = null
if(typeof window !== 'undefined'){
var tmp = window.sessionStorage;
if(tmp && gunRoot._.opt.remember){
window.sessionStorage.alias = alias;
window.sessionStorage.tmp = pass;
}
}
return Object.assign(props, { priv, salt, epub, epriv })
} catch (e) {
err = 'Failed to decrypt secret!'
throw { err }
}
}))
if (!user) {
throw { err: err || 'Public key does not exist!' }
}
return user
}
module.exports = authenticate;
})(USE, './authenticate');
;USE(function(module){
// TODO: BUG! `SEA` needs to be USED!
const Gun = (typeof window !== 'undefined' ? window : global).Gun || USE('gun/gun')
const authsettings = USE('./settings')
const SEA = USE('./sea');
//const { scope: seaIndexedDb } = USE('./indexed')
// This updates sessionStorage & IndexedDB to persist authenticated "session"
const updateStorage = (proof, key, pin) => async (props) => {
if (!Gun.obj.has(props, 'alias')) {
return // No 'alias' - we're done.
}
if (authsettings.validity && proof && Gun.obj.has(props, 'iat')) {
props.proof = proof
delete props.remember // Not stored if present
const { alias, alias: id } = props
const remember = { alias, pin }
try {
const signed = await SEA.sign(JSON.stringify(remember), key)
sessionStorage.setItem('user', alias)
sessionStorage.setItem('remember', signed)
const encrypted = await SEA.encrypt(props, pin)
if (encrypted) {
const auth = await SEA.sign(encrypted, key)
await seaIndexedDb.wipe() // NO! Do not do this. It ruins other people's sessionStorage code. This is bad/wrong, commenting it out.
await seaIndexedDb.put(id, { auth })
}
return props
} catch (err) {
throw { err: 'Session persisting failed!' }
}
}
// Wiping IndexedDB completely when using random PIN
await seaIndexedDb.wipe() // NO! Do not do this. It ruins other people's sessionStorage code. This is bad/wrong, commenting it out.
// And remove sessionStorage data
sessionStorage.removeItem('user')
sessionStorage.removeItem('remember')
return props
}
module.exports = updateStorage
})(USE, './update');
;USE(function(module){
const Gun = (typeof window !== 'undefined' ? window : global).Gun || USE('gun/gun')
const Buffer = USE('./buffer')
const authsettings = USE('./settings')
const updateStorage = USE('./update')
// This internal func persists User authentication if so configured
const authPersist = async (user, proof, opts) => {
// opts = { pin: 'string' }
// no opts.pin then uses random PIN
// How this works:
// called when app bootstraps, with wanted options
// IF authsettings.validity === 0 THEN no remember-me, ever
// IF PIN then signed 'remember' to window.sessionStorage and 'auth' to IndexedDB
const pin = Buffer.from(
(Gun.obj.has(opts, 'pin') && opts.pin) || Gun.text.random(10),
'utf8'
).toString('base64')
const { alias } = user || {}
const { validity: exp } = authsettings // seconds // @mhelander what is `exp`???
if (proof && alias && exp) {
const iat = Math.ceil(Date.now() / 1000) // seconds
const remember = Gun.obj.has(opts, 'pin') || undefined // for hook - not stored
const props = authsettings.hook({ alias, iat, exp, remember })
const { pub, epub, sea: { priv, epriv } } = user
const key = { pub, priv, epub, epriv }
if (props instanceof Promise) {
const asyncProps = await props.then()
return await updateStorage(proof, key, pin)(asyncProps)
}
return await updateStorage(proof, key, pin)(props)
}
return await updateStorage()({ alias: 'delete' })
}
module.exports = authPersist
})(USE, './persist');
;USE(function(module){
const authPersist = USE('./persist')
// This internal func finalizes User authentication
const finalizeLogin = async (alias, key, gunRoot, opts) => {
const { user } = gunRoot._
// add our credentials in-memory only to our root gun instance
//var tmp = user._.tag;
user._ = key.at.gun._
//user._.tag = tmp || user._.tag;
// so that way we can use the credentials to encrypt/decrypt data
// that is input/output through gun (see below)
const { pub, priv, epub, epriv } = key
user._.is = user.is = {alias: alias, pub: pub};
Object.assign(user._, { alias, pub, epub, sea: { pub, priv, epub, epriv } })
//console.log("authorized", user._);
// persist authentication
//await authPersist(user._, key.proof, opts) // temporarily disabled
// emit an auth event, useful for page redirects and stuff.
try {
gunRoot._.on('auth', user._)
} catch (e) {
console.log('Your \'auth\' callback crashed with:', e)
}
// returns success with the user data credentials.
return user._
}
module.exports = finalizeLogin
})(USE, './login');
;USE(function(module){
// TODO: BUG! `SEA` needs to be USEd!
const Gun = (typeof window !== 'undefined' ? window : global).Gun || USE('gun/gun')
const Buffer = USE('./buffer')
const authsettings = USE('./settings')
//const { scope: seaIndexedDb } = USE('./indexed')
const queryGunAliases = USE('./query')
const parseProps = USE('./parse')
const updateStorage = USE('./update')
const SEA = USE('./sea')
const finalizeLogin = USE('./login')
// This internal func recalls persisted User authentication if so configured
const authRecall = async (gunRoot, authprops) => {
// window.sessionStorage only holds signed { alias, pin } !!!
const remember = authprops || sessionStorage.getItem('remember')
const { alias = sessionStorage.getItem('user'), pin: pIn } = authprops || {} // @mhelander what is pIn?
const pin = pIn && Buffer.from(pIn, 'utf8').toString('base64')
// Checks for existing proof, matching alias and expiration:
const checkRememberData = async ({ proof, alias: aLias, iat, exp, remember }) => {
if (!!proof && alias === aLias) {
const checkNotExpired = (args) => {
if (Math.floor(Date.now() / 1000) < (iat + args.exp)) {
// No way hook to update 'iat'
return Object.assign(args, { iat, proof })
} else {
Gun.log('Authentication expired!')
}
}
// We're not gonna give proof to hook!
const hooked = authsettings.hook({ alias, iat, exp, remember })
return ((hooked instanceof Promise)
&& await hooked.then(checkNotExpired)) || checkNotExpired(hooked)
}
}
const readAndDecrypt = async (data, pub, key) =>
parseProps(await SEA.decrypt(await SEA.verify(data, pub), key))
// Already authenticated?
if (gunRoot._.user
&& Gun.obj.has(gunRoot._.user._, 'pub')
&& Gun.obj.has(gunRoot._.user._, 'sea')) {
return gunRoot._.user._ // Yes, we're done here.
}
// No, got persisted 'alias'?
if (!alias) {
throw { err: 'No authentication session found!' }
}
// Yes, got persisted 'remember'?
if (!remember) {
throw { // And return proof if for matching alias
err: (await seaIndexedDb.get(alias, 'auth') && authsettings.validity
&& 'Missing PIN and alias!') || 'No authentication session found!'
}
}
// Yes, let's get (all?) matching aliases
const aliases = (await queryGunAliases(alias, gunRoot))
.filter(({ pub } = {}) => !!pub)
// Got any?
if (!aliases.length) {
throw { err: 'Public key does not exist!' }
}
let err
// Yes, then attempt to log into each one until we find ours!
// (if two users have the same username AND the same password... that would be bad)
const [ { key, at, proof, pin: newPin } = {} ] = await Promise
.all(aliases.filter(({ at: { put } = {} }) => !!put)
.map(async ({ at, pub }) => {
const readStorageData = async (args) => {
const props = args || parseProps(await SEA.verify(remember, pub, true))
let { pin, alias: aLias } = props
const data = (!pin && alias === aLias)
// No PIN, let's try short-term proof if for matching alias
? await checkRememberData(props)
// Got PIN so get IndexedDB secret if signature is ok
: await checkRememberData(await readAndDecrypt(await seaIndexedDb.get(alias, 'auth'), pub, pin))
pin = pin || data.pin
delete data.pin
return { pin, data }
}
// got pub, try auth with pin & alias :: or unwrap Storage data...
const { data, pin: newPin } = await readStorageData(pin && { pin, alias })
const { proof } = data || {}
if (!proof) {
if (!data) {
err = 'No valid authentication session found!'
return
}
try { // Wipes IndexedDB silently
await updateStorage()(data)
} catch (e) {} //eslint-disable-line no-empty
err = 'Expired session!'
return
}
try { // auth parsing or decryption fails or returns empty - silently done
const { auth } = at.put.auth
const sea = await SEA.decrypt(auth, proof)
if (!sea) {
err = 'Failed to decrypt private key!'
return
}
const { priv, epriv } = sea
const { epub } = at.put
// Success! we've found our private data!
err = null
return { proof, at, pin: newPin, key: { pub, priv, epriv, epub } }
} catch (e) {
err = 'Failed to decrypt private key!'
return
}
}).filter((props) => !!props))
if (!key) {
throw { err: err || 'Public key does not exist!' }
}
// now we have AES decrypted the private key,
// if we were successful, then that means we're logged in!
try {
await updateStorage(proof, key, newPin || pin)(key)
const user = Object.assign(key, { at, proof })
const pIN = newPin || pin
const pinProp = pIN && { pin: Buffer.from(pIN, 'base64').toString('utf8') }
return await finalizeLogin(alias, user, gunRoot, pinProp)
} catch (e) { // TODO: right log message ?
Gun.log('Failed to finalize login with new password!')
const { err = '' } = e || {}
throw { err: `Finalizing new password login failed! Reason: ${err}` }
}
}
module.exports = authRecall
})(USE, './recall');
;USE(function(module){
const authPersist = USE('./persist')