diff --git a/src/@types/basic.d.ts b/src/@types/basic.d.ts index 03f9451..90f020e 100644 --- a/src/@types/basic.d.ts +++ b/src/@types/basic.d.ts @@ -1,8 +1,8 @@ -import {Buffer} from 'buffer'; +import { Buffer } from 'buffer' -export type bytes = Buffer; -export type bytes32 = Buffer; -export type bytes16 = Buffer; +export type bytes = Buffer +export type bytes32 = Buffer +export type bytes16 = Buffer -export type uint32 = number; -export type uint64 = number; +export type uint32 = number +export type uint64 = number diff --git a/src/@types/handshake-interface.d.ts b/src/@types/handshake-interface.d.ts index f432bda..748f64f 100644 --- a/src/@types/handshake-interface.d.ts +++ b/src/@types/handshake-interface.d.ts @@ -1,11 +1,11 @@ -import {bytes} from "./basic"; -import {NoiseSession} from "./handshake"; -import PeerId from "peer-id"; +import { bytes } from './basic' +import { NoiseSession } from './handshake' +import PeerId from 'peer-id' export interface IHandshake { - session: NoiseSession; - remotePeer: PeerId; - remoteEarlyData: Buffer; - encrypt(plaintext: bytes, session: NoiseSession): bytes; - decrypt(ciphertext: bytes, session: NoiseSession): {plaintext: bytes; valid: boolean}; + session: NoiseSession + remotePeer: PeerId + remoteEarlyData: Buffer + encrypt: (plaintext: bytes, session: NoiseSession) => bytes + decrypt: (ciphertext: bytes, session: NoiseSession) => {plaintext: bytes, valid: boolean} } diff --git a/src/@types/handshake.d.ts b/src/@types/handshake.d.ts index 7e823b3..c6aa1cc 100644 --- a/src/@types/handshake.d.ts +++ b/src/@types/handshake.d.ts @@ -1,45 +1,45 @@ -import {bytes, bytes32, uint32, uint64} from "./basic"; -import {KeyPair} from "./libp2p"; +import { bytes, bytes32, uint32, uint64 } from './basic' +import { KeyPair } from './libp2p' -export type Hkdf = [bytes, bytes, bytes]; +export type Hkdf = [bytes, bytes, bytes] -export type MessageBuffer = { - ne: bytes32; - ns: bytes; - ciphertext: bytes; +export interface MessageBuffer { + ne: bytes32 + ns: bytes + ciphertext: bytes } -export type CipherState = { - k: bytes32; - n: uint32; +export interface CipherState { + k: bytes32 + n: uint32 } -export type SymmetricState = { - cs: CipherState; - ck: bytes32; // chaining key - h: bytes32; // handshake hash +export interface SymmetricState { + cs: CipherState + ck: bytes32 // chaining key + h: bytes32 // handshake hash } -export type HandshakeState = { - ss: SymmetricState; - s: KeyPair; - e?: KeyPair; - rs: bytes32; - re: bytes32; - psk: bytes32; +export interface HandshakeState { + ss: SymmetricState + s: KeyPair + e?: KeyPair + rs: bytes32 + re: bytes32 + psk: bytes32 } -export type NoiseSession = { - hs: HandshakeState; - h?: bytes32; - cs1?: CipherState; - cs2?: CipherState; - mc: uint64; - i: boolean; +export interface NoiseSession { + hs: HandshakeState + h?: bytes32 + cs1?: CipherState + cs2?: CipherState + mc: uint64 + i: boolean } export interface INoisePayload { - identityKey: bytes; - identitySig: bytes; - data: bytes; + identityKey: bytes + identitySig: bytes + data: bytes } diff --git a/src/@types/it-length-prefixed/index.d.ts b/src/@types/it-length-prefixed/index.d.ts index 99de1ad..825f0cb 100644 --- a/src/@types/it-length-prefixed/index.d.ts +++ b/src/@types/it-length-prefixed/index.d.ts @@ -3,33 +3,33 @@ declare module 'it-length-prefixed' { import { Buffer } from 'buffer' interface LengthDecoderFunction { - (data: Buffer | BufferList): number; - bytes: number; + (data: Buffer | BufferList): number + bytes: number } interface LengthEncoderFunction { - (value: number, target: Buffer, offset: number): number|Buffer; - bytes: number; + (value: number, target: Buffer, offset: number): number|Buffer + bytes: number } interface Encoder { - (options?: Partial<{lengthEncoder: LengthEncoderFunction}>): AsyncGenerator; - single: (chunk: Buffer, options?: Partial<{lengthEncoder: LengthEncoderFunction}>) => BufferList; - MIN_POOL_SIZE: number; - DEFAULT_POOL_SIZE: number; + (options?: Partial<{lengthEncoder: LengthEncoderFunction}>): AsyncGenerator + single: (chunk: Buffer, options?: Partial<{lengthEncoder: LengthEncoderFunction}>) => BufferList + MIN_POOL_SIZE: number + DEFAULT_POOL_SIZE: number } interface DecoderOptions { - lengthDecoder: LengthDecoderFunction; - maxLengthLength: number; - maxDataLength: number; + lengthDecoder: LengthDecoderFunction + maxLengthLength: number + maxDataLength: number } interface Decoder { - (options?: Partial): AsyncGenerator; - fromReader: (reader: any, options?: Partial) => BufferList; - MAX_LENGTH_LENGTH: number; - MAX_DATA_LENGTH: number; + (options?: Partial): AsyncGenerator + fromReader: (reader: any, options?: Partial) => BufferList + MAX_LENGTH_LENGTH: number + MAX_DATA_LENGTH: number } export const encode: Encoder diff --git a/src/@types/it-pair/index.d.ts b/src/@types/it-pair/index.d.ts index 1f05d9b..e5cb214 100644 --- a/src/@types/it-pair/index.d.ts +++ b/src/@types/it-pair/index.d.ts @@ -1,8 +1,8 @@ declare module 'it-pair' { - export type Duplex = [Stream, Stream]; + export type Duplex = [Stream, Stream] - type Stream = { - sink(source: Iterable): void; - source: Record; + interface Stream { + sink: (source: Iterable) => void + source: Record } } diff --git a/src/@types/libp2p.d.ts b/src/@types/libp2p.d.ts index 3c02747..d442353 100644 --- a/src/@types/libp2p.d.ts +++ b/src/@types/libp2p.d.ts @@ -1,20 +1,19 @@ -import { bytes, bytes32 } from "./basic"; -import PeerId from "peer-id"; +import { bytes, bytes32 } from './basic' +import PeerId from 'peer-id' -export type KeyPair = { - publicKey: bytes32; - privateKey: bytes32; +export interface KeyPair { + publicKey: bytes32 + privateKey: bytes32 } export interface INoiseConnection { - remoteEarlyData?(): bytes; - secureOutbound(localPeer: PeerId, insecure: any, remotePeer: PeerId): Promise; - secureInbound(localPeer: PeerId, insecure: any, remotePeer: PeerId): Promise; + remoteEarlyData?: () => bytes + secureOutbound: (localPeer: PeerId, insecure: any, remotePeer: PeerId) => Promise + secureInbound: (localPeer: PeerId, insecure: any, remotePeer: PeerId) => Promise } -export type SecureOutbound = { - conn: any; - remoteEarlyData: Buffer; - remotePeer: PeerId; +export interface SecureOutbound { + conn: any + remoteEarlyData: Buffer + remotePeer: PeerId } - diff --git a/src/crypto.ts b/src/crypto.ts index 8e50f71..5e84d01 100644 --- a/src/crypto.ts +++ b/src/crypto.ts @@ -3,7 +3,7 @@ import { IHandshake } from './@types/handshake-interface' import { NOISE_MSG_MAX_LENGTH_BYTES, NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG } from './constants' interface IReturnEncryptionWrapper { - (source: Iterable): AsyncIterableIterator; + (source: Iterable): AsyncIterableIterator } // Returns generator that encrypts payload from the user diff --git a/src/errors.ts b/src/errors.ts index 5738e3a..08082d5 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -1,7 +1,7 @@ import BufferList from 'bl' export class FailedIKError extends Error { - public initialMsg: string|BufferList|Buffer; + public initialMsg: string|BufferList|Buffer constructor (initialMsg: string|BufferList|Buffer, message?: string) { super(message) diff --git a/src/handshake-ik.ts b/src/handshake-ik.ts index 4a76716..075c5c0 100644 --- a/src/handshake-ik.ts +++ b/src/handshake-ik.ts @@ -19,16 +19,16 @@ import { import PeerId from 'peer-id' export class IKHandshake implements IHandshake { - public isInitiator: boolean; - public session: NoiseSession; - public remotePeer!: PeerId; - public remoteEarlyData: Buffer; + public isInitiator: boolean + public session: NoiseSession + public remotePeer!: PeerId + public remoteEarlyData: Buffer - private payload: bytes; - private prologue: bytes32; - private staticKeypair: KeyPair; - private connection: WrappedConnection; - private ik: IK; + private readonly payload: bytes + private readonly prologue: bytes32 + private readonly staticKeypair: KeyPair + private readonly connection: WrappedConnection + private readonly ik: IK constructor ( isInitiator: boolean, @@ -48,7 +48,7 @@ export class IKHandshake implements IHandshake { if (remotePeer) { this.remotePeer = remotePeer } - this.ik = handshake || new IK() + this.ik = handshake ?? new IK() this.session = this.ik.initSession(this.isInitiator, this.prologue, this.staticKeypair, remoteStaticKey) this.remoteEarlyData = Buffer.alloc(0) } @@ -79,9 +79,10 @@ export class IKHandshake implements IHandshake { logger('IK Stage 0 - Responder successfully verified payload!') logRemoteEphemeralKey(this.session.hs.re) } catch (e) { + const err = e as Error logger('Responder breaking up with IK handshake in stage 0.') - throw new FailedIKError(receivedMsg, `Error occurred while verifying initiator's signed payload: ${e.message}`) + throw new FailedIKError(receivedMsg, `Error occurred while verifying initiator's signed payload: ${err.message}`) } } } @@ -104,8 +105,9 @@ export class IKHandshake implements IHandshake { logger('IK Stage 1 - Initiator successfully verified payload!') logRemoteEphemeralKey(this.session.hs.re) } catch (e) { + const err = e as Error logger('Initiator breaking up with IK handshake in stage 1.') - throw new FailedIKError(receivedMsg, `Error occurred while verifying responder's signed payload: ${e.message}`) + throw new FailedIKError(receivedMsg, `Error occurred while verifying responder's signed payload: ${err.message}`) } } else { logger('IK Stage 1 - Responder sending message...') @@ -117,7 +119,7 @@ export class IKHandshake implements IHandshake { logCipherState(this.session) } - public decrypt (ciphertext: bytes, session: NoiseSession): {plaintext: bytes; valid: boolean} { + public decrypt (ciphertext: bytes, session: NoiseSession): {plaintext: bytes, valid: boolean} { const cs = this.getCS(session, false) return this.ik.decryptWithAd(cs, Buffer.alloc(0), ciphertext) } diff --git a/src/handshake-xx-fallback.ts b/src/handshake-xx-fallback.ts index 10a08a1..748151b 100644 --- a/src/handshake-xx-fallback.ts +++ b/src/handshake-xx-fallback.ts @@ -10,8 +10,8 @@ import { decode0, decode1 } from './encoder' import PeerId from 'peer-id' export class XXFallbackHandshake extends XXHandshake { - private ephemeralKeys?: KeyPair; - private initialMsg: bytes; + private readonly ephemeralKeys?: KeyPair + private readonly initialMsg: bytes constructor ( isInitiator: boolean, @@ -73,7 +73,8 @@ export class XXFallbackHandshake extends XXHandshake { await verifySignedPayload(this.session.hs.rs, decodedPayload, this.remotePeer) this.setRemoteEarlyData(decodedPayload.data) } catch (e) { - throw new Error(`Error occurred while verifying signed payload from responder: ${e.message}`) + const err = e as Error + throw new Error(`Error occurred while verifying signed payload from responder: ${err.message}`) } logger('All good with the signature!') } else { diff --git a/src/handshake-xx.ts b/src/handshake-xx.ts index ba1bbef..91de7fa 100644 --- a/src/handshake-xx.ts +++ b/src/handshake-xx.ts @@ -23,17 +23,17 @@ import { WrappedConnection } from './noise' import PeerId from 'peer-id' export class XXHandshake implements IHandshake { - public isInitiator: boolean; - public session: NoiseSession; - public remotePeer!: PeerId; - public remoteEarlyData: Buffer; + public isInitiator: boolean + public session: NoiseSession + public remotePeer!: PeerId + public remoteEarlyData: Buffer - protected payload: bytes; - protected connection: WrappedConnection; - protected xx: XX; - protected staticKeypair: KeyPair; + protected payload: bytes + protected connection: WrappedConnection + protected xx: XX + protected staticKeypair: KeyPair - private prologue: bytes32; + private readonly prologue: bytes32 constructor ( isInitiator: boolean, @@ -52,7 +52,7 @@ export class XXHandshake implements IHandshake { if (remotePeer) { this.remotePeer = remotePeer } - this.xx = handshake || new XX() + this.xx = handshake ?? new XX() this.session = this.xx.initSession(this.isInitiator, this.prologue, this.staticKeypair) this.remoteEarlyData = Buffer.alloc(0) } @@ -98,7 +98,8 @@ export class XXHandshake implements IHandshake { this.remotePeer = await verifySignedPayload(receivedMessageBuffer.ns, decodedPayload, this.remotePeer) this.setRemoteEarlyData(decodedPayload.data) } catch (e) { - throw new Error(`Error occurred while verifying signed payload: ${e.message}`) + const err = e as Error + throw new Error(`Error occurred while verifying signed payload: ${err.message}`) } logger('All good with the signature!') } else { @@ -132,7 +133,8 @@ export class XXHandshake implements IHandshake { await verifySignedPayload(this.session.hs.rs, decodedPayload, this.remotePeer) this.setRemoteEarlyData(decodedPayload.data) } catch (e) { - throw new Error(`Error occurred while verifying signed payload: ${e.message}`) + const err = e as Error + throw new Error(`Error occurred while verifying signed payload: ${err.message}`) } } logCipherState(this.session) @@ -144,7 +146,7 @@ export class XXHandshake implements IHandshake { return this.xx.encryptWithAd(cs, Buffer.alloc(0), plaintext) } - public decrypt (ciphertext: bytes, session: NoiseSession): {plaintext: bytes; valid: boolean} { + public decrypt (ciphertext: bytes, session: NoiseSession): {plaintext: bytes, valid: boolean} { const cs = this.getCS(session, false) return this.xx.decryptWithAd(cs, Buffer.alloc(0), ciphertext) } diff --git a/src/handshakes/abstract-handshake.ts b/src/handshakes/abstract-handshake.ts index 275152b..98301f1 100644 --- a/src/handshakes/abstract-handshake.ts +++ b/src/handshakes/abstract-handshake.ts @@ -18,7 +18,7 @@ export abstract class AbstractHandshake { return e } - public decryptWithAd (cs: CipherState, ad: bytes, ciphertext: bytes): {plaintext: bytes; valid: boolean} { + public decryptWithAd (cs: CipherState, ad: bytes, ciphertext: bytes): {plaintext: bytes, valid: boolean} { const { plaintext, valid } = this.decrypt(cs.k, cs.n, ad, ciphertext) this.setNonce(cs, this.incrementNonce(cs.n)) @@ -78,7 +78,7 @@ export abstract class AbstractHandshake { return ciphertext } - protected decrypt (k: bytes32, n: uint32, ad: bytes, ciphertext: bytes): {plaintext: bytes; valid: boolean} { + protected decrypt (k: bytes32, n: uint32, ad: bytes, ciphertext: bytes): {plaintext: bytes, valid: boolean} { const nonce = this.nonceToBytes(n) const ctx = new AEAD() ciphertext = Buffer.from(ciphertext) @@ -91,7 +91,7 @@ export abstract class AbstractHandshake { return { plaintext: ciphertext, valid: ctx.verify(tag) } } - protected decryptAndHash (ss: SymmetricState, ciphertext: bytes): {plaintext: bytes; valid: boolean} { + protected decryptAndHash (ss: SymmetricState, ciphertext: bytes): {plaintext: bytes, valid: boolean} { let plaintext: bytes; let valid = true if (this.hasKey(ss.cs)) { ({ plaintext, valid } = this.decryptWithAd(ss.cs, ss.h, ciphertext)) @@ -125,7 +125,7 @@ export abstract class AbstractHandshake { protected mixKey (ss: SymmetricState, ikm: bytes32): void { const [ck, tempK] = getHkdf(ss.ck, ikm) - ss.cs = this.initializeKey(tempK) as CipherState + ss.cs = this.initializeKey(tempK) ss.ck = ck } @@ -173,7 +173,7 @@ export abstract class AbstractHandshake { return { ne, ns, ciphertext } } - protected readMessageRegular (cs: CipherState, message: MessageBuffer): {plaintext: bytes; valid: boolean} { + protected readMessageRegular (cs: CipherState, message: MessageBuffer): {plaintext: bytes, valid: boolean} { return this.decryptWithAd(cs, Buffer.alloc(0), message.ciphertext) } } diff --git a/src/handshakes/ik.ts b/src/handshakes/ik.ts index c57797d..10816c9 100644 --- a/src/handshakes/ik.ts +++ b/src/handshakes/ik.ts @@ -55,7 +55,7 @@ export class IK extends AbstractHandshake { return messageBuffer } - public recvMessage (session: NoiseSession, message: MessageBuffer): {plaintext: bytes; valid: boolean} { + public recvMessage (session: NoiseSession, message: MessageBuffer): {plaintext: bytes, valid: boolean} { let plaintext = Buffer.alloc(0); let valid = false if (session.mc === 0) { ({ plaintext, valid } = this.readMessageA(session.hs, message)) @@ -101,7 +101,7 @@ export class IK extends AbstractHandshake { return { messageBuffer, cs1, cs2, h: hs.ss.h } } - private readMessageA (hs: HandshakeState, message: MessageBuffer): {plaintext: bytes; valid: boolean} { + private readMessageA (hs: HandshakeState, message: MessageBuffer): {plaintext: bytes, valid: boolean} { if (isValidPublicKey(message.ne)) { hs.re = message.ne } @@ -117,7 +117,7 @@ export class IK extends AbstractHandshake { return { plaintext, valid: (valid1 && valid2) } } - private readMessageB (hs: HandshakeState, message: MessageBuffer): {h: bytes; plaintext: bytes; valid: boolean; cs1: CipherState; cs2: CipherState} { + private readMessageB (hs: HandshakeState, message: MessageBuffer): {h: bytes, plaintext: bytes, valid: boolean, cs1: CipherState, cs2: CipherState} { if (isValidPublicKey(message.ne)) { hs.re = message.ne } diff --git a/src/handshakes/xx.ts b/src/handshakes/xx.ts index 1a09218..e7bbdb9 100644 --- a/src/handshakes/xx.ts +++ b/src/handshakes/xx.ts @@ -27,7 +27,7 @@ export class XX extends AbstractHandshake { private writeMessageA (hs: HandshakeState, payload: bytes, e?: KeyPair): MessageBuffer { const ns = Buffer.alloc(0) - if (e) { + if (e !== undefined) { hs.e = e } else { hs.e = generateKeypair() @@ -68,7 +68,7 @@ export class XX extends AbstractHandshake { return { h: hs.ss.h, messageBuffer, cs1, cs2 } } - private readMessageA (hs: HandshakeState, message: MessageBuffer): {plaintext: bytes; valid: boolean} { + private readMessageA (hs: HandshakeState, message: MessageBuffer): {plaintext: bytes, valid: boolean} { if (isValidPublicKey(message.ne)) { hs.re = message.ne } @@ -77,7 +77,7 @@ export class XX extends AbstractHandshake { return this.decryptAndHash(hs.ss, message.ciphertext) } - private readMessageB (hs: HandshakeState, message: MessageBuffer): {plaintext: bytes; valid: boolean} { + private readMessageB (hs: HandshakeState, message: MessageBuffer): {plaintext: bytes, valid: boolean} { if (isValidPublicKey(message.ne)) { hs.re = message.ne } @@ -96,7 +96,7 @@ export class XX extends AbstractHandshake { return { plaintext, valid: (valid1 && valid2) } } - private readMessageC (hs: HandshakeState, message: MessageBuffer): {h: bytes; plaintext: bytes; valid: boolean; cs1: CipherState; cs2: CipherState} { + private readMessageC (hs: HandshakeState, message: MessageBuffer): {h: bytes, plaintext: bytes, valid: boolean, cs1: CipherState, cs2: CipherState} { const { plaintext: ns, valid: valid1 } = this.decryptAndHash(hs.ss, message.ns) if (valid1 && ns.length === 32 && isValidPublicKey(ns)) { hs.rs = ns @@ -164,7 +164,7 @@ export class XX extends AbstractHandshake { return messageBuffer } - public recvMessage (session: NoiseSession, message: MessageBuffer): {plaintext: bytes; valid: boolean} { + public recvMessage (session: NoiseSession, message: MessageBuffer): {plaintext: bytes, valid: boolean} { let plaintext: bytes = Buffer.alloc(0) let valid = false if (session.mc === 0) { diff --git a/src/keycache.ts b/src/keycache.ts index 820161a..9261cda 100644 --- a/src/keycache.ts +++ b/src/keycache.ts @@ -5,7 +5,7 @@ import PeerId from 'peer-id' * Storage for static keys of previously connected peers. */ class Keycache { - private storage = new Map(); + private readonly storage = new Map() public store (peerId: PeerId, key: bytes32): void { this.storage.set(peerId.id, key) @@ -15,7 +15,7 @@ class Keycache { if (!peerId) { return null } - return this.storage.get(peerId.id) || null + return this.storage.get(peerId.id) ?? null } public resetStorage (): void { diff --git a/src/noise.ts b/src/noise.ts index e189bd1..d8b4a24 100644 --- a/src/noise.ts +++ b/src/noise.ts @@ -21,22 +21,22 @@ import { logger } from './logger' import PeerId from 'peer-id' import { NOISE_MSG_MAX_LENGTH_BYTES } from './constants' -export type WrappedConnection = ReturnType; +export type WrappedConnection = ReturnType -type HandshakeParams = { - connection: WrappedConnection; - isInitiator: boolean; - localPeer: PeerId; - remotePeer?: PeerId; -}; +interface HandshakeParams { + connection: WrappedConnection + isInitiator: boolean + localPeer: PeerId + remotePeer?: PeerId +} export class Noise implements INoiseConnection { - public protocol = '/noise'; + public protocol = '/noise' - private readonly prologue = Buffer.alloc(0); - private readonly staticKeys: KeyPair; - private readonly earlyData?: bytes; - private useNoisePipes: boolean; + private readonly prologue = Buffer.alloc(0) + private readonly staticKeys: KeyPair + private readonly earlyData?: bytes + private readonly useNoisePipes: boolean /** * @@ -44,7 +44,7 @@ export class Noise implements INoiseConnection { * @param {bytes} earlyData */ constructor (staticNoiseKey?: bytes, earlyData?: bytes) { - this.earlyData = earlyData || Buffer.alloc(0) + this.earlyData = earlyData ?? Buffer.alloc(0) // disabled until properly specked this.useNoisePipes = false @@ -71,9 +71,6 @@ export class Noise implements INoiseConnection { const wrappedConnection = Wrap( connection, { - // wrong types in repo - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore lengthEncoder: uint16BEEncode, lengthDecoder: uint16BEDecode, maxDataLength: NOISE_MSG_MAX_LENGTH_BYTES @@ -106,9 +103,6 @@ export class Noise implements INoiseConnection { const wrappedConnection = Wrap( connection, { - // wrong types in repo - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore lengthEncoder: uint16BEEncode, lengthDecoder: uint16BEDecode, maxDataLength: NOISE_MSG_MAX_LENGTH_BYTES @@ -153,7 +147,7 @@ export class Noise implements INoiseConnection { this.staticKeys, connection, // safe to cast as we did checks - KeyCache.load(params.remotePeer) || Buffer.alloc(32), + KeyCache.load(params.remotePeer) ?? Buffer.alloc(32), remotePeer as PeerId ) @@ -189,7 +183,8 @@ export class Noise implements INoiseConnection { await handshake.finish() } catch (e) { logger(e) - throw new Error(`Error occurred during XX Fallback handshake: ${e.message}`) + const err = e as Error + throw new Error(`Error occurred during XX Fallback handshake: ${err.message}`) } return handshake @@ -211,7 +206,8 @@ export class Noise implements INoiseConnection { KeyCache.store(handshake.remotePeer, handshake.getRemoteStaticKey()) } } catch (e) { - throw new Error(`Error occurred during XX handshake: ${e.message}`) + const err = e as Error + throw new Error(`Error occurred during XX handshake: ${err.message}`) } return handshake diff --git a/src/utils.ts b/src/utils.ts index 5413c13..700c3bc 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -28,9 +28,9 @@ export async function getPayload ( earlyData?: bytes ): Promise { const signedPayload = await signPayload(localPeer, getHandshakePayload(staticPublicKey)) - const earlyDataPayload = earlyData || Buffer.alloc(0) + const earlyDataPayload = earlyData ?? Buffer.alloc(0) - return await createHandshakePayload( + return createHandshakePayload( localPeer.marshalPubKey(), signedPayload, earlyDataPayload @@ -45,7 +45,7 @@ export function createHandshakePayload ( const payloadInit = NoiseHandshakePayloadProto.create({ identityKey: Buffer.from(libp2pPublicKey), identitySig: signedPayload, - data: earlyData || null + data: earlyData ?? null }) return Buffer.from(NoiseHandshakePayloadProto.encode(payloadInit).finish()) @@ -94,10 +94,12 @@ export async function verifySignedPayload ( const generatedPayload = getHandshakePayload(noiseStaticKey) // Unmarshaling from PublicKey protobuf const publicKey = keys.unmarshalPublicKey(identityKey) + // TODO remove this after libp2p-crypto ships proper types + // eslint-disable-next-line @typescript-eslint/no-misused-promises if (!payload.identitySig || !publicKey.verify(generatedPayload, Buffer.from(payload.identitySig))) { throw new Error("Static key doesn't match to peer that signed payload!") } - return PeerId.createFromPubKey(identityKey) + return await PeerId.createFromPubKey(identityKey) } export function getHkdf (ck: bytes32, ikm: bytes): Hkdf { diff --git a/test/fixtures/peer.ts b/test/fixtures/peer.ts index 15f394a..e87be60 100644 --- a/test/fixtures/peer.ts +++ b/test/fixtures/peer.ts @@ -19,9 +19,9 @@ const peers = [{ pubKey: 'CAESIMbnikZaPciAMZhUXqDRVCs7VFOBtmlIk26g0GgOotDA' }] -export async function createPeerIdsFromFixtures (length:number): Promise { +export async function createPeerIdsFromFixtures (length: number): Promise { return await Promise.all( - Array.from({ length }).map((_, i) => PeerId.createFromJSON(peers[i])) + Array.from({ length }).map(async (_, i) => await PeerId.createFromJSON(peers[i])) ) } diff --git a/test/handshakes/ik.spec.ts b/test/handshakes/ik.spec.ts index f33eb54..bad467f 100644 --- a/test/handshakes/ik.spec.ts +++ b/test/handshakes/ik.spec.ts @@ -56,8 +56,8 @@ describe('IK handshake', () => { // initiator receives message ikI.recvMessage(initiatorSession, messageBuffer2) - assert(initiatorSession?.cs1?.k.equals(responderSession?.cs1?.k || new Uint8Array())) - assert(initiatorSession?.cs2?.k.equals(responderSession?.cs2?.k || new Uint8Array())) + assert(initiatorSession?.cs1?.k.equals(responderSession?.cs1?.k ?? new Uint8Array())) + assert(initiatorSession?.cs2?.k.equals(responderSession?.cs2?.k ?? new Uint8Array())) } catch (e) { return assert(false, e.message) } diff --git a/test/keycache.spec.ts b/test/keycache.spec.ts index e1a3c32..0bd1056 100644 --- a/test/keycache.spec.ts +++ b/test/keycache.spec.ts @@ -15,9 +15,10 @@ describe('KeyCache', () => { const key = Buffer.from('this is id 007') await KeyCache.store(peerA, key) const result = await KeyCache.load(peerA) - assert(uint8ArrayEquals(result, key), 'Stored and loaded key are not the same') + assert(result !== null && uint8ArrayEquals(result, key), 'Stored and loaded key are not the same') } catch (e) { - assert(false, `Test failed - ${e.message}`) + const err = e as Error + assert(false, `Test failed - ${err.message}`) } }) @@ -25,9 +26,10 @@ describe('KeyCache', () => { try { const [newPeer] = await createPeerIds(1) const result = await KeyCache.load(newPeer) - assert(!result) + assert(result === null) } catch (e) { - assert(false, `Test failed - ${e.message}`) + const err = e as Error + assert(false, `Test failed - ${err.message}`) } }) }) diff --git a/test/utils.ts b/test/utils.ts index 4042ef9..4f0eab5 100644 --- a/test/utils.ts +++ b/test/utils.ts @@ -8,7 +8,7 @@ export async function generateEd25519Keys (): Promise { export function getKeyPairFromPeerId (peerId: PeerId): KeyPair { return { - privateKey: peerId.privKey.marshal().slice(0, 32), - publicKey: peerId.marshalPubKey() + privateKey: Buffer.from(peerId.privKey.marshal().slice(0, 32)), + publicKey: Buffer.from(peerId.marshalPubKey()) } } diff --git a/test/xx-fallback-handshake.spec.ts b/test/xx-fallback-handshake.spec.ts index 6dabb02..4f42336 100644 --- a/test/xx-fallback-handshake.spec.ts +++ b/test/xx-fallback-handshake.spec.ts @@ -48,7 +48,7 @@ describe('XX Fallback Handshake', () => { // This is the point where initiator falls back from IK const initialMsgI = await connectionFrom.readLP() const handshakeInit = - new XXFallbackHandshake(true, handshakePayload, prologue, staticKeysInitiator, connectionFrom, initialMsgI, peerB, ephemeralKeys) + new XXFallbackHandshake(true, handshakePayload, prologue, staticKeysInitiator, connectionFrom, initialMsgI.slice(0), peerB, ephemeralKeys) await handshakeInit.propose() await handshakeInit.exchange() @@ -60,7 +60,10 @@ describe('XX Fallback Handshake', () => { const sessionResponder = handshakeResp.session // Test shared key - if (sessionInitator.cs1 && sessionResponder.cs1 && sessionInitator.cs2 && sessionResponder.cs2) { + if (sessionInitator.cs1 !== undefined && + sessionResponder.cs1 !== undefined && + sessionInitator.cs2 !== undefined && + sessionResponder.cs2 !== undefined) { assert(sessionInitator.cs1.k.equals(sessionResponder.cs1.k)) assert(sessionInitator.cs2.k.equals(sessionResponder.cs2.k)) } else {