@nora-link/client 1.0.7 → 1.0.9

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 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|:3000`')
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
- const url = urlPart ?? labelOrUrl;
37
- if (/^https?:\/\//.test(url)) {
38
- tunnelUrl = url;
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
- else if (url.startsWith(':')) {
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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nora-link/client",
3
- "version": "1.0.7",
3
+ "version": "1.0.9",
4
4
  "description": "noralink.eu client",
5
5
  "bin": {
6
6
  "noralink": "dist/cli.js"
@@ -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/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
@@ -1,7 +0,0 @@
1
- export const MessageTypes = {
2
- HEAD: 'head',
3
- DATA: 'data',
4
- END: 'end',
5
- CLOSE: 'close',
6
- BADGATEWAY: 'err-502',
7
- } as const;
package/src/index.ts DELETED
@@ -1,3 +0,0 @@
1
- import { Client } from "./client";
2
-
3
- export { Client };
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
- }