portpreview 0.1.0 → 0.2.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.
- package/README.md +117 -31
- package/bin/portpreview.mjs +5 -61
- package/lib/cli-main.mjs +40 -0
- package/lib/client-info.mjs +83 -0
- package/lib/config-cli.mjs +65 -0
- package/lib/config.mjs +29 -8
- package/lib/geo.mjs +84 -0
- package/lib/http-stream.mjs +134 -0
- package/lib/index.mjs +10 -7
- package/lib/protocol.mjs +145 -10
- package/lib/tunnel-client.mjs +428 -57
- package/lib/user-config.mjs +81 -0
- package/package.json +20 -13
package/lib/tunnel-client.mjs
CHANGED
|
@@ -1,36 +1,44 @@
|
|
|
1
1
|
import http from 'node:http'
|
|
2
2
|
import net from 'node:net'
|
|
3
3
|
import { WebSocket } from 'ws'
|
|
4
|
-
import {
|
|
4
|
+
import {
|
|
5
|
+
attachedBody,
|
|
6
|
+
closeWebSocket,
|
|
7
|
+
localGatewayHttpUrl,
|
|
8
|
+
MAX_BODY_BYTES,
|
|
9
|
+
MAX_FRAME_BYTES,
|
|
10
|
+
LEGACY_PROTOCOL_VERSION,
|
|
11
|
+
parseMessage,
|
|
12
|
+
publicUrl,
|
|
13
|
+
PROTOCOL_VERSION,
|
|
14
|
+
send,
|
|
15
|
+
} from './protocol.mjs'
|
|
16
|
+
import { createHttpStream } from './http-stream.mjs'
|
|
5
17
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
export function waitForLocalPort({ host, port }) {
|
|
18
|
+
function abortError() { const error = new Error('Tunnel connection cancelled'); error.name = 'AbortError'; return error }
|
|
19
|
+
|
|
20
|
+
/** @param {{ host: string, port: number, signal?: AbortSignal }} options */
|
|
21
|
+
export function waitForLocalPort({ host, port, signal }) {
|
|
11
22
|
return new Promise((resolve, reject) => {
|
|
23
|
+
if (signal?.aborted) { reject(abortError()); return }
|
|
12
24
|
const socket = net.connect({ host, port })
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
})
|
|
17
|
-
socket.once('error',
|
|
18
|
-
|
|
19
|
-
})
|
|
20
|
-
socket.setTimeout(3000, () => {
|
|
21
|
-
socket.destroy()
|
|
22
|
-
reject(new Error(`Timed out waiting for http://${host}:${port}`))
|
|
23
|
-
})
|
|
25
|
+
const cleanup = () => { signal?.removeEventListener('abort', aborted); socket.setTimeout(0) }
|
|
26
|
+
const aborted = () => { cleanup(); socket.destroy(); reject(abortError()) }
|
|
27
|
+
signal?.addEventListener('abort', aborted, { once: true })
|
|
28
|
+
socket.once('connect', () => { cleanup(); socket.end(); resolve() })
|
|
29
|
+
socket.once('error', err => { cleanup(); reject(new Error(`Nothing is listening on http://${host}:${port} (${err.message})`)) })
|
|
30
|
+
socket.setTimeout(3000, () => { cleanup(); socket.destroy(); reject(new Error(`Timed out waiting for http://${host}:${port}`)) })
|
|
24
31
|
})
|
|
25
32
|
}
|
|
26
33
|
|
|
27
34
|
/**
|
|
28
35
|
* @param {import('ws').WebSocket} ws
|
|
29
|
-
* @param {string}
|
|
36
|
+
* @param {Record<string, unknown>} message
|
|
30
37
|
* @returns {Promise<Record<string, unknown>>}
|
|
31
38
|
*/
|
|
32
39
|
function waitForMessage(ws, type) {
|
|
33
40
|
return new Promise((resolve, reject) => {
|
|
41
|
+
const timer = setTimeout(() => { cleanup(); reject(new Error('Gateway registration timed out')) }, 10_000)
|
|
34
42
|
/** @param {import('ws').RawData} data */
|
|
35
43
|
const onMessage = (data) => {
|
|
36
44
|
try {
|
|
@@ -42,7 +50,9 @@ function waitForMessage(ws, type) {
|
|
|
42
50
|
}
|
|
43
51
|
if (message.type === 'error') {
|
|
44
52
|
cleanup()
|
|
45
|
-
|
|
53
|
+
const error = new Error(String(message.message ?? 'Gateway error'))
|
|
54
|
+
error.gatewayCode = message.code
|
|
55
|
+
reject(error)
|
|
46
56
|
}
|
|
47
57
|
} catch (err) {
|
|
48
58
|
cleanup()
|
|
@@ -50,9 +60,11 @@ function waitForMessage(ws, type) {
|
|
|
50
60
|
}
|
|
51
61
|
}
|
|
52
62
|
|
|
53
|
-
const onClose = () => {
|
|
63
|
+
const onClose = (code) => {
|
|
54
64
|
cleanup()
|
|
55
|
-
|
|
65
|
+
const error = new Error('Gateway connection closed before tunnel was ready')
|
|
66
|
+
error.closeCode = code
|
|
67
|
+
reject(error)
|
|
56
68
|
}
|
|
57
69
|
|
|
58
70
|
const onError = (err) => {
|
|
@@ -61,6 +73,7 @@ function waitForMessage(ws, type) {
|
|
|
61
73
|
}
|
|
62
74
|
|
|
63
75
|
const cleanup = () => {
|
|
76
|
+
clearTimeout(timer)
|
|
64
77
|
ws.off('message', onMessage)
|
|
65
78
|
ws.off('close', onClose)
|
|
66
79
|
ws.off('error', onError)
|
|
@@ -73,32 +86,145 @@ function waitForMessage(ws, type) {
|
|
|
73
86
|
}
|
|
74
87
|
|
|
75
88
|
/**
|
|
76
|
-
* @param {import('./config.mjs').TunnelOptions & { onRequest?: (info: { method: string, path: string }) => void }} options
|
|
77
|
-
* @returns {Promise<{ url: string, subdomain: string, close: () => Promise<void> }>}
|
|
89
|
+
* @param {import('./config.mjs').TunnelOptions & { signal?: AbortSignal, reconnect?: boolean, reconnectDelayMs?: number, reconnectMaxDelayMs?: number, reconnectJitter?: boolean, onRequest?: (info: { method: string, path: string }) => void, onReconnect?: (info: { url: string, previousUrl: string, subdomain: string, protocolVersion: number, streaming: boolean }) => void }} options
|
|
90
|
+
* @returns {Promise<{ url: string, subdomain: string, streaming: boolean, protocolVersion: number, closed: Promise<unknown>, close: () => Promise<void> }>}
|
|
91
|
+
*
|
|
92
|
+
* Reconnect transient transport failures. Interrupted HTTP requests fail and are
|
|
93
|
+
* never replayed; callers can observe a newly assigned anonymous URL via getters.
|
|
78
94
|
*/
|
|
79
95
|
export async function openTunnel(options) {
|
|
80
|
-
const
|
|
96
|
+
const controller = new AbortController()
|
|
97
|
+
let stopped = false, current, reconnecting, timer, releaseDelay
|
|
98
|
+
let finishClosed
|
|
99
|
+
const closed = new Promise(resolve => { finishClosed = resolve })
|
|
100
|
+
const stop = async () => {
|
|
101
|
+
if (stopped) return
|
|
102
|
+
stopped = true
|
|
103
|
+
clearTimeout(timer)
|
|
104
|
+
releaseDelay?.()
|
|
105
|
+
controller.abort()
|
|
106
|
+
await current?.close()
|
|
107
|
+
await reconnecting
|
|
108
|
+
options.signal?.removeEventListener('abort', externalAbort)
|
|
109
|
+
finishClosed()
|
|
110
|
+
}
|
|
111
|
+
const externalAbort = () => { void stop() }
|
|
112
|
+
if (options.signal?.aborted) throw abortError()
|
|
113
|
+
options.signal?.addEventListener('abort', externalAbort, { once: true })
|
|
114
|
+
try {
|
|
115
|
+
current = await openTunnelConnection({ ...options, signal: controller.signal })
|
|
116
|
+
if (stopped || controller.signal.aborted) { await current.close(); throw abortError() }
|
|
117
|
+
}
|
|
118
|
+
catch (error) { options.signal?.removeEventListener('abort', externalAbort); controller.abort(); throw error }
|
|
119
|
+
const terminal = (detail) => [4000, 4001, 4003, 1002, 1008].includes(detail.code)
|
|
120
|
+
const terminalError = error => [4000, 4001, 4003, 1002, 1008].includes(Number(error.closeCode ?? error.gatewayCode)) || /AUTH|ACCESS_REVOKED|SESSION_EXPIRED|MALFORMED_REGISTER|INVALID_REGISTER|UNSUPPORTED_PROTOCOL/.test(String(error.gatewayCode ?? '')) || /Gateway did not assign|Invalid message|authorization failed|access revoked|Invalid subdomain|Unsupported protocol version|Expected register|Reserved subdomains require|Authenticated tunnels are not configured/i.test(error.message)
|
|
121
|
+
const watch = connection => {
|
|
122
|
+
void connection.closed.then(detail => {
|
|
123
|
+
if (stopped) return
|
|
124
|
+
if (terminal(detail) || options.reconnect === false) { stopped = true; options.signal?.removeEventListener('abort', externalAbort); finishClosed(detail); return }
|
|
125
|
+
const run = reconnect(connection).finally(() => { if (reconnecting === run) reconnecting = null })
|
|
126
|
+
reconnecting = run
|
|
127
|
+
})
|
|
128
|
+
}
|
|
129
|
+
async function reconnect(previous) {
|
|
130
|
+
if (!options.quiet) console.error('Tunnel disconnected. Reconnecting…')
|
|
131
|
+
let attempt = 0
|
|
132
|
+
while (!stopped) {
|
|
133
|
+
const base = Math.max(1, options.reconnectDelayMs ?? 500)
|
|
134
|
+
const max = Math.max(base, options.reconnectMaxDelayMs ?? 30_000)
|
|
135
|
+
const delay = Math.min(max, base * 2 ** Math.min(attempt++, 10))
|
|
136
|
+
const jitter = options.reconnectJitter === false ? 1 : 0.8 + Math.random() * 0.4
|
|
137
|
+
await new Promise(resolve => { releaseDelay = resolve; timer = setTimeout(resolve, Math.ceil(Math.min(max, delay * jitter))) })
|
|
138
|
+
releaseDelay = null
|
|
139
|
+
if (stopped) break
|
|
140
|
+
try {
|
|
141
|
+
const replacement = await openTunnelConnection({ ...options, signal: controller.signal })
|
|
142
|
+
if (stopped) { await replacement.close(); break }
|
|
143
|
+
current = replacement
|
|
144
|
+
watch(replacement)
|
|
145
|
+
if (options.onReconnect) {
|
|
146
|
+
try {
|
|
147
|
+
void Promise.resolve(options.onReconnect({ url: replacement.url, previousUrl: previous.url, subdomain: replacement.subdomain, protocolVersion: replacement.protocolVersion, streaming: replacement.streaming })).catch(error => console.error(`Reconnect callback failed: ${error.message}`))
|
|
148
|
+
} catch (error) { console.error(`Reconnect callback failed: ${error.message}`) }
|
|
149
|
+
}
|
|
150
|
+
else if (options.quiet) console.log(replacement.url)
|
|
151
|
+
else console.log(`Reconnected. URL: ${replacement.url}`)
|
|
152
|
+
break
|
|
153
|
+
} catch (error) {
|
|
154
|
+
if (stopped || error.name === 'AbortError') break
|
|
155
|
+
if (terminalError(error)) {
|
|
156
|
+
stopped = true
|
|
157
|
+
console.error(`Tunnel reconnect stopped: ${error.message}`)
|
|
158
|
+
options.signal?.removeEventListener('abort', externalAbort)
|
|
159
|
+
finishClosed({ error })
|
|
160
|
+
break
|
|
161
|
+
}
|
|
162
|
+
if (!options.quiet) console.error(`Reconnect failed: ${error.message}`)
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
watch(current)
|
|
167
|
+
return {
|
|
168
|
+
get url() { return current.url }, get subdomain() { return current.subdomain },
|
|
169
|
+
get expiresAt() { return current.expiresAt }, get protocolVersion() { return current.protocolVersion },
|
|
170
|
+
get streaming() { return current.streaming },
|
|
171
|
+
closed, close: stop,
|
|
172
|
+
}
|
|
173
|
+
}
|
|
81
174
|
|
|
82
|
-
|
|
175
|
+
async function openTunnelConnection(options) {
|
|
176
|
+
const { host, port, subdomain, apiToken, gatewayUrl, tunnelDomain, quiet, onRequest } = options
|
|
177
|
+
/** @type {Map<string, { socket: import('ws').WebSocket, queue: Array<{ data: Buffer, isBinary: boolean }> }>} */
|
|
178
|
+
const localSockets = new Map()
|
|
83
179
|
|
|
84
|
-
const
|
|
180
|
+
const streams = new Map()
|
|
181
|
+
const protocolVersion = options.protocolVersion ?? PROTOCOL_VERSION
|
|
182
|
+
await waitForLocalPort({ host, port, signal: options.signal })
|
|
85
183
|
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
184
|
+
const ws = new WebSocket(gatewayUrl, { maxPayload: MAX_FRAME_BYTES, handshakeTimeout: 10_000 })
|
|
185
|
+
ws.on('error', () => {})
|
|
186
|
+
const closed = new Promise(resolve => ws.once('close', (code, reason) => resolve({ code, reason: reason.toString() })))
|
|
187
|
+
const aborted = () => ws.terminate()
|
|
188
|
+
options.signal?.addEventListener('abort', aborted, { once: true })
|
|
189
|
+
ws.once('close', () => options.signal?.removeEventListener('abort', aborted))
|
|
190
|
+
if (options.signal?.aborted) ws.terminate()
|
|
191
|
+
|
|
192
|
+
try {
|
|
193
|
+
await new Promise((resolve, reject) => {
|
|
194
|
+
ws.once('open', resolve)
|
|
195
|
+
ws.once('error', reject)
|
|
196
|
+
ws.once('close', () => reject(options.signal?.aborted ? abortError() : new Error('Gateway connection closed before opening')))
|
|
197
|
+
})
|
|
198
|
+
} catch (error) {
|
|
199
|
+
ws.terminate()
|
|
200
|
+
if (options.signal?.aborted) throw abortError()
|
|
201
|
+
throw error
|
|
202
|
+
}
|
|
90
203
|
|
|
91
204
|
send(ws, {
|
|
92
205
|
type: 'register',
|
|
93
|
-
version:
|
|
206
|
+
version: protocolVersion,
|
|
94
207
|
port,
|
|
95
208
|
host,
|
|
96
209
|
subdomain,
|
|
210
|
+
apiToken,
|
|
97
211
|
})
|
|
98
212
|
|
|
99
|
-
|
|
213
|
+
let registered
|
|
214
|
+
try { registered = await waitForMessage(ws, 'registered') }
|
|
215
|
+
catch (error) {
|
|
216
|
+
ws.terminate()
|
|
217
|
+
if (options.signal?.aborted) throw abortError()
|
|
218
|
+
if (protocolVersion === PROTOCOL_VERSION && /Unsupported protocol version/.test(error.message)) {
|
|
219
|
+
if (!quiet) console.error('Gateway supports legacy v2 only: HTTP bodies remain limited to 1 MiB. Upgrade the gateway for streaming.')
|
|
220
|
+
return openTunnelConnection({ ...options, protocolVersion: LEGACY_PROTOCOL_VERSION })
|
|
221
|
+
}
|
|
222
|
+
throw error
|
|
223
|
+
}
|
|
100
224
|
const assignedSubdomain = String(registered.subdomain ?? '')
|
|
101
|
-
if (!assignedSubdomain) throw new Error('Gateway did not assign a subdomain')
|
|
225
|
+
if (!assignedSubdomain) { ws.terminate(); throw new Error('Gateway did not assign a subdomain') }
|
|
226
|
+
options.signal?.removeEventListener('abort', aborted)
|
|
227
|
+
if (options.signal?.aborted) { ws.terminate(); throw abortError() }
|
|
102
228
|
|
|
103
229
|
const url =
|
|
104
230
|
tunnelDomain.includes(':') || tunnelDomain === 'localhost'
|
|
@@ -106,24 +232,49 @@ export async function openTunnel(options) {
|
|
|
106
232
|
: publicUrl(assignedSubdomain, tunnelDomain)
|
|
107
233
|
|
|
108
234
|
ws.on('message', (data) => {
|
|
109
|
-
void handleGatewayMessage(ws, data, { host, port, quiet, onRequest })
|
|
235
|
+
void handleGatewayMessage(ws, data, { host, port, quiet, onRequest, localSockets, streams, streamIdleTimeoutMs: options.streamIdleTimeoutMs })
|
|
110
236
|
})
|
|
111
237
|
|
|
112
|
-
|
|
113
|
-
|
|
238
|
+
let alive = true
|
|
239
|
+
ws.on('pong', () => { alive = true })
|
|
240
|
+
const heartbeat = setInterval(() => {
|
|
241
|
+
if (!alive) { ws.terminate(); return }
|
|
242
|
+
alive = false
|
|
243
|
+
if (ws.readyState === ws.OPEN) ws.ping()
|
|
244
|
+
}, options.heartbeatIntervalMs ?? 30_000)
|
|
245
|
+
heartbeat.unref()
|
|
246
|
+
|
|
247
|
+
ws.on('close', (code, reason) => {
|
|
248
|
+
clearInterval(heartbeat)
|
|
249
|
+
for (const state of streams.values()) state.channel.cancel(new Error('Gateway connection closed'), false)
|
|
250
|
+
streams.clear()
|
|
251
|
+
for (const connection of localSockets.values()) {
|
|
252
|
+
connection.socket.terminate()
|
|
253
|
+
}
|
|
254
|
+
localSockets.clear()
|
|
255
|
+
if (code === 4001) console.error('\nTunnel session limit reached. Run portpreview again to start a new session.')
|
|
256
|
+
else if (code === 4003) console.error('\nTunnel access revoked. Check your account before restarting.')
|
|
257
|
+
|
|
114
258
|
})
|
|
115
259
|
|
|
116
260
|
return {
|
|
261
|
+
closed,
|
|
117
262
|
url,
|
|
118
263
|
subdomain: assignedSubdomain,
|
|
264
|
+
expiresAt: registered.expiresAt ?? null,
|
|
265
|
+
protocolVersion: registered.version ?? LEGACY_PROTOCOL_VERSION,
|
|
266
|
+
streaming: Boolean(registered.streaming),
|
|
119
267
|
close: async () => {
|
|
120
268
|
await new Promise((resolve) => {
|
|
121
269
|
if (ws.readyState === ws.CLOSED) {
|
|
122
270
|
resolve(undefined)
|
|
123
271
|
return
|
|
124
272
|
}
|
|
125
|
-
ws.
|
|
126
|
-
|
|
273
|
+
const deadline = setTimeout(() => ws.terminate(), 1000)
|
|
274
|
+
deadline.unref()
|
|
275
|
+
ws.once('close', () => { clearTimeout(deadline); resolve() })
|
|
276
|
+
if (ws.readyState === ws.CONNECTING) ws.terminate()
|
|
277
|
+
else ws.close()
|
|
127
278
|
})
|
|
128
279
|
},
|
|
129
280
|
}
|
|
@@ -132,7 +283,13 @@ export async function openTunnel(options) {
|
|
|
132
283
|
/**
|
|
133
284
|
* @param {import('ws').WebSocket} ws
|
|
134
285
|
* @param {import('ws').RawData} data
|
|
135
|
-
* @param {{
|
|
286
|
+
* @param {{
|
|
287
|
+
* host: string,
|
|
288
|
+
* port: number,
|
|
289
|
+
* quiet: boolean,
|
|
290
|
+
* onRequest?: (info: { method: string, path: string }) => void,
|
|
291
|
+
* localSockets: Map<string, { socket: import('ws').WebSocket, queue: Array<{ data: Buffer, isBinary: boolean }> }>,
|
|
292
|
+
* }} ctx
|
|
136
293
|
*/
|
|
137
294
|
async function handleGatewayMessage(ws, data, ctx) {
|
|
138
295
|
let message
|
|
@@ -142,13 +299,66 @@ async function handleGatewayMessage(ws, data, ctx) {
|
|
|
142
299
|
return
|
|
143
300
|
}
|
|
144
301
|
|
|
302
|
+
const id = String(message.id ?? '')
|
|
303
|
+
|
|
304
|
+
if (message.type === 'http_request') {
|
|
305
|
+
try { openLocalHttpStream(ws, message, ctx) }
|
|
306
|
+
catch (error) { sendIfOpen(ws, { type: 'http_cancel', id, reason: error.message }) }
|
|
307
|
+
return
|
|
308
|
+
}
|
|
309
|
+
if (String(message.type).startsWith('http_')) {
|
|
310
|
+
ctx.streams.get(id)?.channel.handle(message)
|
|
311
|
+
return
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
if (message.type === 'ws_open') {
|
|
315
|
+
openLocalWebSocket(ws, message, ctx)
|
|
316
|
+
return
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
if (message.type === 'ws_data') {
|
|
320
|
+
const connection = ctx.localSockets.get(id)
|
|
321
|
+
if (!connection) return
|
|
322
|
+
const frame = {
|
|
323
|
+
data: attachedBody(message),
|
|
324
|
+
isBinary: Boolean(message.isBinary),
|
|
325
|
+
}
|
|
326
|
+
if (connection.socket.readyState === connection.socket.OPEN) {
|
|
327
|
+
connection.socket.send(frame.data, { binary: frame.isBinary })
|
|
328
|
+
} else if (connection.socket.readyState === connection.socket.CONNECTING) {
|
|
329
|
+
if (connection.queue.reduce((bytes, queued) => bytes + queued.data.length, frame.data.length) > MAX_BODY_BYTES) {
|
|
330
|
+
connection.socket.terminate()
|
|
331
|
+
ctx.localSockets.delete(id)
|
|
332
|
+
sendIfOpen(ws, { type: 'ws_error', id, reason: 'WebSocket buffer limit reached' })
|
|
333
|
+
return
|
|
334
|
+
}
|
|
335
|
+
connection.queue.push(frame)
|
|
336
|
+
}
|
|
337
|
+
return
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
if (message.type === 'ws_close') {
|
|
341
|
+
const connection = ctx.localSockets.get(id)
|
|
342
|
+
if (!connection) return
|
|
343
|
+
ctx.localSockets.delete(id)
|
|
344
|
+
const close = () => {
|
|
345
|
+
closeWebSocket(connection.socket, message.code, message.reason)
|
|
346
|
+
}
|
|
347
|
+
if (connection.socket.readyState === connection.socket.CONNECTING) {
|
|
348
|
+
connection.socket.once('open', close)
|
|
349
|
+
} else if (connection.socket.readyState === connection.socket.OPEN) {
|
|
350
|
+
close()
|
|
351
|
+
}
|
|
352
|
+
return
|
|
353
|
+
}
|
|
354
|
+
|
|
145
355
|
if (message.type !== 'request') return
|
|
146
356
|
|
|
147
|
-
const id = String(message.id ?? '')
|
|
148
357
|
const method = String(message.method ?? 'GET').toUpperCase()
|
|
149
358
|
const path = String(message.path ?? '/')
|
|
150
359
|
const headers = /** @type {Record<string, string>} */ (message.headers ?? {})
|
|
151
|
-
const body =
|
|
360
|
+
const body = attachedBody(message)
|
|
361
|
+
const requestBody = body.length ? body : undefined
|
|
152
362
|
|
|
153
363
|
ctx.onRequest?.({ method, path })
|
|
154
364
|
if (!ctx.quiet) {
|
|
@@ -156,23 +366,133 @@ async function handleGatewayMessage(ws, data, ctx) {
|
|
|
156
366
|
}
|
|
157
367
|
|
|
158
368
|
try {
|
|
159
|
-
const response = await forwardToLocal({
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
headers
|
|
165
|
-
body:
|
|
369
|
+
const response = await forwardToLocal({
|
|
370
|
+
host: ctx.host,
|
|
371
|
+
port: ctx.port,
|
|
372
|
+
method,
|
|
373
|
+
path,
|
|
374
|
+
headers,
|
|
375
|
+
body: requestBody,
|
|
166
376
|
})
|
|
377
|
+
if (!ctx.quiet && response.truncated) {
|
|
378
|
+
console.log(`${method} ${path} (truncated to 1MB)`)
|
|
379
|
+
}
|
|
380
|
+
send(
|
|
381
|
+
ws,
|
|
382
|
+
{
|
|
383
|
+
type: 'response',
|
|
384
|
+
id,
|
|
385
|
+
status: response.status,
|
|
386
|
+
headers: response.headers,
|
|
387
|
+
truncated: response.truncated || undefined,
|
|
388
|
+
},
|
|
389
|
+
response.body,
|
|
390
|
+
)
|
|
167
391
|
} catch (err) {
|
|
168
|
-
send(
|
|
169
|
-
|
|
392
|
+
send(
|
|
393
|
+
ws,
|
|
394
|
+
{
|
|
395
|
+
type: 'response',
|
|
396
|
+
id,
|
|
397
|
+
status: 502,
|
|
398
|
+
headers: { 'content-type': 'text/plain' },
|
|
399
|
+
},
|
|
400
|
+
Buffer.from(String(err instanceof Error ? err.message : err)),
|
|
401
|
+
)
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* @param {import('ws').WebSocket} gateway
|
|
407
|
+
* @param {Record<string, unknown>} message
|
|
408
|
+
* @param {{
|
|
409
|
+
* host: string,
|
|
410
|
+
* port: number,
|
|
411
|
+
* localSockets: Map<string, { socket: import('ws').WebSocket, queue: Array<{ data: Buffer, isBinary: boolean }> }>,
|
|
412
|
+
* }} ctx
|
|
413
|
+
*/
|
|
414
|
+
function openLocalHttpStream(ws, message, ctx) {
|
|
415
|
+
const id = String(message.id ?? '')
|
|
416
|
+
if (!id || ctx.streams.has(id)) return
|
|
417
|
+
const method = String(message.method ?? 'GET').toUpperCase()
|
|
418
|
+
const path = String(message.path ?? '/')
|
|
419
|
+
if (!path.startsWith('/') || path.startsWith('//') || /[\\\r\n\0]/.test(path)) {
|
|
420
|
+
sendIfOpen(ws, { type: 'http_cancel', id, reason: 'Invalid local HTTP path' }); return
|
|
421
|
+
}
|
|
422
|
+
ctx.onRequest?.({ method, path })
|
|
423
|
+
if (!ctx.quiet) console.log(`${method} ${path}`)
|
|
424
|
+
const upstream = http.request({ host: ctx.host, port: ctx.port, method, path, headers: stripHopByHop(message.headers ?? {}) })
|
|
425
|
+
let localSocket
|
|
426
|
+
upstream.once('socket', socket => { localSocket = socket })
|
|
427
|
+
const channel = createHttpStream({
|
|
428
|
+
ws, id, outgoing: 'response', idleTimeoutMs: ctx.streamIdleTimeoutMs ?? 120_000,
|
|
429
|
+
onError: () => { upstream.destroy(); ctx.streams.delete(id) },
|
|
430
|
+
onSentEnd: () => {
|
|
431
|
+
channel.stop(); ctx.streams.delete(id)
|
|
432
|
+
if (!upstream.writableFinished) { upstream.destroy(); localSocket?.destroy() }
|
|
433
|
+
},
|
|
434
|
+
})
|
|
435
|
+
ctx.streams.set(id, { channel, upstream })
|
|
436
|
+
upstream.once('response', (response) => {
|
|
437
|
+
try {
|
|
438
|
+
send(ws, { type: 'http_response', id, status: response.statusCode ?? 502, headers: stripHopByHop(response.headers) })
|
|
439
|
+
channel.setSource(response)
|
|
440
|
+
response.once('aborted', () => channel.cancel(new Error('Local response aborted')))
|
|
441
|
+
} catch (error) { channel.cancel(error) }
|
|
442
|
+
})
|
|
443
|
+
upstream.on('error', error => channel.cancel(error))
|
|
444
|
+
channel.setDestination(upstream)
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
function openLocalWebSocket(gateway, message, ctx) {
|
|
448
|
+
const id = String(message.id ?? '')
|
|
449
|
+
if (!id || ctx.localSockets.has(id)) return
|
|
450
|
+
|
|
451
|
+
const path = String(message.path ?? '/')
|
|
452
|
+
const headers = /** @type {Record<string, string>} */ (message.headers ?? {})
|
|
453
|
+
const protocol = String(headers['sec-websocket-protocol'] ?? '')
|
|
454
|
+
.split(',')
|
|
455
|
+
.map((protocol) => protocol.trim())
|
|
456
|
+
.find(Boolean)
|
|
457
|
+
const options = { headers: stripWebSocketHeaders(headers), handshakeTimeout: 10_000, maxPayload: MAX_BODY_BYTES }
|
|
458
|
+
if (!path.startsWith('/') || path.startsWith('//') || /[\\\r\n\0]/.test(path)) {
|
|
459
|
+
sendIfOpen(gateway, { type: 'ws_error', id, reason: 'Invalid local WebSocket path' })
|
|
460
|
+
return
|
|
461
|
+
}
|
|
462
|
+
const url = new URL(`ws://${net.isIPv6(ctx.host) ? `[${ctx.host}]` : ctx.host}:${ctx.port}${path}`)
|
|
463
|
+
const local = protocol ? new WebSocket(url, protocol, options) : new WebSocket(url, options)
|
|
464
|
+
const connection = { socket: local, queue: [] }
|
|
465
|
+
ctx.localSockets.set(id, connection)
|
|
466
|
+
|
|
467
|
+
local.on('open', () => {
|
|
468
|
+
for (const frame of connection.queue) {
|
|
469
|
+
local.send(frame.data, { binary: frame.isBinary })
|
|
470
|
+
}
|
|
471
|
+
connection.queue.length = 0
|
|
472
|
+
})
|
|
473
|
+
|
|
474
|
+
local.on('message', (data, isBinary) => {
|
|
475
|
+
sendIfOpen(gateway, { type: 'ws_data', id, isBinary }, Buffer.from(data))
|
|
476
|
+
})
|
|
477
|
+
|
|
478
|
+
local.on('close', (code, reason) => {
|
|
479
|
+
if (ctx.localSockets.get(id)?.socket !== local) return
|
|
480
|
+
ctx.localSockets.delete(id)
|
|
481
|
+
sendIfOpen(gateway, {
|
|
482
|
+
type: 'ws_close',
|
|
170
483
|
id,
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
body: Buffer.from(String(err instanceof Error ? err.message : err)).toString('base64'),
|
|
484
|
+
code,
|
|
485
|
+
reason: reason.toString(),
|
|
174
486
|
})
|
|
175
|
-
}
|
|
487
|
+
})
|
|
488
|
+
|
|
489
|
+
local.on('error', (err) => {
|
|
490
|
+
sendIfOpen(gateway, {
|
|
491
|
+
type: 'ws_error',
|
|
492
|
+
id,
|
|
493
|
+
reason: err instanceof Error ? err.message : 'Local WebSocket failed',
|
|
494
|
+
})
|
|
495
|
+
})
|
|
176
496
|
}
|
|
177
497
|
|
|
178
498
|
/**
|
|
@@ -190,21 +510,42 @@ function forwardToLocal(req) {
|
|
|
190
510
|
},
|
|
191
511
|
(res) => {
|
|
192
512
|
const chunks = []
|
|
193
|
-
|
|
194
|
-
|
|
513
|
+
let received = 0
|
|
514
|
+
let truncated = false
|
|
515
|
+
let settled = false
|
|
516
|
+
const finish = () => {
|
|
517
|
+
if (settled) return
|
|
518
|
+
settled = true
|
|
195
519
|
resolve({
|
|
196
520
|
status: res.statusCode ?? 502,
|
|
197
521
|
headers: Object.fromEntries(
|
|
198
522
|
Object.entries(res.headers).flatMap(([key, value]) =>
|
|
199
|
-
value === undefined ? [] : [[key,
|
|
523
|
+
value === undefined ? [] : [[key, value]],
|
|
200
524
|
),
|
|
201
525
|
),
|
|
202
526
|
body: Buffer.concat(chunks),
|
|
527
|
+
truncated,
|
|
203
528
|
})
|
|
529
|
+
}
|
|
530
|
+
res.on('data', (chunk) => {
|
|
531
|
+
if (settled) return
|
|
532
|
+
if (received + chunk.length > MAX_BODY_BYTES) {
|
|
533
|
+
chunks.push(chunk.subarray(0, MAX_BODY_BYTES - received))
|
|
534
|
+
received = MAX_BODY_BYTES
|
|
535
|
+
truncated = true
|
|
536
|
+
finish()
|
|
537
|
+
res.destroy()
|
|
538
|
+
return
|
|
539
|
+
}
|
|
540
|
+
chunks.push(chunk)
|
|
541
|
+
received += chunk.length
|
|
204
542
|
})
|
|
543
|
+
res.on('end', finish)
|
|
544
|
+
res.on('error', reject)
|
|
205
545
|
},
|
|
206
546
|
)
|
|
207
547
|
|
|
548
|
+
upstream.setTimeout(30_000, () => upstream.destroy(new Error('Local request timed out')))
|
|
208
549
|
upstream.on('error', reject)
|
|
209
550
|
if (req.body?.length) upstream.write(req.body)
|
|
210
551
|
upstream.end()
|
|
@@ -219,10 +560,40 @@ function stripHopByHop(headers) {
|
|
|
219
560
|
'proxy-authenticate',
|
|
220
561
|
'proxy-authorization',
|
|
221
562
|
'te',
|
|
563
|
+
'trailer',
|
|
222
564
|
'trailers',
|
|
223
565
|
'transfer-encoding',
|
|
224
566
|
'upgrade',
|
|
225
567
|
'host',
|
|
226
568
|
])
|
|
569
|
+
for (const name of String(headers.connection ?? '').split(',')) blocked.add(name.trim().toLowerCase())
|
|
227
570
|
return Object.fromEntries(Object.entries(headers).filter(([key]) => !blocked.has(key.toLowerCase())))
|
|
228
571
|
}
|
|
572
|
+
|
|
573
|
+
/**
|
|
574
|
+
* @param {import('ws').WebSocket} ws
|
|
575
|
+
* @param {Record<string, unknown>} message
|
|
576
|
+
* @param {unknown} [body]
|
|
577
|
+
*/
|
|
578
|
+
function sendIfOpen(ws, message, body) {
|
|
579
|
+
if (ws.readyState === ws.OPEN) send(ws, message, body)
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/** @param {Record<string, string>} headers */
|
|
583
|
+
function stripWebSocketHeaders(headers) {
|
|
584
|
+
return Object.fromEntries(
|
|
585
|
+
Object.entries(headers).filter(
|
|
586
|
+
([key]) =>
|
|
587
|
+
![
|
|
588
|
+
'connection',
|
|
589
|
+
'host',
|
|
590
|
+
'sec-websocket-accept',
|
|
591
|
+
'sec-websocket-extensions',
|
|
592
|
+
'sec-websocket-key',
|
|
593
|
+
'sec-websocket-protocol',
|
|
594
|
+
'sec-websocket-version',
|
|
595
|
+
'upgrade',
|
|
596
|
+
].includes(key.toLowerCase()),
|
|
597
|
+
),
|
|
598
|
+
)
|
|
599
|
+
}
|