From ee1e3c9539a8cfb314a71a93e908ca06afbd9ecb Mon Sep 17 00:00:00 2001 From: developjik <67889389+developjik@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:10:48 +0900 Subject: [PATCH 01/14] Update cli.ts --- bin/cli.ts | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/bin/cli.ts b/bin/cli.ts index ea9d1e0..3bb64c1 100644 --- a/bin/cli.ts +++ b/bin/cli.ts @@ -15,6 +15,7 @@ import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { applyFaults, FaultSyntaxError, defaultEncoder, formatScenario, parseScenario } from '../src/faults.js'; import { startRecordingProxy } from '../src/proxy.js'; +import { startServe } from '../src/serve.js'; import { startReplayServer } from '../src/replay.js'; import { formatSummary, parseTrace, readTrace, resolveTracePath, summarize, traceToJsonl } from '../src/trace.js'; import { renderPanelHtml } from '../src/ui/panel.js'; @@ -45,6 +46,7 @@ const BOOLEAN_FLAGS = new Set([ 'no-redact', ]); const VALUE_FLAGS = new Set([ + 'panel-port', 'target', 'port', 'out', @@ -59,7 +61,7 @@ const VALUE_FLAGS = new Set([ 'baseline', 'fail-on', ]); -const COMMANDS = ['record', 'replay', 'inject', 'inspect', 'diff', 'help', 'version'] as const; +const COMMANDS = ['serve', 'record', 'replay', 'inject', 'inspect', 'diff', 'help', 'version'] as const; type Command = (typeof COMMANDS)[number]; interface Parsed { @@ -185,6 +187,7 @@ Usage streamscope [options] Commands + serve Record + session list + replay in one process record Reverse-proxy an app and record every SSE / NDJSON stream it serves replay Serve a recorded stream (optionally fault-injected) + timeline panel inject Write a new trace file with faults baked in (for regression fixtures) @@ -220,6 +223,12 @@ Docs: https://github.com/developjik/streamscope`; function commandHelp(command: string): string { switch (command) { + case 'serve': + return `streamscope serve --target [--port 8787] [--panel-port 8788] [--out .streams] +Both listeners bind only to 127.0.0.1. Use --port 0 --panel-port 0 for random ports. +Supports record flags (--adapter, --include, --ignore, --no-redact, --quiet) and --speed. +Open the panel URL, refresh sessions, select a recorded session. Ctrl-C stops both. +A root lock prevents duplicate serve processes; remove a stale lock only after checking the old process stopped.`; case 'record': return `streamscope record — reverse proxy + recorder @@ -308,6 +317,8 @@ export async function run(argv: string[], io: CliIO = DEFAULT_IO): Promise { + const target=flag(parsed,'target');if(!target)throw new UsageError('--target is required'); + const url=new URL(target);if(!['http:','https:'].includes(url.protocol)||url.username||url.password)throw new UsageError('target must be HTTP(S) without credentials'); + const portValue=(name:string,fallback:number)=>{const n=Number(flag(parsed,name)??fallback);if(!Number.isInteger(n)||n<0||n>65535)throw new UsageError(`--${name} must be an integer from 0 to 65535`);return n;}; + const speed=Number(flag(parsed,'speed')??1);if(!Number.isFinite(speed)||speed<0)throw new UsageError('--speed must be a nonnegative finite number'); + const adapter=(flag(parsed,'adapter')??'auto');if(!['auto','sse','ndjson','json'].includes(adapter))throw new UsageError('invalid adapter'); + const handle=await startServe({target,port:portValue('port',8787),panelPort:portValue('panel-port',8788),outDir:path.resolve(io.cwd,flag(parsed,'out')??'.streams'),speed,adapter:{framing:adapter as 'auto'|'sse'|'ndjson'|'json'},include:flag(parsed,'include')?new RegExp(flag(parsed,'include')!):undefined,ignore:flag(parsed,'ignore')?new RegExp(flag(parsed,'ignore')!):undefined,redact:!bool(parsed,'no-redact'),log:!bool(parsed,'quiet')}); + try{ + io.stdout(`streamscope proxy: ${handle.proxyUrl} -> ${target}\npanel: ${handle.url}\n`); + if(bool(parsed,'no-redact'))io.stderr('Warning: header redaction disabled; recorded headers may contain credentials.\n'); + await new Promise(resolve=>{const stop=()=>{process.off('SIGINT',stop);process.off('SIGTERM',stop);resolve();};process.on('SIGINT',stop);process.on('SIGTERM',stop);}); + }finally{await handle.close();}return 0; +} From f07ea58b5dd25c73bc27ee63ae943222488bb1b0 Mon Sep 17 00:00:00 2001 From: developjik <67889389+developjik@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:10:56 +0900 Subject: [PATCH 02/14] Update README.md --- README.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/README.md b/README.md index cab9c2c..7cad475 100644 --- a/README.md +++ b/README.md @@ -344,3 +344,34 @@ or the baseline manifest (symlink and hardlink aliases are also rejected). Argument JSON numeric normalization is conservative: fractional, exponent-form and unsafe integer values keep the original argument string, so rounding cannot hide a payload change. Those strings may still flag whitespace/key-order changes. + +### Unified recording and session replay + +```sh +streamscope serve --target http://localhost:3000 +# recording proxy: http://127.0.0.1:8787 +# session list: http://127.0.0.1:8788/ +``` + +Point the app/client at the recording proxy. Open the separate panel URL, refresh +sessions, and select a session to replay its timeline. The Sessions link returns +to the list so you can switch without restarting either listener. The session's +`/stream` endpoint replays the saved wire bytes and `/trace.json` returns its plan. +Only completed files in immediate session directories under `--out` are listed; +invalid/unavailable traces are marked rather than crashing the session list. + +`serve` accepts the existing recording flags, `--speed`, `--port` (proxy), and +`--panel-port` (list/replay). Both ports bind only to 127.0.0.1. Use port 0 for +an OS-assigned port. Ctrl-C/SIGTERM closes both servers and releases the session +root lock. Startup errors include the conflicting address and close any listener +already started. One serve process may use a root at a time. After a crash, +remove only `.streamscope-serve.lock`, and only after checking the old process +has stopped. Existing `record` and `replay` commands remain available unchanged. + +The list shows up to the newest 500 directory names. Per-session traces are +limited to 10MB; symlink directories/files, traversal, and files outside the root +are rejected. Large/unavailable traces remain on disk for existing CLI tools. +Refresh is manual: a session appears after the recording response finishes and +its trace is written. The proxy forwards live requests and records their stream +contents; header redaction stays on by default, but body contents may still be +sensitive. Use only with trusted local clients and upstreams. From 45362ff35248bac449992b0c2cc01b913bffcf4a Mon Sep 17 00:00:00 2001 From: developjik <67889389+developjik@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:11:01 +0900 Subject: [PATCH 03/14] Update index.ts --- src/index.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/index.ts b/src/index.ts index 4a56cea..10de2e7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -45,3 +45,6 @@ export { NdjsonParser } from './adapters/ndjson.js'; export { diffTraces, diffViolations, formatTraceDiff, parseDiffGates, renderDiffHtml } from './diff.js'; export type { TraceDiff, FrameChange, PayloadChange, DiffGate } from './diff.js'; + +export { startServe } from './serve.js'; +export type { ServeOptions, ServeHandle } from './serve.js'; From 2bd1c2fb55302e3c6127d79420d1134c1242124f Mon Sep 17 00:00:00 2001 From: developjik <67889389+developjik@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:11:08 +0900 Subject: [PATCH 04/14] Update proxy.ts --- src/proxy.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/proxy.ts b/src/proxy.ts index 04c841f..3bf56af 100644 --- a/src/proxy.ts +++ b/src/proxy.ts @@ -276,7 +276,7 @@ export async function startRecordingProxy(options: ProxyOptions): Promise socket.destroy()); - await new Promise((resolve) => server.listen(options.port ?? 0, options.host ?? '127.0.0.1', resolve)); + await new Promise((resolve, reject) => { const fail = (error: Error) => reject(new Error(`streamscope: cannot listen on ${options.host ?? '127.0.0.1'}:${options.port ?? 0}: ${error.message}`)); server.once('error', fail); server.listen(options.port ?? 0, options.host ?? '127.0.0.1', () => { server.off('error', fail); resolve(); }); }); const address = server.address() as AddressInfo; return { server, From 4f2475fc5702309082ed61b1413135871ae2d24c Mon Sep 17 00:00:00 2001 From: developjik <67889389+developjik@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:11:13 +0900 Subject: [PATCH 05/14] Update replay.ts --- src/replay.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/replay.ts b/src/replay.ts index 95c6f0e..a6c1e93 100644 --- a/src/replay.ts +++ b/src/replay.ts @@ -110,10 +110,10 @@ export async function startReplayServer(options: ReplayServerOptions): Promise { - void handle(req, res, plan, trace, options); + void handleReplayRequest(req, res, plan, trace, options).catch(error => { if (res.headersSent) res.destroy(); else { res.statusCode = 500; res.end(String(error)); } }); }); - await new Promise((resolve) => server.listen(options.port ?? 0, options.host ?? '127.0.0.1', resolve)); + await new Promise((resolve, reject) => { const fail = (error: Error) => reject(new Error(`streamscope: cannot listen on ${options.host ?? '127.0.0.1'}:${options.port ?? 0}: ${error.message}`)); server.once('error', fail); server.listen(options.port ?? 0, options.host ?? '127.0.0.1', () => { server.off('error', fail); resolve(); }); }); const address = server.address() as AddressInfo; const base = `http://${options.host ?? '127.0.0.1'}:${address.port}`; return { @@ -130,7 +130,7 @@ export async function startReplayServer(options: ReplayServerOptions): Promise Date: Tue, 24 Nov 2026 22:11:18 +0900 Subject: [PATCH 06/14] Create serve.ts --- src/serve.ts | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 src/serve.ts diff --git a/src/serve.ts b/src/serve.ts new file mode 100644 index 0000000..af3e9c9 --- /dev/null +++ b/src/serve.ts @@ -0,0 +1,56 @@ +import http from 'node:http'; +import { promises as fs } from 'node:fs'; +import path from 'node:path'; +import type { AddressInfo } from 'node:net'; +import { startRecordingProxy, type ProxyOptions } from './proxy.js'; +import { handleReplayRequest, prepareReplay, type ReplayOptions } from './replay.js'; +import { parseTrace } from './trace.js'; +import { escapeHtml } from './ui/panel.js'; + +export interface ServeOptions extends ProxyOptions { panelPort?: number; speed?: number } +export interface ServeHandle { proxyUrl: string; url: string; close(): Promise } +/** Bind failures reject startup rather than escaping as uncaught server errors. */ +export function listen(server: http.Server, port: number, host: string): Promise { + return new Promise((resolve,reject)=>{const error=(e:Error)=>{server.off('listening',ready);reject(new Error(`streamscope: cannot listen on ${host}:${port}: ${e.message}`));}; const ready=()=>{server.off('error',error);resolve();};server.once('error',error);server.once('listening',ready);server.listen(port,host);}); +} +export async function startServe(options: ServeOptions): Promise { + for (const [name,value] of [['port',options.port??8787],['panelPort',options.panelPort??8788]] as const) if(!Number.isInteger(value)||value<0||value>65535)throw new Error(`${name} must be an integer from 0 to 65535`); + if(!Number.isFinite(options.speed??1)||(options.speed??1)<0)throw new Error('speed must be nonnegative and finite'); + const root=path.resolve(options.outDir??'.streams'); await fs.mkdir(root,{recursive:true}); + const lock=path.join(root,'.streamscope-serve.lock'); + let guard;try{guard=await fs.open(lock,'wx');}catch{throw new Error(`streamscope: session root already in use (or not writable): ${root}. If a previous process crashed, remove only its stale .streamscope-serve.lock after checking it stopped.`);} + try{await guard.writeFile(String(process.pid));}catch(error){await guard.close();await fs.unlink(lock);throw error;} + let proxy:Awaited>|undefined; + const server=http.createServer((req,res)=>{void route(req,res).catch(error=>{if(res.headersSent){res.destroy();return;}res.writeHead(400,{'content-type':'text/plain'});res.end(`Session unavailable: ${error instanceof Error?error.message:String(error)}`);});}); + let closed=false; + const close=async()=>{if(closed)return;closed=true;server.closeAllConnections();await new Promise(r=>server.close(()=>r()));await proxy?.close();await guard.close();await fs.unlink(lock);}; + async function session(id:string){ + if(!id||id==='.'||id==='..'||/[\\/\x00-\x1f]/.test(id))throw new Error('Invalid session id'); + const dir=path.join(root,id),file=path.join(dir,'events.jsonl'); + const [d,f]=await Promise.all([fs.lstat(dir),fs.lstat(file)]); + if(!d.isDirectory()||!f.isFile()||f.size>10_000_000)throw new Error('Session is not a regular trace below 10MB'); + const base=await fs.realpath(root),resolved=await fs.realpath(file);if(!resolved.startsWith(base+path.sep))throw new Error('Session outside root'); + const text=await fs.readFile(file,'utf8');const first=JSON.parse(text.split('\n').find(line=>line.trim())??'null') as Record|null; + if(!first||first.kind!=='meta'||first.v!==1||typeof first.session!=='string'||typeof first.adapter!=='string'||!['sse','ndjson','json','raw'].includes(String(first.framing)))throw new Error('Invalid trace metadata'); + const trace=parseTrace(text,file);if(trace.frames.some(f=>typeof f.raw!=='string'||!f.event||typeof f.event.type!=='string'))throw new Error('Invalid trace frames');return trace; + } + async function route(req:http.IncomingMessage,res:http.ServerResponse){ + if(req.method!=='GET'&&req.method!=='HEAD'){res.writeHead(405,{'allow':'GET, HEAD'});res.end();return;} + const url=new URL(req.url??'/','http://localhost'); + res.setHeader('cache-control','no-store');res.setHeader('x-content-type-options','nosniff');res.setHeader('referrer-policy','no-referrer'); + if(url.pathname==='/'){ + const entries=(await fs.readdir(root,{withFileTypes:true})).filter(e=>e.isDirectory()).sort((a,b)=>b.name.localeCompare(a.name)); + const rows:string[]=[]; + for(const entry of entries.slice(0,500)){try{const t=await session(entry.name);rows.push(`
  • ${escapeHtml(entry.name)}${t.frames.length} frames · ${escapeHtml(t.meta.adapter)}
  • `);}catch{rows.push(`
  • ${escapeHtml(entry.name)}Unavailable or still recording
  • `);}} + res.setHeader('content-security-policy',"default-src 'none'; style-src 'unsafe-inline'");res.setHeader('content-type','text/html; charset=utf-8');res.end(`streamscope sessions

    streamscope sessions

    Record through the proxy, then refresh this list. Select a session to replay its timeline.

    Refresh sessions · ${entries.length} session directories${entries.length>500?' (showing newest 500)':''}

      ${rows.join('')||'
    • No sessions yet. Send a streaming request through the recording proxy.
    • '}
    `);return; + } + const m=/^\/sessions\/([^/]+)(?:\/(stream|trace.json))?$/.exec(url.pathname); + if(!m){res.writeHead(404);res.end('not found');return;} + const trace=await session(decodeURIComponent(m[1]!));const replay:ReplayOptions={speed:options.speed??1}; + if(!m[2]){const {renderPanelHtml}=await import('./ui/panel.js');res.setHeader('content-type','text/html; charset=utf-8');res.end(renderPanelHtml(trace).replace('',''));return;} + req.url='/'+m[2];await handleReplayRequest(req,res,prepareReplay(trace,replay),trace,replay); + } + try {proxy=await startRecordingProxy({...options,outDir:root,host:'127.0.0.1'});await listen(server,options.panelPort??8788,'127.0.0.1');} + catch(error){await close();throw error;} + return {proxyUrl:proxy.url,url:`http://127.0.0.1:${(server.address() as AddressInfo).port}/`,close}; +} From 76ed387ac244ed5a7e2b3b2f8e3ba402f5d46232 Mon Sep 17 00:00:00 2001 From: developjik <67889389+developjik@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:11:24 +0900 Subject: [PATCH 07/14] Create serve.test.ts --- test/serve.test.ts | 50 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 test/serve.test.ts diff --git a/test/serve.test.ts b/test/serve.test.ts new file mode 100644 index 0000000..f75fca0 --- /dev/null +++ b/test/serve.test.ts @@ -0,0 +1,50 @@ +import http from 'node:http'; +import { promises as fs } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { once } from 'node:events'; +import { spawn } from 'node:child_process'; +import { expect,test } from 'vitest'; +import { startServe } from '../src/serve.js'; +import { startRecordingProxy } from '../src/proxy.js'; +import { startReplayServer } from '../src/replay.js'; +import { readTrace } from '../src/trace.js'; + +async function fixture(){const root=await fs.mkdtemp(path.join(os.tmpdir(),'streamscope-serve-'));const upstream=http.createServer((req,res)=>{res.writeHead(200,{'content-type':'text/event-stream'});res.end(`data: ${JSON.stringify({choices:[{delta:{content:req.url}}]})}\n\ndata: [DONE]\n\n`);});upstream.listen(0,'127.0.0.1');await once(upstream,'listening');const addr=upstream.address();if(!addr||typeof addr==='string')throw new Error('port');return{root,target:`http://127.0.0.1:${addr.port}`,done:async()=>{upstream.closeAllConnections();await new Promise(r=>upstream.close(()=>r()));await fs.rm(root,{recursive:true,force:true});}};} +async function sessions(root:string){for(let i=0;i<100;i++){const dirs=(await fs.readdir(root)).filter(n=>!n.startsWith('.'));if(dirs.length)return dirs;await new Promise(r=>setTimeout(r,10));}throw new Error('no session');} +test('serve records, lists, switches and replays two sessions without restarting',async()=>{ + const f=await fixture();const h=await startServe({target:f.target,outDir:f.root,port:0,panelPort:0,speed:0}); + try{ + expect(await (await fetch(h.url)).text()).toContain('No sessions yet'); + await (await fetch(h.proxyUrl+'/first')).text();const first=(await sessions(f.root))[0]!; + await new Promise(r=>setTimeout(r,20));await (await fetch(h.proxyUrl+'/second')).text(); + for(let i=0;i<100&&(await fs.readdir(f.root)).length<3;i++)await new Promise(r=>setTimeout(r,10)); + const ids=(await fs.readdir(f.root)).filter(n=>!n.startsWith('.'));expect(ids).toHaveLength(2); + const list=await (await fetch(h.url)).text();for(const id of ids)expect(list).toContain(encodeURIComponent(id)); + for(const id of ids){const panel=await(await fetch(h.url+'sessions/'+encodeURIComponent(id))).text();expect(panel).toContain('← Sessions');const trace=await readTrace(path.join(f.root,id));expect(await(await fetch(h.url+'sessions/'+encodeURIComponent(id)+'/stream')).text()).toBe(trace.frames.map(x=>x.raw).join(''));expect(((await(await fetch(h.url+'sessions/'+encodeURIComponent(id)+'/trace.json')).json()) as {frames:unknown[]}).frames).toHaveLength(trace.frames.length);} + expect(first).toBeTruthy(); + await expect(startServe({target:f.target,outDir:f.root,port:0,panelPort:0})).rejects.toThrow(/already in use/); + await fs.mkdir(path.join(f.root,'bad'));await fs.writeFile(path.join(f.root,'bad','events.jsonl'),'not json'); + expect((await fetch(h.url+'sessions/bad/stream')).status).toBe(400); + await fs.symlink(path.dirname(f.root),path.join(f.root,'escape')); + expect((await fetch(h.url+'sessions/escape/stream')).status).toBe(400); + expect((await fetch(h.url+'sessions/%2e%2e%2foutside/stream')).status).toBe(400); + expect((await fetch(h.url,{method:'POST'})).status).toBe(405); + }finally{await h.close();await h.close();await f.done();} +}); +test('port conflicts reject clearly and release both proxy and root lock',async()=>{ + const f=await fixture();const blocker=http.createServer();blocker.listen(0,'127.0.0.1');await once(blocker,'listening');const addr=blocker.address();if(!addr||typeof addr==='string')throw new Error('port'); + try{ + for(const create of [()=>startServe({target:f.target,outDir:f.root,port:addr.port,panelPort:0}),()=>startServe({target:f.target,outDir:f.root,port:0,panelPort:addr.port}),()=>startRecordingProxy({target:f.target,port:addr.port}),()=>startReplayServer({trace:{meta:{v:1,kind:'meta',session:'x',adapter:'sse',framing:'sse',protocol:'generic',startedAt:new Date().toISOString()},frames:[]},port:addr.port})])await expect(create()).rejects.toThrow(/cannot listen/); + const h=await startServe({target:f.target,outDir:f.root,port:0,panelPort:0});await h.close();expect(await fs.readdir(f.root)).toEqual([]); + }finally{await new Promise(r=>blocker.close(()=>r()));await f.done();} +}); +test('built serve CLI exits cleanly on SIGTERM and releases listeners and lock',async()=>{ + const f=await fixture();const child=spawn(process.execPath,['dist/cli.js','serve','--target',f.target,'--port','0','--panel-port','0','--out',f.root,'--quiet'],{cwd:process.cwd(),stdio:['ignore','pipe','pipe']}); + let output='';child.stdout.on('data',d=>output+=d.toString());let error='';child.stderr.on('data',d=>error+=d.toString()); + try{ + for(let i=0;i<200&&!output.includes('panel:');i++){if(child.exitCode!==null)throw new Error(error);await new Promise(r=>setTimeout(r,10));} + expect(output).toContain('panel:');const urls=output.match(/http:\/\/127\.0\.0\.1:\d+/g)!;await(await fetch(urls[0]!+'/cli')).text(); + child.kill('SIGTERM');expect((await once(child,'exit'))[0]).toBe(0);await expect(fetch(urls.at(-1)!)).rejects.toThrow();expect((await fs.readdir(f.root)).includes('.streamscope-serve.lock')).toBe(false); + }finally{if(child.exitCode===null){child.kill('SIGKILL');await once(child,'exit');}await f.done();} +}); From 70831d2dd5090d3d2e12470659382924eaa3d4ad Mon Sep 17 00:00:00 2001 From: developjik <67889389+developjik@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:12:01 +0900 Subject: [PATCH 08/14] Update serve.test.ts --- test/serve.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/serve.test.ts b/test/serve.test.ts index f75fca0..9d8e406 100644 --- a/test/serve.test.ts +++ b/test/serve.test.ts @@ -3,7 +3,7 @@ import { promises as fs } from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { once } from 'node:events'; -import { spawn } from 'node:child_process'; +import { spawn, execFileSync } from 'node:child_process'; import { expect,test } from 'vitest'; import { startServe } from '../src/serve.js'; import { startRecordingProxy } from '../src/proxy.js'; @@ -40,6 +40,7 @@ test('port conflicts reject clearly and release both proxy and root lock',async( }finally{await new Promise(r=>blocker.close(()=>r()));await f.done();} }); test('built serve CLI exits cleanly on SIGTERM and releases listeners and lock',async()=>{ + execFileSync(process.platform==='win32'?'npm.cmd':'npm',['run','build'],{cwd:process.cwd(),stdio:'pipe'}); const f=await fixture();const child=spawn(process.execPath,['dist/cli.js','serve','--target',f.target,'--port','0','--panel-port','0','--out',f.root,'--quiet'],{cwd:process.cwd(),stdio:['ignore','pipe','pipe']}); let output='';child.stdout.on('data',d=>output+=d.toString());let error='';child.stderr.on('data',d=>error+=d.toString()); try{ From dbead2b2a25a07f54217499ed86382dfa4ddce5f Mon Sep 17 00:00:00 2001 From: developjik <67889389+developjik@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:18:27 +0900 Subject: [PATCH 09/14] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 7cad475..0c03f14 100644 --- a/README.md +++ b/README.md @@ -350,7 +350,7 @@ payload change. Those strings may still flag whitespace/key-order changes. ```sh streamscope serve --target http://localhost:3000 # recording proxy: http://127.0.0.1:8787 -# session list: http://127.0.0.1:8788/ +# session list: use the exact panel URL printed by serve (includes a random access token) ``` Point the app/client at the recording proxy. Open the separate panel URL, refresh @@ -361,7 +361,7 @@ Only completed files in immediate session directories under `--out` are listed; invalid/unavailable traces are marked rather than crashing the session list. `serve` accepts the existing recording flags, `--speed`, `--port` (proxy), and -`--panel-port` (list/replay). Both ports bind only to 127.0.0.1. Use port 0 for +`--panel-port` (list/replay). Both ports bind only to 127.0.0.1. The panel URL contains a fresh random access token per process; keep that URL private. Bare-port requests cannot list or read sessions. Use port 0 for an OS-assigned port. Ctrl-C/SIGTERM closes both servers and releases the session root lock. Startup errors include the conflicting address and close any listener already started. One serve process may use a root at a time. After a crash, @@ -371,7 +371,7 @@ has stopped. Existing `record` and `replay` commands remain available unchanged. The list shows up to the newest 500 directory names. Per-session traces are limited to 10MB; symlink directories/files, traversal, and files outside the root are rejected. Large/unavailable traces remain on disk for existing CLI tools. -Refresh is manual: a session appears after the recording response finishes and +An active recorder leaves a .recording marker; partial/crashed recordings with that marker cannot be replayed here. Legacy traces without a marker are accepted, so do not run an older recorder concurrently against this root. Refresh is manual: a session appears after the recording response finishes and its trace is written. The proxy forwards live requests and records their stream contents; header redaction stays on by default, but body contents may still be sensitive. Use only with trusted local clients and upstreams. From 54bf557a4e40b6eca034f31f5055cdbd1d6a53ec Mon Sep 17 00:00:00 2001 From: developjik <67889389+developjik@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:18:35 +0900 Subject: [PATCH 10/14] Update cli.ts --- bin/cli.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/bin/cli.ts b/bin/cli.ts index 3bb64c1..b708441 100644 --- a/bin/cli.ts +++ b/bin/cli.ts @@ -609,10 +609,12 @@ async function runServe(parsed: Parsed, io: CliIO): Promise { const portValue=(name:string,fallback:number)=>{const n=Number(flag(parsed,name)??fallback);if(!Number.isInteger(n)||n<0||n>65535)throw new UsageError(`--${name} must be an integer from 0 to 65535`);return n;}; const speed=Number(flag(parsed,'speed')??1);if(!Number.isFinite(speed)||speed<0)throw new UsageError('--speed must be a nonnegative finite number'); const adapter=(flag(parsed,'adapter')??'auto');if(!['auto','sse','ndjson','json'].includes(adapter))throw new UsageError('invalid adapter'); - const handle=await startServe({target,port:portValue('port',8787),panelPort:portValue('panel-port',8788),outDir:path.resolve(io.cwd,flag(parsed,'out')??'.streams'),speed,adapter:{framing:adapter as 'auto'|'sse'|'ndjson'|'json'},include:flag(parsed,'include')?new RegExp(flag(parsed,'include')!):undefined,ignore:flag(parsed,'ignore')?new RegExp(flag(parsed,'ignore')!):undefined,redact:!bool(parsed,'no-redact'),log:!bool(parsed,'quiet')}); + let stopping=false;let finish: (()=>void)|undefined;const stop=()=>{stopping=true;finish?.();};process.on('SIGINT',stop);process.on('SIGTERM',stop); + let handle:Awaited>|undefined; try{ + handle=await startServe({target,port:portValue('port',8787),panelPort:portValue('panel-port',8788),outDir:path.resolve(io.cwd,flag(parsed,'out')??'.streams'),speed,adapter:{framing:adapter as 'auto'|'sse'|'ndjson'|'json'},include:flag(parsed,'include')?new RegExp(flag(parsed,'include')!):undefined,ignore:flag(parsed,'ignore')?new RegExp(flag(parsed,'ignore')!):undefined,redact:!bool(parsed,'no-redact'),log:!bool(parsed,'quiet')}); io.stdout(`streamscope proxy: ${handle.proxyUrl} -> ${target}\npanel: ${handle.url}\n`); if(bool(parsed,'no-redact'))io.stderr('Warning: header redaction disabled; recorded headers may contain credentials.\n'); - await new Promise(resolve=>{const stop=()=>{process.off('SIGINT',stop);process.off('SIGTERM',stop);resolve();};process.on('SIGINT',stop);process.on('SIGTERM',stop);}); - }finally{await handle.close();}return 0; + if(!stopping)await new Promise(resolve=>{finish=resolve;}); + }finally{process.off('SIGINT',stop);process.off('SIGTERM',stop);await handle?.close();}return 0; } From 43852bcbb51ef2150e7dee558925f270e9e0ca29 Mon Sep 17 00:00:00 2001 From: developjik <67889389+developjik@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:18:41 +0900 Subject: [PATCH 11/14] Update proxy.ts --- src/proxy.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/proxy.ts b/src/proxy.ts index 3bf56af..522e47a 100644 --- a/src/proxy.ts +++ b/src/proxy.ts @@ -26,6 +26,7 @@ export interface ProxyOptions { /** Never record URLs matching this pattern (assets, HMR, ...). */ ignore?: RegExp; /** Called once per recorded session. */ + onRecording?: (file: string) => void; onSession?: (trace: Trace, file: string) => void; /** Log one line per session to stderr. */ log?: boolean; @@ -189,6 +190,7 @@ export async function handleProxyRequest( if (options.outDir) recorderOptions.dir = options.outDir; if (options.now) recorderOptions.now = options.now; recorder = new Recorder(recorderOptions); + options.onRecording?.(recorder.file); void recorder.begin(); } @@ -236,6 +238,7 @@ export async function handleProxyRequest( } }); + res.on('close', () => upstream.destroy()); req.on('close', () => { if (!res.writableEnded) upstream.destroy(); }); From c87dda3d592448639677f55a2c3c75d5384e7add Mon Sep 17 00:00:00 2001 From: developjik <67889389+developjik@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:18:46 +0900 Subject: [PATCH 12/14] Update serve.ts --- src/serve.ts | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/src/serve.ts b/src/serve.ts index af3e9c9..a76c92a 100644 --- a/src/serve.ts +++ b/src/serve.ts @@ -1,5 +1,6 @@ import http from 'node:http'; -import { promises as fs } from 'node:fs'; +import { randomBytes } from 'node:crypto'; +import { constants, promises as fs } from 'node:fs'; import path from 'node:path'; import type { AddressInfo } from 'node:net'; import { startRecordingProxy, type ProxyOptions } from './proxy.js'; @@ -16,41 +17,54 @@ export function listen(server: http.Server, port: number, host: string): Promise export async function startServe(options: ServeOptions): Promise { for (const [name,value] of [['port',options.port??8787],['panelPort',options.panelPort??8788]] as const) if(!Number.isInteger(value)||value<0||value>65535)throw new Error(`${name} must be an integer from 0 to 65535`); if(!Number.isFinite(options.speed??1)||(options.speed??1)<0)throw new Error('speed must be nonnegative and finite'); + const token=randomBytes(24).toString('hex');const prefix='/'+token; const root=path.resolve(options.outDir??'.streams'); await fs.mkdir(root,{recursive:true}); const lock=path.join(root,'.streamscope-serve.lock'); - let guard;try{guard=await fs.open(lock,'wx');}catch{throw new Error(`streamscope: session root already in use (or not writable): ${root}. If a previous process crashed, remove only its stale .streamscope-serve.lock after checking it stopped.`);} + let guard;try{guard=await fs.open(lock,'wx',0o600);}catch{throw new Error(`streamscope: session root already in use (or not writable): ${root}. If a previous process crashed, remove only its stale .streamscope-serve.lock after checking it stopped.`);} try{await guard.writeFile(String(process.pid));}catch(error){await guard.close();await fs.unlink(lock);throw error;} let proxy:Awaited>|undefined; const server=http.createServer((req,res)=>{void route(req,res).catch(error=>{if(res.headersSent){res.destroy();return;}res.writeHead(400,{'content-type':'text/plain'});res.end(`Session unavailable: ${error instanceof Error?error.message:String(error)}`);});}); + const active=new Set(); let closed=false; const close=async()=>{if(closed)return;closed=true;server.closeAllConnections();await new Promise(r=>server.close(()=>r()));await proxy?.close();await guard.close();await fs.unlink(lock);}; async function session(id:string){ if(!id||id==='.'||id==='..'||/[\\/\x00-\x1f]/.test(id))throw new Error('Invalid session id'); const dir=path.join(root,id),file=path.join(dir,'events.jsonl'); + if(active.has(file)||await fs.lstat(path.join(dir,'.recording')).then(()=>true,()=>false))throw new Error('Session still recording'); const [d,f]=await Promise.all([fs.lstat(dir),fs.lstat(file)]); if(!d.isDirectory()||!f.isFile()||f.size>10_000_000)throw new Error('Session is not a regular trace below 10MB'); const base=await fs.realpath(root),resolved=await fs.realpath(file);if(!resolved.startsWith(base+path.sep))throw new Error('Session outside root'); - const text=await fs.readFile(file,'utf8');const first=JSON.parse(text.split('\n').find(line=>line.trim())??'null') as Record|null; + const fd=await fs.open(file,constants.O_RDONLY|constants.O_NOFOLLOW); + let text:string; + try { + const stat=await fd.stat();const after=await fs.lstat(file);const parent=await fs.lstat(dir); + if(!stat.isFile()||stat.size>10_000_000||stat.ino!==f.ino||stat.dev!==f.dev||after.ino!==stat.ino||after.dev!==stat.dev||parent.ino!==d.ino||parent.dev!==d.dev)throw new Error('Session changed while opening'); + if(process.platform==='linux'){const opened=await fs.realpath('/proc/self/fd/'+fd.fd);if(!opened.startsWith(base+path.sep))throw new Error('Opened file outside root');} + const buffer=Buffer.alloc(10_000_001);let count=0;while(count10_000_000)throw new Error('Trace exceeds10MB');text=buffer.subarray(0,count).toString('utf8'); + } finally {await fd.close();} + if(active.has(file))throw new Error('Session still recording'); + const first=JSON.parse(text.split('\n').find(line=>line.trim())??'null') as Record|null; if(!first||first.kind!=='meta'||first.v!==1||typeof first.session!=='string'||typeof first.adapter!=='string'||!['sse','ndjson','json','raw'].includes(String(first.framing)))throw new Error('Invalid trace metadata'); const trace=parseTrace(text,file);if(trace.frames.some(f=>typeof f.raw!=='string'||!f.event||typeof f.event.type!=='string'))throw new Error('Invalid trace frames');return trace; } async function route(req:http.IncomingMessage,res:http.ServerResponse){ if(req.method!=='GET'&&req.method!=='HEAD'){res.writeHead(405,{'allow':'GET, HEAD'});res.end();return;} const url=new URL(req.url??'/','http://localhost'); + if(!url.pathname.startsWith(prefix+'/')){res.writeHead(404);res.end('not found');return;}url.pathname=url.pathname.slice(prefix.length); res.setHeader('cache-control','no-store');res.setHeader('x-content-type-options','nosniff');res.setHeader('referrer-policy','no-referrer'); if(url.pathname==='/'){ const entries=(await fs.readdir(root,{withFileTypes:true})).filter(e=>e.isDirectory()).sort((a,b)=>b.name.localeCompare(a.name)); const rows:string[]=[]; - for(const entry of entries.slice(0,500)){try{const t=await session(entry.name);rows.push(`
  • ${escapeHtml(entry.name)}${t.frames.length} frames · ${escapeHtml(t.meta.adapter)}
  • `);}catch{rows.push(`
  • ${escapeHtml(entry.name)}Unavailable or still recording
  • `);}} - res.setHeader('content-security-policy',"default-src 'none'; style-src 'unsafe-inline'");res.setHeader('content-type','text/html; charset=utf-8');res.end(`streamscope sessions

    streamscope sessions

    Record through the proxy, then refresh this list. Select a session to replay its timeline.

    Refresh sessions · ${entries.length} session directories${entries.length>500?' (showing newest 500)':''}

      ${rows.join('')||'
    • No sessions yet. Send a streaming request through the recording proxy.
    • '}
    `);return; + for(const entry of entries.slice(0,500)){try{const t=await session(entry.name);rows.push(`
  • ${escapeHtml(entry.name)}${t.frames.length} frames · ${escapeHtml(t.meta.adapter)}
  • `);}catch{rows.push(`
  • ${escapeHtml(entry.name)}Unavailable or still recording
  • `);}} + res.setHeader('content-security-policy',"default-src 'none'; style-src 'unsafe-inline'");res.setHeader('content-type','text/html; charset=utf-8');res.end(`streamscope sessions

    streamscope sessions

    Record through the proxy, then refresh this list. Select a session to replay its timeline.

    Refresh sessions · ${entries.length} session directories${entries.length>500?' (showing newest 500)':''}

      ${rows.join('')||'
    • No sessions yet. Send a streaming request through the recording proxy.
    • '}
    `);return; } const m=/^\/sessions\/([^/]+)(?:\/(stream|trace.json))?$/.exec(url.pathname); if(!m){res.writeHead(404);res.end('not found');return;} const trace=await session(decodeURIComponent(m[1]!));const replay:ReplayOptions={speed:options.speed??1}; - if(!m[2]){const {renderPanelHtml}=await import('./ui/panel.js');res.setHeader('content-type','text/html; charset=utf-8');res.end(renderPanelHtml(trace).replace('',''));return;} + if(!m[2]){const {renderPanelHtml}=await import('./ui/panel.js');res.setHeader('content-type','text/html; charset=utf-8');res.end(renderPanelHtml(trace).replace('',``));return;} req.url='/'+m[2];await handleReplayRequest(req,res,prepareReplay(trace,replay),trace,replay); } - try {proxy=await startRecordingProxy({...options,outDir:root,host:'127.0.0.1'});await listen(server,options.panelPort??8788,'127.0.0.1');} + try {proxy=await startRecordingProxy({...options,port:options.port??8787,outDir:root,host:'127.0.0.1',onRecording:file=>{active.add(file);options.onRecording?.(file);},onSession:(trace,file)=>{active.delete(file);options.onSession?.(trace,file);}});await listen(server,options.panelPort??8788,'127.0.0.1');} catch(error){await close();throw error;} - return {proxyUrl:proxy.url,url:`http://127.0.0.1:${(server.address() as AddressInfo).port}/`,close}; + return {proxyUrl:proxy.url,url:`http://127.0.0.1:${(server.address() as AddressInfo).port}${prefix}/`,close}; } From d30fcde6361a1c4a9e5fe14bccdd2d1120838b5f Mon Sep 17 00:00:00 2001 From: developjik <67889389+developjik@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:18:51 +0900 Subject: [PATCH 13/14] Update serve.test.ts --- test/serve.test.ts | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/test/serve.test.ts b/test/serve.test.ts index 9d8e406..717fc69 100644 --- a/test/serve.test.ts +++ b/test/serve.test.ts @@ -16,6 +16,7 @@ test('serve records, lists, switches and replays two sessions without restarting const f=await fixture();const h=await startServe({target:f.target,outDir:f.root,port:0,panelPort:0,speed:0}); try{ expect(await (await fetch(h.url)).text()).toContain('No sessions yet'); + expect((await fetch(new URL('/',h.url))).status).toBe(404); await (await fetch(h.proxyUrl+'/first')).text();const first=(await sessions(f.root))[0]!; await new Promise(r=>setTimeout(r,20));await (await fetch(h.proxyUrl+'/second')).text(); for(let i=0;i<100&&(await fs.readdir(f.root)).length<3;i++)await new Promise(r=>setTimeout(r,10)); @@ -49,3 +50,24 @@ test('built serve CLI exits cleanly on SIGTERM and releases listeners and lock', child.kill('SIGTERM');expect((await once(child,'exit'))[0]).toBe(0);await expect(fetch(urls.at(-1)!)).rejects.toThrow();expect((await fs.readdir(f.root)).includes('.streamscope-serve.lock')).toBe(false); }finally{if(child.exitCode===null){child.kill('SIGKILL');await once(child,'exit');}await f.done();} }); + + +test('active POST recording is unavailable and stopping cancels its upstream connection',async()=>{ + const root=await fs.mkdtemp(path.join(os.tmpdir(),'serve-post-'));let ended:()=>void=()=>{};const closed=new Promise(r=>ended=r); + const upstream=http.createServer((req,res)=>{req.resume();res.writeHead(200,{'content-type':'text/event-stream'});res.write('data: waiting\n\n');res.on('close',ended);});upstream.listen(0,'127.0.0.1');await once(upstream,'listening');const addr=upstream.address();if(!addr||typeof addr==='string')throw Error('port'); + const h=await startServe({target:`http://127.0.0.1:${addr.port}`,outDir:root,port:0,panelPort:0}); + try{const response=await fetch(h.proxyUrl+'/hang',{method:'POST',body:'hello'});const id=(await sessions(root))[0]!; + expect((await fetch(h.url+'sessions/'+encodeURIComponent(id))).status).toBe(400);expect(await(await fetch(h.url)).text()).toContain('still recording'); + await h.close();await Promise.race([closed,new Promise((_,reject)=>setTimeout(()=>reject(Error('upstream leaked')),1000))]);await response.body?.cancel().catch(()=>{}); + }finally{await h.close();upstream.closeAllConnections();await new Promise(r=>upstream.close(()=>r()));await fs.rm(root,{recursive:true,force:true});} +}); +test('recording marker prevents partial legacy session replay',async()=>{const f=await fixture();const h=await startServe({target:f.target,outDir:f.root,port:0,panelPort:0});try{await fs.mkdir(path.join(f.root,'partial'));await fs.writeFile(path.join(f.root,'partial','.recording'),'active');await fs.writeFile(path.join(f.root,'partial','events.jsonl'),'{}');expect((await fetch(h.url+'sessions/partial/stream')).status).toBe(400);}finally{await h.close();await f.done();}}); + + +test('SIGTERM during startup releases an acquired root lock',async()=>{ + const f=await fixture();const logFile=path.join(f.root,'started'); + const code=`import {run} from ${JSON.stringify(new URL('../bin/cli.ts',import.meta.url).pathname)};`; + void code;void logFile; + const child=spawn(process.execPath,['dist/cli.js','serve','--target',f.target,'--port','0','--panel-port','0','--out',f.root,'--quiet'],{stdio:['ignore','pipe','pipe']}); + try{for(let i=0;i<1000;i++){if(await fs.stat(path.join(f.root,'.streamscope-serve.lock')).then(()=>true,()=>false))break;if(child.exitCode!==null)throw Error('early exit');await new Promise(r=>setTimeout(r,1));}child.kill('SIGTERM');expect((await once(child,'exit'))[0]).toBe(0);expect(await fs.stat(path.join(f.root,'.streamscope-serve.lock')).then(()=>true,()=>false)).toBe(false);}finally{if(child.exitCode===null){child.kill('SIGKILL');await once(child,'exit');}await f.done();} +}); From 8d9e3388375f6b2338eb19c3c5737483ed4e68af Mon Sep 17 00:00:00 2001 From: developjik <67889389+developjik@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:19:26 +0900 Subject: [PATCH 14/14] Update recorder.ts --- src/recorder.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/recorder.ts b/src/recorder.ts index 54d26fd..15be16c 100644 --- a/src/recorder.ts +++ b/src/recorder.ts @@ -65,6 +65,7 @@ export class Recorder { begin(): Promise { this.queue = this.queue.then(async () => { await fs.mkdir(path.dirname(this.file), { recursive: true }); + await fs.writeFile(path.join(path.dirname(this.file), '.recording'), 'active'); await fs.writeFile(this.file, `${serializeMeta({ ...this.meta, adapter: this.adapter.label })}\n`, 'utf8'); }); return this.queue.then(() => undefined); @@ -106,6 +107,7 @@ export class Recorder { this.meta.framing = meta.framing; this.meta.protocol = meta.protocol; if (response) this.meta.response = meta.response; + await fs.unlink(path.join(path.dirname(this.file), '.recording')).catch(() => undefined); return this.snapshot(); }