refactor: bug fixes, added type asserts and use ? chaining where needed

This commit is contained in:
Derrick Hammer 2023-07-05 06:19:41 -04:00
parent 8797249ae5
commit 1ad6c1d692
Signed by: pcfreak30
GPG Key ID: C997C339BE476FF2
8 changed files with 47 additions and 49 deletions

View File

@ -1,11 +1,10 @@
import Proxy from "./proxy.js"; import Proxy from "./proxy.js";
import Socket from "./socket.js"; import Socket from "./socket.js";
import { Buffer } from "buffer";
import { maybeGetAsyncProperty } from "./util.js";
export type OnOpen = ( export type OnOpen = (
peer: Peer, peer: Peer,
socket: Socket, socket: Socket,
data: any data: any,
) => ) =>
| { connect: boolean } | { connect: boolean }
| Promise<{ connect: boolean }> | Promise<{ connect: boolean }>
@ -19,7 +18,7 @@ export type OnChannel = (peer: Peer, channel: any) => void;
export type OnOpenBound = ( export type OnOpenBound = (
socket: Socket, socket: Socket,
data: any data: any,
) => ) =>
| { connect: boolean } | { connect: boolean }
| Promise<{ connect: boolean }> | Promise<{ connect: boolean }>
@ -75,18 +74,18 @@ export default abstract class Peer {
this._proxy = proxy; this._proxy = proxy;
this._peer = peer; this._peer = peer;
this._muxer = muxer; this._muxer = muxer;
this._onopen = onopen?.bind(undefined, this); this._onopen = onopen?.bind(undefined, this) as OnOpenBound;
this._onreceive = onreceive?.bind(undefined, this); this._onreceive = onreceive?.bind(undefined, this) as OnReceiveBound;
this._onsend = onsend?.bind(undefined, this); this._onsend = onsend?.bind(undefined, this) as OnSendBound;
this._onclose = onclose?.bind(undefined, this); this._onclose = onclose?.bind(undefined, this) as OnCloseBound;
this._onchannel = onchannel?.bind(undefined, this); this._onchannel = onchannel?.bind(undefined, this) as OnChannelBound;
this._emulateWebsocket = emulateWebsocket; this._emulateWebsocket = emulateWebsocket;
} }
protected _socket?: Socket; protected _socket?: Socket;
get socket(): Socket { get socket(): Socket {
return this._socket; return this._socket as Socket;
} }
protected _channel?: any; protected _channel?: any;

View File

@ -1,10 +1,11 @@
import BasePeer from "../../peer.js"; import BasePeer from "#peer.js";
import { maybeGetAsyncProperty } from "../../util.js"; import { maybeGetAsyncProperty } from "#util.js";
import Socket from "../../socket.js"; import Socket from "#socket.js";
import { Buffer } from "buffer"; import { Buffer } from "buffer";
export default class Peer extends BasePeer { export default class Peer extends BasePeer {
private _pipe?: any; private _pipe?: any;
protected async initSocket() { protected async initSocket() {
const self = this; const self = this;
@ -32,7 +33,7 @@ export default class Peer extends BasePeer {
} }
this._socket?.on("end", () => this._channel.close()); this._socket?.on("end", () => this._channel.close());
let ret = await this._onopen?.(this._socket, m); let ret = await this._onopen?.(this._socket as Socket, m);
if (!ret || (ret && ret.connect === false)) { if (!ret || (ret && ret.connect === false)) {
// @ts-ignore // @ts-ignore
self._socket?.emit("connect"); self._socket?.emit("connect");
@ -52,7 +53,7 @@ export default class Peer extends BasePeer {
if (m instanceof Uint8Array) { if (m instanceof Uint8Array) {
m = Buffer.from(m); m = Buffer.from(m);
} }
self._socket.emit("data", m); self._socket?.emit("data", m);
await self._onreceive?.(m); await self._onreceive?.(m);
}, },
}); });

View File

