diff --git a/CLAUDE.md b/CLAUDE.md index b161c59..271b8cb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -91,7 +91,7 @@ shortlink/ │ │ │ │ ├── analytics.ts # Per-link and summary click analytics (D1 batch queries) │ │ │ │ ├── admin.ts # Admin: user mgmt, link mgmt, settings │ │ │ │ ├── redirect.ts # /:slug redirect + async click logging -│ │ │ │ └── setup.ts # /setup/:secret — HTTP-triggered DB migration (schema_v1) +│ │ │ │ └── setup.ts # POST /setup — HTTP-triggered DB migration (schema_v1 + schema_v2) │ │ │ ├── middleware/ │ │ │ │ └── auth.ts # requireAuth and requireAdmin middleware (JWT verification) │ │ │ └── lib/ @@ -161,7 +161,11 @@ Stored AES-256-GCM encrypted in D1. The encryption key (`TOTP_ENCRYPTION_KEY`) i | `link:{slug}` | Short link cache | 21600s (6h) | | `passkey_challenge:{id}` | WebAuthn challenge | 300s | | `otp_rate:{email}` | Email OTP rate limit (also used by forgot-password) | 600s | -| `login_attempts:{email}` | Login brute-force rate limit | 900s | +| `login_attempts:{email}` | Login brute-force rate limit (email dimension) | 900s | +| `login_attempts_ip:{ip}` | Login brute-force rate limit (IP dimension) | 900s | +| `register_rate:{ip}` | Registration rate limit (IP) | 3600s | +| `forgot_pw_rate:{ip}` | Forgot-password rate limit (IP) | 3600s | +| `setup_rate:{ip}` | Setup/migration endpoint rate limit (IP) | 900s | | `2fa_attempts:{jti}` | General 2FA attempt counter | 600s | | `passkey_opts:{jti}` | Passkey options attempt counter | 600s | | `totp_confirm:{userId}` | TOTP setup confirm attempt counter | 120s | @@ -233,12 +237,14 @@ Email sender config and API keys are managed in the **admin UI settings**, not h There are two migration paths: **`wrangler d1 migrations apply` (local dev):** -One file in `apps/worker/migrations/`: +Two files in `apps/worker/migrations/`: - `0001_init.sql` — canonical schema: all tables (users, passkeys, links, click_logs, verifications, settings, audit_logs, totp_used) + default settings rows +- `0002_token_version.sql` — adds `users.token_version` for session revocation **HTTP setup route (production):** -`GET /setup/:secret` runs migrations embedded in `routes/setup.ts`. Currently one migration: +`POST /setup` with `X-Setup-Secret` header runs migrations embedded in `routes/setup.ts`. Two migrations: - `schema_v1` — identical DDL as `0001_init.sql`, but parameterized by `TABLE_PREFIX` and tracked in `_schema_migrations` table +- `schema_v2` — adds `token_version` to `users` (mirrors `0002_token_version.sql`) Re-visiting the setup URL is safe — already-applied migrations return `"skipped"`. @@ -251,14 +257,17 @@ Re-visiting the setup URL is safe — already-applied migrations return `"skippe - Passkey registration capped at 10 per user - Forgot-password endpoint never reveals whether an email exists (always returns success) - Password reset codes: max 3 wrong attempts per code; rate-limited 3 sends per 10 min per email -- Login brute-force limited to 10 attempts per 15-minute window per email (`login_attempts:{email}` KV) +- Login brute-force limited to 10 attempts per 15-minute window per email, plus 20 per IP (`login_attempts:{email}` + `login_attempts_ip:{ip}` KV) +- Registration and forgot-password additionally rate-limited per IP (`register_rate:{ip}`, `forgot_pw_rate:{ip}`) +- Setup/migration endpoint rate-limited per IP (`setup_rate:{ip}`); secret passed via header and compared in constant time - `cf-connecting-ip` used for IP logging (cannot be forged); `x-forwarded-for` ignored - User-Agent and Referer headers truncated before storage (512 and 2048 bytes respectively) - `app_name` setting validated: 1–64 chars, no HTML-special or CR/LF characters - LIKE queries escape `%`, `_`, `\` metacharacters - `expiresAt` validated with `Number.isSafeInteger()` to reject NaN/Infinity - SMTP settings (`smtp_host`, `smtp_user`, `smtp_pass`, `smtp_from`) are validated against CR/LF injection; `smtp_from` validated as a valid email address; `smtp_port` validated as integer 1–65535 -- SMTP passwords are stored in plain text in D1 — for production deployments where this is a concern, use Resend with a Worker secret instead +- SMTP STARTTLS failure aborts the send (never falls back to plaintext); SMTP I/O and Resend fetch both carry 10s timeouts +- SMTP passwords are stored in plain text in D1 (but masked in audit logs and never returned by the settings API) — for production deployments where this is a concern, use Resend with a Worker secret instead --- diff --git a/README.md b/README.md index 4253ce3..428c9c0 100644 --- a/README.md +++ b/README.md @@ -94,10 +94,12 @@ This will deploy the code to Cloudflare Workers. ### 6. Run database migrations -After deploying, visit this URL once in your browser (or with `curl`): +After deploying, trigger the migrations once via a `POST` request with the setup +secret in a header (it is no longer accepted in the URL): ``` -https://your-worker.workers.dev/setup/ +curl -X POST https://your-worker.workers.dev/setup \ + -H "X-Setup-Secret: " ``` Response on success: diff --git a/README.zh-CN.md b/README.zh-CN.md index 78c4c95..cf3fd8b 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -97,10 +97,11 @@ ### 6. 运行数据库迁移 -部署后,在浏览器中访问以下 URL 一次(或使用 `curl`): +部署后,通过 `POST` 请求触发迁移一次,密钥放在请求头中(不再通过 URL 传递): ``` -https://your-worker.workers.dev/setup/ +curl -X POST https://your-worker.workers.dev/setup \ + -H "X-Setup-Secret: " ``` 成功响应: diff --git a/apps/web/src/api/client.ts b/apps/web/src/api/client.ts index dd40a75..8ab74cc 100644 --- a/apps/web/src/api/client.ts +++ b/apps/web/src/api/client.ts @@ -75,11 +75,26 @@ async function request( // S3: In-flight dedup prevents multiple concurrent 401s from each triggering a refresh call. // With refresh token rotation, only the first call succeeds; others would see a revoked // token and force the user back to login unexpectedly. +// FE-S1: The dedup is additionally serialized across tabs via the Web Locks API, so +// sibling tabs refreshing from the same cookie wait for each other instead of +// rotating the refresh token out from under one another. let refreshPromise: Promise | null = null; +function withRefreshLock(fn: () => Promise): Promise { + const locks = typeof navigator !== 'undefined' ? navigator.locks : undefined; + if (locks?.request) { + return locks.request( + 'auth-refresh', + { mode: 'exclusive' }, + fn, + ) as Promise; + } + return fn(); +} + async function tryRefresh(): Promise { if (refreshPromise) return refreshPromise; - refreshPromise = _doRefresh().finally(() => { + refreshPromise = withRefreshLock(_doRefresh).finally(() => { refreshPromise = null; }); return refreshPromise; @@ -101,6 +116,14 @@ async function _doRefresh(): Promise { } } +// Serialized silent refresh for the BroadcastChannel 'refresh' handler and the +// initial session restore — returns the new access token, or null when there is +// no valid session. +export async function refreshSession(): Promise { + const ok = await tryRefresh(); + return ok ? getAccessToken() : null; +} + // ─── Auth API ───────────────────────────────────────────────────────────────── export interface User { diff --git a/apps/web/src/components/link-table-cells.tsx b/apps/web/src/components/link-table-cells.tsx index 5cd2035..ef874d3 100644 --- a/apps/web/src/components/link-table-cells.tsx +++ b/apps/web/src/components/link-table-cells.tsx @@ -10,6 +10,7 @@ import { copyToClipboard, expiryLabel, isExpired, + isSafeUrl, } from '@/lib/utils'; export function LinkSlugCell({ slug }: { slug: string }) { @@ -34,18 +35,21 @@ export function LinkSlugCell({ slug }: { slug: string }) { } export function LinkDestinationCell({ url }: { url: string }) { + // FE-S2: Only render the URL as a clickable link when its protocol is http/https. return (
{url} - - - + {isSafeUrl(url) && ( + + + + )}
); diff --git a/apps/web/src/contexts/AuthContext.tsx b/apps/web/src/contexts/AuthContext.tsx index 83dde95..682bb45 100644 --- a/apps/web/src/contexts/AuthContext.tsx +++ b/apps/web/src/contexts/AuthContext.tsx @@ -10,6 +10,7 @@ import { import { authApi, type LoginResult, + refreshSession, setAccessToken, type User, } from '../api/client.ts'; @@ -21,7 +22,7 @@ interface AuthContextType { pendingMethods: string[]; login: (email: string, password: string) => Promise; logout: () => Promise; - broadcastLogin: (accessToken: string) => void; + broadcastRefresh: () => void; setPendingState: (token: string, methods: string[]) => void; clearPendingState: () => void; refreshUser: () => Promise; @@ -29,14 +30,18 @@ interface AuthContextType { const AuthContext = createContext(null); -type ChannelMsg = { type: 'token'; accessToken: string } | { type: 'logout' }; +// FE-S1: The channel carries only a signal, never a token. Any same-origin script +// (XSS, malicious extension) could listen on BroadcastChannel and steal a token +// sent through it, so tokens stay out — each tab fetches its own via the HttpOnly +// refresh cookie. +type ChannelMsg = { type: 'refresh' } | { type: 'logout' }; export function AuthProvider({ children }: { children: React.ReactNode }) { const [user, setUser] = useState(null); const [isLoading, setIsLoading] = useState(true); const [pendingToken, setPendingToken] = useState(null); const [pendingMethods, setPendingMethods] = useState([]); - // H-1: BroadcastChannel for cross-tab token/logout coordination + // H-1: BroadcastChannel for cross-tab login/logout coordination (signal only) const channelRef = useRef(null); const refreshUser = useCallback(async () => { @@ -58,12 +63,19 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { channelRef.current = channel; channel?.addEventListener('message', (e: MessageEvent) => { - if (e.data?.type === 'token') { - // Another tab refreshed — adopt the new token and fetch the user - setAccessToken(e.data.accessToken); - authApi - .me() - .then((d) => setUser(d.user)) + if (e.data?.type === 'refresh') { + // Another tab logged in — obtain our own token via the HttpOnly refresh + // cookie instead of receiving one over the channel. Serialized across + // tabs (Web Locks) so concurrent refreshes don't rotate each other out. + refreshSession() + .then((token) => { + if (!token) return; + setAccessToken(token); + return authApi.me(); + }) + .then((d) => { + if (d) setUser(d.user); + }) .catch(() => {}); } else if (e.data?.type === 'logout') { // Another tab logged out — mirror the logout in this tab @@ -74,13 +86,9 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { const init = async () => { try { - const data = await authApi.refresh(); - setAccessToken(data.accessToken); - // Broadcast so sibling tabs avoid their own refresh round-trip - channel?.postMessage({ - type: 'token', - accessToken: data.accessToken, - } satisfies ChannelMsg); + const token = await refreshSession(); + if (!token) return; + setAccessToken(token); await refreshUser(); } catch { // No valid session — user needs to log in @@ -104,8 +112,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { // H4: refresh token is set as HttpOnly cookie by the server — no localStorage setUser(result.user); channelRef.current?.postMessage({ - type: 'token', - accessToken: result.accessToken, + type: 'refresh', } satisfies ChannelMsg); } return result; @@ -125,11 +132,8 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { channelRef.current?.postMessage({ type: 'logout' } satisfies ChannelMsg); }, []); - const broadcastLogin = useCallback((accessToken: string) => { - channelRef.current?.postMessage({ - type: 'token', - accessToken, - } satisfies ChannelMsg); + const broadcastRefresh = useCallback(() => { + channelRef.current?.postMessage({ type: 'refresh' } satisfies ChannelMsg); }, []); const setPendingState = useCallback((token: string, methods: string[]) => { @@ -151,7 +155,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { pendingMethods, login, logout, - broadcastLogin, + broadcastRefresh, setPendingState, clearPendingState, refreshUser, diff --git a/apps/web/src/lib/utils.ts b/apps/web/src/lib/utils.ts index 8141f85..a0d23db 100644 --- a/apps/web/src/lib/utils.ts +++ b/apps/web/src/lib/utils.ts @@ -40,6 +40,18 @@ export function copyToClipboard(text: string): Promise { return navigator.clipboard.writeText(text); } +// FE-S2: Validate that a URL is safe to render as a clickable . Only +// http/https are allowed — anything else (javascript:, data:, etc.) is rendered +// as plain text to prevent XSS if backend validation is ever bypassed. +export function isSafeUrl(url: string): boolean { + try { + const parsed = new URL(url); + return parsed.protocol === 'http:' || parsed.protocol === 'https:'; + } catch { + return false; + } +} + export function buildShortUrl(slug: string): string { return `${window.location.origin}/${slug}`; } diff --git a/apps/web/src/pages/admin/AdminSettingsPage.tsx b/apps/web/src/pages/admin/AdminSettingsPage.tsx index 8182089..cf6107b 100644 --- a/apps/web/src/pages/admin/AdminSettingsPage.tsx +++ b/apps/web/src/pages/admin/AdminSettingsPage.tsx @@ -45,6 +45,10 @@ export default function AdminSettingsPage() { const [smtpPass, setSmtpPass] = useState(''); const [smtpFrom, setSmtpFrom] = useState(''); const [savingEmail, setSavingEmail] = useState(false); + // FE-S3: Backend masks secrets; track whether one is already configured so the + // UI can show "leave blank to keep" and avoid submitting an empty value. + const [resendKeyIsSet, setResendKeyIsSet] = useState(false); + const [smtpPassIsSet, setSmtpPassIsSet] = useState(false); useEffect(() => { if (data?.settings) { @@ -53,13 +57,17 @@ export default function AdminSettingsPage() { setRequireEmailVerification(s.require_email_verification === 'true'); setAppName(s.app_name ?? 'ShortLink'); setEmailProvider((s.email_provider as 'resend' | 'smtp') ?? 'resend'); - setResendApiKey(s.resend_api_key ?? ''); + // FE-S3: Secrets are masked by the server ("***" when set) — never fill the + // input with them; only remember whether one is configured. + setResendApiKey(''); + setResendKeyIsSet(s.resend_api_key === '***'); setEmailFromDomain(s.email_from_domain ?? ''); setEmailFromName(s.email_from_name ?? ''); setSmtpHost(s.smtp_host ?? ''); setSmtpPort(s.smtp_port ?? '587'); setSmtpUser(s.smtp_user ?? ''); - setSmtpPass(s.smtp_pass ?? ''); + setSmtpPass(''); + setSmtpPassIsSet(s.smtp_pass === '***'); setSmtpFrom(s.smtp_from ?? ''); } }, [data]); @@ -112,17 +120,20 @@ export default function AdminSettingsPage() { e.preventDefault(); setSavingEmail(true); try { - await adminApi.updateSettings({ + // FE-S3: Only submit secret fields when the admin explicitly typed a value; + // empty values leave the existing credential untouched. + const payload: Record = { email_provider: emailProvider, - resend_api_key: resendApiKey, email_from_domain: emailFromDomain, email_from_name: emailFromName, smtp_host: smtpHost, smtp_port: smtpPort, smtp_user: smtpUser, - smtp_pass: smtpPass, smtp_from: smtpFrom, - }); + }; + if (resendApiKey !== '') payload.resend_api_key = resendApiKey; + if (smtpPass !== '') payload.smtp_pass = smtpPass; + await adminApi.updateSettings(payload); toast.success('Email settings saved'); } catch (err) { toast.error(err instanceof Error ? err.message : 'Failed'); @@ -247,10 +258,20 @@ export default function AdminSettingsPage() { id="resend-api-key" value={resendApiKey} onChange={(e) => setResendApiKey(e.target.value)} - placeholder="re_xxxxxxxxxxxx" + placeholder={ + resendKeyIsSet + ? '•••••••• (leave blank to keep)' + : 're_xxxxxxxxxxxx' + } type="password" autoComplete="new-password" /> + {resendKeyIsSet && ( +

+ An API key is configured. Leave blank to keep it + unchanged. +

+ )}

Get your API key from{' '} setSmtpPass(e.target.value)} - placeholder="••••••••" + placeholder={ + smtpPassIsSet + ? '•••••••• (leave blank to keep)' + : '••••••••' + } type="password" autoComplete="new-password" />

