@nora-link/client 1.0.7 → 1.0.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +9 -15
- package/package.json +1 -1
- package/.vscode/launch.json +0 -26
- package/dist/cli.d.ts +0 -2
- package/dist/client.d.ts +0 -27
- package/dist/client.js +0 -216
- package/dist/const.d.ts +0 -7
- package/dist/const.js +0 -10
- package/dist/index.d.ts +0 -2
- package/dist/logger.d.ts +0 -6
- package/dist/logger.js +0 -30
- package/src/cli.ts +0 -69
- package/src/client.ts +0 -311
- package/src/const.ts +0 -7
- package/src/index.ts +0 -3
- package/src/logger.ts +0 -34
- package/tsconfig.json +0 -23
package/dist/cli.js
CHANGED
|
@@ -21,8 +21,9 @@ commander_1.program
|
|
|
21
21
|
.requiredOption('-f, --forward <subdomain|label|url...>', 'Tunnel subdomain to local url. Label is optional')
|
|
22
22
|
.requiredOption('-k, --key <api-key>', 'Api Key')
|
|
23
23
|
.requiredOption('-h, --host <hostname>', 'Server host name', 'noralink.eu')
|
|
24
|
-
.addHelpText('afterAll', 'To tunnel a local port to the subdomain `test`, you can use `-f test
|
|
25
|
-
.addHelpText('afterAll', 'To tunnel an ip to the subdomain `test`, you can use `-f test|192.168.1.130`')
|
|
24
|
+
.addHelpText('afterAll', 'To tunnel a local port to the subdomain `test`, you can use `-f "test|localhost:3000"`')
|
|
25
|
+
.addHelpText('afterAll', 'To tunnel an ip to the subdomain `test`, you can use `-f "test|192.168.1.130"`')
|
|
26
|
+
.addHelpText('afterAll', 'To tunnel a local hostname to the subdomain `test` with label `My App`, you can use `-f "test|My App|local-host.local"`')
|
|
26
27
|
.parse();
|
|
27
28
|
const options = commander_1.program.opts();
|
|
28
29
|
let tunnels = [];
|
|
@@ -31,21 +32,14 @@ if (Array.isArray(options.forward)) {
|
|
|
31
32
|
.filter((v) => typeof v === 'string')
|
|
32
33
|
.map(v => {
|
|
33
34
|
const [segment, labelOrUrl, urlPart] = v.split('|');
|
|
34
|
-
let tunnelUrl;
|
|
35
35
|
const label = urlPart ? labelOrUrl : segment;
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
36
|
+
let url = urlPart ?? labelOrUrl;
|
|
37
|
+
const urlHasProtocol = /^https?:\/\//.test(url);
|
|
38
|
+
if (!urlHasProtocol) {
|
|
39
|
+
//if missing protocol, assume http
|
|
40
|
+
url = `http://${url}`;
|
|
39
41
|
}
|
|
40
|
-
|
|
41
|
-
//only port and/or path specified
|
|
42
|
-
const portAndPath = url.split(':')[1];
|
|
43
|
-
tunnelUrl = `http://localhost:${portAndPath}`;
|
|
44
|
-
}
|
|
45
|
-
else {
|
|
46
|
-
tunnelUrl = `http://${url}`;
|
|
47
|
-
}
|
|
48
|
-
return { remotePath: segment, url: tunnelUrl, label };
|
|
42
|
+
return { remotePath: segment, url, label };
|
|
49
43
|
});
|
|
50
44
|
}
|
|
51
45
|
if (!tunnels.length) {
|
package/package.json
CHANGED
package/.vscode/launch.json
DELETED
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"configurations": [
|
|
3
|
-
{
|
|
4
|
-
"type": "node",
|
|
5
|
-
"request": "launch",
|
|
6
|
-
"name": "Launch client",
|
|
7
|
-
"runtimeArgs": [
|
|
8
|
-
"--trace-warnings",
|
|
9
|
-
"-r",
|
|
10
|
-
"ts-node/register"
|
|
11
|
-
],
|
|
12
|
-
"args": [
|
|
13
|
-
"${workspaceFolder}/src/cli.ts",
|
|
14
|
-
"-f",
|
|
15
|
-
"dashboard|NR Dashboard|smarthome.local:1880/ui",
|
|
16
|
-
"-f",
|
|
17
|
-
"admin|NR Admin|smarthome.local:1880",
|
|
18
|
-
"-n",
|
|
19
|
-
"-h",
|
|
20
|
-
"noralink.localhost:3000",
|
|
21
|
-
"-k",
|
|
22
|
-
"your-own-key"
|
|
23
|
-
]
|
|
24
|
-
}
|
|
25
|
-
],
|
|
26
|
-
}
|
package/dist/cli.d.ts
DELETED
package/dist/client.d.ts
DELETED
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
import { Observable } from 'rxjs';
|
|
2
|
-
import WebSocket from 'ws';
|
|
3
|
-
import { Logger } from './logger';
|
|
4
|
-
export interface TunnelOptions {
|
|
5
|
-
remotePath: string;
|
|
6
|
-
url: string;
|
|
7
|
-
label: string;
|
|
8
|
-
removeHostHeader?: boolean;
|
|
9
|
-
}
|
|
10
|
-
export interface ClientConnectionOptions {
|
|
11
|
-
agent?: string;
|
|
12
|
-
hostname: string;
|
|
13
|
-
secure?: boolean;
|
|
14
|
-
apiKey: string;
|
|
15
|
-
tunnels: TunnelOptions[];
|
|
16
|
-
logger?: Logger;
|
|
17
|
-
}
|
|
18
|
-
export declare class Client {
|
|
19
|
-
private options;
|
|
20
|
-
constructor(options: ClientConnectionOptions);
|
|
21
|
-
private server$;
|
|
22
|
-
private data$;
|
|
23
|
-
readonly handle$: Observable<void | WebSocket>;
|
|
24
|
-
send(id: number, type: string, msg?: Buffer): Observable<void>;
|
|
25
|
-
private getStreamData;
|
|
26
|
-
private httpRequest;
|
|
27
|
-
}
|
package/dist/client.js
DELETED
|
@@ -1,216 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
-
};
|
|
5
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.Client = void 0;
|
|
7
|
-
const rxjs_1 = require("rxjs");
|
|
8
|
-
const ws_1 = __importDefault(require("ws"));
|
|
9
|
-
const node_http_1 = require("node:http");
|
|
10
|
-
const node_querystring_1 = require("node:querystring");
|
|
11
|
-
const const_1 = require("./const");
|
|
12
|
-
class Client {
|
|
13
|
-
constructor(options) {
|
|
14
|
-
this.options = options;
|
|
15
|
-
this.server$ = new rxjs_1.Observable(observer => {
|
|
16
|
-
const segments = this.options.tunnels.map(v => `${v.remotePath}|${v.label}`);
|
|
17
|
-
const qs = (0, node_querystring_1.stringify)({ s: segments });
|
|
18
|
-
this.options.logger?.info(`[nora-link] connecting`);
|
|
19
|
-
const protocol = this.options.secure ? 'wss' : 'ws';
|
|
20
|
-
const headers = {
|
|
21
|
-
authorization: `Bearer ${this.options.apiKey}`,
|
|
22
|
-
...(this.options.agent ? {
|
|
23
|
-
'user-agent': this.options.agent,
|
|
24
|
-
} : {}),
|
|
25
|
-
};
|
|
26
|
-
const ws = new ws_1.default(`${protocol}://${this.options.hostname}/api/tunnel?${qs}`, { headers });
|
|
27
|
-
ws.on('open', () => {
|
|
28
|
-
this.options.logger?.info(`[nora-link] connected`);
|
|
29
|
-
observer.next(ws);
|
|
30
|
-
});
|
|
31
|
-
ws.on('error', err => observer.error(err));
|
|
32
|
-
ws.on('close', () => observer.complete());
|
|
33
|
-
return () => ws.close();
|
|
34
|
-
}).pipe((0, rxjs_1.share)({ connector: () => new rxjs_1.ReplaySubject(1) }));
|
|
35
|
-
this.data$ = this.server$.pipe((0, rxjs_1.switchMap)(ws => new rxjs_1.Observable(observer => {
|
|
36
|
-
const handler = (msg) => {
|
|
37
|
-
Buffer.isBuffer(msg) && observer.next(msg);
|
|
38
|
-
};
|
|
39
|
-
ws.on('message', handler);
|
|
40
|
-
ws.once('error', err => observer.error(err));
|
|
41
|
-
ws.once('close', (code, reason) => {
|
|
42
|
-
observer.error(new Error(`${code} - ${reason.toString()}`));
|
|
43
|
-
});
|
|
44
|
-
return () => ws.off('message', handler);
|
|
45
|
-
})), (0, rxjs_1.map)(v => {
|
|
46
|
-
if (v.length >= 5) {
|
|
47
|
-
const id = v.readUint32BE();
|
|
48
|
-
const typeLength = v.readUint8(4);
|
|
49
|
-
const type = v.subarray(5, 5 + typeLength).toString();
|
|
50
|
-
return {
|
|
51
|
-
id,
|
|
52
|
-
type,
|
|
53
|
-
msg: v.subarray(5 + typeLength),
|
|
54
|
-
};
|
|
55
|
-
}
|
|
56
|
-
return null;
|
|
57
|
-
}), (0, rxjs_1.filter)(v => !!v), (0, rxjs_1.share)());
|
|
58
|
-
this.handle$ = (0, rxjs_1.merge)(this.server$, this.data$.pipe((0, rxjs_1.mergeMap)(({ id, msg, type }) => type === 'http' || type === 'ws'
|
|
59
|
-
? this.httpRequest({
|
|
60
|
-
type,
|
|
61
|
-
options: JSON.parse(msg.toString()),
|
|
62
|
-
data$: this.getStreamData(id),
|
|
63
|
-
send: (type, msg) => this.send(id, type, msg),
|
|
64
|
-
})
|
|
65
|
-
: rxjs_1.EMPTY))).pipe((0, rxjs_1.retry)({
|
|
66
|
-
resetOnSuccess: true,
|
|
67
|
-
delay: (err, retryCount) => {
|
|
68
|
-
const delaySeconds = Math.round(Math.min(300, Math.pow(1.8, retryCount + 3)));
|
|
69
|
-
this.options.logger?.trace(`[nora-link] connection error`, err);
|
|
70
|
-
this.options.logger?.error(`[nora-link] retrying in ${delaySeconds} sec`);
|
|
71
|
-
return (0, rxjs_1.timer)(delaySeconds * 1000);
|
|
72
|
-
},
|
|
73
|
-
}), (0, rxjs_1.share)());
|
|
74
|
-
}
|
|
75
|
-
send(id, type, msg) {
|
|
76
|
-
return this.server$.pipe((0, rxjs_1.first)(), (0, rxjs_1.switchMap)(ws => {
|
|
77
|
-
const header = Buffer.alloc(5);
|
|
78
|
-
const typeBuffer = Buffer.from(type);
|
|
79
|
-
header.writeUint32BE(id);
|
|
80
|
-
header.writeUint8(typeBuffer.length, 4);
|
|
81
|
-
const all = msg
|
|
82
|
-
? Buffer.concat([header, typeBuffer, msg])
|
|
83
|
-
: Buffer.concat([header, typeBuffer]);
|
|
84
|
-
return new rxjs_1.Observable(observer => {
|
|
85
|
-
ws.send(all, (err) => {
|
|
86
|
-
if (err)
|
|
87
|
-
observer.error(err);
|
|
88
|
-
else
|
|
89
|
-
observer.complete();
|
|
90
|
-
});
|
|
91
|
-
});
|
|
92
|
-
}));
|
|
93
|
-
}
|
|
94
|
-
getStreamData(id) {
|
|
95
|
-
return this.data$.pipe((0, rxjs_1.filter)((m) => m.id === id), (0, rxjs_1.map)(({ id, ...rest }) => rest));
|
|
96
|
-
}
|
|
97
|
-
httpRequest({ type, options, data$, send }) {
|
|
98
|
-
const { url, subdomain, method, headers } = options;
|
|
99
|
-
return new rxjs_1.Observable(reqObserver => {
|
|
100
|
-
this.options.logger?.trace(`[nora-link] START ${method} ${url}`);
|
|
101
|
-
const tunnel = this.options.tunnels.find(v => v.remotePath === subdomain);
|
|
102
|
-
if (!tunnel) {
|
|
103
|
-
throw new Error(`subdomain ${subdomain} not registered`);
|
|
104
|
-
}
|
|
105
|
-
if (tunnel.removeHostHeader ?? true) {
|
|
106
|
-
delete headers["host"];
|
|
107
|
-
}
|
|
108
|
-
const { hostname, port, pathname } = new URL(tunnel.url);
|
|
109
|
-
const req = (0, node_http_1.request)({
|
|
110
|
-
host: hostname,
|
|
111
|
-
port: port,
|
|
112
|
-
path: pathname === '/' ? url : `${pathname}${url}`,
|
|
113
|
-
method,
|
|
114
|
-
headers,
|
|
115
|
-
});
|
|
116
|
-
req.on('error', (err) => reqObserver.error(err));
|
|
117
|
-
if (type === 'ws') {
|
|
118
|
-
req.flushHeaders();
|
|
119
|
-
const handleUpgrade$ = new rxjs_1.Observable(observer => {
|
|
120
|
-
const handler = (res, socket) => {
|
|
121
|
-
observer.next({ res, socket });
|
|
122
|
-
observer.complete();
|
|
123
|
-
};
|
|
124
|
-
req.once('upgrade', handler);
|
|
125
|
-
return () => req.off('upgrade', handler);
|
|
126
|
-
}).pipe((0, rxjs_1.concatMap)(({ res, socket }) => {
|
|
127
|
-
const tx$ = new rxjs_1.Observable(observer => {
|
|
128
|
-
const head = [
|
|
129
|
-
`HTTP/${res.httpVersion} ${res.statusCode} ${res.statusMessage}`,
|
|
130
|
-
...(Object.entries(res.headers).map(([k, v]) => `${k}: ${v}`)),
|
|
131
|
-
'',
|
|
132
|
-
'',
|
|
133
|
-
].join('\r\n');
|
|
134
|
-
observer.next(send(const_1.MessageTypes.DATA, Buffer.from(head)));
|
|
135
|
-
socket.on('data', data => {
|
|
136
|
-
observer.next(send(const_1.MessageTypes.DATA, data));
|
|
137
|
-
});
|
|
138
|
-
socket.once('end', () => {
|
|
139
|
-
observer.next(send(const_1.MessageTypes.END));
|
|
140
|
-
//TODO: don't really like this:
|
|
141
|
-
reqObserver.complete();
|
|
142
|
-
});
|
|
143
|
-
socket.once('error', (err) => {
|
|
144
|
-
observer.error(err);
|
|
145
|
-
});
|
|
146
|
-
return () => socket.end();
|
|
147
|
-
}).pipe((0, rxjs_1.concatMap)(obs => obs), (0, rxjs_1.ignoreElements)());
|
|
148
|
-
const rx$ = data$.pipe((0, rxjs_1.concatMap)(({ type, msg }) => new rxjs_1.Observable(observer => {
|
|
149
|
-
switch (type) {
|
|
150
|
-
case 'data':
|
|
151
|
-
socket.write(msg, err => {
|
|
152
|
-
err ? observer.error(err) : observer.complete();
|
|
153
|
-
});
|
|
154
|
-
break;
|
|
155
|
-
case 'end':
|
|
156
|
-
socket.end(() => observer.next(1));
|
|
157
|
-
break;
|
|
158
|
-
}
|
|
159
|
-
})), (0, rxjs_1.takeWhile)(_ => false), (0, rxjs_1.ignoreElements)(), (0, rxjs_1.finalize)(() => {
|
|
160
|
-
//TODO: don't really like this:
|
|
161
|
-
reqObserver.complete();
|
|
162
|
-
}));
|
|
163
|
-
return (0, rxjs_1.merge)(tx$, rx$);
|
|
164
|
-
}));
|
|
165
|
-
return handleUpgrade$.subscribe(reqObserver);
|
|
166
|
-
}
|
|
167
|
-
if (type === 'http') {
|
|
168
|
-
const handleResponse$ = new rxjs_1.Observable(observer => {
|
|
169
|
-
const handler = (res) => {
|
|
170
|
-
observer.next(res);
|
|
171
|
-
observer.complete();
|
|
172
|
-
};
|
|
173
|
-
req.once('response', handler);
|
|
174
|
-
return () => req.off('response', handler);
|
|
175
|
-
}).pipe((0, rxjs_1.concatMap)((res) => new rxjs_1.Observable(observer => {
|
|
176
|
-
const head$ = send(const_1.MessageTypes.HEAD, Buffer.from(JSON.stringify({
|
|
177
|
-
statusCode: res.statusCode,
|
|
178
|
-
headers: res.headers
|
|
179
|
-
})));
|
|
180
|
-
observer.next(head$);
|
|
181
|
-
const dataHandler = (data) => observer.next(send(const_1.MessageTypes.DATA, data));
|
|
182
|
-
res.on('data', dataHandler);
|
|
183
|
-
res.once('end', () => {
|
|
184
|
-
observer.next(send(const_1.MessageTypes.END));
|
|
185
|
-
observer.complete();
|
|
186
|
-
});
|
|
187
|
-
res.once('error', err => {
|
|
188
|
-
observer.error(err);
|
|
189
|
-
});
|
|
190
|
-
return () => res.off('data', dataHandler);
|
|
191
|
-
})), (0, rxjs_1.concatMap)(o => o), (0, rxjs_1.ignoreElements)());
|
|
192
|
-
const rx$ = data$.pipe((0, rxjs_1.concatMap)(({ type, msg }) => new rxjs_1.Observable(observer => {
|
|
193
|
-
switch (type) {
|
|
194
|
-
case const_1.MessageTypes.DATA:
|
|
195
|
-
req.write(msg, err => {
|
|
196
|
-
err ? observer.error(err) : observer.complete();
|
|
197
|
-
});
|
|
198
|
-
break;
|
|
199
|
-
case const_1.MessageTypes.END:
|
|
200
|
-
req.end(() => observer.next(1));
|
|
201
|
-
break;
|
|
202
|
-
}
|
|
203
|
-
})), (0, rxjs_1.takeWhile)(_ => false), (0, rxjs_1.ignoreElements)());
|
|
204
|
-
return (0, rxjs_1.merge)(handleResponse$, rx$)
|
|
205
|
-
.subscribe(reqObserver);
|
|
206
|
-
}
|
|
207
|
-
return () => req.end();
|
|
208
|
-
}).pipe((0, rxjs_1.catchError)(err => {
|
|
209
|
-
this.options.logger?.warn(`[nora-link] error handling request`, err);
|
|
210
|
-
return send(const_1.MessageTypes.BADGATEWAY);
|
|
211
|
-
}), (0, rxjs_1.finalize)(() => {
|
|
212
|
-
this.options.logger?.trace(`[nora-link] DONE ${method} ${url}`);
|
|
213
|
-
}));
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
exports.Client = Client;
|
package/dist/const.d.ts
DELETED
package/dist/const.js
DELETED
package/dist/index.d.ts
DELETED
package/dist/logger.d.ts
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
export declare const LOG_LEVEL: readonly ["trace", "debug", "info", "warn", "error"];
|
|
2
|
-
export type LogLevel = typeof LOG_LEVEL[number];
|
|
3
|
-
export type Logger = {
|
|
4
|
-
[P in LogLevel]: (msg: string, err?: any) => void;
|
|
5
|
-
};
|
|
6
|
-
export declare function createConsoleLogger(minLevel: LogLevel): Logger;
|
package/dist/logger.js
DELETED
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.LOG_LEVEL = void 0;
|
|
4
|
-
exports.createConsoleLogger = createConsoleLogger;
|
|
5
|
-
exports.LOG_LEVEL = [
|
|
6
|
-
'trace',
|
|
7
|
-
'debug',
|
|
8
|
-
'info',
|
|
9
|
-
'warn',
|
|
10
|
-
'error'
|
|
11
|
-
];
|
|
12
|
-
function createConsoleLogger(minLevel) {
|
|
13
|
-
const minLevelIndex = exports.LOG_LEVEL.indexOf(minLevel);
|
|
14
|
-
function log(kind, ...args) {
|
|
15
|
-
const level = exports.LOG_LEVEL.indexOf(kind);
|
|
16
|
-
if (level < minLevelIndex) {
|
|
17
|
-
return;
|
|
18
|
-
}
|
|
19
|
-
const now = new Date().toLocaleString();
|
|
20
|
-
const logArgs = [`[${now}][${kind}]${args[0]}`];
|
|
21
|
-
if (args[1])
|
|
22
|
-
logArgs.push(args[1]);
|
|
23
|
-
console.log(...logArgs);
|
|
24
|
-
}
|
|
25
|
-
return new Proxy({}, {
|
|
26
|
-
get: function (_, name) {
|
|
27
|
-
return log.bind(null, name);
|
|
28
|
-
}
|
|
29
|
-
});
|
|
30
|
-
}
|
package/src/cli.ts
DELETED
|
@@ -1,69 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
import { program } from 'commander';
|
|
4
|
-
import { Client, ClientConnectionOptions } from './client';
|
|
5
|
-
import { createConsoleLogger, LOG_LEVEL, LogLevel } from './logger';
|
|
6
|
-
|
|
7
|
-
const { name, version } = require('../package.json');
|
|
8
|
-
|
|
9
|
-
program
|
|
10
|
-
.name(name)
|
|
11
|
-
.version(version, '-v, --version')
|
|
12
|
-
.usage('[OPTIONS]...')
|
|
13
|
-
.option('-d, --debug', 'output extra debugging', false)
|
|
14
|
-
.option('-n, --non-secure', 'don\'t use secure connection', false)
|
|
15
|
-
.option<LogLevel>('-l, --log <log-level>', `min log level to display. Options: ${LOG_LEVEL.join(',')}`, (value, previous) => {
|
|
16
|
-
const v = value?.toLowerCase() as LogLevel;
|
|
17
|
-
if (LOG_LEVEL.includes(v)) {
|
|
18
|
-
return v;
|
|
19
|
-
}
|
|
20
|
-
return previous;
|
|
21
|
-
}, 'info')
|
|
22
|
-
.requiredOption('-f, --forward <subdomain|label|url...>', 'Tunnel subdomain to local url. Label is optional')
|
|
23
|
-
.requiredOption('-k, --key <api-key>', 'Api Key')
|
|
24
|
-
.requiredOption('-h, --host <hostname>', 'Server host name', 'noralink.eu')
|
|
25
|
-
.addHelpText('afterAll', 'To tunnel a local port to the subdomain `test`, you can use `-f test|:3000`')
|
|
26
|
-
.addHelpText('afterAll', 'To tunnel an ip to the subdomain `test`, you can use `-f test|192.168.1.130`')
|
|
27
|
-
.parse();
|
|
28
|
-
|
|
29
|
-
const options = program.opts();
|
|
30
|
-
|
|
31
|
-
let tunnels: ClientConnectionOptions['tunnels'] = [];
|
|
32
|
-
if (Array.isArray(options.forward)) {
|
|
33
|
-
tunnels = options.forward
|
|
34
|
-
.filter((v): v is string => typeof v === 'string')
|
|
35
|
-
.map(v => {
|
|
36
|
-
const [segment, labelOrUrl, urlPart] = v.split('|');
|
|
37
|
-
let tunnelUrl: string;
|
|
38
|
-
|
|
39
|
-
const label = urlPart ? labelOrUrl : segment;
|
|
40
|
-
const url = urlPart ?? labelOrUrl;
|
|
41
|
-
|
|
42
|
-
if (/^https?:\/\//.test(url)) {
|
|
43
|
-
tunnelUrl = url;
|
|
44
|
-
} else if (url.startsWith(':')) {
|
|
45
|
-
//only port and/or path specified
|
|
46
|
-
const portAndPath = url.split(':')[1];
|
|
47
|
-
tunnelUrl = `http://localhost:${portAndPath}`;
|
|
48
|
-
} else {
|
|
49
|
-
tunnelUrl = `http://${url}`;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
return { remotePath: segment, url: tunnelUrl, label };
|
|
53
|
-
});
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
if (!tunnels.length) {
|
|
57
|
-
console.info('no valid tunnels specified');
|
|
58
|
-
process.exit(1);
|
|
59
|
-
}
|
|
60
|
-
else {
|
|
61
|
-
new Client({
|
|
62
|
-
agent: `${name}@${version}`,
|
|
63
|
-
hostname: options.host,
|
|
64
|
-
secure: !options.nonSecure,
|
|
65
|
-
tunnels,
|
|
66
|
-
apiKey: options.key,
|
|
67
|
-
logger: createConsoleLogger(options.log),
|
|
68
|
-
}).handle$.subscribe();
|
|
69
|
-
}
|
package/src/client.ts
DELETED
|
@@ -1,311 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
EMPTY, Observable, ReplaySubject, catchError, concatMap, filter, finalize,
|
|
3
|
-
first, ignoreElements, map, merge, mergeMap, retry, share, switchMap, takeWhile, timer
|
|
4
|
-
} from 'rxjs';
|
|
5
|
-
import WebSocket from 'ws';
|
|
6
|
-
import { request, OutgoingHttpHeaders, IncomingMessage } from 'node:http';
|
|
7
|
-
import { Socket } from 'node:net';
|
|
8
|
-
import { stringify as querystringStringify } from 'node:querystring';
|
|
9
|
-
import { MessageTypes } from './const';
|
|
10
|
-
import { Logger } from './logger';
|
|
11
|
-
|
|
12
|
-
export interface TunnelOptions {
|
|
13
|
-
remotePath: string;
|
|
14
|
-
url: string;
|
|
15
|
-
label: string;
|
|
16
|
-
removeHostHeader?: boolean;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
export interface ClientConnectionOptions {
|
|
20
|
-
agent?: string;
|
|
21
|
-
hostname: string;
|
|
22
|
-
secure?: boolean;
|
|
23
|
-
apiKey: string;
|
|
24
|
-
tunnels: TunnelOptions[];
|
|
25
|
-
logger?: Logger;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
export class Client {
|
|
29
|
-
constructor(
|
|
30
|
-
private options: ClientConnectionOptions) {
|
|
31
|
-
}
|
|
32
|
-
private server$ = new Observable<WebSocket>(observer => {
|
|
33
|
-
const segments = this.options.tunnels.map(v => `${v.remotePath}|${v.label}`);
|
|
34
|
-
const qs = querystringStringify({ s: segments });
|
|
35
|
-
this.options.logger?.info(`[nora-link] connecting`);
|
|
36
|
-
const protocol = this.options.secure ? 'wss' : 'ws';
|
|
37
|
-
|
|
38
|
-
const headers = {
|
|
39
|
-
authorization: `Bearer ${this.options.apiKey}`,
|
|
40
|
-
...(this.options.agent ? {
|
|
41
|
-
'user-agent': this.options.agent,
|
|
42
|
-
} : {}),
|
|
43
|
-
};
|
|
44
|
-
|
|
45
|
-
const ws = new WebSocket(`${protocol}://${this.options.hostname}/api/tunnel?${qs}`, { headers });
|
|
46
|
-
|
|
47
|
-
ws.on('open', () => {
|
|
48
|
-
this.options.logger?.info(`[nora-link] connected`);
|
|
49
|
-
observer.next(ws);
|
|
50
|
-
});
|
|
51
|
-
ws.on('error', err => observer.error(err));
|
|
52
|
-
ws.on('close', () => observer.complete());
|
|
53
|
-
|
|
54
|
-
return () => ws.close();
|
|
55
|
-
}).pipe(
|
|
56
|
-
share({ connector: () => new ReplaySubject(1) }),
|
|
57
|
-
);
|
|
58
|
-
|
|
59
|
-
private data$ = this.server$.pipe(
|
|
60
|
-
switchMap(ws => new Observable<Buffer>(observer => {
|
|
61
|
-
const handler = (msg: Buffer) => {
|
|
62
|
-
Buffer.isBuffer(msg) && observer.next(msg);
|
|
63
|
-
};
|
|
64
|
-
|
|
65
|
-
ws.on('message', handler);
|
|
66
|
-
ws.once('error', err => observer.error(err));
|
|
67
|
-
ws.once('close', (code, reason) => {
|
|
68
|
-
observer.error(new Error(`${code} - ${reason.toString()}`));
|
|
69
|
-
});
|
|
70
|
-
return () => ws.off('message', handler);
|
|
71
|
-
})),
|
|
72
|
-
map(v => {
|
|
73
|
-
if (v.length >= 5) {
|
|
74
|
-
const id = v.readUint32BE();
|
|
75
|
-
const typeLength = v.readUint8(4);
|
|
76
|
-
const type = v.subarray(5, 5 + typeLength).toString();
|
|
77
|
-
return {
|
|
78
|
-
id,
|
|
79
|
-
type,
|
|
80
|
-
msg: v.subarray(5 + typeLength),
|
|
81
|
-
};
|
|
82
|
-
}
|
|
83
|
-
return null;
|
|
84
|
-
}),
|
|
85
|
-
filter(v => !!v),
|
|
86
|
-
share(),
|
|
87
|
-
);
|
|
88
|
-
|
|
89
|
-
readonly handle$ =
|
|
90
|
-
merge(
|
|
91
|
-
this.server$,
|
|
92
|
-
this.data$.pipe(
|
|
93
|
-
mergeMap(({ id, msg, type }) =>
|
|
94
|
-
type === 'http' || type === 'ws'
|
|
95
|
-
? this.httpRequest({
|
|
96
|
-
type,
|
|
97
|
-
options: JSON.parse(msg.toString()),
|
|
98
|
-
data$: this.getStreamData(id),
|
|
99
|
-
send: (type, msg) => this.send(id, type, msg),
|
|
100
|
-
})
|
|
101
|
-
: EMPTY
|
|
102
|
-
),
|
|
103
|
-
),
|
|
104
|
-
).pipe(
|
|
105
|
-
retry({
|
|
106
|
-
resetOnSuccess: true,
|
|
107
|
-
delay: (err, retryCount) => {
|
|
108
|
-
const delaySeconds = Math.round(Math.min(300, Math.pow(1.8, retryCount + 3)));
|
|
109
|
-
this.options.logger?.trace(`[nora-link] connection error`, err);
|
|
110
|
-
this.options.logger?.error(`[nora-link] retrying in ${delaySeconds} sec`);
|
|
111
|
-
return timer(delaySeconds * 1000);
|
|
112
|
-
},
|
|
113
|
-
}),
|
|
114
|
-
share(),
|
|
115
|
-
);
|
|
116
|
-
|
|
117
|
-
send(id: number, type: string, msg?: Buffer) {
|
|
118
|
-
return this.server$.pipe(
|
|
119
|
-
first(),
|
|
120
|
-
switchMap(ws => {
|
|
121
|
-
const header = Buffer.alloc(5);
|
|
122
|
-
const typeBuffer = Buffer.from(type);
|
|
123
|
-
header.writeUint32BE(id);
|
|
124
|
-
header.writeUint8(typeBuffer.length, 4);
|
|
125
|
-
const all = msg
|
|
126
|
-
? Buffer.concat([header, typeBuffer, msg])
|
|
127
|
-
: Buffer.concat([header, typeBuffer]);
|
|
128
|
-
return new Observable<void>(observer => {
|
|
129
|
-
ws.send(all, (err) => {
|
|
130
|
-
if (err) observer.error(err);
|
|
131
|
-
else observer.complete();
|
|
132
|
-
});
|
|
133
|
-
});
|
|
134
|
-
})
|
|
135
|
-
);
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
private getStreamData(id: number) {
|
|
139
|
-
return this.data$.pipe(filter((m) => m.id === id), map(({ id, ...rest }) => rest));
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
private httpRequest({ type, options, data$, send }: {
|
|
143
|
-
type: 'ws' | 'http',
|
|
144
|
-
options: { url: string, subdomain: string, method: string, headers: OutgoingHttpHeaders },
|
|
145
|
-
data$: ReturnType<Client['getStreamData']>,
|
|
146
|
-
send: (type: string, msg?: Buffer) => Observable<void>,
|
|
147
|
-
}) {
|
|
148
|
-
const { url, subdomain, method, headers } = options;
|
|
149
|
-
|
|
150
|
-
return new Observable<never>(reqObserver => {
|
|
151
|
-
this.options.logger?.trace(`[nora-link] START ${method} ${url}`);
|
|
152
|
-
|
|
153
|
-
const tunnel = this.options.tunnels.find(v => v.remotePath === subdomain);
|
|
154
|
-
if (!tunnel) {
|
|
155
|
-
throw new Error(`subdomain ${subdomain} not registered`);
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
if (tunnel.removeHostHeader ?? true) {
|
|
159
|
-
delete headers["host"];
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
const { hostname, port, pathname } = new URL(tunnel.url);
|
|
163
|
-
const req = request({
|
|
164
|
-
host: hostname,
|
|
165
|
-
port: port,
|
|
166
|
-
path: pathname === '/' ? url : `${pathname}${url}`,
|
|
167
|
-
method,
|
|
168
|
-
headers,
|
|
169
|
-
});
|
|
170
|
-
|
|
171
|
-
req.on('error', (err) => reqObserver.error(err));
|
|
172
|
-
|
|
173
|
-
if (type === 'ws') {
|
|
174
|
-
req.flushHeaders();
|
|
175
|
-
|
|
176
|
-
const handleUpgrade$ = new Observable<{ res: IncomingMessage, socket: Socket }>(observer => {
|
|
177
|
-
const handler = (res: IncomingMessage, socket: Socket) => {
|
|
178
|
-
observer.next({ res, socket });
|
|
179
|
-
observer.complete();
|
|
180
|
-
};
|
|
181
|
-
req.once('upgrade', handler);
|
|
182
|
-
return () => req.off('upgrade', handler);
|
|
183
|
-
}).pipe(
|
|
184
|
-
concatMap(({ res, socket }) => {
|
|
185
|
-
const tx$ = new Observable<Observable<void>>(observer => {
|
|
186
|
-
const head = [
|
|
187
|
-
`HTTP/${res.httpVersion} ${res.statusCode} ${res.statusMessage}`,
|
|
188
|
-
...(Object.entries(res.headers).map(([k, v]) => `${k}: ${v}`)),
|
|
189
|
-
'',
|
|
190
|
-
'',
|
|
191
|
-
].join('\r\n');
|
|
192
|
-
observer.next(send(MessageTypes.DATA, Buffer.from(head)));
|
|
193
|
-
|
|
194
|
-
socket.on('data', data => {
|
|
195
|
-
observer.next(send(MessageTypes.DATA, data));
|
|
196
|
-
});
|
|
197
|
-
|
|
198
|
-
socket.once('end', () => {
|
|
199
|
-
observer.next(send(MessageTypes.END));
|
|
200
|
-
|
|
201
|
-
//TODO: don't really like this:
|
|
202
|
-
reqObserver.complete();
|
|
203
|
-
});
|
|
204
|
-
|
|
205
|
-
socket.once('error', (err) => {
|
|
206
|
-
observer.error(err);
|
|
207
|
-
});
|
|
208
|
-
|
|
209
|
-
return () => socket.end();
|
|
210
|
-
}).pipe(
|
|
211
|
-
concatMap(obs => obs),
|
|
212
|
-
ignoreElements(),
|
|
213
|
-
);
|
|
214
|
-
|
|
215
|
-
const rx$ = data$.pipe(
|
|
216
|
-
concatMap(({ type, msg }) => new Observable<number>(observer => {
|
|
217
|
-
switch (type) {
|
|
218
|
-
case 'data':
|
|
219
|
-
socket.write(msg, err => {
|
|
220
|
-
err ? observer.error(err) : observer.complete();
|
|
221
|
-
});
|
|
222
|
-
break;
|
|
223
|
-
|
|
224
|
-
case 'end':
|
|
225
|
-
socket.end(() => observer.next(1));
|
|
226
|
-
break;
|
|
227
|
-
}
|
|
228
|
-
})),
|
|
229
|
-
takeWhile(_ => false),
|
|
230
|
-
ignoreElements(),
|
|
231
|
-
finalize(() => {
|
|
232
|
-
//TODO: don't really like this:
|
|
233
|
-
reqObserver.complete();
|
|
234
|
-
}),
|
|
235
|
-
);
|
|
236
|
-
|
|
237
|
-
return merge(tx$, rx$);
|
|
238
|
-
}),
|
|
239
|
-
)
|
|
240
|
-
|
|
241
|
-
return handleUpgrade$.subscribe(reqObserver);
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
if (type === 'http') {
|
|
245
|
-
const handleResponse$ = new Observable<IncomingMessage>(observer => {
|
|
246
|
-
const handler = (res: IncomingMessage) => {
|
|
247
|
-
observer.next(res);
|
|
248
|
-
observer.complete();
|
|
249
|
-
};
|
|
250
|
-
req.once('response', handler);
|
|
251
|
-
return () => req.off('response', handler);
|
|
252
|
-
}).pipe(
|
|
253
|
-
concatMap((res) => new Observable<Observable<void>>(observer => {
|
|
254
|
-
const head$ = send(MessageTypes.HEAD, Buffer.from(JSON.stringify({
|
|
255
|
-
statusCode: res.statusCode,
|
|
256
|
-
headers: res.headers
|
|
257
|
-
})));
|
|
258
|
-
observer.next(head$);
|
|
259
|
-
|
|
260
|
-
const dataHandler = (data: Buffer) => observer.next(send(MessageTypes.DATA, data));
|
|
261
|
-
res.on('data', dataHandler);
|
|
262
|
-
|
|
263
|
-
res.once('end', () => {
|
|
264
|
-
observer.next(send(MessageTypes.END));
|
|
265
|
-
observer.complete();
|
|
266
|
-
});
|
|
267
|
-
|
|
268
|
-
res.once('error', err => {
|
|
269
|
-
observer.error(err);
|
|
270
|
-
});
|
|
271
|
-
|
|
272
|
-
return () => res.off('data', dataHandler);
|
|
273
|
-
})),
|
|
274
|
-
concatMap(o => o),
|
|
275
|
-
ignoreElements(),
|
|
276
|
-
);
|
|
277
|
-
|
|
278
|
-
const rx$ = data$.pipe(
|
|
279
|
-
concatMap(({ type, msg }) => new Observable<number>(observer => {
|
|
280
|
-
switch (type) {
|
|
281
|
-
case MessageTypes.DATA:
|
|
282
|
-
req.write(msg, err => {
|
|
283
|
-
err ? observer.error(err) : observer.complete();
|
|
284
|
-
});
|
|
285
|
-
break;
|
|
286
|
-
|
|
287
|
-
case MessageTypes.END:
|
|
288
|
-
req.end(() => observer.next(1));
|
|
289
|
-
break;
|
|
290
|
-
}
|
|
291
|
-
})),
|
|
292
|
-
takeWhile(_ => false),
|
|
293
|
-
ignoreElements(),
|
|
294
|
-
);
|
|
295
|
-
|
|
296
|
-
return merge(handleResponse$, rx$)
|
|
297
|
-
.subscribe(reqObserver);
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
return () => req.end();
|
|
301
|
-
}).pipe(
|
|
302
|
-
catchError(err => {
|
|
303
|
-
this.options.logger?.warn(`[nora-link] error handling request`, err);
|
|
304
|
-
return send(MessageTypes.BADGATEWAY);
|
|
305
|
-
}),
|
|
306
|
-
finalize(() => {
|
|
307
|
-
this.options.logger?.trace(`[nora-link] DONE ${method} ${url}`);
|
|
308
|
-
}),
|
|
309
|
-
);
|
|
310
|
-
}
|
|
311
|
-
}
|
package/src/const.ts
DELETED
package/src/index.ts
DELETED
package/src/logger.ts
DELETED
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
export const LOG_LEVEL = [
|
|
2
|
-
'trace',
|
|
3
|
-
'debug',
|
|
4
|
-
'info',
|
|
5
|
-
'warn',
|
|
6
|
-
'error'
|
|
7
|
-
] as const;
|
|
8
|
-
|
|
9
|
-
export type LogLevel = typeof LOG_LEVEL[number];
|
|
10
|
-
|
|
11
|
-
export type Logger = {
|
|
12
|
-
[P in LogLevel]: (msg: string, err?: any) => void;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
export function createConsoleLogger(minLevel: LogLevel): Logger {
|
|
16
|
-
const minLevelIndex = LOG_LEVEL.indexOf(minLevel);
|
|
17
|
-
function log(kind: keyof Logger, ...args: Parameters<Logger['info']>) {
|
|
18
|
-
const level = LOG_LEVEL.indexOf(kind);
|
|
19
|
-
if (level < minLevelIndex) {
|
|
20
|
-
return;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
const now = new Date().toLocaleString();
|
|
24
|
-
const logArgs = [`[${now}][${kind}]${args[0]}`];
|
|
25
|
-
if (args[1]) logArgs.push(args[1]);
|
|
26
|
-
console.log(...logArgs);
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
return new Proxy({}, {
|
|
30
|
-
get: function (_, name: LogLevel) {
|
|
31
|
-
return log.bind(null, name);
|
|
32
|
-
}
|
|
33
|
-
}) as Logger;
|
|
34
|
-
}
|
package/tsconfig.json
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
// This is an alias to @tsconfig/node16: https://github.com/tsconfig/bases
|
|
3
|
-
"extends": "ts-node/node16/tsconfig.json",
|
|
4
|
-
// Most ts-node options can be specified here using their programmatic names.
|
|
5
|
-
"ts-node": {
|
|
6
|
-
// It is faster to skip typechecking.
|
|
7
|
-
// Remove if you want ts-node to do typechecking.
|
|
8
|
-
"transpileOnly": true,
|
|
9
|
-
"files": true,
|
|
10
|
-
"compilerOptions": {
|
|
11
|
-
// compilerOptions specified here will override those declared below,
|
|
12
|
-
// but *only* in ts-node. Useful if you want ts-node and tsc to use
|
|
13
|
-
// different options with a single tsconfig.json.
|
|
14
|
-
}
|
|
15
|
-
},
|
|
16
|
-
"compilerOptions": {
|
|
17
|
-
"strict": true,
|
|
18
|
-
"declaration": true,
|
|
19
|
-
"module": "CommonJS",
|
|
20
|
-
"noUnusedLocals": true,
|
|
21
|
-
"outDir": "dist"
|
|
22
|
-
},
|
|
23
|
-
}
|