Add support client API and support proxy http/https and tcp
This commit is contained in:
parent
afbf3097f1
commit
9f61c8aebf
@ -1,2 +1,3 @@
|
|||||||
src/
|
src/
|
||||||
.github/
|
.github/
|
||||||
|
test/
|
@ -1,3 +1,9 @@
|
|||||||
|
### 11/07/2023
|
||||||
|
|
||||||
|
- Support Client API
|
||||||
|
- Support Proxy (HTTP/HTTPS) and TCP
|
||||||
|
- Improvements and Bugs fixed
|
||||||
|
|
||||||
### 30/11/2022
|
### 30/11/2022
|
||||||
|
|
||||||
- Fixed response data in axios request with accept-encoding to identity
|
- Fixed response data in axios request with accept-encoding to identity
|
||||||
|
1333
package-lock.json
generated
1333
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -25,6 +25,8 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"axios": "^1.2.0",
|
"axios": "^1.2.0",
|
||||||
"commander": "^9.3.0",
|
"commander": "^9.3.0",
|
||||||
|
"express": "^4.18.2",
|
||||||
|
"http-proxy-middleware": "^2.0.6",
|
||||||
"https-proxy-agent": "^5.0.1",
|
"https-proxy-agent": "^5.0.1",
|
||||||
"socket.io-client": "^4.5.1"
|
"socket.io-client": "^4.5.1"
|
||||||
},
|
},
|
||||||
@ -32,6 +34,7 @@
|
|||||||
"access": "public"
|
"access": "public"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@types/express": "^4.17.15",
|
||||||
"@types/node": "^18.0.3",
|
"@types/node": "^18.0.3",
|
||||||
"ts-node-dev": "^2.0.0",
|
"ts-node-dev": "^2.0.0",
|
||||||
"typescript": "^4.7.4"
|
"typescript": "^4.7.4"
|
||||||
|
99
src/api.ts
99
src/api.ts
@ -11,21 +11,32 @@ import { PROFILE_DEFAULT, PROFILE_PATH, SERVER_DEFAULT_URL, TOKEN_FREE } from ".
|
|||||||
import { ClientOptions, Options } from "./interface";
|
import { ClientOptions, Options } from "./interface";
|
||||||
import { getTokenFree } from './sdk';
|
import { getTokenFree } from './sdk';
|
||||||
|
|
||||||
|
interface Stoppable {
|
||||||
|
stop(): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
class HttpTunnelClient implements Stoppable {
|
||||||
// create socket instance
|
// create socket instance
|
||||||
let socket: Socket | null = null;
|
private socket: Socket | null = null;
|
||||||
let keepAliveTimer: NodeJS.Timeout | null = null;
|
private keepAliveTimer: NodeJS.Timeout | null = null;
|
||||||
|
private keepAliveTimeout: number | null = null;
|
||||||
|
|
||||||
function keepAlive() {
|
private keepAlive() {
|
||||||
keepAliveTimer = setTimeout(() => {
|
if (!this.socket) {
|
||||||
if (socket && socket.connected) {
|
return;
|
||||||
socket.send("ping");
|
|
||||||
}
|
|
||||||
keepAlive();
|
|
||||||
}, 5000);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Init the Client
|
this.keepAliveTimer = setTimeout(() => {
|
||||||
const initClient = async (options: any) => {
|
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);
|
const configDir = path.resolve(os.homedir(), PROFILE_PATH);
|
||||||
|
|
||||||
if (!fs.existsSync(configDir)) {
|
if (!fs.existsSync(configDir)) {
|
||||||
@ -34,7 +45,7 @@ const initClient = async (options: any) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let config: any = {};
|
let config: any = {};
|
||||||
const configFilename = `${options.profile}.json`;
|
const configFilename = `${profile}.json`;
|
||||||
const configFilePath = path.resolve(configDir, configFilename);
|
const configFilePath = path.resolve(configDir, configFilename);
|
||||||
|
|
||||||
if (fs.existsSync(configFilePath)) {
|
if (fs.existsSync(configFilePath)) {
|
||||||
@ -94,7 +105,7 @@ const initClient = async (options: any) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Start Client
|
// Start Client
|
||||||
const initStartClient = async (options: Options) => {
|
public initStartClient = async (options: Options) => {
|
||||||
// Please change this if your domain goes wrong here
|
// Please change this if your domain goes wrong here
|
||||||
// Current style using sub-domain: https://{{clientId}}-tunnel.myhostingdomain.com
|
// Current style using sub-domain: https://{{clientId}}-tunnel.myhostingdomain.com
|
||||||
// (Original server: https://tunnel.myhostingdomain.com)
|
// (Original server: https://tunnel.myhostingdomain.com)
|
||||||
@ -113,7 +124,7 @@ const initStartClient = async (options: Options) => {
|
|||||||
const defaultParams = {
|
const defaultParams = {
|
||||||
apiKey: options.apiKey,
|
apiKey: options.apiKey,
|
||||||
clientId: options.clientId,
|
clientId: options.clientId,
|
||||||
profile: options.profile,
|
profile: profile,
|
||||||
clientIdSub: clientIdSub,
|
clientIdSub: clientIdSub,
|
||||||
clientEndpoint: clientEndpoint,
|
clientEndpoint: clientEndpoint,
|
||||||
serverUrl: serverUrl,
|
serverUrl: serverUrl,
|
||||||
@ -128,6 +139,7 @@ const initStartClient = async (options: Options) => {
|
|||||||
platform: os.platform(),
|
platform: os.platform(),
|
||||||
arch: os.arch(),
|
arch: os.arch(),
|
||||||
release: os.release(),
|
release: os.release(),
|
||||||
|
timestamp: new Date().getTime(),
|
||||||
};
|
};
|
||||||
|
|
||||||
const initParams: any = {
|
const initParams: any = {
|
||||||
@ -151,16 +163,16 @@ const initStartClient = async (options: Options) => {
|
|||||||
|
|
||||||
// Connecting to socket server and agent here...
|
// Connecting to socket server and agent here...
|
||||||
console.log(`client connecting to server: ${serverUrl}`);
|
console.log(`client connecting to server: ${serverUrl}`);
|
||||||
socket = io(serverUrl, initParams);
|
this.socket = io(serverUrl, initParams);
|
||||||
|
|
||||||
const clientLogPrefix = `client: ${clientId} on profile: ${profile}`;
|
const clientLogPrefix = `client: ${clientId} on profile: ${profile}`;
|
||||||
socket.on("connect", () => {
|
this.socket.on("connect", () => {
|
||||||
if (socket!.connected) {
|
if (this.socket!.connected) {
|
||||||
console.log(`${clientLogPrefix} is connected to server successfully!`);
|
console.log(`${clientLogPrefix} is connected to server successfully!`);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
socket.on("connect_error", (e) => {
|
this.socket.on("connect_error", (e) => {
|
||||||
console.error(
|
console.error(
|
||||||
`${clientLogPrefix} connect error:`,
|
`${clientLogPrefix} connect error:`,
|
||||||
(e && e.message) || "something wrong"
|
(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}!`);
|
console.warn(`${clientLogPrefix} disconnected: ${reason}!`);
|
||||||
});
|
});
|
||||||
|
|
||||||
socket.on("disconnect_exit", (reason) => {
|
this.socket.on("disconnect_exit", (reason) => {
|
||||||
console.warn(`${clientLogPrefix} disconnected and exited ${reason}!`);
|
console.warn(`${clientLogPrefix} disconnected and exited ${reason}!`);
|
||||||
socket?.disconnect();
|
this.socket?.disconnect();
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
socket.on("request", (requestId, request) => {
|
this.socket.on("request", (requestId, request) => {
|
||||||
const isWebSocket = request.headers.upgrade === "websocket";
|
const isWebSocket = request.headers.upgrade === "websocket";
|
||||||
console.log(`${isWebSocket ? "WS" : request.method}: `, request.path);
|
console.log(`${isWebSocket ? "WS" : request.method}: `, request.path);
|
||||||
request.port = options.port;
|
request.port = options.port;
|
||||||
@ -190,7 +202,7 @@ const initStartClient = async (options: Options) => {
|
|||||||
request.headers.host = options.origin;
|
request.headers.host = options.origin;
|
||||||
}
|
}
|
||||||
|
|
||||||
const tunnelRequest = new TunnelRequest(socket!, requestId);
|
const tunnelRequest = new TunnelRequest(this.socket!, requestId);
|
||||||
|
|
||||||
const localReq = http.request(request);
|
const localReq = http.request(request);
|
||||||
tunnelRequest.pipe(localReq);
|
tunnelRequest.pipe(localReq);
|
||||||
@ -215,7 +227,7 @@ const initStartClient = async (options: Options) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const tunnelResponse = new TunnelResponse(socket!, requestId);
|
const tunnelResponse = new TunnelResponse(this.socket!, requestId);
|
||||||
|
|
||||||
tunnelResponse.writeHead(
|
tunnelResponse.writeHead(
|
||||||
localRes.statusCode,
|
localRes.statusCode,
|
||||||
@ -230,7 +242,7 @@ const initStartClient = async (options: Options) => {
|
|||||||
const onLocalError = (error: any) => {
|
const onLocalError = (error: any) => {
|
||||||
console.error("local error:", error);
|
console.error("local error:", error);
|
||||||
localReq.off("response", onLocalResponse);
|
localReq.off("response", onLocalResponse);
|
||||||
socket?.emit("request-error", requestId, error && error.message);
|
this.socket?.emit("request-error", requestId, error && error.message);
|
||||||
tunnelRequest.destroy(error);
|
tunnelRequest.destroy(error);
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -238,7 +250,7 @@ const initStartClient = async (options: Options) => {
|
|||||||
// localSocket.once('error', onTunnelRequestError);
|
// localSocket.once('error', onTunnelRequestError);
|
||||||
if (localHead && localHead.length) localSocket.unshift(localHead);
|
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);
|
tunnelResponse.writeHead(null, null, localRes.headers);
|
||||||
localSocket.pipe(tunnelResponse).pipe(localSocket);
|
localSocket.pipe(tunnelResponse).pipe(localSocket);
|
||||||
};
|
};
|
||||||
@ -263,10 +275,10 @@ const initStartClient = async (options: Options) => {
|
|||||||
// };
|
// };
|
||||||
// socket.io.on("close", tryReconnect);
|
// 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 { port, options = {} } = clientOptions;
|
||||||
const configDir = path.resolve(os.homedir(), PROFILE_PATH);
|
const configDir = path.resolve(os.homedir(), PROFILE_PATH);
|
||||||
|
|
||||||
@ -277,6 +289,7 @@ const startClient = (clientOptions: ClientOptions) => {
|
|||||||
let config: any = {};
|
let config: any = {};
|
||||||
const configFilename = `${options.profile || PROFILE_DEFAULT}.json`;
|
const configFilename = `${options.profile || PROFILE_DEFAULT}.json`;
|
||||||
const configFilePath = path.resolve(configDir, configFilename);
|
const configFilePath = path.resolve(configDir, configFilename);
|
||||||
|
console.log(`config file: ${configFilePath}`);
|
||||||
|
|
||||||
if (fs.existsSync(configFilePath)) {
|
if (fs.existsSync(configFilePath)) {
|
||||||
config = JSON.parse(fs.readFileSync(configFilePath, "utf8"));
|
config = JSON.parse(fs.readFileSync(configFilePath, "utf8"));
|
||||||
@ -315,22 +328,26 @@ const startClient = (clientOptions: ClientOptions) => {
|
|||||||
options.suffix = generateUUID();
|
options.suffix = generateUUID();
|
||||||
}
|
}
|
||||||
|
|
||||||
initStartClient(options);
|
await this.initStartClient(options);
|
||||||
|
console.log("client started!");
|
||||||
|
|
||||||
|
return this;
|
||||||
};
|
};
|
||||||
|
|
||||||
const stopClient = () => {
|
public stop = () => {
|
||||||
if (socket) {
|
if (this.socket) {
|
||||||
socket.disconnect();
|
this.socket.disconnect();
|
||||||
socket.close();
|
this.socket.close();
|
||||||
socket = null;
|
this.socket = null;
|
||||||
keepAliveTimer && clearInterval(keepAliveTimer);
|
this.keepAliveTimer && clearInterval(this.keepAliveTimer);
|
||||||
|
|
||||||
console.log("client stopped");
|
console.log("client stopped!");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export {
|
export const client = new HttpTunnelClient();
|
||||||
initClient,
|
|
||||||
startClient,
|
export const initConfigFileClient = client.initConfigFile;
|
||||||
stopClient,
|
export const startClient = client.start;
|
||||||
};
|
export const stopClient = client.stop;
|
96
src/cli.ts
96
src/cli.ts
@ -2,10 +2,12 @@ import { Argument, InvalidArgumentError, program } from "commander";
|
|||||||
import * as fs from "fs";
|
import * as fs from "fs";
|
||||||
import * as os from "os";
|
import * as os from "os";
|
||||||
import * as path from "path";
|
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 { 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 { getTokenFree } from './sdk';
|
||||||
import { generateUUID } from "./util";
|
import { generateUUID, isValidHost, isValidUrl } from "./util";
|
||||||
|
|
||||||
const packageInfo = require("../package.json");
|
const packageInfo = require("../package.json");
|
||||||
|
|
||||||
@ -35,7 +37,7 @@ program
|
|||||||
.option("-p --profile <string>", "setting profile name", PROFILE_DEFAULT)
|
.option("-p --profile <string>", "setting profile name", PROFILE_DEFAULT)
|
||||||
.option("-f --force", "force to generate new client and token", false)
|
.option("-f --force", "force to generate new client and token", false)
|
||||||
.action(async (options) => {
|
.action(async (options) => {
|
||||||
initClient(options);
|
initConfigFileClient(options);
|
||||||
});
|
});
|
||||||
|
|
||||||
// start
|
// 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();
|
program.parse();
|
||||||
|
@ -1,9 +0,0 @@
|
|||||||
import { startClient, stopClient } from './api';
|
|
||||||
|
|
||||||
startClient({
|
|
||||||
port: 3001,
|
|
||||||
});
|
|
||||||
|
|
||||||
setTimeout(() => {
|
|
||||||
stopClient();
|
|
||||||
}, 5000);
|
|
45
src/util.ts
45
src/util.ts
@ -16,4 +16,49 @@ const generateUUID = () => {
|
|||||||
return crypto.randomUUID();
|
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 };
|
export { addPrefixOnHttpSchema, generateUUID };
|
||||||
|
@ -9,6 +9,8 @@
|
|||||||
"outDir": "dist",
|
"outDir": "dist",
|
||||||
"forceConsistentCasingInFileNames": true,
|
"forceConsistentCasingInFileNames": true,
|
||||||
"strict": true,
|
"strict": true,
|
||||||
"skipLibCheck": true
|
"skipLibCheck": true,
|
||||||
}
|
"esModuleInterop": true
|
||||||
|
},
|
||||||
|
"exclude": ["node_modules", "dist", "test", "src/**/*.spec.ts"]
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user