portpreview 0.3.0 → 0.3.2

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
@@ -1,247 +1,101 @@
1
1
  # PortPreview CLI
2
2
 
3
- Open-source client for [PortPreview](https://portpreview.com) — expose a local port through a public URL for webhook debugging, OAuth callbacks, and dev previews.
3
+ [![npm](https://img.shields.io/npm/v/portpreview)](https://www.npmjs.com/package/portpreview)
4
+ [![License](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE)
4
5
 
5
- ## Usage
6
-
7
- ```bash
8
- npx portpreview 3000
9
- ```
10
-
11
- That connects to the PortPreview gateway and forwards public traffic to `http://127.0.0.1:3000`.
12
-
13
- ## Install in this repo
14
-
15
- From the project root:
6
+ Open-source localhost tunnel client for [PortPreview](https://portpreview.com).
7
+ One command gives a local HTTP server a public HTTPS URL on `*.portpreview.dev`
8
+ for webhook debugging, OAuth callbacks, and client or mobile previews — without
9
+ deploying to staging.
16
10
 
17
11
  ```bash
18
- npm install
19
12
  npx portpreview 3000
20
13
  ```
21
14
 
22
- `npx` picks up the local CLI from `node_modules/.bin` before hitting the npm registry.
23
-
24
- ## Publish to npm
25
-
26
- ```bash
27
- cd cli
28
- npm login
29
- npm publish
30
15
  ```
31
-
32
- After the current package version is published to npm, `npx portpreview 3000` works from any directory without cloning this repo.
33
-
34
- ## Standalone Windows x64
35
-
36
- The standalone executable includes Node.js and the same CLI used by npm. On a
37
- verified release, download the versioned `.exe` and its `.sha256` file, check the
38
- hash with `Get-FileHash`, then run in PowerShell:
39
-
40
- ```powershell
41
- .\portpreview-0.2.0-windows-x64.exe --help
42
- .\portpreview-0.2.0-windows-x64.exe 3000
43
- .\portpreview-0.2.0-windows-x64.exe config set-token pp_live_...
16
+ URL: https://jjm5s.portpreview.dev
17
+ Target: http://127.0.0.1:3000
44
18
  ```
45
19
 
46
- No Node.js or npm installation is needed to run the executable. Windows tokens
47
- are stored in `%LOCALAPPDATA%\portpreview\config.json` by default. Current builds
48
- are unsigned. Download availability depends on successful Windows verification;
49
- a cross-built artifact alone is not a verified release. See
50
- [Windows packaging and release checks](packaging/README.md).
20
+ No signup and no config file. Requires Node.js 18 or newer.
21
+
22
+ ## What you get
23
+
24
+ - **Public HTTPS URL** that forwards to `http://127.0.0.1:<port>`; visitors see
25
+ your app directly, with no warning or interstitial page.
26
+ - **Live request log** in the terminal: method, path, status, and response time
27
+ of every request, e.g. `POST /webhooks/stripe 200 19ms`.
28
+ - **Local request inspector** at `http://127.0.0.1:4041` while the CLI runs: headers,
29
+ bodies, copy as cURL, replay, and edit-and-replay against your app. No account;
30
+ nothing leaves your machine.
31
+ - **Webhook-safe forwarding**: raw bodies and headers reach your app unchanged,
32
+ so Stripe and GitHub signature checks pass. `Host` is rewritten to
33
+ `127.0.0.1:<port>`, so Vite and similar dev servers need no `allowedHosts` change.
34
+ - **WebSocket, Server-Sent Events, and HMR** through the tunnel.
35
+ - **Streaming bodies** with no total size limit, and automatic reconnect with
36
+ backoff after network loss.
37
+ - **No session time limit** on any plan.
38
+
39
+ With a free account you also get a reserved subdomain, request history in the web
40
+ dashboard, and password or IP allowlist protection for previews. Paid plans add raw
41
+ TCP tunnels: `npx portpreview tcp 5432` gives `tcp.portpreview.dev:<port>`. See
42
+ [pricing](https://portpreview.com/pricing).
51
43
 
52
- ## Local development (no production gateway)
44
+ ## Usage
53
45
 
54
46
  ```bash
55
- # Terminal 1 — dev gateway
56
- npm run gateway --prefix cli
57
-
58
- # Terminal 2 — your app
59
- python3 -m http.server 3000
60
-
61
- # Terminal 3 — tunnel
62
- npx portpreview 3000 \
63
- --gateway ws://127.0.0.1:4040/tunnel \
64
- --domain localhost:4040
47
+ npx portpreview 3000 # random subdomain
48
+ npx portpreview config set-token pp_live_... # save a CLI token from the dashboard
49
+ npx portpreview 3000 --subdomain my-app # reserved subdomain
50
+ npx portpreview tcp 5432 # raw TCP tunnel (paid plans)
65
51
  ```
66
52
 
67
- ## Options
68
-
69
- | Flag | Description |
70
- |------|-------------|
71
- | `--host` | Local address to forward to (default `127.0.0.1`) |
72
- | `--subdomain` | Use a name reserved in your dashboard |
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`) |
53
+ | Option | Description |
54
+ |---|---|
55
+ | `--host <addr>` | Local address to forward to (default `127.0.0.1`) |
56
+ | `--subdomain <name>` | Use a subdomain reserved by your account |
57
+ | `--token <token>` | Authenticate with a CLI token |
58
+ | `--gateway <url>` | Gateway WebSocket URL (default `wss://gateway.portpreview.dev/tunnel`) |
59
+ | `--domain <domain>` | Public tunnel domain (default `portpreview.dev`) |
60
+ | `--no-inspect` / `--inspect-port <n>` | Turn the local inspector off, or choose its port (default `4041`) |
76
61
  | `-q, --quiet` | Print only the public URL |
77
- | `-h, --help` | Show help |
78
- | `-v, --version` | Show version |
62
+ | `-h, --help` / `-v, --version` | Help and version |
79
63
 
80
- ## Environment
64
+ | Environment variable | Description |
65
+ |---|---|
66
+ | `PORTPREVIEW_TOKEN` | CLI token |
67
+ | `PORTPREVIEW_CONFIG` | Config file path (default `~/.config/portpreview/config.json` on Linux) |
68
+ | `PORTPREVIEW_GATEWAY_URL` | Gateway WebSocket URL |
69
+ | `PORTPREVIEW_TUNNEL_DOMAIN` | Public tunnel domain |
81
70
 
82
- | Variable | Description |
83
- |----------|-------------|
84
- | `PORTPREVIEW_TOKEN` | CLI token used for reserved subdomains |
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`) |
71
+ If your server listens only on IPv6 `::1` (default Vite), start it with
72
+ `--host 127.0.0.1` or pass `--host ::1` to the CLI.
88
73
 
89
- See **Local development** below for `--gateway`, `--domain`, and related env vars.
74
+ ## Limits
90
75
 
91
- ## TCP tunnels (paid plans)
76
+ - HTTP and WebSocket on every plan; raw TCP on paid plans; no UDP.
77
+ - WebSocket messages up to 1 MiB each.
78
+ - Streams with no progress for 120 seconds are closed.
79
+ - One gateway region (Tokyo, Japan).
80
+ - The local inspector keeps the last 200 requests in memory; the dashboard stores
81
+ the first 64 KiB of each body.
82
+ - A tunnel URL is not a secret: its TLS certificate is listed in public Certificate
83
+ Transparency logs, so scanners usually find a new URL within minutes. Do not expose
84
+ debug endpoints; protect reserved previews with a password or an IP allowlist.
92
85
 
93
- ```bash
94
- npx portpreview config set-token pp_live_...
95
- npx portpreview tcp 5432
96
- ```
86
+ Full reference: [portpreview.com/docs](https://portpreview.com/docs).
97
87
 
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
- ```
88
+ ## What is open source
180
89
 
181
- The server does not keep the process alive on its own.
90
+ This repository contains the CLI client published to npm as
91
+ [`portpreview`](https://www.npmjs.com/package/portpreview). The hosted gateway,
92
+ dashboard, request history, and billing are not open source.
182
93
 
183
- ## Persistent token (recommended)
94
+ `npm test` here covers argument parsing, the wire protocol, the token store and a
95
+ tunnel against a small fixture gateway. The streaming, reconnect, inspector and TCP
96
+ suites need the hosted gateway code and run in the private repository before each
97
+ release.
184
98
 
185
- ```bash
186
- npx portpreview config set-token pp_live_...
187
- npx portpreview 3000
188
- npx portpreview config check
189
- ```
190
-
191
- Default config file: `~/.config/portpreview/config.json` on Linux.
192
-
193
- Gateway deployments also require `GATEWAY_API_SECRET` (shared with the website) and may set
194
- `PORTPREVIEW_ACCOUNT_API_URL`, `PORTPREVIEW_MAX_TUNNELS`, and
195
- `PORTPREVIEW_MAX_REQUEST_BODY_BYTES`.
196
-
197
- ## Tests
198
-
199
- ```bash
200
- npm test --prefix cli
201
-
202
- # Opt-in: generated >5 GiB upload and download, checksums, bounded memory; no disk body
203
- RUN_LARGE_STREAM_TEST=1 node --test --test-concurrency=1 cli/test/streaming.test.mjs
204
-
205
- # Opt-in: real wall-clock session for 2 hours + 90 seconds
206
- node cli/test/tunnel-soak.mjs
207
- ```
99
+ ## License
208
100
 
209
- ## Tunnel sessions and request history
210
-
211
- Free accounts and anonymous visitors can run one active tunnel at a time.
212
- Tunnel sessions have no duration limit on any plan. Self-hosted gateways older
213
- than 0.2.0 can retain their previous session limits until they are upgraded.
214
-
215
- The 0.2.0 client negotiates protocol v3 with a 0.2.0 gateway. HTTP
216
- request and response bodies stream without a total byte, traffic, or active
217
- transfer duration limit. Each direction uses 64 KiB chunks and a 256 KiB credit
218
- window; the hosted dashboard captures only the first 64 KiB and marks incomplete previews.
219
- Range, If-Range, ETag, Content-Range and original Content-Length are preserved,
220
- including 206/416 and HEAD. Streams with no progress for 120 seconds are
221
- cancelled; active slow streams may continue indefinitely. Tunnel transport
222
- heartbeats detect dead connections. After transient network loss, the CLI
223
- reconnects automatically with exponential backoff and jitter, from 500 ms up to
224
- 30 seconds. Anonymous tunnels may receive a new URL, which the command announces;
225
- reserved tunnels retry with the same subdomain and token. Access revocation and
226
- permanent registration or authentication errors stop retries. Ctrl+C cancels
227
- pending connection attempts and retry timers.
228
-
229
- Interrupted HTTP transfers are cancelled and must be retried by the application;
230
- reconnecting does not replay requests or resume their bytes. Applications can
231
- resume downloads with Range and If-Range when the upstream supports them. Library
232
- callers can observe the current URL through the returned `url` getter or an
233
- `onReconnect` callback.
234
-
235
- Clients older than 0.2.0 and fallback to older v2 gateways retain the legacy
236
- 1 MiB HTTP body cap; both ends need upgrading for streaming. WebSocket messages
237
- retain an explicit 1 MiB per-message limit; oversized messages close rather than
238
- silently truncate. Requests made by automated agents and webhooks are included
239
- in request history.
240
-
241
- Protect reserved preview domains with a password or IP/CIDR allowlist in the
242
- dashboard (all plans). A password uses HTTP Basic authentication; enter any
243
- username and your preview password. This credential is consumed by the gateway
244
- and is not forwarded to localhost. Application HTTP Basic authentication cannot
245
- share the same Authorization header, so use an application session cookie or a
246
- bearer token route without preview password protection. Policy changes and token
247
- revocations take effect within 30 seconds on connected gateways.
101
+ [Apache-2.0](LICENSE) © 2026 ElemOps
@@ -2,7 +2,7 @@ import crypto from 'node:crypto'
2
2
  import http from 'node:http'
3
3
  import net from 'node:net'
4
4
  import zlib from 'node:zlib'
5
- import { beginExchange, createInspectorStore, DEFAULT_INSPECTOR_PORT, summary } from './inspector-store.mjs'
5
+ import { beginExchange, createInspectorStore, DEFAULT_INSPECTOR_PORT, INSPECTOR_LIMITS, summary } from './inspector-store.mjs'
6
6
  import { renderInspectorPage } from './inspector-ui.mjs'
7
7
 
8
8
  export { DEFAULT_INSPECTOR_PORT }
@@ -10,11 +10,30 @@ export { DEFAULT_INSPECTOR_PORT }
10
10
  const FALLBACK_PORTS = 9
11
11
  const DECODE_LIMIT = 4 * 1024 * 1024
12
12
  const MUTATION_BODY_LIMIT = 16 * 1024
13
+ /** Bytes of an oversized mutation body read and discarded after the 413, so the client sees the answer. */
14
+ const MUTATION_DRAIN_LIMIT = 8 * 1024 * 1024
13
15
  const SSE_BUFFER_LIMIT = 4 * 1024 * 1024
14
16
  const UPDATE_COALESCE_MS = 100
15
17
  const HEARTBEAT_MS = 15_000
16
18
  const REPLAY_TIMEOUT_MS = 30_000
17
19
 
20
+ /** Edited replay (`POST /api/replay`) limits. The body limit is the per-request capture limit. */
21
+ export const EDIT_LIMITS = Object.freeze({
22
+ methods: Object.freeze(['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']),
23
+ bodyBytes: INSPECTOR_LIMITS.requestBodyLimit,
24
+ // Room for the body as base64 (4/3) or JSON-escaped text (up to 2x for quotes, backslashes and newlines), plus headers.
25
+ requestBytes: 3 * 1024 * 1024,
26
+ pathLength: 8 * 1024,
27
+ headerCount: 200,
28
+ headerBytes: 64 * 1024,
29
+ })
30
+ const EDIT_FIELDS = new Set(['replayOf', 'method', 'path', 'headers', 'body', 'bodyEncoding'])
31
+ /** Always set by the inspector (or Node) for a replay, whatever the captured or edited headers say. */
32
+ const REGENERATED_HEADERS = new Set(['host', 'connection', 'content-length', 'transfer-encoding'])
33
+ /** Methods for which Node sends `Content-Length: 0` on an empty body; recorded so the entry shows it. */
34
+ const BODY_METHODS = new Set(['POST', 'PUT', 'PATCH'])
35
+ const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/
36
+
18
37
  /**
19
38
  * Local-only inspector UI and API. Binds 127.0.0.1 only, enforces a loopback Host allowlist
20
39
  * (DNS rebinding), never sends CORS headers, and requires a custom header, a JSON content type
@@ -115,6 +134,7 @@ export async function startInspectorServer({ store, target, port = DEFAULT_INSPE
115
134
  const route = parts.slice(1)
116
135
  if (route.length === 1 && route[0] === 'status' && req.method === 'GET') { status(res); return }
117
136
  if (route.length === 1 && route[0] === 'events' && req.method === 'GET') { events(req, res, query); return }
137
+ if (route.length === 1 && route[0] === 'replay' && req.method === 'POST') { mutate(req, res, body => editedReplay(res, body), EDIT_LIMITS.requestBytes); return }
118
138
  if (route[0] === 'requests') {
119
139
  if (route.length === 1 && req.method === 'GET') { list(res, query); return }
120
140
  if (route.length === 1 && req.method === 'DELETE') { mutate(req, res, () => { store.clear(); json(res, 200, { ok: true }) }); return }
@@ -127,16 +147,23 @@ export async function startInspectorServer({ store, target, port = DEFAULT_INSPE
127
147
  fail(res, req.method === 'GET' ? 404 : 405, req.method === 'GET' ? 'Not found' : 'Method not allowed')
128
148
  }
129
149
 
130
- function mutate(req, res, action) {
150
+ /** Guards, then reads the JSON body (at most `limit` bytes) and calls `action(bodyBuffer)`. */
151
+ function mutate(req, res, action, limit = MUTATION_BODY_LIMIT) {
131
152
  const reason = mutationRejection(req)
132
153
  if (reason) { req.resume(); fail(res, 403, reason); return }
154
+ const chunks = []
133
155
  let size = 0
134
156
  let aborted = false
157
+ const tooLarge = () => { aborted = true; chunks.length = 0; fail(res, 413, `Request body too large (limit ${formatBytes(limit)})`) }
158
+ if (Number(req.headers['content-length']) > limit) tooLarge()
135
159
  req.on('data', chunk => {
136
160
  size += chunk.length
137
- if (size > MUTATION_BODY_LIMIT && !aborted) { aborted = true; fail(res, 413, 'Request body too large'); req.destroy() }
161
+ // Keep reading a little after the 413 so the client gets the answer instead of a reset.
162
+ if (aborted) { if (size > limit + MUTATION_DRAIN_LIMIT) req.destroy(); return }
163
+ if (size > limit) { tooLarge(); return }
164
+ chunks.push(chunk)
138
165
  })
139
- req.once('end', () => { if (!aborted) { try { action() } catch { fail(res, 500, 'Internal inspector error') } } })
166
+ req.once('end', () => { if (!aborted) { try { action(Buffer.concat(chunks, size)) } catch { fail(res, 500, 'Internal inspector error') } } })
140
167
  req.once('error', () => {})
141
168
  }
142
169
 
@@ -181,24 +208,43 @@ export async function startInspectorServer({ store, target, port = DEFAULT_INSPE
181
208
  const blocked = replayBlockedReason(entry)
182
209
  if (blocked) { json(res, 409, { error: blocked }); return }
183
210
  const body = store.body(entry, 'request')
184
- const headers = replayHeaders(entry.headers, body.length)
185
- const exchange = beginExchange(store, {
186
- kind: 'http', source: 'replay', replayOf: entry.id, method: entry.method, path: entry.path, headers,
187
- publicUrl: entry.publicUrl, protocolVersion: entry.protocolVersion,
211
+ forward(res, {
212
+ method: entry.method, path: entry.path, headers: replayHeaders(entry.headers, body.length), body,
213
+ replayOf: entry.id, edited: false, publicUrl: entry.publicUrl, protocolVersion: entry.protocolVersion,
214
+ })
215
+ }
216
+
217
+ function editedReplay(res, raw) {
218
+ let input
219
+ try { input = JSON.parse(raw.toString('utf8')) } catch { fail(res, 400, 'The request body must be JSON'); return }
220
+ const parsed = parseEditedRequest(input)
221
+ if (parsed.error) { fail(res, parsed.status, parsed.error); return }
222
+ // An evicted original is fine: the edited request does not depend on it, and the link shows "(evicted)".
223
+ const original = parsed.replayOf === null ? null : store.get(parsed.replayOf)
224
+ if (original?.kind === 'websocket') { fail(res, 400, 'WebSocket connections cannot be replayed'); return }
225
+ forward(res, {
226
+ method: parsed.method, path: parsed.path, headers: editedHeaders(parsed.headers, parsed.method, parsed.body.length), body: parsed.body,
227
+ replayOf: parsed.replayOf, edited: true, publicUrl: original?.publicUrl ?? null, protocolVersion: original?.protocolVersion ?? null,
188
228
  })
229
+ }
230
+
231
+ /** Send a request straight to the local target, capture it as a replay entry and answer `{ id }`. */
232
+ function forward(res, { method, path, headers, body, replayOf, edited, publicUrl, protocolVersion }) {
233
+ const exchange = beginExchange(store, { kind: 'http', source: 'replay', replayOf, edited, method, path, headers, publicUrl, protocolVersion })
189
234
  exchange.requestChunk(body)
190
235
  exchange.requestEnd()
191
236
  const startedAt = performance.now()
237
+ const label = edited ? 'replay, edited' : 'replay'
192
238
  let logged = false
193
239
  const logLine = (code, note = '') => {
194
240
  if (logged || !log) return
195
241
  logged = true
196
242
  const ms = Math.max(0, Math.round(performance.now() - startedAt))
197
- try { log(`${entry.method} ${entry.path} ${code} ${ms}ms (replay${note ? `, ${note}` : ''})`) } catch {}
243
+ try { log(`${method} ${path} ${code} ${ms}ms (${label}${note ? `, ${note}` : ''})`) } catch {}
198
244
  }
199
245
  let request
200
246
  try {
201
- request = http.request({ host: targetHost, port: target.port, method: entry.method, path: entry.path, headers })
247
+ request = http.request({ host: targetHost, port: target.port, method, path, headers })
202
248
  } catch (error) {
203
249
  exchange.finish({ error })
204
250
  logLine(502, localErrorReason(error))
@@ -339,6 +385,92 @@ function replayHeaders(captured, length) {
339
385
  return headers
340
386
  }
341
387
 
388
+ /**
389
+ * Validate a `POST /api/replay` body. Returns `{ error, status }` or
390
+ * `{ replayOf, method, path, headers: [name, value][], body: Buffer }`.
391
+ */
392
+ export function parseEditedRequest(input) {
393
+ const invalid = (error, status = 400) => ({ error, status })
394
+ if (!input || typeof input !== 'object' || Array.isArray(input)) return invalid('The request body must be a JSON object')
395
+ for (const key of Object.keys(input)) {
396
+ if (!EDIT_FIELDS.has(key)) return invalid(`Unknown field ${quote(key)}; expected ${[...EDIT_FIELDS].join(', ')}`)
397
+ }
398
+ const { replayOf = null, method, path, headers = [], body = '', bodyEncoding = 'text' } = input
399
+
400
+ if (replayOf !== null && !(Number.isSafeInteger(replayOf) && replayOf > 0)) return invalid('replayOf must be the numeric id of a captured request, or null')
401
+ if (typeof method !== 'string' || !EDIT_LIMITS.methods.includes(method)) return invalid(`method must be one of ${EDIT_LIMITS.methods.join(', ')}`)
402
+
403
+ if (typeof path !== 'string' || !path.startsWith('/')) return invalid('path must start with "/"')
404
+ if (path.startsWith('//')) return invalid('path must start with a single "/", not "//"')
405
+ if (path.length > EDIT_LIMITS.pathLength) return invalid(`path is longer than ${EDIT_LIMITS.pathLength} characters`)
406
+ if (/[\r\n\0]/.test(path)) return invalid('path must not contain CR, LF or NUL')
407
+ if (path.includes('\\')) return invalid('path must not contain a backslash')
408
+ if (/[^\x21-\x7e\x80-\xff]/.test(path)) return invalid('path must not contain spaces, control characters or characters outside Latin-1; percent-encode them')
409
+
410
+ let pairs
411
+ if (Array.isArray(headers)) pairs = headers
412
+ else if (headers && typeof headers === 'object') pairs = Object.entries(headers).flatMap(([name, value]) => (Array.isArray(value) ? value : [value]).map(item => [name, item]))
413
+ else return invalid('headers must be a list of [name, value] pairs or an object')
414
+ if (pairs.length > EDIT_LIMITS.headerCount) return invalid(`Too many headers (${pairs.length}; the limit is ${EDIT_LIMITS.headerCount})`)
415
+ let headerBytes = 0
416
+ for (const pair of pairs) {
417
+ if (!Array.isArray(pair) || pair.length !== 2 || typeof pair[0] !== 'string' || typeof pair[1] !== 'string') {
418
+ return invalid('Each header must be a [name, value] pair of strings')
419
+ }
420
+ const [name, value] = pair
421
+ if (!TOKEN.test(name)) return invalid(`Invalid header name ${quote(name)}: use only letters, digits and !#$%&'*+-.^_\`|~`)
422
+ if (/[\r\n\0]/.test(value)) return invalid(`Header ${quote(name)}: the value must not contain CR, LF or NUL`)
423
+ if (/[^\t\x20-\x7e\x80-\xff]/.test(value)) return invalid(`Header ${quote(name)}: the value must not contain control characters or characters outside Latin-1`)
424
+ headerBytes += name.length + value.length + 4
425
+ }
426
+ if (headerBytes > EDIT_LIMITS.headerBytes) return invalid(`Headers are larger than ${formatBytes(EDIT_LIMITS.headerBytes)} in total`)
427
+
428
+ if (bodyEncoding !== 'text' && bodyEncoding !== 'base64') return invalid('bodyEncoding must be "text" or "base64"')
429
+ let bytes
430
+ if (body === null) bytes = Buffer.alloc(0)
431
+ else if (typeof body !== 'string') return invalid('body must be a string (text, or base64 with bodyEncoding "base64")')
432
+ else if (bodyEncoding === 'text') {
433
+ if (Buffer.byteLength(body, 'utf8') > EDIT_LIMITS.bodyBytes) return invalid(`The body is larger than ${formatBytes(EDIT_LIMITS.bodyBytes)}`, 413)
434
+ bytes = Buffer.from(body, 'utf8')
435
+ } else {
436
+ if (body.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(body)) return invalid('body is not valid base64')
437
+ if ((body.length / 4) * 3 - (body.match(/=*$/)[0].length) > EDIT_LIMITS.bodyBytes) return invalid(`The body is larger than ${formatBytes(EDIT_LIMITS.bodyBytes)}`, 413)
438
+ bytes = Buffer.from(body, 'base64')
439
+ }
440
+
441
+ return { replayOf, method, path, headers: pairs, body: bytes }
442
+ }
443
+
444
+ /**
445
+ * Outgoing headers for an edited replay: names keep the client's casing and order, repeated names
446
+ * become one array (sent as separate lines), and the regenerated headers are dropped. Content-Length
447
+ * is the body length, kept where the client listed it.
448
+ */
449
+ function editedHeaders(pairs, method, length) {
450
+ const headers = {}
451
+ const keys = new Map()
452
+ for (const [name, value] of pairs) {
453
+ const lower = name.toLowerCase()
454
+ if (lower === 'content-length') { if (!keys.has(lower)) { keys.set(lower, name); headers[name] = '' } continue }
455
+ if (REGENERATED_HEADERS.has(lower)) continue
456
+ const key = keys.get(lower)
457
+ if (key === undefined) { keys.set(lower, name); headers[name] = value }
458
+ else headers[key] = [].concat(headers[key], value)
459
+ }
460
+ if (keys.has('content-length')) headers[keys.get('content-length')] = String(length)
461
+ else if (length > 0 || BODY_METHODS.has(method)) headers['content-length'] = String(length)
462
+ return headers
463
+ }
464
+
465
+ function quote(value) {
466
+ const text = JSON.stringify(String(value))
467
+ return text.length > 66 ? `${text.slice(0, 64)}…"` : text
468
+ }
469
+
470
+ function formatBytes(bytes) {
471
+ return bytes % (1024 * 1024) === 0 ? `${bytes / (1024 * 1024)} MiB` : bytes % 1024 === 0 ? `${bytes / 1024} KiB` : `${bytes} bytes`
472
+ }
473
+
342
474
  function mutationRejection(req) {
343
475
  if (req.headers['x-portpreview-inspector'] !== '1') return 'Missing X-PortPreview-Inspector header'
344
476
  const type = String(req.headers['content-type'] ?? '').split(';')[0].trim().toLowerCase()
@@ -164,6 +164,8 @@ export function createInspectorStore(options = {}) {
164
164
  kind,
165
165
  source: info.source === 'replay' ? 'replay' : 'tunnel',
166
166
  replayOf: Number.isSafeInteger(info.replayOf) ? info.replayOf : null,
167
+ /** A replay sent from the editor with a changed method, path, headers or body. */
168
+ edited: info.source === 'replay' && Boolean(info.edited),
167
169
  replays: [],
168
170
  method: String(info.method ?? 'GET').toUpperCase(),
169
171
  path: String(info.path ?? '/'),
@@ -236,6 +238,7 @@ export function summary(entry) {
236
238
  kind: entry.kind,
237
239
  source: entry.source,
238
240
  replayOf: entry.replayOf,
241
+ edited: entry.edited,
239
242
  replays: [...entry.replays],
240
243
  method: entry.method,
241
244
  path: entry.path,
@@ -21,12 +21,12 @@ export function renderInspectorPage({ nonce }) {
21
21
  * { box-sizing: border-box; }
22
22
  html, body { height: 100%; }
23
23
  body { margin: 0; font: 13px/1.45 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; color: var(--text); background: var(--bg); display: flex; flex-direction: column; }
24
- button, select, input { font: inherit; color: inherit; }
24
+ button, select, input, textarea { font: inherit; color: inherit; }
25
25
  button { background: var(--panel); border: 1px solid var(--line); border-radius: 6px; padding: 4px 10px; cursor: pointer; }
26
26
  button:hover:not(:disabled) { border-color: var(--accent); }
27
27
  button:disabled { opacity: .45; cursor: not-allowed; }
28
28
  button.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
29
- select, input[type=search] { background: var(--panel); border: 1px solid var(--line); border-radius: 6px; padding: 4px 8px; }
29
+ select, input[type=search], input[type=text] { background: var(--panel); border: 1px solid var(--line); border-radius: 6px; padding: 4px 8px; }
30
30
  header.top { display: flex; align-items: center; gap: 14px; padding: 10px 16px; background: var(--panel); border-bottom: 1px solid var(--line); flex-wrap: wrap; }
31
31
  .brand { font-weight: 650; font-size: 14px; }
32
32
  .brand span { color: var(--muted); font-weight: 500; }
@@ -52,6 +52,7 @@ tr.row.selected td { background: var(--sel); }
52
52
  .badge { display: inline-block; font-family: system-ui, sans-serif; font-size: 10px; padding: 0 5px; border-radius: 4px; background: var(--chip); color: var(--muted); margin-left: 5px; vertical-align: 1px; }
53
53
  .badge.replay { color: var(--accent); }
54
54
  .badge.trunc { color: var(--warn); }
55
+ .badge.edited { color: var(--accent); }
55
56
  .empty, .placeholder { color: var(--muted); padding: 24px 16px; margin: 0; }
56
57
  .detail { flex: 1; overflow: auto; padding: 14px 18px 40px; min-width: 0; }
57
58
  .d-head { display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; }
@@ -82,6 +83,26 @@ footer .stats { margin-left: auto; }
82
83
  .copybox { margin-top: 10px; }
83
84
  .copybox textarea { width: 100%; min-height: 120px; font: 12px var(--mono); background: var(--panel); color: var(--text); border: 1px solid var(--line); border-radius: 6px; padding: 8px; }
84
85
  [hidden] { display: none !important; }
86
+ :focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
87
+ dialog.editor { width: min(940px, 94vw); max-height: 92vh; padding: 0; border: 1px solid var(--line); border-radius: 10px; background: var(--panel); color: var(--text); box-shadow: 0 14px 44px rgba(0,0,0,.3); }
88
+ dialog.editor::backdrop { background: rgba(12,12,16,.45); }
89
+ .ed { display: flex; flex-direction: column; gap: 6px; padding: 16px 18px 14px; }
90
+ .ed h2 { font-size: 15px; margin: 0; font-weight: 650; }
91
+ .ed-sub { color: var(--muted); margin: 0 0 6px; }
92
+ .ed-line { display: flex; gap: 8px; }
93
+ .ed-line input { flex: 1; min-width: 0; font-family: var(--mono); font-size: 12px; }
94
+ .ed-label { display: block; font-size: 11px; text-transform: uppercase; letter-spacing: .03em; color: var(--muted); font-weight: 600; margin: 10px 0 0; }
95
+ .ed-label span { text-transform: none; letter-spacing: 0; font-weight: 400; }
96
+ .ed textarea { width: 100%; font: 12px/1.5 var(--mono); background: var(--bg); color: var(--text); border: 1px solid var(--line); border-radius: 6px; padding: 8px; resize: vertical; }
97
+ .ed-hint { color: var(--muted); font-size: 12px; }
98
+ .ed-bodybar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-top: 10px; }
99
+ .ed-bodybar .ed-label { margin: 0; }
100
+ .ed-bodybar .bodyinfo { margin-right: auto; }
101
+ .ed .note { margin: 2px 0; }
102
+ .ed-confirm { display: flex; align-items: center; gap: 6px; color: var(--warn); }
103
+ .ed-actions { display: flex; justify-content: flex-end; align-items: center; gap: 8px; margin-top: 8px; }
104
+ .ed-actions .ed-hint { margin-right: auto; }
105
+ .sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
85
106
  @media (max-width: 860px) { main { flex-direction: column; } .list { width: auto; min-width: 0; max-height: 45vh; border-right: 0; border-bottom: 1px solid var(--line); } }
86
107
  </style>
87
108
  </head>
@@ -116,6 +137,39 @@ footer .stats { margin-left: auto; }
116
137
  <span class="stats" id="stats"></span>
117
138
  </footer>
118
139
  <div class="toast" id="toast" hidden></div>
140
+ <dialog class="editor" id="editor" aria-labelledby="ed-title">
141
+ <div class="ed">
142
+ <h2 id="ed-title">Edit &amp; replay</h2>
143
+ <p class="ed-sub" id="ed-sub"></p>
144
+ <div class="ed-line">
145
+ <label class="sr" for="ed-method">Method</label>
146
+ <select id="ed-method"><option>GET</option><option>POST</option><option>PUT</option><option>PATCH</option><option>DELETE</option><option>HEAD</option><option>OPTIONS</option></select>
147
+ <label class="sr" for="ed-path">Path and query</label>
148
+ <input id="ed-path" type="text" spellcheck="false" autocomplete="off">
149
+ </div>
150
+ <div id="ed-method-note"></div>
151
+ <label class="ed-label" for="ed-headers">Headers <span>(one "name: value" per line)</span></label>
152
+ <textarea id="ed-headers" rows="9" spellcheck="false" wrap="off"></textarea>
153
+ <div class="ed-hint">Host, Connection, Content-Length and Transfer-Encoding are always set by the inspector; lines for them are ignored.</div>
154
+ <div class="ed-bodybar">
155
+ <label class="ed-label" for="ed-body">Body</label>
156
+ <span class="bodyinfo" id="ed-bodyinfo"></span>
157
+ <select id="ed-eol" aria-label="Line endings" hidden><option value="crlf">CRLF line endings</option><option value="lf">LF line endings</option></select>
158
+ <button type="button" id="ed-astext" hidden>Edit as text</button>
159
+ <button type="button" id="ed-restore" hidden>Restore captured body</button>
160
+ <button type="button" id="ed-empty">Empty body</button>
161
+ </div>
162
+ <div id="ed-notes"></div>
163
+ <textarea id="ed-body" rows="12" spellcheck="false"></textarea>
164
+ <label class="ed-confirm" id="ed-confirm-row" hidden><input type="checkbox" id="ed-confirm"> Send this partial body as shown</label>
165
+ <div class="note bad" id="ed-error" role="alert" hidden></div>
166
+ <div class="ed-actions">
167
+ <span class="ed-hint">Ctrl+Enter sends · Esc cancels</span>
168
+ <button type="button" id="ed-cancel">Cancel</button>
169
+ <button type="button" class="primary" id="ed-send">Send</button>
170
+ </div>
171
+ </div>
172
+ </dialog>
119
173
  <script nonce="${n}">
120
174
  (function () {
121
175
  'use strict';
@@ -125,6 +179,8 @@ footer .stats { margin-left: auto; }
125
179
  var STATIC_EXT = /\.(?:m?js|css|map|png|jpe?g|gif|svg|ico|webp|avif|bmp|woff2?|ttf|otf|eot|mp4|webm|mp3|wav|wasm)$/i;
126
180
  var STATIC_PREFIX = /^\/(?:_next\/static\/|_next\/image|@vite\/|@fs\/|@id\/|@react-refresh|node_modules\/|__vite_ping|assets\/|static\/|favicon)/i;
127
181
  var HEX_LIMIT = 4096;
182
+ var EDIT_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'];
183
+ var REGENERATED = { 'host': 1, 'connection': 1, 'content-length': 1, 'transfer-encoding': 1 };
128
184
 
129
185
  var entries = new Map();
130
186
  var selected = null;
@@ -234,6 +290,7 @@ footer .stats { margin-left: auto; }
234
290
  var path = el('td', 'path', entry.path);
235
291
  path.title = entry.path;
236
292
  if (entry.source === 'replay') path.appendChild(el('span', 'badge replay', 'replay'));
293
+ if (entry.edited) path.appendChild(el('span', 'badge edited', 'edited'));
237
294
  if (entry.request.truncated || entry.response.truncated) path.appendChild(el('span', 'badge trunc', 'truncated'));
238
295
  tr.appendChild(path);
239
296
  tr.appendChild(el('td', statusClass(entry), statusText(entry)));
@@ -305,6 +362,12 @@ footer .stats { margin-left: auto; }
305
362
  replay.title = d.replayable ? 'Send this exact request to the local app again' : d.replayBlockedReason;
306
363
  replay.addEventListener('click', function () { doReplay(d.id, replay); });
307
364
  actions.appendChild(replay);
365
+ var edit = el('button', '', 'Edit & replay');
366
+ edit.type = 'button';
367
+ edit.id = 'd-edit';
368
+ edit.title = 'Change the method, path, headers or body, then send it to the local app';
369
+ edit.addEventListener('click', function () { openEditor(d, edit); });
370
+ actions.appendChild(edit);
308
371
  var curlLocal = el('button', '', 'Copy cURL (local)');
309
372
  var curlPublic = el('button', '', 'Copy cURL (public URL)');
310
373
  var curlBlocked = d.request.truncated || !d.request.complete;
@@ -325,7 +388,7 @@ footer .stats { margin-left: auto; }
325
388
  meta.appendChild(el('span', '', 'Duration ' + fmtDuration(d)));
326
389
  if (d.protocolVersion) meta.appendChild(el('span', '', 'Protocol v' + d.protocolVersion));
327
390
  if (d.replayOf !== null) {
328
- var of = el('span', '', 'Replay of ');
391
+ var of = el('span', '', d.edited ? 'Edited replay of ' : 'Replay of ');
329
392
  of.appendChild(entries.has(d.replayOf) ? link('#' + d.replayOf, d.replayOf) : el('span', '', '#' + d.replayOf + ' (evicted)'));
330
393
  meta.appendChild(of);
331
394
  }
@@ -508,6 +571,155 @@ footer .stats { margin-left: auto; }
508
571
  button.disabled = false;
509
572
  });
510
573
  }
574
+
575
+ // ---------- edit & replay ----------
576
+ // Unchanged bodies are sent as the captured bytes (base64), so CRLF line endings, a BOM or
577
+ // binary data survive; the textarea only becomes the body once the user edits it.
578
+ var ed = null;
579
+ function textOrNull(bytes) {
580
+ var text;
581
+ try { text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes); } catch (e) { return null; }
582
+ return looksBinary(text) ? null : text;
583
+ }
584
+ function openEditor(d, opener) {
585
+ var req = d.request;
586
+ var raw = bytesFrom64(req.base64);
587
+ var text = textOrNull(raw);
588
+ ed = { id: d.id, opener: opener, base64: req.base64 || '', raw: raw, text: text, encoding: req.contentEncoding || '',
589
+ decoded: req.decodedBase64 || '', partial: !!req.truncated || !req.complete, truncated: req.truncated, bytes: req.bytes,
590
+ mode: text === null ? 'bytes' : 'text', touched: false, converted: '', sending: false };
591
+ $('ed-title').textContent = 'Edit & replay #' + d.id;
592
+ $('ed-sub').textContent = 'Sends a new request straight to ' + (localBase() || 'the local app') + ' (not through the tunnel). Request #' + d.id + ' stays as captured.';
593
+ var methodNote = $('ed-method-note');
594
+ clear(methodNote);
595
+ if (EDIT_METHODS.indexOf(d.method) === -1) {
596
+ $('ed-method').value = 'GET';
597
+ methodNote.appendChild(el('div', 'note warn', 'The captured method ' + d.method + ' cannot be sent from the editor; pick one of ' + EDIT_METHODS.join(', ') + '.'));
598
+ } else $('ed-method').value = d.method;
599
+ $('ed-path').value = d.path;
600
+ $('ed-headers').value = req.headers.filter(function (pair) { return !REGENERATED[pair[0].toLowerCase()]; })
601
+ .map(function (pair) { return pair[0] + ': ' + pair[1]; }).join('\n');
602
+ $('ed-body').value = text === null ? '' : text;
603
+ var crlf = text !== null && text.indexOf('\r\n') !== -1;
604
+ $('ed-eol').hidden = !(text !== null && text.indexOf('\r') !== -1);
605
+ $('ed-eol').value = crlf ? 'crlf' : 'lf';
606
+ $('ed-confirm').checked = false;
607
+ editorError('');
608
+ renderEditorBody();
609
+ $('editor').showModal();
610
+ $('ed-path').focus();
611
+ }
612
+ function renderEditorBody() {
613
+ var notes = $('ed-notes');
614
+ clear(notes);
615
+ var asIs = ed.mode === 'bytes' || !ed.touched;
616
+ if (ed.partial && asIs && ed.raw.length) {
617
+ notes.appendChild(el('div', 'note warn', ed.truncated
618
+ ? 'Partial body: only the first ' + fmtBytes(ed.raw.length) + ' of ' + fmtBytes(ed.bytes) + ' were captured. Confirm below to send it as shown, or replace it.'
619
+ : 'Partial body: the captured body never finished arriving (' + fmtBytes(ed.raw.length) + ' captured). Confirm below to send it as shown, or replace it.'));
620
+ } else if (ed.partial && ed.raw.length && ed.converted !== 'empty') {
621
+ notes.appendChild(el('div', 'note warn', 'This body started from a partial capture; check that it is complete before sending.'));
622
+ }
623
+ if (ed.mode === 'bytes') {
624
+ notes.appendChild(el('div', 'note', 'The captured body is not UTF-8 text' + (ed.encoding ? ' (Content-Encoding: ' + ed.encoding + ')' : '') + '. Its ' + fmtBytes(ed.raw.length) + ' of original bytes are sent unchanged unless you switch to editing it as text.'));
625
+ } else if (ed.converted === 'decoded' || ed.converted === 'lossy') {
626
+ notes.appendChild(el('div', 'note warn', ed.converted === 'decoded'
627
+ ? 'Shown decoded from ' + ed.encoding + '. The text is sent as is, so remove the Content-Encoding header or the app will try to decompress it.'
628
+ : 'Shown as text: bytes that are not valid UTF-8 became U+FFFD. The text below is sent, not the original bytes.'));
629
+ }
630
+ $('ed-body').hidden = ed.mode === 'bytes';
631
+ $('ed-astext').hidden = ed.mode !== 'bytes';
632
+ $('ed-restore').hidden = asIs && ed.mode === (ed.text === null ? 'bytes' : 'text');
633
+ $('ed-confirm-row').hidden = !(ed.partial && asIs && ed.raw.length);
634
+ var size = ed.mode === 'bytes' ? ed.raw.length : new TextEncoder().encode($('ed-body').value).length;
635
+ $('ed-bodyinfo').textContent = fmtBytes(size) + (asIs ? ', as captured' : ', edited');
636
+ }
637
+ function editorError(message) {
638
+ var node = $('ed-error');
639
+ node.textContent = message;
640
+ node.hidden = !message;
641
+ }
642
+ function editorPayload() {
643
+ var pairs = [];
644
+ var lines = $('ed-headers').value.split('\n');
645
+ for (var i = 0; i < lines.length; i++) {
646
+ if (!lines[i].trim()) continue;
647
+ var colon = lines[i].indexOf(':');
648
+ if (colon <= 0) return { error: 'Header line ' + (i + 1) + ' must look like "name: value".' };
649
+ pairs.push([lines[i].slice(0, colon).trim(), lines[i].slice(colon + 1).trim()]);
650
+ }
651
+ var payload = { replayOf: ed.id, method: $('ed-method').value, path: $('ed-path').value, headers: pairs };
652
+ if (ed.mode === 'bytes' || !ed.touched) {
653
+ if (ed.partial && ed.raw.length && !$('ed-confirm').checked) return { error: 'The body shown is partial. Tick "Send this partial body as shown", or replace or empty the body.', focus: 'ed-confirm' };
654
+ payload.body = ed.base64;
655
+ payload.bodyEncoding = 'base64';
656
+ } else {
657
+ var text = $('ed-body').value;
658
+ if (!$('ed-eol').hidden && $('ed-eol').value === 'crlf') text = text.replace(/\r?\n/g, '\r\n');
659
+ payload.body = text;
660
+ payload.bodyEncoding = 'text';
661
+ }
662
+ return { payload: payload };
663
+ }
664
+ function sendEditor() {
665
+ if (!ed || ed.sending) return;
666
+ var built = editorPayload();
667
+ if (built.error) { editorError(built.error); if (built.focus) $(built.focus).focus(); return; }
668
+ editorError('');
669
+ ed.sending = true;
670
+ $('ed-send').disabled = true;
671
+ var current = ed;
672
+ api('/api/replay', { method: 'POST', headers: MUTATE, body: JSON.stringify(built.payload) }).then(function (body) {
673
+ if (ed === current) $('editor').close();
674
+ toast('Sent edited request as #' + body.id);
675
+ if (body.id) select(body.id);
676
+ }).catch(function (error) {
677
+ if (ed === current) editorError('Not sent: ' + error.message);
678
+ }).then(function () {
679
+ current.sending = false;
680
+ $('ed-send').disabled = false;
681
+ });
682
+ }
683
+ function touchBody() { ed.touched = true; renderEditorBody(); }
684
+ $('ed-body').addEventListener('input', function () { if (ed && !ed.touched) touchBody(); else if (ed) renderEditorBody(); });
685
+ $('ed-eol').addEventListener('change', function () { if (ed) touchBody(); });
686
+ $('ed-confirm').addEventListener('change', function () { if ($('ed-confirm').checked) editorError(''); });
687
+ $('ed-astext').addEventListener('click', function () {
688
+ var decoded = ed.decoded ? textOrNull(bytesFrom64(ed.decoded)) : null;
689
+ ed.converted = decoded !== null ? 'decoded' : 'lossy';
690
+ $('ed-body').value = decoded !== null ? decoded : utf8(ed.raw, false);
691
+ ed.mode = 'text';
692
+ touchBody();
693
+ $('ed-body').focus();
694
+ });
695
+ $('ed-restore').addEventListener('click', function () {
696
+ ed.mode = ed.text === null ? 'bytes' : 'text';
697
+ ed.touched = false;
698
+ ed.converted = '';
699
+ $('ed-body').value = ed.text === null ? '' : ed.text;
700
+ $('ed-eol').value = ed.text !== null && ed.text.indexOf('\r\n') !== -1 ? 'crlf' : 'lf';
701
+ renderEditorBody();
702
+ });
703
+ $('ed-empty').addEventListener('click', function () {
704
+ ed.mode = 'text';
705
+ ed.converted = 'empty';
706
+ $('ed-body').value = '';
707
+ touchBody();
708
+ $('ed-body').focus();
709
+ });
710
+ $('ed-send').addEventListener('click', sendEditor);
711
+ $('ed-cancel').addEventListener('click', function () { $('editor').close(); });
712
+ $('editor').addEventListener('keydown', function (event) {
713
+ if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) { event.preventDefault(); sendEditor(); }
714
+ });
715
+ $('editor').addEventListener('close', function () {
716
+ var opener = ed && ed.opener;
717
+ ed = null;
718
+ // Live updates re-render the detail pane, so the button that opened the editor may be gone.
719
+ var target = opener && opener.isConnected ? opener : $('d-edit');
720
+ if (target) target.focus();
721
+ });
722
+
511
723
  function shellQuote(value) { return "'" + String(value).replace(/'/g, "'\\''") + "'"; }
512
724
  function publicBase(d) {
513
725
  var url = (status && status.publicUrl) || d.publicUrl;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "portpreview",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
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",
@@ -35,8 +35,6 @@
35
35
  "scripts": {
36
36
  "prepublishOnly": "npm test",
37
37
  "start": "node bin/portpreview.mjs",
38
- "gateway": "node bin/gateway.mjs",
39
- "telegram-daemon": "node bin/telegram-daemon.mjs",
40
38
  "test": "node --test test/*.test.mjs"
41
39
  },
42
40
  "keywords": [
@@ -45,7 +43,10 @@
45
43
  "preview",
46
44
  "webhook",
47
45
  "devtools",
48
- "cli"
46
+ "cli",
47
+ "ngrok",
48
+ "localtunnel",
49
+ "tcp-tunnel"
49
50
  ],
50
51
  "engines": {
51
52
  "node": ">=18"
@@ -60,7 +61,10 @@
60
61
  "url": "https://github.com/elemops/portpreview/issues"
61
62
  },
62
63
  "dependencies": {
63
- "node-telegram-bot-api": "^1.2.0",
64
64
  "ws": "^8.19.0"
65
+ },
66
+ "publishConfig": {
67
+ "access": "public",
68
+ "registry": "https://registry.npmjs.org/"
65
69
  }
66
70
  }