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.
package/lib/geo.mjs ADDED
@@ -0,0 +1,84 @@
1
+ /** @type {Map<string, string | null>} */
2
+ const countryCache = new Map()
3
+
4
+ const regionNames = new Intl.DisplayNames(['en'], { type: 'region' })
5
+
6
+ /**
7
+ * @param {string} code
8
+ * @returns {string | null}
9
+ */
10
+ export function countryNameFromCode(code) {
11
+ if (!code) return null
12
+ const normalized = String(code).trim().toUpperCase()
13
+ if (normalized.length !== 2 || normalized === 'XX') return null
14
+ try {
15
+ return regionNames.of(normalized) ?? null
16
+ } catch {
17
+ return null
18
+ }
19
+ }
20
+
21
+ /**
22
+ * @param {string | null | undefined} value
23
+ * @returns {string | null}
24
+ */
25
+ export function normalizeCountryName(value) {
26
+ if (!value) return null
27
+ const trimmed = String(value).trim()
28
+ if (!trimmed) return null
29
+ if (trimmed.length === 2) return countryNameFromCode(trimmed)
30
+ return trimmed
31
+ }
32
+
33
+ /**
34
+ * @param {string} ip
35
+ */
36
+ export function isPublicIp(ip) {
37
+ if (!ip || ip === 'unknown') return false
38
+ if (ip.includes(':')) {
39
+ if (ip === '::1') return false
40
+ if (ip.startsWith('fe80:') || ip.startsWith('fc') || ip.startsWith('fd')) return false
41
+ return true
42
+ }
43
+
44
+ const parts = ip.split('.').map(Number)
45
+ if (parts.length !== 4 || parts.some((part) => Number.isNaN(part) || part < 0 || part > 255)) return false
46
+ const [a, b] = parts
47
+ if (a === 10) return false
48
+ if (a === 127) return false
49
+ if (a === 0) return false
50
+ if (a === 169 && b === 254) return false
51
+ if (a === 172 && b >= 16 && b <= 31) return false
52
+ if (a === 192 && b === 168) return false
53
+ return true
54
+ }
55
+
56
+ /**
57
+ * @param {string} ip
58
+ * @returns {Promise<string | null>}
59
+ */
60
+ export async function resolveCountryFromIp(ip) {
61
+ if (!isPublicIp(ip)) return null
62
+ if (countryCache.has(ip)) return countryCache.get(ip) ?? null
63
+
64
+ /** @type {string | null} */
65
+ let country = null
66
+
67
+ try {
68
+ const response = await fetch(
69
+ `http://ip-api.com/json/${encodeURIComponent(ip)}?fields=status,country,countryCode`,
70
+ { signal: AbortSignal.timeout(3000) },
71
+ )
72
+ if (response.ok) {
73
+ const data = await response.json()
74
+ if (data?.status === 'success') {
75
+ country = normalizeCountryName(data.country) ?? normalizeCountryName(data.countryCode)
76
+ }
77
+ }
78
+ } catch {
79
+ // Best-effort lookup — tunnel notifications still work without country.
80
+ }
81
+
82
+ countryCache.set(ip, country)
83
+ return country
84
+ }
@@ -0,0 +1,134 @@
1
+ import { attachedBody, encodeFrame, send, STREAM_CHUNK_BYTES, STREAM_WINDOW_BYTES } from './protocol.mjs'
2
+
3
+ /** Bounded HTTP pipe. Credits return only after the destination flushes its write.
4
+ * The readable is pulled in <=64KiB pieces; at most 256KiB is in flight per direction.
5
+ * Neither byte count nor elapsed transfer duration limits a stream.
6
+ */
7
+ export function createHttpStream({ ws, id, outgoing, onError, onEnd, onSentEnd, onSend, onReceive, idleTimeoutMs = 120_000, destroyOnError = true }) {
8
+ const incoming = outgoing === 'request' ? 'response' : 'request'
9
+ let source, destination, credit = 0, available = STREAM_WINDOW_BYTES
10
+ let pumping = false, sentEnd = false, receivedEnd = false, closed = false
11
+ let timer
12
+ const activity = () => {
13
+ clearTimeout(timer)
14
+ if (idleTimeoutMs > 0 && !closed) {
15
+ timer = setTimeout(() => fail(new Error('HTTP stream idle timeout')), idleTimeoutMs)
16
+ timer.unref()
17
+ }
18
+ }
19
+ const control = (message) => {
20
+ if (ws.readyState !== ws.OPEN) throw new Error('Tunnel offline')
21
+ send(ws, { ...message, id })
22
+ activity()
23
+ }
24
+ const fail = (error, notify = true) => {
25
+ if (closed) return
26
+ if (notify && ws.readyState === ws.OPEN) send(ws, { type: 'http_cancel', id, reason: error.message })
27
+ stop()
28
+ onError?.(error)
29
+ if (destroyOnError) { source?.destroy(); destination?.destroy() }
30
+ }
31
+ function stop() {
32
+ if (closed) return
33
+ closed = true
34
+ clearTimeout(timer)
35
+ source?.off('readable', pump)
36
+ source?.off('end', pump)
37
+ source?.off('error', fail)
38
+ // Aborted IncomingMessages can emit ECONNRESET after their aborted event.
39
+ source?.once('error', () => {})
40
+ destination?.off('error', fail)
41
+ }
42
+ async function pump() {
43
+ if (pumping || closed || sentEnd || !source) return
44
+ pumping = true
45
+ try {
46
+ source.read(0)
47
+ while (!closed && credit > 0) {
48
+ // IncomingMessage.read(n) may wait for n bytes. read() then split would
49
+ // retain an arbitrarily sized custom source chunk; cap the pull instead.
50
+ const size = Math.min(credit, STREAM_CHUNK_BYTES, source.readableLength)
51
+ if (!size) break
52
+ const chunk = source.read(size)
53
+ if (!chunk) break
54
+ credit -= chunk.length
55
+ onSend?.(chunk)
56
+ const frame = encodeFrame({ type: 'http_data', id, direction: outgoing }, chunk)
57
+ await new Promise((resolve, reject) => ws.send(frame, { binary: true }, (error) => error ? reject(error) : resolve()))
58
+ activity()
59
+ }
60
+ if (!closed && source.readableEnded && source.readableLength === 0) {
61
+ sentEnd = true
62
+ control({ type: 'http_end', direction: outgoing })
63
+ onSentEnd?.()
64
+ }
65
+ } catch (error) { fail(error) }
66
+ finally { pumping = false }
67
+ }
68
+ activity()
69
+ return {
70
+ setSource(readable) {
71
+ source = readable
72
+ readable.on('readable', pump)
73
+ readable.on('end', pump)
74
+ readable.on('error', fail)
75
+ void pump()
76
+ },
77
+ setDestination(writable) {
78
+ destination = writable
79
+ writable.on('error', fail)
80
+ control({ type: 'http_credit', direction: incoming, bytes: STREAM_WINDOW_BYTES })
81
+ },
82
+ handle(message) {
83
+ if (closed) return
84
+ activity()
85
+ if (message.type === 'http_cancel') { fail(new Error(String(message.reason ?? 'HTTP stream cancelled')), false); return }
86
+ if (message.type === 'http_credit') {
87
+ if (message.direction !== outgoing || !Number.isInteger(message.bytes) || message.bytes <= 0 || credit + message.bytes > STREAM_WINDOW_BYTES) {
88
+ fail(new Error('Invalid HTTP stream credit')); return
89
+ }
90
+ credit += message.bytes
91
+ void pump()
92
+ } else if (message.type === 'http_data') {
93
+ const chunk = attachedBody(message)
94
+ if (message.direction !== incoming || !destination || receivedEnd || !chunk.length || chunk.length > STREAM_CHUNK_BYTES || chunk.length > available) {
95
+ fail(new Error('Invalid HTTP stream data')); return
96
+ }
97
+ available -= chunk.length
98
+ onReceive?.(chunk)
99
+ destination.write(chunk, (error) => {
100
+ if (error) { fail(error); return }
101
+ if (closed || receivedEnd) return
102
+ available += chunk.length
103
+ try { control({ type: 'http_credit', direction: incoming, bytes: chunk.length }) } catch (error) { fail(error) }
104
+ })
105
+ } else if (message.type === 'http_end') {
106
+ if (message.direction !== incoming || !destination || receivedEnd) { fail(new Error('Invalid HTTP stream end')); return }
107
+ receivedEnd = true
108
+ destination.end(() => onEnd?.())
109
+ }
110
+ },
111
+ cancel: fail,
112
+ stop,
113
+ touch: activity,
114
+ }
115
+ }
116
+
117
+ /** Capture only a preview; never retain the full streaming body. */
118
+ export function createBodyPreview(limit = 64 * 1024) {
119
+ const chunks = []
120
+ let retained = 0, bytes = 0n
121
+ return {
122
+ add(chunk) {
123
+ bytes += BigInt(chunk.length)
124
+ if (retained < limit) {
125
+ const part = chunk.subarray(0, limit - retained)
126
+ chunks.push(Buffer.from(part))
127
+ retained += part.length
128
+ }
129
+ },
130
+ get bytes() { return bytes <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(bytes) : bytes.toString() },
131
+ get truncated() { return bytes > BigInt(retained) },
132
+ body() { return Buffer.concat(chunks, retained) },
133
+ }
134
+ }
package/lib/index.mjs CHANGED
@@ -1,10 +1,4 @@
1
- export {
2
- DEFAULT_GATEWAY_URL,
3
- DEFAULT_TUNNEL_DOMAIN,
4
- fail,
5
- parseArgs,
6
- printHelp,
7
- } from './config.mjs'
1
+ export { parseArgs, printHelp, DEFAULT_GATEWAY_URL, DEFAULT_TUNNEL_DOMAIN, fail } from './config.mjs'
8
2
  export { printConfigHelp, runConfigCommand } from './config-cli.mjs'
