portpreview 0.2.1 → 0.3.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 CHANGED
@@ -71,6 +71,8 @@ npx portpreview 3000 \
71
71
  | `--host` | Local address to forward to (default `127.0.0.1`) |
72
72
  | `--subdomain` | Use a name reserved in your dashboard |
73
73
  | `--token` | Authenticate with a dashboard CLI token |
74
+ | `--inspect` / `--no-inspect` | Turn the local request inspector on or off (default: on, off with `--quiet`) |
75
+ | `--inspect-port <n>` | Inspector port on `127.0.0.1` (default `4041`) |
74
76
  | `-q, --quiet` | Print only the public URL |
75
77
  | `-h, --help` | Show help |
76
78
  | `-v, --version` | Show version |
@@ -81,9 +83,103 @@ npx portpreview 3000 \
81
83
  |----------|-------------|
82
84
  | `PORTPREVIEW_TOKEN` | CLI token used for reserved subdomains |
83
85
  | `PORTPREVIEW_CONFIG` | Override local config file path |
86
+ | `PORTPREVIEW_INSPECT` | `1` or `0` to turn the request inspector on or off |
87
+ | `PORTPREVIEW_INSPECT_PORT` | Request inspector port (default `4041`) |
84
88
 
85
89
  See **Local development** below for `--gateway`, `--domain`, and related env vars.
86
90
 
