@synotech/utils
v1.0.3
Published
a collection of utilities for internal use
Downloads
74
Maintainers
Readme
Table of Contents
- validateEmail
- validateEmailBulk
- tld
- atIndex
- Cryptography
- NODE_CIPHER
- AUTH_TAG_BYTE_LEN
- IV_BYTE_LEN
- KEY_BYTE_LEN
- SALT_BYTE_LEN
- get
- invoiceTotals
- currencyParse
- phoneNumberGetInternationalString
- toJSON
- initials
- currencyMask
- isTrue
- sleep
- phoneNumberFormatString
- emailGetFromString
- searchObject
- truncate
- dateFormat
- publicKeySetString
- publicKeyGetString
- bloodGroups
- accountsAsset
- accountsEquity
- accountsPayable
- accountsLiability
- accountsReceivable
- currencyDenomination
- estimateTerm
- invoiceTerm
- itemCategory
- employmentStatus
- customerTypes
- bankAccountType
- dateFormats
- contactType
- expenseStatus
- salaryFrequency
- leavePolicy
- languages
- taxTypes
- expenseType
- gender
- documentSize
- deliveryNoteStatus
- creditNoteStatus
- invoiceStatus
- estimateStatus
- docTypes
- months
- monthDays
- industries
- monthNameNumber
- orderStatus
- paymentMethods
- deliveryMethods
- paymentStatus
- paymentTerms
- productTypes
- alphabet
- productUnits
- quoteStatus
- recurringFrequency
- salutations
- weekdays
- timezones
- payoutMethod
- paymentMethod
- transactionStatus
- Country
App dictionary
App countries
validateEmail
This method validates email address
Parameters
Examples
const isValid = await validateEmail({
email: '[email protected]',
})
Returns boolean {Promise} a boolean value indicating if the email is valid or not
validateEmailBulk
This method validates all supplied email addresses.
Parameters
mailingList
Array array of email objects to be verified
Examples
const { data } = await validateEmailBulk(
{
email: '[email protected]',
},
{
email: '[email protected]',
},
])
Returns Array object consisting of valid and invalid email addresses { valid: [], invalid: [] }
Check if the email contains more than 3 numeric characters. If it does, throw an error.
tld
Validate TLD
Parameters
email
any
atIndex
remove email modifier
Cryptography
The Cryptography class provides methods for encryption, decryption, signing, and verification of data using various cryptographic algorithms.
Examples
const cryptography = new Cryptography({
keys: ['key1', 'key2', 'key3'],
encryptKey: '',
encryptKeySingle: '',
})
const encryptedData = cryptography.encrypt('Hello, World!')
const decryptedData = cryptography.decrypt(encryptedData)
const signature = cryptography.signature()
const isVerified = cryptography.signatureVerify(signature)
// creates a KrugerGold Token Address
const address = cryptography.address()
const encodedData = cryptography.base64Encode('Hello, World!')
const decodedData = cryptography.base64Decode(encodedData)
const isEncodedOrNot = cryptography.isBase64Encoded(encodedData)
cryptography.get('strong_pw') // returns i=SQ_qa3W[<RxoM
cryptography.random({ length: 20, useLowerCase: true, useUpperCase: true, useNumbers: true, useSpecial: true, useHex: false }) // returns *ajz:74,*ak0
random
Parameters
options
RandomOptions
Examples
cryptography.random({ length: 20, useLowerCase: true, useUpperCase: true, useNumbers: true, useSpecial: true, useHex: false }) // returns *ajz:74,*ak0
// Decent Passwords - Good for nothing really, public accounts and other non-critical things.
cryptography.get('decent_pw') // returns rXjdx36oro
// Strong Passwords - Robust enough to keep your web hosting account secure.
cryptography.get('strong_pw') // returns i=SQ_qa3W[<RxoM
// Fort Knox Passwords - Secure enough for almost anything, like root or administrator passwords.
cryptography.get('ft_knox_pw') // returns P}U%H\OOYAYb;wc"3hgI,3Lz[gd-z]
// Encryption Keys - Can be used for any other 256-bit key requirement.
cryptography.get('ci_key') // returns CeXHpM3nDgzdv0o3AkMCs3OuxzepLGW8
// 160-bit WPA Key
cryptography.get('160_wpa') // returns oHI#gR8z#h7BS>cZ!zH(
// 504-bit WPA Key
cryptography.get('504_wpa') // returns <os[g`s}u06jqt"Ea]t11,HsI[UipHD)%F";:9RhJ@kTU8GknLpMAXtoCzsJjT`
// 64-bit WEP Keys
cryptography.get('64_wep') // returns 8911B
// 128-bit WEP Keys
cryptography.get('128_wep') // returns 9F4E4F933BCCC
// 152-bit WEP Keys
cryptography.get('152_wep') // returns 695E1EE96E483961
// 256-bit WEP Keys
cryptography.get('256_wep') // returns AC7E866246BA6B71BF5D88A6861AB
Returns string
salt
Examples
const salt = cryptography.salt()
console.log(salt)
// Output:
// 5eb63bbbe01eeed093cb22bb8f5acdc3
Returns any The generated salt value as a hexadecimal string.
iv
Returns any The generated IV as a Buffer.
signature
Examples
const signature = cryptography.signature()
console.log(signature)
// Output:
// 6a3a4b5c6d7e8f9a
Returns any The generated signature as a string.
signatureVerify
Parameters
signature
string The signature to verify.
Examples
const signature = '6a3a4b5c6d7e8f9a'
const isValid = cryptography.signatureVerify(signature)
console.log(isValid)
// Output:
// true
- Throws any An error if the signature contains unknown identifiers.
Returns any True if the signature is valid, false otherwise.
address
Examples
const address = cryptography.address()
console.log(address)
// Output:
// kK5HCVlAmmEnnlKh6wVX9TiJ6YGI7FCl
- Throws any An error if an error occurs during address generation.
Returns any The generated address as a string.
getKeys
Parameters
count
number? The number of keys to generate. Defaults to 12.
Returns any An array of randomly generated keys.
encryptSingle
Parameters
data
any The data to encrypt.
Examples
const crypto = new Cryptography(['key1', 'key2', 'key3'], 'encryptKey', 'encryptKeySingle')
const data = 'Hello, World!'
const encryptedData = cryptography.encryptSingle(data)
console.log(encryptedData)
// Output:
// 5eb63bbbe01eeed093cb22bb8f5acdc3
Returns any The encrypted data as a base64-encoded string.
encrypt
Parameters
text
any The text to encrypt.
Examples
const text = 'Hello, World!'
const encryptedText = cryptography.encrypt(text)
console.log(encryptedText)
// Output:
// 6a3a4b5c6d7e8f9a:6a3a4b5c6d7e8f9a:6a3a4b5c6d7e8f9a
- Throws any An error if an error occurs during encryption.
Returns any The encrypted text as a string.
decrypt
Parameters
encryptedText
any The encrypted text to decrypt.
Examples
const encryptedText = '6a3a4b5c6d7e8f9a:6a3a4b5c6d7e8f9a:6a3a4b5c6d7e8f9a'
const decryptedText = cryptography.decrypt(encryptedText)
console.log(decryptedText)
// Output:
// Hello, World!
- Throws any An error if an error occurs during decryption.
Returns any The decrypted text as a string.
password
Parameters
Examples
const password = 'myPassword'
const salt = cryptography.salt()
const hashedPassword = cryptography.password(password, salt)
console.log(hashedPassword)
// Output:
// 5ebe2294ecd0e0f08eab7690d2a6ee69
- Throws any An error if an error occurs during password hashing.
Returns any The hashed password as a hexadecimal string.
jwtIssue
Parameters
payload
any The payload to include in the JWT. (optional, default{}
)expiry
string The expiry time for the JWT.
Examples
const payload = {
sub: '1234567890',
name: 'John Doe',
iat: 1516239022
}
const expiry = '1h'
const token = cryptography.jwtIssue(payload, expiry)
console.log(token)
// Output:
// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
- Throws any An error if an error occurs during JWT issuance.
Returns any The issued JWT as a string.
jwtVerify
Parameters
token
string The JWT to verify.
Examples
const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'
const payload = cryptography.jwtVerify(token)
console.log(payload)
// Output:
// {
// sub: '1234567890',
// name: 'John Doe',
// iat: 1516239022
// }
- Throws any An error if the JWT is invalid or an error occurs during verification.
Returns any The decoded payload if the JWT is valid.
privateKey
Examples
const privateKey = cryptography.privateKey()
console.log(privateKey)
// Output:
// -----BEGIN PRIVATE KEY-----
// MIHuAgEAMBAGByqGSM49AgEGBSuBBAAjBIHWMIHTAgEBBEIBA4GCAWqjggFMMIIB
// ...
// -----END PRIVATE KEY-----
- Throws any An error if an error occurs during private key generation.
Returns any The generated private key as a PEM-encoded string.
publicKey
Parameters
privateKey
string The private key to generate the public key from.
Examples
const privateKey = `-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDZ1Ck6vJQK0J5T
...
-----END PRIVATE KEY-----`
const publicKey = cryptography.publicKey(privateKey)
console.log(publicKey)
// Output:
// -----BEGIN PUBLIC KEY-----
// MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2dQpOryUCtCeUz8vZ6zB
// ...
// -----END PUBLIC KEY-----
Returns any The generated public key as a PEM-encoded string.
publicKeyVerify
Parameters
$0
{privateKey: string, publicKey: string}$0.privateKey
$0.publicKey
privateKey
The private key used to sign the data.publicKey
The public key used to verify the signature.
Examples
const privateKey = `-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDZ1Ck6vJQK0J5T
...
-----END PRIVATE KEY-----`
const publicKey = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2dQpOryUCtCeUz8vZ6zB
...
-----END PUBLIC KEY-----`
const isAuthentic = cryptography.publicKeyVerify({ privateKey, publicKey })
console.log(isAuthentic)
// Output:
// true
- Throws any An error if the public key fails to authenticate.
Returns any True if the public key is authentic, false otherwise.
isBase64Encoded
Parameters
string
string The string to check.
Examples
const encodedString = 'SGVsbG8sIFdvcmxkIQ=='
const isEncoded = cryptography.isBase64Encoded(encodedString)
console.log(isEncoded)
// Output:
// true
Returns any True if the string is base64 encoded, false otherwise.
base64Encode
Parameters
data
string The data to encode.
Examples
const data = 'Hello, World!'
const encodedData = cryptography.base64Encode(data)
console.log(encodedData)
// Output:
// SGVsbG8sIFdvcmxkIQ==
Returns any The base64-encoded string.
base64Decode
Parameters
encodedString
string The base64-encoded string to decode.
Examples
const encodedString = 'SGVsbG8sIFdvcmxkIQ=='
const decodedString = cryptography.base64Decode(encodedString)
console.log(decodedString)
// Output:
// Hello, World!
Returns any The decoded string.
NODE_CIPHER
GCM is an authenticated encryption mode that not only provides confidentiality but also provides integrity in a secured way.
AUTH_TAG_BYTE_LEN
128 bit auth tag is recommended for GCM.
IV_BYTE_LEN
NIST recommends 96 bits or 12 bytes IV for GCM to promote interoperability, efficiency, and simplicity of design.
KEY_BYTE_LEN
Note: 256 (in ALG name) is key size. NODE size for AES is always 128.
SALT_BYTE_LEN
To prevent rainbow table attacks.
get
Parameters
strength
The strength of the key to generate. decent_pw|strong_pw|ft_knox_pw|ci_key|160_wpa|504_wpa|64_wep|128_wep|152_wep|256_wep
invoiceTotals
Calculates the invoice totals based on the provided parameters.
Parameters
doc
The invoice totals document.docProducts
An array of products in the invoice.taxes
An array of taxes applied to the invoice.
Examples
const doc = {
number: 10001,
objectId: 'testDocObject',
discountAmount: 0,
discountPercentage: 0,
taxableSubTotal: 438.5,
paid: 0,
adjustment: 0,
shipping: 0,
}
const docProducts = [{ qty: 2, price: 100, tax: 15 }]
const taxes = [
{
name: 'VAT',
category: 'sales',
value: 15,
},
{
name: 'None',
category: 'sales',
value: 0,
},
]
Returns any A Promise that resolves to an object containing the calculated invoice totals.
currencyParse
This method validates email address
Parameters
number
String the number or string instance to parse as a floating currency string
Examples
currencyParse('123.43') // return '123.43'
currencyParse('12xs3.3') // return '123.30'
Returns string {String} a boolean value indicating if the email is valid or not
phoneNumberGetInternationalString
Returns the international format of a phone number.
Parameters
phoneNumberObject
An object containing the phone number and country code.
Examples
const phoneNumberObject = {
phoneNumber: '+1234567890',
countryCode: 'US',
}
const internationalPhoneNumber = phoneNumberGetInternationalString(phoneNumberObject);
console.log(internationalPhoneNumber); // Output: { national: '1234567890', international: '+1 234-567-890' }
Returns any The international format of the phone number as a string.
toJSON
This function returns a well structured json object
Parameters
object
string a stringified object in string format
Examples
toJSON('{"name":"John Doe"}') // returns {"name": "John Doe"}
Returns object {Object} a well structured json object
initials
This method returns initials from a given name string
Parameters
alt
string a name string to get initials from
Examples
initials('Zeal Murapa') // returns ZM
Returns string {String} a string of initials
currencyMask
This method validates email address
Parameters
number
number a number to mask as currency
Examples
currencyMask(1000) // returns 1,000
Returns string {String} a string of currency
isTrue
This method is a truthy check for a given value
Parameters
value
any a stringified object in string format
Examples
isTrue('') // returns false
Returns boolean {Boolean} a boolean value
sleep
This function sleeps for a given time
Parameters
ms
ms a number in milliseconds
Examples
await sleep(1000) // sleeps for 1 second
Returns promise {Promise} blocking async promise
phoneNumberFormatString
This function formats a phone number string to international format
Parameters
numberString
string a phone number string
Examples
phoneNumberFormatString('+276925411223') // returns +27 692 541 1223
Returns object {String} a formatted phone number string
emailGetFromString
This function extracts an email address from a string
Parameters
text
string a string containing an email address
Examples
emailGetFromString('This is my email address: [email protected]')
Returns string {String} an email address
searchObject
This function searches an array of objects for a query string
Parameters
Examples
searchObject('John', [{name: 'John Doe'}, {name: 'Jane Doe'}]) // returns [{name: 'John Doe'}]
Returns object {Array} a well structured json object
truncate
This method validates email address
Parameters
str
string a string to truncate
Examples
truncate('This is a long string', 10) // returns 'This is a...'
Returns string {String} a truncated string
dateFormat
This method validates email address
Parameters
date
date a date objectnull
@param {"full" | "long" | "short" | "time"} format - The format of the output.
Examples
dateFormat(new Date(), 'full') // returns 'Sun, Jan 3rd 2021 20:00:00'
Returns object {Object} a well structured json object
publicKeySetString
This function returns a public key string with the header and footer
Parameters
key
string a public key string without the header and footer
Examples
publicKeySetString('MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA') // returns -----BEGIN PUBLIC KEY----- ...
Returns string {string} a public key string with the header and footer
publicKeyGetString
This function returns a public key string without the header and footer
Parameters
key
string a stringified object in string format
Examples
publicKeyGetString('-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA)
Returns string {string} a public key string without the header and footer
bloodGroups
A list of bloodGroups
accountsAsset
A list of accountsAsset
accountsEquity
A list of accountsEquity
accountsPayable
A list of accountsPayable
accountsLiability
A list of accountsLiability
accountsReceivable
A list of accountsReceivable
currencyDenomination
A list of currencyDenomination
estimateTerm
A list of estimateTerm
invoiceTerm
A list of invoiceTerm
itemCategory
A list of itemCategory
employmentStatus
A list of employmentStatus
customerTypes
A list of customerTypes
bankAccountType
A list of bankAccountType
dateFormats
A list of dateFormats
contactType
A list of contactType
expenseStatus
A list of expenseStatus
salaryFrequency
A list of salaryFrequency
leavePolicy
A list of leavePolicy
languages
A list of alphabet
taxTypes
A list of taxTypes
expenseType
A list of expenseType
gender
A list of gender
documentSize
A list of documentSize
deliveryNoteStatus
A list of deliveryNoteStatus
creditNoteStatus
A list of creditNoteStatus
invoiceStatus
A list of invoiceStatus
estimateStatus
A list of estimateStatus
docTypes
A list of docTypes
months
A list of months
monthDays
A list of monthDays
industries
A list of industries
monthNameNumber
A list of monthNameNumber
orderStatus
A list of orderStatus
paymentMethods
A list of paymentMethods
deliveryMethods
A list of deliveryMethods
paymentStatus
A list of paymentStatus
paymentTerms
A list of paymentTerms
productTypes
A list of productTypes
alphabet
A list of alphabet
productUnits
A list of productUnits
quoteStatus
A list of quoteStatus
recurringFrequency
A list of recurringFrequency
salutations
A list of salutations
weekdays
A list of weekdays
timezones
A list of timezones
payoutMethod
A list of payment methods
paymentMethod
A list of payment methods
transactionStatus
A list of transaction status
Country
This method validates email address
Examples
// get country of andorra only
import { country_ad } from '@synotech/utils';
// get all countries
import { countries } from '@synotech/utils';
console.log(countries.find((country) => country.tld === country_ad.tld);
{
name: 'Andorra',
capital: 'Andorra la Vella',
population: '84000',
languages: 'ca',
callingCode: '376',
numeric: '020',
timezone: 'UTC+01:00',
region: 'Europe',
tld: 'ad',
currency: {
name: 'Euro',
symbol: '\u20ac',
symbolNative: '\u20ac',
decimalDigits: 2,
rounding: 0,
isoCode: 'EUR',
namePlural: 'euros',
},
countryName: 'Andorra',
countryShortCode: 'AD',
regions: [
{
name: 'Andorra la Vella',
shortCode: '07',
},
{
name: 'Canillo',
shortCode: '02',
},
{
name: 'Encamp',
shortCode: '03',
},
{
name: 'Escaldes-Engordany',
shortCode: '08',
},
{
name: 'La Massana',
shortCode: '04',
},
{
name: 'Ordino',
shortCode: '05',
},
{
name: 'Sant Juli\u00e0 de L\u00f2ria',
shortCode: '06',
},
],
}
Returns object {Country} a country object