portpreview 0.2.1 → 0.3.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/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,134 @@ 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, at most 10 from one source address; a connection with no
106
+ traffic for 30 minutes is closed.
107
+ Each closed connection is logged with its duration and byte counts.
108
+
109
+ PortPreview adds no TLS and no password on the public side of a TCP tunnel: anyone who knows the
110
+ address can connect, so expose only services that authenticate and encrypt connections themselves.
111
+ There is no UDP, and the request inspector does not apply to TCP tunnels.
112
+
113
+ Self-hosted gateways enable TCP tunnels with `PORTPREVIEW_TCP_PORTS=20000-20099` (the public port
114
+ range), optionally `PORTPREVIEW_TCP_HOST` and `PORTPREVIEW_TCP_PUBLIC_HOST`.
115
+
116
+ ## Local request inspector
117
+
118
+ While the tunnel runs, the CLI serves a local web UI that lists every request that
119
+ reached it, with headers and bodies, and can replay a request against your app:
120
+
121
+ ```text
122
+ Connected
123
+ URL: https://abc12.portpreview.dev
124
+ Inspect: http://127.0.0.1:4041
125
+ Target: http://127.0.0.1:3000
126
+ ```
127
+
128
+ - **What it shows:** method, path, status, duration and size; request and response
129
+ headers (response headers in the app's original casing); bodies as pretty JSON or
130
+ form fields, raw text, or hex (first 4 KiB), plus a raw download. Gzip, deflate and
131
+ Brotli bodies are decoded for display. WebSocket connections are listed with frame
132
+ and byte counts and the close code (frame contents are not recorded yet). Filters:
133
+ method, status class, path substring, hide static assets.
134
+ - **Replay** sends the captured request again, straight to the local app (not through
135
+ the gateway, so it also works while the tunnel reconnects). Method, path, headers
136
+ and body are exactly what the app received the first time, including
137
+ `X-Forwarded-*`; only `Host`, `Connection` and `Content-Length` are regenerated, and
138
+ no marker header is added. The replayed request appears as a new entry linked to the
139
+ original, and the terminal logs it with a `(replay)` suffix. Requests whose body was
140
+ only partly captured, that are still in flight, or WebSockets cannot be replayed.
141
+ Webhook signatures with a timestamp (Stripe, Slack, Svix/Clerk) are usually rejected
142
+ after about five minutes; GitHub and Shopify signatures have no timestamp.
143
+ - **Edit & replay** opens the captured request in an editor: method (GET, HEAD, POST,
144
+ PUT, PATCH, DELETE, OPTIONS), path and query, headers as `name: value` lines (secret
145
+ headers are shown in full here, since you are editing them), and the body as text.
146
+ A body that is not UTF-8 text (images, protobuf, gzip) is kept byte for byte unless
147
+ you choose to edit it as text, and an untouched text body is also sent as the
148
+ captured bytes, so CRLF line endings survive. Requests whose body was only partly
149
+ captured can be edited too; the editor says the body is partial and asks you to
150
+ confirm it or replace it. The edited request goes straight to the local app, appears
151
+ as a new entry marked `edited` and linked to the original, and the terminal logs it
152
+ with a `(replay, edited)` suffix. `Host`, `Connection`, `Content-Length` and
153
+ `Transfer-Encoding` are always regenerated, whatever the editor contains. Limits:
154
+ 1 MiB body, 200 headers and 64 KiB of headers in total, 8 KiB path.
155
+ - **Copy as cURL** builds a command for the local target or the public URL. It
156
+ contains the captured header values, so treat it as a secret.
157
+ - **Limits:** the newest 200 entries, 1 MiB per request body, 256 KiB per response
158
+ body and 32 MiB in total; larger bodies are marked truncated (the app and the
159
+ visitor still get every byte). Data lives only in the CLI's memory and is gone when
160
+ it exits. Only requests that reached this CLI appear; requests the gateway rejects
161
+ (body too large, preview password, IP allowlist, tunnel offline) do not.
162
+ - **Port:** `4041` by default. If it is busy the CLI tries 4042–4050 and then a random
163
+ free port, and prints the one it got. A port set with `--inspect-port` or
164
+ `PORTPREVIEW_INSPECT_PORT` is used as is: if it is busy the CLI prints a warning
165
+ and runs without the inspector. The inspector never stops or delays the tunnel.
166
+ - **On by default** for interactive runs. `--quiet` turns it off unless you also pass
167
+ `--inspect` (the `Inspect:` line then goes to stderr, so stdout stays just the URL).
168
+ Library callers of `openTunnel` get no inspector unless they pass one (see below).
169
+
170
+ **Security.** The inspector listens on `127.0.0.1` only and has no login, like ngrok's
171
+ local inspector: any program on this machine can read it. It rejects requests whose
172
+ `Host` is not `127.0.0.1:<port>`, `localhost:<port>` or `[::1]:<port>` (DNS
173
+ rebinding), never sends CORS headers, and accepts replay, edited replay and clear only
174
+ with an `X-PortPreview-Inspector: 1` header, `Content-Type: application/json` and a
175
+ matching `Origin`, so other websites cannot trigger them. Pages use a nonce-based CSP and
176
+ render captured data as text only; raw bodies download as attachments. The values of
177
+ `Authorization`, `Proxy-Authorization`, `Cookie`, `Set-Cookie` and `X-API-Key` are
178
+ hidden on screen until clicked; they are stored unmodified because replay needs them.
179
+ On a shared machine where you do not trust other local users, run with `--no-inspect`.
180
+
181
+ **Edited replay from a script.** The editor uses `POST /api/replay`, which answers
182
+ `{ "id": <new entry id> }`:
183
+
184
+ ```bash
185
+ curl http://127.0.0.1:4041/api/replay \
186
+ -H 'X-PortPreview-Inspector: 1' -H 'Content-Type: application/json' \
187
+ -d '{"replayOf":12,"method":"POST","path":"/webhooks/stripe",
188
+ "headers":[["Content-Type","application/json"],["X-Dup","a"],["X-Dup","b"]],
189
+ "body":"{\"type\":\"invoice.paid\"}"}'
190
+ ```
191
+
192
+ `headers` is a list of `[name, value]` pairs (repeated names are sent as separate
193
+ lines) or an object; `body` is UTF-8 text, or base64 with `"bodyEncoding": "base64"`;
194
+ `replayOf` is optional. Invalid input gets `400` with a message (method outside the
195
+ list, a path that does not start with a single `/` or contains a backslash, spaces or
196
+ control characters, a header name that is not an HTTP token, CR/LF/NUL in a value,
197
+ unknown fields); a body over 1 MiB, or a request over 3 MiB, gets `413`.
198
+
199
+ Library use:
200
+
201
+ ```js
202
+ import { openTunnel, createInspectorStore, startInspectorServer } from 'portpreview'
203
+
204
+ const store = createInspectorStore()
205
+ const tunnel = await openTunnel({ port: 3000, host: '127.0.0.1', gatewayUrl, tunnelDomain, quiet: true, inspector: store })
206
+ const inspector = await startInspectorServer({ store, target: { host: '127.0.0.1', port: 3000 }, port: 4041 })
207
+ console.log(inspector.url)
208
+ await tunnel.closed
209
+ await inspector.close()
210
+ ```
211
+
212
+ The server does not keep the process alive on its own.
213
+
87
214
  ## Persistent token (recommended)
88
215
 
89
216
  ```bash
@@ -119,7 +246,7 @@ than 0.2.0 can retain their previous session limits until they are upgraded.
119
246
  The 0.2.0 client negotiates protocol v3 with a 0.2.0 gateway. HTTP
120
247
  request and response bodies stream without a total byte, traffic, or active
121
248
  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.
249
+ window; the hosted dashboard captures only the first 64 KiB and marks incomplete previews.
123
250
  Range, If-Range, ETag, Content-Range and original Content-Length are preserved,
124
251
  including 206/416 and HEAD. Streams with no progress for 120 seconds are
125
252
  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'