91
+ ## TCP tunnels (paid plans)
92
+
93
+ ```bash
94
+ npx portpreview config set-token pp_live_...
95
+ npx portpreview tcp 5432
96
+ ```
97
+
98
+ ```
99
+ URL: tcp://tcp.portpreview.dev:20017
100
+ Target: 127.0.0.1:5432
101
+ ```
102
+
103
+ Raw TCP for databases, SSH and other non-HTTP services. Available on Pro, Ultra and Team; each
104
+ account has one stable port, so the address is the same on every run and one TCP tunnel can run at
105
+ a time. Up to 50 concurrent connections; a connection with no traffic for 30 minutes is closed.
106
+ Each closed connection is logged with its duration and byte counts.
107
+
108
+ PortPreview adds no TLS and no password on the public side of a TCP tunnel: anyone who knows the
109
+ address can connect, so expose only services that authenticate and encrypt connections themselves.
110
+ There is no UDP, and the request inspector does not apply to TCP tunnels.
111
+
112
+ Self-hosted gateways enable TCP tunnels with `PORTPREVIEW_TCP_PORTS=20000-20099` (the public port
113
+ range), optionally `PORTPREVIEW_TCP_HOST` and `PORTPREVIEW_TCP_PUBLIC_HOST`.
114
+
115
+ ## Local request inspector
116
+
117
+ While the tunnel runs, the CLI serves a local web UI that lists every request that
118
+ reached it, with headers and bodies, and can replay a request against your app:
119
+
120
+ ```text
121
+ Connected
122
+ URL: https://abc12.portpreview.dev
123
+ Inspect: http://127.0.0.1:4041
124
+ Target: http://127.0.0.1:3000
125
+ ```
126
+
127
+ - **What it shows:** method, path, status, duration and size; request and response
128
+ headers (response headers in the app's original casing); bodies as pretty JSON or
129
+ form fields, raw text, or hex (first 4 KiB), plus a raw download. Gzip, deflate and
130
+ Brotli bodies are decoded for display. WebSocket connections are listed with frame
131
+ and byte counts and the close code (frame contents are not recorded yet). Filters:
132
+ method, status class, path substring, hide static assets.
133
+ - **Replay** sends the captured request again, straight to the local app (not through
134
+ the gateway, so it also works while the tunnel reconnects). Method, path, headers
135
+ and body are exactly what the app received the first time, including
136
+ `X-Forwarded-*`; only `Host`, `Connection` and `Content-Length` are regenerated, and
137
+ no marker header is added. The replayed request appears as a new entry linked to the
138
+ original, and the terminal logs it with a `(replay)` suffix. Requests whose body was
139
+ only partly captured, that are still in flight, or WebSockets cannot be replayed.
140
+ Webhook signatures with a timestamp (Stripe, Slack, Svix/Clerk) are usually rejected
141
+ after about five minutes; GitHub and Shopify signatures have no timestamp.
142
+ - **Copy as cURL** builds a command for the local target or the public URL. It
143
+ contains the captured header values, so treat it as a secret.
144
+ - **Limits:** the newest 200 entries, 1 MiB per request body, 256 KiB per response
145
+ body and 32 MiB in total; larger bodies are marked truncated (the app and the
146
+ visitor still get every byte). Data lives only in the CLI's memory and is gone when
147
+ it exits. Only requests that reached this CLI appear; requests the gateway rejects
148
+ (body too large, preview password, IP allowlist, tunnel offline) do not.
149
+ - **Port:** `4041` by default. If it is busy the CLI tries 4042–4050 and then a random
150
+ free port, and prints the one it got. A port set with `--inspect-port` or
151
+ `PORTPREVIEW_INSPECT_PORT` is used as is: if it is busy the CLI prints a warning
152
+ and runs without the inspector. The inspector never stops or delays the tunnel.
153
+ - **On by default** for interactive runs. `--quiet` turns it off unless you also pass
154
+ `--inspect` (the `Inspect:` line then goes to stderr, so stdout stays just the URL).
155
+ Library callers of `openTunnel` get no inspector unless they pass one (see below).
156
+
157
+ **Security.** The inspector listens on `127.0.0.1` only and has no login, like ngrok's
158
+ local inspector: any program on this machine can read it. It rejects requests whose
159
+ `Host` is not `127.0.0.1:<port>`, `localhost:<port>` or `[::1]:<port>` (DNS
160
+ rebinding), never sends CORS headers, and accepts replay and clear only with an
161
+ `X-PortPreview-Inspector: 1` header, `Content-Type: application/json` and a matching
162
+ `Origin`, so other websites cannot trigger them. Pages use a nonce-based CSP and
163
+ render captured data as text only; raw bodies download as attachments. The values of
164
+ `Authorization`, `Proxy-Authorization`, `Cookie`, `Set-Cookie` and `X-API-Key` are
165
+ hidden on screen until clicked; they are stored unmodified because replay needs them.
166
+ On a shared machine where you do not trust other local users, run with `--no-inspect`.
167
+
168
+ Library use:
169
+
170
+ ```js
171
+ import { openTunnel, createInspectorStore, startInspectorServer } from 'portpreview'
172
+
173
+ const store = createInspectorStore()
174
+ const tunnel = await openTunnel({ port: 3000, host: '127.0.0.1', gatewayUrl, tunnelDomain, quiet: true, inspector: store })
175
+ const inspector = await startInspectorServer({ store, target: { host: '127.0.0.1', port: 3000 }, port: 4041 })
176
+ console.log(inspector.url)
177
+ await tunnel.closed
178
+ await inspector.close()
179
+ ```
180
+
181
+ The server does not keep the process alive on its own.
182
+
87
183
  ## Persistent token (recommended)
88
184
 
89
185
  ```bash
@@ -119,7 +215,7 @@ than 0.2.0 can retain their previous session limits until they are upgraded.
119
215
  The 0.2.0 client negotiates protocol v3 with a 0.2.0 gateway. HTTP
120
216
  request and response bodies stream without a total byte, traffic, or active
121
217
  transfer duration limit. Each direction uses 64 KiB chunks and a 256 KiB credit
122
- window; inspector captures only the first 64 KiB and marks incomplete previews.
218
+ window; the hosted dashboard captures only the first 64 KiB and marks incomplete previews.
123
219
  Range, If-Range, ETag, Content-Range and original Content-Length are preserved,
124
220
  including 206/416 and HEAD. Streams with no progress for 120 seconds are
125
221
  cancelled; active slow streams may continue indefinitely. Tunnel transport
package/lib/cli-main.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  import { parseArgs, printHelp } from './config.mjs'
2
2
  import { runConfigCommand } from './config-cli.mjs'
3
3
  import { openTunnel } from './tunnel-client.mjs'
4
+ import { startInspector } from './inspector-server.mjs'
4
5
 
5
6
  /** Shared entry point for the npm command and the standalone executable. */
6
7
  export async function runCli(argv, { version }) {
@@ -12,29 +13,35 @@ export async function runCli(argv, { version }) {
12
13
  if ('help' in parsed) { printHelp(); return }
13
14
  if ('version' in parsed) { console.log(version); return }
14
15
 
15
- const target = `http://${parsed.host}:${parsed.port}`
16
+ const target = `${parsed.kind === 'tcp' ? '' : 'http://'}${parsed.host}:${parsed.port}`
16
17
  if (!parsed.quiet) {
17
18
  console.log('Connecting to gateway…')
18
19
  console.log(`Forwarding ${target}`)
19
20
  }
20
21
  const controller = new AbortController()
21
22
  let tunnel
22
- const shutdown = () => { controller.abort(); void tunnel?.close() }
23
+ const inspector = parsed.inspect ? startInspector(parsed, { version, getTunnel: () => tunnel }) : null
24
+ const shutdown = () => { controller.abort(); void tunnel?.close(); void inspector?.close() }
23
25
  process.on('SIGINT', shutdown)
24
26
  process.on('SIGTERM', shutdown)
25
- try { tunnel = await openTunnel({ ...parsed, signal: controller.signal }) }
27
+ try { tunnel = await openTunnel({ ...parsed, inspector: inspector?.store, signal: controller.signal }) }
26
28
  catch (error) {
27
29
  process.off('SIGINT', shutdown); process.off('SIGTERM', shutdown)
30
+ void inspector?.close()
28
31
  if (controller.signal.aborted) return
29
32
  throw error
30
33
  }
31
34
  if (!parsed.quiet) {
32
35
  console.log('Connected')
33
36
  console.log(`URL: ${tunnel.url}`)
37
+ const inspectUrl = await inspector?.url
38
+ if (inspectUrl) console.log(`Inspect: ${inspectUrl}`)
34
39
  console.log(`Target: ${target}`)
35
40
  console.log('Press Ctrl+C to stop.')
36
41
  } else {
37
42
  console.log(tunnel.url)
43
+ const inspectUrl = await inspector?.url
44
+ if (inspectUrl) console.error(`Inspect: ${inspectUrl}`)
38
45
  }
39
- void tunnel.closed.then(() => { process.off('SIGINT', shutdown); process.off('SIGTERM', shutdown) })
46
+ void tunnel.closed.then(() => { process.off('SIGINT', shutdown); process.off('SIGTERM', shutdown); void inspector?.close() })
40
47
  }
