mirror of
https://github.com/fluencelabs/js-libp2p-noise
synced 2025-04-24 16:32:17 +00:00
fix: ts and lint errors
This commit is contained in:
parent
2df5f9546e
commit
ead151471e
12
src/@types/basic.d.ts
vendored
12
src/@types/basic.d.ts
vendored
@ -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
|
||||
|
16
src/@types/handshake-interface.d.ts
vendored
16
src/@types/handshake-interface.d.ts
vendored
@ -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}
|
||||
}
|
||||
|
62
src/@types/handshake.d.ts
vendored
62
src/@types/handshake.d.ts
vendored
@ -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
|
||||
}
|
||||
|
30
src/@types/it-length-prefixed/index.d.ts
vendored
30
src/@types/it-length-prefixed/index.d.ts
vendored
@ -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<BufferList, Buffer>;
|
||||
single: (chunk: Buffer, options?: Partial<{lengthEncoder: LengthEncoderFunction}>) => BufferList;
|
||||
MIN_POOL_SIZE: number;
|
||||
DEFAULT_POOL_SIZE: number;
|
||||
(options?: Partial<{lengthEncoder: LengthEncoderFunction}>): AsyncGenerator<BufferList, Buffer>
|
||||
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<DecoderOptions>): AsyncGenerator<BufferList, BufferList>;
|
||||
fromReader: (reader: any, options?: Partial<DecoderOptions>) => BufferList;
|
||||
MAX_LENGTH_LENGTH: number;
|
||||
MAX_DATA_LENGTH: number;
|
||||
(options?: Partial<DecoderOptions>): AsyncGenerator<BufferList, BufferList>
|
||||
fromReader: (reader: any, options?: Partial<DecoderOptions>) => BufferList
|
||||
MAX_LENGTH_LENGTH: number
|
||||
MAX_DATA_LENGTH: number
|
||||
}
|
||||
|
||||
export const encode: Encoder
|
||||
|
8
src/@types/it-pair/index.d.ts
vendored
8
src/@types/it-pair/index.d.ts
vendored
@ -1,8 +1,8 @@
|
||||
declare module 'it-pair' {
|
||||
export type Duplex = [Stream, Stream];
|
||||
export type Duplex = [Stream, Stream]
|
||||
|
||||
type Stream = {
|
||||
sink(source: Iterable<any>): void;
|
||||
source: Record<string, any>;
|
||||
interface Stream {
|
||||
sink: (source: Iterable<any>) => void
|
||||
source: Record<string, any>
|
||||
}
|
||||
}
|
||||
|
25
src/@types/libp2p.d.ts
vendored
25
src/@types/libp2p.d.ts
vendored
@ -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<SecureOutbound>;
|
||||
secureInbound(localPeer: PeerId, insecure: any, remotePeer: PeerId): Promise<SecureOutbound>;
|
||||
remoteEarlyData?: () => bytes
|
||||
secureOutbound: (localPeer: PeerId, insecure: any, remotePeer: PeerId) => Promise<SecureOutbound>
|
||||
secureInbound: (localPeer: PeerId, insecure: any, remotePeer: PeerId) => Promise<SecureOutbound>
|
||||
}
|
||||
|
||||
export type SecureOutbound = {
|
||||
conn: any;
|
||||
remoteEarlyData: Buffer;
|
||||
remotePeer: PeerId;
|
||||
export interface SecureOutbound {
|
||||
conn: any
|
||||
remoteEarlyData: Buffer
|
||||
remotePeer: PeerId
|
||||
}
|
||||
|
||||
|
@ -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<Uint8Array>): AsyncIterableIterator<Uint8Array>;
|
||||
(source: Iterable<Uint8Array>): AsyncIterableIterator<Uint8Array>
|
||||
}
|
||||
|
||||
// Returns generator that encrypts payload from the user
|
||||
|
@ -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)
|
||||
|
@ -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)
|
||||
}
|
||||
|
@ -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 {
|
||||
|
@ -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)
|
||||
}
|
||||
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
@ -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
|
||||
}
|
||||
|
@ -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) {
|
||||
|
@ -5,7 +5,7 @@ import PeerId from 'peer-id'
|
||||
* Storage for static keys of previously connected peers.
|
||||
*/
|
||||
class Keycache {
|
||||
private storage = new Map<Uint8Array, bytes32>();
|
||||
private readonly storage = new Map<Uint8Array, bytes32>()
|
||||
|
||||
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 {
|
||||
|
40
src/noise.ts
40
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<typeof Wrap>;
|
||||
export type WrappedConnection = ReturnType<typeof Wrap>
|
||||
|
||||
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
|
||||
|
10
src/utils.ts
10
src/utils.ts
@ -28,9 +28,9 @@ export async function getPayload (
|
||||
earlyData?: bytes
|
||||
): Promise<bytes> {
|
||||
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 {
|
||||
|
4
test/fixtures/peer.ts
vendored
4
test/fixtures/peer.ts
vendored
@ -19,9 +19,9 @@ const peers = [{
|
||||
pubKey: 'CAESIMbnikZaPciAMZhUXqDRVCs7VFOBtmlIk26g0GgOotDA'
|
||||
}]
|
||||
|
||||
export async function createPeerIdsFromFixtures (length:number): Promise<PeerId[]> {
|
||||
export async function createPeerIdsFromFixtures (length: number): Promise<PeerId[]> {
|
||||
return await Promise.all(
|
||||
Array.from({ length }).map((_, i) => PeerId.createFromJSON(peers[i]))
|
||||
Array.from({ length }).map(async (_, i) => await PeerId.createFromJSON(peers[i]))
|
||||
)
|
||||
}
|
||||
|
||||
|
@ -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)
|
||||
}
|
||||
|
@ -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}`)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
@ -8,7 +8,7 @@ export async function generateEd25519Keys (): Promise<PrivateKey> {
|
||||
|
||||
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())
|
||||
}
|
||||
}
|
||||
|
@ -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 {
|
||||
|
Loading…
x
Reference in New Issue
Block a user