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: strategy:
matrix: 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/ # See supported Node.js release schedule at https://nodejs.org/en/about/releases/
steps: steps:
@ -26,5 +26,5 @@ jobs:
with: with:
node-version: ${{ matrix.node-version }} node-version: ${{ matrix.node-version }}
cache: 'npm' cache: 'npm'
- run: npm i && npm ci - run: npm ci
- run: npm run build --if-present - run: npm run build --if-present

View File

@ -1,33 +1,8 @@
### 27/07/2023 (1.0.10) ### 11/07/2023
- 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)
- Support Client API - Support Client API
- Support Proxy (HTTP/HTTPS) and TCP - Support Proxy (HTTP/HTTPS) and TCP
- Improvements and Bugs fixed - Improvements and Bugs fixed
- Support auto proxy with hlt client
### 30/11/2022 ### 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", "name": "@cubetiq/hlt",
"version": "0.1.10", "version": "0.1.6",
"description": "A lightweight http tunnel client using nodejs and socket.io client", "description": "A lightweight http tunnel client using nodejs and socket.io client",
"main": "dist/cli.js", "main": "dist/cli.js",
"bin": { "bin": {
@ -8,9 +8,9 @@
}, },
"scripts": { "scripts": {
"start": "ts-node-dev --respawn --transpile-only src/cli.ts", "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", "local": "ts-node-dev --respawn --transpile-only src/cli.ts start -p local",
"build": "rimraf dist && tsc" "build": "tsc"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
@ -24,10 +24,10 @@
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"axios": "^1.2.0", "axios": "^1.2.0",
"commander": "^11.0.0", "commander": "^9.3.0",
"express": "^4.18.2", "express": "^4.18.2",
"http-proxy-middleware": "^2.0.6", "http-proxy-middleware": "^2.0.6",
"https-proxy-agent": "^7.0.0", "https-proxy-agent": "^5.0.1",
"socket.io-client": "^4.5.1" "socket.io-client": "^4.5.1"
}, },
"publishConfig": { "publishConfig": {
@ -35,9 +35,8 @@
}, },
"devDependencies": { "devDependencies": {
"@types/express": "^4.17.15", "@types/express": "^4.17.15",
"@types/node": "^20.0.0", "@types/node": "^18.0.3",
"rimraf": "^5.0.1",
"ts-node-dev": "^2.0.0", "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 { ClientOptions, Options } from "./interface";
import { getTokenFree } from './sdk'; import { getTokenFree } from './sdk';
interface Client { interface Stoppable {
getEndpoint(): string | null;
stop(): void; stop(): void;
} }
class HttpTunnelClient implements Client { class HttpTunnelClient implements Stoppable {
// create socket instance // create socket instance
private socket: Socket | null = null; private socket: Socket | null = null;
private keepAliveTimer: NodeJS.Timeout | null = null; private keepAliveTimer: NodeJS.Timeout | null = null;
private keepAliveTimeout: number | null = null; private keepAliveTimeout: number | null = null;
private endpoint: string | null = null;
private keepAlive() { private keepAlive() {
if (!this.socket) { if (!this.socket) {
@ -121,7 +119,6 @@ class HttpTunnelClient implements Client {
.toLowerCase() .toLowerCase()
.trim(); .trim();
const serverUrl = addPrefixOnHttpSchema(options.server || SERVER_DEFAULT_URL, clientEndpoint); 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) // extra options for socket to identify the client (authentication and options of tunnel)
const defaultParams = { const defaultParams = {
@ -281,50 +278,8 @@ class HttpTunnelClient implements Client {
this.keepAlive(); this.keepAlive();
}; };
public start = async (clientOptions: Partial<ClientOptions>): Promise<Client | undefined> => { public start = async (clientOptions: ClientOptions): Promise<Stoppable | undefined> => {
const { port, address, options = {} } = clientOptions; const { port, 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`);
}
}
const configDir = path.resolve(os.homedir(), PROFILE_PATH); const configDir = path.resolve(os.homedir(), PROFILE_PATH);
if (!fs.existsSync(configDir)) { if (!fs.existsSync(configDir)) {
@ -334,6 +289,7 @@ class HttpTunnelClient implements Client {
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"));
@ -357,7 +313,7 @@ class HttpTunnelClient implements Client {
return; return;
} }
// options.port = port; options.port = port;
options.token = config.token; options.token = config.token;
options.access = config.access; options.access = config.access;
options.server = config.server; options.server = config.server;
@ -373,6 +329,8 @@ class HttpTunnelClient implements Client {
} }
await this.initStartClient(options); await this.initStartClient(options);
console.log("client started!");
return this; return this;
}; };
@ -383,13 +341,9 @@ class HttpTunnelClient implements Client {
this.socket = null; this.socket = null;
this.keepAliveTimer && clearInterval(this.keepAliveTimer); 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(); export const client = new HttpTunnelClient();

View File

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

View File

@ -17,6 +17,5 @@ export interface Options {
export interface ClientOptions { export interface ClientOptions {
port: number; port: number;
address?: string; // e.g. localhost:8081 (take if port is not set)
options?: Options; 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 getTokenFree = async (baseUrl: string, data: any = {}) => {
const url = `${baseUrl}/__free__/api/get_token`; const url = `${baseUrl}/__free__/api/get_token`;

View File

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