package/lib/config.mjs CHANGED
@@ -1,16 +1,20 @@
1
- /** @typedef {{ port: number, host: string, subdomain?: string, apiToken?: string, gatewayUrl: string, tunnelDomain: string, quiet: boolean }} TunnelOptions */
1
+ /** @typedef {{ kind: 'http' | 'tcp', port: number, host: string, subdomain?: string, apiToken?: string, gatewayUrl: string, tunnelDomain: string, quiet: boolean }} TunnelOptions */
2
+ /** @typedef {{ inspect: boolean, inspectPort: number, inspectPortExplicit: boolean }} InspectOptions */
2
3
 
3
4
  import { readStoredToken } from './user-config.mjs'
5
+ import { DEFAULT_INSPECTOR_PORT as DEFAULT_INSPECT_PORT } from './inspector-store.mjs'
4
6
 
5
7
  export const DEFAULT_TUNNEL_DOMAIN = 'portpreview.dev'
6
8
  export const DEFAULT_GATEWAY_URL = 'wss://gateway.portpreview.dev/tunnel'
7
9
 
8
10
  /**
9
11
  * @param {string[]=} argv
10
- * @returns {TunnelOptions | { help: true } | { version: true }}
12
+ * @returns {(TunnelOptions & InspectOptions) | { help: true } | { version: true }}
11
13
  */
