From f439c8730305c0f9d87d828d5aa00c20c50753ae Mon Sep 17 00:00:00 2001 From: Todos Date: Sun, 18 Oct 2026 10:06:24 +0800 Subject: [PATCH 1/2] feat(worker): allow Cloudflare JS detections via per-request CSP nonce - Replace the static SPA_CSP with spaCsp(nonce) and stamp a fresh nonce onto HTML responses so Bot Fight Mode's injected inline challenge script is no longer blocked by script-src, without loosening to 'unsafe-inline'. - Extract redirectHeaders() so short-link 302s also send Referrer-Policy: no-referrer and HSTS (on https), closing the header gap. - Add security.test.ts covering the nonce, HSTS gating, and redirect headers. HSTS and CORS not echoing in production are left untouched: they stem from the production APP_URL variable/Cloudflare edge, not the code, and are reported with dashboard instructions rather than worked around. Checkpoint: ugmHKE24tXFtLoM_XCxZi --- apps/worker/src/index.ts | 11 ++++- apps/worker/src/lib/security.ts | 19 ++++++-- apps/worker/src/routes/redirect.ts | 43 +++++++++------- apps/worker/test/security.test.ts | 78 ++++++++++++++++++++++++++++++ 4 files changed, 128 insertions(+), 23 deletions(-) create mode 100644 apps/worker/test/security.test.ts diff --git a/apps/worker/src/index.ts b/apps/worker/src/index.ts index 9ced1c2..eedf0ec 100644 --- a/apps/worker/src/index.ts +++ b/apps/worker/src/index.ts @@ -3,7 +3,7 @@ import { cors } from 'hono/cors'; import { tbl } from './lib/db.js'; import { apiError } from './lib/errors.js'; import { getCachedSetting, setCachedSetting } from './lib/kv.js'; -import { API_CSP, SPA_CSP, securityHeaders } from './lib/security.js'; +import { API_CSP, securityHeaders, spaCsp } from './lib/security.js'; import { RESERVED_SLUGS } from './lib/slug.js'; import adminRoutes from './routes/admin.js'; import analyticsRoutes from './routes/analytics.js'; @@ -148,8 +148,15 @@ app.all('*', async (c) => { // BE-S11: the /api/* middleware above does not cover SPA/static responses, so // attach security headers (including a Vite-compatible CSP) here. const headers = new Headers(res.headers); + // BE-S13: give HTML responses a fresh nonce so Cloudflare's JavaScript + // Detections (Bot Fight Mode) can stamp it onto the inline challenge script it + // injects, instead of being blocked by script-src. Static assets get no nonce + // (meaningless there), so the CSP stays unchanged for them. + const nonce = (headers.get('content-type') ?? '').includes('text/html') + ? crypto.randomUUID() + : undefined; for (const [k, v] of Object.entries( - securityHeaders(c.env.APP_URL, SPA_CSP), + securityHeaders(c.env.APP_URL, spaCsp(nonce)), )) { headers.set(k, v); } diff --git a/apps/worker/src/lib/security.ts b/apps/worker/src/lib/security.ts index 6ed5005..f4122b0 100644 --- a/apps/worker/src/lib/security.ts +++ b/apps/worker/src/lib/security.ts @@ -4,6 +4,9 @@ export const API_CSP = "default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'self'"; +// HSTS policy applied to HTTPS responses (API, SPA, and short-link redirects). +export const HSTS = 'max-age=63072000; includeSubDomains'; + // CSP for the Vite-built SPA. Kept deliberately permissive where the build // requires it: // - script-src 'unsafe-eval': recharts (via decimal.js) and qrcode call @@ -11,8 +14,17 @@ export const API_CSP = // pages (verified by grepping dist/assets/*.js). // - style-src 'unsafe-inline': React/recharts set inline style attributes. // - img-src data:: the TOTP QR code is rendered from a data: URL. -export const SPA_CSP = - "default-src 'self'; script-src 'self' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'"; +// +// `nonce`, when provided, is appended to script-src so Cloudflare's JavaScript +// Detections (Bot Fight Mode) can inject its inline challenge snippet. Cloudflare +// parses the nonce out of this CSP response header and stamps it onto the inline +// script it injects, which keeps bot detection working without loosening +// script-src to 'unsafe-inline'. The SPA itself ships only external module +// scripts (Vite output), so it needs no nonce in its own markup. +export function spaCsp(nonce?: string): string { + const nonceDirective = nonce ? ` 'nonce-${nonce}'` : ''; + return `default-src 'self'; script-src 'self' 'unsafe-eval'${nonceDirective}; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'`; +} export function securityHeaders( appUrl: string, @@ -25,8 +37,7 @@ export function securityHeaders( 'Content-Security-Policy': csp, }; if (appUrl.startsWith('https')) { - headers['Strict-Transport-Security'] = - 'max-age=63072000; includeSubDomains'; + headers['Strict-Transport-Security'] = HSTS; } return headers; } diff --git a/apps/worker/src/routes/redirect.ts b/apps/worker/src/routes/redirect.ts index 007291f..34902f4 100644 --- a/apps/worker/src/routes/redirect.ts +++ b/apps/worker/src/routes/redirect.ts @@ -1,11 +1,33 @@ import { Hono } from 'hono'; import { tbl } from '../lib/db.js'; import { getCachedLink, setCachedLink } from '../lib/kv.js'; +import { HSTS } from '../lib/security.js'; import { parseUA } from '../lib/ua.js'; import type { CachedLink, Env, LinkRow, Variables } from '../types.js'; const redirect = new Hono<{ Bindings: Env; Variables: Variables }>(); +// BE-S13: redirect responses carry the minimal security headers that matter on +// a 302. CSP / X-Content-Type-Options / X-Frame-Options are skipped — the body +// is empty so there is nothing to sniff, script, or frame. Referrer-Policy: +// no-referrer stops the short-link origin leaking as the Referer to the +// destination; HSTS (on https) hardens first-visit downgrade, complementing +// Cloudflare's Always Use HTTPS. +function redirectHeaders( + appUrl: string, + location: string, +): Record { + const headers: Record = { + Location: location, + 'Cache-Control': 'no-store', + 'Referrer-Policy': 'no-referrer', + }; + if (appUrl.startsWith('https')) { + headers['Strict-Transport-Security'] = HSTS; + } + return headers; +} + redirect.get('/:slug', async (c) => { const slug = c.req.param('slug'); @@ -25,10 +47,7 @@ redirect.get('/:slug', async (c) => { if (!row) { return new Response(null, { status: 302, - headers: { - Location: `${c.env.APP_URL}/404`, - 'Cache-Control': 'no-store', - }, + headers: redirectHeaders(c.env.APP_URL, `${c.env.APP_URL}/404`), }); } @@ -50,20 +69,14 @@ redirect.get('/:slug', async (c) => { if (!linkData.isActive) { return new Response(null, { status: 302, - headers: { - Location: `${c.env.APP_URL}/404`, - 'Cache-Control': 'no-store', - }, + headers: redirectHeaders(c.env.APP_URL, `${c.env.APP_URL}/404`), }); } if (linkData.expiresAt !== null && linkData.expiresAt <= now) { return new Response(null, { status: 302, - headers: { - Location: `${c.env.APP_URL}/404`, - 'Cache-Control': 'no-store', - }, + headers: redirectHeaders(c.env.APP_URL, `${c.env.APP_URL}/404`), }); } @@ -96,11 +109,7 @@ redirect.get('/:slug', async (c) => { // ── 5. Redirect ──────────────────────────────────────────────────────────── return new Response(null, { status: 302, - headers: { - Location: linkData.url, - 'Cache-Control': 'no-store', - 'Referrer-Policy': 'no-referrer', - }, + headers: redirectHeaders(c.env.APP_URL, linkData.url), }); }); diff --git a/apps/worker/test/security.test.ts b/apps/worker/test/security.test.ts new file mode 100644 index 0000000..f738478 --- /dev/null +++ b/apps/worker/test/security.test.ts @@ -0,0 +1,78 @@ +// Security-header tests: HSTS gating on the APP_URL scheme, the SPA CSP nonce +// used to let Cloudflare's JavaScript Detections (Bot Fight Mode) run, and the +// minimal security headers on short-link redirects. +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { app } from '../src/index.ts'; +import { API_CSP, HSTS, securityHeaders, spaCsp } from '../src/lib/security.ts'; +import redirect from '../src/routes/redirect.ts'; +import { makeEnv, request } from './helpers/app.ts'; + +test('spaCsp 无 nonce 时不含 nonce 指令', () => { + const csp = spaCsp(); + assert.match(csp, /script-src 'self' 'unsafe-eval'/); + assert.doesNotMatch(csp, /nonce-/); +}); + +test('spaCsp 带 nonce 时在 script-src 追加 nonce 指令', () => { + const csp = spaCsp('abc123'); + assert.match(csp, /script-src 'self' 'unsafe-eval' 'nonce-abc123'/); +}); + +test('securityHeaders 在 https APP_URL 下附带 HSTS', () => { + const headers = securityHeaders('https://example.com', API_CSP); + assert.equal(headers['Strict-Transport-Security'], HSTS); +}); + +test('securityHeaders 在 http APP_URL 下不附带 HSTS', () => { + const headers = securityHeaders('http://localhost:8787', API_CSP); + assert.equal(headers['Strict-Transport-Security'], undefined); +}); + +test('SPA HTML 响应携带带 nonce 的 CSP(供 Cloudflare JS detections 使用)', async () => { + const ctx = makeEnv({ + ASSETS: { + fetch: async () => + new Response('', { + headers: { 'content-type': 'text/html; charset=utf-8' }, + }), + }, + }); + const res = await request(app, '/login', { method: 'GET' }, ctx); + assert.equal(res.status, 200); + const csp = res.headers.get('content-security-policy') ?? ''; + assert.match(csp, /script-src 'self' 'unsafe-eval' 'nonce-/); +}); + +test('静态资源响应不附带 nonce 的 CSP', async () => { + const ctx = makeEnv({ + ASSETS: { + fetch: async () => + new Response('export default {};', { + headers: { 'content-type': 'text/javascript' }, + }), + }, + }); + const res = await request(app, '/assets/app.js', { method: 'GET' }, ctx); + assert.equal(res.status, 200); + const csp = res.headers.get('content-security-policy') ?? ''; + assert.match(csp, /script-src 'self' 'unsafe-eval'/); + assert.doesNotMatch(csp, /nonce-/); +}); + +test('短链 302 响应附带 HSTS 与 no-referrer(https APP_URL)', async () => { + const ctx = makeEnv(); + const res = await request(redirect, '/missing', { method: 'GET' }, ctx); + assert.equal(res.status, 302); + assert.equal(res.headers.get('Strict-Transport-Security'), HSTS); + assert.equal(res.headers.get('Referrer-Policy'), 'no-referrer'); +}); + +test('短链 302 响应在 http APP_URL 下不附带 HSTS', async () => { + const ctx = makeEnv({ APP_URL: 'http://localhost:8787' }); + const res = await request(redirect, '/missing', { method: 'GET' }, ctx); + assert.equal(res.status, 302); + assert.equal(res.headers.get('Strict-Transport-Security'), null); + assert.equal(res.headers.get('Location'), 'http://localhost:8787/404'); + assert.equal(res.headers.get('Referrer-Policy'), 'no-referrer'); +}); From f37144d7e886abbec7c7f04c765d5e9e73966256 Mon Sep 17 00:00:00 2001 From: Todos Date: Sun, 18 Oct 2026 10:48:36 +0800 Subject: [PATCH 2/2] feat(worker): allow Cloudflare JS detections via per-request CSP nonce - Replace the static SPA_CSP with spaCsp(nonce) and stamp a fresh nonce onto HTML responses so Bot Fight Mode's injected inline challenge script is no longer blocked by script-src, without loosening to 'unsafe-inline'. - Normalize APP_URL with .trim() in securityHeaders, CORS, and redirectHeaders so leading/trailing whitespace can't silently suppress HSTS or CORS echoing. - Extract redirectHeaders() so short-link 302s also send Referrer-Policy: no-referrer and HSTS (on https). - Add security.test.ts covering nonce uniqueness, HSTS gating/trim, CORS echo, and redirect headers. Checkpoint: YgqPChNPtOvsC137HUU9b --- apps/worker/src/index.ts | 5 ++- apps/worker/src/lib/security.ts | 5 ++- apps/worker/src/routes/redirect.ts | 4 +- apps/worker/test/security.test.ts | 59 ++++++++++++++++++++++++++++++ 4 files changed, 70 insertions(+), 3 deletions(-) diff --git a/apps/worker/src/index.ts b/apps/worker/src/index.ts index eedf0ec..66e0ecf 100644 --- a/apps/worker/src/index.ts +++ b/apps/worker/src/index.ts @@ -50,7 +50,10 @@ app.use('/api/*', async (c, next) => { app.use('/api/*', async (c, next) => { const handler = cors({ origin: (origin) => { - const allowed = [c.env.APP_URL]; + // Trim APP_URL so a stray leading/trailing space in the variable doesn't + // make the allowed-origin list miss every real Origin (which is also why + // HSTS went missing in production). + const allowed = [c.env.APP_URL.trim()]; // BE-S10: allow the Vite dev-server origins only when the Worker is reached // over plain http on a loopback host (i.e. wrangler dev). A deployed Worker // is served from a real hostname, so neither condition holds in production. diff --git a/apps/worker/src/lib/security.ts b/apps/worker/src/lib/security.ts index f4122b0..78a12f1 100644 --- a/apps/worker/src/lib/security.ts +++ b/apps/worker/src/lib/security.ts @@ -36,7 +36,10 @@ export function securityHeaders( 'Referrer-Policy': 'strict-origin-when-cross-origin', 'Content-Security-Policy': csp, }; - if (appUrl.startsWith('https')) { + // Normalize APP_URL before checking its scheme: a stray leading/trailing space + // would otherwise silently suppress HSTS (and break CORS origin matching) even + // though the variable is "correct" apart from the whitespace. + if (appUrl.trim().startsWith('https')) { headers['Strict-Transport-Security'] = HSTS; } return headers; diff --git a/apps/worker/src/routes/redirect.ts b/apps/worker/src/routes/redirect.ts index 34902f4..0f8d086 100644 --- a/apps/worker/src/routes/redirect.ts +++ b/apps/worker/src/routes/redirect.ts @@ -22,7 +22,9 @@ function redirectHeaders( 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer', }; - if (appUrl.startsWith('https')) { + // Same APP_URL normalization as securityHeaders/CORS: a leading/trailing + // space must not silently suppress HSTS here either. + if (appUrl.trim().startsWith('https')) { headers['Strict-Transport-Security'] = HSTS; } return headers; diff --git a/apps/worker/test/security.test.ts b/apps/worker/test/security.test.ts index f738478..27d065e 100644 --- a/apps/worker/test/security.test.ts +++ b/apps/worker/test/security.test.ts @@ -29,6 +29,11 @@ test('securityHeaders 在 http APP_URL 下不附带 HSTS', () => { assert.equal(headers['Strict-Transport-Security'], undefined); }); +test('securityHeaders 对带前导/尾随空格的 https APP_URL 归一化后仍发 HSTS', () => { + const headers = securityHeaders(' https://go.example.com ', API_CSP); + assert.equal(headers['Strict-Transport-Security'], HSTS); +}); + test('SPA HTML 响应携带带 nonce 的 CSP(供 Cloudflare JS detections 使用)', async () => { const ctx = makeEnv({ ASSETS: { @@ -44,6 +49,60 @@ test('SPA HTML 响应携带带 nonce 的 CSP(供 Cloudflare JS detections 使 assert.match(csp, /script-src 'self' 'unsafe-eval' 'nonce-/); }); +test('连续两次 SPA HTML 请求的 nonce 互不相同', async () => { + const ctx = makeEnv({ + ASSETS: { + fetch: async () => + new Response('', { + headers: { 'content-type': 'text/html; charset=utf-8' }, + }), + }, + }); + const csp1 = + (await request(app, '/login', { method: 'GET' }, ctx)).headers.get( + 'content-security-policy', + ) ?? ''; + const csp2 = + (await request(app, '/login', { method: 'GET' }, ctx)).headers.get( + 'content-security-policy', + ) ?? ''; + const nonce1 = csp1.match(/nonce-([\w-]+)/)?.[1]; + const nonce2 = csp2.match(/nonce-([\w-]+)/)?.[1]; + assert.ok(nonce1, '第一次请求应带 nonce'); + assert.ok(nonce2, '第二次请求应带 nonce'); + assert.notEqual(nonce1, nonce2); +}); + +test('API 响应(/api/health)CSP 不包含 nonce', async () => { + const ctx = makeEnv(); + const res = await request(app, '/api/health', { method: 'GET' }, ctx); + assert.equal(res.status, 200); + const csp = res.headers.get('content-security-policy') ?? ''; + assert.equal(csp, API_CSP); + assert.doesNotMatch(csp, /nonce-/); +}); + +test('APP_URL 带前导空格时 CORS 仍回显匹配的 Origin', async () => { + const ctx = makeEnv({ APP_URL: ' https://example.com' }); + const res = await request( + app, + '/api/config', + { + method: 'OPTIONS', + headers: { + Origin: 'https://example.com', + 'Access-Control-Request-Method': 'GET', + }, + }, + ctx, + ); + assert.equal(res.status, 204); + assert.equal( + res.headers.get('Access-Control-Allow-Origin'), + 'https://example.com', + ); +}); + test('静态资源响应不附带 nonce 的 CSP', async () => { const ctx = makeEnv({ ASSETS: {