-
Notifications
You must be signed in to change notification settings - Fork 0
/
serializer-mod.ts
1011 lines (820 loc) · 32.2 KB
/
serializer-mod.ts
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
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Serializer Module
*
* This module provides functions for serializing and deserializing SSASy
* resources (i.e. keys, challenges, ciphertexts and signatures) for transport.
* In other words, it provides functions for converting SSASy resources into
* URI strings and vice versa.
*/
import { KeyType } from "../interfaces";
import { KeyChecker, KeyModule } from "./key-mod";
import { ChallengeChecker } from "./challenge-mod";
import { CryptoChecker } from "./crypto-mod";
import type {
AdvancedCiphertext,
Challenge,
Ciphertext,
GenericKey,
PublicKey,
RawKey,
SecureContextKey,
StandardCiphertext
} from "../interfaces";
const SERIALIZER_ERROR_MESSAGE = {
INVALID_KEY: "Key is invalid or not supported",
INVALID_KEY_STRING: "Key is invalid",
INVALID_CHALLENGE: "Challenge is invalid",
INVALID_CHALLENGE_STRING: "Challenge string is invalid",
INVALID_CIPHERTEXT: "Ciphertext is invalid",
INVALID_CIPHERTEXT_STRING: "Ciphertext string is invalid",
INVALID_SIGNATURE: "Signature is invalid",
INVALID_SIGNATURE_STRING: "Signature string is invalid",
INVALID_CREDENTIAL: "Credential is invalid",
INVALID_CREDENTIAL_STRING: "Credential string is invalid",
MISSING_PARAM: "Parameter key or value is missing",
MISSING_KEY_STRING: "Key is missing",
MISSING_CHALLENGE_STRING: "Challenge string is missing",
MISSING_CIPHERTEXT_STRING: "Ciphertext string is missing",
MISSING_SIGNATURE_STRING: "Signature string is missing",
MISSING_CREDENTIAL_URI: "Credential uri is missing",
MISSING_CREDENTIAL_KEY: "Credential public key is missing",
MISSING_CREDENTIAL_SIGNATURE: "Credential signature is missing",
LEGACY_INVALID_CIPHERTEXT_STRING: "Legacy ciphertext string is invalid",
LEGACY_INVALID_CHALLENGE_STRING: "Legacy challenge string is invalid"
};
/**
* A credential is a combination of a public key and a digital signature signed
* by the corresponding private key.
*/
type Credential = { publicKey: PublicKey, signature: StandardCiphertext };
/**
* Returns an encoded string for a uri parameter value. The following
* characters are considered reserved and are encoded: `&`, `,` and `=`.
*/
function _encodeUriParamValue(value: string): string {
return encodeURIComponent(value)
.replace(/&/g, "%26")
.replace(/=/g, "%3D")
.replace(/'/g, "%27")
.replace(/"/g, "%22");
}
/**
* Returns a decoded string for a uri parameter value. The following
* characters are considered reserved and are decoded: `&`, `,` and `=`.
*/
function _decodeUriParam(value: string): string {
return decodeURIComponent(value)
.replace(/%26/g, "&")
.replace(/%3D/g, "=")
.replace(/%27/g, "'")
.replace(/%22/g, "\"");
}
/**
* Returns a uri parameter from a key-value pair. The parameter is prefixed
* with an ampersand (`&`) if it is not the first parameter in the uri and
* the value is encoded.
*
* @param key - parameter key
* @param value - parameter value
* @param config - configuration object
* @param config.first - indicates whether the parameter is the first parameter in the uri
*/
function _constructParam(key: string, value: string, config?: { first?: boolean}): string {
if(!key || !value){
throw new Error(SERIALIZER_ERROR_MESSAGE.MISSING_PARAM);
}
// encode value
value = _encodeUriParamValue(value);
return config?.first ? `${key}=${value}` : `&${key}=${value}`;
}
/**
* Returns key and value from a uri parameter.
*
* @param param - uri parameter
* @returns key and value
*/
function _deconstructParam(param: string): { key: string, value: string } {
// get first index of "=" to split property into key and value
// note: this is a workaround for edge-cases where a value contains "=" (i.e. iv="gjhgdfhshgadhfga==")
const equalOperatorIndex = param.indexOf("=");
let key: string = param.slice(0, equalOperatorIndex);
let value: string = param.slice(equalOperatorIndex + 1);
// remove ampersand from key (e.g. &key=value)
if(key.startsWith("&")){
key = key.slice(1);
}
// decode property value
value = _decodeUriParam(value);
return { key, value };
}
/**
* ! Temporary fix for legacy resource strings
*/
const LegacySerializerModule = {
/**
* Convert legacy key string back to a key object.
* Old key string format: JSON.stringify(rawKey)
*/
deserializeKey: (legacyKeyUri: string): RawKey => {
return JSON.parse(legacyKeyUri);
},
/**
* Converts legacy ciphertext string back to a ciphertext object.
* Old ciphertext string format: `"{ iv, data, salt?, sender?, recipient?, signature? }"`
*
* @param ciphertextUri - legacy ciphertext string
* @returns ciphertext object
*
*/
deserializeCiphertext: async (legacyCiphertextUri: string): Promise<Ciphertext> => {
interface ShallowCiphertext extends Omit<Ciphertext, "sender" | "recipient" | "signature"> {
sender?: string;
recipient?: string;
signature?: string;
}
const shallowCiphertext: ShallowCiphertext = JSON.parse(legacyCiphertextUri);
const ciphertext = {
data: shallowCiphertext.data,
iv: shallowCiphertext.iv
} as any;
if(shallowCiphertext.salt){
ciphertext.salt = shallowCiphertext.salt;
}
if(shallowCiphertext.sender){
// deserialize stringified key if it is a string (do the same for recipient and signature)
const key: RawKey = typeof shallowCiphertext.sender === "string"
? LegacySerializerModule.deserializeKey(shallowCiphertext.sender)
: shallowCiphertext.sender as unknown as RawKey;
ciphertext.sender = await KeyModule.importKey(key) as PublicKey;
}
if(shallowCiphertext.recipient){
const key: RawKey = typeof shallowCiphertext.recipient === "string"
? LegacySerializerModule.deserializeKey(shallowCiphertext.recipient)
: shallowCiphertext.recipient as unknown as RawKey;
ciphertext.recipient = await KeyModule.importKey(key) as PublicKey;
}
if(shallowCiphertext.signature){
const legacySignature: StandardCiphertext = typeof shallowCiphertext.signature === "string"
? await LegacySerializerModule.deserializeCiphertext(shallowCiphertext.signature)
: shallowCiphertext.signature as unknown as StandardCiphertext;
ciphertext.signature = legacySignature;
}
return ciphertext as Ciphertext;
},
/**
* Converts legacy challenge string back to a challenge object.
* Old challenge string format: `<nonce>::<timestamp>::<raw verifier public key>::<raw claimant public key>::<solution>`
*
* @param legacyChallengeUri - legacy challenge string
* @returns challenge object
*/
deserializeChallenge: async (legacyChallengeUri: string): Promise<Challenge> => {
const properties = legacyChallengeUri.split("::");
const challenge = {} as any;
if(properties.length < 4){
throw new Error("legacy uri is missing required properties (4)");
}
challenge.nonce = properties[0];
challenge.timestamp = Number(properties[1]);
challenge.solution = properties[4];
const verifier = properties[2];
const claimant = properties[3];
const verifierRawPublicKey: RawKey = LegacySerializerModule.deserializeKey(verifier);
const claimantRawPublicKey: RawKey = LegacySerializerModule.deserializeKey(claimant);
challenge.verifier = await KeyModule.importKey(verifierRawPublicKey) as PublicKey;
challenge.claimant = await KeyModule.importKey(claimantRawPublicKey) as PublicKey;
return challenge as Challenge;
}
};
/**
* Prefixes for uri
*/
const SerializerPrefix = {
URI: {
KEY: "ssasy://key?",
CHALLENGE: "ssasy://challenge?",
CIPHERTEXT: "ssasy://ciphertext?",
SIGNATURE: "ssasy://signature?",
CREDENTIAL: "ssasy://credential?"
},
PARAM: { KEY_CRYPTO: "c_" }
};
/**
* Operations for serializing SSASy resources for transport
*/
const SerializerModule = {
PREFIX: SerializerPrefix,
/**
* Returns a uri string representation of a key.
*
* The representation has the following format:
*
* `ssasy://key?type=value&domain=value&hash=value&salt=value&iterations=value&c_kty=value&c_key_ops=value&c_alg=value&c_ext=value&c_kid=value&c_use=value&c_k=value&c_crv=value&c_x=value&c_y=value&c_d=value`
*
* Note: Try to keep the order of the parameters as shown above so that keys that are saved
* in a database can be easily compared.
*
* @param key - key
* @returns key
* */
serializeKey: async (key: GenericKey): Promise<string> => {
if (!KeyChecker.isKey(key)) {
throw new Error(SERIALIZER_ERROR_MESSAGE.INVALID_KEY);
}
const rawKey: RawKey = KeyChecker.isRawKey(key)
? key as RawKey
: await KeyModule.exportKey(key);
let keyUri: string = SerializerPrefix.URI.KEY;
// add type to keyUri
keyUri += _constructParam("type", rawKey.type, { first: true });
//! the order of the parameters is important for the key comparison (i.e. database queries)
const paramKeys: string[] = [
"domain",
"hash",
"salt",
"iterations",
`${SerializerPrefix.PARAM.KEY_CRYPTO}kty`,
`${SerializerPrefix.PARAM.KEY_CRYPTO}key_ops`,
`${SerializerPrefix.PARAM.KEY_CRYPTO}alg`,
`${SerializerPrefix.PARAM.KEY_CRYPTO}ext`,
`${SerializerPrefix.PARAM.KEY_CRYPTO}kid`,
`${SerializerPrefix.PARAM.KEY_CRYPTO}use`,
`${SerializerPrefix.PARAM.KEY_CRYPTO}k`,
`${SerializerPrefix.PARAM.KEY_CRYPTO}crv`,
`${SerializerPrefix.PARAM.KEY_CRYPTO}x`,
`${SerializerPrefix.PARAM.KEY_CRYPTO}y`,
`${SerializerPrefix.PARAM.KEY_CRYPTO}d`
];
for (const paramKey of paramKeys) {
// check if param belongs to crypto object
const isCryptoValue: boolean = paramKey.startsWith(SerializerPrefix.PARAM.KEY_CRYPTO);
// remove protocol prefix
const cleanParam: string = isCryptoValue ? paramKey.slice(SerializerPrefix.PARAM.KEY_CRYPTO.length) : paramKey;
// skip param if it does not exist in raw key or nested crypto object
if (
!(rawKey as any)[cleanParam] !== undefined &&
!(isCryptoValue && (rawKey.crypto as any)[cleanParam] !== undefined)
) {
continue;
}
// set value depending on whether it belongs to crypto object
let paramValue: any = isCryptoValue ? (rawKey.crypto as any)[cleanParam] : (rawKey as any)[cleanParam];
// convert value to a string if it is an array
if (Array.isArray(paramValue)) {
paramValue = `[${paramValue.join(",")}]`;
}
// add param to keyUri
keyUri += _constructParam(paramKey, paramValue);
}
return keyUri;
},
/**
* Returns a key object from a key uri (see `serializeKey`)
*
* @param key - key uri
* @param config - configuration object
* @param config.raw - returns a raw key instead of a secure context key
* @returns key
* */
deserializeKey: async (keyUri: string, config?: { raw: boolean }): Promise<SecureContextKey | RawKey> => {
if (!keyUri) {
throw new Error(SERIALIZER_ERROR_MESSAGE.MISSING_KEY_STRING);
}
if(typeof keyUri !== "string" || !SerializerChecker.isKeyUri(keyUri)){
throw new Error(SERIALIZER_ERROR_MESSAGE.INVALID_KEY_STRING);
}
// remove key protocol prefix
keyUri = keyUri.slice(SerializerPrefix.URI.KEY.length);
// extract all properties from key string
const keyParams: string[] = keyUri.split("&");
/**
* Returns a RawKey from a key uri
*/
function _rebuildRawKey(keyParams: string[]): RawKey {
const rawKey: any = {
type: KeyType.Key,
crypto: {}
};
for(const param of keyParams){
const deconstructedParam = _deconstructParam(param);
let key: string = deconstructedParam.key;
let value: string | string[] = deconstructedParam.value;
if(value.startsWith("[") && value.endsWith("]")){
value = value.slice(1, -1).split(",");
}
// add value to nested crypto object if key starts with crypto prefix
if(key.startsWith(SerializerPrefix.PARAM.KEY_CRYPTO)){
key = key.slice(SerializerPrefix.PARAM.KEY_CRYPTO.length);
rawKey.crypto[key] = value;
} else {
rawKey[key] = value;
}
}
return rawKey as RawKey;
}
// convert raw key to a key instance (secure context)
const rawKey: RawKey = _rebuildRawKey(keyParams);
return config?.raw
? rawKey
: await KeyModule.importKey(rawKey);
},
/**
* Returns a uri string representation of a challenge.
*
* The representation has the following format:
* `ssasy://challenge?nonce=value&solution=value×tamp=value&verifier=value&claimant=value`
*
* @param challenge - the challenge to convert to a string
* @returns challenge in string format
* */
serializeChallenge: async (challenge: Challenge): Promise<string> => {
if (!ChallengeChecker.isChallenge(challenge)) {
throw new Error(SERIALIZER_ERROR_MESSAGE.INVALID_CHALLENGE);
}
const { nonce, timestamp, verifier, claimant, solution } = challenge;
let challengeUri = SerializerPrefix.URI.CHALLENGE;
// add nonce
challengeUri += _constructParam("nonce", nonce, { first: true });
// convert timestamp to string
const timestampString = timestamp.toString();
challengeUri += _constructParam("timestamp", timestampString);
// add verifier
const verifierUri = await SerializerModule.serializeKey(verifier);
challengeUri += _constructParam("verifier", verifierUri);
// add claimant
const claimantUri = await SerializerModule.serializeKey(claimant);
challengeUri += _constructParam("claimant", claimantUri);
// add solution (if exists)
if(solution){
challengeUri += _constructParam("solution", solution);
}
return challengeUri;
},
/**
* Returns a challenge object from a string representation of a challenge.
*
* @param challengeUri - the string representation of the challenge
* @returns challenge object
* */
deserializeChallenge: async (challengeUri: string): Promise<Challenge> => {
if(!challengeUri) {
throw new Error(SERIALIZER_ERROR_MESSAGE.MISSING_CHALLENGE_STRING);
}
if(typeof challengeUri !== "string"){
throw new Error(SERIALIZER_ERROR_MESSAGE.INVALID_CHALLENGE_STRING);
}
if(!SerializerChecker.isChallengeUri(challengeUri)){
/**
* ! Temporary fix for legacy challenge strings
*
* This block needs to handle the edge-case where a challenge uri is
* conforming to the old format: `<nonce>::<timestamp>::<verifier>::<claimant>::<solution>`
*/
let migratedLegacyUri = false;
try {
const legacyChallenge: Challenge = await LegacySerializerModule.deserializeChallenge(challengeUri);
challengeUri = await SerializerModule.serializeChallenge(legacyChallenge);
migratedLegacyUri = true;
} catch (error) {
throw new Error(SERIALIZER_ERROR_MESSAGE.LEGACY_INVALID_CHALLENGE_STRING);
}
if(!migratedLegacyUri){
throw new Error(SERIALIZER_ERROR_MESSAGE.INVALID_CHALLENGE_STRING);
}
}
/**
* Returns a typed challenge value based on key string
*/
async function _getTypedValue(key: string, value: string): Promise<string | number | PublicKey> {
if(key === "nonce" || key === "solution"){
return value as string;
} else if(key === "timestamp"){
return Number(value) as number;
} else if(key === "verifier" || key === "claimant"){
return await SerializerModule.deserializeKey(value) as PublicKey;
} else {
throw new Error(SERIALIZER_ERROR_MESSAGE.INVALID_CHALLENGE_STRING);
}
}
async function rebuildChallenge(challengeParams: string[]): Promise<Challenge> {
const challenge: any = {};
for(const param of challengeParams){
const { key, value } = _deconstructParam(param);
// get typed value
const typedValue = await _getTypedValue(key, value);
challenge[key] = typedValue;
}
return challenge as Challenge;
}
// remove challenge protocol prefix
challengeUri = challengeUri.slice(SerializerPrefix.URI.CHALLENGE.length);
// extract all properties
const challengeParams: string[] = challengeUri.split("&");
return await rebuildChallenge(challengeParams);
},
/**
* Returns a uri string representation of a ciphertext.
*
* The representation has the following format:
* - standard ciphertext: `ssasy://ciphertext?data=value&iv=value&salt=value`
* - advanced ciphertext: `ssasy://ciphertext?data=value&iv=value&salt=value&sender=value&recipient=value&signature=value`
*
* @param ciphertext - the ciphertext to convert to a string
*/
serializeCiphertext: async (ciphertext: Ciphertext): Promise<string> => {
if(!CryptoChecker.isCiphertext(ciphertext)) {
throw new Error(SERIALIZER_ERROR_MESSAGE.INVALID_CIPHERTEXT);
}
let ciphertextUri = `${SerializerPrefix.URI.CIPHERTEXT}`;
// add data to ciphertext string
ciphertextUri += _constructParam("data", ciphertext.data, { first: true });
// add iv to ciphertext string
ciphertextUri += _constructParam("iv", ciphertext.iv);
// add salt to ciphertext string (if salt exists)
if(ciphertext.salt) {
ciphertextUri += _constructParam("salt", ciphertext.salt);
}
// add sender to ciphertext string (if sender exists)
if((ciphertext as AdvancedCiphertext).sender) {
const sender = (ciphertext as AdvancedCiphertext).sender as PublicKey;
const senderUri = await SerializerModule.serializeKey(sender);
// add sender to ciphertext string
ciphertextUri += _constructParam("sender", senderUri);
}
// add recipient to ciphertext string (if recipient exists)
if((ciphertext as AdvancedCiphertext).recipient) {
const recipient = (ciphertext as AdvancedCiphertext).recipient as PublicKey;
const recipientUri = await SerializerModule.serializeKey(recipient);
// add recipient to ciphertext string
ciphertextUri += _constructParam("recipient", recipientUri);
}
// add signature to ciphertext string (if signature exists)
if((ciphertext as AdvancedCiphertext).signature) {
const signature = (ciphertext as AdvancedCiphertext).signature as StandardCiphertext;
const signatureUri = await SerializerModule.serializeSignature(signature);
// add signature to ciphertext string
ciphertextUri += _constructParam("signature", signatureUri);
}
return ciphertextUri;
},
/**
* Returns a ciphertext object from a string representation of a ciphertext.
*
* @param ciphertextUri - the string representation of the ciphertext
*/
deserializeCiphertext: async (ciphertextUri: string): Promise<Ciphertext> => {
if(!ciphertextUri) {
throw new Error(SERIALIZER_ERROR_MESSAGE.MISSING_CIPHERTEXT_STRING);
}
if(typeof ciphertextUri !== "string"){
throw new Error(SERIALIZER_ERROR_MESSAGE.INVALID_CIPHERTEXT_STRING);
}
if(!SerializerChecker.isCiphertextUri(ciphertextUri)){
/**
* ! Temporary fix for legacy challenge strings
*
* This block needs to handle the edge-case where a ciphertext uri is
* conforming to the old format: `"{ iv, data, salt?, sender?, recipient?, signature? }"`
*/
let migratedLegacyUri = false;
try {
const legacyCiphertext: Ciphertext = await LegacySerializerModule.deserializeCiphertext(ciphertextUri);
ciphertextUri = await SerializerModule.serializeCiphertext(legacyCiphertext);
migratedLegacyUri = true;
} catch (error) {
throw new Error(SERIALIZER_ERROR_MESSAGE.LEGACY_INVALID_CIPHERTEXT_STRING);
}
if(!migratedLegacyUri){
throw new Error(SERIALIZER_ERROR_MESSAGE.INVALID_CIPHERTEXT_STRING);
}
}
/**
* Returns a typed ciphertext value based on key string
*/
async function _getTypedValue(key: string, value: string): Promise<string | PublicKey | StandardCiphertext | undefined> {
if(key === "data" || key === "iv" || key === "salt"){
return value as string;
} else if(key === "signature"){
try {
return await SerializerModule.deserializeSignature(value) as StandardCiphertext;
} catch (error) {
throw new Error(SERIALIZER_ERROR_MESSAGE.INVALID_SIGNATURE_STRING);
}
} else if(key === "sender" || key === "recipient"){
return await SerializerModule.deserializeKey(value) as PublicKey;
} else {
throw new Error(SERIALIZER_ERROR_MESSAGE.INVALID_CIPHERTEXT_STRING);
}
}
async function _rebuildCiphertext(ciphertextParams: string[]): Promise<Ciphertext>{
const ciphertext: any = {};
for(const param of ciphertextParams){
const { key, value } = _deconstructParam(param);
// get typed value
const typedValue = await _getTypedValue(key, value as string);
ciphertext[key] = typedValue;
}
return ciphertext as Ciphertext;
}
// remove ciphertext protocol prefix
ciphertextUri = ciphertextUri.slice(SerializerPrefix.URI.CIPHERTEXT.length);
// extract all parameters
const ciphertextParams: string[] = ciphertextUri.split("&");
return await _rebuildCiphertext(ciphertextParams);
},
/**
* Returns a uri string representation of a signature.
*
* The representation has the following format:
* `ssasy://signature?data=value&iv=value`
*
* @param signature - the signature to convert to a string
*/
serializeSignature: async (signature: StandardCiphertext): Promise<string> => {
const ciphertextUri = await SerializerModule.serializeCiphertext(signature);
return ciphertextUri.replace(SerializerPrefix.URI.CIPHERTEXT, SerializerPrefix.URI.SIGNATURE);
},
/**
* Returns a signature object from a string representation of a signature.
*
* @param signatureUri - the string representation of the signature
* @returns signature object
* */
deserializeSignature: async (signatureUri: string): Promise<StandardCiphertext> => {
if(!signatureUri || !SerializerChecker.isSignatureUri(signatureUri)) {
throw new Error(SERIALIZER_ERROR_MESSAGE.MISSING_SIGNATURE_STRING);
}
const ciphertextUri = signatureUri.replace(SerializerPrefix.URI.SIGNATURE, SerializerPrefix.URI.CIPHERTEXT);
return await SerializerModule.deserializeCiphertext(ciphertextUri);
},
/**
* Returns a uri string representation of a credential which is a combination
* of a public key and a digital signature signed by the corresponding private key.
*/
serializeCredential: async (publicKey: PublicKey, signature: StandardCiphertext): Promise<any> => {
if(!publicKey){
throw new Error(SERIALIZER_ERROR_MESSAGE.MISSING_CREDENTIAL_KEY);
}
if(!signature){
throw new Error(SERIALIZER_ERROR_MESSAGE.MISSING_CREDENTIAL_SIGNATURE);
}
if(
(!KeyChecker.isAsymmetricKey(publicKey) || publicKey.type !== KeyType.PublicKey) ||
!CryptoChecker.isCiphertext(signature)
) {
throw new Error(SERIALIZER_ERROR_MESSAGE.INVALID_CREDENTIAL);
}
let credentialUri: string = SerializerPrefix.URI.CREDENTIAL;
const publicKeyUri: string = await SerializerModule.serializeKey(publicKey);
credentialUri += _constructParam("publicKey", publicKeyUri, { first: true });
const signatureUri: string = await SerializerModule.serializeSignature(signature);
credentialUri += _constructParam("signature", signatureUri);
return credentialUri;
},
/**
* Returns a credential object from a string representation of a credential.
*/
deserializeCredential: async (credentialUri: string): Promise<any> => {
if(!credentialUri){
throw new Error(SERIALIZER_ERROR_MESSAGE.MISSING_CREDENTIAL_URI);
}
if(typeof credentialUri !== "string" || !SerializerChecker.isCredentialUri(credentialUri)){
throw new Error(SERIALIZER_ERROR_MESSAGE.INVALID_CREDENTIAL_STRING);
}
// remove credential protocol prefix
credentialUri = credentialUri.slice(SerializerPrefix.URI.CREDENTIAL.length);
// extract all properties from credential string
const credentialParams: string[] = credentialUri.split("&");
let publicKey: PublicKey | undefined;
let signature: StandardCiphertext | undefined;
for(const param of credentialParams){
const { key, value } = _deconstructParam(param);
if(key === "publicKey"){
publicKey = await SerializerModule.deserializeKey(value) as PublicKey;
} else if(key === "signature"){
signature = await SerializerModule.deserializeSignature(value);
}
}
if(!publicKey || !signature){
throw new Error(SERIALIZER_ERROR_MESSAGE.INVALID_CREDENTIAL_STRING);
}
return {
publicKey,
signature
};
}
};
/**
* Returns true if arg has a valid prefix.
*/
function _hasValidPrefix(arg: any, prefix: string): boolean {
if(!arg) {
return false;
}
if(typeof arg !== "string") {
return false;
}
if(!arg.startsWith(prefix)) {
return false;
}
return true;
}
/**
* Returns decoded uri params from a uri string.
*/
function _extractUriParams(uri: string, prefix: string): {key: string, value: string}[] {
// remove protocol prefix
uri = uri.slice(prefix.length);
// extract all properties from key string
const properties: string[] = uri.split("&");
return properties.map(property => _deconstructParam(property));
}
type KeyT = KeyType.Key | KeyType.SecretKey | KeyType.PassKey | KeyType.PublicKey | KeyType.PrivateKey | KeyType.SharedKey;
const SerializerChecker = {
/**
* Returns true if a key uri is valid.
*
* @param keyUri - encoded key uri
* @param config - configuration object
* @param config.type - match key type
* @returns true if key uri is valid
*/
isKeyUri: (keyUri: string, config?: { type?: KeyT } ): boolean => {
const requiredParams = [ "type", "c_kty", "c_key_ops", "c_ext" ];
const requiredSymmetricParams = [ ...requiredParams, "c_alg", "c_k" ];
const requiredAsymmetricParams = [ ...requiredParams, "c_crv", "c_x", "c_y" ]; // excluding `c_d` (private key)
if(!_hasValidPrefix(keyUri, SerializerPrefix.URI.KEY)) {
return false;
}
const params: {key: string, value: string}[] = _extractUriParams(keyUri, SerializerPrefix.URI.KEY);
// arg must have required params
if(params.length < requiredParams.length) {
return false;
}
const keyType: string | undefined = params.find(param => param.key === "type")?.value;
// key type must match `type`, if it is provided
if(config?.type && keyType !== config?.type) {
return false;
}
// arg must have asymmetric params if type is asymmetric
if(
(keyType === KeyType.PublicKey || keyType === KeyType.PrivateKey) &&
params.length < requiredAsymmetricParams.length
) {
return false;
}
// arg must have symmetric params if type is symmetric
if(
(keyType === KeyType.SecretKey || keyType === KeyType.PassKey || keyType === KeyType.SharedKey) &&
params.length < requiredSymmetricParams.length
) {
return false;
}
return true;
},
/**
* Returns true if a challenge uri is valid.
*/
isChallengeUri: (challengeUri: string): boolean => {
const requiredParams = [ "nonce", "timestamp", "verifier", "claimant" ];
const maxParams = [ ...requiredParams, "solution" ];
if(!_hasValidPrefix(challengeUri, SerializerPrefix.URI.CHALLENGE)) {
return false;
}
const params: {key: string, value: string}[] = _extractUriParams(challengeUri, SerializerPrefix.URI.CHALLENGE);
// arg must have required params
if(params.length < requiredParams.length){
return false;
}
// arg should not exceed max params
if(params.length > maxParams.length){
return false;
}
try {
const nonce: string | undefined = params.find(param => param.key === "nonce")?.value;
const timestamp: string | undefined = params.find(param => param.key === "timestamp")?.value;
const verifier: string | undefined = params.find(param => param.key === "verifier")?.value;
const claimant: string | undefined = params.find(param => param.key === "claimant")?.value;
if(
(!nonce || !timestamp || !verifier || !claimant) || // required params must exist
!SerializerChecker.isKeyUri(verifier) || // verifier must be a valid key uri
!SerializerChecker.isKeyUri(claimant) // claimant must be a valid key uri
){
return false;
}
} catch (error) {
return false;
}
return true;
},
/**
* Returns true if a ciphertext uri is valid.
*/
isCiphertextUri: (ciphertextUri: string): boolean => {
const requiredParams = [ "data", "iv" ];
const maxParamas = [ ...requiredParams, "salt", "sender", "recipient", "signature" ];
if(!_hasValidPrefix(ciphertextUri, SerializerPrefix.URI.CIPHERTEXT)) {
return false;
}
const params: {key: string, value: string}[] = _extractUriParams(ciphertextUri, SerializerPrefix.URI.CIPHERTEXT);
// arg must have required params
if(params.length < requiredParams.length){
return false;
}
// arg should not exceed max params
if(params.length > maxParamas.length){
return false;
}
try {
const data: string | undefined = params.find(param => param.key === "data")?.value;
const iv: string | undefined = params.find(param => param.key === "iv")?.value;
const sender: string | undefined = params.find(param => param.key === "sender")?.value;
const recipient: string | undefined = params.find(param => param.key === "recipient")?.value;
const signature: string | undefined = params.find(param => param.key === "signature")?.value;
if(
(data === "" || data === "undefined") ||
(iv === "" || iv === "undefined")
){
return false;
}
if(sender && !SerializerChecker.isKeyUri(sender)){
return false;
}
if(recipient && !SerializerChecker.isKeyUri(recipient)){
return false;
}
if(signature && !SerializerChecker.isSignatureUri(signature)){
return false;
}
} catch (error) {
return false;
}
return true;
},
/**
* Returns true if a signature uri is valid.
*/
isSignatureUri: (signatureUri: string): boolean => {
const requiredParams = [ "data", "iv" ];
if(!_hasValidPrefix(signatureUri, SerializerPrefix.URI.SIGNATURE)) {
return false;
}
const params: {key: string, value: string}[] = _extractUriParams(signatureUri, SerializerPrefix.URI.SIGNATURE);
// arg must have required params
if(params.length < requiredParams.length){
return false;
}
try {
const data: string | undefined = params.find(param => param.key === "data")?.value;
const iv: string | undefined = params.find(param => param.key === "iv")?.value;
if(
(data === "" || data === "undefined") ||
(iv === "" || iv === "undefined")
){
return false;
}
} catch (error) {
return false;
}
return true;
},
/**
* Returns true if a credential uri is valid.
*/
isCredentialUri: (credentialUri: string): boolean => {
const requiredParams = [ "publicKey", "signature" ];
if(!_hasValidPrefix(credentialUri, SerializerPrefix.URI.CREDENTIAL)) {
return false;
}
const params: {key: string, value: string}[] = _extractUriParams(credentialUri, SerializerPrefix.URI.CREDENTIAL);
// arg must have required params
if(params.length !== requiredParams.length){
return false;
}
try {
const publicKey: string | undefined = params.find(param => param.key === "publicKey")?.value;
const signature: string | undefined = params.find(param => param.key === "signature")?.value;
if(
(!publicKey || publicKey === "" || publicKey === "undefined") ||
(!signature || signature === "" || signature === "undefined")
){
return false;
}
if(!SerializerChecker.isKeyUri(publicKey)){
return false;
}
if(!SerializerChecker.isSignatureUri(signature)){
return false;
}
} catch (error) {
return false;