diff --git a/worker/src/middleware/security.ts b/worker/src/middleware/security.ts index 57cd216..9a0be27 100644 --- a/worker/src/middleware/security.ts +++ b/worker/src/middleware/security.ts @@ -1,6 +1,7 @@ import type { MiddlewareHandler } from 'hono' import type { Env, Variables } from '../types' import { SPARK_WORKER_MOUNT } from '../lib/spark-worker-link' +import { r2Host } from '../lib/r2-presign' // Secure whenever the app is configured for HTTPS *or* this request actually arrived over HTTPS, // so a mistyped http:// APP_URL behind TLS cannot strip the refresh cookie's Secure flag or HSTS. @@ -25,9 +26,14 @@ export const securityHeaders: MiddlewareHandler<{ Bindings: Env; Variables: Vari ) } else { c.header('X-Frame-Options', 'DENY') + // R2 直传/直拉(预签名 PUT/GET)是浏览器直连,SPA 的 connect-src 必须放行精确的账号级 + // R2 host(.r2.cloudflarestorage.com)。最小权限:不用 *.r2.cloudflarestorage.com + // 通配;R2 未配置时保持 'self',与上传接口在该状态下 fail-closed 返回 503 的行为一致。 + const r2 = r2Host(c.env) + const r2Source = r2 ? ` https://${r2}` : '' c.header( 'Content-Security-Policy', - "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'; object-src 'none'" + `default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:; connect-src 'self'${r2Source}; frame-ancestors 'none'; base-uri 'self'; form-action 'self'; object-src 'none'` ) } if (isSecure(c)) { diff --git a/worker/src/routes/__tests__/app.test.ts b/worker/src/routes/__tests__/app.test.ts index 8b4c7da..3f92f29 100644 --- a/worker/src/routes/__tests__/app.test.ts +++ b/worker/src/routes/__tests__/app.test.ts @@ -90,6 +90,18 @@ describe('security headers', () => { expect(csp).toContain("base-uri 'self'") expect(csp).toContain("form-action 'self'") }) + + it('allows the exact R2 account host in the SPA connect-src for browser uploads', async () => { + const res = await callWorker(fakeEnv({ CF_ACCOUNT_ID: '0123456789abcdef0123456789abcdef' }), '/query') + const csp = res.headers.get('Content-Security-Policy') ?? '' + expect(csp).toContain("connect-src 'self' https://0123456789abcdef0123456789abcdef.r2.cloudflarestorage.com") + }) + + it('keeps connect-src to self when R2 is unconfigured', async () => { + const res = await callWorker(fakeEnv({ CF_ACCOUNT_ID: 'CF_ACCOUNT_ID_PLACEHOLDER' }), '/query') + const csp = res.headers.get('Content-Security-Policy') ?? '' + expect(csp).toContain("connect-src 'self';") + }) }) describe('request body limit', () => {