9
3
  export {
10
4
  assertValidToken,
@@ -15,4 +9,4 @@ export {
15
9
  saveToken,
16
10
  } from './user-config.mjs'
17
11
  export { openTunnel, waitForLocalPort } from './tunnel-client.mjs'
18
- export { PROTOCOL_VERSION, publicUrl, MAX_BODY_BYTES } from './protocol.mjs'
12
+ export { publicUrl, PROTOCOL_VERSION, MAX_BODY_BYTES } from './protocol.mjs'
package/lib/protocol.mjs CHANGED
@@ -1,8 +1,11 @@
1
1
  /** Wire format shared by CLI client and gateway. */
2
2
 
3
- export const PROTOCOL_VERSION = 2
3
+ export const PROTOCOL_VERSION = 3
4
+ export const LEGACY_PROTOCOL_VERSION = 2
5
+ export const STREAM_CHUNK_BYTES = 64 * 1024
6
+ export const STREAM_WINDOW_BYTES = 256 * 1024
4
7
 
5
- /** Hard cap for attached HTTP / WebSocket payloads. Oversized bodies are truncated. */
8
+ /** Legacy v2 attached-body cap; v3 HTTP uses bounded chunks with no total body cap. */
6
9
  export const MAX_BODY_BYTES = 1024 * 1024
7
10
  export const MAX_HEADER_BYTES = 256 * 1024
8
11
  export const MAX_FRAME_BYTES = 4 + MAX_HEADER_BYTES + MAX_BODY_BYTES
@@ -83,6 +86,8 @@ function withBodyHeaders(headers, length, truncated) {
83
86
  * @param {unknown} [body]
84
87
  */
85
88
  export function encodeFrame(header, body) {
89
+ if (header.type === 'http_data' && toBuffer(body).length > STREAM_CHUNK_BYTES) throw new Error('Streaming chunk too large')
90
+ if (header.type === 'ws_data' && toBuffer(body).length > MAX_BODY_BYTES) throw new Error('WebSocket message too large')
86
91
  const clipped = clipBody(body)
87
92
  const payload = stripAttachedFields(header)
88
93
  const truncated = Boolean(payload.truncated) || clipped.truncated
@@ -169,3 +174,11 @@ export function localGatewayHttpUrl(subdomain, tunnelDomain) {
169
174
  }
170
175
  return publicUrl(subdomain, tunnelDomain)
171
176
  }
177
+
178
+ /** Normalize received close details before passing them to ws. */
179
+ export function closeWebSocket(socket, code = 1000, reason = '') {
180
+ const valid = [1000, 1001, 1002, 1003, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014].includes(Number(code)) || (Number.isInteger(Number(code)) && Number(code) >= 3000 && Number(code) <= 4999)
181
+ let text = String(reason ?? '')
182
+ while (Buffer.byteLength(text) > 123) text = text.slice(0, -1)
183
+ socket.close(valid ? Number(code) : 1000, text)
184
+ }