Merge PR #682: fix(trust-fence): 允许 bfcache 恢复的图片带过期 cross-site 标记(PNG 预览空白修复)

# Conflicts:
#	tests/trusted-hosts.spec.ts
This commit is contained in:
HuanLinOTO committed 2026-10-01 17:18:31 +08:00
commit 356c3b1dbc
2 files changed
+115 -12

No files matched your search

+27 -2
View File
@@ -14,6 +14,9 @@ import type { IncomingHttpHeaders } from 'node:http'
/** The request facts the fence reads (structural subset of IncomingMessage). */
interface ApiTrustRequest {
headers: IncomingHttpHeaders
/** Present on a real node request; the bfcache exception is media-route only. */
method?: string
url?: string
}
function header(headers: IncomingHttpHeaders, name: string): string | undefined {
@@ -70,7 +73,8 @@ function isTrustedAuthority(hostUrl: URL, trustedHosts: readonly string[]): bool
/**
* Decide whether one sidebar request may reach the plugin routes.
* @param request - node HTTP request facts (headers).
* @param request - node HTTP request facts (headers, and the method/url the
* media-route exception is scoped to).
* @param trustedHosts - non-loopback authorities this deployment serves.
* @returns true when the Host is ours (loopback or trusted) and browser markers are same-origin.
*/
@@ -80,7 +84,28 @@ export function isTrustedApiRequest(request: ApiTrustRequest, trustedHosts: read
const hostUrl = parseAuthority(host)
if (hostUrl === undefined) return false
if (!isLoopbackHostname(hostUrl.hostname) && !isTrustedAuthority(hostUrl, trustedHosts)) return false
if (header(request.headers, 'sec-fetch-site') === 'cross-site') return false
const fetchSite = header(request.headers, 'sec-fetch-site')
if (fetchSite === 'cross-site') {
// Chromium can restore a same-origin image from bfcache with a stale
// cross-site marker. The exception is deliberately narrow: the media route
// only, browser image subresources only (`no-cors` + `image`), and the
// unforgeable Referer must name this exact authority. API requests, uploads,
// HTML previews, foreign embeds and Referer-less requests stay refused.
const referer = header(request.headers, 'referer')
const mediaRequest = request.method === 'GET' && (request.url ?? '').startsWith('/sidebar/file')
const restoredImage = mediaRequest
&& header(request.headers, 'sec-fetch-mode') === 'no-cors'
&& header(request.headers, 'sec-fetch-dest') === 'image'
&& referer !== undefined
&& (() => {
try {
return new URL(referer).host === hostUrl.host
} catch {
return false
}
})()
if (!restoredImage) return false
}
// Origin fence: when a browser attaches an Origin it must name this
// hostname (the Host fence above already bound the authority, so the port
// must not re-decide trust). Comparing hostname, not host: some Chromium
+88 -10
View File
@@ -15,7 +15,10 @@
* name.
*/
import { describe, expect, it } from 'vitest'
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import type { IncomingMessage, ServerResponse } from 'node:http'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { apply } from '../src/index.ts'
import type { SidebarWebRoute, SidebarWebUpgradeRoute } from '../src/context-types.ts'
@@ -63,6 +66,7 @@ function req(
function mount(initialTrustedHosts: readonly string[] = []): {
api: (r: IncomingMessage, s: ServerResponse) => Promise<void>
upgrade: (path: string) => SidebarWebUpgradeRoute['handler']
media: (r: IncomingMessage, s: ServerResponse) => Promise<void>
setTrustedHosts: (hosts: readonly string[]) => void
cleanup: () => void
} {
@@ -90,6 +94,8 @@ function mount(initialTrustedHosts: readonly string[] = []): {
apply(ctx as never)
const api = routes.find(route => route.path === '/sidebar/api')?.handler
if (api === undefined) throw new Error('test setup: /sidebar/api route not registered')
const media = routes.find(route => route.path === '/sidebar/file')?.handler
if (media === undefined) throw new Error('test setup: /sidebar/file route not registered')
return {
api: api as (r: IncomingMessage, s: ServerResponse) => Promise<void>,
upgrade: (path) => {
@@ -97,6 +103,7 @@ function mount(initialTrustedHosts: readonly string[] = []): {
if (handler === undefined) throw new Error(`test setup: ${path} upgrade route not registered`)
return handler
},
media: media as (r: IncomingMessage, s: ServerResponse) => Promise<void>,
setTrustedHosts: (hosts) => { runtime.trustedHosts = [...hosts] },
cleanup: () => { for (const cleanup of effects) cleanup() },
}
@@ -209,23 +216,94 @@ describe('remote-access trust (webRuntime.trustedHosts)', () => {
}
})
it('rejects cross-site browser markers even for a trusted host', async () => {
const { api, cleanup } = mount(['example.com'])
/**
* The four headers a same-origin `<img>` carries after Chromium restores it
* from bfcache: the stale cross-site marker plus the real Referer. The
* `Sec-Fetch-*` and `Referer` headers are forbidden request headers, so a
* foreign page cannot forge them.
*/
function restoredImageHeaders(host: string, referer: string): Record<string, string> {
return {
host,
'sec-fetch-site': 'cross-site',
'sec-fetch-mode': 'no-cors',
'sec-fetch-dest': 'image',
referer,
}
}
/** One real GET /sidebar/file for a temp PNG with `headers` on the request. */
async function mediaRequestWith(
headers: Record<string, string>,
trustedHosts: readonly string[] = [],
): Promise<{ status: number; headers: Record<string, string> }> {
const directory = mkdtempSync(join(tmpdir(), 'dsh-sidebar-fence-'))
const file = join(directory, 'shot.png')
writeFileSync(file, Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))
const { media, cleanup } = mount(trustedHosts)
try {
const query = new URLSearchParams({ sessionId: 'test-session', cwd: directory, path: file }).toString()
const res = fakeRes()
// Same-origin origin: only the explicit cross-site marker can reject —
// this pins the marker branch (a mismatched origin would also 403).
await api(req('POST', '/sidebar/api/session.cwd', {
host: 'example.com',
'sec-fetch-site': 'cross-site',
origin: 'https://example.com',
}, '{"sessionId":"test-session"}'), res as unknown as ServerResponse)
expect(res.status).toBe(403)
await media(req('GET', `/sidebar/file?${query}`, headers), res as unknown as ServerResponse)
return { status: res.status, headers: res.headers }
} finally {
cleanup()
rmSync(directory, { recursive: true, force: true })
}
}
it('accepts a restored same-origin image on the media route (Chromium stale cross-site marker)', async () => {
const res = await mediaRequestWith(restoredImageHeaders('127.0.0.1:3080', 'http://127.0.0.1:3080/'))
expect(res.status).toBe(200)
expect(res.headers['content-type']).toBe('image/png')
})
it('accepts the same restored image on a trusted remote host', async () => {
const res = await mediaRequestWith(restoredImageHeaders('example.com', 'https://example.com/'), ['example.com'])
expect(res.status).toBe(200)
})
it('refuses a cross-site image without a Referer', async () => {
const headers = restoredImageHeaders('127.0.0.1:3080', 'http://127.0.0.1:3080/')
delete headers.referer
expect((await mediaRequestWith(headers)).status).toBe(403)
})
it.each([
['a non-image no-cors subresource', { ...restoredImageHeaders('127.0.0.1:3080', 'http://127.0.0.1:3080/'), 'sec-fetch-dest': 'script' }],
['a CORS image read', { ...restoredImageHeaders('127.0.0.1:3080', 'http://127.0.0.1:3080/'), 'sec-fetch-mode': 'cors' }],
['a foreign Referer', restoredImageHeaders('127.0.0.1:3080', 'https://attacker.invalid/')],
['a look-alike Referer host', restoredImageHeaders('127.0.0.1:3080', 'http://127.0.0.1.attacker.invalid/')],
['a userinfo-spoofed Referer', restoredImageHeaders('127.0.0.1:3080', 'http://127.0.0.1@attacker.invalid/')],
['a malformed Referer', restoredImageHeaders('127.0.0.1:3080', 'null')],
['a Referer on a different port', restoredImageHeaders('127.0.0.1:3080', 'http://127.0.0.1:9999/')],
['a Referer naming localhost instead of the Host', restoredImageHeaders('127.0.0.1:3080', 'http://localhost:3080/')],
])('refuses a restored image carrying %s', async (_case, headers) => {
expect((await mediaRequestWith(headers)).status).toBe(403)
})
it('still refuses a matching-Referer image whose Origin is foreign or opaque', async () => {
const base = restoredImageHeaders('127.0.0.1:3080', 'http://127.0.0.1:3080/')
expect((await mediaRequestWith({ ...base, origin: 'https://attacker.invalid' })).status).toBe(403)
expect((await mediaRequestWith({ ...base, origin: 'null' })).status).toBe(403)
})
it('keeps the exception off the API and non-GET media paths', async () => {
const headers = restoredImageHeaders('127.0.0.1:3080', 'http://127.0.0.1:3080/')
const { api, media, cleanup } = mount([])
try {
const onApi = fakeRes()
await api(req('POST', '/sidebar/api/session.cwd', headers, '{"sessionId":"test-session"}'), onApi as unknown as ServerResponse)
expect(onApi.status).toBe(403)
const onMediaPost = fakeRes()
await media(req('POST', '/sidebar/file', headers, ''), onMediaPost as unknown as ServerResponse)
expect(onMediaPost.status).toBe(403)
} finally {
cleanup()
}
})
it('reads webRuntime.trustedHosts per request, not once at apply', async () => {
const { api, setTrustedHosts, cleanup } = mount([])
try {