12
14
  export function parseArgs(argv = process.argv.slice(2)) {
13
15
  let port
16
+ /** @type {'http' | 'tcp'} */
17
+ let kind = 'http'
14
18
  let host = '127.0.0.1'
15
19
  /** @type {string | undefined} */
16
20
  let subdomain
@@ -18,6 +22,9 @@ export function parseArgs(argv = process.argv.slice(2)) {
18
22
  let gatewayUrl = process.env.PORTPREVIEW_GATEWAY_URL?.trim() || DEFAULT_GATEWAY_URL
19
23
  let tunnelDomain = process.env.PORTPREVIEW_TUNNEL_DOMAIN?.trim() || DEFAULT_TUNNEL_DOMAIN
20
24
  let quiet = false
25
+ /** @type {boolean | undefined} undefined = default (on unless --quiet) */
26
+ let inspect
27
+ let inspectPort
21
28
 
22
29
  for (let i = 0; i < argv.length; i++) {
23
30
  const arg = argv[i]
@@ -27,6 +34,14 @@ export function parseArgs(argv = process.argv.slice(2)) {
27
34
  quiet = true
28
35
  continue
29
36
  }
37
+ if (arg === '--inspect' || arg === '--no-inspect') {
38
+ inspect = arg === '--inspect'
39
+ continue
40
+ }
41
+ if (arg === '--inspect-port') {
42
+ inspectPort = parseInspectPort(argv[++i] ?? fail('--inspect-port requires a value'), '--inspect-port')
43
+ continue
44
+ }
30
45
  if (arg === '--host') {
31
46
  host = argv[++i] ?? fail('--host requires a value')
32
47
  continue
@@ -48,27 +63,59 @@ export function parseArgs(argv = process.argv.slice(2)) {
48
63
  continue
49
64
  }
50
65
  if (arg.startsWith('-')) fail(`Unknown option: ${arg}`)
66
+ if (arg === 'tcp' && kind === 'http' && port === undefined) {
67
+ kind = 'tcp'
68
+ continue
69
+ }
51
70
  if (port !== undefined) fail(`Unexpected argument: ${arg}`)
52
71
  port = Number(arg)
53
72
  }
54
73
 
55
- if (port === undefined) fail('Missing local port. Usage: portpreview <port>')
74
+ if (port === undefined) fail(kind === 'tcp' ? 'Missing local port. Usage: portpreview tcp <port>' : 'Missing local port. Usage: portpreview <port>')
56
75
  if (!Number.isInteger(port) || port < 1 || port > 65535) {
57
- fail(`Invalid port: ${argv.find((a) => !a.startsWith('-'))}`)
76
+ fail(`Invalid port: ${argv.find((a) => !a.startsWith('-') && a !== 'tcp')}`)
77
+ }
78
+
79
+ if (kind === 'tcp') {
80
+ if (subdomain) fail('TCP tunnels do not use --subdomain: your account has one stable TCP port')
81
+ if (!apiToken) fail('TCP tunnels require a paid plan and a CLI token. Run: portpreview config set-token <token>')
58
82
  }
59
83
 
60
84
  if (subdomain && !apiToken) {
61
85
  fail('Reserved subdomains require --token, PORTPREVIEW_TOKEN, or portpreview config set-token')
62
86
  }
63
87
 
64
- return { port, host, subdomain, apiToken, gatewayUrl, tunnelDomain, quiet }
88
+ const inspector = inspectOptions(inspect, inspectPort, quiet)
89
+ // The request inspector understands HTTP only.
90
+ return { kind, port, host, subdomain, apiToken, gatewayUrl, tunnelDomain, quiet, ...inspector, ...(kind === 'tcp' ? { inspect: false } : {}) }
91
+ }
92
+
93
+ /** Flags win over PORTPREVIEW_INSPECT / PORTPREVIEW_INSPECT_PORT; the default is on unless --quiet. */
94
+ function inspectOptions(flag, flagPort, quiet) {
95
+ const env = process.env.PORTPREVIEW_INSPECT?.trim().toLowerCase()
96
+ let inspect = flag
97
+ if (inspect === undefined && env) {
98
+ if (['1', 'true', 'yes', 'on'].includes(env)) inspect = true
99
+ else if (['0', 'false', 'no', 'off'].includes(env)) inspect = false
100
+ else fail(`Invalid PORTPREVIEW_INSPECT: ${env} (use 1 or 0)`)
101
+ }
102
+ const envPort = process.env.PORTPREVIEW_INSPECT_PORT?.trim()
103
+ const inspectPort = flagPort ?? (envPort ? parseInspectPort(envPort, 'PORTPREVIEW_INSPECT_PORT') : undefined)
104
+ return { inspect: inspect ?? !quiet, inspectPort: inspectPort ?? DEFAULT_INSPECT_PORT, inspectPortExplicit: inspectPort !== undefined }
105
+ }
106
+
107
+ function parseInspectPort(value, name) {
108
+ const port = Number(value)
109
+ if (!/^\d+$/.test(String(value)) || !Number.isInteger(port) || port > 65535) fail(`Invalid ${name}: ${value}`)
110
+ return port
65
111
  }
66
112
 
67
113
  export function printHelp() {
68
114
  console.log(`PortPreview — expose localhost through a public URL
69
115
 
70
116
  Usage:
71
- portpreview <port> [options]
117
+ portpreview <port> [options] HTTP tunnel with a public HTTPS URL
118
+ portpreview tcp <port> [options] Raw TCP tunnel (paid plans)
72
119
  portpreview config <command>
73
120
 
74
121
  Options:
@@ -77,6 +124,9 @@ Options:
77
124
  --token <token> Authenticate with a CLI token
78
125
  --gateway <url> WebSocket gateway URL (default: ${DEFAULT_GATEWAY_URL})
79
126
  --domain <domain> Public tunnel domain (default: ${DEFAULT_TUNNEL_DOMAIN})
127
+ --inspect Start the local request inspector (default: on, off with --quiet)
128
+ --no-inspect Do not start the request inspector
129
+ --inspect-port <n> Inspector port on 127.0.0.1 (default: ${DEFAULT_INSPECT_PORT}, next free port if busy)
80
130
  -q, --quiet Minimal output
81
131
  -h, --help Show this help
82
132
  -v, --version Show version
@@ -91,11 +141,14 @@ Environment:
91
141
  PORTPREVIEW_TUNNEL_DOMAIN Override public tunnel domain
92
142
  PORTPREVIEW_TOKEN Authenticate with a CLI token
93
143
  PORTPREVIEW_CONFIG Override config file path
144
+ PORTPREVIEW_INSPECT 1 or 0 to turn the request inspector on or off
145
+ PORTPREVIEW_INSPECT_PORT Request inspector port (default: ${DEFAULT_INSPECT_PORT})
94
146
 
95
147
  Examples:
96
148
  portpreview config set-token pp_live_...
97
149
  portpreview 3000
98
150
  portpreview 8080 --subdomain myapp
151
+ portpreview tcp 5432
99
152
  portpreview 3000 --gateway ws://127.0.0.1:4040/tunnel --domain localhost:4040
100
153
  `)
101
154
  }
package/lib/index.mjs CHANGED
@@ -9,4 +9,6 @@ export {
9
9
  saveToken,
10
10
  } from './user-config.mjs'
11
11
  export { openTunnel, waitForLocalPort } from './tunnel-client.mjs'
12
+ export { createInspectorStore, INSPECTOR_LIMITS } from './inspector-store.mjs'
13
+ export { startInspectorServer, DEFAULT_INSPECTOR_PORT } from './inspector-server.mjs'
12
14
  export { publicUrl, PROTOCOL_VERSION, MAX_BODY_BYTES } from './protocol.mjs'