From a698ec582b285d3ad9af425b38b65302a65ed049 Mon Sep 17 00:00:00 2001 From: "haozhe.yang" Date: Thu, 10 Sep 2026 22:11:11 +0800 Subject: [PATCH 1/3] feat(remote-control): cache rewritten tunnel responses with ETag validation --- .changeset/rc-tunnel-cache.md | 5 +++ packages/remote-control/src/remote-control.ts | 40 ++++++++++++++++--- .../test/remote-control.test.ts | 30 +++++++++++++- 3 files changed, 67 insertions(+), 8 deletions(-) create mode 100644 .changeset/rc-tunnel-cache.md diff --git a/.changeset/rc-tunnel-cache.md b/.changeset/rc-tunnel-cache.md new file mode 100644 index 0000000000..e121fbdf51 --- /dev/null +++ b/.changeset/rc-tunnel-cache.md @@ -0,0 +1,5 @@ +--- +"@moonshot-ai/kimi-code": patch +--- + +Cache rewritten Remote Control tunnel responses with ETag validation. diff --git a/packages/remote-control/src/remote-control.ts b/packages/remote-control/src/remote-control.ts index 1eaef02e20..0fd71c604d 100644 --- a/packages/remote-control/src/remote-control.ts +++ b/packages/remote-control/src/remote-control.ts @@ -1,3 +1,4 @@ +import { createHash } from 'node:crypto'; import { hostname, platform } from 'node:os'; import { join } from 'node:path'; import { request as httpRequest, validateHeaderName, validateHeaderValue } from 'node:http'; @@ -248,6 +249,24 @@ function isGzipCompressibleType(contentType: string): boolean { return mime.startsWith('text/') || GZIP_COMPRESSIBLE_TYPES.has(mime); } +function rewrittenResponseETag(body: Buffer): string { + return `"${createHash('sha256').update(body).digest('hex')}"`; +} + +function requestMatchesETag( + headers: readonly [string, string][], + etag: string, +): boolean { + const candidates = [etag, `W/${etag}`]; + for (const [name, value] of headers) { + if (name.toLowerCase() !== 'if-none-match') continue; + for (const token of value.split(',')) { + if (candidates.includes(token.trim())) return true; + } + } + return false; +} + export async function startRemoteControl( options: RemoteControlOptions, ): Promise { @@ -856,7 +875,14 @@ function requestLocalHttp( : receivedBody; const rewritten = body !== receivedBody; const headers = filterResponseHeaders(response.rawHeaders, rewritten); - if (rewritten) headers.push('Cache-Control', 'no-cache'); + if (rewritten) { + const etag = rewrittenResponseETag(body); + headers.push('Cache-Control', 'no-cache', 'ETag', etag); + if (requestMatchesETag(parsed.headers, etag)) { + headers.push('Content-Length', '0'); + return Buffer.from(`HTTP/1.1 304 Not Modified\r\n${headerLines(headers)}\r\n\r\n`); + } + } const negotiated = response.headers['content-encoding'] === undefined && response.statusCode !== 206 && @@ -877,9 +903,6 @@ function requestLocalHttp( if (negotiated && acceptsGzipEncoding(parsed.headers)) { body = await gzipAsync(body); headers.push('Content-Encoding', 'gzip'); - for (let index = headers.length - 2; index >= 0; index -= 2) { - if (headers[index]!.toLowerCase() === 'etag') headers.splice(index, 2); - } } headers.push('Content-Length', String(body.length)); const statusCode = response.statusCode ?? 502; @@ -898,7 +921,7 @@ function requestLocalHttp( }); } -function filterResponseHeaders(rawHeaders: readonly string[], blockCacheControl = false): string[] { +function filterResponseHeaders(rawHeaders: readonly string[], blockCacheValidators = false): string[] { const connectionHeaders = new Set(); for (let index = 0; index < rawHeaders.length; index += 2) { if (rawHeaders[index]!.toLowerCase() === 'connection') { @@ -914,7 +937,12 @@ function filterResponseHeaders(rawHeaders: readonly string[], blockCacheControl if (BLOCKED_RESPONSE_HEADERS.has(lower) || connectionHeaders.has(lower)) { continue; } - if (blockCacheControl && lower === 'cache-control') continue; + if ( + blockCacheValidators && + (lower === 'cache-control' || lower === 'etag' || lower === 'last-modified') + ) { + continue; + } result.push(name, rawHeaders[index + 1]!); } return result; diff --git a/packages/remote-control/test/remote-control.test.ts b/packages/remote-control/test/remote-control.test.ts index e1da065908..964465325b 100644 --- a/packages/remote-control/test/remote-control.test.ts +++ b/packages/remote-control/test/remote-control.test.ts @@ -455,12 +455,37 @@ describe('Remote Control tunnel', () => { expect(gzipHead).toContain('HTTP/1.1 200 OK'); expect(gzipHead).toContain('Content-Encoding: gzip'); expect(gzipHead).toContain('Vary: Accept-Encoding'); - expect(gzipHead).not.toContain('ETag'); + expect(gzipHead).toContain('Cache-Control: no-cache'); + const rewrittenETag = /ETag: "([0-9a-f]{64})"/.exec(gzipHead)?.[0]; + expect(rewrittenETag).toBeDefined(); expect(gzipHead).toContain(`Content-Length: ${gzipBody.length}`); expect(gunzipSync(gzipBody).toString()).toBe( assetJs.replaceAll('"/assets/', `"/coding-relay/devices/${handle.deviceId}/assets/`), ); + const revalidateResponsePromise = nextJsonMessage(httpConnections[0]!); + httpConnections[0]!.send( + JSON.stringify({ + request_id: 'request-3b', + type: 'request', + is_last: true, + body_base64: Buffer.from( + `GET /assets/index.js HTTP/1.1\r\nHost: relay.test\r\nAccept-Encoding: br, gzip\r\nIf-None-Match: ${rewrittenETag!.replace('ETag: ', '')}\r\n\r\n`, + ).toString('base64'), + }), + ); + const revalidateResponse = Buffer.from( + (await revalidateResponsePromise)['body_base64'] as string, + 'base64', + ); + const revalidateHead = revalidateResponse + .subarray(0, revalidateResponse.indexOf('\r\n\r\n')) + .toString('latin1'); + expect(revalidateHead).toContain('HTTP/1.1 304 Not Modified'); + expect(revalidateHead).toContain('Cache-Control: no-cache'); + expect(revalidateHead).toContain(rewrittenETag!); + expect(revalidateHead).not.toContain('Content-Encoding'); + const binaryResponsePromise = nextJsonMessage(httpConnections[0]!); httpConnections[0]!.send( JSON.stringify({ @@ -501,7 +526,8 @@ describe('Remote Control tunnel', () => { const excludedHead = excludedResponse.subarray(0, excludedSeparator).toString('latin1'); expect(excludedHead).not.toContain('Content-Encoding'); expect(excludedHead).toContain('Vary: Accept-Encoding'); - expect(excludedHead).toContain('ETag: "v1"'); + expect(excludedHead).toContain(rewrittenETag!); + expect(excludedHead).not.toContain('ETag: "v1"'); expect(excludedResponse.subarray(excludedSeparator + 4).toString()).toBe( assetJs.replaceAll('"/assets/', `"/coding-relay/devices/${handle.deviceId}/assets/`), ); From 27148a23e604e3ae9f79ccfe194fb4c81ec765ab Mon Sep 17 00:00:00 2001 From: "haozhe.yang" Date: Thu, 10 Sep 2026 22:25:02 +0800 Subject: [PATCH 2/3] fix(remote-control): weaken tunnel cache etag and drop 304 content-length --- .changeset/rc-tunnel-cache.md | 2 +- packages/remote-control/src/remote-control.ts | 5 ++--- packages/remote-control/test/remote-control.test.ts | 3 ++- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.changeset/rc-tunnel-cache.md b/.changeset/rc-tunnel-cache.md index e121fbdf51..737b2821ec 100644 --- a/.changeset/rc-tunnel-cache.md +++ b/.changeset/rc-tunnel-cache.md @@ -2,4 +2,4 @@ "@moonshot-ai/kimi-code": patch --- -Cache rewritten Remote Control tunnel responses with ETag validation. +Reuse unchanged Remote Control assets across page loads instead of retransferring them. diff --git a/packages/remote-control/src/remote-control.ts b/packages/remote-control/src/remote-control.ts index 0fd71c604d..82f8528f47 100644 --- a/packages/remote-control/src/remote-control.ts +++ b/packages/remote-control/src/remote-control.ts @@ -250,14 +250,14 @@ function isGzipCompressibleType(contentType: string): boolean { } function rewrittenResponseETag(body: Buffer): string { - return `"${createHash('sha256').update(body).digest('hex')}"`; + return `W/"${createHash('sha256').update(body).digest('hex')}"`; } function requestMatchesETag( headers: readonly [string, string][], etag: string, ): boolean { - const candidates = [etag, `W/${etag}`]; + const candidates = [etag, etag.replace(/^W\//, '')]; for (const [name, value] of headers) { if (name.toLowerCase() !== 'if-none-match') continue; for (const token of value.split(',')) { @@ -879,7 +879,6 @@ function requestLocalHttp( const etag = rewrittenResponseETag(body); headers.push('Cache-Control', 'no-cache', 'ETag', etag); if (requestMatchesETag(parsed.headers, etag)) { - headers.push('Content-Length', '0'); return Buffer.from(`HTTP/1.1 304 Not Modified\r\n${headerLines(headers)}\r\n\r\n`); } } diff --git a/packages/remote-control/test/remote-control.test.ts b/packages/remote-control/test/remote-control.test.ts index 964465325b..0a7fcb5e40 100644 --- a/packages/remote-control/test/remote-control.test.ts +++ b/packages/remote-control/test/remote-control.test.ts @@ -456,7 +456,7 @@ describe('Remote Control tunnel', () => { expect(gzipHead).toContain('Content-Encoding: gzip'); expect(gzipHead).toContain('Vary: Accept-Encoding'); expect(gzipHead).toContain('Cache-Control: no-cache'); - const rewrittenETag = /ETag: "([0-9a-f]{64})"/.exec(gzipHead)?.[0]; + const rewrittenETag = /ETag: (W\/"[0-9a-f]{64}")/.exec(gzipHead)?.[0]; expect(rewrittenETag).toBeDefined(); expect(gzipHead).toContain(`Content-Length: ${gzipBody.length}`); expect(gunzipSync(gzipBody).toString()).toBe( @@ -485,6 +485,7 @@ describe('Remote Control tunnel', () => { expect(revalidateHead).toContain('Cache-Control: no-cache'); expect(revalidateHead).toContain(rewrittenETag!); expect(revalidateHead).not.toContain('Content-Encoding'); + expect(revalidateHead).not.toContain('Content-Length'); const binaryResponsePromise = nextJsonMessage(httpConnections[0]!); httpConnections[0]!.send( From 31de021cea0c16ae3597d427bcc978f7916d7e7f Mon Sep 17 00:00:00 2001 From: "haozhe.yang" Date: Thu, 10 Sep 2026 22:30:54 +0800 Subject: [PATCH 3/3] fix(remote-control): restrict tunnel 304 to successful GET/HEAD and honor wildcard If-None-Match --- packages/remote-control/src/remote-control.ts | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/packages/remote-control/src/remote-control.ts b/packages/remote-control/src/remote-control.ts index 82f8528f47..5a332278a7 100644 --- a/packages/remote-control/src/remote-control.ts +++ b/packages/remote-control/src/remote-control.ts @@ -261,7 +261,9 @@ function requestMatchesETag( for (const [name, value] of headers) { if (name.toLowerCase() !== 'if-none-match') continue; for (const token of value.split(',')) { - if (candidates.includes(token.trim())) return true; + const candidate = token.trim(); + if (candidate === '*') return true; + if (candidates.includes(candidate)) return true; } } return false; @@ -878,7 +880,12 @@ function requestLocalHttp( if (rewritten) { const etag = rewrittenResponseETag(body); headers.push('Cache-Control', 'no-cache', 'ETag', etag); - if (requestMatchesETag(parsed.headers, etag)) { + const statusCode = response.statusCode ?? 502; + const revalidatable = + (parsed.method === 'GET' || parsed.method === 'HEAD') && + statusCode >= 200 && + statusCode < 300; + if (revalidatable && requestMatchesETag(parsed.headers, etag)) { return Buffer.from(`HTTP/1.1 304 Not Modified\r\n${headerLines(headers)}\r\n\r\n`); } }