virunx 0.0.0-stage → 0.1.0

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.
Files changed (3) hide show
  1. package/dist/index.js +851 -0
  2. package/package.json +23 -4
  3. package/README.md +0 -3
package/dist/index.js ADDED
@@ -0,0 +1,851 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __commonJS = (cb, mod) => function __require() {
10
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+
29
+ // ../proto/dist/index.js
30
+ var require_dist = __commonJS({
31
+ "../proto/dist/index.js"(exports2) {
32
+ "use strict";
33
+ Object.defineProperty(exports2, "__esModule", { value: true });
34
+ exports2.FrameKind = exports2.PROTOCOL_VERSION = void 0;
35
+ exports2.encodeFrame = encodeFrame;
36
+ exports2.decodeFrame = decodeFrame;
37
+ exports2.parseControl = parseControl;
38
+ exports2.PROTOCOL_VERSION = 1;
39
+ exports2.FrameKind = {
40
+ /** request body bytes, relay -> client */
41
+ ReqBody: 1,
42
+ /** response body bytes, client -> relay */
43
+ RespBody: 2,
44
+ /** bytes from the visitor on an upgraded (websocket) connection, relay -> client */
45
+ WsUp: 3,
46
+ /** bytes from the local app on an upgraded (websocket) connection, client -> relay */
47
+ WsDown: 4
48
+ };
49
+ var MAX_RID_LEN = 255;
50
+ function encodeFrame(kind, rid, payload = Buffer.alloc(0)) {
51
+ const ridBuf = Buffer.from(rid, "ascii");
52
+ if (ridBuf.length > MAX_RID_LEN)
53
+ throw new Error(`rid too long: ${rid}`);
54
+ const out = Buffer.allocUnsafe(2 + ridBuf.length + payload.length);
55
+ out[0] = kind;
56
+ out[1] = ridBuf.length;
57
+ ridBuf.copy(out, 2);
58
+ payload.copy(out, 2 + ridBuf.length);
59
+ return out;
60
+ }
61
+ function decodeFrame(data) {
62
+ if (data.length < 2)
63
+ return null;
64
+ const ridLen = data[1];
65
+ if (data.length < 2 + ridLen)
66
+ return null;
67
+ return {
68
+ kind: data[0],
69
+ rid: data.toString("ascii", 2, 2 + ridLen),
70
+ payload: data.subarray(2 + ridLen)
71
+ };
72
+ }
73
+ function parseControl(data) {
74
+ try {
75
+ const msg = JSON.parse(data);
76
+ if (msg && typeof msg === "object" && typeof msg.t === "string")
77
+ return msg;
78
+ return null;
79
+ } catch {
80
+ return null;
81
+ }
82
+ }
83
+ }
84
+ });
85
+
86
+ // ../core/dist/index.js
87
+ var require_dist2 = __commonJS({
88
+ "../core/dist/index.js"(exports2) {
89
+ "use strict";
90
+ var __importDefault = exports2 && exports2.__importDefault || function(mod) {
91
+ return mod && mod.__esModule ? mod : { "default": mod };
92
+ };
93
+ Object.defineProperty(exports2, "__esModule", { value: true });
94
+ exports2.Tunnel = void 0;
95
+ exports2.startTunnel = startTunnel2;
96
+ exports2.sanitizeId = sanitizeId2;
97
+ exports2.defaultIdFromDir = defaultIdFromDir2;
98
+ var node_events_1 = require("node:events");
99
+ var node_fs_1 = __importDefault(require("node:fs"));
100
+ var node_http_1 = __importDefault(require("node:http"));
101
+ var node_net_1 = __importDefault(require("node:net"));
102
+ var node_path_1 = __importDefault(require("node:path"));
103
+ var ws_1 = __importDefault(require("ws"));
104
+ var proto_1 = require_dist();
105
+ var FATAL = /* @__PURE__ */ new Set(["bad-version", "bad-id", "id-taken", "banned", "bad-token", "server-full"]);
106
+ var BACKOFF_MS = [1e3, 2e3, 4e3, 8e3, 1e4];
107
+ var CREDIT_WINDOW = 256e3;
108
+ var BODY_CHUNK = 64e3;
109
+ var HOP_HEADERS = [
110
+ "connection",
111
+ "keep-alive",
112
+ "proxy-connection",
113
+ "te",
114
+ "trailer",
115
+ "transfer-encoding",
116
+ "upgrade"
117
+ ];
118
+ function toBuf(data) {
119
+ if (Buffer.isBuffer(data))
120
+ return data;
121
+ if (Array.isArray(data))
122
+ return Buffer.concat(data);
123
+ return Buffer.from(data);
124
+ }
125
+ var Tunnel = class extends node_events_1.EventEmitter {
126
+ id;
127
+ port;
128
+ relay;
129
+ token;
130
+ ws = null;
131
+ agent;
132
+ ctxs = /* @__PURE__ */ new Map();
133
+ state = "connecting";
134
+ _publicUrl = null;
135
+ stopped = false;
136
+ flow = false;
137
+ retryCount = 0;
138
+ retryTimer = null;
139
+ pingTimer = null;
140
+ bpTimer;
141
+ constructor(opts) {
142
+ super();
143
+ this.id = opts.id;
144
+ this.port = opts.port;
145
+ this.relay = opts.relay;
146
+ this.token = opts.token;
147
+ this.agent = new node_http_1.default.Agent({ keepAlive: true, maxSockets: 32, keepAliveMsecs: 15e3 });
148
+ this.bpTimer = setInterval(() => this.resumeSockets(), 300);
149
+ setImmediate(() => this.connect());
150
+ }
151
+ get status() {
152
+ return this.state;
153
+ }
154
+ get publicUrl() {
155
+ return this._publicUrl;
156
+ }
157
+ async stop() {
158
+ if (this.stopped && this.state === "stopped")
159
+ return;
160
+ this.stopped = true;
161
+ this.clearTimers();
162
+ this.failCtxs();
163
+ const ws = this.ws;
164
+ if (ws) {
165
+ await new Promise((resolve) => {
166
+ const kill = setTimeout(() => {
167
+ try {
168
+ ws.terminate();
169
+ } catch {
170
+ }
171
+ resolve();
172
+ }, 250);
173
+ ws.once("close", () => {
174
+ clearTimeout(kill);
175
+ resolve();
176
+ });
177
+ try {
178
+ ws.close(1e3, "shutdown");
179
+ } catch {
180
+ clearTimeout(kill);
181
+ resolve();
182
+ }
183
+ });
184
+ }
185
+ if (this.state !== "error")
186
+ this.setState("stopped");
187
+ }
188
+ // -- connection lifecycle ------------------------------------------------
189
+ connect() {
190
+ if (this.stopped)
191
+ return;
192
+ this.setState(this.retryCount === 0 ? "connecting" : "reconnecting");
193
+ const ws = new ws_1.default(this.relay, { maxPayload: 8 * 1024 * 1024 });
194
+ this.ws = ws;
195
+ let lastPong = Date.now();
196
+ ws.on("open", () => {
197
+ const hello = {
198
+ t: "hello",
199
+ v: proto_1.PROTOCOL_VERSION,
200
+ id: this.id,
201
+ ...this.token ? { token: this.token } : {}
202
+ };
203
+ this.sendCtrl(hello);
204
+ });
205
+ ws.on("pong", () => {
206
+ lastPong = Date.now();
207
+ });
208
+ ws.on("message", (data, isBinary) => this.onMessage(data, isBinary));
209
+ ws.on("error", () => {
210
+ });
211
+ ws.on("close", () => this.onClose());
212
+ this.pingTimer = setInterval(() => {
213
+ if (ws.readyState !== ws_1.default.OPEN)
214
+ return;
215
+ ws.ping();
216
+ if (Date.now() - lastPong > 45e3)
217
+ ws.terminate();
218
+ }, 15e3);
219
+ }
220
+ onClose() {
221
+ if (this.pingTimer) {
222
+ clearInterval(this.pingTimer);
223
+ this.pingTimer = null;
224
+ }
225
+ this.failCtxs();
226
+ this.ws = null;
227
+ if (this.stopped) {
228
+ if (this.state !== "error")
229
+ this.setState("stopped");
230
+ return;
231
+ }
232
+ if (this.state === "error")
233
+ return;
234
+ this.retryCount += 1;
235
+ const delay = BACKOFF_MS[Math.min(this.retryCount - 1, BACKOFF_MS.length - 1)];
236
+ this.setState("reconnecting");
237
+ this.retryTimer = setTimeout(() => this.connect(), delay);
238
+ }
239
+ clearTimers() {
240
+ if (this.retryTimer)
241
+ clearTimeout(this.retryTimer);
242
+ if (this.pingTimer)
243
+ clearInterval(this.pingTimer);
244
+ clearInterval(this.bpTimer);
245
+ }
246
+ setState(s, info) {
247
+ if (this.state === s)
248
+ return;
249
+ this.state = s;
250
+ this.emit("status", s, info);
251
+ }
252
+ // -- relay -> us ----------------------------------------------------------
253
+ onMessage(data, isBinary) {
254
+ const buf = toBuf(data);
255
+ if (isBinary) {
256
+ const f = (0, proto_1.decodeFrame)(buf);
257
+ if (!f)
258
+ return;
259
+ const ctx = this.ctxs.get(f.rid);
260
+ if (!ctx || ctx.ended)
261
+ return;
262
+ if (f.kind === proto_1.FrameKind.ReqBody) {
263
+ ctx.bytesIn += f.payload.length;
264
+ ctx.req?.write(f.payload);
265
+ } else if (f.kind === proto_1.FrameKind.WsUp) {
266
+ if (ctx.hsDone)
267
+ ctx.sock?.write(f.payload);
268
+ }
269
+ return;
270
+ }
271
+ const msg = (0, proto_1.parseControl)(buf.toString("utf8"));
272
+ if (!msg)
273
+ return;
274
+ switch (msg.t) {
275
+ case "ok":
276
+ this.retryCount = 0;
277
+ this.flow = msg.flow === 1;
278
+ this._publicUrl = msg.publicUrl;
279
+ this.setState("live");
280
+ this.emit("url", msg.publicUrl, msg.id);
281
+ break;
282
+ case "credit": {
283
+ const c = this.ctxs.get(msg.rid);
284
+ if (!c || typeof c.creditLeft !== "number" || c.ended)
285
+ break;
286
+ c.creditLeft += Math.max(0, msg.n);
287
+ if (c.pausedByCredit && c.creditLeft > 0) {
288
+ while (c.pendingBufs && c.pendingBufs.length > 0 && c.creditLeft > 0) {
289
+ const chunk = c.pendingBufs[0];
290
+ const take = Math.min(BODY_CHUNK, chunk.length);
291
+ const part = chunk.subarray(0, take);
292
+ c.bytesOut += take;
293
+ this.sendFrame(proto_1.FrameKind.RespBody, c.rid, part);
294
+ c.creditLeft -= take;
295
+ if (take < chunk.length)
296
+ c.pendingBufs[0] = chunk.subarray(take);
297
+ else
298
+ c.pendingBufs.shift();
299
+ }
300
+ if (c.pendingBufs && c.pendingBufs.length === 0) {
301
+ c.pausedByCredit = false;
302
+ try {
303
+ c.res?.resume();
304
+ } catch {
305
+ }
306
+ }
307
+ }
308
+ break;
309
+ }
310
+ case "err":
311
+ if (FATAL.has(msg.code)) {
312
+ this.stopped = true;
313
+ this.setState("error", { code: msg.code, message: msg.message });
314
+ try {
315
+ this.ws?.close();
316
+ } catch {
317
+ }
318
+ }
319
+ break;
320
+ case "req":
321
+ this.startReq(msg);
322
+ break;
323
+ case "req-end": {
324
+ const c = this.ctxs.get(msg.rid);
325
+ if (c)
326
+ c.req?.end();
327
+ break;
328
+ }
329
+ case "abort":
330
+ case "close": {
331
+ const c = this.ctxs.get(msg.rid);
332
+ if (c)
333
+ this.closeCtx(c, msg.t === "abort" ? "visitor aborted" : "visitor closed");
334
+ break;
335
+ }
336
+ default:
337
+ break;
338
+ }
339
+ }
340
+ // -- visitor request handling ----------------------------------------------
341
+ startReq(msg) {
342
+ const ctx = {
343
+ rid: msg.rid,
344
+ kind: msg.upgrade ? "ws" : "http",
345
+ method: msg.method,
346
+ url: msg.url,
347
+ startedAt: Date.now(),
348
+ bytesIn: 0,
349
+ bytesOut: 0,
350
+ status: null,
351
+ respStarted: false,
352
+ ended: false,
353
+ // релей с flow:1 шлёт credit'ы; до первого credit — имплицитное окно
354
+ creditLeft: msg.upgrade || !this.flow ? null : CREDIT_WINDOW,
355
+ pausedByCredit: false,
356
+ pendingBufs: []
357
+ };
358
+ this.ctxs.set(msg.rid, ctx);
359
+ if (ctx.kind === "ws")
360
+ this.startUpgrade(ctx, msg);
361
+ else
362
+ this.startHttp(ctx, msg);
363
+ }
364
+ startHttp(ctx, msg) {
365
+ const headers = { ...msg.headers };
366
+ for (const h of HOP_HEADERS)
367
+ delete headers[h];
368
+ const req = node_http_1.default.request({
369
+ host: "127.0.0.1",
370
+ port: this.port,
371
+ method: msg.method,
372
+ path: msg.url,
373
+ headers,
374
+ agent: this.agent
375
+ }, (res) => {
376
+ ctx.res = res;
377
+ ctx.status = res.statusCode ?? 502;
378
+ const rh = {};
379
+ for (const [k, v] of Object.entries(res.headers)) {
380
+ if (v !== void 0)
381
+ rh[k] = v;
382
+ }
383
+ for (const h of HOP_HEADERS)
384
+ delete rh[h];
385
+ this.sendCtrl({
386
+ t: "resp-start",
387
+ rid: ctx.rid,
388
+ status: ctx.status,
389
+ statusText: res.statusMessage,
390
+ headers: rh
391
+ });
392
+ ctx.respStarted = true;
393
+ const sendBody = (buf) => {
394
+ const win = ctx.creditLeft;
395
+ if (typeof win !== "number") {
396
+ ctx.bytesOut += buf.length;
397
+ this.sendFrame(proto_1.FrameKind.RespBody, ctx.rid, buf);
398
+ return;
399
+ }
400
+ let left = win;
401
+ let off = 0;
402
+ while (off < buf.length) {
403
+ if (left <= 0) {
404
+ ctx.creditLeft = left;
405
+ ctx.pendingBufs.push(buf.subarray(off));
406
+ if (!ctx.pausedByCredit) {
407
+ ctx.pausedByCredit = true;
408
+ try {
409
+ res.pause();
410
+ } catch {
411
+ }
412
+ }
413
+ return;
414
+ }
415
+ const take = Math.min(BODY_CHUNK, buf.length - off);
416
+ const part = buf.subarray(off, off + take);
417
+ ctx.bytesOut += take;
418
+ this.sendFrame(proto_1.FrameKind.RespBody, ctx.rid, part);
419
+ left -= take;
420
+ off += take;
421
+ }
422
+ ctx.creditLeft = left;
423
+ };
424
+ res.on("data", (chunk) => sendBody(chunk));
425
+ res.on("end", () => {
426
+ this.sendCtrl({ t: "resp-end", rid: ctx.rid });
427
+ this.closeCtx(ctx);
428
+ });
429
+ const onResFail = (err) => {
430
+ if (ctx.ended)
431
+ return;
432
+ if (!ctx.respStarted)
433
+ this.sendLocalError(ctx, err.message);
434
+ else
435
+ this.sendCtrl({ t: "resp-end", rid: ctx.rid });
436
+ this.closeCtx(ctx, err.message);
437
+ };
438
+ res.on("error", onResFail);
439
+ res.on("aborted", () => onResFail(new Error("response aborted")));
440
+ });
441
+ ctx.req = req;
442
+ req.on("error", (err) => {
443
+ if (ctx.ended)
444
+ return;
445
+ if (!ctx.respStarted)
446
+ this.sendLocalError(ctx, err.message);
447
+ else
448
+ this.sendCtrl({ t: "resp-end", rid: ctx.rid });
449
+ this.closeCtx(ctx, err.message);
450
+ });
451
+ }
452
+ startUpgrade(ctx, msg) {
453
+ const sock = node_net_1.default.connect({ host: "127.0.0.1", port: this.port });
454
+ ctx.sock = sock;
455
+ ctx.hsBuf = Buffer.alloc(0);
456
+ let failed = false;
457
+ const fail = (reason, status = 502) => {
458
+ if (failed || ctx.ended)
459
+ return;
460
+ failed = true;
461
+ if (!ctx.respStarted) {
462
+ const body = Buffer.from(`virun: upgrade failed: ${reason}
463
+ `, "utf8");
464
+ this.sendCtrl({
465
+ t: "resp-start",
466
+ rid: ctx.rid,
467
+ status,
468
+ statusText: "Bad Gateway",
469
+ headers: {
470
+ "content-type": "text/plain; charset=utf-8",
471
+ "content-length": String(body.length)
472
+ }
473
+ });
474
+ this.sendFrame(proto_1.FrameKind.RespBody, ctx.rid, body);
475
+ this.sendCtrl({ t: "resp-end", rid: ctx.rid });
476
+ ctx.respStarted = true;
477
+ ctx.status = status;
478
+ }
479
+ this.closeCtx(ctx, reason);
480
+ };
481
+ sock.setTimeout(1e4, () => fail("local handshake timeout", 504));
482
+ sock.on("error", (err) => fail(err.message));
483
+ sock.on("close", () => {
484
+ if (ctx.ended)
485
+ return;
486
+ if (ctx.pipe) {
487
+ this.sendCtrl({ t: "close", rid: ctx.rid });
488
+ this.closeCtx(ctx, "local socket closed");
489
+ } else if (ctx.hsDone) {
490
+ this.sendCtrl({ t: "resp-end", rid: ctx.rid });
491
+ this.closeCtx(ctx);
492
+ } else {
493
+ this.closeCtx(ctx, "local socket closed before handshake");
494
+ }
495
+ });
496
+ let head = `${msg.method} ${msg.url} HTTP/1.1\r
497
+ `;
498
+ for (const [k, v] of Object.entries(msg.headers)) {
499
+ head += `${k}: ${Array.isArray(v) ? v.join(", ") : v}\r
500
+ `;
501
+ }
502
+ head += "\r\n";
503
+ sock.write(head);
504
+ sock.on("data", (chunk) => {
505
+ if (ctx.ended)
506
+ return;
507
+ if (!ctx.hsDone) {
508
+ ctx.hsBuf = Buffer.concat([ctx.hsBuf, chunk]);
509
+ const idx = ctx.hsBuf.indexOf("\r\n\r\n");
510
+ if (idx === -1) {
511
+ if (ctx.hsBuf.length > 64 * 1024)
512
+ fail("handshake too large");
513
+ return;
514
+ }
515
+ const headStr = ctx.hsBuf.toString("latin1", 0, idx);
516
+ const rest = ctx.hsBuf.subarray(idx + 4);
517
+ ctx.hsBuf = Buffer.alloc(0);
518
+ ctx.hsDone = true;
519
+ sock.setTimeout(0);
520
+ const lines = headStr.split("\r\n");
521
+ const m = /^HTTP\/1\.[01] (\d{3})(?: (.*))?$/.exec(lines[0] ?? "");
522
+ if (!m) {
523
+ fail("malformed local handshake");
524
+ return;
525
+ }
526
+ const status = parseInt(m[1], 10);
527
+ const headers = {};
528
+ for (let i = 1; i < lines.length; i++) {
529
+ const ci = lines[i].indexOf(":");
530
+ if (ci <= 0)
531
+ continue;
532
+ const k = lines[i].slice(0, ci).trim().toLowerCase();
533
+ const v = lines[i].slice(ci + 1).trim();
534
+ if (k in headers) {
535
+ const prev = headers[k];
536
+ headers[k] = Array.isArray(prev) ? [...prev, v] : [prev, v];
537
+ } else {
538
+ headers[k] = v;
539
+ }
540
+ }
541
+ ctx.status = status;
542
+ this.sendCtrl({
543
+ t: "resp-start",
544
+ rid: ctx.rid,
545
+ status,
546
+ statusText: m[2] || void 0,
547
+ headers
548
+ });
549
+ ctx.respStarted = true;
550
+ if (status === 101) {
551
+ ctx.pipe = true;
552
+ sock.setNoDelay(true);
553
+ if (rest.length) {
554
+ ctx.bytesOut += rest.length;
555
+ this.sendFrame(proto_1.FrameKind.WsDown, ctx.rid, rest);
556
+ }
557
+ } else if (rest.length) {
558
+ ctx.bytesOut += rest.length;
559
+ this.sendFrame(proto_1.FrameKind.RespBody, ctx.rid, rest);
560
+ }
561
+ return;
562
+ }
563
+ if (ctx.pipe) {
564
+ ctx.bytesOut += chunk.length;
565
+ const ws = this.ws;
566
+ if (ws && ws.bufferedAmount > 4 * 1024 * 1024) {
567
+ sock.pause();
568
+ ctx.paused = true;
569
+ }
570
+ this.sendFrame(proto_1.FrameKind.WsDown, ctx.rid, chunk);
571
+ } else {
572
+ ctx.bytesOut += chunk.length;
573
+ this.sendFrame(proto_1.FrameKind.RespBody, ctx.rid, chunk);
574
+ }
575
+ });
576
+ }
577
+ sendLocalError(ctx, reason) {
578
+ const body = Buffer.from(`virun: cannot reach localhost:${this.port} (${reason})
579
+ `, "utf8");
580
+ this.sendCtrl({
581
+ t: "resp-start",
582
+ rid: ctx.rid,
583
+ status: 502,
584
+ statusText: "Bad Gateway",
585
+ headers: {
586
+ "content-type": "text/plain; charset=utf-8",
587
+ "content-length": String(body.length)
588
+ }
589
+ });
590
+ this.sendFrame(proto_1.FrameKind.RespBody, ctx.rid, body);
591
+ this.sendCtrl({ t: "resp-end", rid: ctx.rid });
592
+ ctx.respStarted = true;
593
+ ctx.status = 502;
594
+ }
595
+ closeCtx(ctx, err) {
596
+ if (ctx.ended)
597
+ return;
598
+ ctx.ended = true;
599
+ this.ctxs.delete(ctx.rid);
600
+ if (ctx.pipe)
601
+ this.sendCtrl({ t: "close", rid: ctx.rid });
602
+ try {
603
+ ctx.req?.destroy();
604
+ } catch {
605
+ }
606
+ try {
607
+ ctx.res?.destroy();
608
+ } catch {
609
+ }
610
+ try {
611
+ ctx.sock?.destroy();
612
+ } catch {
613
+ }
614
+ this.emit("request", {
615
+ method: ctx.method,
616
+ url: ctx.url,
617
+ status: ctx.status ?? 0,
618
+ ms: Date.now() - ctx.startedAt,
619
+ bytesIn: ctx.bytesIn,
620
+ bytesOut: ctx.bytesOut,
621
+ ...err ? { err } : {}
622
+ });
623
+ }
624
+ /** tear down every in-flight exchange (relay connection lost) */
625
+ failCtxs() {
626
+ for (const ctx of [...this.ctxs.values()])
627
+ this.closeCtx(ctx, "relay connection lost");
628
+ this.ctxs.clear();
629
+ }
630
+ resumeSockets() {
631
+ const ws = this.ws;
632
+ if (!ws || ws.readyState !== ws_1.default.OPEN || ws.bufferedAmount > 1024 * 1024)
633
+ return;
634
+ for (const c of this.ctxs.values()) {
635
+ if (c.paused && c.sock) {
636
+ c.paused = false;
637
+ c.sock.resume();
638
+ }
639
+ }
640
+ }
641
+ // -- us -> relay -----------------------------------------------------------
642
+ sendCtrl(msg) {
643
+ const ws = this.ws;
644
+ if (ws && ws.readyState === ws_1.default.OPEN)
645
+ ws.send(JSON.stringify(msg));
646
+ }
647
+ sendFrame(kind, rid, payload) {
648
+ const ws = this.ws;
649
+ if (ws && ws.readyState === ws_1.default.OPEN)
650
+ ws.send((0, proto_1.encodeFrame)(kind, rid, payload));
651
+ }
652
+ };
653
+ exports2.Tunnel = Tunnel;
654
+ function startTunnel2(opts) {
655
+ return new Tunnel(opts);
656
+ }
657
+ function sanitizeId2(raw) {
658
+ const s = raw.trim().toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, "").slice(0, 24).replace(/-+$/g, "");
659
+ return /^[a-z0-9][a-z0-9-]*$/.test(s) ? s : null;
660
+ }
661
+ function defaultIdFromDir2(dir) {
662
+ try {
663
+ const pkg = JSON.parse(node_fs_1.default.readFileSync(node_path_1.default.join(dir, "package.json"), "utf8"));
664
+ const name = typeof pkg?.name === "string" ? pkg.name.split("/").pop() ?? "" : "";
665
+ const id = sanitizeId2(name);
666
+ if (id)
667
+ return id;
668
+ } catch {
669
+ }
670
+ return sanitizeId2(node_path_1.default.basename(dir)) ?? "app";
671
+ }
672
+ }
673
+ });
674
+
675
+ // src/index.ts
676
+ var import_core = __toESM(require_dist2());
677
+ var VERSION = "0.1.0";
678
+ var DEFAULT_RELAY = "wss://relay.run.vishota.com";
679
+ var USAGE = `virunx ${VERSION} \u2014 expose a local port behind a public link
680
+
681
+ usage
682
+ virunx -p <port> [options]
683
+
684
+ options
685
+ -p, --port <n> local port to tunnel (required)
686
+ -s, --sub <name> subdomain (default: project name)
687
+ -r, --relay <url> relay url (default: ${DEFAULT_RELAY})
688
+ -t, --token <tok> relay token (or set VIRUN_TOKEN)
689
+ -y, --yes skip the security notice
690
+ -h, --help show this help
691
+
692
+ more
693
+ virunx help hosts fix "Blocked request" / "Invalid Host header" errors
694
+
695
+ examples
696
+ virunx -p 3000
697
+ virunx -p 5173 -s myapp
698
+ virunx -p 8000 -r ws://relay.example.com
699
+ `;
700
+ var HOSTS_HELP = `fixing "Blocked request" / "Invalid Host header" while tunneling
701
+
702
+ some dev servers only accept requests addressed to localhost. through virunx
703
+ the Host header is the public subdomain, so they reject it. allow virunx's
704
+ host in your dev server config and restart it:
705
+
706
+ vite vite.config.js
707
+ export default defineConfig({
708
+ server: { allowedHosts: ['.run.vishota.com'] }
709
+ })
710
+
711
+ webpack webpack.config.js -> devServer
712
+ allowedHosts: 'all' // dev only!
713
+
714
+ angular ng serve --disable-host-check
715
+ (newer versions: "allowedHosts" in angular.json serve options)
716
+
717
+ next.js works out of the box with "next dev"
718
+
719
+ other search your dev server docs for "allowedHosts" or "host check"
720
+
721
+ if you use a different relay domain, replace ".run.vishota.com" accordingly.
722
+ `;
723
+ var ArgError = class extends Error {
724
+ };
725
+ function parseArgs(argv) {
726
+ const out = { yes: false, help: false };
727
+ for (let i = 0; i < argv.length; i++) {
728
+ let a = argv[i];
729
+ let inline;
730
+ if (a.startsWith("--")) {
731
+ const eq = a.indexOf("=");
732
+ if (eq !== -1) {
733
+ inline = a.slice(eq + 1);
734
+ a = a.slice(0, eq);
735
+ }
736
+ }
737
+ const value = () => {
738
+ const v = inline !== void 0 ? inline : argv[++i];
739
+ if (v === void 0 || v.startsWith("-")) throw new ArgError(`missing value for ${a}`);
740
+ return v;
741
+ };
742
+ if (a === "-h" || a === "--help") out.help = true;
743
+ else if (a === "-y" || a === "--yes") out.yes = true;
744
+ else if (a === "-p" || a === "--port") out.port = Number(value());
745
+ else if (a === "-s" || a === "--sub") out.sub = value();
746
+ else if (a === "-r" || a === "--relay") out.relay = value();
747
+ else if (a === "-t" || a === "--token") out.token = value();
748
+ else throw new ArgError(`unknown option: ${a}`);
749
+ }
750
+ return out;
751
+ }
752
+ function fmtBytes(n) {
753
+ if (n < 1024) return `${n}B`;
754
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)}KB`;
755
+ return `${(n / (1024 * 1024)).toFixed(1)}MB`;
756
+ }
757
+ function describeHost(id, relay) {
758
+ try {
759
+ const h = new URL(relay).hostname;
760
+ if (h.startsWith("relay.")) return `${id}.${h.slice("relay.".length)}`;
761
+ return `${id} via ${h}`;
762
+ } catch {
763
+ return id;
764
+ }
765
+ }
766
+ function main() {
767
+ const argv = process.argv.slice(2);
768
+ if (argv[0] === "hosts" || argv[0] === "help" && argv[1] === "hosts") {
769
+ process.stdout.write(HOSTS_HELP);
770
+ process.exit(0);
771
+ }
772
+ let args;
773
+ try {
774
+ args = parseArgs(argv);
775
+ } catch (e) {
776
+ process.stderr.write(`error: ${e.message}
777
+
778
+ ${USAGE}`);
779
+ process.exit(1);
780
+ }
781
+ if (args.help || argv[0] === "help") {
782
+ process.stdout.write(USAGE);
783
+ process.exit(0);
784
+ }
785
+ if (args.port === void 0) {
786
+ process.stderr.write(`error: -p/--port is required
787
+
788
+ ${USAGE}`);
789
+ process.exit(1);
790
+ }
791
+ if (!Number.isInteger(args.port) || args.port < 1 || args.port > 65535) {
792
+ process.stderr.write("error: -p must be a port number (1-65535)\n");
793
+ process.exit(1);
794
+ }
795
+ const id = args.sub !== void 0 ? (0, import_core.sanitizeId)(args.sub) : (0, import_core.defaultIdFromDir)(process.cwd());
796
+ if (!id) {
797
+ process.stderr.write(`error: "${args.sub}" is not a valid subdomain (use a-z, 0-9, -)
798
+ `);
799
+ process.exit(1);
800
+ }
801
+ const relay = args.relay ?? DEFAULT_RELAY;
802
+ if (!/^wss?:\/\//i.test(relay)) {
803
+ process.stderr.write("error: --relay must be a ws:// or wss:// url\n");
804
+ process.exit(1);
805
+ }
806
+ const token = args.token ?? process.env.VIRUN_TOKEN;
807
+ console.log(`virunx ${VERSION}`);
808
+ console.log(` relay ${relay}`);
809
+ console.log(` target ${describeHost(id, relay)} -> localhost:${args.port}`);
810
+ console.log();
811
+ if (!args.yes) {
812
+ console.log(" ! the link is public: anyone who has it can reach this app");
813
+ console.log(" ! dev servers may block public hosts - fix: virunx help hosts");
814
+ console.log(" ! don't tunnel apps with real secrets or admin panels");
815
+ console.log();
816
+ }
817
+ const t = (0, import_core.startTunnel)({ relay, id, port: args.port, ...token ? { token } : {} });
818
+ t.on("url", (url, tid) => {
819
+ const shown = url ?? `tunnel "${tid}" online (direct relay, no public url)`;
820
+ console.log(` live ${shown}`);
821
+ console.log(" press Ctrl+C to stop");
822
+ console.log();
823
+ });
824
+ t.on("status", (s, info) => {
825
+ if (s === "reconnecting") {
826
+ console.log(" -- relay connection lost, retrying");
827
+ } else if (s === "error") {
828
+ console.error(`
829
+ error ${info?.message ?? "unknown error"}${info?.code ? ` (${info.code})` : ""}`);
830
+ process.exit(1);
831
+ }
832
+ });
833
+ t.on("request", (r) => {
834
+ const time = (/* @__PURE__ */ new Date()).toTimeString().slice(0, 8);
835
+ const url = r.url.length > 40 ? `${r.url.slice(0, 39)}~` : r.url;
836
+ const err = r.err ? ` !${r.err}` : "";
837
+ console.log(
838
+ ` ${time} ${r.method.padEnd(7)} ${url.padEnd(40)} ${String(r.status).padStart(3)} ${String(r.ms).padStart(7)}ms ${fmtBytes(r.bytesOut).padStart(9)}${err}`
839
+ );
840
+ });
841
+ let stopping = false;
842
+ const stop = () => {
843
+ if (stopping) process.exit(130);
844
+ stopping = true;
845
+ process.stdout.write("\n stopping...\n");
846
+ void t.stop().then(() => process.exit(0));
847
+ };
848
+ process.on("SIGINT", stop);
849
+ process.on("SIGTERM", stop);
850
+ }
851
+ main();
package/package.json CHANGED
@@ -1,6 +1,25 @@
1
1
  {
2
2
  "name": "virunx",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "expose a local port behind a public link (virun tunnel CLI)",
5
+ "license": "MIT",
6
+ "repository": "github:Vishota/virun",
7
+ "bin": {
8
+ "virunx": "dist/index.js"
9
+ },
10
+ "files": [
11
+ "dist"
12
+ ],
13
+ "engines": {
14
+ "node": ">=18"
15
+ },
16
+ "scripts": {
17
+ "build": "esbuild src/index.ts --bundle --platform=node --format=cjs --external:ws --banner:js=\"#!/usr/bin/env node\" --outfile=dist/index.js"
18
+ },
19
+ "dependencies": {
20
+ "ws": "^8.18.0"
21
+ },
22
+ "devDependencies": {
23
+ "esbuild": "^0.25.0"
24
+ }
25
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.