portpreview 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,445 @@
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, 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
+ const SSE_BUFFER_LIMIT = 4 * 1024 * 1024
14
+ const UPDATE_COALESCE_MS = 100
15
+ const HEARTBEAT_MS = 15_000
16
+ const REPLAY_TIMEOUT_MS = 30_000
17
+
18
+ /**
19
+ * Local-only inspector UI and API. Binds 127.0.0.1 only, enforces a loopback Host allowlist
20
+ * (DNS rebinding), never sends CORS headers, and requires a custom header, a JSON content type
21
+ * and a same-origin Origin (when present) for state-changing requests. The server and its
22
+ * sockets are unref'd, so it never keeps the process alive.
23
+ *
24
+ * @param {{ store: ReturnType<typeof import('./inspector-store.mjs').createInspectorStore>, target: { host: string, port: number },
25
+ * port?: number, strictPort?: boolean, getStatus?: () => Record<string, unknown>, log?: (line: string) => void }} options
26
+ * @returns {Promise<{ url: string, port: number, close: () => Promise<void> }>}
27
+ */
28
+ export async function startInspectorServer({ store, target, port = DEFAULT_INSPECTOR_PORT, strictPort = false, getStatus, log } = {}) {
29
+ if (!store) throw new TypeError('startInspectorServer requires a store')
30
+ if (!target?.port) throw new TypeError('startInspectorServer requires a target { host, port }')
31
+ const targetHost = target.host || '127.0.0.1'
32
+ const sockets = new Set()
33
+ const sseClients = new Set()
34
+ const replays = new Set()
35
+ let allowedHosts = new Set()
36
+ let closed = false
37
+
38
+ const server = http.createServer((req, res) => {
39
+ try { handle(req, res) }
40
+ catch { fail(res, 500, 'Internal inspector error') }
41
+ })
42
+ server.on('connection', socket => {
43
+ socket.unref()
44
+ sockets.add(socket)
45
+ socket.once('close', () => sockets.delete(socket))
46
+ })
47
+ server.on('clientError', (_error, socket) => socket.destroy())
48
+ server.unref()
49
+
50
+ const boundPort = await bind(server, port, strictPort)
51
+ allowedHosts = new Set([`127.0.0.1:${boundPort}`, `localhost:${boundPort}`, `[::1]:${boundPort}`])
52
+ const url = `http://127.0.0.1:${boundPort}`
53
+
54
+ // Store events -> SSE. `updated` is coalesced per entry so streaming bodies do not flood clients.
55
+ const pendingUpdates = new Set()
56
+ let flushTimer = null
57
+ const flush = () => {
58
+ flushTimer = null
59
+ const ids = [...pendingUpdates]
60
+ pendingUpdates.clear()
61
+ for (const id of ids) {
62
+ const entry = store.get(id)
63
+ if (entry) broadcast('updated', summary(entry))
64
+ }
65
+ }
66
+ const listeners = {
67
+ created: entry => { pendingUpdates.delete(entry.id); broadcast('created', summary(entry), entry.id) },
68
+ updated: entry => {
69
+ pendingUpdates.add(entry.id)
70
+ if (!flushTimer && sseClients.size) { flushTimer = setTimeout(flush, UPDATE_COALESCE_MS); flushTimer.unref() }
71
+ else if (!sseClients.size) pendingUpdates.clear()
72
+ },
73
+ evicted: ids => { for (const id of ids) pendingUpdates.delete(id); broadcast('evicted', { ids }) },
74
+ cleared: () => { pendingUpdates.clear(); broadcast('cleared', {}) },
75
+ }
76
+ const subscriptions = Object.entries(listeners).map(([name, listener]) => [name, (...args) => { try { listener(...args) } catch {} }])
77
+ for (const [name, listener] of subscriptions) store.on(name, listener)
78
+ const heartbeat = setInterval(() => { for (const res of sseClients) write(res, ': ping\n\n') }, HEARTBEAT_MS)
79
+ heartbeat.unref()
80
+
81
+ function broadcast(event, data, id) {
82
+ if (!sseClients.size) return
83
+ const message = `${id ? `id: ${id}\n` : ''}event: ${event}\ndata: ${JSON.stringify(data)}\n\n`
84
+ for (const res of sseClients) write(res, message)
85
+ }
86
+ function write(res, text) {
87
+ // A client that stopped reading is dropped; EventSource reconnects and the UI refetches.
88
+ if (res.writableLength > SSE_BUFFER_LIMIT) { res.destroy(); sseClients.delete(res); return }
89
+ res.write(text)
90
+ }
91
+
92
+ function handle(req, res) {
93
+ const host = String(req.headers.host ?? '').toLowerCase()
94
+ if (!allowedHosts.has(host)) { fail(res, 403, 'Forbidden host'); return }
95
+ let pathname, query
96
+ try { ({ pathname, searchParams: query } = new URL(req.url ?? '/', 'http://127.0.0.1')) }
97
+ catch { fail(res, 400, 'Bad request'); return }
98
+
99
+ if (pathname === '/') {
100
+ if (req.method !== 'GET' && req.method !== 'HEAD') { fail(res, 405, 'Method not allowed'); return }
101
+ const nonce = crypto.randomBytes(18).toString('base64')
102
+ const html = Buffer.from(renderInspectorPage({ nonce }))
103
+ res.writeHead(200, { ...securityHeaders(nonce), 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': html.length })
104
+ res.end(req.method === 'HEAD' ? undefined : html)
105
+ return
106
+ }
107
+ if (!pathname.startsWith('/api/')) { fail(res, 404, 'Not found'); return }
108
+ // Defence in depth: browsers label cross-origin fetches; other localhost ports are "same-site".
109
+ const site = req.headers['sec-fetch-site']
110
+ if (site !== undefined && site !== 'same-origin' && site !== 'none') { fail(res, 403, 'Cross-origin requests are not allowed'); return }
111
+ // Preflights are never answered, so browsers refuse cross-origin requests with custom headers.
112
+ if (req.method === 'OPTIONS') { fail(res, 405, 'Method not allowed'); return }
113
+
114
+ const parts = pathname.split('/').filter(Boolean) // ['api', ...]
115
+ const route = parts.slice(1)
116
+ if (route.length === 1 && route[0] === 'status' && req.method === 'GET') { status(res); return }
117
+ if (route.length === 1 && route[0] === 'events' && req.method === 'GET') { events(req, res, query); return }
118
+ if (route[0] === 'requests') {
119
+ if (route.length === 1 && req.method === 'GET') { list(res, query); return }
120
+ if (route.length === 1 && req.method === 'DELETE') { mutate(req, res, () => { store.clear(); json(res, 200, { ok: true }) }); return }
121
+ const entry = route.length >= 2 && /^\d+$/.test(route[1]) ? store.get(Number(route[1])) : null
122
+ if (route.length >= 2 && !entry) { fail(res, 404, 'Request not found'); return }
123
+ if (route.length === 2 && req.method === 'GET') { json(res, 200, detail(entry)); return }
124
+ if (route.length === 3 && route[2] === 'replay' && req.method === 'POST') { mutate(req, res, () => replay(res, entry)); return }
125
+ if (route.length === 4 && route[2] === 'body' && (route[3] === 'request' || route[3] === 'response') && req.method === 'GET') { download(res, entry, route[3]); return }
126
+ }
127
+ fail(res, req.method === 'GET' ? 404 : 405, req.method === 'GET' ? 'Not found' : 'Method not allowed')
128
+ }
129
+
130
+ function mutate(req, res, action) {
131
+ const reason = mutationRejection(req)
132
+ if (reason) { req.resume(); fail(res, 403, reason); return }
133
+ let size = 0
134
+ let aborted = false
135
+ req.on('data', chunk => {
136
+ size += chunk.length
137
+ if (size > MUTATION_BODY_LIMIT && !aborted) { aborted = true; fail(res, 413, 'Request body too large'); req.destroy() }
138
+ })
139
+ req.once('end', () => { if (!aborted) { try { action() } catch { fail(res, 500, 'Internal inspector error') } } })
140
+ req.once('error', () => {})
141
+ }
142
+
143
+ function status(res) {
144
+ let extra = {}
145
+ try { extra = getStatus?.() ?? {} } catch {}
146
+ json(res, 200, {
147
+ publicUrl: null,
148
+ ...extra,
149
+ target: `http://${net.isIPv6(targetHost) ? `[${targetHost}]` : targetHost}:${target.port}`,
150
+ inspector: { url, port: boundPort, ...store.stats() },
151
+ })
152
+ }
153
+
154
+ function list(res, query) {
155
+ const after = toInt(query.get('after'), 0)
156
+ const limit = Math.min(toInt(query.get('limit'), 500), 500)
157
+ json(res, 200, { entries: store.list({ after, limit }).map(summary), stats: store.stats() })
158
+ }
159
+
160
+ function events(req, res, query) {
161
+ res.writeHead(200, { ...securityHeaders(), 'Content-Type': 'text/event-stream; charset=utf-8', 'X-Accel-Buffering': 'no' })
162
+ res.write('retry: 2000\n\n')
163
+ const after = toInt(query.get('after') ?? req.headers['last-event-id'], -1)
164
+ if (after >= 0) for (const entry of store.list({ after })) res.write(`id: ${entry.id}\nevent: created\ndata: ${JSON.stringify(summary(entry))}\n\n`)
165
+ sseClients.add(res)
166
+ res.once('close', () => sseClients.delete(res))
167
+ }
168
+
169
+ function download(res, entry, side) {
170
+ const body = store.body(entry, side)
171
+ res.writeHead(200, {
172
+ ...securityHeaders(),
173
+ 'Content-Type': 'application/octet-stream',
174
+ 'Content-Disposition': `attachment; filename="request-${entry.id}-${side}.bin"`,
175
+ 'Content-Length': body.length,
176
+ })
177
+ res.end(body)
178
+ }
179
+
180
+ function replay(res, entry) {
181
+ const blocked = replayBlockedReason(entry)
182
+ if (blocked) { json(res, 409, { error: blocked }); return }
183
+ 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,
188
+ })
189
+ exchange.requestChunk(body)
190
+ exchange.requestEnd()
191
+ const startedAt = performance.now()
192
+ let logged = false
193
+ const logLine = (code, note = '') => {
194
+ if (logged || !log) return
195
+ logged = true
196
+ const ms = Math.max(0, Math.round(performance.now() - startedAt))
197
+ try { log(`${entry.method} ${entry.path} ${code} ${ms}ms (replay${note ? `, ${note}` : ''})`) } catch {}
198
+ }
199
+ let request
200
+ try {
201
+ request = http.request({ host: targetHost, port: target.port, method: entry.method, path: entry.path, headers })
202
+ } catch (error) {
203
+ exchange.finish({ error })
204
+ logLine(502, localErrorReason(error))
205
+ json(res, 200, { id: exchange.id })
206
+ return
207
+ }
208
+ replays.add(request)
209
+ request.once('close', () => replays.delete(request))
210
+ request.setTimeout(REPLAY_TIMEOUT_MS, () => request.destroy(new Error('Local request timed out')))
211
+ request.once('response', response => {
212
+ logLine(response.statusCode ?? 502)
213
+ exchange.response(response.statusCode ?? 502, response.headers, response.rawHeaders)
214
+ response.on('data', chunk => exchange.responseChunk(chunk))
215
+ response.once('end', () => exchange.finish())
216
+ response.once('close', () => { if (!response.complete) exchange.finish({ error: new Error('Local response aborted') }) })
217
+ response.on('error', () => {})
218
+ })
219
+ request.on('error', error => {
220
+ logLine(502, localErrorReason(error))
221
+ exchange.finish({ error })
222
+ })
223
+ request.end(body.length ? body : undefined)
224
+ json(res, 200, { id: exchange.id })
225
+ }
226
+
227
+ return {
228
+ url,
229
+ port: boundPort,
230
+ async close() {
231
+ if (closed) return
232
+ closed = true
233
+ clearInterval(heartbeat)
234
+ if (flushTimer) clearTimeout(flushTimer)
235
+ for (const [name, listener] of subscriptions) store.off(name, listener)
236
+ for (const request of replays) request.destroy()
237
+ for (const res of sseClients) res.destroy()
238
+ sseClients.clear()
239
+ const done = new Promise(resolve => server.close(() => resolve()))
240
+ if (typeof server.closeAllConnections === 'function') server.closeAllConnections() // Node >= 18.2
241
+ for (const socket of sockets) socket.destroy()
242
+ await done
243
+ },
244
+ }
245
+ }
246
+
247
+ /**
248
+ * CLI wiring: create a store and bind the server in the background, concurrently with the tunnel.
249
+ * A bind failure prints one warning and turns capture off; it never throws or delays the tunnel.
250
+ * @param {{ host: string, port: number, quiet?: boolean, inspectPort?: number, inspectPortExplicit?: boolean }} options
251
+ * @param {{ version?: string, getTunnel?: () => { url?: string, protocolVersion?: number, streaming?: boolean } | undefined }} [context]
252
+ * @returns {{ store: { begin: Function }, url: Promise<string | null>, close: () => Promise<void> }}
253
+ */
254
+ export function startInspector(options, { version, getTunnel } = {}) {
255
+ const store = createInspectorStore()
256
+ let enabled = true
257
+ let closing = false
258
+ const port = options.inspectPort ?? DEFAULT_INSPECTOR_PORT
259
+ const started = Promise.resolve().then(() => startInspectorServer({
260
+ store,
261
+ target: { host: options.host, port: options.port },
262
+ port,
263
+ strictPort: Boolean(options.inspectPortExplicit),
264
+ log: options.quiet ? undefined : line => console.log(line),
265
+ getStatus: () => {
266
+ const tunnel = getTunnel?.()
267
+ return { version: version ?? null, publicUrl: tunnel?.url ?? null, protocolVersion: tunnel?.protocolVersion ?? null, streaming: tunnel?.streaming ?? null }
268
+ },
269
+ })).then(server => {
270
+ if (closing) { void server.close(); return null }
271
+ return server
272
+ }, error => {
273
+ enabled = false
274
+ store.clear()
275
+ const reason = error?.code === 'EADDRINUSE' ? `port ${port} is in use` : error?.code === 'EACCES' ? `port ${port} is not permitted` : String(error?.message ?? error)
276
+ console.error(options.inspectPortExplicit
277
+ ? `Inspector disabled: ${reason}. Pick another --inspect-port, or use --no-inspect.`
278
+ : `Inspector disabled: ${reason}.`)
279
+ return null
280
+ })
281
+ return {
282
+ // The tunnel only needs begin(); capture stops if the server could not start.
283
+ store: { begin: info => (enabled && !closing ? store.begin(info) : null) },
284
+ url: started.then(server => server?.url ?? null),
285
+ async close() {
286
+ closing = true
287
+ const server = await started
288
+ await server?.close()
289
+ },
290
+ }
291
+ }
292
+
293
+ function listenOnce(server, port) {
294
+ return new Promise((resolve, reject) => {
295
+ const onError = error => { server.off('listening', onListening); reject(error) }
296
+ const onListening = () => { server.off('error', onError); resolve(server.address().port) }
297
+ server.once('error', onError)
298
+ server.once('listening', onListening)
299
+ server.listen({ port, host: '127.0.0.1' })
300
+ })
301
+ }
302
+
303
+ /** Try the requested port, then the next few, then an ephemeral port. A strict port never falls back. */
304
+ async function bind(server, port, strict) {
305
+ const candidates = [port]
306
+ if (!strict && port !== 0) {
307
+ for (let next = port + 1; next <= Math.min(65535, port + FALLBACK_PORTS); next++) candidates.push(next)
308
+ candidates.push(0)
309
+ }
310
+ let lastError
311
+ for (const candidate of candidates) {
312
+ try { return await listenOnce(server, candidate) }
313
+ catch (error) {
314
+ lastError = error
315
+ if (strict || !['EADDRINUSE', 'EACCES'].includes(error.code)) throw error
316
+ }
317
+ }
318
+ throw lastError
319
+ }
320
+
321
+ /** Why a captured request cannot be replayed, or null when it can. */
322
+ export function replayBlockedReason(entry) {
323
+ if (entry.kind === 'websocket') return 'WebSocket connections cannot be replayed'
324
+ if (!entry.done) return 'The request is still in flight'
325
+ if (entry.request.truncated) return 'The request body was only partially captured'
326
+ if (!entry.request.complete) return 'The request body never finished arriving'
327
+ return null
328
+ }
329
+
330
+ /** Captured headers with Content-Length regenerated from the retained body, in the original position. */
331
+ function replayHeaders(captured, length) {
332
+ const headers = {}
333
+ let sawLength = false
334
+ for (const [name, value] of Object.entries(captured)) {
335
+ if (name.toLowerCase() === 'content-length') { sawLength = true; headers[name] = String(length); continue }
336
+ headers[name] = value
337
+ }
338
+ if (!sawLength && length > 0) headers['content-length'] = String(length)
339
+ return headers
340
+ }
341
+
342
+ function mutationRejection(req) {
343
+ if (req.headers['x-portpreview-inspector'] !== '1') return 'Missing X-PortPreview-Inspector header'
344
+ const type = String(req.headers['content-type'] ?? '').split(';')[0].trim().toLowerCase()
345
+ if (type !== 'application/json') return 'Content-Type must be application/json'
346
+ const origin = req.headers.origin
347
+ if (origin !== undefined && String(origin).toLowerCase() !== `http://${String(req.headers.host).toLowerCase()}`) return 'Origin not allowed'
348
+ return null
349
+ }
350
+
351
+ function detail(entry) {
352
+ const base = summary(entry)
353
+ const requestBody = bodyDetail(entry.request, entry.request.chunks, header(entry.headers, 'content-encoding'))
354
+ const responseBody = bodyDetail(entry.response, entry.response.chunks, header(entry.responseHeaders, 'content-encoding'))
355
+ return {
356
+ ...base,
357
+ replayable: replayBlockedReason(entry) === null,
358
+ replayBlockedReason: replayBlockedReason(entry),
359
+ request: { ...base.request, headers: headerPairs(entry.headers), contentType: header(entry.headers, 'content-type'), ...requestBody },
360
+ response: {
361
+ ...base.response,
362
+ headers: entry.responseRawHeaders ? rawPairs(entry.responseRawHeaders) : headerPairs(entry.responseHeaders ?? {}),
363
+ contentType: header(entry.responseHeaders, 'content-type'),
364
+ ...responseBody,
365
+ },
366
+ }
367
+ }
368
+
369
+ function bodyDetail(body, chunks, encoding) {
370
+ const bytes = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, body.retained)
371
+ const result = { base64: bytes.toString('base64') }
372
+ const decoded = decodeBody(bytes, encoding, Boolean(body.truncated) || !body.complete)
373
+ if (decoded) Object.assign(result, decoded)
374
+ return result
375
+ }
376
+
377
+ /** Display-only decoding of compressed bodies; raw bytes are always kept and downloadable. */
378
+ function decodeBody(bytes, encoding, partial) {
379
+ const name = String(encoding ?? '').trim().toLowerCase()
380
+ if (!bytes.length || !name || name === 'identity') return null
381
+ const options = { maxOutputLength: DECODE_LIMIT }
382
+ try {
383
+ let decoded
384
+ if (name === 'gzip' || name === 'x-gzip') decoded = zlib.gunzipSync(bytes, { ...options, finishFlush: zlib.constants.Z_SYNC_FLUSH })
385
+ else if (name === 'deflate') {
386
+ try { decoded = zlib.inflateSync(bytes, { ...options, finishFlush: zlib.constants.Z_SYNC_FLUSH }) }
387
+ catch { decoded = zlib.inflateRawSync(bytes, { ...options, finishFlush: zlib.constants.Z_SYNC_FLUSH }) }
388
+ } else if (name === 'br') decoded = zlib.brotliDecompressSync(bytes, { ...options, finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH })
389
+ else return { contentEncoding: name, decodeError: `Content-Encoding "${name}" is shown undecoded` }
390
+ return { contentEncoding: name, decodedBase64: decoded.toString('base64'), decodedPartial: partial }
391
+ } catch (error) {
392
+ const tooLarge = error?.code === 'ERR_BUFFER_TOO_LARGE' || error instanceof RangeError
393
+ return { contentEncoding: name, decodeError: tooLarge ? 'Decoded body is larger than 4 MiB; download the raw bytes instead' : `Could not decode ${name}: ${error.message}` }
394
+ }
395
+ }
396
+
397
+ function header(headers, name) {
398
+ if (!headers) return null
399
+ for (const [key, value] of Object.entries(headers)) {
400
+ if (key.toLowerCase() === name) return Array.isArray(value) ? value.join(', ') : String(value)
401
+ }
402
+ return null
403
+ }
404
+
405
+ function headerPairs(headers) {
406
+ return Object.entries(headers).flatMap(([name, value]) => (Array.isArray(value) ? value : [value]).filter(item => item !== undefined).map(item => [name, String(item)]))
407
+ }
408
+
409
+ function rawPairs(raw) {
410
+ const pairs = []
411
+ for (let i = 0; i + 1 < raw.length; i += 2) pairs.push([raw[i], raw[i + 1]])
412
+ return pairs
413
+ }
414
+
415
+ function securityHeaders(nonce = crypto.randomBytes(18).toString('base64')) {
416
+ return {
417
+ 'Cache-Control': 'no-store',
418
+ 'X-Content-Type-Options': 'nosniff',
419
+ 'Referrer-Policy': 'no-referrer',
420
+ 'Cross-Origin-Resource-Policy': 'same-origin',
421
+ 'Cross-Origin-Opener-Policy': 'same-origin',
422
+ 'X-Frame-Options': 'DENY',
423
+ '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'`,
424
+ }
425
+ }
426
+
427
+ function json(res, statusCode, value) {
428
+ if (res.headersSent || res.destroyed) return
429
+ const body = Buffer.from(JSON.stringify(value))
430
+ res.writeHead(statusCode, { ...securityHeaders(), 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': body.length })
431
+ res.end(body)
432
+ }
433
+
434
+ function fail(res, statusCode, message) { json(res, statusCode, { error: message }) }
435
+
436
+ function toInt(value, fallback) {
437
+ const number = Number(value)
438
+ return value !== null && value !== undefined && value !== '' && Number.isSafeInteger(number) && number >= 0 ? number : fallback
439
+ }
440
+
441
+ function localErrorReason(error) {
442
+ const code = error && typeof error === 'object' && 'code' in error ? String(error.code) : ''
443
+ if (code === 'ECONNREFUSED') return 'nothing is listening on the local port'
444
+ return code || (error instanceof Error ? error.message : String(error))
445
+ }