- Credentials are stored in the database. + {smtpPassIsSet + ? 'A password is configured. Leave blank to keep it unchanged.' + : 'Credentials are stored in the database.'}

diff --git a/apps/web/src/pages/auth/RegisterPage.tsx b/apps/web/src/pages/auth/RegisterPage.tsx index 1968799..577b84b 100644 --- a/apps/web/src/pages/auth/RegisterPage.tsx +++ b/apps/web/src/pages/auth/RegisterPage.tsx @@ -25,7 +25,7 @@ export default function RegisterPage() { const { t } = useTranslation(); const navigate = useNavigate(); const { registrationEnabled } = useAppConfig(); - const { refreshUser, broadcastLogin } = useAuth(); + const { refreshUser, broadcastRefresh } = useAuth(); const [step, setStep] = useState('form'); const [email, setEmail] = useState(''); const [username, setUsername] = useState(''); @@ -66,7 +66,7 @@ export default function RegisterPage() { const result = await authApi.verifyEmail(userId, code); if (result.accessToken) { setAccessToken(result.accessToken); - broadcastLogin(result.accessToken); + broadcastRefresh(); } await refreshUser(); navigate('/dashboard'); diff --git a/apps/web/src/pages/auth/TwoFactorPage.tsx b/apps/web/src/pages/auth/TwoFactorPage.tsx index 6963884..5b14c64 100644 --- a/apps/web/src/pages/auth/TwoFactorPage.tsx +++ b/apps/web/src/pages/auth/TwoFactorPage.tsx @@ -25,7 +25,7 @@ export default function TwoFactorPage() { pendingMethods, clearPendingState, refreshUser, - broadcastLogin, + broadcastRefresh, } = useAuth(); const { t } = useTranslation(); const navigate = useNavigate(); @@ -44,7 +44,7 @@ export default function TwoFactorPage() { const handleSuccess = (result: LoginResult) => { if (result.accessToken) { setAccessToken(result.accessToken); - broadcastLogin(result.accessToken); + broadcastRefresh(); } clearPendingState(); refreshUser().then(() => navigate('/dashboard')); diff --git a/apps/web/src/pages/dashboard/AnalyticsPage.tsx b/apps/web/src/pages/dashboard/AnalyticsPage.tsx index d4aaada..faf740d 100644 --- a/apps/web/src/pages/dashboard/AnalyticsPage.tsx +++ b/apps/web/src/pages/dashboard/AnalyticsPage.tsx @@ -19,6 +19,7 @@ import { Button } from '@/components/ui/button'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Input } from '@/components/ui/input'; import { useTranslation } from '@/i18n'; +import { isSafeUrl } from '@/lib/utils'; const COLORS = [ '#6366f1', @@ -165,14 +166,19 @@ export default function AnalyticsPage() { {selectedLinkData.link.slug} {' → '} - - {selectedLinkData.link.destination_url} - + {/* FE-S2: Only render as a link when the protocol is http/https */} + {isSafeUrl(selectedLinkData.link.destination_url) ? ( + + {selectedLinkData.link.destination_url} + + ) : ( + {selectedLinkData.link.destination_url} + )} )} diff --git a/apps/worker/migrations/0002_token_version.sql b/apps/worker/migrations/0002_token_version.sql new file mode 100644 index 0000000..607355b --- /dev/null +++ b/apps/worker/migrations/0002_token_version.sql @@ -0,0 +1,5 @@ +-- BE-S3/S4: per-user token_version — bumping it revokes all of a user's sessions +-- (password change/reset, admin disable/demote). Keep in sync with the `schema_v2` +-- migration embedded in routes/setup.ts. + +ALTER TABLE users ADD COLUMN token_version INTEGER NOT NULL DEFAULT 0; diff --git a/apps/worker/src/lib/crypto.ts b/apps/worker/src/lib/crypto.ts index 208d242..034ecd2 100644 --- a/apps/worker/src/lib/crypto.ts +++ b/apps/worker/src/lib/crypto.ts @@ -92,6 +92,20 @@ export async function sha256(data: string): Promise { .join(''); } +// Constant-time string comparison — for secrets whose value must not leak +// through timing (e.g. the setup secret in a header). Always loops over the +// longer of the two inputs so the duration does not depend on the inputs. +export function constantTimeEqual(a: string, b: string): boolean { + const aBytes = new TextEncoder().encode(a); + const bBytes = new TextEncoder().encode(b); + let diff = aBytes.length ^ bBytes.length; + const len = Math.max(aBytes.length, bBytes.length); + for (let i = 0; i < len; i++) { + diff |= (aBytes[i] ?? 0) ^ (bBytes[i] ?? 0); + } + return diff === 0; +} + // AES-256-GCM encrypt (for TOTP secrets) // S-3: Cache the imported CryptoKey per keyHex to avoid paying importKey overhead on every call. // Workers isolate memory per-request in some configurations, but within a single request diff --git a/apps/worker/src/lib/email.ts b/apps/worker/src/lib/email.ts index 908b5d5..7952e29 100644 --- a/apps/worker/src/lib/email.ts +++ b/apps/worker/src/lib/email.ts @@ -69,6 +69,8 @@ export async function sendEmail( ); } + // BE-R1: Abort the fetch if Resend doesn't respond within 10s so registration + // / reset flows don't hang on a stalled upstream. const res = await fetch('https://api.resend.com/emails', { method: 'POST', headers: { @@ -81,6 +83,7 @@ export async function sendEmail( subject: payload.subject, html: payload.html, }), + signal: AbortSignal.timeout(10_000), }); if (!res.ok) { diff --git a/apps/worker/src/lib/jwt.ts b/apps/worker/src/lib/jwt.ts index faf6106..e26cc1f 100644 --- a/apps/worker/src/lib/jwt.ts +++ b/apps/worker/src/lib/jwt.ts @@ -37,10 +37,11 @@ export async function signAccessToken( export async function signRefreshToken( sub: string, + tv: number, secret: string, ): Promise<{ token: string; jti: string }> { const jti = newJti(); - const token = await new SignJWT({ sub, purpose: 'refresh', jti }) + const token = await new SignJWT({ sub, tv, purpose: 'refresh', jti }) .setProtectedHeader({ alg: 'HS256' }) .setExpirationTime(REFRESH_TOKEN_TTL) .setIssuedAt() diff --git a/apps/worker/src/lib/kv.ts b/apps/worker/src/lib/kv.ts index 493c03e..6d47bca 100644 --- a/apps/worker/src/lib/kv.ts +++ b/apps/worker/src/lib/kv.ts @@ -9,6 +9,11 @@ const KV_PREFIX = { settingCache: (key: string) => `setting:${key}`, // C1: Login brute-force limiting loginAttempts: (email: string) => `login_attempts:${email}`, + // BE-S6: Per-IP login/register/forgot-password/setup rate limiting + loginAttemptsIp: (ip: string) => `login_attempts_ip:${ip}`, + registerIp: (ip: string) => `register_rate:${ip}`, + forgotPasswordIp: (ip: string) => `forgot_pw_rate:${ip}`, + setupRate: (ip: string) => `setup_rate:${ip}`, // C2: 2FA verify attempt tracking per pending token (shared by TOTP + email-OTP + passkey/verify) twoFaAttempts: (jti: string) => `2fa_attempts:${jti}`, // R4-L3: Separate counter for passkey/verify-options so challenge-fetch calls don't burn verify budget @@ -148,18 +153,25 @@ export async function deletePending2fa( // the limit before writes settle. A Cloudflare WAF rate-limit rule is the primary // enforcement layer; this provides a defence-in-depth best-effort guard. -export async function checkLoginRateLimit( +// Fixed-window counter. Returns true (allowed) unless the key is already at +// `limit`; records the attempt by incrementing the stored count. +async function fixedWindowIncrement( kv: KVNamespace, - email: string, + key: string, + limit: number, + windowSec: number, ): Promise { - const key = KV_PREFIX.loginAttempts(email); const current = await kv.get(key); const now = Math.floor(Date.now() / 1000); if (!current) { - await kv.put(key, JSON.stringify({ count: 1, windowEnd: now + 900 }), { - expirationTtl: 900, - }); + await kv.put( + key, + JSON.stringify({ count: 1, windowEnd: now + windowSec }), + { + expirationTtl: windowSec, + }, + ); return true; } @@ -167,13 +179,17 @@ export async function checkLoginRateLimit( try { entry = JSON.parse(current); } catch { - await kv.put(key, JSON.stringify({ count: 1, windowEnd: now + 900 }), { - expirationTtl: 900, - }); + await kv.put( + key, + JSON.stringify({ count: 1, windowEnd: now + windowSec }), + { + expirationTtl: windowSec, + }, + ); return true; } - if (entry.count >= 10) return false; + if (entry.count >= limit) return false; const remaining = Math.max(entry.windowEnd - now, 1); await kv.put( key, @@ -183,11 +199,56 @@ export async function checkLoginRateLimit( return true; } +// BE-S6: Rate limit login on two dimensions — email (10/15min) and IP (20/15min). +// Both counters are recorded; a request is blocked if either dimension is over. +export async function checkLoginRateLimit( + kv: KVNamespace, + email: string, + ip: string, +): Promise { + const [emailOk, ipOk] = await Promise.all([ + fixedWindowIncrement(kv, KV_PREFIX.loginAttempts(email), 10, 900), + fixedWindowIncrement(kv, KV_PREFIX.loginAttemptsIp(ip), 20, 900), + ]); + return emailOk && ipOk; +} + export async function resetLoginAttempts( kv: KVNamespace, email: string, + ip: string, ): Promise { - await kv.delete(KV_PREFIX.loginAttempts(email)); + await Promise.all([ + kv.delete(KV_PREFIX.loginAttempts(email)), + kv.delete(KV_PREFIX.loginAttemptsIp(ip)), + ]); +} + +// BE-S6: IP-only rate limit for registration (10/hour) — closes the bulk +// account-creation gap; /register previously had no rate limiting at all. +export async function checkRegisterRateLimit( + kv: KVNamespace, + ip: string, +): Promise { + return fixedWindowIncrement(kv, KV_PREFIX.registerIp(ip), 10, 3600); +} + +// BE-S6: IP dimension for forgot-password (10/hour), complementing the existing +// per-email OTP limit, so an attacker can't mail-bomb arbitrary addresses. +export async function checkForgotPasswordIpRateLimit( + kv: KVNamespace, + ip: string, +): Promise { + return fixedWindowIncrement(kv, KV_PREFIX.forgotPasswordIp(ip), 10, 3600); +} + +// BE-S5: IP rate limit for the setup/migration endpoint (5/15min) — prevents +// online brute-forcing of the setup secret. +export async function checkSetupRateLimit( + kv: KVNamespace, + ip: string, +): Promise { + return fixedWindowIncrement(kv, KV_PREFIX.setupRate(ip), 5, 900); } // ─── 2FA attempt tracking (C2: max 5 per pending token) ────────────────────── diff --git a/apps/worker/src/lib/smtp.ts b/apps/worker/src/lib/smtp.ts index 39b0f18..66bfa76 100644 --- a/apps/worker/src/lib/smtp.ts +++ b/apps/worker/src/lib/smtp.ts @@ -15,6 +15,29 @@ interface SmtpSocket { close: () => Promise; } +// BE-R1: Per-operation read/write timeout so a non-responsive SMTP server can't +// hang the Worker until the platform kills the request. +const SMTP_TIMEOUT_MS = 10_000; + +function withTimeout(promise: Promise, ms: number): Promise { + return new Promise((resolve, reject) => { + const timer = setTimeout( + () => reject(new Error(`SMTP: operation timed out after ${ms}ms`)), + ms, + ); + promise.then( + (v) => { + clearTimeout(timer); + resolve(v); + }, + (e) => { + clearTimeout(timer); + reject(e); + }, + ); + }); +} + // Send an HTML email via a custom SMTP server. // Supports implicit TLS (port 465) and STARTTLS (port 587 / others). export async function sendViaSMTP( @@ -70,12 +93,16 @@ class SmtpSession { } // Send STARTTLS and upgrade the socket to TLS in-place. - // If the server responds with a non-220 code, the connection stays plain - // and we proceed without TLS (some internal relays allow this). + // BE-S2: If the server declines STARTTLS (non-220), abort — never fall back to + // sending credentials (AUTH LOGIN) over a plaintext channel. async tryStartTls(): Promise { await this.cmd('STARTTLS'); const resp = await this.readResponse(); - if (resp.code !== 220) return; // server declined STARTTLS — continue plain + if (resp.code !== 220) { + throw new Error( + `SMTP: server declined STARTTLS (${resp.code} ${resp.message}); refusing to send credentials in plaintext`, + ); + } // Release stream locks before handing the socket to startTls() this.reader.releaseLock(); @@ -133,7 +160,10 @@ class SmtpSession { `${b64Body}\r\n` + `.\r\n`; // end-of-data marker - await this.writer.write(new TextEncoder().encode(message)); + await withTimeout( + this.writer.write(new TextEncoder().encode(message)), + SMTP_TIMEOUT_MS, + ); await this.expect(250); } @@ -142,7 +172,10 @@ class SmtpSession { } async cmd(text: string): Promise { - await this.writer.write(new TextEncoder().encode(`${text}\r\n`)); + await withTimeout( + this.writer.write(new TextEncoder().encode(`${text}\r\n`)), + SMTP_TIMEOUT_MS, + ); } async expect(code: number): Promise { @@ -159,7 +192,10 @@ class SmtpSession { for (;;) { // Buffer until we have at least one complete line while (!this.buf.includes('\r\n')) { - const { value, done } = await this.reader.read(); + const { value, done } = await withTimeout( + this.reader.read(), + SMTP_TIMEOUT_MS, + ); if (done) throw new Error('SMTP: connection closed unexpectedly'); this.buf += this.dec.decode(value); } diff --git a/apps/worker/src/middleware/auth.ts b/apps/worker/src/middleware/auth.ts index a0d6fb8..c88d417 100644 --- a/apps/worker/src/middleware/auth.ts +++ b/apps/worker/src/middleware/auth.ts @@ -1,4 +1,5 @@ import type { Context, Next } from 'hono'; +import { tbl } from '../lib/db.js'; import { verifyAccessToken } from '../lib/jwt.js'; import { isJtiDenylisted } from '../lib/kv.js'; import type { Env, Variables } from '../types.js'; @@ -8,6 +9,10 @@ type AppContext = Context<{ Bindings: Env; Variables: Variables }>; // LOW-1: Shared helper eliminates duplication between requireAuth and requireAdmin. // MED-3: Denylist check happens BEFORE role check so a revoked non-admin token // returns 401 (not 403), preventing leaking the token's privilege level. +// BE-S3/S4: Token is re-validated against the DB on every request. The role is +// taken from the DB (not the JWT claim) and the token_version is compared, +// so password changes/resets and admin disable/demote revoke all existing +// tokens immediately — including access tokens still within their TTL. async function verifyTokenAndSetContext( c: AppContext, ): Promise { @@ -22,8 +27,23 @@ async function verifyTokenAndSetContext( if (await isJtiDenylisted(c.env.LINKS_KV, payload.jti)) { return c.json({ error: 'Unauthorized' }, 401); } + // BE-S3/S4: Confirm the account is still active and its token_version matches. + const user = await c.env.DB.prepare( + `SELECT is_active, role, token_version FROM ${tbl(c.env, 'users')} WHERE id = ?1`, + ) + .bind(payload.sub) + .first<{ + is_active: number; + role: 'admin' | 'user'; + token_version: number; + }>(); + + if (!user?.is_active || user.token_version !== payload.tv) { + return c.json({ error: 'Unauthorized' }, 401); + } + c.set('userId', payload.sub); - c.set('userRole', payload.role); + c.set('userRole', user.role); c.set('userEmail', payload.email); c.set('userJti', payload.jti); c.set('userTokenExp', payload.exp); diff --git a/apps/worker/src/routes/admin.ts b/apps/worker/src/routes/admin.ts index ed0d4b5..9690b88 100644 --- a/apps/worker/src/routes/admin.ts +++ b/apps/worker/src/routes/admin.ts @@ -9,6 +9,23 @@ const admin = new Hono<{ Bindings: Env; Variables: Variables }>(); admin.use('*', requireAdmin); +// BE-S1: Setting keys that hold secrets. They must never be written in plaintext +// to the audit log, nor returned in plaintext by GET /settings. +const SECRET_SETTING_KEYS = new Set(['smtp_pass', 'resend_api_key']); +const SECRET_MASK = '***'; + +function maskSecrets( + settings: Record, +): Record { + const out: Record = {}; + for (const [k, v] of Object.entries(settings)) { + // Only mask configured (non-empty) secrets — an empty value means "not set", + // so it must stay empty rather than read as "***" (= already set) by the UI. + out[k] = SECRET_SETTING_KEYS.has(k) && v !== '' ? SECRET_MASK : v; + } + return out; +} + // ─── Audit log helper (L7) ──────────────────────────────────────────────────── async function auditLog( @@ -214,6 +231,12 @@ admin.patch('/users/:id', async (c) => { sets.push(`role = ?${vals.push(body.role)}`); } + // BE-S4: Deactivating or changing a user's role revokes all of their sessions + // immediately by bumping token_version (checked on every request + refresh). + if (body.isActive === false || body.role !== undefined) { + sets.push('token_version = token_version + 1'); + } + if (sets.length === 1) return c.json({ error: 'Nothing to update' }, 400); vals.push(id); @@ -331,7 +354,9 @@ admin.get('/settings', async (c) => { const settings = Object.fromEntries( rows.results.map((r) => [r.key, r.value]), ); - return c.json({ settings }); + // BE-S1: Never return secret values in plaintext — replace with a mask so the + // admin UI can show "already set" without exposing the credential. + return c.json({ settings: maskSecrets(settings) }); }); // ───────────────────────────────────────────────────────────────────────────── @@ -356,7 +381,15 @@ admin.put('/settings', async (c) => { 'smtp_from', ]); - const updates = Object.entries(body).filter(([k]) => allowedKeys.has(k)); + // FE-S3/BE-S1: An empty or masked ("***") secret means "leave unchanged". + // Never write those back — an empty string would wipe the credential, and a + // "***" literal would be stored as the real password. + const updates = Object.entries(body) + .filter(([k]) => allowedKeys.has(k)) + .filter( + ([k, v]) => + !SECRET_SETTING_KEYS.has(k) || (v !== '' && v !== SECRET_MASK), + ); if (updates.length === 0) return c.json({ error: 'No valid settings keys provided' }, 400); @@ -443,7 +476,8 @@ admin.put('/settings', async (c) => { ); await auditLog(c.env, adminId, 'update_settings', 'settings', { - updates: Object.fromEntries(updates), + // BE-S1: Mask secrets so they never land in the audit log in plaintext. + updates: maskSecrets(Object.fromEntries(updates)), }); return c.json({ success: true }); diff --git a/apps/worker/src/routes/auth.ts b/apps/worker/src/routes/auth.ts index 221721d..f8b9895 100644 --- a/apps/worker/src/routes/auth.ts +++ b/apps/worker/src/routes/auth.ts @@ -21,8 +21,10 @@ import { verifyRefreshToken, } from '../lib/jwt.js'; import { + checkForgotPasswordIpRateLimit, checkLoginRateLimit, checkOtpRateLimit, + checkRegisterRateLimit, deletePending2fa, denylistJti, getAndDeletePasskeyChallenge, @@ -88,13 +90,27 @@ function getRefreshCookie(c: AuthContext): string | null { async function issueTokens(user: UserRow, jwtSecret: string) { const { token: accessToken } = await signAccessToken( - { sub: user.id, role: user.role, email: user.email }, + { + sub: user.id, + role: user.role, + email: user.email, + tv: user.token_version, + }, + jwtSecret, + ); + const { token: refreshToken } = await signRefreshToken( + user.id, + user.token_version, jwtSecret, ); - const { token: refreshToken } = await signRefreshToken(user.id, jwtSecret); return { accessToken, refreshToken }; } +// Client IP from Cloudflare's verified header (cannot be forged by the client). +function clientIp(c: AuthContext): string { + return c.req.header('cf-connecting-ip') ?? 'unknown'; +} + // ─── Helper: get registration enabled ──────────────────────────────────────── async function isRegistrationEnabled(env: Env): Promise { @@ -166,6 +182,15 @@ auth.post('/register', async (c) => { const username = body.username.trim(); const password = body.password; + // BE-S6: IP rate limit for registration (10/hour) — bulk account creation guard + const registerAllowed = await checkRegisterRateLimit( + c.env.LINKS_KV, + clientIp(c), + ); + if (!registerAllowed) { + return c.json({ error: 'Too many requests. Try again later.' }, 429); + } + // M4: Input validation if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { return c.json({ error: 'Invalid email address' }, 400); @@ -422,8 +447,12 @@ auth.post('/login', async (c) => { const email = body.email.trim().toLowerCase(); - // C1: Rate limit login attempts per email - const loginAllowed = await checkLoginRateLimit(c.env.LINKS_KV, email); + // C1: Rate limit login attempts per email AND per IP (BE-S6) + const loginAllowed = await checkLoginRateLimit( + c.env.LINKS_KV, + email, + clientIp(c), + ); if (!loginAllowed) { return c.json( { error: 'Too many login attempts. Please try again later.' }, @@ -449,7 +478,7 @@ auth.post('/login', async (c) => { } // C1: Reset failed counter on successful login - await resetLoginAttempts(c.env.LINKS_KV, email); + await resetLoginAttempts(c.env.LINKS_KV, email, clientIp(c)); const methods = getUserMethods(user); @@ -533,6 +562,13 @@ auth.post('/refresh', async (c) => { .first(); if (!user?.is_active) return c.json({ error: 'User not found' }, 401); + // BE-S3: If the account's token_version has changed (password change/reset, + // admin disable/demote), this refresh token is no longer valid. + if (user.token_version !== payload.tv) { + clearRefreshCookie(c); + return c.json({ error: 'Unauthorized' }, 401); + } + const tokens = await issueTokens(user, c.env.JWT_SECRET); setRefreshCookie(c, tokens.refreshToken); return c.json({ accessToken: tokens.accessToken }); @@ -602,12 +638,13 @@ auth.post('/change-password', requireAuth, async (c) => { const newHash = await hashPassword(body.newPassword); await c.env.DB.prepare( - `UPDATE ${tbl(c.env, 'users')} SET password_hash = ?1, updated_at = unixepoch() WHERE id = ?2`, + `UPDATE ${tbl(c.env, 'users')} SET password_hash = ?1, token_version = token_version + 1, updated_at = unixepoch() WHERE id = ?2`, ) .bind(newHash, userId) .run(); - // C-3 + S1: Denylist both access and refresh tokens + // C-3 + S1: Denylist both access and refresh tokens. BE-S3: token_version bump + // above additionally revokes every other active session. const accessTtl = Math.max(exp - Math.floor(Date.now() / 1000), 0) + 60; await denylistJti(c.env.LINKS_KV, jti, accessTtl); @@ -1557,9 +1594,14 @@ auth.post('/forgot-password', async (c) => { if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) return c.json({ success: true }); - // Rate limit using same KV bucket as email OTP + // Rate limit using same KV bucket as email OTP, plus an IP dimension (BE-S6) + // so an attacker can't mail-bomb arbitrary victim addresses. const allowed = await checkOtpRateLimit(c.env.LINKS_KV, email); - if (!allowed) { + const ipAllowed = await checkForgotPasswordIpRateLimit( + c.env.LINKS_KV, + clientIp(c), + ); + if (!allowed || !ipAllowed) { return c.json({ error: 'Too many requests. Try again later.' }, 429); } @@ -1658,7 +1700,7 @@ auth.post('/reset-password', async (c) => { `UPDATE ${tbl(c.env, 'verifications')} SET used = 1 WHERE id = ?1`, ).bind(verification.id), c.env.DB.prepare( - `UPDATE ${tbl(c.env, 'users')} SET password_hash = ?1, updated_at = unixepoch() WHERE id = ?2`, + `UPDATE ${tbl(c.env, 'users')} SET password_hash = ?1, token_version = token_version + 1, updated_at = unixepoch() WHERE id = ?2`, ).bind(newHash, user.id), ]); diff --git a/apps/worker/src/routes/setup.ts b/apps/worker/src/routes/setup.ts index 4b164c3..54e17df 100644 --- a/apps/worker/src/routes/setup.ts +++ b/apps/worker/src/routes/setup.ts @@ -1,4 +1,6 @@ import { Hono } from 'hono'; +import { constantTimeEqual } from '../lib/crypto.js'; +import { checkSetupRateLimit } from '../lib/kv.js'; import type { Env, Variables } from '../types.js'; const app = new Hono<{ Bindings: Env; Variables: Variables }>(); @@ -125,6 +127,14 @@ CREATE TABLE IF NOT EXISTS ${t('totp_used')} ( PRIMARY KEY (user_id, code) ); CREATE INDEX IF NOT EXISTS idx_totp_used_at ON ${t('totp_used')}(used_at); +`, + }, + { + // BE-S3/S4: per-user token_version — bumping it revokes all of a user's + // sessions (password change/reset, admin disable/demote). + name: 'schema_v2', + sql: ` +ALTER TABLE ${t('users')} ADD COLUMN token_version INTEGER NOT NULL DEFAULT 0; `, }, ]; @@ -144,9 +154,21 @@ function toSingleLine(sql: string): string { .trim(); } -app.get('/:secret', async (c) => { - const secret = c.req.param('secret'); - if (!c.env.SETUP_SECRET || secret !== c.env.SETUP_SECRET) { +// BE-S5: POST + header secret (kept out of URL/logs), constant-time comparison, +// and per-IP rate limiting. When SETUP_SECRET is not set the endpoint 404s. +app.post('/', async (c) => { + if (!c.env.SETUP_SECRET) { + return c.notFound(); + } + + const ip = c.req.header('cf-connecting-ip') ?? 'unknown'; + const allowed = await checkSetupRateLimit(c.env.LINKS_KV, ip); + if (!allowed) { + return c.json({ error: 'Too many requests. Try again later.' }, 429); + } + + const provided = c.req.header('X-Setup-Secret') ?? ''; + if (!constantTimeEqual(provided, c.env.SETUP_SECRET)) { return c.notFound(); } diff --git a/apps/worker/src/types.ts b/apps/worker/src/types.ts index 90450ba..019bf26 100644 --- a/apps/worker/src/types.ts +++ b/apps/worker/src/types.ts @@ -45,6 +45,7 @@ export interface UserRow { email_2fa_enabled: number; passkey_enabled: number; is_active: number; + token_version: number; created_at: number; updated_at: number; } @@ -114,6 +115,7 @@ export interface AccessTokenPayload { sub: string; role: 'admin' | 'user'; email: string; + tv: number; purpose: 'access'; jti: string; exp: number; @@ -121,6 +123,7 @@ export interface AccessTokenPayload { export interface RefreshTokenPayload { sub: string; + tv: number; purpose: 'refresh'; jti: string; exp: number;