This repository has been archived by the owner on Dec 23, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
EncodeTools.ts
1780 lines (1668 loc) · 62.4 KB
/
EncodeTools.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
import { Buffer } from 'buffer';
import * as msgpack from '@msgpack/msgpack';
const {nanoid} = require('nanoid');
import {
v1 as UUIDv1,
v4 as UUIDv4,
stringify as UUIDStringify,
parse as UUIDParse
} from 'uuid';
const Hashids = require('hashids/cjs');
const base32 = require('base32.js');
const slugid = require('slugid');
const ZstdCodec = require('zstd-codec').ZstdCodec;
const toBuffer = require('typedarray-to-buffer');
import {
md5,
sha1,
sha512,
sha3,
xxhash32,
crc32,
bcrypt as Bcrypt,
bcryptVerify,
xxhash64, BcryptOptions, BcryptVerifyOptions
} from 'hash-wasm';
const ObjSorter = require('node-object-hash/dist/objectSorter');
const LZMA = require('lzma').LZMA;
const Jimp = require('jimp/dist');
import {
CropDims,
ExtractedContentType, ExtractedImageFormatContentType,
ExtractedSerializationFormatContentType, HTTPRequestWithHeader,
IEncodeTools,
ImageDims,
ImageMetadataBase
} from "./IEncodeTools";
import {IncomingMessage} from "http";
const cbor = require('cbor-web');
import * as ContentType from 'content-type';
import * as _ from 'lodash';
import Base85 from 'base85';
/**
* Is thrown when a content type cannot be determined
*/
export class InvalidContentTypeError extends Error {
constructor(contentType: string) {
super(`Invalid content type ${contentType}`);
}
}
/**
* Is thrown when a header cannot be found
*/
export class InvalidHeaderError extends Error {
constructor(contentType: string) {
super(`Invalid header ${contentType}`);
}
}
export enum BinaryEncoding {
/**
* Node.js buffer under a compatibility layer for the browser
*/
nodeBuffer = 'nodeBuffer',
/**
* Base64 String
*/
base64 = 'base64',
/**
* Base64 String
*/
base64url = 'base64url',
/**
* Hexadecimal String
*/
hex = 'hex',
/**
* URL-safe base32 string
*/
base32 = 'base32',
/**
* Not recommended, hashids library for backwards compatability
*/
hashids = 'hashids',
/**
* A platform agnostic ArrayBuffer
*/
arrayBuffer = 'arrayBuffer',
/**
* Base85 in the ASCII-85 encoding, requires escaping when used in JSON
*
* https://en.wikipedia.org/wiki/Ascii85
*/
ascii85 = 'ascii85',
// /**
// * Base85 in the ZeroMQ-85 (z85) encoding, does not require escaping when used in JSON
// *
// * https://rfc.zeromq.org/spec/32/
// */
// z85 = 'z85',
/**
* Base85 in the ASCII-85 encoding, requires escaping when used in JSON
*
* https://en.wikipedia.org/wiki/Ascii85
*/
base85 = 'ascii85'
}
export enum HashAlgorithm {
crc32 = 'crc32',
/**
* Super fast non-cryptographic hashing algorithm.
*/
xxhash64 = 'xxhash64',
/**
* Super fast non-cryptographic hashing algorithm.
*/
xxhash32 = 'xxhash32',
/**
* Super fast non-cryptographic hashing algorithm.
*/
/**
* Insecure hashing algorithm, included for backwards compatibility.
*/
md5 = 'md5',
/**
* SHA2 hashing algorithm.
*/
sha1 = 'sha1',
/**
* SHA512 hashing algorithm.
*/
sha512 = 'sha512',
/**
* SHA2 hashing algorithm.
* @deprecated Use SHA512
*/
sha2 = 'sha2',
/**
* SHA3 hashing algorithm.
*/
sha3 = 'sha3',
/**
* BCrypt hashing algorithm
*/
bcrypt = 'bcrypt',
/**
* Must use EncodeToolsNative
* @deprecated
*/
xxhash3 = 'xxhash3'
}
/**
* Different formats for a unique ID.
*/
export enum IDFormat {
/**
* UUID v4, as a Buffer
*/
uuidv4 = 'uuidv4',
/**
* UUID v1, as a Buffer
*/
uuidv1 = 'uuidv1',
/**
* UUID v4 String (with dashes)
* Example: 710b962e-041c-11e1-9234-0123456789ab
*/
uuidv4String = 'uuidv4String',
/**
* UUID v1 String (with dashes)
* Example: 710b962e-041c-11e1-9234-0123456789ab
*/
uuidv1String = 'uuidv1String',
/**
* MongoDB BSON ObjectId.
*
* Will use native library if available.
*/
objectId = 'objectId',
/**
* 4-character NanoID
*/
nanoid = 'nanoid',
/**
* A JavaScript timestamp
*/
timestamp = 'timestamp'
}
/**
* Format for object serialization
*/
export enum SerializationFormat {
/**
* JSON
*/
json = 'json',
/**
* CBOR
*/
cbor = 'cbor',
/**
* Msgpack
*/
msgpack = 'msgpack',
/**
* MongoDB BSON, may throw an error if the object does not contain BSON elements.
*/
bson = 'bson'
}
/**
* Format for compressing/decompressing files
*/
export enum CompressionFormat {
/**
* ZStandard (ZStd)
*/
zstd = 'zstd',
/**
* LZMA
*/
lzma = 'lzma'
}
/**
* Format for converting images
*/
/**
* Format for converting images
*/
export enum ImageFormat {
png = 'png',
jpeg = 'jpeg',
// bmp = 'bmp',
/**
* Must use EncodeToolsNative to use this format
* @deprecated
*/
webp = 'webp',
/**
* Must use EncodeToolsNative to use this format
* @deprecated
*/
avif = 'avif',
/**
* Must use EncodeToolsNative to use this format
* @deprecated
*/
tiff = 'tiff',
/**
* Must use EncodeToolsNative to use this format
* @deprecated
*/
gif = 'gif',
/**
* Must use EncodeToolsNative to use this format
* @deprecated
*/
// svg = 'svg'
}
/**
* Default options for the encoding tools.
* These will be used if none are passed to the functions used.
*/
export interface EncodingOptions {
uniqueIdFormat?: IDFormat;
serializationFormat?: SerializationFormat;
hashAlgorithm?: HashAlgorithm;
binaryEncoding?: BinaryEncoding;
compressionFormat?: CompressionFormat;
compressionLevel?: number;
imageFormat?: ImageFormat;
}
export class InvalidFormat extends Error {
constructor(format?: any) {
super(
'The format requested'+(
format ? ' '+format:''
)+' is not available for this operation'
);
}
}
/**
* The input type commonly accepted by most functions
*/
export type BinaryInputOutput = Buffer|string|ArrayBuffer;
export type EncodeToolsFormat = IDFormat|SerializationFormat|HashAlgorithm|BinaryEncoding|CompressionFormat|ImageFormat;
export type EncodeToolsFunction<F extends EncodeToolsFormat, R extends BinaryInputOutput> = (input: BinaryInputOutput, format?: F, ...args: any[]) => Promise<R>|R;
function ensureBuffer(...args: any[]): Buffer {
return (Buffer.from as any)(...args);
}
/**
* Default options used by encode tools
*/
export const DEFAULT_ENCODE_TOOLS_OPTIONS: EncodingOptions = {
binaryEncoding: BinaryEncoding.base64,
hashAlgorithm: HashAlgorithm.xxhash64,
serializationFormat: SerializationFormat.json,
uniqueIdFormat: IDFormat.uuidv1String,
compressionFormat: CompressionFormat.lzma,
imageFormat: ImageFormat.png
};
export type ImageMetadata = ImageMetadataBase<ImageFormat>;
/**
* A `SerializationFormat` or `ImageFormat`
*/
export type ConvertableFormat = ImageFormat|SerializationFormat;
/**
* MIME Types for all serialization formats
*/
export const SerializationFormatMimeTypes: Map<SerializationFormat, string> = new Map<SerializationFormat, string>([
[ SerializationFormat.json, 'application/json' ],
/**
* Per https://zb.gy/DlNu
*/
[ SerializationFormat.msgpack, 'application/msgpack' ],
/**
* Per https://zb.gy/cb-T
*/
[SerializationFormat.cbor, 'application/cbor'],
/**
* Seems to be https://zb.gy/AYR1
*/
[ SerializationFormat.bson, 'application/bson' ]
]);
/**
* Serialization formats for each MIME Type
*/
export const MimeTypesSerializationFormat: Map<string, SerializationFormat> = new Map<string, SerializationFormat>(Array.from(
SerializationFormatMimeTypes.entries()
).map(([a,b]) => [b,a]));
/**
* MIME Types for all image formats
*/
export const ImageFormatMimeTypes: Map<ImageFormat, string> = new Map<ImageFormat, string>([
[ ImageFormat.avif, 'image/avif' ],
[ ImageFormat.tiff, 'image/tiff' ],
[ ImageFormat.gif, 'image/gif' ],
[ ImageFormat.png, 'image/png' ],
[ ImageFormat.jpeg, 'image/jpeg' ],
[ ImageFormat.webp, 'image/webp' ]
]);
/**
* Image formats for each MIME Type
*/
export const MimeTypesImageFormat: Map<string, ImageFormat> = new Map<string, ImageFormat>(
Array.from(ImageFormatMimeTypes.entries()).map(([a,b]) => [b,a])
);
/**
* Combined map of all `SerializationFormat` and `ImageFormat` entries to their respective MIME Types
*/
export const ConvertableFormatMimeTypes: Map<ConvertableFormat, string> = new Map<ConvertableFormat, string>(
[
...Array.from(ImageFormatMimeTypes),
...Array.from(SerializationFormatMimeTypes),
]
);
/**
* Map of MIME Type to each `ImageFormat` or `SerializationFormat`.
*/
export const MimeTypesConvertableFormat: Map<string, ConvertableFormat> = new Map<string, ConvertableFormat>(
Array.from(ConvertableFormatMimeTypes.entries()).map(([a,b]) => [b,a])
);
/**
* Contains tools for encoding/decoding data in different circumstances.
*
*/
export class EncodeTools implements IEncodeTools {
constructor(public options: EncodingOptions = DEFAULT_ENCODE_TOOLS_OPTIONS) {
}
/**
* Combined map of all `SerializationFormat` and `ImageFormat` entries to their respective MIME Types
*/
public get convertableFormatMimeTypes() { return ConvertableFormatMimeTypes; }
/**
* Map of MIME Type to each `ImageFormat` or `SerializationFormat`.
*/
public get mimeTypesConvertableFormat() { return MimeTypesConvertableFormat; }
public headerToConvertableFormat(req: HTTPRequestWithHeader, key: string, defaultValue?: ConvertableFormat): ExtractedContentType<ConvertableFormat> {
let format: ConvertableFormat|null = defaultValue || null;
let mimeType: string|null = null;
if (req.headers[key] && !_.isEmpty(req.headers[key])) {
try {
const contentType = ContentType.parse(req.headers[key] as string);
mimeType = contentType?.type || null;
} catch (err) { }
}
if (mimeType) {
if (MimeTypesConvertableFormat.has(mimeType) )
format = MimeTypesConvertableFormat.get(mimeType);
}
return {
format,
mimeType: (format ? ConvertableFormatMimeTypes.get(format) : mimeType) || mimeType,
header: key
};
}
public headerToSerializationFormat(req: HTTPRequestWithHeader, key: string): ExtractedSerializationFormatContentType {
return this.headerToConvertableFormat(req, key, this.options.serializationFormat) as ExtractedSerializationFormatContentType;
}
public headerToImageFormat(req: HTTPRequestWithHeader, key: string): ExtractedImageFormatContentType {
return this.headerToConvertableFormat(req, key, this.options.imageFormat) as ExtractedImageFormatContentType;
}
/**
* Always returns the provided data as a `Buffer`, passing the data through `Buffer.from` if not already a Buffer
*
* @param n Number of bytes to return
* @author https://zb.gy/_wpj
*/
public static ensureBuffer(buf: BinaryInputOutput): Buffer {
// @ts-ignore
return Buffer.isBuffer(buf as any) ? buf: ensureBuffer(buf as any);
}
/**
* Attempts to load a module if available, or returns null
*
* @param n Number of bytes to return
* @author https://zb.gy/_wpj
*/
public static safeLoadModule(name: string): any {
if (typeof(require) === 'undefined')
return null;
try {
return require(name);
}
catch (e) {
return null;
}
}
/**
* Gets random bytes returning the result as a `Buffer`
* @param n Number of bytes to return
*/
public static getRandomBytes(n: number): Buffer {
let myself = (typeof(window) !== 'undefined' ? window : void(0)) as any;
if (typeof myself !== 'undefined' && (myself.crypto || myself.msCrypto)) {
let crypto = (myself.crypto || myself.msCrypto), QUOTA = 65536;
let a = new Uint8Array(n);
for (let i = 0; i < n; i += QUOTA) {
crypto.getRandomValues(a.subarray(i, i + Math.min(n - i, QUOTA)));
}
return ensureBuffer(a);
} else {
return require("crypto").randomBytes(n);
}
}
/**
* Encodes an `ArrayBuffer` to a node.js `Buffer` using npm:typedarray-to-buffer, and
* npm:Buffer if node.js Buffer is not available.
* @param arrayBuffer
*/
public static arrayBufferToNodeBuffer (arrayBuffer: any): Buffer { return toBuffer(arrayBuffer); }
/**
* Encodes a node.js `Buffer` as an `ArrayBuffer`
* using npm:Buffer if node.js Buffer is not available.
* @param nodeBuffer
*/
public static nodeBufferToArrayBuffer(nodeBuffer: BinaryInputOutput): ArrayBuffer {
let outBuf = EncodeTools.ensureBuffer(nodeBuffer);
return outBuf.buffer.slice(outBuf.byteOffset, outBuf.byteOffset + outBuf.byteLength);
}
/**
* Decodes a hashids string, first to hex, then to a node.js buffer
* using npm:hashids.
* @param hashid - Hashid string to decode
* @param args - Additional arguments to be passed to the `Hashids` constructor
* in npm:hashids
*/
public static hashidsToNodeBuffer(hashid: string, ...args: any[]): Buffer {
const hasher = new Hashids(...args);
const hex = hasher.decodeHex(hashid);
return EncodeTools.hexToNodeBuffer(hex);
}
/**
* Encodes a hashids string, from a node.js buffer
* by first converting to hex and then using npm:hashids.
* @param hashid - Hashid string to decode
* @param args - Additional arguments to be passed to the `Hashids` constructor
* in npm:hashids
*/
public static nodeBufferToHashids(nodeBuffer: BinaryInputOutput, ...args: any[]): string {
const hasher = new Hashids(...args);
const hex = EncodeTools.nodeBufferToHex(EncodeTools.ensureBuffer(nodeBuffer));
return hasher.encodeHex(hex);
}
/**
* Encodes a hexadecimal string to a node.js buffer.
* @param hex
*/
public static hexToNodeBuffer(hex: string): Buffer { return ensureBuffer(hex, 'hex'); }
/**
* Encodes a node.js buffer as a hexadecimal string.
* @param hex
*/
public static nodeBufferToHex(buffer: Buffer): string { return buffer.toString('hex'); }
/**
* Encodes a base64 string to a node.js buffer.
* @param hex
*/
public static base64ToNodeBuffer(base64: string): Buffer { return ensureBuffer(base64, 'base64'); }
/**
* Encodes a node.js buffer as a base64 string.
* @param hex
*/
public static nodeBufferToBase64(buffer: Buffer): string { return buffer.toString('base64'); }
//
// /**
// * Encodes a base64 string to a node.js buffer.
// * @param hex
// */
// public static z85ToNodeBuffer(base85: string): Buffer {
// return ensureBuffer(Base85.decode(base85, 'z85') as Buffer);
// }
// /**
// * Encodes a node.js buffer as a base64 string.
// * @param hex
// */
// public static nodeBufferToZ85(buffer: Buffer): string {
// return Base85.encode(buffer, 'z85');
// }
/**
* Encodes a base64 string to a node.js buffer.
* @param hex
*/
public static base85ToNodeBuffer(base85: string): Buffer {
return EncodeTools.ascii85ToNodeBuffer(base85);
}
/**
* Encodes a node.js buffer as a base64 string.
* @param hex
*/
public static nodeBufferToBase85(buffer: Buffer): string {
return EncodeTools.nodeBufferToAscii85(buffer);
}
/**
* Encodes a base64 string to a node.js buffer.
* @param hex
*/
public static ascii85ToNodeBuffer(base85: string): Buffer {
return ensureBuffer(Base85.decode(base85, 'ascii85') as Buffer);
}
/**
* Encodes a node.js buffer as a base64 string.
* @param hex
*/
public static nodeBufferToAscii85(buffer: Buffer): string {
return Base85.encode(buffer, 'ascii85');
}
/**
* Encodes a base64url string to a node.js buffer.
* @author https://zb.gy/ESRN
* @param hex
*/
public static base64urlToNodeBuffer(base64url: string): Buffer {
base64url = (base64url + '==='.slice((base64url.length + 3) % 4))
.replace(/-/g, '+')
.replace(/_/g, '/');
return EncodeTools.base64ToNodeBuffer(base64url);
}
/**
* Encodes a node.js buffer as a base64url string.
* @author https://zb.gy/ESRN
* @param hex
*/
public static nodeBufferToBase64url(buffer: BinaryInputOutput): string {
let base64url = EncodeTools.nodeBufferToBase64(EncodeTools.ensureBuffer(buffer));
base64url = base64url.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '')
return base64url;
}
/**
* Encodes a node.js buffer as a base32 string using npm:base32.js
* @param buffer - Buffer to encode
* @param args - Additional arguments to be passed to the `Encoder` constructor
* in npm:base32.js
*/
public static nodeBufferToBase32(buffer: BinaryInputOutput, ...args: any[]): string {
const encoder = new base32.Encoder(...args);
const base32String = encoder.write(EncodeTools.ensureBuffer(buffer)).finalize();
return base32String;
}
/**
* Encodes a node.js buffer as a base32 string using npm:base32.js
* @param base32String - Base32 string to decode.
* @param args - Additional arguments to be passed to the `Decoder` constructor
* in npm:base32.js
*/
public static base32ToNodeBuffer(base32String: string, ...args: any[]): Buffer {
const decoder = new base32.Decoder(...args);
const bytes = decoder.write(base32String).finalize();
return ensureBuffer(bytes);
}
/**
* Encodes binary data using the provided format returning either a node.js buffer, array buffer, or string
* @param buffer
* @param format
*/
public encodeBuffer(inputBuffer: Buffer|ArrayBuffer, format?: BinaryEncoding.nodeBuffer, ...args: any[]): Buffer;
/**
* Encodes binary data using the provided format returning either a node.js buffer, array buffer, or string
* @param buffer
* @param format
*/
public encodeBuffer(inputBuffer: Buffer|ArrayBuffer, format?: BinaryEncoding.arrayBuffer, ...args: any[]): ArrayBuffer;
/**
* Encodes binary data using the provided format returning either a node.js buffer, array buffer, or string
* @param buffer
* @param format
*/
public encodeBuffer(inputBuffer: Buffer|ArrayBuffer|string, format?: BinaryEncoding.hex, ...args: any[]): string;
/**
* Encodes binary data using the provided format returning either a node.js buffer, array buffer, or string
* @param buffer
* @param format
*/
public encodeBuffer(inputBuffer: Buffer|ArrayBuffer|string, format?: BinaryEncoding.base64, ...args: any[]): string;
/**
* Encodes binary data using the provided format returning either a node.js buffer, array buffer, or string
* @param buffer
* @param format
*/
public encodeBuffer(inputBuffer: Buffer|ArrayBuffer|string, format?: BinaryEncoding.base32, ...args: any[]): string;
/**
* Encodes binary data using the provided format returning either a node.js buffer, array buffer, or string
* @param buffer
* @param format
*/
public encodeBuffer(inputBuffer: Buffer|ArrayBuffer|string, format?: BinaryEncoding.base64url, ...args: any[]): string;
/**
* Encodes binary data using the provided format returning either a node.js buffer, array buffer, or string
* @param buffer
* @param format
*/
public encodeBuffer(inputBuffer: Buffer|ArrayBuffer|string, format?: BinaryEncoding.hashids, ...args: any[]): string;
/**
* Encodes binary data using the provided format returning either a node.js buffer, array buffer, or string
* @param buffer
* @param format
*/
public encodeBuffer(inputBuffer: Buffer|ArrayBuffer|string, format?: BinaryEncoding.base85, ...args: any[]): string;
// /**
// * Encodes binary data using the provided format returning either a node.js buffer, array buffer, or string
// * @param buffer
// * @param format
// */
// public encodeBuffer(inputBuffer: Buffer|ArrayBuffer|string, format?: BinaryEncoding.z85, ...args: any[]): string;
/**
* Encodes binary data using the provided format returning either a node.js buffer, array buffer, or string
* @param buffer
* @param format
*/
public encodeBuffer(inputBuffer: Buffer|ArrayBuffer|string, format?: BinaryEncoding.ascii85, ...args: any[]): string;
/**
* Encodes binary data using the provided format returning either a node.js buffer, array buffer, or string
* @param buffer
* @param format
*/
public encodeBuffer(inputBuffer: BinaryInputOutput, format?: BinaryEncoding, ...args: any[]): BinaryInputOutput;
/**
* Encodes binary data using the provided format returning either a node.js buffer, array buffer, or string
* @param buffer
* @param format
*/
public encodeBuffer(inputBuffer: BinaryInputOutput, format = this.options.binaryEncoding, ...args: any[]): BinaryInputOutput {
const buffer: Buffer = EncodeTools.ensureBuffer(inputBuffer);
if (format === BinaryEncoding.nodeBuffer) return buffer;
else if (format === BinaryEncoding.arrayBuffer) return EncodeTools.nodeBufferToArrayBuffer(buffer);
else if (format === BinaryEncoding.base64) return EncodeTools.nodeBufferToBase64(buffer);
else if (format === BinaryEncoding.base64url) return EncodeTools.nodeBufferToBase64url(buffer);
else if (format === BinaryEncoding.base32) return EncodeTools.nodeBufferToBase32(buffer);
else if (format === BinaryEncoding.hashids) return EncodeTools.nodeBufferToHashids(buffer, ...args);
else if (format === BinaryEncoding.hex) return EncodeTools.nodeBufferToHex(buffer);
// else if (format === BinaryEncoding.z85) return EncodeTools.nodeBufferToZ85(buffer);
else if (format === BinaryEncoding.ascii85) return EncodeTools.nodeBufferToAscii85(buffer);
throw new InvalidFormat(format);
}
/**
* Decodes binary data from the provided format returning either a node.js buffer.
* @param buffer
* @param format
*/
public decodeBuffer(buffer: ArrayBuffer, format?: BinaryEncoding.arrayBuffer, ...args: any[]): Buffer;
/**
* Decodes binary data from the provided format returning either a node.js buffer.
* @param buffer
* @param format
*/
public decodeBuffer(buffer: Buffer, format?: BinaryEncoding.nodeBuffer, ...args: any[]): Buffer;
/**
* Decodes binary data from the provided format returning either a node.js buffer.
* @param buffer
* @param format
*/
public decodeBuffer(input: string, format?: BinaryEncoding.hex, ...args: any[]): Buffer;
/**
* Decodes binary data from the provided format returning either a node.js buffer.
* @param buffer
* @param format
*/
public decodeBuffer(input: string, format?: BinaryEncoding.base32, ...args: any[]): Buffer;
/**
* Decodes binary data from the provided format returning either a node.js buffer.
* @param buffer
* @param format
*/
public decodeBuffer(input: string, format?: BinaryEncoding.hashids, ...args: any[]): Buffer;
/**
* Decodes binary data from the provided format returning either a node.js buffer.
* @param buffer
* @param format
*/
public decodeBuffer(input: string, format?: BinaryEncoding.base64, ...args: any[]): Buffer;
/**
* Decodes binary data from the provided format returning either a node.js buffer.
* @param buffer
* @param format
*/
public decodeBuffer(input: string, format?: BinaryEncoding.base64url, ...args: any[]): Buffer;
/**
* Decodes binary data from the provided format returning either a node.js buffer.
* @param buffer
* @param format
*/
public decodeBuffer(input: string, format?: BinaryEncoding.base85, ...args: any[]): Buffer;
// /**
// * Decodes binary data from the provided format returning either a node.js buffer.
// * @param buffer
// * @param format
// */
// public decodeBuffer(input: string, format?: BinaryEncoding.z85, ...args: any[]): Buffer;
/**
* Decodes binary data from the provided format returning either a node.js buffer.
* @param buffer
* @param format
*/
public decodeBuffer(input: string, format?: BinaryEncoding.ascii85, ...args: any[]): Buffer;
/**
* Decodes binary data from the provided format returning either a node.js buffer.
* @param buffer
* @param format
*/
public decodeBuffer(buffer: BinaryInputOutput, format?: BinaryEncoding, ...args: any[]): Buffer;
/**
* Decodes binary data from the provided format returning either a node.js buffer.
* @param buffer
* @param format
*/
public decodeBuffer(buffer: BinaryInputOutput, format = this.options.binaryEncoding, ...args: any[]): Buffer {
if (format === BinaryEncoding.nodeBuffer)
return ensureBuffer(buffer);
else if (format === BinaryEncoding.arrayBuffer) return EncodeTools.arrayBufferToNodeBuffer(buffer);
else if (format === BinaryEncoding.base64) return EncodeTools.base64ToNodeBuffer(buffer.toString());
else if (format === BinaryEncoding.base64url) return EncodeTools.base64urlToNodeBuffer(buffer.toString());
else if (format === BinaryEncoding.base32) return EncodeTools.base32ToNodeBuffer(buffer.toString());
else if (format === BinaryEncoding.hashids) return EncodeTools.hashidsToNodeBuffer(buffer.toString(), ...args);
else if (format === BinaryEncoding.hex) return EncodeTools.hexToNodeBuffer(buffer.toString());
// else if (format === BinaryEncoding.z85) return EncodeTools.z85ToNodeBuffer(buffer.toString());
else if (format === BinaryEncoding.ascii85) return EncodeTools.ascii85ToNodeBuffer(buffer.toString());
throw new InvalidFormat(format);
}
public static async crc32(buffer: BinaryInputOutput): Promise<Buffer> {
return ensureBuffer(await crc32(EncodeTools.ensureBuffer(buffer)), 'hex');
}
/* Hashing functions */
/**
* Hashes using XXHash-32 (https://zb.gy/l4kN), a fast, non-cryptographic,
* hashing function.
*
* Uses XXHash from npm:hash-wasm
* @param buffer
* @param args
*/
public static async xxhash32(buffer: BinaryInputOutput, ...args: any[]): Promise<Buffer> {
return ensureBuffer(await xxhash32(EncodeTools.ensureBuffer(buffer), ...args), 'hex');
}
/**
* Hashes using XXHash-64 (https://zb.gy/l4kN), a fast, non-cryptographic,
* hashing function.
*
* Uses XXHash from npm:hash-wasm
* @param buffer
* @param args
*/
public static async xxhash64(buffer: BinaryInputOutput, ...args: any[]): Promise<Buffer> {
return ensureBuffer(await xxhash64(EncodeTools.ensureBuffer(buffer), ...args), 'hex');
}
/**
* Uses the very popular, but UNSAFE, SHA-1 cryptographic algorithm.
* Use SHA3 for new projects.
*
* Uses SHA1 from npm:hash-wasm
* @param buffer
* @param args
*/
public static async sha1(buffer: BinaryInputOutput): Promise<Buffer> { return ensureBuffer(await sha1(EncodeTools.ensureBuffer(buffer)), 'hex'); }
/**
* Uses the popular, but UNSAFE, 512bit SHA-2 cryptographic algorithm.
* Use SHA3 for new projects.
*
* Uses 512bit SHA from npm:hash-wasm
* @param buffer
* @param args
*/
public static async sha512(buffer: BinaryInputOutput): Promise<Buffer> { return ensureBuffer(await sha512(EncodeTools.ensureBuffer(buffer)), 'hex'); }
/**
* Uses the popular, but UNSAFE, 512bit SHA-2 cryptographic algorithm.
* Use SHA3 for new projects.
*
* Uses 512bit SHA from npm:hash-wasm
* @param buffer
* @param args
* @deprecated Use SHA512 instead
*/
public static async sha2(buffer: BinaryInputOutput): Promise<Buffer> { return EncodeTools.sha512(buffer); }
/**
* Uses the new SHA-3 cryptographic algorithm.
*
* Uses SHA-3 from npm:hash-wasm
* @param buffer
* @param args
*/
public static async sha3(buffer: BinaryInputOutput): Promise<Buffer> { return ensureBuffer(await sha3(EncodeTools.ensureBuffer(buffer)), 'hex'); }
/**
* Uses the very popular, but VERY VERY UNSAFE, MD5 cryptographic algorithm.
* Use SHA3 for new projects.
*
* Uses MD5 from npm:hash-wasm
* @param buffer
* @param args
*/
public static async md5(buffer: BinaryInputOutput): Promise<Buffer> { return ensureBuffer(await md5(EncodeTools.ensureBuffer(buffer)), 'hex'); }
/**
* Hashes using bcrypt
* @param buffer
* @param args
*/
public static async bcrypt(buffer: BinaryInputOutput, options?: BcryptOptions): Promise<Buffer> {
options = (options || {}) as any;
options.password = ensureBuffer(buffer).toString('utf8');
if (!options.salt)
options.salt = EncodeTools.getRandomBytes(16);
if (!options.costFactor)
options.costFactor = 11;
if (!options.outputType)
options.outputType = 'encoded';
let key = await Bcrypt(options);
return ensureBuffer(EncodeTools.ensureBuffer(key), 'hex');
}
/**
* Compares a password with bcrypt
* @param buffer
* @param args
*/
public static async bcryptVerify(password: BinaryInputOutput, hash: BinaryInputOutput, options: BcryptVerifyOptions = ({} as any)): Promise<boolean> {
const hashString = (EncodeTools.ensureBuffer(hash).toString('utf8'));
options.password = EncodeTools.ensureBuffer(password);
options.hash = hashString;
return bcryptVerify(options);
}
/**
* Hashes data using the provided algorithm, returning a node.js Buffer.
*
* @param buffer
* @param algorithm
*/
public async hash(buffer: BinaryInputOutput, algorithm: HashAlgorithm = this.options.hashAlgorithm, ...args: any[]): Promise<Buffer> {
if (algorithm === HashAlgorithm.xxhash64) return EncodeTools.xxhash64(buffer, ...args);
else if (algorithm === HashAlgorithm.xxhash32) return EncodeTools.xxhash32(buffer, ...args);
else if (algorithm === HashAlgorithm.sha1) return EncodeTools.sha1(buffer);
else if (algorithm === HashAlgorithm.sha512) return EncodeTools.sha512(buffer);
else if (algorithm === HashAlgorithm.sha2) return EncodeTools.sha2(buffer);
else if (algorithm === HashAlgorithm.sha3) return EncodeTools.sha3(buffer);
else if (algorithm === HashAlgorithm.md5) return EncodeTools.md5(buffer);
else if (algorithm === HashAlgorithm.bcrypt) return EncodeTools.bcrypt(buffer, ...args);
else if (algorithm === HashAlgorithm.crc32) return EncodeTools.crc32(buffer);
throw new InvalidFormat(algorithm);
}
/**
* Hashes data using the provided algorithm, returning a node.js Buffer.
*
* @param buffer
* @param algorithm
*/
public async hashString(buffer: BinaryInputOutput, algorithm: HashAlgorithm = this.options.hashAlgorithm, ...args: any[]): Promise<string> {
let buf = (await this.hash(EncodeTools.ensureBuffer(buffer), algorithm, ...args));
return buf.toString('hex');
}
/**
* Hashes an object using the provided algorithm, returning a node.js Buffer.
*
* @param buffer
* @param algorithm
*/
public async hashObject(obj: any, algorithm: HashAlgorithm = this.options.hashAlgorithm, ...args: any[]): Promise<Buffer> {
// @ts-ignore
let sorter = ObjSorter();
let buffer = ensureBuffer(
sorter(obj)
);
return (await this.hash(buffer, algorithm, ...args));
}
/**
* Generates a v1 UUID, returning the bytes as an array of numbers
*
* @param buffer
* @param algorithm
*/
protected static uuidv1Array(): number[] {
const buf: number[] = [];
UUIDv1(void(0), buf, 0);
return buf;
}
/**
* Generates a v4 UUID, returning the bytes as an array of numbers
*
* @param buffer
* @param algorithm
*/
protected static uuidv4Array(): number[] {
const buf: number[] = [];
UUIDv4(void(0), buf, 0);
return buf;
}
/**
* Generates an ID using nanoid
*
* @param size Size of the id (in characters)
*/
public static nanoid(size?: number): string {
return nanoid(size);
}