@ -19,6 +19,7 @@ import {
} from "./multiSocket/types.js"; } from "./multiSocket/types.js";
import DummySocket from "./multiSocket/dummySocket.js"; import DummySocket from "./multiSocket/dummySocket.js";
import Peer from "./multiSocket/peer.js"; import Peer from "./multiSocket/peer.js";
import { uint8ArrayToHexString } from "binconv";
export interface MultiSocketProxyOptions extends ProxyOptions { export interface MultiSocketProxyOptions extends ProxyOptions {
socketClass?: any; socketClass?: any;
@ -102,7 +103,7 @@ export default class MultiSocketProxy extends Proxy {
private _peers: Map<string, PeerEntity> = new Map<string, PeerEntity>(); private _peers: Map<string, PeerEntity> = new Map<string, PeerEntity>();
private _nextPeer; private _nextPeer;
private _server = false; private _server = false;
private _allowedPorts = []; private _allowedPorts: number[] = [];
constructor(options: MultiSocketProxyOptions) { constructor(options: MultiSocketProxyOptions) {
super(options); super(options);
@ -209,12 +210,14 @@ export default class MultiSocketProxy extends Proxy {
self._allowedPorts.length && self._allowedPorts.length &&
!self._allowedPorts.includes((m as TcpSocketConnectOpts).port) !self._allowedPorts.includes((m as TcpSocketConnectOpts).port)
) { ) {
self.get(await self._getPublicKey(peer)).messages.errorSocket.send({ self
id: (m as SocketRequest).id, .get(await self._getPublicKey(peer))
err: new Error( ?.messages.errorSocket?.send({
`port ${(m as TcpSocketConnectOpts).port} not allowed` id: (m as SocketRequest).id,
), err: new Error(
}); `port ${(m as TcpSocketConnectOpts).port} not allowed`,
),
});
return; return;
} }
} }
@ -227,7 +230,7 @@ export default class MultiSocketProxy extends Proxy {
m.id, m.id,
self, self,
self.get(await self._getPublicKey(peer)) as PeerEntity, self.get(await self._getPublicKey(peer)) as PeerEntity,
m m,
).connect(); ).connect();
return; return;
} }
@ -290,7 +293,6 @@ export default class MultiSocketProxy extends Proxy {
const message = await peer.channel.addMessage({ const message = await peer.channel.addMessage({
encoding: errorSocketEncoding, encoding: errorSocketEncoding,
onmessage(m: ErrorSocketRequest) { onmessage(m: ErrorSocketRequest) {
// @ts-ignore
self._sockets.get(m.id)?.emit("error", m.err); self._sockets.get(m.id)?.emit("error", m.err);
}, },
}); });
@ -300,7 +302,7 @@ export default class MultiSocketProxy extends Proxy {
} }
private _toString(pubkey: Uint8Array) { private _toString(pubkey: Uint8Array) {
return b4a.from(pubkey).toString("hex"); return uint8ArrayToHexString(pubkey);
} }
private async _getPublicKey(peer: Peer) { private async _getPublicKey(peer: Peer) {

View File

@ -3,8 +3,8 @@ import { TcpSocketConnectOpts } from "net";
import { clearTimeout } from "timers"; import { clearTimeout } from "timers";
import MultiSocketProxy from "../multiSocket.js"; import MultiSocketProxy from "../multiSocket.js";
import { PeerEntity, SocketRequest, WriteSocketRequest } from "./types.js"; import { PeerEntity, SocketRequest, WriteSocketRequest } from "./types.js";
import { maybeGetAsyncProperty } from "../../util.js"; import { maybeGetAsyncProperty } from "#util.js";
import Socket, { SocketOptions } from "../../socket.js"; import Socket, { SocketOptions } from "#socket.js";
export default class DummySocket extends Socket { export default class DummySocket extends Socket {
private _options: TcpSocketConnectOpts; private _options: TcpSocketConnectOpts;
@ -18,7 +18,7 @@ export default class DummySocket extends Socket {
manager: MultiSocketProxy, manager: MultiSocketProxy,
peer: PeerEntity, peer: PeerEntity,
connectOptions: TcpSocketConnectOpts, connectOptions: TcpSocketConnectOpts,
socketOptions: SocketOptions socketOptions: SocketOptions,
) { ) {
super(socketOptions); super(socketOptions);
this._id = id; this._id = id;

View File

@ -1,5 +1,5 @@
import BasePeer from "../../peer.js"; import BasePeer from "#peer.js";
import Socket from "../../socket.js"; import Socket from "#socket.js";
import MultiSocketProxy from "../multiSocket.js"; import MultiSocketProxy from "../multiSocket.js";
export default class Peer extends BasePeer { export default class Peer extends BasePeer {

View File

@ -1,8 +1,8 @@
import { Callback, Duplex } from "streamx"; import { Callback } from "streamx";
import * as net from "net";
import { Socket, TcpSocketConnectOpts } from "net"; import { Socket, TcpSocketConnectOpts } from "net";
import MultiSocketProxy from "../multiSocket.js"; import MultiSocketProxy from "../multiSocket.js";
import { PeerEntity, SocketRequest, WriteSocketRequest } from "./types.js"; import { PeerEntity, SocketRequest, WriteSocketRequest } from "./types.js";
import * as net from "net";
import BaseSocket from "../../socket.js"; import BaseSocket from "../../socket.js";
export default class TcpSocket extends BaseSocket { export default class TcpSocket extends BaseSocket {
@ -18,7 +18,7 @@ export default class TcpSocket extends BaseSocket {
remoteId: number, remoteId: number,
manager: MultiSocketProxy, manager: MultiSocketProxy,
peer: PeerEntity, peer: PeerEntity,
options: TcpSocketConnectOpts options: TcpSocketConnectOpts,
) { ) {
super(); super();
this._remoteId = remoteId; this._remoteId = remoteId;
@ -72,9 +72,9 @@ export default class TcpSocket extends BaseSocket {
["timeout", "error", "connect", "end", "destroy", "close"].forEach( ["timeout", "error", "connect", "end", "destroy", "close"].forEach(
(event) => { (event) => {
this._socket?.on(event, (...args: any) => this._socket?.on(event, (...args: any) =>
this.emit(event as any, ...args) this.emit(event as any, ...args),
); );
} },
); );
this._socket.pipe(this as any); this._socket.pipe(this as any);

View File

@ -1,5 +1,4 @@
import { ProxyOptions } from "../../proxy.js"; import Peer from "#peer.js";
import Peer from "../../peer.js";
export interface SocketRequest { export interface SocketRequest {
remoteId: number; remoteId: number;

View File

@ -1,5 +1,4 @@
import { Duplex, DuplexEvents, Callback } from "streamx"; import { Callback, Duplex, DuplexEvents } from "streamx";
import { write } from "fs";
const IPV4 = "IPv4"; const IPV4 = "IPv4";
const IPV6 = "IPv6"; const IPV6 = "IPv6";
@ -14,7 +13,7 @@ export interface SocketOptions {
write?: ( write?: (
this: Duplex<any, any, any, any, true, true, DuplexEvents<any, any>>, this: Duplex<any, any, any, any, true, true, DuplexEvents<any, any>>,
data: any, data: any,
cb: Callback cb: Callback,
) => void; ) => void;
emulateWebsocket?: boolean; emulateWebsocket?: boolean;
} }
@ -23,9 +22,7 @@ export default class Socket extends Duplex {
private _allowHalfOpen: boolean; private _allowHalfOpen: boolean;
public remoteAddress: any; public remoteAddress: any;
public remotePort: any; public remotePort: any;
public remoteFamily: AddressFamily; public remoteFamily?: AddressFamily;
public bufferSize;
declare readable: true; declare readable: true;
declare writable: true; declare writable: true;
@ -49,7 +46,7 @@ export default class Socket extends Duplex {
this._allowHalfOpen = allowHalfOpen; this._allowHalfOpen = allowHalfOpen;
this.remoteAddress = remoteAddress; this.remoteAddress = remoteAddress;
this.remotePort = remotePort; this.remotePort = remotePort;
this.remotePublicKey = remotePublicKey; this.remotePublicKey = remotePublicKey as Uint8Array;
this._emulateWebsocket = emulateWebsocket; this._emulateWebsocket = emulateWebsocket;
if (remoteAddress) { if (remoteAddress) {
@ -68,15 +65,15 @@ export default class Socket extends Duplex {
this.close = this.end; this.close = this.end;
this.addEventListener("data", (data: any) => this.addEventListener("data", (data: any) =>
// @ts-ignore // @ts-ignore
this.emit("message", new MessageEvent("data", { data })) this.emit("message", new MessageEvent("data", { data })),
); );
} }
} }
private _connecting: boolean; private _connecting?: boolean;
get connecting(): boolean { get connecting(): boolean {
return this._connecting; return this._connecting as boolean;
} }
get readyState(): string | number { get readyState(): string | number {
@ -140,13 +137,13 @@ export default class Socket extends Duplex {
static isIPv4(input: string) { static isIPv4(input: string) {
return /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test( return /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(
input input,
); );
} }
static isIPv6(input: string) { static isIPv6(input: string) {
return /^(([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1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