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
16 changes: 13 additions & 3 deletions apps/worker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -148,8 +151,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);
}
Expand Down
24 changes: 19 additions & 5 deletions apps/worker/src/lib/security.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,27 @@
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
// `Function("return this")()` at module init, so omitting it breaks those
// 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,
Expand All @@ -24,9 +36,11 @@ export function securityHeaders(
'Referrer-Policy': 'strict-origin-when-cross-origin',
'Content-Security-Policy': csp,
};
if (appUrl.startsWith('https')) {
headers['Strict-Transport-Security'] =
'max-age=63072000; includeSubDomains';
// 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;
}
45 changes: 28 additions & 17 deletions apps/worker/src/routes/redirect.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,35 @@
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<string, string> {
const headers: Record<string, string> = {
Location: location,
'Cache-Control': 'no-store',
'Referrer-Policy': 'no-referrer',
};
// 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;
}

redirect.get('/:slug', async (c) => {
const slug = c.req.param('slug');

Expand All @@ -25,10 +49,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`),
});
}

Expand All @@ -50,20 +71,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`),
});
}

Expand Down Expand Up @@ -96,11 +111,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),
});
});

Expand Down
137 changes: 137 additions & 0 deletions apps/worker/test/security.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
// 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('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: {
fetch: async () =>
new Response('<!doctype html><html><body></body></html>', {
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('连续两次 SPA HTML 请求的 nonce 互不相同', async () => {
const ctx = makeEnv({
ASSETS: {
fetch: async () =>
new Response('<!doctype html><html><body></body></html>', {
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: {
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');
});
Loading