Compare commits

..

No commits in common. "main" and "hlt-api" have entirely different histories.

11 changed files with 1352 additions and 768 deletions

View File

@ -16,7 +16,7 @@ jobs:
strategy:
matrix:
node-version: [14.x, 16.x, 18.x, 20.x]
node-version: [12.x, 14.x, 16.x]
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/
steps:
@ -26,5 +26,5 @@ jobs:
with:
node-version: ${{ matrix.node-version }}
cache: 'npm'
- run: npm i && npm ci
- run: npm ci
- run: npm run build --if-present

View File

@ -1,33 +1,8 @@
### 27/07/2023 (1.0.10)
- Add list profiles
### 14/07/2023 (1.0.9)
- Fixed the start with port unable to start
### 11/07/2023 (1.0.8)
- Support tunnel with host with port
* Prev
```
hlt start 8080 -h 192.168.1.1
```
- New
```
hlt start 192.168.1.1:8080
```
### 11/07/2023 (1.0.7)
### 11/07/2023
- Support Client API
- Support Proxy (HTTP/HTTPS) and TCP
- Improvements and Bugs fixed
- Support auto proxy with hlt client
### 30/11/2022

1903
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
{
"name": "@cubetiq/hlt",
"version": "0.1.10",
"version": "0.1.6",
"description": "A lightweight http tunnel client using nodejs and socket.io client",
"main": "dist/cli.js",
"bin": {
@ -8,9 +8,9 @@
},
"scripts": {
"start": "ts-node-dev --respawn --transpile-only src/cli.ts",
"test": "ts-node-dev --respawn --transpile-only test/test.ts",
"test": "ts-node-dev --respawn --transpile-only src/test.ts",
"local": "ts-node-dev --respawn --transpile-only src/cli.ts start -p local",
"build": "rimraf dist && tsc"
"build": "tsc"
},
"repository": {
"type": "git",
@ -24,10 +24,10 @@
"license": "ISC",
"dependencies": {
"axios": "^1.2.0",
"commander": "^11.0.0",
"commander": "^9.3.0",
"express": "^4.18.2",
"http-proxy-middleware": "^2.0.6",
"https-proxy-agent": "^7.0.0",
"https-proxy-agent": "^5.0.1",
"socket.io-client": "^4.5.1"
},
"publishConfig": {
@ -35,9 +35,8 @@
},
"devDependencies": {
"@types/express": "^4.17.15",
"@types/node": "^20.0.0",
"rimraf": "^5.0.1",
"@types/node": "^18.0.3",
"ts-node-dev": "^2.0.0",
"typescript": "^5.0.0"
"typescript": "^4.7.4"
}
}

View File

@ -1,6 +0,0 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": [
"config:base"
]
}

View File

