portpreview 0.3.0 → 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
@@ -102,7 +102,8 @@ Target: 127.0.0.1:5432
102
102
 
103
103
  Raw TCP for databases, SSH and other non-HTTP services. Available on Pro, Ultra and Team; each
104
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.
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.
106
107
  Each closed connection is logged with its duration and byte counts.
107
108
 
108
109
  PortPreview adds no TLS and no password on the public side of a TCP tunnel: anyone who knows the
@@ -139,6 +140,18 @@ Target: http://127.0.0.1:3000
139
140
  only partly captured, that are still in flight, or WebSockets cannot be replayed.
140
141
  Webhook signatures with a timestamp (Stripe, Slack, Svix/Clerk) are usually rejected
141
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.
142
155
  - **Copy as cURL** builds a command for the local target or the public URL. It
143
156
  contains the captured header values, so treat it as a secret.
144
157
  - **Limits:** the newest 200 entries, 1 MiB per request body, 256 KiB per response
@@ -157,14 +170,32 @@ Target: http://127.0.0.1:3000
157
170
  **Security.** The inspector listens on `127.0.0.1` only and has no login, like ngrok's
158
171
  local inspector: any program on this machine can read it. It rejects requests whose
159
172
  `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
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
163
176
  render captured data as text only; raw bodies download as attachments. The values of
164
177
  `Authorization`, `Proxy-Authorization`, `Cookie`, `Set-Cookie` and `X-API-Key` are
165
178
  hidden on screen until clicked; they are stored unmodified because replay needs them.
166
179
  On a shared machine where you do not trust other local users, run with `--no-inspect`.
167
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
+
168
199
  Library use:
169
200
 
170
201
  ```js
@@ -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.1",
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",