-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
70 lines (59 loc) · 2.17 KB
/
index.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
'use strict'
/*
___ ___ ___ _____ ___ ___
/ /\ / /\ / /\ / /::\ / /\ / /\
/ /:/_ / /:/_ / /:/_ / /:/\:\ / /:/_ / /::\
/ /:/ /\ / /:/ /\ / /:/ /\ / /:/ \:\ / /:/ /\ / /:/\:\
/ /:/ /::\ / /:/ /:/_ / /:/ /:/_ /__/:/ \__\:| / /:/ /:/_ / /:/~/:/
/__/:/ /:/\:\ /__/:/ /:/ /\ /__/:/ /:/ /\ \ \:\ / /:/ /__/:/ /:/ /\ /__/:/ /:/___
\ \:\/:/~/:/ \ \:\/:/ /:/ \ \:\/:/ /:/ \ \:\ /:/ \ \:\/:/ /:/ \ \:\/:::::/
\ \::/ /:/ \ \::/ /:/ \ \::/ /:/ \ \:\/:/ \ \::/ /:/ \ \::/~~~~
\__\/ /:/ \ \:\/:/ \ \:\/:/ \ \::/ \ \:\/:/ \ \:\
/__/:/ \ \::/ \ \::/ \__\/ \ \::/ \ \:\
\__\/ \__\/ \__\/ \__\/ \__\/
@datamosh
*/
const { createHash } = require('crypto')
const now = require('./utils/now')
/**
* Make a SHA512 hexadecimal hash
* @param {...any} args String coercible metadata used when generating the seed
* @returns SHA512 hexadecimal hash
*/
const seeder512 = (...args) => {
const argsBuff = args?.reduce((acc, val) => {
if (!val.toString) return acc
const valBuff = Buffer.from(val.toString())
return Buffer.concat([acc, valBuff])
}, Buffer.from(''))
const hash = createHash('sha512')
hash.write(now())
hash.write(argsBuff.toString('utf16le'))
return hash.digest('hex')
}
/**
* Make a 4 byte hexadecimal hash
* @param {...any} args String coercible metadata used when generating the seed
* @returns 4 byte hexadecimal hash
*/
const seeder = (...args) => {
const seed512 = seeder512(...args)
return seed512.slice(0, 8)
}
/**
* Validate seed from seeder
* @param {String} seed Seed to validate
* @param {Number} nibbles Optional: number of nibbles expected
*/
const validate = (seed, nibbles = 8) => {
if (seed.constructor.name !== 'String') return false
// nibble = 4 bits
if (seed.length !== nibbles) return false
const hexRegex = /^([0-9A-Fa-f]{2})*$/
return hexRegex.test(seed)
}
module.exports = {
seeder,
seeder512,
validate
}