Add support client API and support proxy http/https and tcp

This commit is contained in:
Sambo Chea 2023-07-11 12:20:03 +07:00
parent afbf3097f1
commit 9f61c8aebf
Signed by: sombochea
GPG Key ID: 3C7CF22A05D95490
9 changed files with 1765 additions and 343 deletions

View File

@ -1,2 +1,3 @@
src/
.github/
test/

View File

@ -1,3 +1,9 @@
### 11/07/2023
- Support Client API
- Support Proxy (HTTP/HTTPS) and TCP
- Improvements and Bugs fixed
### 30/11/2022
- Fixed response data in axios request with accept-encoding to identity

1333
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -25,6 +25,8 @@
"dependencies": {
"axios": "^1.2.0",
"commander": "^9.3.0",
"express": "^4.18.2",
"http-proxy-middleware": "^2.0.6",
"https-proxy-agent": "^5.0.1",
"socket.io-client": "^4.5.1"
},
@ -32,6 +34,7 @@
"access": "public"
},
"devDependencies": {
"@types/express": "^4.17.15",
"@types/node": "^18.0.3",
"ts-node-dev": "^2.0.0",
"typescript": "^4.7.4"

View File

@ -11,21 +11,32 @@ import { PROFILE_DEFAULT, PROFILE_PATH, SERVER_DEFAULT_URL, TOKEN_FREE } from ".
import { ClientOptions, Options } from "./interface";
import { getTokenFree } from './sdk';
interface Stoppable {
stop(): void;
}
class HttpTunnelClient implements Stoppable {
// create socket instance
let socket: Socket | null = null;
let keepAliveTimer: NodeJS.Timeout | null = null;
private socket: Socket | null = null;
private keepAliveTimer: NodeJS.Timeout | null = null;
private keepAliveTimeout: number | null = null;
function keepAlive() {
keepAliveTimer = setTimeout(() => {
if (socket && socket.connected) {
socket.send("ping");
}
keepAlive();
}, 5000);
private keepAlive() {
if (!this.socket) {
return;
}
// Init the Client
const initClient = async (options: any) => {
this.keepAliveTimer = setTimeout(() => {
if (this.socket && this.socket.connected) {
this.socket.send("ping");
}
this.keepAlive();
}, this.keepAliveTimeout || 5000);
}
// Init the Client for config file
public initConfigFile = async (options: any) => {
const profile = options.profile || PROFILE_DEFAULT;
const configDir = path.resolve(os.homedir(), PROFILE_PATH);
if (!fs.existsSync(configDir)) {
@ -34,7 +45,7 @@ const initClient = async (options: any) => {
}
let config: any = {};
const configFilename = `${options.profile}.json`;
const configFilename = `${profile}.json`;
const configFilePath = path.resolve(configDir, configFilename);
if (fs.existsSync(configFilePath)) {
@ -94,7 +105,7 @@ const initClient = async (options: any) => {
};
// Start Client
const initStartClient = async (options: Options) => {
public initStartClient = async (options: Options) => {
// Please change this if your domain goes wrong here
// Current style using sub-domain: https://{{clientId}}-tunnel.myhostingdomain.com
// (Original server: https://tunnel.myhostingdomain.com)
@ -113,7 +124,7 @@ const initStartClient = async (options: Options) => {
const defaultParams = {
apiKey: options.apiKey,
clientId: options.clientId,
profile: options.profile,
profile: profile,
clientIdSub: clientIdSub,
clientEndpoint: clientEndpoint,
serverUrl: serverUrl,
@ -128,6 +139,7 @@ const initStartClient = async (options: Options) => {
platform: os.platform(),
arch: os.arch(),
release: os.release(),
timestamp: new Date().getTime(),
};
const initParams: any = {
@ -151,16 +163,16 @@ const initStartClient = async (options: Options) => {
// Connecting to socket server and agent here...
console.log(`client connecting to server: ${serverUrl}`);
socket = io(serverUrl, initParams);
this.socket = io(serverUrl, initParams);
const clientLogPrefix = `client: ${clientId} on profile: ${profile}`;
socket.on("connect", () => {
if (socket!.connected) {
this.socket.on("connect", () => {
if (this.socket!.connected) {
console.log(`${clientLogPrefix} is connected to server successfully!`);
}
});
socket.on("connect_error", (e) => {
this.socket.on("connect_error", (e) => {
console.error(
`${clientLogPrefix} connect error:`,
(e && e.message) || "something wrong"
@ -170,17 +182,17 @@ const initStartClient = async (options: Options) => {
}
});
socket.on("disconnect", (reason) => {
this.socket.on("disconnect", (reason) => {
console.warn(`${clientLogPrefix} disconnected: ${reason}!`);
});
socket.on("disconnect_exit", (reason) => {
this.socket.on("disconnect_exit", (reason) => {
console.warn(`${clientLogPrefix} disconnected and exited ${reason}!`);
socket?.disconnect();
this.socket?.disconnect();
process.exit(1);
});
socket.on("request", (requestId, request) => {
this.socket.on("request", (requestId, request) => {
const isWebSocket = request.headers.upgrade === "websocket";
console.log(`${isWebSocket ? "WS" : request.method}: `, request.path);
request.port = options.port;
@ -190,7 +202,7 @@ const initStartClient = async (options: Options) => {
request.headers.host = options.origin;
}
const tunnelRequest = new TunnelRequest(socket!, requestId);
const tunnelRequest = new TunnelRequest(this.socket!, requestId);
const localReq = http.request(request);
tunnelRequest.pipe(localReq);
@ -215,7 +227,7 @@ const initStartClient = async (options: Options) => {
return;
}
const tunnelResponse = new TunnelResponse(socket!, requestId);
const tunnelResponse = new TunnelResponse(this.socket!, requestId);
tunnelResponse.writeHead(
localRes.statusCode,
@ -230,7 +242,7 @@ const initStartClient = async (options: Options) => {
const onLocalError = (error: any) => {
console.error("local error:", error);
localReq.off("response", onLocalResponse);
socket?.emit("request-error", requestId, error && error.message);
this.socket?.emit("request-error", requestId, error && error.message);
tunnelRequest.destroy(error);
};
@ -238,7 +250,7 @@ const initStartClient = async (options: Options) => {
// localSocket.once('error', onTunnelRequestError);
if (localHead && localHead.length) localSocket.unshift(localHead);
const tunnelResponse = new TunnelResponse(socket!, requestId, true);
const tunnelResponse = new TunnelResponse(this.socket!, requestId, true);
tunnelResponse.writeHead(null, null, localRes.headers);
localSocket.pipe(tunnelResponse).pipe(localSocket);
};
@ -263,10 +275,10 @@ const initStartClient = async (options: Options) => {
// };
// socket.io.on("close", tryReconnect);
keepAlive();
this.keepAlive();
};
const startClient = (clientOptions: ClientOptions) => {
public start = async (clientOptions: ClientOptions): Promise<Stoppable | undefined> => {
const { port, options = {} } = clientOptions;
const configDir = path.resolve(os.homedir(), PROFILE_PATH);
@ -277,6 +289,7 @@ const startClient = (clientOptions: ClientOptions) => {
let config: any = {};
const configFilename = `${options.profile || PROFILE_DEFAULT}.json`;
const configFilePath = path.resolve(configDir, configFilename);
console.log(`config file: ${configFilePath}`);
if (fs.existsSync(configFilePath)) {
config = JSON.parse(fs.readFileSync(configFilePath, "utf8"));
@ -315,22 +328,26 @@ const startClient = (clientOptions: ClientOptions) => {
options.suffix = generateUUID();
}
initStartClient(options);
await this.initStartClient(options);
console.log("client started!");
return this;
};
const stopClient = () => {
if (socket) {
socket.disconnect();
socket.close();
socket = null;
keepAliveTimer && clearInterval(keepAliveTimer);
public stop = () => {
if (this.socket) {
this.socket.disconnect();
this.socket.close();
this.socket = null;
this.keepAliveTimer && clearInterval(this.keepAliveTimer);
console.log("client stopped");
console.log("client stopped!");
}
};
}
export {
initClient,
startClient,
stopClient,
};
export const client = new HttpTunnelClient();
export const initConfigFileClient = client.initConfigFile;
export const startClient = client.start;
export const stopClient = client.stop;

View File

@ -2,10 +2,12 @@ import { Argument, InvalidArgumentError, program } from "commander";
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import { initClient, startClient } from "./api";
import { initConfigFileClient, startClient } from "./api";
import { PROFILE_DEFAULT, PROFILE_PATH, SERVER_DEFAULT_URL, TOKEN_FREE } from "./constant";
import { createProxyServer } from "./proxy";
import { createProxyServer as createProxyTCPServer } from "./proxy_tcp";
import { getTokenFree } from './sdk';
import { generateUUID } from "./util";
import { generateUUID, isValidHost, isValidUrl } from "./util";
const packageInfo = require("../package.json");
@ -35,7 +37,7 @@ program
.option("-p --profile <string>", "setting profile name", PROFILE_DEFAULT)
.option("-f --force", "force to generate new client and token", false)
.action(async (options) => {
initClient(options);
initConfigFileClient(options);
});
// start
@ -211,4 +213,92 @@ program
}
});
// proxy
program
.command("proxy")
.description("start a proxy server with specific port")
.argument("<port>", "local server port number", (value) => {
const port = parseInt(value, 10);
if (isNaN(port)) {
throw new InvalidArgumentError("Not a number.");
}
return port;
})
.argument("<target>", "target server url (https://google.com) or tcp (tcp://127.0.0.1:8080 or 127.0.0.1:8080)", (value) => {
// Validate target
if (!value) {
throw new InvalidArgumentError("Target is required.");
}
// Check if target is url
if (value.indexOf("http") === 0 || value.indexOf("https") === 0) {
if (isValidUrl(value)) {
return value;
}
throw new InvalidArgumentError("Target is not a valid url.");
}
if (value.indexOf("tcp") === 0) {
// Remove tcp prefix from target
const t = value.substring(6); // remove tcp prefix (tcp://)
if (isValidHost(t)) {
return value;
}
throw new InvalidArgumentError("Target is not a valid tcp host.");
}
// Check if target is host with port (tcp)
const target = value.split(":");
if (target.length === 2) {
const port = parseInt(target[1], 10);
if (isNaN(port)) {
throw new InvalidArgumentError("Target port is not a number.");
}
return `tcp://${value}`;
}
if (isValidHost(value)) {
return `tcp://${value}`
}
throw new InvalidArgumentError("Target is not a url or host with port.");
})
.action((port, target) => {
const isTcp = target.indexOf("tcp") === 0;
if (isTcp) {
console.log("[TCP] Start proxy server with port:", port, "and target:", target);
const t = target.substring(6); // remove tcp prefix (tcp://)
const targetHost = t.split(":")[0];
const targetPort = parseInt(t.split(":")[1], 10);
const proxy = createProxyTCPServer(targetHost, targetPort, {
proxyPort: port,
});
proxy.on("error", (err) => {
console.error("Proxy server error:", err);
});
proxy.on("close", () => {
console.log("Proxy server closed");
});
} else {
console.log("[HTTP/HTTPS] Start proxy server with port:", port, "and target:", target);
const proxy = createProxyServer(target, {
proxyPort: port,
});
proxy.on("error", (err) => {
console.error("Proxy server error:", err);
});
proxy.on("close", () => {
console.log("Proxy server closed");
});
}
});
program.parse();

View File

@ -1,9 +0,0 @@
import { startClient, stopClient } from './api';
startClient({
port: 3001,
});
setTimeout(() => {
stopClient();
}, 5000);

View File

@ -16,4 +16,49 @@ const generateUUID = () => {
return crypto.randomUUID();
};
export const isValidUrl = (url: string) => {
try {
new URL(url);
return true;
} catch (err) {
return false;
}
};
export const isValidIP = (ip: string) => {
const regex = new RegExp(
"^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\.|$)){4}$"
);
return regex.test(ip);
};
export const isValidHostname = (hostname: string) => {
const regex = new RegExp(
"^(?:(?:(?:xn--)?[a-z0-9]+(?:-[a-z0-9]+)*\\.?)+(?:(?:[a-z]{2,}\\.)?[a-z]{2,})|localhost)$",
"i"
);
return regex.test(hostname) || isValidIP(hostname);
};
export const isValidPort = (port: number) => {
return port > 0 && port < 65536;
};
export const isValidHost = (host: string) => {
const [hostname, port] = host.split(":");
return isValidHostname(hostname) && isValidPort(parseInt(port, 10));
};
export const isValidTarget = (target: string) => {
if (isValidUrl(target)) {
return true;
}
if (isValidHost(target)) {
return true;
}
return false;
};
export { addPrefixOnHttpSchema, generateUUID };

View File

@ -9,6 +9,8 @@
"outDir": "dist",
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
"skipLibCheck": true,
"esModuleInterop": true
},
"exclude": ["node_modules", "dist", "test", "src/**/*.spec.ts"]
}