@ -11,17 +11,15 @@ import { PROFILE_DEFAULT, PROFILE_PATH, SERVER_DEFAULT_URL, TOKEN_FREE } from ".
import { ClientOptions, Options } from "./interface";
import { getTokenFree } from './sdk';
interface Client {
getEndpoint(): string | null;
interface Stoppable {
stop(): void;
}
class HttpTunnelClient implements Client {
class HttpTunnelClient implements Stoppable {
// create socket instance
private socket: Socket | null = null;
private keepAliveTimer: NodeJS.Timeout | null = null;
private keepAliveTimeout: number | null = null;
private endpoint: string | null = null;
private keepAlive() {
if (!this.socket) {
@ -121,7 +119,6 @@ class HttpTunnelClient implements Client {
.toLowerCase()
.trim();
const serverUrl = addPrefixOnHttpSchema(options.server || SERVER_DEFAULT_URL, clientEndpoint);
this.endpoint = serverUrl
// extra options for socket to identify the client (authentication and options of tunnel)
const defaultParams = {
@ -281,50 +278,8 @@ class HttpTunnelClient implements Client {
this.keepAlive();
};
public start = async (clientOptions: Partial<ClientOptions>): Promise<Client | undefined> => {
const { port, address, options = {} } = clientOptions;
// Load host and port check
if (!port) {
if (!address) {
console.error("port or address is required!");
return;
}
const [host, portStr] = address.split(":");
if (!host || !portStr) {
console.error("invalid address!");
return;
}
options.host = host;
try {
options.port = parseInt(portStr);
} catch (e) {
console.error("invalid port!");
return;
}
} else {
if (typeof address !== "number" && address && address.includes(":")) {
const [host, portStr] = address.split(":");
if (host) {
options.host = host;
}
if (portStr) {
try {
options.port = parseInt(portStr);
console.log(`default port: ${port} will be ignored and override by port: ${options.port}`);
} catch (e) {
options.port = port;
}
}
} else {
options.port = port;
console.log(`default port: ${port} will be forwared`);
}
}
public start = async (clientOptions: ClientOptions): Promise<Stoppable | undefined> => {
const { port, options = {} } = clientOptions;
const configDir = path.resolve(os.homedir(), PROFILE_PATH);
if (!fs.existsSync(configDir)) {
@ -334,6 +289,7 @@ class HttpTunnelClient implements Client {
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"));
@ -357,7 +313,7 @@ class HttpTunnelClient implements Client {
return;
}
// options.port = port;
options.port = port;
options.token = config.token;
options.access = config.access;
options.server = config.server;
@ -373,6 +329,8 @@ class HttpTunnelClient implements Client {
}
await this.initStartClient(options);
console.log("client started!");
return this;
};
@ -383,13 +341,9 @@ class HttpTunnelClient implements Client {
this.socket = null;
this.keepAliveTimer && clearInterval(this.keepAliveTimer);
console.log("client stopped from server:", this.endpoint);
console.log("client stopped!");
}
};
public getEndpoint = () => {
return this.endpoint;
}
}
export const client = new HttpTunnelClient();

View File

@ -4,7 +4,6 @@ import * as os from "os";
import * as path from "path";
import { initConfigFileClient, startClient } from "./api";
import { PROFILE_DEFAULT, PROFILE_PATH, SERVER_DEFAULT_URL, TOKEN_FREE } from "./constant";
import { listProfile } from "./manage";
import { createProxyServer } from "./proxy";
import { createProxyServer as createProxyTCPServer } from "./proxy_tcp";
import { getTokenFree } from './sdk';
@ -23,20 +22,20 @@ program
program
.command("init")
.description("generate a new client and token with free access")
.option("-s, --server <string>", "setting server url", SERVER_DEFAULT_URL)
.option("-s --server <string>", "setting server url", SERVER_DEFAULT_URL)
.option(
"-t, --token <string>",
"-t --token <string>",
"setting token (default generate FREE access token)",
""
)
.option("-a, --access <string>", "setting token access type", TOKEN_FREE)
.option("-c, --client <string>", "setting client (auto generate uuid)")
.option("-a --access <string>", "setting token access type", TOKEN_FREE)
.option("-c --client <string>", "setting client (auto generate uuid)")
.option(
"-k, --key <string>",
"-k --key <string>",
"setting client api key for authentication access"
)
.option("-p, --profile <string>", "setting profile name", PROFILE_DEFAULT)
.option("-f, --force", "force to generate new client and token", false)
.option("-p --profile <string>", "setting profile name", PROFILE_DEFAULT)
.option("-f --force", "force to generate new client and token", false)
.action(async (options) => {
initConfigFileClient(options);
});
@ -45,14 +44,10 @@ program
program
.command("start")
.description("start a connection with specific port")
.argument("<port> | <address>", "local server port number or address", (value) => {
if (isValidHost(value)) {
return value;
}
.argument("<port>", "local server port number", (value) => {
const port = parseInt(value, 10);
if (isNaN(port)) {
throw new InvalidArgumentError("Not a number or valid address.");
throw new InvalidArgumentError("Not a number.");
}
return port;
})
@ -70,10 +65,9 @@ program
.option("-p, --profile <string>", "profile name", PROFILE_DEFAULT)
.option("-h, --host <string>", "local host value", "localhost")
.option("-o, --origin <string>", "change request origin")
.action((portOrAddress, options) => {
.action((port, options) => {
startClient({
port: portOrAddress,
address: portOrAddress,
port,
options,
})
});
@ -92,7 +86,7 @@ program
])
)
.argument("<value>", "config value")
.option("-p, --profile <string>", "setting profile name", PROFILE_DEFAULT)
.option("-p --profile <string>", "setting profile name", PROFILE_DEFAULT)
.action(async (type, value, options) => {
if (!type) {
console.error("type config is required!");
@ -180,7 +174,7 @@ program
"key",
])
)
.option("-p, --profile <string>", "setting profile name", PROFILE_DEFAULT)
.option("-p --profile <string>", "setting profile name", PROFILE_DEFAULT)
.action(async (type, options) => {
if (!type) {
console.error("type config is required!");
@ -272,8 +266,7 @@ program
throw new InvalidArgumentError("Target is not a url or host with port.");
})
.option("-p, --profile <string>", "setting profile name for connect with hlt server (proxy with current local port)")
.action((port, target, options) => {
.action((port, target) => {
const isTcp = target.indexOf("tcp") === 0;
if (isTcp) {
console.log("[TCP] Start proxy server with port:", port, "and target:", target);
@ -284,8 +277,6 @@ program
proxyPort: port,
});
onConnectProxy(port, options);
proxy.on("error", (err) => {
console.error("Proxy server error:", err);
});
@ -293,15 +284,12 @@ program
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,
});
onConnectProxy(port, options);
proxy.on("error", (err) => {
console.error("Proxy server error:", err);
});
@ -313,27 +301,4 @@ program
});
const onConnectProxy = (port: number, options: any) => {
if (options?.profile) {
console.log(`Start proxy: ${port} via hlt client with profile: ${options.profile}`);
startClient({
port,
options,
})
}
}
// profile
program
.command("profile")
.description("manage profile")
.option("-l, --list", "list all profiles", false)
.action((options) => {
if (options.list) {
listProfile();
} else {
console.log("profile command is required");
}
});
program.parse();

View File

@ -17,6 +17,5 @@ export interface Options {
export interface ClientOptions {
port: number;
address?: string; // e.g. localhost:8081 (take if port is not set)
options?: Options;
}

View File

@ -1,28 +0,0 @@
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import { PROFILE_DEFAULT, PROFILE_PATH } from "./constant";
export const listProfile = () => {
const configDir = path.resolve(os.homedir(), PROFILE_PATH);
if (!fs.existsSync(configDir)) {
console.log(`config file ${configDir} not found`);
return;
}
const configFiles = fs.readdirSync(configDir);
if (configFiles.length === 0) {
console.log(`config file ${configDir} not found`);
return;
}
console.log("List of profile:");
configFiles.forEach((file) => {
const configFilePath = path.resolve(configDir, file);
const config = JSON.parse(fs.readFileSync(configFilePath, "utf8"));
const name = file.replace(".json", "");
console.log(`- ${name} (${config.clientId})`);
});
console.log(`\nCurrent profile: ${PROFILE_DEFAULT}`);
}

View File

@ -1,4 +1,4 @@
import axios from "axios";
const axios = require("axios");
const getTokenFree = async (baseUrl: string, data: any = {}) => {
const url = `${baseUrl}/__free__/api/get_token`;

View File

@ -2,18 +2,15 @@ import { startClient } from '../src/api';
async function main() {
const client = await startClient({
// port: 8081,
address: '172.17.0.2:8222',
port: 3000,
options: {
profile: 'mytest',
},
});
console.log('Client started:', client?.getEndpoint());
setTimeout(async () => {
client?.stop();
}, 10000);
}, 5000);
}
main().catch((err) => {