portpreview 0.1.1 → 0.2.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.
@@ -3,42 +3,42 @@ import net from 'node:net'
3
3
  import { WebSocket } from 'ws'
4
4
  import {
5
5
  attachedBody,
6
+ closeWebSocket,
6
7
  localGatewayHttpUrl,
7
8
  MAX_BODY_BYTES,
9
+ MAX_FRAME_BYTES,
10
+ LEGACY_PROTOCOL_VERSION,
8
11
  parseMessage,
9
12
  publicUrl,
10
13
  PROTOCOL_VERSION,
11
14
  send,
12
15
  } from './protocol.mjs'
16
+ import { createHttpStream } from './http-stream.mjs'
13
17
 
14
- /**
15
- * @param {{ host: string, port: number }} options
16
- * @returns {Promise<void>}
17
- */
18
- 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 }) {
19
22
  return new Promise((resolve, reject) => {
23
+ if (signal?.aborted) { reject(abortError()); return }
20
24
  const socket = net.connect({ host, port })
21
- socket.once('connect', () => {
22
- socket.end()
23
- resolve()
24
- })
25
- socket.once('error', (err) => {
26
- reject(new Error(`Nothing is listening on http://${host}:${port} (${err.message})`))
27
- })
28
- socket.setTimeout(3000, () => {
29
- socket.destroy()
30
- reject(new Error(`Timed out waiting for http://${host}:${port}`))
31
- })
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}`)) })
32
31
  })
33
32
  }
34
33
 
35
34
  /**
36
35
  * @param {import('ws').WebSocket} ws
37
- * @param {string} type
36
+ * @param {Record<string, unknown>} message
38
37
  * @returns {Promise<Record<string, unknown>>}
39
38
  */
40
39
  function waitForMessage(ws, type) {
41
40
  return new Promise((resolve, reject) => {
41
+ const timer = setTimeout(() => { cleanup(); reject(new Error('Gateway registration timed out')) }, 10_000)
42
42
  /** @param {import('ws').RawData} data */
43
43
  const onMessage = (data) => {
44
44
  try {
@@ -50,7 +50,9 @@ function waitForMessage(ws, type) {
50
50
  }
51
51
  if (message.type === 'error') {
52
52
  cleanup()
53
- reject(new Error(String(message.message ?? 'Gateway error')))
53
+ const error = new Error(String(message.message ?? 'Gateway error'))
54
+ error.gatewayCode = message.code
55
+ reject(error)
54
56
  }
55
57
  } catch (err) {
56
58
  cleanup()
@@ -58,9 +60,11 @@ function waitForMessage(ws, type) {
58
60
  }
59
61
  }
60
62
 
61
- const onClose = () => {
63
+ const onClose = (code) => {
62
64
  cleanup()
63
- reject(new Error('Gateway connection closed before tunnel was ready'))
65
+ const error = new Error('Gateway connection closed before tunnel was ready')
66
+ error.closeCode = code
67
+ reject(error)
64
68
  }
65
69
 
66
70
  const onError = (err) => {
@@ -69,6 +73,7 @@ function waitForMessage(ws, type) {
69
73
  }
70
74
 
71
75
  const cleanup = () => {
76
+ clearTimeout(timer)
72
77
  ws.off('message', onMessage)
73
78
  ws.off('close', onClose)
74
79
  ws.off('error', onError)
@@ -81,33 +86,145 @@ function waitForMessage(ws, type) {
81
86
  }
82
87
 
83
88
  /**
84
- * @param {import('./config.mjs').TunnelOptions & { onRequest?: (info: { method: string, path: string }) => void }} options
85
- * @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.
86
94
  */
87
95
  export async function openTunnel(options) {
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
+ }
174
+
175
+ async function openTunnelConnection(options) {
88
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()
89
179
 
90
- await waitForLocalPort({ host, port })
180
+ const streams = new Map()
181
+ const protocolVersion = options.protocolVersion ?? PROTOCOL_VERSION
182
+ await waitForLocalPort({ host, port, signal: options.signal })
91
183
 
92
- const ws = new WebSocket(gatewayUrl)
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()
93
191
 
94
- await new Promise((resolve, reject) => {
95
- ws.once('open', resolve)
96
- ws.once('error', reject)
97
- })
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
+ }
98
203
 
99
204
  send(ws, {
100
205
  type: 'register',
101
- version: PROTOCOL_VERSION,
206
+ version: protocolVersion,
102
207
  port,
103
208
  host,
104
209
  subdomain,
105
210
  apiToken,
106
211
  })
107
212
 
108
- const registered = await waitForMessage(ws, 'registered')
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
+ }
109
224
  const assignedSubdomain = String(registered.subdomain ?? '')
110
- 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() }
111
228
 
112
229
  const url =
113
230
  tunnelDomain.includes(':') || tunnelDomain === 'localhost'
@@ -115,24 +232,49 @@ export async function openTunnel(options) {
115
232
  : publicUrl(assignedSubdomain, tunnelDomain)
116
233
 
117
234
  ws.on('message', (data) => {
118
- void handleGatewayMessage(ws, data, { host, port, quiet, onRequest })
235
+ void handleGatewayMessage(ws, data, { host, port, quiet, onRequest, localSockets, streams, streamIdleTimeoutMs: options.streamIdleTimeoutMs })
119
236
  })
120
237
 
121
- ws.on('close', () => {
122
- if (!quiet) console.log('\nTunnel closed.')
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
+
123
258
  })
124
259
 
125
260
  return {
261
+ closed,
126
262
  url,
127
263
  subdomain: assignedSubdomain,
264
+ expiresAt: registered.expiresAt ?? null,
265
+ protocolVersion: registered.version ?? LEGACY_PROTOCOL_VERSION,
266
+ streaming: Boolean(registered.streaming),
128
267
  close: async () => {
129
268
  await new Promise((resolve) => {
130
269
  if (ws.readyState === ws.CLOSED) {
131
270
  resolve(undefined)
132
271
  return
133
272
  }
134
- ws.once('close', resolve)
135
- ws.close()
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()
136
278
  })
137
279
  },
138
280
  }
@@ -141,7 +283,13 @@ export async function openTunnel(options) {
141
283
  /**
142
284
  * @param {import('ws').WebSocket} ws
143
285
  * @param {import('ws').RawData} data
144
- * @param {{ host: string, port: number, quiet: boolean, onRequest?: (info: { method: string, path: string }) => void }} ctx
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
145
293
  */
146
294
  async function handleGatewayMessage(ws, data, ctx) {
147
295
  let message
@@ -151,9 +299,61 @@ async function handleGatewayMessage(ws, data, ctx) {
151
299
  return
152
300
  }
153
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
+
154
355
  if (message.type !== 'request') return
155
356
 
156
- const id = String(message.id ?? '')
157
357
  const method = String(message.method ?? 'GET').toUpperCase()
158
358
  const path = String(message.path ?? '/')
159
359
  const headers = /** @type {Record<string, string>} */ (message.headers ?? {})
@@ -161,9 +361,7 @@ async function handleGatewayMessage(ws, data, ctx) {
161
361
  const requestBody = body.length ? body : undefined
162
362
 
163
363
  ctx.onRequest?.({ method, path })
164
- if (!ctx.quiet) {
165
- console.log(`${method} ${path}`)
166
- }
364
+ const startedAt = performance.now()
167
365
 
168
366
  try {
169
367
  const response = await forwardToLocal({
@@ -174,9 +372,7 @@ async function handleGatewayMessage(ws, data, ctx) {
174
372
  headers,
175
373
  body: requestBody,
176
374
  })
177
- if (!ctx.quiet && response.truncated) {
178
- console.log(`${method} ${path} (truncated to 1MB)`)
179
- }
375
+ if (!ctx.quiet) logRequest(method, path, response.status, startedAt, response.truncated ? 'truncated to 1MB' : '')
180
376
  send(
181
377
  ws,
182
378
  {
@@ -189,6 +385,7 @@ async function handleGatewayMessage(ws, data, ctx) {
189
385
  response.body,
190
386
  )
191
387
  } catch (err) {
388
+ if (!ctx.quiet) logRequest(method, path, 502, startedAt, localErrorReason(err))
192
389
  send(
193
390
  ws,
194
391
  {
@@ -202,6 +399,102 @@ async function handleGatewayMessage(ws, data, ctx) {
202
399
  }
203
400
  }
204
401
 
402
+ /**
403
+ * @param {import('ws').WebSocket} gateway
404
+ * @param {Record<string, unknown>} message
405
+ * @param {{
406
+ * host: string,
407
+ * port: number,
408
+ * localSockets: Map<string, { socket: import('ws').WebSocket, queue: Array<{ data: Buffer, isBinary: boolean }> }>,
409
+ * }} ctx
410
+ */
411
+ function openLocalHttpStream(ws, message, ctx) {
412
+ const id = String(message.id ?? '')
413
+ if (!id || ctx.streams.has(id)) return
414
+ const method = String(message.method ?? 'GET').toUpperCase()
415
+ const path = String(message.path ?? '/')
416
+ if (!path.startsWith('/') || path.startsWith('//') || /[\\\r\n\0]/.test(path)) {
417
+ sendIfOpen(ws, { type: 'http_cancel', id, reason: 'Invalid local HTTP path' }); return
418
+ }
419
+ ctx.onRequest?.({ method, path })
420
+ const startedAt = performance.now()
421
+ let logged = false
422
+ const log = (status, note = '') => { if (!ctx.quiet && !logged) { logged = true; logRequest(method, path, status, startedAt, note) } }
423
+ const upstream = http.request({ host: ctx.host, port: ctx.port, method, path, headers: stripHopByHop(message.headers ?? {}) })
424
+ let localSocket
425
+ upstream.once('socket', socket => { localSocket = socket })
426
+ const channel = createHttpStream({
427
+ ws, id, outgoing: 'response', idleTimeoutMs: ctx.streamIdleTimeoutMs ?? 120_000,
428
+ onError: () => { upstream.destroy(); ctx.streams.delete(id) },
429
+ onSentEnd: () => {
430
+ channel.stop(); ctx.streams.delete(id)
431
+ if (!upstream.writableFinished) { upstream.destroy(); localSocket?.destroy() }
432
+ },
433
+ })
434
+ ctx.streams.set(id, { channel, upstream })
435
+ upstream.once('response', (response) => {
436
+ try {
437
+ log(response.statusCode ?? 502)
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 => { log(502, localErrorReason(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',
483
+ id,
484
+ code,
485
+ reason: reason.toString(),
486
+ })
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
+ })
496
+ }
497
+
205
498
  /**
206
499
  * @param {{ host: string, port: number, method: string, path: string, headers: Record<string, string>, body?: Buffer }} req
207
500
  */
@@ -227,7 +520,7 @@ function forwardToLocal(req) {
227
520
  status: res.statusCode ?? 502,
228
521
  headers: Object.fromEntries(
229
522
  Object.entries(res.headers).flatMap(([key, value]) =>
230
- value === undefined ? [] : [[key, Array.isArray(value) ? value.join(', ') : value]],
523
+ value === undefined ? [] : [[key, value]],
231
524
  ),
232
525
  ),
233
526
  body: Buffer.concat(chunks),
@@ -248,9 +541,11 @@ function forwardToLocal(req) {
248
541
  received += chunk.length
249
542
  })
250
543
  res.on('end', finish)
544
+ res.on('error', reject)
251
545
  },
252
546
  )
253
547
 
548
+ upstream.setTimeout(30_000, () => upstream.destroy(new Error('Local request timed out')))
254
549
  upstream.on('error', reject)
255
550
  if (req.body?.length) upstream.write(req.body)
256
551
  upstream.end()
@@ -265,10 +560,52 @@ function stripHopByHop(headers) {
265
560
  'proxy-authenticate',
266
561
  'proxy-authorization',
267
562
  'te',
563
+ 'trailer',
268
564
  'trailers',
269
565
  'transfer-encoding',
270
566
  'upgrade',
271
567
  'host',
272
568
  ])
569
+ for (const name of String(headers.connection ?? '').split(',')) blocked.add(name.trim().toLowerCase())
273
570
  return Object.fromEntries(Object.entries(headers).filter(([key]) => !blocked.has(key.toLowerCase())))
274
571
  }
572
+
573
+ /**
574
+ * @param {import('ws').WebSocket} ws
575
+ * @param {Record<string, unknown>} message
576
+ * @param {unknown} [body]
577
+ */
578
+ /** One terminal line per request, printed once the local response status is known: `POST /hook 200 32ms`. */
579
+ function logRequest(method, path, status, startedAt, note) {
580
+ const ms = Math.max(0, Math.round(performance.now() - startedAt))
581
+ console.log(`${method} ${path} ${status} ${ms}ms${note ? ` (${note})` : ''}`)
582
+ }
583
+
584
+ function localErrorReason(error) {
585
+ const code = error && typeof error === 'object' && 'code' in error ? String(error.code) : ''
586
+ if (code === 'ECONNREFUSED') return 'nothing is listening on the local port'
587
+ return code || (error instanceof Error ? error.message : String(error))
588
+ }
589
+
590
+ function sendIfOpen(ws, message, body) {
591
+ if (ws.readyState === ws.OPEN) send(ws, message, body)
592
+ }
593
+
594
+ /** @param {Record<string, string>} headers */
595
+ function stripWebSocketHeaders(headers) {
596
+ return Object.fromEntries(
597
+ Object.entries(headers).filter(
598
+ ([key]) =>
599
+ ![
600
+ 'connection',
601
+ 'host',
602
+ 'sec-websocket-accept',
603
+ 'sec-websocket-extensions',
604
+ 'sec-websocket-key',
605
+ 'sec-websocket-protocol',
606
+ 'sec-websocket-version',
607
+ 'upgrade',
608
+ ].includes(key.toLowerCase()),
609
+ ),
610
+ )
611
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "portpreview",
3
- "version": "0.1.1",
4
- "description": "Expose a local port through a public HTTPS URL — webhook debugging, OAuth callbacks, and dev previews.",
3
+ "version": "0.2.1",
4
+ "description": "Instant secure previews for localhost apps — expose a local port through a public HTTPS URL.",
5
5
  "type": "module",
6
6
  "main": "./lib/index.mjs",
7
7
  "exports": {
@@ -10,20 +10,29 @@
10
10
  "./package.json": "./package.json"
11
11
  },
12
12
  "bin": {
13
- "portpreview": "bin/portpreview.mjs"
13
+ "portpreview": "./bin/portpreview.mjs"
14
14
  },
15
15
  "files": [
16
16
  "bin/portpreview.mjs",
17
- "lib",
18
- "README.md",
19
- "LICENSE"
17
+ "lib/cli-main.mjs",
18
+ "lib/client-info.mjs",
19
+ "lib/config-cli.mjs",
20
+ "lib/config.mjs",
21
+ "lib/geo.mjs",
22
+ "lib/http-stream.mjs",
23
+ "lib/index.mjs",
24
+ "lib/protocol.mjs",
25
+ "lib/tunnel-client.mjs",
26
+ "lib/user-config.mjs",
27
+ "LICENSE",
28
+ "NOTICE",
29
+ "README.md"
20
30
  ],
21
- "publishConfig": {
22
- "access": "public",
23
- "registry": "https://registry.npmjs.org/"
24
- },
25
31
  "scripts": {
26
32
  "prepublishOnly": "npm test",
33
+ "start": "node bin/portpreview.mjs",
34
+ "gateway": "node bin/gateway.mjs",
35
+ "telegram-daemon": "node bin/telegram-daemon.mjs",
27
36
  "test": "node --test test/*.test.mjs"
28
37
  },
29
38
  "keywords": [
@@ -32,9 +41,7 @@
32
41
  "preview",
33
42
  "webhook",
34
43
  "devtools",
35
- "cli",
36
- "ngrok",
37
- "localtunnel"
44
+ "cli"
38
45
  ],
39
46
  "engines": {
40
47
  "node": ">=18"
@@ -49,6 +56,7 @@
49
56
  "url": "https://github.com/elemops/portpreview/issues"
50
57
  },
51
58
  "dependencies": {
59
+ "node-telegram-bot-api": "^1.2.0",
52
60
  "ws": "^8.19.0"
53
61
  }
54
62
  }