import { expect, test } from 'vitest' import { createEchoRedactionStream, redactEchoedSecrets, redactEchoedSecretsInError, secretRedactionWarningHeaderName, } from './echo-redaction.ts' const encoder = new TextEncoder() async function redactChunks(chunks: Array, values: Array) { const stream = new ReadableStream({ start(controller) { for (const chunk of chunks) controller.enqueue(chunk) controller.close() }, }).pipeThrough(createEchoRedactionStream(values)) return new Uint8Array(await new Response(stream).arrayBuffer()) } const text = (bytes: Uint8Array) => new TextDecoder().decode(bytes) test('redacts a value however the body is chunked, including split mid-value', async () => { const body = 'before sk_live_abc123 middle sk_live_abc123 after' const bytes = encoder.encode(body) const expected = 'before [REDACTED SECRET] middle [REDACTED SECRET] after' for (let split = 0; split <= bytes.length; split += 1) { const output = await redactChunks( [bytes.subarray(0, split), bytes.subarray(split)], ['sk_live_abc123'], ) expect(text(output)).toBe(expected) } const oneByteChunks = Array.from(bytes, (byte) => new Uint8Array([byte])) expect(text(await redactChunks(oneByteChunks, ['sk_live_abc123']))).toBe( expected, ) }) test('prefers the longest value at a position and leaves other bytes intact', async () => { expect( text( await redactChunks( [encoder.encode('token=abcdef; short=abc; ünïcode-secret')], ['abc', 'abcdef', 'ünïcode-secret'], ), ), ).toBe('token=[REDACTED SECRET]; short=[REDACTED SECRET]; [REDACTED SECRET]') const binary = new Uint8Array([0xff, 0x00, 0x89, 0x50, 0xfe]) expect(await redactChunks([binary], ['secret'])).toEqual(binary) }) test('a longer value that begins with a shorter one is redacted whole at every split', async () => { const bytes = encoder.encode('x abcdef y abc') for (let split = 0; split <= bytes.length; split += 1) { const output = await redactChunks( [bytes.subarray(0, split), bytes.subarray(split)], ['abc', 'abcdef'], ) expect(text(output)).toBe('x [REDACTED SECRET] y [REDACTED SECRET]') } }) test('redactEchoedSecrets redacts headers, set-cookie, and status text and keeps url', async () => { const upstream = new Response('echo: Bearer tok-123', { status: 401, statusText: 'bad tok-123', headers: { 'content-length': '20', 'www-authenticate': 'Bearer realm="tok-123"', location: 'https://evil.test/?t=tok-123', }, }) upstream.headers.append('set-cookie', 'a=tok-123; Path=/') upstream.headers.append('set-cookie', 'b=plain; Path=/') Object.defineProperty(upstream, 'url', { value: 'https://api.test/me' }) const redacted = redactEchoedSecrets(upstream, ['tok-123', '']) expect(redacted.status).toBe(401) expect(redacted.statusText).toBe('bad [REDACTED SECRET]') expect(redacted.url).toBe('https://api.test/me') expect(redacted.headers.get('content-length')).toBeNull() expect(redacted.headers.get('www-authenticate')).toBe( 'Bearer realm="[REDACTED SECRET]"', ) expect(redacted.headers.get('location')).toBe( 'https://evil.test/?t=[REDACTED SECRET]', ) expect(redacted.headers.getSetCookie()).toEqual([ 'a=[REDACTED SECRET]; Path=/', 'b=plain; Path=/', ]) expect(await redacted.text()).toBe('echo: Bearer [REDACTED SECRET]') const redirectedTo = new Response('ok') Object.defineProperties(redirectedTo, { url: { value: 'https://api.test/landing?token=tok-123' }, redirected: { value: true }, }) const landed = redactEchoedSecrets(redirectedTo, ['tok-123']) expect(landed.url).toBe('https://api.test/landing?token=[REDACTED SECRET]') expect(landed.redirected).toBe(true) const landedCopy = landed.clone().clone() expect(landedCopy.url).toBe(landed.url) expect(landedCopy.redirected).toBe(true) expect(await landedCopy.text()).toBe('ok') expect(await landed.text()).toBe('ok') const untouched = new Response('ok') expect(redactEchoedSecrets(untouched, [])).toBe(untouched) const empty = redactEchoedSecrets(new Response(null, { status: 204 }), [ 'tok-123', ]) expect(empty.status).toBe(204) expect(empty.body).toBeNull() }) test('a range response is masked byte for byte so its offsets stay true', async () => { const chunk = 'id=tok-123;' const partial = new Response(chunk, { status: 206, headers: { 'content-range': `bytes 0-${chunk.length - 1}/40`, 'content-length': String(chunk.length), }, }) const redacted = redactEchoedSecrets(partial, ['tok-123']) expect(redacted.status).toBe(206) expect(redacted.headers.get('content-range')).toBe('bytes 0-10/40') expect(redacted.headers.get('content-length')).toBe(String(chunk.length)) const body = await redacted.text() expect(body).toBe('id=*******;') expect(body).toHaveLength(chunk.length) }) test('redactEchoedSecretsInError redacts the cause chain and fields, and keeps clean errors', () => { const cause = Object.assign( new Error('connect to https://h/t-s3cret failed'), { code: 'ECONNREFUSED', url: 'https://h/t-s3cret', }, ) const error = new TypeError('fetch failed', { cause }) const redacted = redactEchoedSecretsInError(error, ['s3cret']) expect(redacted).not.toBe(error) expect(redacted).toBeInstanceOf(Error) const redactedError = redacted as Error expect(redactedError.name).toBe('TypeError') expect(redactedError.message).toBe('fetch failed') const redactedCause = redactedError.cause as Error & Record expect(redactedCause.message).toBe( 'connect to https://h/t-[REDACTED SECRET] failed', ) expect(redactedCause.code).toBe('ECONNREFUSED') expect(redactedCause.url).toBeUndefined() expect( JSON.stringify(redactedError, Object.getOwnPropertyNames(redactedError)), ).not.toContain('s3cret') const clean = new DOMException('aborted', 'AbortError') expect(redactEchoedSecretsInError(clean, ['s3cret'])).toBe(clean) }) test('a short numeric secret never rewrites ids or timestamps inside JSON', async () => { const body = JSON.stringify({ id: 981234567, orderId: 'ord_1234abc', createdAt: '2026-11-28T12:34:56.1234Z', amount: 12.34, path: '/v1/1234/items', pin: '1234', }) const expected = body.replace('"pin":"1234"', '"pin":"[REDACTED SECRET]"') const bytes = encoder.encode(body) for (let split = 0; split <= bytes.length; split += 1) { const output = text( await redactChunks( [bytes.subarray(0, split), bytes.subarray(split)], ['1234'], ), ) expect(output).toBe(expected) expect(JSON.parse(output)).toMatchObject({ id: 981234567, createdAt: '2026-11-28T12:34:56.1234Z', }) } }) test('a weak secret is still redacted where it stands alone', async () => { expect( text( await redactChunks( [encoder.encode('pin=1234&next=x 1234\n[1234] "1234" 12345 a1234')], ['1234'], ), ), ).toBe( 'pin=[REDACTED SECRET]&next=x [REDACTED SECRET]\n[[REDACTED SECRET]] "[REDACTED SECRET]" 12345 a1234', ) }) test('a strong secret is redacted even inside other text', async () => { const secret = 'Zq8xW2mN4vB7kL1p' expect( text( await redactChunks( [encoder.encode(`id-${secret}-suffix x${secret}y`)], [secret], ), ), ).toBe('id-[REDACTED SECRET]-suffix x[REDACTED SECRET]y') }) test('the redaction warning header is set only by the gateway and only for weak values', async () => { const upstream = () => new Response('{"pin":"1234"}', { headers: { [secretRedactionWarningHeaderName]: 'forged' }, }) const weak = redactEchoedSecrets(upstream(), ['1234']) expect(weak.headers.get(secretRedactionWarningHeaderName)).toMatch( /only where it stands alone/, ) expect(await weak.text()).toBe('{"pin":"[REDACTED SECRET]"}') const strong = redactEchoedSecrets(upstream(), ['Zq8xW2mN4vB7kL1p']) expect(strong.headers.has(secretRedactionWarningHeaderName)).toBe(false) const none = redactEchoedSecrets(upstream(), []) expect(none.headers.has(secretRedactionWarningHeaderName)).toBe(false) }) test('in a JSON body a weak secret is redacted only inside strings, so JSON stays valid', async () => { const body = JSON.stringify({ codes: [1234, 5], pin: '1234', note: 'pin 1234 ok', nested: { 1234: [1234] }, }) const response = redactEchoedSecrets( new Response(body, { headers: { 'content-type': 'application/json; charset=utf-8' }, }), ['1234'], ) const parsed = JSON.parse(await response.text()) expect(parsed).toEqual({ codes: [1234, 5], pin: '[REDACTED SECRET]', note: 'pin [REDACTED SECRET] ok', nested: { '[REDACTED SECRET]': [1234] }, }) }) test('a JSON string that spans chunks keeps its string state', async () => { const body = '{"a":"x \\" 1234 \\" y","b":[1234]}' const bytes = encoder.encode(body) for (let split = 0; split <= bytes.length; split += 1) { const stream = new ReadableStream({ start(controller) { controller.enqueue(bytes.subarray(0, split)) controller.enqueue(bytes.subarray(split)) controller.close() }, }).pipeThrough(createEchoRedactionStream(['1234'], { json: true })) expect(JSON.parse(await new Response(stream).text())).toEqual({ a: 'x " [REDACTED SECRET] " y', b: [1234], }) } }) test('a weak secret echoed as a path segment in a header or URL is redacted', () => { const response = redactEchoedSecrets( new Response(null, { status: 302, headers: { location: '/v1/1234/items?at=2026-11-28T12:34:56' }, }), ['1234'], ) expect(response.headers.get('location')).toBe( '/v1/[REDACTED SECRET]/items?at=2026-11-28T12:34:56', ) }) test('redaction stays linear when weak matches are mostly embedded', async () => { const body = encoder.encode( Array.from({ length: 20_000 }, (_, index) => index % 2 ? '"1234"' : '91234', ).join(','), ) const started = performance.now() const output = text(await redactChunks([body], ['1234', '12'])) expect(performance.now() - started).toBeLessThan(2000) expect(output.split('[REDACTED SECRET]')).toHaveLength(10_001) }) test('a weak secret never splits a JSON escape sequence', async () => { const body = '{"a":"x\\n","b":"n","c":"\\\\n"}' const response = redactEchoedSecrets( new Response(body, { headers: { 'content-type': 'application/json' } }), ['n'], ) expect(JSON.parse(await response.text())).toEqual({ a: 'x\n', b: '[REDACTED SECRET]', c: '\\[REDACTED SECRET]', }) }) test('a range of a JSON body that starts inside a string still masks a weak secret', async () => { const response = redactEchoedSecrets( new Response('1234","b":[1234]}', { status: 206, headers: { 'content-type': 'application/json', 'content-range': 'bytes 6-22/1234', 'content-length': '17', }, }), ['1234'], ) expect(await response.text()).toBe('****","b":[****]}') expect(response.headers.get('content-range')).toBe('bytes 6-22/1234') expect(response.headers.get('content-length')).toBe('17') }) test('a weak secret does not rewrite media types or other non-URL headers', () => { const response = redactEchoedSecrets( new Response(null, { headers: { 'content-type': 'application/1234', 'x-echo': '1234', }, }), ['1234'], ) expect(response.headers.get('content-type')).toBe('application/1234') expect(response.headers.get('x-echo')).toBe('[REDACTED SECRET]') }) test('JSON escape state survives a chunk that ends at the backslash', async () => { const bytes = encoder.encode('{"a":"x\\n","b":"n","c":"\\\\n"}') for (let split = 0; split <= bytes.length; split += 1) { const stream = new ReadableStream({ start(controller) { controller.enqueue(bytes.subarray(0, split)) controller.enqueue(bytes.subarray(split)) controller.close() }, }).pipeThrough(createEchoRedactionStream(['n'], { json: true })) expect(JSON.parse(await new Response(stream).text())).toEqual({ a: 'x\n', b: '[REDACTED SECRET]', c: '\\[REDACTED SECRET]', }) } }) test('a weak secret echoed as a path segment in a Link header is redacted', () => { const response = redactEchoedSecrets( new Response(null, { headers: { link: '; rel="next"', }, }), ['1234'], ) expect(response.headers.get('link')).toBe( '; rel="next"', ) })