Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion worker/src/middleware/security.ts
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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(<accountId>.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)) {
Expand Down
12 changes: 12 additions & 0 deletions worker/src/routes/__tests__/app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down