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.
@@ -0,0 +1,577 @@
1
+ import crypto from 'node:crypto'
2
+ import http from 'node:http'
3
+ import net from 'node:net'
4
+ import zlib from 'node:zlib'
5
+ import { beginExchange, createInspectorStore, DEFAULT_INSPECTOR_PORT, INSPECTOR_LIMITS, summary } from './inspector-store.mjs'
6
+ import { renderInspectorPage } from './inspector-ui.mjs'
7
+
8
+ export { DEFAULT_INSPECTOR_PORT }
9
+ /** Ports tried after the requested one before falling back to an ephemeral port. */
10
+ const FALLBACK_PORTS = 9
11
+ const DECODE_LIMIT = 4 * 1024 * 1024
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
15
+ const SSE_BUFFER_LIMIT = 4 * 1024 * 1024
16
+ const UPDATE_COALESCE_MS = 100
17
+ const HEARTBEAT_MS = 15_000
18
+ const REPLAY_TIMEOUT_MS = 30_000
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
+
37
+ /**
38
+ * Local-only inspector UI and API. Binds 127.0.0.1 only, enforces a loopback Host allowlist
39
+ * (DNS rebinding), never sends CORS headers, and requires a custom header, a JSON content type
40
+ * and a same-origin Origin (when present) for state-changing requests. The server and its
41
+ * sockets are unref'd, so it never keeps the process alive.
42
+ *
43
+ * @param {{ store: ReturnType<typeof import('./inspector-store.mjs').createInspectorStore>, target: { host: string, port: number },
44
+ * port?: number, strictPort?: boolean, getStatus?: () => Record<string, unknown>, log?: (line: string) => void }} options
45
+ * @returns {Promise<{ url: string, port: number, close: () => Promise<void> }>}
46
+ */
47
+ export async function startInspectorServer({ store, target, port = DEFAULT_INSPECTOR_PORT, strictPort = false, getStatus, log } = {}) {
48
+ if (!store) throw new TypeError('startInspectorServer requires a store')
49
+ if (!target?.port) throw new TypeError('startInspectorServer requires a target { host, port }')
50
+ const targetHost = target.host || '127.0.0.1'
51
+ const sockets = new Set()
52
+ const sseClients = new Set()
53
+ const replays = new Set()
54
+ let allowedHosts = new Set()
55
+ let closed = false
56
+
57
+ const server = http.createServer((req, res) => {
58
+ try { handle(req, res) }
59
+ catch { fail(res, 500, 'Internal inspector error') }
60
+ })
61
+ server.on('connection', socket => {
62
+ socket.unref()
63
+ sockets.add(socket)
64
+ socket.once('close', () => sockets.delete(socket))
65
+ })
66
+ server.on('clientError', (_error, socket) => socket.destroy())
67
+ server.unref()
68
+
69
+ const boundPort = await bind(server, port, strictPort)
70
+ allowedHosts = new Set([`127.0.0.1:${boundPort}`, `localhost:${boundPort}`, `[::1]:${boundPort}`])
71
+ const url = `http://127.0.0.1:${boundPort}`
72
+
73
+ // Store events -> SSE. `updated` is coalesced per entry so streaming bodies do not flood clients.
74
+ const pendingUpdates = new Set()
75
+ let flushTimer = null
76
+ const flush = () => {
77
+ flushTimer = null
78
+ const ids = [...pendingUpdates]
79
+ pendingUpdates.clear()
80
+ for (const id of ids) {
81
+ const entry = store.get(id)
82
+ if (entry) broadcast('updated', summary(entry))
83
+ }
84
+ }
85
+ const listeners = {
86
+ created: entry => { pendingUpdates.delete(entry.id); broadcast('created', summary(entry), entry.id) },
87
+ updated: entry => {
88
+ pendingUpdates.add(entry.id)
89
+ if (!flushTimer && sseClients.size) { flushTimer = setTimeout(flush, UPDATE_COALESCE_MS); flushTimer.unref() }
90
+ else if (!sseClients.size) pendingUpdates.clear()
91
+ },
92
+ evicted: ids => { for (const id of ids) pendingUpdates.delete(id); broadcast('evicted', { ids }) },
93
+ cleared: () => { pendingUpdates.clear(); broadcast('cleared', {}) },
94
+ }
95
+ const subscriptions = Object.entries(listeners).map(([name, listener]) => [name, (...args) => { try { listener(...args) } catch {} }])
96
+ for (const [name, listener] of subscriptions) store.on(name, listener)
97
+ const heartbeat = setInterval(() => { for (const res of sseClients) write(res, ': ping\n\n') }, HEARTBEAT_MS)
98
+ heartbeat.unref()
99
+
100
+ function broadcast(event, data, id) {
101
+ if (!sseClients.size) return
102
+ const message = `${id ? `id: ${id}\n` : ''}event: ${event}\ndata: ${JSON.stringify(data)}\n\n`
103
+ for (const res of sseClients) write(res, message)
104
+ }
105
+ function write(res, text) {
106
+ // A client that stopped reading is dropped; EventSource reconnects and the UI refetches.
107
+ if (res.writableLength > SSE_BUFFER_LIMIT) { res.destroy(); sseClients.delete(res); return }
108
+ res.write(text)
109
+ }
110
+
111
+ function handle(req, res) {
112
+ const host = String(req.headers.host ?? '').toLowerCase()
113
+ if (!allowedHosts.has(host)) { fail(res, 403, 'Forbidden host'); return }
114
+ let pathname, query
115
+ try { ({ pathname, searchParams: query } = new URL(req.url ?? '/', 'http://127.0.0.1')) }
116
+ catch { fail(res, 400, 'Bad request'); return }
117
+
118
+ if (pathname === '/') {
119
+ if (req.method !== 'GET' && req.method !== 'HEAD') { fail(res, 405, 'Method not allowed'); return }
120
+ const nonce = crypto.randomBytes(18).toString('base64')
121
+ const html = Buffer.from(renderInspectorPage({ nonce }))
122
+ res.writeHead(200, { ...securityHeaders(nonce), 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': html.length })
123
+ res.end(req.method === 'HEAD' ? undefined : html)
124
+ return
125
+ }
126
+ if (!pathname.startsWith('/api/')) { fail(res, 404, 'Not found'); return }
127
+ // Defence in depth: browsers label cross-origin fetches; other localhost ports are "same-site".
128
+ const site = req.headers['sec-fetch-site']
129
+ if (site !== undefined && site !== 'same-origin' && site !== 'none') { fail(res, 403, 'Cross-origin requests are not allowed'); return }
130
+ // Preflights are never answered, so browsers refuse cross-origin requests with custom headers.
131
+ if (req.method === 'OPTIONS') { fail(res, 405, 'Method not allowed'); return }
132
+
133
+ const parts = pathname.split('/').filter(Boolean) // ['api', ...]
134
+ const route = parts.slice(1)
135
+ if (route.length === 1 && route[0] === 'status' && req.method === 'GET') { status(res); return }
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 }
138
+ if (route[0] === 'requests') {
139
+ if (route.length === 1 && req.method === 'GET') { list(res, query); return }
140
+ if (route.length === 1 && req.method === 'DELETE') { mutate(req, res, () => { store.clear(); json(res, 200, { ok: true }) }); return }
141
+ const entry = route.length >= 2 && /^\d+$/.test(route[1]) ? store.get(Number(route[1])) : null
142
+ if (route.length >= 2 && !entry) { fail(res, 404, 'Request not found'); return }
143
+ if (route.length === 2 && req.method === 'GET') { json(res, 200, detail(entry)); return }
144
+ if (route.length === 3 && route[2] === 'replay' && req.method === 'POST') { mutate(req, res, () => replay(res, entry)); return }
145
+ if (route.length === 4 && route[2] === 'body' && (route[3] === 'request' || route[3] === 'response') && req.method === 'GET') { download(res, entry, route[3]); return }
146
+ }
147
+ fail(res, req.method === 'GET' ? 404 : 405, req.method === 'GET' ? 'Not found' : 'Method not allowed')
148
+ }
149
+
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) {
152
+ const reason = mutationRejection(req)
153
+ if (reason) { req.resume(); fail(res, 403, reason); return }
154
+ const chunks = []
155
+ let size = 0
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()
159
+ req.on('data', chunk => {
160
+ size += chunk.length
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)
165
+ })
166
+ req.once('end', () => { if (!aborted) { try { action(Buffer.concat(chunks, size)) } catch { fail(res, 500, 'Internal inspector error') } } })
167
+ req.once('error', () => {})
168
+ }
169
+
170
+ function status(res) {
171
+ let extra = {}
172
+ try { extra = getStatus?.() ?? {} } catch {}
173
+ json(res, 200, {
174
+ publicUrl: null,
175
+ ...extra,
176
+ target: `http://${net.isIPv6(targetHost) ? `[${targetHost}]` : targetHost}:${target.port}`,
177
+ inspector: { url, port: boundPort, ...store.stats() },
178
+ })
179
+ }
180
+
181
+ function list(res, query) {
182
+ const after = toInt(query.get('after'), 0)
183
+ const limit = Math.min(toInt(query.get('limit'), 500), 500)
184
+ json(res, 200, { entries: store.list({ after, limit }).map(summary), stats: store.stats() })
185
+ }
186
+
187
+ function events(req, res, query) {
188
+ res.writeHead(200, { ...securityHeaders(), 'Content-Type': 'text/event-stream; charset=utf-8', 'X-Accel-Buffering': 'no' })
189
+ res.write('retry: 2000\n\n')
190
+ const after = toInt(query.get('after') ?? req.headers['last-event-id'], -1)
191
+ if (after >= 0) for (const entry of store.list({ after })) res.write(`id: ${entry.id}\nevent: created\ndata: ${JSON.stringify(summary(entry))}\n\n`)
192
+ sseClients.add(res)
193
+ res.once('close', () => sseClients.delete(res))
194
+ }
195
+
196
+ function download(res, entry, side) {
197
+ const body = store.body(entry, side)
198
+ res.writeHead(200, {
199
+ ...securityHeaders(),
200
+ 'Content-Type': 'application/octet-stream',
201
+ 'Content-Disposition': `attachment; filename="request-${entry.id}-${side}.bin"`,
202
+ 'Content-Length': body.length,
203
+ })
204
+ res.end(body)
205
+ }
206
+
207
+ function replay(res, entry) {
208
+ const blocked = replayBlockedReason(entry)
209
+ if (blocked) { json(res, 409, { error: blocked }); return }
210
+ const body = store.body(entry, 'request')
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,
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 })
234
+ exchange.requestChunk(body)
235
+ exchange.requestEnd()
236
+ const startedAt = performance.now()
237
+ const label = edited ? 'replay, edited' : 'replay'
238
+ let logged = false
239
+ const logLine = (code, note = '') => {
240
+ if (logged || !log) return
241
+ logged = true
242
+ const ms = Math.max(0, Math.round(performance.now() - startedAt))
243
+ try { log(`${method} ${path} ${code} ${ms}ms (${label}${note ? `, ${note}` : ''})`) } catch {}
244
+ }
245
+ let request
246
+ try {
247
+ request = http.request({ host: targetHost, port: target.port, method, path, headers })
248
+ } catch (error) {
249
+ exchange.finish({ error })
250
+ logLine(502, localErrorReason(error))
251
+ json(res, 200, { id: exchange.id })
252
+ return
253
+ }
254
+ replays.add(request)
255
+ request.once('close', () => replays.delete(request))
256
+ request.setTimeout(REPLAY_TIMEOUT_MS, () => request.destroy(new Error('Local request timed out')))
257
+ request.once('response', response => {
258
+ logLine(response.statusCode ?? 502)
259
+ exchange.response(response.statusCode ?? 502, response.headers, response.rawHeaders)
260
+ response.on('data', chunk => exchange.responseChunk(chunk))
261
+ response.once('end', () => exchange.finish())
262
+ response.once('close', () => { if (!response.complete) exchange.finish({ error: new Error('Local response aborted') }) })
263
+ response.on('error', () => {})
264
+ })
265
+ request.on('error', error => {
266
+ logLine(502, localErrorReason(error))
267
+ exchange.finish({ error })
268
+ })
269
+ request.end(body.length ? body : undefined)
270
+ json(res, 200, { id: exchange.id })
271
+ }
272
+
273
+ return {
274
+ url,
275
+ port: boundPort,
276
+ async close() {
277
+ if (closed) return
278
+ closed = true
279
+ clearInterval(heartbeat)
280
+ if (flushTimer) clearTimeout(flushTimer)
281
+ for (const [name, listener] of subscriptions) store.off(name, listener)
282
+ for (const request of replays) request.destroy()
283
+ for (const res of sseClients) res.destroy()
284
+ sseClients.clear()
285
+ const done = new Promise(resolve => server.close(() => resolve()))
286
+ if (typeof server.closeAllConnections === 'function') server.closeAllConnections() // Node >= 18.2
287
+ for (const socket of sockets) socket.destroy()
288
+ await done
289
+ },
290
+ }
291
+ }
292
+
293
+ /**
294
+ * CLI wiring: create a store and bind the server in the background, concurrently with the tunnel.
295
+ * A bind failure prints one warning and turns capture off; it never throws or delays the tunnel.
296
+ * @param {{ host: string, port: number, quiet?: boolean, inspectPort?: number, inspectPortExplicit?: boolean }} options
297
+ * @param {{ version?: string, getTunnel?: () => { url?: string, protocolVersion?: number, streaming?: boolean } | undefined }} [context]
298
+ * @returns {{ store: { begin: Function }, url: Promise<string | null>, close: () => Promise<void> }}
299
+ */
300
+ export function startInspector(options, { version, getTunnel } = {}) {
301
+ const store = createInspectorStore()
302
+ let enabled = true
303
+ let closing = false
304
+ const port = options.inspectPort ?? DEFAULT_INSPECTOR_PORT
305
+ const started = Promise.resolve().then(() => startInspectorServer({
306
+ store,
307
+ target: { host: options.host, port: options.port },
308
+ port,
309
+ strictPort: Boolean(options.inspectPortExplicit),
310
+ log: options.quiet ? undefined : line => console.log(line),
311
+ getStatus: () => {
312
+ const tunnel = getTunnel?.()
313
+ return { version: version ?? null, publicUrl: tunnel?.url ?? null, protocolVersion: tunnel?.protocolVersion ?? null, streaming: tunnel?.streaming ?? null }
314
+ },
315
+ })).then(server => {
316
+ if (closing) { void server.close(); return null }
317
+ return server
318
+ }, error => {
319
+ enabled = false
320
+ store.clear()
321
+ const reason = error?.code === 'EADDRINUSE' ? `port ${port} is in use` : error?.code === 'EACCES' ? `port ${port} is not permitted` : String(error?.message ?? error)
322
+ console.error(options.inspectPortExplicit
323
+ ? `Inspector disabled: ${reason}. Pick another --inspect-port, or use --no-inspect.`
324
+ : `Inspector disabled: ${reason}.`)
325
+ return null
326
+ })
327
+ return {
328
+ // The tunnel only needs begin(); capture stops if the server could not start.
329
+ store: { begin: info => (enabled && !closing ? store.begin(info) : null) },
330
+ url: started.then(server => server?.url ?? null),
331
+ async close() {
332
+ closing = true
333
+ const server = await started
334
+ await server?.close()
335
+ },
336
+ }
337
+ }
338
+
339
+ function listenOnce(server, port) {
340
+ return new Promise((resolve, reject) => {
341
+ const onError = error => { server.off('listening', onListening); reject(error) }
342
+ const onListening = () => { server.off('error', onError); resolve(server.address().port) }
343
+ server.once('error', onError)
344
+ server.once('listening', onListening)
345
+ server.listen({ port, host: '127.0.0.1' })
346
+ })
347
+ }
348
+
349
+ /** Try the requested port, then the next few, then an ephemeral port. A strict port never falls back. */
350
+ async function bind(server, port, strict) {
351
+ const candidates = [port]
352
+ if (!strict && port !== 0) {
353
+ for (let next = port + 1; next <= Math.min(65535, port + FALLBACK_PORTS); next++) candidates.push(next)
354
+ candidates.push(0)
355
+ }
356
+ let lastError
357
+ for (const candidate of candidates) {
358
+ try { return await listenOnce(server, candidate) }
359
+ catch (error) {
360
+ lastError = error
361
+ if (strict || !['EADDRINUSE', 'EACCES'].includes(error.code)) throw error
362
+ }
363
+ }
364
+ throw lastError
365
+ }
366
+
367
+ /** Why a captured request cannot be replayed, or null when it can. */
368
+ export function replayBlockedReason(entry) {
369
+ if (entry.kind === 'websocket') return 'WebSocket connections cannot be replayed'
370
+ if (!entry.done) return 'The request is still in flight'
371
+ if (entry.request.truncated) return 'The request body was only partially captured'
372
+ if (!entry.request.complete) return 'The request body never finished arriving'
373
+ return null
374
+ }
375
+
376
+ /** Captured headers with Content-Length regenerated from the retained body, in the original position. */
377
+ function replayHeaders(captured, length) {
378
+ const headers = {}
379
+ let sawLength = false
380
+ for (const [name, value] of Object.entries(captured)) {
381
+ if (name.toLowerCase() === 'content-length') { sawLength = true; headers[name] = String(length); continue }
382
+ headers[name] = value
383
+ }
384
+ if (!sawLength && length > 0) headers['content-length'] = String(length)
385
+ return headers
386
+ }
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
+
474
+ function mutationRejection(req) {
475
+ if (req.headers['x-portpreview-inspector'] !== '1') return 'Missing X-PortPreview-Inspector header'
476
+ const type = String(req.headers['content-type'] ?? '').split(';')[0].trim().toLowerCase()
477
+ if (type !== 'application/json') return 'Content-Type must be application/json'
478
+ const origin = req.headers.origin
479
+ if (origin !== undefined && String(origin).toLowerCase() !== `http://${String(req.headers.host).toLowerCase()}`) return 'Origin not allowed'
480
+ return null
481
+ }
482
+
483
+ function detail(entry) {
484
+ const base = summary(entry)
485
+ const requestBody = bodyDetail(entry.request, entry.request.chunks, header(entry.headers, 'content-encoding'))
486
+ const responseBody = bodyDetail(entry.response, entry.response.chunks, header(entry.responseHeaders, 'content-encoding'))
487
+ return {
488
+ ...base,
489
+ replayable: replayBlockedReason(entry) === null,
490
+ replayBlockedReason: replayBlockedReason(entry),
491
+ request: { ...base.request, headers: headerPairs(entry.headers), contentType: header(entry.headers, 'content-type'), ...requestBody },
492
+ response: {
493
+ ...base.response,
494
+ headers: entry.responseRawHeaders ? rawPairs(entry.responseRawHeaders) : headerPairs(entry.responseHeaders ?? {}),
495
+ contentType: header(entry.responseHeaders, 'content-type'),
496
+ ...responseBody,
497
+ },
498
+ }
499
+ }
500
+
501
+ function bodyDetail(body, chunks, encoding) {
502
+ const bytes = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, body.retained)
503
+ const result = { base64: bytes.toString('base64') }
504
+ const decoded = decodeBody(bytes, encoding, Boolean(body.truncated) || !body.complete)
505
+ if (decoded) Object.assign(result, decoded)
506
+ return result
507
+ }
508
+
509
+ /** Display-only decoding of compressed bodies; raw bytes are always kept and downloadable. */
510
+ function decodeBody(bytes, encoding, partial) {
511
+ const name = String(encoding ?? '').trim().toLowerCase()
512
+ if (!bytes.length || !name || name === 'identity') return null
513
+ const options = { maxOutputLength: DECODE_LIMIT }
514
+ try {
515
+ let decoded
516
+ if (name === 'gzip' || name === 'x-gzip') decoded = zlib.gunzipSync(bytes, { ...options, finishFlush: zlib.constants.Z_SYNC_FLUSH })
517
+ else if (name === 'deflate') {
518
+ try { decoded = zlib.inflateSync(bytes, { ...options, finishFlush: zlib.constants.Z_SYNC_FLUSH }) }
519
+ catch { decoded = zlib.inflateRawSync(bytes, { ...options, finishFlush: zlib.constants.Z_SYNC_FLUSH }) }
520
+ } else if (name === 'br') decoded = zlib.brotliDecompressSync(bytes, { ...options, finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH })
521
+ else return { contentEncoding: name, decodeError: `Content-Encoding "${name}" is shown undecoded` }
522
+ return { contentEncoding: name, decodedBase64: decoded.toString('base64'), decodedPartial: partial }
523
+ } catch (error) {
524
+ const tooLarge = error?.code === 'ERR_BUFFER_TOO_LARGE' || error instanceof RangeError
525
+ return { contentEncoding: name, decodeError: tooLarge ? 'Decoded body is larger than 4 MiB; download the raw bytes instead' : `Could not decode ${name}: ${error.message}` }
526
+ }
527
+ }
528
+
529
+ function header(headers, name) {
530
+ if (!headers) return null
531
+ for (const [key, value] of Object.entries(headers)) {
532
+ if (key.toLowerCase() === name) return Array.isArray(value) ? value.join(', ') : String(value)
533
+ }
534
+ return null
535
+ }
536
+
537
+ function headerPairs(headers) {
538
+ return Object.entries(headers).flatMap(([name, value]) => (Array.isArray(value) ? value : [value]).filter(item => item !== undefined).map(item => [name, String(item)]))
539
+ }
540
+
541
+ function rawPairs(raw) {
542
+ const pairs = []
543
+ for (let i = 0; i + 1 < raw.length; i += 2) pairs.push([raw[i], raw[i + 1]])
544
+ return pairs
545
+ }
546
+
547
+ function securityHeaders(nonce = crypto.randomBytes(18).toString('base64')) {
548
+ return {
549
+ 'Cache-Control': 'no-store',
550
+ 'X-Content-Type-Options': 'nosniff',
551
+ 'Referrer-Policy': 'no-referrer',
552
+ 'Cross-Origin-Resource-Policy': 'same-origin',
553
+ 'Cross-Origin-Opener-Policy': 'same-origin',
554
+ 'X-Frame-Options': 'DENY',
555
+ 'Content-Security-Policy': `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'nonce-${nonce}'; connect-src 'self'; img-src data:; frame-ancestors 'none'; form-action 'none'; base-uri 'none'`,
556
+ }
557
+ }
558
+
559
+ function json(res, statusCode, value) {
560
+ if (res.headersSent || res.destroyed) return
561
+ const body = Buffer.from(JSON.stringify(value))
562
+ res.writeHead(statusCode, { ...securityHeaders(), 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': body.length })
563
+ res.end(body)
564
+ }
565
+
566
+ function fail(res, statusCode, message) { json(res, statusCode, { error: message }) }
567
+
568
+ function toInt(value, fallback) {
569
+ const number = Number(value)
570
+ return value !== null && value !== undefined && value !== '' && Number.isSafeInteger(number) && number >= 0 ? number : fallback
571
+ }
572
+
573
+ function localErrorReason(error) {
574
+ const code = error && typeof error === 'object' && 'code' in error ? String(error.code) : ''
575
+ if (code === 'ECONNREFUSED') return 'nothing is listening on the local port'
576
+ return code || (error instanceof Error ? error.message : String(error))
577
+ }