virunx 0.0.0-stage → 0.1.1
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/index.js +853 -0
- package/package.json +23 -4
- package/README.md +0 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,853 @@
|
|
|
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 opts = {
|
|
369
|
+
host: "localhost",
|
|
370
|
+
port: this.port,
|
|
371
|
+
autoSelectFamily: true,
|
|
372
|
+
method: msg.method,
|
|
373
|
+
path: msg.url,
|
|
374
|
+
headers,
|
|
375
|
+
agent: this.agent
|
|
376
|
+
};
|
|
377
|
+
const req = node_http_1.default.request(opts, (res) => {
|
|
378
|
+
ctx.res = res;
|
|
379
|
+
ctx.status = res.statusCode ?? 502;
|
|
380
|
+
const rh = {};
|
|
381
|
+
for (const [k, v] of Object.entries(res.headers)) {
|
|
382
|
+
if (v !== void 0)
|
|
383
|
+
rh[k] = v;
|
|
384
|
+
}
|
|
385
|
+
for (const h of HOP_HEADERS)
|
|
386
|
+
delete rh[h];
|
|
387
|
+
this.sendCtrl({
|
|
388
|
+
t: "resp-start",
|
|
389
|
+
rid: ctx.rid,
|
|
390
|
+
status: ctx.status,
|
|
391
|
+
statusText: res.statusMessage,
|
|
392
|
+
headers: rh
|
|
393
|
+
});
|
|
394
|
+
ctx.respStarted = true;
|
|
395
|
+
const sendBody = (buf) => {
|
|
396
|
+
const win = ctx.creditLeft;
|
|
397
|
+
if (typeof win !== "number") {
|
|
398
|
+
ctx.bytesOut += buf.length;
|
|
399
|
+
this.sendFrame(proto_1.FrameKind.RespBody, ctx.rid, buf);
|
|
400
|
+
return;
|
|
401
|
+
}
|
|
402
|
+
let left = win;
|
|
403
|
+
let off = 0;
|
|
404
|
+
while (off < buf.length) {
|
|
405
|
+
if (left <= 0) {
|
|
406
|
+
ctx.creditLeft = left;
|
|
407
|
+
ctx.pendingBufs.push(buf.subarray(off));
|
|
408
|
+
if (!ctx.pausedByCredit) {
|
|
409
|
+
ctx.pausedByCredit = true;
|
|
410
|
+
try {
|
|
411
|
+
res.pause();
|
|
412
|
+
} catch {
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
return;
|
|
416
|
+
}
|
|
417
|
+
const take = Math.min(BODY_CHUNK, buf.length - off);
|
|
418
|
+
const part = buf.subarray(off, off + take);
|
|
419
|
+
ctx.bytesOut += take;
|
|
420
|
+
this.sendFrame(proto_1.FrameKind.RespBody, ctx.rid, part);
|
|
421
|
+
left -= take;
|
|
422
|
+
off += take;
|
|
423
|
+
}
|
|
424
|
+
ctx.creditLeft = left;
|
|
425
|
+
};
|
|
426
|
+
res.on("data", (chunk) => sendBody(chunk));
|
|
427
|
+
res.on("end", () => {
|
|
428
|
+
this.sendCtrl({ t: "resp-end", rid: ctx.rid });
|
|
429
|
+
this.closeCtx(ctx);
|
|
430
|
+
});
|
|
431
|
+
const onResFail = (err) => {
|
|
432
|
+
if (ctx.ended)
|
|
433
|
+
return;
|
|
434
|
+
if (!ctx.respStarted)
|
|
435
|
+
this.sendLocalError(ctx, err.message);
|
|
436
|
+
else
|
|
437
|
+
this.sendCtrl({ t: "resp-end", rid: ctx.rid });
|
|
438
|
+
this.closeCtx(ctx, err.message);
|
|
439
|
+
};
|
|
440
|
+
res.on("error", onResFail);
|
|
441
|
+
res.on("aborted", () => onResFail(new Error("response aborted")));
|
|
442
|
+
});
|
|
443
|
+
ctx.req = req;
|
|
444
|
+
req.on("error", (err) => {
|
|
445
|
+
if (ctx.ended)
|
|
446
|
+
return;
|
|
447
|
+
if (!ctx.respStarted)
|
|
448
|
+
this.sendLocalError(ctx, err.message);
|
|
449
|
+
else
|
|
450
|
+
this.sendCtrl({ t: "resp-end", rid: ctx.rid });
|
|
451
|
+
this.closeCtx(ctx, err.message);
|
|
452
|
+
});
|
|
453
|
+
}
|
|
454
|
+
startUpgrade(ctx, msg) {
|
|
455
|
+
const sock = node_net_1.default.connect({ host: "localhost", port: this.port, autoSelectFamily: true });
|
|
456
|
+
ctx.sock = sock;
|
|
457
|
+
ctx.hsBuf = Buffer.alloc(0);
|
|
458
|
+
let failed = false;
|
|
459
|
+
const fail = (reason, status = 502) => {
|
|
460
|
+
if (failed || ctx.ended)
|
|
461
|
+
return;
|
|
462
|
+
failed = true;
|
|
463
|
+
if (!ctx.respStarted) {
|
|
464
|
+
const body = Buffer.from(`virun: upgrade failed: ${reason}
|
|
465
|
+
`, "utf8");
|
|
466
|
+
this.sendCtrl({
|
|
467
|
+
t: "resp-start",
|
|
468
|
+
rid: ctx.rid,
|
|
469
|
+
status,
|
|
470
|
+
statusText: "Bad Gateway",
|
|
471
|
+
headers: {
|
|
472
|
+
"content-type": "text/plain; charset=utf-8",
|
|
473
|
+
"content-length": String(body.length)
|
|
474
|
+
}
|
|
475
|
+
});
|
|
476
|
+
this.sendFrame(proto_1.FrameKind.RespBody, ctx.rid, body);
|
|
477
|
+
this.sendCtrl({ t: "resp-end", rid: ctx.rid });
|
|
478
|
+
ctx.respStarted = true;
|
|
479
|
+
ctx.status = status;
|
|
480
|
+
}
|
|
481
|
+
this.closeCtx(ctx, reason);
|
|
482
|
+
};
|
|
483
|
+
sock.setTimeout(1e4, () => fail("local handshake timeout", 504));
|
|
484
|
+
sock.on("error", (err) => fail(err.message));
|
|
485
|
+
sock.on("close", () => {
|
|
486
|
+
if (ctx.ended)
|
|
487
|
+
return;
|
|
488
|
+
if (ctx.pipe) {
|
|
489
|
+
this.sendCtrl({ t: "close", rid: ctx.rid });
|
|
490
|
+
this.closeCtx(ctx, "local socket closed");
|
|
491
|
+
} else if (ctx.hsDone) {
|
|
492
|
+
this.sendCtrl({ t: "resp-end", rid: ctx.rid });
|
|
493
|
+
this.closeCtx(ctx);
|
|
494
|
+
} else {
|
|
495
|
+
this.closeCtx(ctx, "local socket closed before handshake");
|
|
496
|
+
}
|
|
497
|
+
});
|
|
498
|
+
let head = `${msg.method} ${msg.url} HTTP/1.1\r
|
|
499
|
+
`;
|
|
500
|
+
for (const [k, v] of Object.entries(msg.headers)) {
|
|
501
|
+
head += `${k}: ${Array.isArray(v) ? v.join(", ") : v}\r
|
|
502
|
+
`;
|
|
503
|
+
}
|
|
504
|
+
head += "\r\n";
|
|
505
|
+
sock.write(head);
|
|
506
|
+
sock.on("data", (chunk) => {
|
|
507
|
+
if (ctx.ended)
|
|
508
|
+
return;
|
|
509
|
+
if (!ctx.hsDone) {
|
|
510
|
+
ctx.hsBuf = Buffer.concat([ctx.hsBuf, chunk]);
|
|
511
|
+
const idx = ctx.hsBuf.indexOf("\r\n\r\n");
|
|
512
|
+
if (idx === -1) {
|
|
513
|
+
if (ctx.hsBuf.length > 64 * 1024)
|
|
514
|
+
fail("handshake too large");
|
|
515
|
+
return;
|
|
516
|
+
}
|
|
517
|
+
const headStr = ctx.hsBuf.toString("latin1", 0, idx);
|
|
518
|
+
const rest = ctx.hsBuf.subarray(idx + 4);
|
|
519
|
+
ctx.hsBuf = Buffer.alloc(0);
|
|
520
|
+
ctx.hsDone = true;
|
|
521
|
+
sock.setTimeout(0);
|
|
522
|
+
const lines = headStr.split("\r\n");
|
|
523
|
+
const m = /^HTTP\/1\.[01] (\d{3})(?: (.*))?$/.exec(lines[0] ?? "");
|
|
524
|
+
if (!m) {
|
|
525
|
+
fail("malformed local handshake");
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
528
|
+
const status = parseInt(m[1], 10);
|
|
529
|
+
const headers = {};
|
|
530
|
+
for (let i = 1; i < lines.length; i++) {
|
|
531
|
+
const ci = lines[i].indexOf(":");
|
|
532
|
+
if (ci <= 0)
|
|
533
|
+
continue;
|
|
534
|
+
const k = lines[i].slice(0, ci).trim().toLowerCase();
|
|
535
|
+
const v = lines[i].slice(ci + 1).trim();
|
|
536
|
+
if (k in headers) {
|
|
537
|
+
const prev = headers[k];
|
|
538
|
+
headers[k] = Array.isArray(prev) ? [...prev, v] : [prev, v];
|
|
539
|
+
} else {
|
|
540
|
+
headers[k] = v;
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
ctx.status = status;
|
|
544
|
+
this.sendCtrl({
|
|
545
|
+
t: "resp-start",
|
|
546
|
+
rid: ctx.rid,
|
|
547
|
+
status,
|
|
548
|
+
statusText: m[2] || void 0,
|
|
549
|
+
headers
|
|
550
|
+
});
|
|
551
|
+
ctx.respStarted = true;
|
|
552
|
+
if (status === 101) {
|
|
553
|
+
ctx.pipe = true;
|
|
554
|
+
sock.setNoDelay(true);
|
|
555
|
+
if (rest.length) {
|
|
556
|
+
ctx.bytesOut += rest.length;
|
|
557
|
+
this.sendFrame(proto_1.FrameKind.WsDown, ctx.rid, rest);
|
|
558
|
+
}
|
|
559
|
+
} else if (rest.length) {
|
|
560
|
+
ctx.bytesOut += rest.length;
|
|
561
|
+
this.sendFrame(proto_1.FrameKind.RespBody, ctx.rid, rest);
|
|
562
|
+
}
|
|
563
|
+
return;
|
|
564
|
+
}
|
|
565
|
+
if (ctx.pipe) {
|
|
566
|
+
ctx.bytesOut += chunk.length;
|
|
567
|
+
const ws = this.ws;
|
|
568
|
+
if (ws && ws.bufferedAmount > 4 * 1024 * 1024) {
|
|
569
|
+
sock.pause();
|
|
570
|
+
ctx.paused = true;
|
|
571
|
+
}
|
|
572
|
+
this.sendFrame(proto_1.FrameKind.WsDown, ctx.rid, chunk);
|
|
573
|
+
} else {
|
|
574
|
+
ctx.bytesOut += chunk.length;
|
|
575
|
+
this.sendFrame(proto_1.FrameKind.RespBody, ctx.rid, chunk);
|
|
576
|
+
}
|
|
577
|
+
});
|
|
578
|
+
}
|
|
579
|
+
sendLocalError(ctx, reason) {
|
|
580
|
+
const body = Buffer.from(`virun: cannot reach localhost:${this.port} (${reason})
|
|
581
|
+
`, "utf8");
|
|
582
|
+
this.sendCtrl({
|
|
583
|
+
t: "resp-start",
|
|
584
|
+
rid: ctx.rid,
|
|
585
|
+
status: 502,
|
|
586
|
+
statusText: "Bad Gateway",
|
|
587
|
+
headers: {
|
|
588
|
+
"content-type": "text/plain; charset=utf-8",
|
|
589
|
+
"content-length": String(body.length)
|
|
590
|
+
}
|
|
591
|
+
});
|
|
592
|
+
this.sendFrame(proto_1.FrameKind.RespBody, ctx.rid, body);
|
|
593
|
+
this.sendCtrl({ t: "resp-end", rid: ctx.rid });
|
|
594
|
+
ctx.respStarted = true;
|
|
595
|
+
ctx.status = 502;
|
|
596
|
+
}
|
|
597
|
+
closeCtx(ctx, err) {
|
|
598
|
+
if (ctx.ended)
|
|
599
|
+
return;
|
|
600
|
+
ctx.ended = true;
|
|
601
|
+
this.ctxs.delete(ctx.rid);
|
|
602
|
+
if (ctx.pipe)
|
|
603
|
+
this.sendCtrl({ t: "close", rid: ctx.rid });
|
|
604
|
+
try {
|
|
605
|
+
ctx.req?.destroy();
|
|
606
|
+
} catch {
|
|
607
|
+
}
|
|
608
|
+
try {
|
|
609
|
+
ctx.res?.destroy();
|
|
610
|
+
} catch {
|
|
611
|
+
}
|
|
612
|
+
try {
|
|
613
|
+
ctx.sock?.destroy();
|
|
614
|
+
} catch {
|
|
615
|
+
}
|
|
616
|
+
this.emit("request", {
|
|
617
|
+
method: ctx.method,
|
|
618
|
+
url: ctx.url,
|
|
619
|
+
status: ctx.status ?? 0,
|
|
620
|
+
ms: Date.now() - ctx.startedAt,
|
|
621
|
+
bytesIn: ctx.bytesIn,
|
|
622
|
+
bytesOut: ctx.bytesOut,
|
|
623
|
+
...err ? { err } : {}
|
|
624
|
+
});
|
|
625
|
+
}
|
|
626
|
+
/** tear down every in-flight exchange (relay connection lost) */
|
|
627
|
+
failCtxs() {
|
|
628
|
+
for (const ctx of [...this.ctxs.values()])
|
|
629
|
+
this.closeCtx(ctx, "relay connection lost");
|
|
630
|
+
this.ctxs.clear();
|
|
631
|
+
}
|
|
632
|
+
resumeSockets() {
|
|
633
|
+
const ws = this.ws;
|
|
634
|
+
if (!ws || ws.readyState !== ws_1.default.OPEN || ws.bufferedAmount > 1024 * 1024)
|
|
635
|
+
return;
|
|
636
|
+
for (const c of this.ctxs.values()) {
|
|
637
|
+
if (c.paused && c.sock) {
|
|
638
|
+
c.paused = false;
|
|
639
|
+
c.sock.resume();
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
// -- us -> relay -----------------------------------------------------------
|
|
644
|
+
sendCtrl(msg) {
|
|
645
|
+
const ws = this.ws;
|
|
646
|
+
if (ws && ws.readyState === ws_1.default.OPEN)
|
|
647
|
+
ws.send(JSON.stringify(msg));
|
|
648
|
+
}
|
|
649
|
+
sendFrame(kind, rid, payload) {
|
|
650
|
+
const ws = this.ws;
|
|
651
|
+
if (ws && ws.readyState === ws_1.default.OPEN)
|
|
652
|
+
ws.send((0, proto_1.encodeFrame)(kind, rid, payload));
|
|
653
|
+
}
|
|
654
|
+
};
|
|
655
|
+
exports2.Tunnel = Tunnel;
|
|
656
|
+
function startTunnel2(opts) {
|
|
657
|
+
return new Tunnel(opts);
|
|
658
|
+
}
|
|
659
|
+
function sanitizeId2(raw) {
|
|
660
|
+
const s = raw.trim().toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, "").slice(0, 24).replace(/-+$/g, "");
|
|
661
|
+
return /^[a-z0-9][a-z0-9-]*$/.test(s) ? s : null;
|
|
662
|
+
}
|
|
663
|
+
function defaultIdFromDir2(dir) {
|
|
664
|
+
try {
|
|
665
|
+
const pkg = JSON.parse(node_fs_1.default.readFileSync(node_path_1.default.join(dir, "package.json"), "utf8"));
|
|
666
|
+
const name = typeof pkg?.name === "string" ? pkg.name.split("/").pop() ?? "" : "";
|
|
667
|
+
const id = sanitizeId2(name);
|
|
668
|
+
if (id)
|
|
669
|
+
return id;
|
|
670
|
+
} catch {
|
|
671
|
+
}
|
|
672
|
+
return sanitizeId2(node_path_1.default.basename(dir)) ?? "app";
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
});
|
|
676
|
+
|
|
677
|
+
// src/index.ts
|
|
678
|
+
var import_core = __toESM(require_dist2());
|
|
679
|
+
var VERSION = "0.1.0";
|
|
680
|
+
var DEFAULT_RELAY = "wss://relay.run.vishota.com";
|
|
681
|
+
var USAGE = `virunx ${VERSION} \u2014 expose a local port behind a public link
|
|
682
|
+
|
|
683
|
+
usage
|
|
684
|
+
virunx -p <port> [options]
|
|
685
|
+
|
|
686
|
+
options
|
|
687
|
+
-p, --port <n> local port to tunnel (required)
|
|
688
|
+
-s, --sub <name> subdomain (default: project name)
|
|
689
|
+
-r, --relay <url> relay url (default: ${DEFAULT_RELAY})
|
|
690
|
+
-t, --token <tok> relay token (or set VIRUN_TOKEN)
|
|
691
|
+
-y, --yes skip the security notice
|
|
692
|
+
-h, --help show this help
|
|
693
|
+
|
|
694
|
+
more
|
|
695
|
+
virunx help hosts fix "Blocked request" / "Invalid Host header" errors
|
|
696
|
+
|
|
697
|
+
examples
|
|
698
|
+
virunx -p 3000
|
|
699
|
+
virunx -p 5173 -s myapp
|
|
700
|
+
virunx -p 8000 -r ws://relay.example.com
|
|
701
|
+
`;
|
|
702
|
+
var HOSTS_HELP = `fixing "Blocked request" / "Invalid Host header" while tunneling
|
|
703
|
+
|
|
704
|
+
some dev servers only accept requests addressed to localhost. through virunx
|
|
705
|
+
the Host header is the public subdomain, so they reject it. allow virunx's
|
|
706
|
+
host in your dev server config and restart it:
|
|
707
|
+
|
|
708
|
+
vite vite.config.js
|
|
709
|
+
export default defineConfig({
|
|
710
|
+
server: { allowedHosts: ['.run.vishota.com'] }
|
|
711
|
+
})
|
|
712
|
+
|
|
713
|
+
webpack webpack.config.js -> devServer
|
|
714
|
+
allowedHosts: 'all' // dev only!
|
|
715
|
+
|
|
716
|
+
angular ng serve --disable-host-check
|
|
717
|
+
(newer versions: "allowedHosts" in angular.json serve options)
|
|
718
|
+
|
|
719
|
+
next.js works out of the box with "next dev"
|
|
720
|
+
|
|
721
|
+
other search your dev server docs for "allowedHosts" or "host check"
|
|
722
|
+
|
|
723
|
+
if you use a different relay domain, replace ".run.vishota.com" accordingly.
|
|
724
|
+
`;
|
|
725
|
+
var ArgError = class extends Error {
|
|
726
|
+
};
|
|
727
|
+
function parseArgs(argv) {
|
|
728
|
+
const out = { yes: false, help: false };
|
|
729
|
+
for (let i = 0; i < argv.length; i++) {
|
|
730
|
+
let a = argv[i];
|
|
731
|
+
let inline;
|
|
732
|
+
if (a.startsWith("--")) {
|
|
733
|
+
const eq = a.indexOf("=");
|
|
734
|
+
if (eq !== -1) {
|
|
735
|
+
inline = a.slice(eq + 1);
|
|
736
|
+
a = a.slice(0, eq);
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
const value = () => {
|
|
740
|
+
const v = inline !== void 0 ? inline : argv[++i];
|
|
741
|
+
if (v === void 0 || v.startsWith("-")) throw new ArgError(`missing value for ${a}`);
|
|
742
|
+
return v;
|
|
743
|
+
};
|
|
744
|
+
if (a === "-h" || a === "--help") out.help = true;
|
|
745
|
+
else if (a === "-y" || a === "--yes") out.yes = true;
|
|
746
|
+
else if (a === "-p" || a === "--port") out.port = Number(value());
|
|
747
|
+
else if (a === "-s" || a === "--sub") out.sub = value();
|
|
748
|
+
else if (a === "-r" || a === "--relay") out.relay = value();
|
|
749
|
+
else if (a === "-t" || a === "--token") out.token = value();
|
|
750
|
+
else throw new ArgError(`unknown option: ${a}`);
|
|
751
|
+
}
|
|
752
|
+
return out;
|
|
753
|
+
}
|
|
754
|
+
function fmtBytes(n) {
|
|
755
|
+
if (n < 1024) return `${n}B`;
|
|
756
|
+
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)}KB`;
|
|
757
|
+
return `${(n / (1024 * 1024)).toFixed(1)}MB`;
|
|
758
|
+
}
|
|
759
|
+
function describeHost(id, relay) {
|
|
760
|
+
try {
|
|
761
|
+
const h = new URL(relay).hostname;
|
|
762
|
+
if (h.startsWith("relay.")) return `${id}.${h.slice("relay.".length)}`;
|
|
763
|
+
return `${id} via ${h}`;
|
|
764
|
+
} catch {
|
|
765
|
+
return id;
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
function main() {
|
|
769
|
+
const argv = process.argv.slice(2);
|
|
770
|
+
if (argv[0] === "hosts" || argv[0] === "help" && argv[1] === "hosts") {
|
|
771
|
+
process.stdout.write(HOSTS_HELP);
|
|
772
|
+
process.exit(0);
|
|
773
|
+
}
|
|
774
|
+
let args;
|
|
775
|
+
try {
|
|
776
|
+
args = parseArgs(argv);
|
|
777
|
+
} catch (e) {
|
|
778
|
+
process.stderr.write(`error: ${e.message}
|
|
779
|
+
|
|
780
|
+
${USAGE}`);
|
|
781
|
+
process.exit(1);
|
|
782
|
+
}
|
|
783
|
+
if (args.help || argv[0] === "help") {
|
|
784
|
+
process.stdout.write(USAGE);
|
|
785
|
+
process.exit(0);
|
|
786
|
+
}
|
|
787
|
+
if (args.port === void 0) {
|
|
788
|
+
process.stderr.write(`error: -p/--port is required
|
|
789
|
+
|
|
790
|
+
${USAGE}`);
|
|
791
|
+
process.exit(1);
|
|
792
|
+
}
|
|
793
|
+
if (!Number.isInteger(args.port) || args.port < 1 || args.port > 65535) {
|
|
794
|
+
process.stderr.write("error: -p must be a port number (1-65535)\n");
|
|
795
|
+
process.exit(1);
|
|
796
|
+
}
|
|
797
|
+
const id = args.sub !== void 0 ? (0, import_core.sanitizeId)(args.sub) : (0, import_core.defaultIdFromDir)(process.cwd());
|
|
798
|
+
if (!id) {
|
|
799
|
+
process.stderr.write(`error: "${args.sub}" is not a valid subdomain (use a-z, 0-9, -)
|
|
800
|
+
`);
|
|
801
|
+
process.exit(1);
|
|
802
|
+
}
|
|
803
|
+
const relay = args.relay ?? DEFAULT_RELAY;
|
|
804
|
+
if (!/^wss?:\/\//i.test(relay)) {
|
|
805
|
+
process.stderr.write("error: --relay must be a ws:// or wss:// url\n");
|
|
806
|
+
process.exit(1);
|
|
807
|
+
}
|
|
808
|
+
const token = args.token ?? process.env.VIRUN_TOKEN;
|
|
809
|
+
console.log(`virunx ${VERSION}`);
|
|
810
|
+
console.log(` relay ${relay}`);
|
|
811
|
+
console.log(` target ${describeHost(id, relay)} -> localhost:${args.port}`);
|
|
812
|
+
console.log();
|
|
813
|
+
if (!args.yes) {
|
|
814
|
+
console.log(" ! the link is public: anyone who has it can reach this app");
|
|
815
|
+
console.log(" ! dev servers may block public hosts - fix: virunx help hosts");
|
|
816
|
+
console.log(" ! don't tunnel apps with real secrets or admin panels");
|
|
817
|
+
console.log();
|
|
818
|
+
}
|
|
819
|
+
const t = (0, import_core.startTunnel)({ relay, id, port: args.port, ...token ? { token } : {} });
|
|
820
|
+
t.on("url", (url, tid) => {
|
|
821
|
+
const shown = url ?? `tunnel "${tid}" online (direct relay, no public url)`;
|
|
822
|
+
console.log(` live ${shown}`);
|
|
823
|
+
console.log(" press Ctrl+C to stop");
|
|
824
|
+
console.log();
|
|
825
|
+
});
|
|
826
|
+
t.on("status", (s, info) => {
|
|
827
|
+
if (s === "reconnecting") {
|
|
828
|
+
console.log(" -- relay connection lost, retrying");
|
|
829
|
+
} else if (s === "error") {
|
|
830
|
+
console.error(`
|
|
831
|
+
error ${info?.message ?? "unknown error"}${info?.code ? ` (${info.code})` : ""}`);
|
|
832
|
+
process.exit(1);
|
|
833
|
+
}
|
|
834
|
+
});
|
|
835
|
+
t.on("request", (r) => {
|
|
836
|
+
const time = (/* @__PURE__ */ new Date()).toTimeString().slice(0, 8);
|
|
837
|
+
const url = r.url.length > 40 ? `${r.url.slice(0, 39)}~` : r.url;
|
|
838
|
+
const err = r.err ? ` !${r.err}` : "";
|
|
839
|
+
console.log(
|
|
840
|
+
` ${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}`
|
|
841
|
+
);
|
|
842
|
+
});
|
|
843
|
+
let stopping = false;
|
|
844
|
+
const stop = () => {
|
|
845
|
+
if (stopping) process.exit(130);
|
|
846
|
+
stopping = true;
|
|
847
|
+
process.stdout.write("\n stopping...\n");
|
|
848
|
+
void t.stop().then(() => process.exit(0));
|
|
849
|
+
};
|
|
850
|
+
process.on("SIGINT", stop);
|
|
851
|
+
process.on("SIGTERM", stop);
|
|
852
|
+
}
|
|
853
|
+
main();
|
package/package.json
CHANGED
|
@@ -1,6 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "virunx",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
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