From 9d60e394d5e52167e9197067d3fa7953b30a990b Mon Sep 17 00:00:00 2001 From: Chad Nehemiah Date: Fri, 10 Mar 2023 04:50:46 -0500 Subject: [PATCH] deps(dev): upgrade aegir to `38.1.2` (#302) Co-authored-by: Alex Potsides --- package.json | 10 ++--- src/aes/cipher-mode.ts | 2 +- src/aes/ciphers-browser.ts | 8 +++- src/aes/index.ts | 2 +- src/ciphers/aes-gcm.browser.ts | 6 +-- src/ciphers/aes-gcm.ts | 10 ++--- src/hmac/index-browser.ts | 4 +- src/hmac/index.ts | 7 +++- src/keys/ecdh-browser.ts | 12 +++--- src/keys/ed25519-browser.ts | 11 +++--- src/keys/ed25519-class.ts | 39 ++++++++++---------- src/keys/ed25519.ts | 11 +++--- src/keys/exporter.ts | 3 +- src/keys/importer.ts | 2 +- src/keys/index.ts | 4 +- src/keys/interface.ts | 15 ++++++++ src/keys/jwk2pem.ts | 11 ++++-- src/keys/key-stretcher.ts | 5 ++- src/keys/keys.ts | 2 +- src/keys/rsa-browser.ts | 19 +++++----- src/keys/rsa-class.ts | 41 +++++++++++---------- src/keys/rsa-utils.ts | 4 +- src/keys/rsa.ts | 8 ++-- src/keys/secp256k1-class.ts | 35 +++++++++--------- src/keys/secp256k1.ts | 16 ++++---- src/util.ts | 4 +- test/aes/aes.spec.ts | 2 +- test/crypto.spec.ts | 2 +- test/helpers/test-garbage-error-handling.ts | 2 +- test/keys/ed25519.spec.ts | 4 +- test/keys/rsa.spec.ts | 6 +-- test/keys/secp256k1.spec.ts | 20 +++++----- 32 files changed, 181 insertions(+), 146 deletions(-) diff --git a/package.json b/package.json index d375601b..4ead7c6a 100644 --- a/package.json +++ b/package.json @@ -165,7 +165,7 @@ "scripts": { "clean": "aegir clean", "lint": "aegir lint", - "dep-check": "aegir dep-check", + "dep-check": "aegir dep-check -i protons", "build": "aegir build", "test": "aegir test", "test:chrome": "aegir test -t browser", @@ -186,16 +186,14 @@ "multiformats": "^11.0.0", "node-forge": "^1.1.0", "protons-runtime": "^4.0.1", + "uint8arraylist": "^2.4.3", "uint8arrays": "^4.0.2" }, "devDependencies": { "@types/mocha": "^10.0.0", - "aegir": "^37.0.12", + "aegir": "^38.1.2", "benchmark": "^2.1.4", - "protons": "^6.0.0", - "sinon": "^15.0.0", - "util": "^0.12.3", - "wherearewe": "^2.0.1" + "util": "^0.12.5" }, "browser": { "./dist/src/aes/ciphers.js": "./dist/src/aes/ciphers-browser.js", diff --git a/src/aes/cipher-mode.ts b/src/aes/cipher-mode.ts index 6fb0840a..b420deed 100644 --- a/src/aes/cipher-mode.ts +++ b/src/aes/cipher-mode.ts @@ -5,7 +5,7 @@ const CIPHER_MODES = { 32: 'aes-256-ctr' } -export function cipherMode (key: Uint8Array) { +export function cipherMode (key: Uint8Array): string { if (key.length === 16 || key.length === 32) { return CIPHER_MODES[key.length] } diff --git a/src/aes/ciphers-browser.ts b/src/aes/ciphers-browser.ts index be5a285d..5bd4fcee 100644 --- a/src/aes/ciphers-browser.ts +++ b/src/aes/ciphers-browser.ts @@ -5,7 +5,11 @@ import forge from 'node-forge/lib/forge.js' import { toString as uint8ArrayToString } from 'uint8arrays/to-string' import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string' -export function createCipheriv (mode: any, key: Uint8Array, iv: Uint8Array) { +export interface Cipher { + update: (data: Uint8Array) => Uint8Array +} + +export function createCipheriv (mode: any, key: Uint8Array, iv: Uint8Array): Cipher { const cipher2 = forge.cipher.createCipher('AES-CTR', uint8ArrayToString(key, 'ascii')) cipher2.start({ iv: uint8ArrayToString(iv, 'ascii') }) return { @@ -16,7 +20,7 @@ export function createCipheriv (mode: any, key: Uint8Array, iv: Uint8Array) { } } -export function createDecipheriv (mode: any, key: Uint8Array, iv: Uint8Array) { +export function createDecipheriv (mode: any, key: Uint8Array, iv: Uint8Array): Cipher { const cipher2 = forge.cipher.createDecipher('AES-CTR', uint8ArrayToString(key, 'ascii')) cipher2.start({ iv: uint8ArrayToString(iv, 'ascii') }) return { diff --git a/src/aes/index.ts b/src/aes/index.ts index 79cd969c..ee1334fd 100644 --- a/src/aes/index.ts +++ b/src/aes/index.ts @@ -6,7 +6,7 @@ export interface AESCipher { decrypt: (data: Uint8Array) => Promise } -export async function create (key: Uint8Array, iv: Uint8Array) { // eslint-disable-line require-await +export async function create (key: Uint8Array, iv: Uint8Array): Promise { // eslint-disable-line require-await const mode = cipherMode(key) const cipher = ciphers.createCipheriv(mode, key, iv) const decipher = ciphers.createDecipheriv(mode, key, iv) diff --git a/src/ciphers/aes-gcm.browser.ts b/src/ciphers/aes-gcm.browser.ts index 658fdf16..c90be827 100644 --- a/src/ciphers/aes-gcm.browser.ts +++ b/src/ciphers/aes-gcm.browser.ts @@ -5,7 +5,7 @@ import type { CreateOptions, AESCipher } from './interface.js' // Based off of code from https://github.com/luke-park/SecureCompatibleEncryptionExamples -export function create (opts?: CreateOptions) { +export function create (opts?: CreateOptions): AESCipher { const algorithm = opts?.algorithm ?? 'AES-GCM' let keyLength = opts?.keyLength ?? 16 const nonceLength = opts?.nonceLength ?? 12 @@ -20,7 +20,7 @@ export function create (opts?: CreateOptions) { * Uses the provided password to derive a pbkdf2 key. The key * will then be used to encrypt the data. */ - async function encrypt (data: Uint8Array, password: string | Uint8Array) { // eslint-disable-line require-await + async function encrypt (data: Uint8Array, password: string | Uint8Array): Promise { // eslint-disable-line require-await const salt = crypto.getRandomValues(new Uint8Array(saltLength)) const nonce = crypto.getRandomValues(new Uint8Array(nonceLength)) const aesGcm = { name: algorithm, iv: nonce } @@ -45,7 +45,7 @@ export function create (opts?: CreateOptions) { * this decryption cipher must be the same as those used to create * the encryption cipher. */ - async function decrypt (data: Uint8Array, password: string | Uint8Array) { + async function decrypt (data: Uint8Array, password: string | Uint8Array): Promise { const salt = data.subarray(0, saltLength) const nonce = data.subarray(saltLength, saltLength + nonceLength) const ciphertext = data.subarray(saltLength + nonceLength) diff --git a/src/ciphers/aes-gcm.ts b/src/ciphers/aes-gcm.ts index ea408976..2c988615 100644 --- a/src/ciphers/aes-gcm.ts +++ b/src/ciphers/aes-gcm.ts @@ -5,7 +5,7 @@ import type { CreateOptions, AESCipher } from './interface.js' // Based off of code from https://github.com/luke-park/SecureCompatibleEncryptionExamples -export function create (opts?: CreateOptions) { +export function create (opts?: CreateOptions): AESCipher { const algorithm = opts?.algorithm ?? 'aes-128-gcm' const keyLength = opts?.keyLength ?? 16 const nonceLength = opts?.nonceLength ?? 12 @@ -14,7 +14,7 @@ export function create (opts?: CreateOptions) { const iterations = opts?.iterations ?? 32767 const algorithmTagLength = opts?.algorithmTagLength ?? 16 - async function encryptWithKey (data: Uint8Array, key: Uint8Array) { // eslint-disable-line require-await + async function encryptWithKey (data: Uint8Array, key: Uint8Array): Promise { // eslint-disable-line require-await const nonce = crypto.randomBytes(nonceLength) // Create the cipher instance. @@ -31,7 +31,7 @@ export function create (opts?: CreateOptions) { * Uses the provided password to derive a pbkdf2 key. The key * will then be used to encrypt the data. */ - async function encrypt (data: Uint8Array, password: string | Uint8Array) { // eslint-disable-line require-await + async function encrypt (data: Uint8Array, password: string | Uint8Array): Promise { // eslint-disable-line require-await // Generate a 128-bit salt using a CSPRNG. const salt = crypto.randomBytes(saltLength) @@ -53,7 +53,7 @@ export function create (opts?: CreateOptions) { * this decryption cipher must be the same as those used to create * the encryption cipher. */ - async function decryptWithKey (ciphertextAndNonce: Uint8Array, key: Uint8Array) { // eslint-disable-line require-await + async function decryptWithKey (ciphertextAndNonce: Uint8Array, key: Uint8Array): Promise { // eslint-disable-line require-await // Create Uint8Arrays of nonce, ciphertext and tag. const nonce = ciphertextAndNonce.subarray(0, nonceLength) const ciphertext = ciphertextAndNonce.subarray(nonceLength, ciphertextAndNonce.length - algorithmTagLength) @@ -77,7 +77,7 @@ export function create (opts?: CreateOptions) { * @param {Uint8Array} data - The data to decrypt * @param {string|Uint8Array} password - A plain password */ - async function decrypt (data: Uint8Array, password: string | Uint8Array) { // eslint-disable-line require-await + async function decrypt (data: Uint8Array, password: string | Uint8Array): Promise { // eslint-disable-line require-await // Create Uint8Arrays of salt and ciphertextAndNonce. const salt = data.subarray(0, saltLength) const ciphertextAndNonce = data.subarray(saltLength) diff --git a/src/hmac/index-browser.ts b/src/hmac/index-browser.ts index e80b8341..734cf2f8 100644 --- a/src/hmac/index-browser.ts +++ b/src/hmac/index-browser.ts @@ -7,12 +7,12 @@ const hashTypes = { SHA512: 'SHA-512' } -const sign = async (key: CryptoKey, data: Uint8Array) => { +const sign = async (key: CryptoKey, data: Uint8Array): Promise => { const buf = await webcrypto.get().subtle.sign({ name: 'HMAC' }, key, data) return new Uint8Array(buf, 0, buf.byteLength) } -export async function create (hashType: 'SHA1' | 'SHA256' | 'SHA512', secret: Uint8Array) { +export async function create (hashType: 'SHA1' | 'SHA256' | 'SHA512', secret: Uint8Array): Promise<{ digest: (data: Uint8Array) => Promise, length: number }> { const hash = hashTypes[hashType] const key = await webcrypto.get().subtle.importKey( diff --git a/src/hmac/index.ts b/src/hmac/index.ts index ab70f643..a0a802f1 100644 --- a/src/hmac/index.ts +++ b/src/hmac/index.ts @@ -1,7 +1,12 @@ import crypto from 'crypto' import lengths from './lengths.js' -export async function create (hash: 'SHA1' | 'SHA256' | 'SHA512', secret: Uint8Array) { // eslint-disable-line require-await +export interface HMAC { + digest: (data: Uint8Array) => Promise + length: number +} + +export async function create (hash: 'SHA1' | 'SHA256' | 'SHA512', secret: Uint8Array): Promise { const res = { async digest (data: Uint8Array) { // eslint-disable-line require-await const hmac = crypto.createHmac(hash.toLowerCase(), secret) diff --git a/src/keys/ecdh-browser.ts b/src/keys/ecdh-browser.ts index bb0f5367..95a61dfc 100644 --- a/src/keys/ecdh-browser.ts +++ b/src/keys/ecdh-browser.ts @@ -4,7 +4,7 @@ import { base64urlToBuffer } from '../util.js' import { toString as uint8ArrayToString } from 'uint8arrays/to-string' import { concat as uint8ArrayConcat } from 'uint8arrays/concat' import { equals as uint8ArrayEquals } from 'uint8arrays/equals' -import type { ECDHKey, ECDHKeyPair } from './interface.js' +import type { ECDHKey, ECDHKeyPair, JWKEncodedPrivateKey, JWKEncodedPublicKey } from './interface.js' const bits = { 'P-256': 256, @@ -15,7 +15,7 @@ const bits = { const curveTypes = Object.keys(bits) const names = curveTypes.join(' / ') -export async function generateEphmeralKeyPair (curve: string) { +export async function generateEphmeralKeyPair (curve: string): Promise { if (curve !== 'P-256' && curve !== 'P-384' && curve !== 'P-521') { throw new CodeError(`Unknown curve: ${curve}. Must be ${names}`, 'ERR_INVALID_CURVE') } @@ -30,7 +30,7 @@ export async function generateEphmeralKeyPair (curve: string) { ) // forcePrivate is used for testing only - const genSharedKey = async (theirPub: Uint8Array, forcePrivate?: ECDHKeyPair) => { + const genSharedKey = async (theirPub: Uint8Array, forcePrivate?: ECDHKeyPair): Promise => { let privateKey if (forcePrivate != null) { @@ -92,7 +92,7 @@ const curveLengths = { // Marshal converts a jwk encoded ECDH public key into the // form specified in section 4.3.6 of ANSI X9.62. (This is the format // go-ipfs uses) -function marshalPublicKey (jwk: JsonWebKey) { +function marshalPublicKey (jwk: JsonWebKey): Uint8Array { if (jwk.crv == null || jwk.x == null || jwk.y == null) { throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS') } @@ -111,7 +111,7 @@ function marshalPublicKey (jwk: JsonWebKey) { } // Unmarshal converts a point, serialized by Marshal, into an jwk encoded key -function unmarshalPublicKey (curve: string, key: Uint8Array) { +function unmarshalPublicKey (curve: string, key: Uint8Array): JWKEncodedPublicKey { if (curve !== 'P-256' && curve !== 'P-384' && curve !== 'P-521') { throw new CodeError(`Unknown curve: ${curve}. Must be ${names}`, 'ERR_INVALID_CURVE') } @@ -131,7 +131,7 @@ function unmarshalPublicKey (curve: string, key: Uint8Array) { } } -const unmarshalPrivateKey = (curve: string, key: ECDHKeyPair) => ({ +const unmarshalPrivateKey = (curve: string, key: ECDHKeyPair): JWKEncodedPrivateKey => ({ ...unmarshalPublicKey(curve, key.public), d: uint8ArrayToString(key.private, 'base64url') }) diff --git a/src/keys/ed25519-browser.ts b/src/keys/ed25519-browser.ts index 533421fd..01159c95 100644 --- a/src/keys/ed25519-browser.ts +++ b/src/keys/ed25519-browser.ts @@ -1,4 +1,5 @@ import * as ed from '@noble/ed25519' +import type { Uint8ArrayKeyPair } from './interface' const PUBLIC_KEY_BYTE_LENGTH = 32 const PRIVATE_KEY_BYTE_LENGTH = 64 // private key is actually 32 bytes but for historical reasons we concat private and public keys @@ -7,7 +8,7 @@ const KEYS_BYTE_LENGTH = 32 export { PUBLIC_KEY_BYTE_LENGTH as publicKeyLength } export { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength } -export async function generateKey () { +export async function generateKey (): Promise { // the actual private key (32 bytes) const privateKeyRaw = ed.utils.randomPrivateKey() const publicKey = await ed.getPublicKey(privateKeyRaw) @@ -24,7 +25,7 @@ export async function generateKey () { /** * Generate keypair from a 32 byte uint8array */ -export async function generateKeyFromSeed (seed: Uint8Array) { +export async function generateKeyFromSeed (seed: Uint8Array): Promise { if (seed.length !== KEYS_BYTE_LENGTH) { throw new TypeError('"seed" must be 32 bytes in length.') } else if (!(seed instanceof Uint8Array)) { @@ -43,17 +44,17 @@ export async function generateKeyFromSeed (seed: Uint8Array) { } } -export async function hashAndSign (privateKey: Uint8Array, msg: Uint8Array) { +export async function hashAndSign (privateKey: Uint8Array, msg: Uint8Array): Promise { const privateKeyRaw = privateKey.subarray(0, KEYS_BYTE_LENGTH) return await ed.sign(msg, privateKeyRaw) } -export async function hashAndVerify (publicKey: Uint8Array, sig: Uint8Array, msg: Uint8Array) { +export async function hashAndVerify (publicKey: Uint8Array, sig: Uint8Array, msg: Uint8Array): Promise { return await ed.verify(sig, msg, publicKey) } -function concatKeys (privateKeyRaw: Uint8Array, publicKey: Uint8Array) { +function concatKeys (privateKeyRaw: Uint8Array, publicKey: Uint8Array): Uint8Array { const privateKey = new Uint8Array(PRIVATE_KEY_BYTE_LENGTH) for (let i = 0; i < KEYS_BYTE_LENGTH; i++) { privateKey[i] = privateKeyRaw[i] diff --git a/src/keys/ed25519-class.ts b/src/keys/ed25519-class.ts index 469d18b7..7d0f9255 100644 --- a/src/keys/ed25519-class.ts +++ b/src/keys/ed25519-class.ts @@ -6,6 +6,7 @@ import { identity } from 'multiformats/hashes/identity' import * as crypto from './ed25519.js' import * as pbm from './keys.js' import { exporter } from './exporter.js' +import type { Multibase } from 'multiformats' export class Ed25519PublicKey { private readonly _key: Uint8Array @@ -14,26 +15,26 @@ export class Ed25519PublicKey { this._key = ensureKey(key, crypto.publicKeyLength) } - async verify (data: Uint8Array, sig: Uint8Array) { // eslint-disable-line require-await + async verify (data: Uint8Array, sig: Uint8Array): Promise { // eslint-disable-line require-await return await crypto.hashAndVerify(this._key, sig, data) } - marshal () { + marshal (): Uint8Array { return this._key } - get bytes () { + get bytes (): Uint8Array { return pbm.PublicKey.encode({ Type: pbm.KeyType.Ed25519, Data: this.marshal() }).subarray() } - equals (key: any) { + equals (key: any): boolean { return uint8ArrayEquals(this.bytes, key.bytes) } - async hash () { + async hash (): Promise { const { bytes } = await sha256.digest(this.bytes) return bytes @@ -51,30 +52,30 @@ export class Ed25519PrivateKey { this._publicKey = ensureKey(publicKey, crypto.publicKeyLength) } - async sign (message: Uint8Array) { // eslint-disable-line require-await + async sign (message: Uint8Array): Promise { // eslint-disable-line require-await return await crypto.hashAndSign(this._key, message) } - get public () { + get public (): Ed25519PublicKey { return new Ed25519PublicKey(this._publicKey) } - marshal () { + marshal (): Uint8Array { return this._key } - get bytes () { + get bytes (): Uint8Array { return pbm.PrivateKey.encode({ Type: pbm.KeyType.Ed25519, Data: this.marshal() }).subarray() } - equals (key: any) { + equals (key: any): boolean { return uint8ArrayEquals(this.bytes, key.bytes) } - async hash () { + async hash (): Promise { const { bytes } = await sha256.digest(this.bytes) return bytes @@ -89,15 +90,15 @@ export class Ed25519PrivateKey { * * @returns {Promise} */ - async id () { - const encoding = await identity.digest(this.public.bytes) + async id (): Promise { + const encoding = identity.digest(this.public.bytes) return base58btc.encode(encoding.bytes).substring(1) } /** * Exports the key into a password protected `format` */ - async export (password: string, format = 'libp2p-key') { // eslint-disable-line require-await + async export (password: string, format = 'libp2p-key'): Promise> { if (format === 'libp2p-key') { return await exporter(this.bytes, password) } else { @@ -106,7 +107,7 @@ export class Ed25519PrivateKey { } } -export function unmarshalEd25519PrivateKey (bytes: Uint8Array) { +export function unmarshalEd25519PrivateKey (bytes: Uint8Array): Ed25519PrivateKey { // Try the old, redundant public key version if (bytes.length > crypto.privateKeyLength) { bytes = ensureKey(bytes, crypto.privateKeyLength + crypto.publicKeyLength) @@ -121,22 +122,22 @@ export function unmarshalEd25519PrivateKey (bytes: Uint8Array) { return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes) } -export function unmarshalEd25519PublicKey (bytes: Uint8Array) { +export function unmarshalEd25519PublicKey (bytes: Uint8Array): Ed25519PublicKey { bytes = ensureKey(bytes, crypto.publicKeyLength) return new Ed25519PublicKey(bytes) } -export async function generateKeyPair () { +export async function generateKeyPair (): Promise { const { privateKey, publicKey } = await crypto.generateKey() return new Ed25519PrivateKey(privateKey, publicKey) } -export async function generateKeyPairFromSeed (seed: Uint8Array) { +export async function generateKeyPairFromSeed (seed: Uint8Array): Promise { const { privateKey, publicKey } = await crypto.generateKeyFromSeed(seed) return new Ed25519PrivateKey(privateKey, publicKey) } -function ensureKey (key: Uint8Array, length: number) { +function ensureKey (key: Uint8Array, length: number): Uint8Array { key = Uint8Array.from(key ?? []) if (key.length !== length) { throw new CodeError(`Key must be a Uint8Array of length ${length}, got ${key.length}`, 'ERR_INVALID_KEY_TYPE') diff --git a/src/keys/ed25519.ts b/src/keys/ed25519.ts index f643e3d7..cce5c59c 100644 --- a/src/keys/ed25519.ts +++ b/src/keys/ed25519.ts @@ -2,6 +2,7 @@ import crypto from 'crypto' import { promisify } from 'util' import { toString as uint8arrayToString } from 'uint8arrays/to-string' import { fromString as uint8arrayFromString } from 'uint8arrays/from-string' +import type { Uint8ArrayKeyPair } from './interface.js' const keypair = promisify(crypto.generateKeyPair) @@ -34,7 +35,7 @@ function derivePublicKey (privateKey: Uint8Array): Uint8Array { return uint8arrayFromString(jwk.x, 'base64url') } -export async function generateKey () { +export async function generateKey (): Promise { const key = await keypair('ed25519', { publicKeyEncoding: { type: 'spki', format: 'jwk' }, privateKeyEncoding: { type: 'pkcs8', format: 'jwk' } @@ -54,7 +55,7 @@ export async function generateKey () { /** * Generate keypair from a 32 byte uint8array */ -export async function generateKeyFromSeed (seed: Uint8Array) { +export async function generateKeyFromSeed (seed: Uint8Array): Promise { if (seed.length !== KEYS_BYTE_LENGTH) { throw new TypeError('"seed" must be 32 bytes in length.') } else if (!(seed instanceof Uint8Array)) { @@ -70,7 +71,7 @@ export async function generateKeyFromSeed (seed: Uint8Array) { } } -export async function hashAndSign (key: Uint8Array, msg: Uint8Array) { +export async function hashAndSign (key: Uint8Array, msg: Uint8Array): Promise { if (!(key instanceof Uint8Array)) { throw new TypeError('"key" must be a node.js Buffer, or Uint8Array.') } @@ -101,7 +102,7 @@ export async function hashAndSign (key: Uint8Array, msg: Uint8Array) { return crypto.sign(null, msg, obj) } -export async function hashAndVerify (key: Uint8Array, sig: Uint8Array, msg: Uint8Array) { +export async function hashAndVerify (key: Uint8Array, sig: Uint8Array, msg: Uint8Array): Promise { if (key.byteLength !== PUBLIC_KEY_BYTE_LENGTH) { throw new TypeError('"key" must be 32 bytes in length.') } else if (!(key instanceof Uint8Array)) { @@ -126,7 +127,7 @@ export async function hashAndVerify (key: Uint8Array, sig: Uint8Array, msg: Uint return crypto.verify(null, msg, obj, sig) } -function concatKeys (privateKeyRaw: Uint8Array, publicKey: Uint8Array) { +function concatKeys (privateKeyRaw: Uint8Array, publicKey: Uint8Array): Uint8Array { const privateKey = new Uint8Array(PRIVATE_KEY_BYTE_LENGTH) for (let i = 0; i < KEYS_BYTE_LENGTH; i++) { privateKey[i] = privateKeyRaw[i] diff --git a/src/keys/exporter.ts b/src/keys/exporter.ts index 221fd50f..6b5e22fa 100644 --- a/src/keys/exporter.ts +++ b/src/keys/exporter.ts @@ -1,3 +1,4 @@ +import type { Multibase } from 'multiformats' import { base64 } from 'multiformats/bases/base64' import * as ciphers from '../ciphers/aes-gcm.js' @@ -6,7 +7,7 @@ import * as ciphers from '../ciphers/aes-gcm.js' * The PrivateKey is encrypted via a password derived PBKDF2 key * leveraging the aes-gcm cipher algorithm. */ -export async function exporter (privateKey: Uint8Array, password: string) { +export async function exporter (privateKey: Uint8Array, password: string): Promise> { const cipher = ciphers.create() const encryptedKey = await cipher.encrypt(privateKey, password) return base64.encode(encryptedKey) diff --git a/src/keys/importer.ts b/src/keys/importer.ts index e47a5b4b..0c27e9a3 100644 --- a/src/keys/importer.ts +++ b/src/keys/importer.ts @@ -6,7 +6,7 @@ import * as ciphers from '../ciphers/aes-gcm.js' * with the given password. The privateKey must have been exported * using the same password and underlying cipher (aes-gcm) */ -export async function importer (privateKey: string, password: string) { +export async function importer (privateKey: string, password: string): Promise { const encryptedKey = base64.decode(privateKey) const cipher = ciphers.create() return await cipher.decrypt(encryptedKey, password) diff --git a/src/keys/index.ts b/src/keys/index.ts index 85276fb8..6c55e0c6 100644 --- a/src/keys/index.ts +++ b/src/keys/index.ts @@ -25,12 +25,12 @@ export const supportedKeys = { secp256k1: Secp256k1 } -function unsupportedKey (type: string) { +function unsupportedKey (type: string): CodeError> { const supported = Object.keys(supportedKeys).join(' / ') return new CodeError(`invalid or unsupported key type ${type}. Must be ${supported}`, 'ERR_UNSUPPORTED_KEY_TYPE') } -function typeToKey (type: string) { +function typeToKey (type: string): typeof RSA | typeof Ed25519 | typeof Secp256k1 { type = type.toLowerCase() if (type === 'rsa' || type === 'ed25519' || type === 'secp256k1') { diff --git a/src/keys/interface.ts b/src/keys/interface.ts index 282d5dfe..30bceb1d 100644 --- a/src/keys/interface.ts +++ b/src/keys/interface.ts @@ -18,3 +18,18 @@ export interface ECDHKey { key: Uint8Array genSharedKey: (theirPub: Uint8Array, forcePrivate?: ECDHKeyPair) => Promise } + +export interface JWKEncodedPublicKey { kty: string, crv: 'P-256' | 'P-384' | 'P-521', x: string, y: string, ext: boolean } + +export interface JWKEncodedPrivateKey extends JWKEncodedPublicKey { d: string} + +export interface EnhancedKey { + iv: Uint8Array + cipherKey: Uint8Array + macKey: Uint8Array +} + +export interface EnhancedKeyPair { + k1: EnhancedKey + k2: EnhancedKey +} diff --git a/src/keys/jwk2pem.ts b/src/keys/jwk2pem.ts index 27a80e68..64feebc1 100644 --- a/src/keys/jwk2pem.ts +++ b/src/keys/jwk2pem.ts @@ -3,14 +3,19 @@ import 'node-forge/lib/rsa.js' import forge from 'node-forge/lib/forge.js' import { base64urlToBigInteger } from '../util.js' -function convert (key: any, types: string[]) { +export interface JWK { + encrypt: (msg: string) => string + decrypt: (msg: string) => string +} + +function convert (key: any, types: string[]): Array { return types.map(t => base64urlToBigInteger(key[t])) } -export function jwk2priv (key: JsonWebKey) { +export function jwk2priv (key: JsonWebKey): JWK { return forge.pki.setRsaPrivateKey(...convert(key, ['n', 'e', 'd', 'p', 'q', 'dp', 'dq', 'qi'])) } -export function jwk2pub (key: JsonWebKey) { +export function jwk2pub (key: JsonWebKey): JWK { return forge.pki.setRsaPublicKey(...convert(key, ['n', 'e'])) } diff --git a/src/keys/key-stretcher.ts b/src/keys/key-stretcher.ts index 061fd37d..c1feefcf 100644 --- a/src/keys/key-stretcher.ts +++ b/src/keys/key-stretcher.ts @@ -2,6 +2,7 @@ import { CodeError } from '@libp2p/interfaces/errors' import { concat as uint8ArrayConcat } from 'uint8arrays/concat' import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string' import * as hmac from '../hmac/index.js' +import type { EnhancedKey, EnhancedKeyPair } from './interface.js' const cipherMap = { 'AES-128': { @@ -22,7 +23,7 @@ const cipherMap = { * Generates a set of keys for each party by stretching the shared key. * (myIV, theirIV, myCipherKey, theirCipherKey, myMACKey, theirMACKey) */ -export async function keyStretcher (cipherType: 'AES-128' | 'AES-256' | 'Blowfish', hash: 'SHA1' | 'SHA256' | 'SHA512', secret: Uint8Array) { +export async function keyStretcher (cipherType: 'AES-128' | 'AES-256' | 'Blowfish', hash: 'SHA1' | 'SHA256' | 'SHA512', secret: Uint8Array): Promise { const cipher = cipherMap[cipherType] if (cipher == null) { @@ -64,7 +65,7 @@ export async function keyStretcher (cipherType: 'AES-128' | 'AES-256' | 'Blowfis const r1 = resultBuffer.subarray(0, half) const r2 = resultBuffer.subarray(half, resultLength) - const createKey = (res: Uint8Array) => ({ + const createKey = (res: Uint8Array): EnhancedKey => ({ iv: res.subarray(0, ivSize), cipherKey: res.subarray(ivSize, ivSize + cipherKeySize), macKey: res.subarray(ivSize + cipherKeySize) diff --git a/src/keys/keys.ts b/src/keys/keys.ts index f6a1d67b..cea144dc 100644 --- a/src/keys/keys.ts +++ b/src/keys/keys.ts @@ -20,7 +20,7 @@ enum __KeyTypeValues { } export namespace KeyType { - export const codec = () => { + export const codec = (): Codec => { return enumeration(__KeyTypeValues) } } diff --git a/src/keys/rsa-browser.ts b/src/keys/rsa-browser.ts index 273e46d1..fc97eeef 100644 --- a/src/keys/rsa-browser.ts +++ b/src/keys/rsa-browser.ts @@ -5,10 +5,11 @@ import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string' import * as utils from './rsa-utils.js' import { jwk2pub, jwk2priv } from './jwk2pem.js' import { CodeError } from '@libp2p/interfaces/errors' +import type { JWKKeyPair } from './interface.js' export { utils } -export async function generateKey (bits: number) { +export async function generateKey (bits: number): Promise { const pair = await webcrypto.get().subtle.generateKey( { name: 'RSASSA-PKCS1-v1_5', @@ -29,7 +30,7 @@ export async function generateKey (bits: number) { } // Takes a jwk key -export async function unmarshalPrivateKey (key: JsonWebKey) { +export async function unmarshalPrivateKey (key: JsonWebKey): Promise { const privateKey = await webcrypto.get().subtle.importKey( 'jwk', key, @@ -59,7 +60,7 @@ export async function unmarshalPrivateKey (key: JsonWebKey) { export { randomBytes as getRandomValues } -export async function hashAndSign (key: JsonWebKey, msg: Uint8Array) { +export async function hashAndSign (key: JsonWebKey, msg: Uint8Array): Promise { const privateKey = await webcrypto.get().subtle.importKey( 'jwk', key, @@ -80,7 +81,7 @@ export async function hashAndSign (key: JsonWebKey, msg: Uint8Array) { return new Uint8Array(sig, 0, sig.byteLength) } -export async function hashAndVerify (key: JsonWebKey, sig: Uint8Array, msg: Uint8Array) { +export async function hashAndVerify (key: JsonWebKey, sig: Uint8Array, msg: Uint8Array): Promise { const publicKey = await webcrypto.get().subtle.importKey( 'jwk', key, @@ -100,7 +101,7 @@ export async function hashAndVerify (key: JsonWebKey, sig: Uint8Array, msg: Uint ) } -async function exportKey (pair: CryptoKeyPair) { +async function exportKey (pair: CryptoKeyPair): Promise<[JsonWebKey, JsonWebKey]> { if (pair.privateKey == null || pair.publicKey == null) { throw new CodeError('Private and public key are required', 'ERR_INVALID_PARAMETERS') } @@ -111,7 +112,7 @@ async function exportKey (pair: CryptoKeyPair) { ]) } -async function derivePublicFromPrivate (jwKey: JsonWebKey) { +async function derivePublicFromPrivate (jwKey: JsonWebKey): Promise { return await webcrypto.get().subtle.importKey( 'jwk', { @@ -140,17 +141,17 @@ Explanation: */ -function convertKey (key: JsonWebKey, pub: boolean, msg: Uint8Array, handle: (msg: string, key: { encrypt: (msg: string) => string, decrypt: (msg: string) => string}) => string) { +function convertKey (key: JsonWebKey, pub: boolean, msg: Uint8Array, handle: (msg: string, key: { encrypt: (msg: string) => string, decrypt: (msg: string) => string }) => string): Uint8Array { const fkey = pub ? jwk2pub(key) : jwk2priv(key) const fmsg = uint8ArrayToString(Uint8Array.from(msg), 'ascii') const fomsg = handle(fmsg, fkey) return uint8ArrayFromString(fomsg, 'ascii') } -export function encrypt (key: JsonWebKey, msg: Uint8Array) { +export function encrypt (key: JsonWebKey, msg: Uint8Array): Uint8Array { return convertKey(key, true, msg, (msg, key) => key.encrypt(msg)) } -export function decrypt (key: JsonWebKey, msg: Uint8Array) { +export function decrypt (key: JsonWebKey, msg: Uint8Array): Uint8Array { return convertKey(key, false, msg, (msg, key) => key.decrypt(msg)) } diff --git a/src/keys/rsa-class.ts b/src/keys/rsa-class.ts index a69019cb..ceeade6a 100644 --- a/src/keys/rsa-class.ts +++ b/src/keys/rsa-class.ts @@ -9,6 +9,7 @@ import forge from 'node-forge/lib/forge.js' import * as crypto from './rsa.js' import * as pbm from './keys.js' import { exporter } from './exporter.js' +import type { Multibase } from 'multiformats' export class RsaPublicKey { private readonly _key: JsonWebKey @@ -17,30 +18,30 @@ export class RsaPublicKey { this._key = key } - async verify (data: Uint8Array, sig: Uint8Array) { // eslint-disable-line require-await + async verify (data: Uint8Array, sig: Uint8Array): Promise { // eslint-disable-line require-await return await crypto.hashAndVerify(this._key, sig, data) } - marshal () { + marshal (): Uint8Array { return crypto.utils.jwkToPkix(this._key) } - get bytes () { + get bytes (): Uint8Array { return pbm.PublicKey.encode({ Type: pbm.KeyType.RSA, Data: this.marshal() }).subarray() } - encrypt (bytes: Uint8Array) { + encrypt (bytes: Uint8Array): Uint8Array { return crypto.encrypt(this._key, bytes) } - equals (key: any) { + equals (key: any): boolean { return uint8ArrayEquals(this.bytes, key.bytes) } - async hash () { + async hash (): Promise { const { bytes } = await sha256.digest(this.bytes) return bytes @@ -56,15 +57,15 @@ export class RsaPrivateKey { this._publicKey = publicKey } - genSecret () { + genSecret (): Uint8Array { return crypto.getRandomValues(16) } - async sign (message: Uint8Array) { // eslint-disable-line require-await + async sign (message: Uint8Array): Promise { // eslint-disable-line require-await return await crypto.hashAndSign(this._key, message) } - get public () { + get public (): RsaPublicKey { if (this._publicKey == null) { throw new CodeError('public key not provided', 'ERR_PUBKEY_NOT_PROVIDED') } @@ -72,26 +73,26 @@ export class RsaPrivateKey { return new RsaPublicKey(this._publicKey) } - decrypt (bytes: Uint8Array) { + decrypt (bytes: Uint8Array): Uint8Array { return crypto.decrypt(this._key, bytes) } - marshal () { + marshal (): Uint8Array { return crypto.utils.jwkToPkcs1(this._key) } - get bytes () { + get bytes (): Uint8Array { return pbm.PrivateKey.encode({ Type: pbm.KeyType.RSA, Data: this.marshal() }).subarray() } - equals (key: any) { + equals (key: any): boolean { return uint8ArrayEquals(this.bytes, key.bytes) } - async hash () { + async hash (): Promise { const { bytes } = await sha256.digest(this.bytes) return bytes @@ -104,7 +105,7 @@ export class RsaPrivateKey { * The public key is a protobuf encoding containing a type and the DER encoding * of the PKCS SubjectPublicKeyInfo. */ - async id () { + async id (): Promise { const hash = await this.public.hash() return uint8ArrayToString(hash, 'base58btc') } @@ -112,7 +113,7 @@ export class RsaPrivateKey { /** * Exports the key into a password protected PEM format */ - async export (password: string, format = 'pkcs-8') { // eslint-disable-line require-await + async export (password: string, format = 'pkcs-8'): Promise> { // eslint-disable-line require-await if (format === 'pkcs-8') { const buffer = new forge.util.ByteBuffer(this.marshal()) const asn1 = forge.asn1.fromDer(buffer) @@ -133,23 +134,23 @@ export class RsaPrivateKey { } } -export async function unmarshalRsaPrivateKey (bytes: Uint8Array) { +export async function unmarshalRsaPrivateKey (bytes: Uint8Array): Promise { const jwk = crypto.utils.pkcs1ToJwk(bytes) const keys = await crypto.unmarshalPrivateKey(jwk) return new RsaPrivateKey(keys.privateKey, keys.publicKey) } -export function unmarshalRsaPublicKey (bytes: Uint8Array) { +export function unmarshalRsaPublicKey (bytes: Uint8Array): RsaPublicKey { const jwk = crypto.utils.pkixToJwk(bytes) return new RsaPublicKey(jwk) } -export async function fromJwk (jwk: JsonWebKey) { +export async function fromJwk (jwk: JsonWebKey): Promise { const keys = await crypto.unmarshalPrivateKey(jwk) return new RsaPrivateKey(keys.privateKey, keys.publicKey) } -export async function generateKeyPair (bits: number) { +export async function generateKeyPair (bits: number): Promise { const keys = await crypto.generateKey(bits) return new RsaPrivateKey(keys.privateKey, keys.publicKey) } diff --git a/src/keys/rsa-utils.ts b/src/keys/rsa-utils.ts index a6bc9bf3..a094651f 100644 --- a/src/keys/rsa-utils.ts +++ b/src/keys/rsa-utils.ts @@ -28,7 +28,7 @@ export function pkcs1ToJwk (bytes: Uint8Array): JsonWebKey { } // Convert a JWK key into PKCS#1 in ASN1 DER format -export function jwkToPkcs1 (jwk: JsonWebKey) { +export function jwkToPkcs1 (jwk: JsonWebKey): Uint8Array { if (jwk.n == null || jwk.e == null || jwk.d == null || jwk.p == null || jwk.q == null || jwk.dp == null || jwk.dq == null || jwk.qi == null) { throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS') } @@ -60,7 +60,7 @@ export function pkixToJwk (bytes: Uint8Array): JsonWebKey { } // Convert a JWK key to PKCIX in ASN1 DER format -export function jwkToPkix (jwk: JsonWebKey) { +export function jwkToPkix (jwk: JsonWebKey): Uint8Array { if (jwk.n == null || jwk.e == null) { throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS') } diff --git a/src/keys/rsa.ts b/src/keys/rsa.ts index d47b4c30..619874bc 100644 --- a/src/keys/rsa.ts +++ b/src/keys/rsa.ts @@ -42,14 +42,14 @@ export async function unmarshalPrivateKey (key: JsonWebKey): Promise export { randomBytes as getRandomValues } -export async function hashAndSign (key: JsonWebKey, msg: Uint8Array) { // eslint-disable-line require-await +export async function hashAndSign (key: JsonWebKey, msg: Uint8Array): Promise { return crypto.createSign('RSA-SHA256') .update(msg) // @ts-expect-error node types are missing jwk as a format .sign({ format: 'jwk', key }) } -export async function hashAndVerify (key: JsonWebKey, sig: Uint8Array, msg: Uint8Array) { // eslint-disable-line require-await +export async function hashAndVerify (key: JsonWebKey, sig: Uint8Array, msg: Uint8Array): Promise { // eslint-disable-line require-await return crypto.createVerify('RSA-SHA256') .update(msg) // @ts-expect-error node types are missing jwk as a format @@ -58,12 +58,12 @@ export async function hashAndVerify (key: JsonWebKey, sig: Uint8Array, msg: Uint const padding = crypto.constants.RSA_PKCS1_PADDING -export function encrypt (key: JsonWebKey, bytes: Uint8Array) { +export function encrypt (key: JsonWebKey, bytes: Uint8Array): Uint8Array { // @ts-expect-error node types are missing jwk as a format return crypto.publicEncrypt({ format: 'jwk', key, padding }, bytes) } -export function decrypt (key: JsonWebKey, bytes: Uint8Array) { +export function decrypt (key: JsonWebKey, bytes: Uint8Array): Uint8Array { // @ts-expect-error node types are missing jwk as a format return crypto.privateDecrypt({ format: 'jwk', key, padding }, bytes) } diff --git a/src/keys/secp256k1-class.ts b/src/keys/secp256k1-class.ts index 4e38f23a..c48dd67f 100644 --- a/src/keys/secp256k1-class.ts +++ b/src/keys/secp256k1-class.ts @@ -5,6 +5,7 @@ import { toString as uint8ArrayToString } from 'uint8arrays/to-string' import * as crypto from './secp256k1.js' import { exporter } from './exporter.js' import * as keysProtobuf from './keys.js' +import type { Multibase } from 'multiformats' export class Secp256k1PublicKey { private readonly _key: Uint8Array @@ -14,26 +15,26 @@ export class Secp256k1PublicKey { this._key = key } - async verify (data: Uint8Array, sig: Uint8Array) { + async verify (data: Uint8Array, sig: Uint8Array): Promise { return await crypto.hashAndVerify(this._key, sig, data) } - marshal () { + marshal (): Uint8Array { return crypto.compressPublicKey(this._key) } - get bytes () { + get bytes (): Uint8Array { return keysProtobuf.PublicKey.encode({ Type: keysProtobuf.KeyType.Secp256k1, Data: this.marshal() }).subarray() } - equals (key: any) { + equals (key: any): boolean { return uint8ArrayEquals(this.bytes, key.bytes) } - async hash () { + async hash (): Promise { const { bytes } = await sha256.digest(this.bytes) return bytes @@ -51,30 +52,30 @@ export class Secp256k1PrivateKey { crypto.validatePublicKey(this._publicKey) } - async sign (message: Uint8Array) { + async sign (message: Uint8Array): Promise { return await crypto.hashAndSign(this._key, message) } - get public () { + get public (): Secp256k1PublicKey { return new Secp256k1PublicKey(this._publicKey) } - marshal () { + marshal (): Uint8Array { return this._key } - get bytes () { + get bytes (): Uint8Array { return keysProtobuf.PrivateKey.encode({ Type: keysProtobuf.KeyType.Secp256k1, Data: this.marshal() }).subarray() } - equals (key: any) { + equals (key: any): boolean { return uint8ArrayEquals(this.bytes, key.bytes) } - async hash () { + async hash (): Promise { const { bytes } = await sha256.digest(this.bytes) return bytes @@ -87,7 +88,7 @@ export class Secp256k1PrivateKey { * The public key is a protobuf encoding containing a type and the DER encoding * of the PKCS SubjectPublicKeyInfo. */ - async id () { + async id (): Promise { const hash = await this.public.hash() return uint8ArrayToString(hash, 'base58btc') } @@ -95,7 +96,7 @@ export class Secp256k1PrivateKey { /** * Exports the key into a password protected `format` */ - async export (password: string, format = 'libp2p-key') { // eslint-disable-line require-await + async export (password: string, format = 'libp2p-key'): Promise> { if (format === 'libp2p-key') { return await exporter(this.bytes, password) } else { @@ -104,15 +105,15 @@ export class Secp256k1PrivateKey { } } -export function unmarshalSecp256k1PrivateKey (bytes: Uint8Array) { +export function unmarshalSecp256k1PrivateKey (bytes: Uint8Array): Secp256k1PrivateKey { return new Secp256k1PrivateKey(bytes) } -export function unmarshalSecp256k1PublicKey (bytes: Uint8Array) { +export function unmarshalSecp256k1PublicKey (bytes: Uint8Array): Secp256k1PublicKey { return new Secp256k1PublicKey(bytes) } -export async function generateKeyPair () { - const privateKeyBytes = await crypto.generateKey() +export async function generateKeyPair (): Promise { + const privateKeyBytes = crypto.generateKey() return new Secp256k1PrivateKey(privateKeyBytes) } diff --git a/src/keys/secp256k1.ts b/src/keys/secp256k1.ts index 23bc1ab4..a41207a8 100644 --- a/src/keys/secp256k1.ts +++ b/src/keys/secp256k1.ts @@ -6,14 +6,14 @@ const PRIVATE_KEY_BYTE_LENGTH = 32 export { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength } -export function generateKey () { +export function generateKey (): Uint8Array { return secp.utils.randomPrivateKey() } /** * Hash and sign message with private key */ -export async function hashAndSign (key: Uint8Array, msg: Uint8Array) { +export async function hashAndSign (key: Uint8Array, msg: Uint8Array): Promise { const { digest } = await sha256.digest(msg) try { return await secp.sign(digest, key) @@ -25,7 +25,7 @@ export async function hashAndSign (key: Uint8Array, msg: Uint8Array) { /** * Hash message and verify signature with public key */ -export async function hashAndVerify (key: Uint8Array, sig: Uint8Array, msg: Uint8Array) { +export async function hashAndVerify (key: Uint8Array, sig: Uint8Array, msg: Uint8Array): Promise { try { const { digest } = await sha256.digest(msg) return secp.verify(sig, digest, key) @@ -34,17 +34,17 @@ export async function hashAndVerify (key: Uint8Array, sig: Uint8Array, msg: Uint } } -export function compressPublicKey (key: Uint8Array) { +export function compressPublicKey (key: Uint8Array): Uint8Array { const point = secp.Point.fromHex(key).toRawBytes(true) return point } -export function decompressPublicKey (key: Uint8Array) { +export function decompressPublicKey (key: Uint8Array): Uint8Array { const point = secp.Point.fromHex(key).toRawBytes(false) return point } -export function validatePrivateKey (key: Uint8Array) { +export function validatePrivateKey (key: Uint8Array): void { try { secp.getPublicKey(key, true) } catch (err) { @@ -52,7 +52,7 @@ export function validatePrivateKey (key: Uint8Array) { } } -export function validatePublicKey (key: Uint8Array) { +export function validatePublicKey (key: Uint8Array): void { try { secp.Point.fromHex(key) } catch (err) { @@ -60,7 +60,7 @@ export function validatePublicKey (key: Uint8Array) { } } -export function computePublicKey (privateKey: Uint8Array) { +export function computePublicKey (privateKey: Uint8Array): Uint8Array { try { return secp.getPublicKey(privateKey, true) } catch (err) { diff --git a/src/util.ts b/src/util.ts index 9d4a4fe9..57ea415b 100644 --- a/src/util.ts +++ b/src/util.ts @@ -6,7 +6,7 @@ import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string' import { toString as uint8ArrayToString } from 'uint8arrays/to-string' import { concat as uint8ArrayConcat } from 'uint8arrays/concat' -export function bigIntegerToUintBase64url (num: { abs: () => any}, len?: number) { +export function bigIntegerToUintBase64url (num: { abs: () => any }, len?: number): string { // Call `.abs()` to convert to unsigned let buf = Uint8Array.from(num.abs().toByteArray()) // toByteArray converts to big endian @@ -30,7 +30,7 @@ export function base64urlToBigInteger (str: string): typeof forge.jsbn.BigIntege return new forge.jsbn.BigInteger(uint8ArrayToString(buf, 'base16'), 16) } -export function base64urlToBuffer (str: string, len?: number) { +export function base64urlToBuffer (str: string, len?: number): Uint8Array { let buf = uint8ArrayFromString(str, 'base64urlpad') if (len != null) { diff --git a/test/aes/aes.spec.ts b/test/aes/aes.spec.ts index 06ddddb7..0b41c1d2 100644 --- a/test/aes/aes.spec.ts +++ b/test/aes/aes.spec.ts @@ -94,7 +94,7 @@ describe('AES-CTR', () => { }) }) -async function encryptAndDecrypt (cipher: AESCipher) { +async function encryptAndDecrypt (cipher: AESCipher): Promise { const data = new Uint8Array(100) data.fill(Math.ceil(Math.random() * 100)) diff --git a/test/crypto.spec.ts b/test/crypto.spec.ts index 242bc248..24aa3fd7 100644 --- a/test/crypto.spec.ts +++ b/test/crypto.spec.ts @@ -115,7 +115,7 @@ describe('libp2p-crypto', function () { }) it('throws on invalid hash name', () => { - const fn = () => crypto.pbkdf2('password', 'at least 16 character salt', 500, 512 / 8, 'shaX-xxx') + const fn = (): string => crypto.pbkdf2('password', 'at least 16 character salt', 500, 512 / 8, 'shaX-xxx') expect(fn).to.throw().with.property('code', 'ERR_UNSUPPORTED_HASH_TYPE') }) }) diff --git a/test/helpers/test-garbage-error-handling.ts b/test/helpers/test-garbage-error-handling.ts index 3b306911..f53aa34c 100644 --- a/test/helpers/test-garbage-error-handling.ts +++ b/test/helpers/test-garbage-error-handling.ts @@ -4,7 +4,7 @@ import util from 'util' const garbage = [uint8ArrayFromString('00010203040506070809', 'base16'), {}, null, false, undefined, true, 1, 0, uint8ArrayFromString(''), 'aGVsbG93b3JsZA==', 'helloworld', ''] -export function testGarbage (fncName: string, fnc: (...args: Uint8Array[]) => Promise, num?: number, skipBuffersAndStrings?: boolean) { +export function testGarbage (fncName: string, fnc: (...args: Uint8Array[]) => Promise, num?: number, skipBuffersAndStrings?: boolean): void { const count = num ?? 1 garbage.forEach((garbage) => { diff --git a/test/keys/ed25519.spec.ts b/test/keys/ed25519.spec.ts index 8e8499e1..b0408490 100644 --- a/test/keys/ed25519.spec.ts +++ b/test/keys/ed25519.spec.ts @@ -61,9 +61,9 @@ describe('ed25519', function () { expect(res).to.be.eql(true) }) - it('encoding', async () => { + it('encoding', () => { const keyMarshal = key.marshal() - const key2 = await ed25519.unmarshalEd25519PrivateKey(keyMarshal) + const key2 = ed25519.unmarshalEd25519PrivateKey(keyMarshal) const keyMarshal2 = key2.marshal() expect(keyMarshal).to.eql(keyMarshal2) diff --git a/test/keys/rsa.spec.ts b/test/keys/rsa.spec.ts index a407297c..fbb82fcc 100644 --- a/test/keys/rsa.spec.ts +++ b/test/keys/rsa.spec.ts @@ -81,10 +81,10 @@ describe('RSA', function () { expect(valid).to.be.eql(true) }) - it('encrypt and decrypt', async () => { + it('encrypt and decrypt', () => { const data = uint8ArrayFromString('hello world') - const enc = await key.public.encrypt(data) - const dec = await key.decrypt(enc) + const enc = key.public.encrypt(data) + const dec = key.decrypt(enc) expect(dec).to.be.eql(data) }) diff --git a/test/keys/secp256k1.spec.ts b/test/keys/secp256k1.spec.ts index ce0e927b..bdac9ac7 100644 --- a/test/keys/secp256k1.spec.ts +++ b/test/keys/secp256k1.spec.ts @@ -40,9 +40,9 @@ describe('secp256k1 keys', () => { expect(res).to.equal(true) }) - it('encoding', async () => { + it('encoding', () => { const keyMarshal = key.marshal() - const key2 = await secp256k1.unmarshalSecp256k1PrivateKey(keyMarshal) + const key2 = secp256k1.unmarshalSecp256k1PrivateKey(keyMarshal) const keyMarshal2 = key2.marshal() expect(keyMarshal).to.eql(keyMarshal2) @@ -57,7 +57,7 @@ describe('secp256k1 keys', () => { it('key id', async () => { const decoded = keysPBM.PrivateKey.decode(fixtures.privateKey) - const key = await secp256k1.unmarshalSecp256k1PrivateKey(decoded.Data ?? new Uint8Array()) + const key = secp256k1.unmarshalSecp256k1PrivateKey(decoded.Data ?? new Uint8Array()) const id = await key.id() expect(id).to.eql('QmPCyMBGEyifPtx5aa6k6wkY9N1eBf9vHK1eKfNc35q9uq') }) @@ -122,8 +122,8 @@ describe('crypto functions', () => { let privKey: Uint8Array let pubKey: Uint8Array - before(async () => { - privKey = await secp256k1Crypto.generateKey() + before(() => { + privKey = secp256k1Crypto.generateKey() pubKey = secp256k1Crypto.computePublicKey(privKey) }) @@ -135,8 +135,8 @@ describe('crypto functions', () => { }) it('does not validate an invalid key', () => { - expect(() => secp256k1Crypto.validatePublicKey(uint8ArrayFromString('42'))).to.throw() - expect(() => secp256k1Crypto.validatePrivateKey(uint8ArrayFromString('42'))).to.throw() + expect(() => { secp256k1Crypto.validatePublicKey(uint8ArrayFromString('42')) }).to.throw() + expect(() => { secp256k1Crypto.validatePrivateKey(uint8ArrayFromString('42')) }).to.throw() }) it('validates a correct signature', async () => { @@ -185,13 +185,13 @@ describe('crypto functions', () => { }) describe('go interop', () => { - it('loads a private key marshaled by go-libp2p-crypto', async () => { + it('loads a private key marshaled by go-libp2p-crypto', () => { // we need to first extract the key data from the protobuf, which is // normally handled by js-libp2p-crypto const decoded = keysPBM.PrivateKey.decode(fixtures.privateKey) expect(decoded.Type).to.eql(keysPBM.KeyType.Secp256k1) - const key = await secp256k1.unmarshalSecp256k1PrivateKey(decoded.Data ?? new Uint8Array()) + const key = secp256k1.unmarshalSecp256k1PrivateKey(decoded.Data ?? new Uint8Array()) expect(key).to.be.an.instanceof(secp256k1.Secp256k1PrivateKey) expect(key.bytes).to.eql(fixtures.privateKey) }) @@ -209,7 +209,7 @@ describe('go interop', () => { const decoded = keysPBM.PrivateKey.decode(fixtures.privateKey) expect(decoded.Type).to.eql(keysPBM.KeyType.Secp256k1) - const key = await secp256k1.unmarshalSecp256k1PrivateKey(decoded.Data ?? new Uint8Array()) + const key = secp256k1.unmarshalSecp256k1PrivateKey(decoded.Data ?? new Uint8Array()) const sig = await key.sign(fixtures.message) expect(sig).to.eql(fixtures.signature) })