From 3fbf69d31c65e142c15daec19cc4485a5ca48bc9 Mon Sep 17 00:00:00 2001 From: Todos Date: Sat, 17 Oct 2026 23:09:22 +0800 Subject: [PATCH 1/2] fix: round-3 correctness and reliability fixes from review report - BE-C1: shared parseIntParam/parsePagination helpers guard page, limit and days against NaN in links, admin and analytics routes - BE-C3: map D1 UNIQUE violations to 409 in register and admin create user - FE-C1/C2: drop stale expiry fields from the create payload and use local time for datetime-local; edit only sends expiresAt when changed - FE-C3/C4: replace render-time navigate in TwoFactorPage; only treat verify-email as signed in when an access token is returned - FE-R1/R2: keep the session on transient refresh failures, handle expiry once in-SPA and clear the query cache when signed out - FE-R3: expose AppConfig isLoading/loadFailed; register and login pages wait for config and surface load errors - add node --test worker unit tests and a pnpm test script Co-Authored-By: Claude Code Checkpoint: dedJ4t0xV3KkeaGQPpASD --- CLAUDE.md | 1 + apps/web/src/api/client.ts | 70 +++++++++++++++++----- apps/web/src/contexts/AppConfigContext.tsx | 23 ++++++- apps/web/src/contexts/AuthContext.tsx | 17 ++++++ apps/web/src/i18n/locales/en.ts | 4 ++ apps/web/src/i18n/locales/zh-CN.ts | 3 + apps/web/src/lib/utils.ts | 18 ++++++ apps/web/src/pages/auth/LoginPage.tsx | 23 ++++++- apps/web/src/pages/auth/RegisterPage.tsx | 68 ++++++++++++++++++--- apps/web/src/pages/auth/TwoFactorPage.tsx | 30 ++++++---- apps/web/src/pages/dashboard/LinksPage.tsx | 40 +++++++------ apps/worker/package.json | 2 + apps/worker/src/lib/db.ts | 14 +++++ apps/worker/src/lib/params.ts | 31 ++++++++++ apps/worker/src/routes/admin.ts | 38 +++++++----- apps/worker/src/routes/analytics.ts | 11 +--- apps/worker/src/routes/auth.ts | 35 ++++++++--- apps/worker/src/routes/links.ts | 8 +-- apps/worker/test/db.test.ts | 34 +++++++++++ apps/worker/test/params.test.ts | 48 +++++++++++++++ package.json | 1 + turbo.json | 3 + 22 files changed, 429 insertions(+), 93 deletions(-) create mode 100644 apps/worker/src/lib/params.ts create mode 100644 apps/worker/test/db.test.ts create mode 100644 apps/worker/test/params.test.ts diff --git a/CLAUDE.md b/CLAUDE.md index 271b8cb..0c3923c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -18,6 +18,7 @@ The Worker serves both the API (`/api/*`) and the compiled frontend, so there is pnpm dev # turbo: runs both worker dev + web dev concurrently pnpm build # turbo: typecheck + build web pnpm typecheck # turbo: tsc --noEmit on both packages +pnpm test # turbo: worker unit tests (node --test, apps/worker/test/*.test.ts) pnpm deploy # turbo: builds web then deploys worker ``` diff --git a/apps/web/src/api/client.ts b/apps/web/src/api/client.ts index 8ab74cc..82a7d9c 100644 --- a/apps/web/src/api/client.ts +++ b/apps/web/src/api/client.ts @@ -2,14 +2,35 @@ let accessToken: string | null = null; +// FE-R2: When a refresh is rejected, every request that was waiting on it sees +// the same failure. Handle the expiry once per session (instead of each request +// hard-navigating to /login) and let the app end the session in-SPA through the +// handler registered by AuthProvider. +let sessionExpiredHandled = false; +let sessionExpiredHandler: (() => void) | null = null; + export function setAccessToken(token: string | null) { accessToken = token; + // A fresh token starts a new session, so a later expiry is handled again. + if (token) sessionExpiredHandled = false; } export function getAccessToken() { return accessToken; } +export function setSessionExpiredHandler(handler: (() => void) | null) { + sessionExpiredHandler = handler; +} + +function handleSessionExpired() { + accessToken = null; + if (sessionExpiredHandled) return; + sessionExpiredHandled = true; + if (sessionExpiredHandler) sessionExpiredHandler(); + else window.location.assign('/login'); +} + const BASE = '/api'; interface ApiError { @@ -38,8 +59,8 @@ async function request( if (res.status === 401 && !options.skipAuth) { // Attempt silent refresh via HttpOnly cookie - const refreshed = await tryRefresh(); - if (refreshed) { + const outcome = await tryRefresh(); + if (outcome === 'ok') { headers.Authorization = `Bearer ${accessToken}`; const retryRes = await fetch(`${BASE}${path}`, { ...options, @@ -54,9 +75,14 @@ async function request( } return retryRes.json() as Promise; } - // Refresh failed — clear access token and redirect - setAccessToken(null); - window.location.href = '/login'; + if (outcome === 'transient') { + // FE-R1: The refresh never got a verdict (offline, 5xx). The refresh + // cookie may still be valid, so keep the session and fail just this + // request — react-query retries, and the next 401 refreshes again. + throw new Error('Network error. Please try again.'); + } + // The server rejected the refresh cookie — the session is really over. + handleSessionExpired(); throw new Error('Session expired'); } @@ -78,7 +104,11 @@ async function request( // 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; +// FE-R1: 'transient' (network failure, 5xx, 408/429) says nothing about the +// session; only 'expired' — the server rejected the refresh cookie — ends it. +type RefreshOutcome = 'ok' | 'expired' | 'transient'; + +let refreshPromise: Promise | null = null; function withRefreshLock(fn: () => Promise): Promise { const locks = typeof navigator !== 'undefined' ? navigator.locks : undefined; @@ -92,7 +122,7 @@ function withRefreshLock(fn: () => Promise): Promise { return fn(); } -async function tryRefresh(): Promise { +async function tryRefresh(): Promise { if (refreshPromise) return refreshPromise; refreshPromise = withRefreshLock(_doRefresh).finally(() => { refreshPromise = null; @@ -100,19 +130,29 @@ async function tryRefresh(): Promise { return refreshPromise; } -async function _doRefresh(): Promise { +async function _doRefresh(): Promise { + let res: Response; try { - const res = await fetch(`${BASE}/auth/refresh`, { + res = await fetch(`${BASE}/auth/refresh`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', }); - if (!res.ok) return false; - const data = (await res.json()) as { accessToken: string }; + } catch { + return 'transient'; + } + if (!res.ok) { + const transient = + res.status >= 500 || res.status === 408 || res.status === 429; + return transient ? 'transient' : 'expired'; + } + try { + const data = (await res.json()) as { accessToken?: string }; + if (!data.accessToken) return 'transient'; setAccessToken(data.accessToken); - return true; + return 'ok'; } catch { - return false; + return 'transient'; } } @@ -120,8 +160,8 @@ async function _doRefresh(): Promise { // 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; + const outcome = await tryRefresh(); + return outcome === 'ok' ? getAccessToken() : null; } // ─── Auth API ───────────────────────────────────────────────────────────────── diff --git a/apps/web/src/contexts/AppConfigContext.tsx b/apps/web/src/contexts/AppConfigContext.tsx index 84ae50c..ef8888c 100644 --- a/apps/web/src/contexts/AppConfigContext.tsx +++ b/apps/web/src/contexts/AppConfigContext.tsx @@ -15,6 +15,11 @@ interface AppConfig { interface AppConfigContextType { appName: string; registrationEnabled: boolean; + // FE-R3: Consumers must not act on `registrationEnabled` until the first + // /api/config response has arrived (`isLoading`), and must tell the user when + // it could not be loaded (`loadFailed`) instead of silently assuming "closed". + isLoading: boolean; + loadFailed: boolean; reload: () => void; } @@ -22,21 +27,27 @@ const AppConfigContext = createContext(null); async function fetchConfig(): Promise { const res = await fetch('/api/config'); - if (!res.ok) return { appName: 'ShortLink', registrationEnabled: false }; + if (!res.ok) throw new Error(`GET /api/config failed: ${res.status}`); return res.json() as Promise; } export function AppConfigProvider({ children }: { children: React.ReactNode }) { const [appName, setAppName] = useState('ShortLink'); const [registrationEnabled, setRegistrationEnabled] = useState(false); + const [isLoading, setIsLoading] = useState(true); + const [loadFailed, setLoadFailed] = useState(false); + // Reloads keep the last known values on screen; only the first load shows as + // `isLoading`. const load = useCallback(() => { fetchConfig() .then((c) => { setAppName(c.appName); setRegistrationEnabled(c.registrationEnabled); + setLoadFailed(false); }) - .catch(() => {}); + .catch(() => setLoadFailed(true)) + .finally(() => setIsLoading(false)); }, []); useEffect(() => { @@ -45,7 +56,13 @@ export function AppConfigProvider({ children }: { children: React.ReactNode }) { return ( {children} diff --git a/apps/web/src/contexts/AuthContext.tsx b/apps/web/src/contexts/AuthContext.tsx index 682bb45..17fdf7b 100644 --- a/apps/web/src/contexts/AuthContext.tsx +++ b/apps/web/src/contexts/AuthContext.tsx @@ -1,3 +1,4 @@ +import { useQueryClient } from '@tanstack/react-query'; import type React from 'react'; import { createContext, @@ -12,6 +13,7 @@ import { type LoginResult, refreshSession, setAccessToken, + setSessionExpiredHandler, type User, } from '../api/client.ts'; @@ -43,6 +45,21 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { const [pendingMethods, setPendingMethods] = useState([]); // H-1: BroadcastChannel for cross-tab login/logout coordination (signal only) const channelRef = useRef(null); + const queryClient = useQueryClient(); + + // FE-R2: End an expired session in-SPA. Clearing the user lets + // ProtectedRoute/AdminRoute redirect to /login, replacing the per-request + // `window.location.href = '/login'` hard reloads. + useEffect(() => { + setSessionExpiredHandler(() => setUser(null)); + return () => setSessionExpiredHandler(null); + }, []); + + // Without a full page reload on session end, cached queries would survive + // into the next session in this tab — drop them whenever nobody is signed in. + useEffect(() => { + if (!user) queryClient.clear(); + }, [user, queryClient]); const refreshUser = useCallback(async () => { try { diff --git a/apps/web/src/i18n/locales/en.ts b/apps/web/src/i18n/locales/en.ts index 8e0974a..57e8565 100644 --- a/apps/web/src/i18n/locales/en.ts +++ b/apps/web/src/i18n/locales/en.ts @@ -20,6 +20,7 @@ export const en = { no: 'No', user: 'User', admin: 'Admin', + retry: 'Retry', }, nav: { links: 'Links', @@ -77,6 +78,9 @@ export const en = { verificationCode: 'Verification Code', accountCreated: 'Account created! Please sign in.', verifyCodeResent: 'Verification code resent.', + emailVerifiedSignIn: 'Email verified. Please sign in.', + configLoadFailed: + "Couldn't load site settings. Check your connection and try again.", }, links: { title: 'My Links', diff --git a/apps/web/src/i18n/locales/zh-CN.ts b/apps/web/src/i18n/locales/zh-CN.ts index 83bfda6..6954bf3 100644 --- a/apps/web/src/i18n/locales/zh-CN.ts +++ b/apps/web/src/i18n/locales/zh-CN.ts @@ -22,6 +22,7 @@ export const zhCN: Translations = { no: '否', user: '用户', admin: '管理员', + retry: '重试', }, nav: { links: '链接', @@ -77,6 +78,8 @@ export const zhCN: Translations = { verificationCode: '验证码', accountCreated: '账户已创建!请登录。', verifyCodeResent: '验证码已重新发送。', + emailVerifiedSignIn: '邮箱已验证,请登录。', + configLoadFailed: '无法加载站点配置,请检查网络后重试。', }, links: { title: '我的链接', diff --git a/apps/web/src/lib/utils.ts b/apps/web/src/lib/utils.ts index a0d23db..3b93958 100644 --- a/apps/web/src/lib/utils.ts +++ b/apps/web/src/lib/utils.ts @@ -36,6 +36,24 @@ export function expiryLabel(expiresAt: number | null): string { return `${Math.floor(diff / 86400)}d remaining`; } +// FE-C2: shows and parses wall-clock time in the +// browser's local time zone, so its value must be formatted locally too — +// toISOString() is UTC and shifted the expiry by the UTC offset on every edit. +export function toDatetimeLocalValue(ts: number | null): string { + if (!ts) return ''; + const d = new Date(ts * 1000); + const pad = (n: number) => String(n).padStart(2, '0'); + return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`; +} + +// Inverse of toDatetimeLocalValue: a local "YYYY-MM-DDTHH:mm" string to a Unix +// timestamp in seconds, or null when empty/invalid. +export function fromDatetimeLocalValue(value: string): number | null { + if (!value) return null; + const ms = new Date(value).getTime(); + return Number.isNaN(ms) ? null : Math.floor(ms / 1000); +} + export function copyToClipboard(text: string): Promise { return navigator.clipboard.writeText(text); } diff --git a/apps/web/src/pages/auth/LoginPage.tsx b/apps/web/src/pages/auth/LoginPage.tsx index 81a0255..f82f08d 100644 --- a/apps/web/src/pages/auth/LoginPage.tsx +++ b/apps/web/src/pages/auth/LoginPage.tsx @@ -17,7 +17,11 @@ import { useTranslation } from '@/i18n'; export default function LoginPage() { const { login, setPendingState } = useAuth(); - const { registrationEnabled } = useAppConfig(); + const { + registrationEnabled, + loadFailed: configLoadFailed, + reload: reloadConfig, + } = useAppConfig(); const { t } = useTranslation(); const navigate = useNavigate(); const [email, setEmail] = useState(''); @@ -85,6 +89,23 @@ export default function LoginPage() { {t('auth.signIn')} + {/* FE-R3: Say so when /api/config failed instead of silently hiding + the register link. */} + {configLoadFailed && ( +

+ {t('auth.configLoadFailed')}{' '} + +

+ )} {registrationEnabled && (

{t('auth.noAccount')}{' '} diff --git a/apps/web/src/pages/auth/RegisterPage.tsx b/apps/web/src/pages/auth/RegisterPage.tsx index 577b84b..e7769fe 100644 --- a/apps/web/src/pages/auth/RegisterPage.tsx +++ b/apps/web/src/pages/auth/RegisterPage.tsx @@ -24,8 +24,13 @@ type Step = 'form' | 'verify'; export default function RegisterPage() { const { t } = useTranslation(); const navigate = useNavigate(); - const { registrationEnabled } = useAppConfig(); - const { refreshUser, broadcastRefresh } = useAuth(); + const { + registrationEnabled, + isLoading: configLoading, + loadFailed: configLoadFailed, + reload: reloadConfig, + } = useAppConfig(); + const { refreshUser, broadcastRefresh, setPendingState } = useAuth(); const [step, setStep] = useState('form'); const [email, setEmail] = useState(''); const [username, setUsername] = useState(''); @@ -35,9 +40,12 @@ export default function RegisterPage() { const [code, setCode] = useState(''); const { countdown, start: startCountdown } = useCountdown(); + // FE-R3: Decide only once /api/config has answered — the provider's initial + // `registrationEnabled = false` used to bounce every direct visit to /login. useEffect(() => { + if (configLoading || configLoadFailed) return; if (!registrationEnabled) navigate('/login', { replace: true }); - }, [registrationEnabled, navigate]); + }, [configLoading, configLoadFailed, registrationEnabled, navigate]); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); @@ -64,12 +72,22 @@ export default function RegisterPage() { setLoading(true); try { const result = await authApi.verifyEmail(userId, code); - if (result.accessToken) { - setAccessToken(result.accessToken); - broadcastRefresh(); + // FE-C4: Only a response carrying an access token is a signed-in session; + // anything else would land on /dashboard and be bounced to /login. + if (result.requiresTwoFactor && result.pendingToken && result.methods) { + setPendingState(result.pendingToken, result.methods); + navigate('/two-factor', { replace: true }); + return; } + if (!result.accessToken) { + toast.success(t('auth.emailVerifiedSignIn')); + navigate('/login', { replace: true }); + return; + } + setAccessToken(result.accessToken); + broadcastRefresh(); await refreshUser(); - navigate('/dashboard'); + navigate('/dashboard', { replace: true }); } catch (err) { toast.error(err instanceof Error ? err.message : 'Verification failed'); } finally { @@ -91,6 +109,42 @@ export default function RegisterPage() { } }; + if (step === 'form' && (configLoading || configLoadFailed)) { + return ( + + + {t('auth.createAccount')} + + + {configLoading ? ( +

+ {t('common.loading')} +

+ ) : ( +
+

+ {t('auth.configLoadFailed')} +

+ +
+ )} +

+ + {t('auth.backToLogin')} + +

+ + + ); + } + if (step === 'verify') { return ( diff --git a/apps/web/src/pages/auth/TwoFactorPage.tsx b/apps/web/src/pages/auth/TwoFactorPage.tsx index 5b14c64..482a8ff 100644 --- a/apps/web/src/pages/auth/TwoFactorPage.tsx +++ b/apps/web/src/pages/auth/TwoFactorPage.tsx @@ -1,6 +1,6 @@ import { startAuthentication } from '@simplewebauthn/browser'; import { useState } from 'react'; -import { useNavigate } from 'react-router-dom'; +import { Navigate, useNavigate } from 'react-router-dom'; import { toast } from 'sonner'; import type { LoginResult } from '@/api/client'; import { authApi, setAccessToken } from '@/api/client'; @@ -36,18 +36,22 @@ export default function TwoFactorPage() { const [loading, setLoading] = useState(false); const [otpSent, setOtpSent] = useState(false); - if (!pendingToken) { - navigate('/login'); - return null; - } + // FE-C3: Redirect declaratively — calling navigate() during render is a side + // effect React may run twice (StrictMode) or warn about. + if (!pendingToken) return ; - const handleSuccess = (result: LoginResult) => { - if (result.accessToken) { - setAccessToken(result.accessToken); - broadcastRefresh(); + const handleSuccess = async (result: LoginResult) => { + if (!result.accessToken) { + toast.error('Verification failed'); + return; } + setAccessToken(result.accessToken); + broadcastRefresh(); + await refreshUser(); + // Leave the page before clearing the pending state: clearing it first + // re-renders this page without a pendingToken and flashes /login. + navigate('/dashboard', { replace: true }); clearPendingState(); - refreshUser().then(() => navigate('/dashboard')); }; const handleTotpVerify = async (e: React.FormEvent) => { @@ -55,7 +59,7 @@ export default function TwoFactorPage() { setLoading(true); try { const result = await authApi.totpVerify(pendingToken, code); - handleSuccess(result); + await handleSuccess(result); } catch (err) { toast.error(err instanceof Error ? err.message : 'Invalid code'); } finally { @@ -81,7 +85,7 @@ export default function TwoFactorPage() { setLoading(true); try { const result = await authApi.emailOtpVerify(pendingToken, code); - handleSuccess(result); + await handleSuccess(result); } catch (err) { toast.error(err instanceof Error ? err.message : 'Invalid code'); } finally { @@ -100,7 +104,7 @@ export default function TwoFactorPage() { response, challengeId, ); - handleSuccess(result); + await handleSuccess(result); } catch (err) { toast.error( err instanceof Error ? err.message : 'Passkey authentication failed', diff --git a/apps/web/src/pages/dashboard/LinksPage.tsx b/apps/web/src/pages/dashboard/LinksPage.tsx index aececd6..01c0fa6 100644 --- a/apps/web/src/pages/dashboard/LinksPage.tsx +++ b/apps/web/src/pages/dashboard/LinksPage.tsx @@ -22,7 +22,11 @@ import { import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { useTranslation } from '@/i18n'; -import { formatDate } from '@/lib/utils'; +import { + formatDate, + fromDatetimeLocalValue, + toDatetimeLocalValue, +} from '@/lib/utils'; export default function LinksPage() { const { t } = useTranslation(); @@ -231,20 +235,28 @@ function CreateLinkDialog({ const [expiryOption, setExpiryOption] = useState< 'never' | '1' | '7' | '30' | 'custom' >('never'); + // Raw datetime-local value for the "custom" option, kept apart from `form` so + // switching options can never leave a stale timestamp in the payload. + const [customExpiry, setCustomExpiry] = useState(''); const [loading, setLoading] = useState(false); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setLoading(true); try { + // FE-C1: The backend gives expiresAt precedence over expiryDays, so only + // the field matching the currently selected option may be sent. const payload: CreateLinkPayload = { ...form }; - if (expiryOption !== 'never' && expiryOption !== 'custom') { + if (expiryOption === 'custom') { + payload.expiresAt = fromDatetimeLocalValue(customExpiry); + } else if (expiryOption !== 'never') { payload.expiryDays = parseInt(expiryOption, 10); } await linksApi.create(payload); toast.success('Link created!'); setForm({ destinationUrl: '' }); setExpiryOption('never'); + setCustomExpiry(''); onCreated(); } catch (err) { toast.error(err instanceof Error ? err.message : 'Failed to create link'); @@ -325,14 +337,8 @@ function CreateLinkDialog({ {expiryOption === 'custom' && ( - setForm((f) => ({ - ...f, - expiresAt: e.target.value - ? Math.floor(new Date(e.target.value).getTime() / 1000) - : null, - })) - } + value={customExpiry} + onChange={(e) => setCustomExpiry(e.target.value)} /> )} @@ -386,7 +392,9 @@ export function EditLinkDialog({ customSlug: form.customSlug, title: form.title || undefined, isActive: form.isActive, - expiresAt, + // Only send expiresAt when it was edited: re-sending an unchanged past + // expiry would make the backend reject edits to an expired link. + ...(expiresAt !== link.expires_at && { expiresAt }), }); toast.success('Link updated'); onUpdated(); @@ -397,9 +405,7 @@ export function EditLinkDialog({ } }; - const expiresAtInputValue = expiresAt - ? new Date(expiresAt * 1000).toISOString().slice(0, 16) - : ''; + const expiresAtInputValue = toDatetimeLocalValue(expiresAt); return ( @@ -444,11 +450,7 @@ export function EditLinkDialog({ type="datetime-local" value={expiresAtInputValue} onChange={(e) => - setExpiresAt( - e.target.value - ? Math.floor(new Date(e.target.value).getTime() / 1000) - : null, - ) + setExpiresAt(fromDatetimeLocalValue(e.target.value)) } /> diff --git a/apps/worker/package.json b/apps/worker/package.json index c270ca2..b97dc9d 100644 --- a/apps/worker/package.json +++ b/apps/worker/package.json @@ -2,10 +2,12 @@ "name": "@shortlink/worker", "version": "1.0.0", "private": true, + "type": "module", "scripts": { "dev": "wrangler dev", "build": "tsc --noEmit", "typecheck": "tsc --noEmit", + "test": "node --test test/*.test.ts", "deploy": "wrangler deploy", "db:migrate:local": "wrangler d1 migrations apply DB --local", "db:migrate": "wrangler d1 migrations apply DB --remote" diff --git a/apps/worker/src/lib/db.ts b/apps/worker/src/lib/db.ts index 8b86d4e..d362309 100644 --- a/apps/worker/src/lib/db.ts +++ b/apps/worker/src/lib/db.ts @@ -7,3 +7,17 @@ export function tbl(env: { TABLE_PREFIX?: string }, name: string): string { const prefix = (env.TABLE_PREFIX ?? '').replace(/[^a-zA-Z0-9_]/g, ''); return prefix ? `${prefix}_${name}` : name; } + +// BE-C3: True when a D1 error is a UNIQUE constraint violation. D1 surfaces the +// SQLite message (e.g. "D1_ERROR: UNIQUE constraint failed: users.email: +// SQLITE_CONSTRAINT"), sometimes only on a wrapped `cause`, so walk that chain. +export function isUniqueConstraintError(err: unknown): boolean { + let e: unknown = err; + for (let depth = 0; e instanceof Error && depth < 5; depth++) { + if (/UNIQUE constraint failed|SQLITE_CONSTRAINT_UNIQUE/.test(e.message)) { + return true; + } + e = e.cause; + } + return false; +} diff --git a/apps/worker/src/lib/params.ts b/apps/worker/src/lib/params.ts new file mode 100644 index 0000000..0e8800b --- /dev/null +++ b/apps/worker/src/lib/params.ts @@ -0,0 +1,31 @@ +// Query-string number parsing shared by the list/analytics routes. +// This module has no imports so it can be unit-tested directly under Node. + +// BE-C1: parseInt('abc') is NaN and Math.max/min propagate it, so a malformed +// ?page= or ?limit= used to reach D1's LIMIT/OFFSET and turn into a 500. +// Missing or non-numeric input falls back to the default; numeric input is +// clamped to [min, max]. +export function parseIntParam( + raw: string | undefined, + fallback: number, + min: number, + max: number, +): number { + const n = raw === undefined ? Number.NaN : Number.parseInt(raw, 10); + if (!Number.isFinite(n)) return fallback; + return Math.min(max, Math.max(min, n)); +} + +// Upper bound for ?page= so (page - 1) * limit always stays a safe integer. +export const MAX_PAGE = 1_000_000; + +export function parsePagination( + rawPage: string | undefined, + rawLimit: string | undefined, + maxLimit: number, + defaultLimit = 20, +): { page: number; limit: number; offset: number } { + const page = parseIntParam(rawPage, 1, 1, MAX_PAGE); + const limit = parseIntParam(rawLimit, defaultLimit, 1, maxLimit); + return { page, limit, offset: (page - 1) * limit }; +} diff --git a/apps/worker/src/routes/admin.ts b/apps/worker/src/routes/admin.ts index 9690b88..27eb723 100644 --- a/apps/worker/src/routes/admin.ts +++ b/apps/worker/src/routes/admin.ts @@ -1,7 +1,8 @@ import { Hono } from 'hono'; import { hashPassword } from '../lib/crypto.js'; -import { tbl } from '../lib/db.js'; +import { isUniqueConstraintError, tbl } from '../lib/db.js'; import { deleteCachedLink, deleteCachedSetting } from '../lib/kv.js'; +import { parsePagination } from '../lib/params.js'; import { requireAdmin } from '../middleware/auth.js'; import type { Env, LinkRow, UserRow, Variables } from '../types.js'; @@ -69,13 +70,12 @@ admin.get('/stats', async (c) => { // GET /api/admin/users // ───────────────────────────────────────────────────────────────────────────── admin.get('/users', async (c) => { - const page = Math.max(1, parseInt(c.req.query('page') ?? '1', 10)); - const limit = Math.min( + const { page, limit, offset } = parsePagination( + c.req.query('page'), + c.req.query('limit'), 50, - Math.max(1, parseInt(c.req.query('limit') ?? '20', 10)), ); const search = c.req.query('search')?.trim() ?? ''; - const offset = (page - 1) * limit; const U = tbl(c.env, 'users'); let query: string; @@ -166,11 +166,22 @@ admin.post('/users', async (c) => { const passwordHash = await hashPassword(body.password); const role = body.role ?? 'user'; - const result = await c.env.DB.prepare( - `INSERT INTO ${U} (email, username, password_hash, role) VALUES (?1, ?2, ?3, ?4) RETURNING id, email, username, role`, - ) - .bind(email, username, passwordHash, role) - .first<{ id: string; email: string; username: string; role: string }>(); + // BE-C3: Concurrent creates can race past the SELECT above; map the UNIQUE + // constraint violation to 409 instead of letting it surface as a 500. + type NewUser = { id: string; email: string; username: string; role: string }; + let result: NewUser | null; + try { + result = await c.env.DB.prepare( + `INSERT INTO ${U} (email, username, password_hash, role) VALUES (?1, ?2, ?3, ?4) RETURNING id, email, username, role`, + ) + .bind(email, username, passwordHash, role) + .first(); + } catch (err) { + if (isUniqueConstraintError(err)) { + return c.json({ error: 'Email or username already taken' }, 409); + } + throw err; + } if (!result) return c.json({ error: 'Failed to create user' }, 500); @@ -291,14 +302,13 @@ admin.delete('/users/:id', async (c) => { // GET /api/admin/links // ───────────────────────────────────────────────────────────────────────────── admin.get('/links', async (c) => { - const page = Math.max(1, parseInt(c.req.query('page') ?? '1', 10)); - const limit = Math.min( + const { page, limit, offset } = parsePagination( + c.req.query('page'), + c.req.query('limit'), 100, - Math.max(1, parseInt(c.req.query('limit') ?? '20', 10)), ); const search = c.req.query('search')?.trim() ?? ''; const userId = c.req.query('userId'); - const offset = (page - 1) * limit; const L = tbl(c.env, 'links'); const U = tbl(c.env, 'users'); diff --git a/apps/worker/src/routes/analytics.ts b/apps/worker/src/routes/analytics.ts index be58e5c..c7e41c8 100644 --- a/apps/worker/src/routes/analytics.ts +++ b/apps/worker/src/routes/analytics.ts @@ -1,5 +1,6 @@ import { Hono } from 'hono'; import { tbl } from '../lib/db.js'; +import { parseIntParam } from '../lib/params.js'; import { requireAuth } from '../middleware/auth.js'; import type { Env, LinkRow, Variables } from '../types.js'; @@ -33,10 +34,7 @@ async function getLinkForUser( // ───────────────────────────────────────────────────────────────────────────── analytics.get('/summary', async (c) => { const userId = c.get('userId'); - const days = Math.min( - 365, - Math.max(1, parseInt(c.req.query('days') ?? '30', 10)), - ); + const days = parseIntParam(c.req.query('days'), 30, 1, 365); const now = Math.floor(Date.now() / 1000); const since = now - days * 86400; @@ -133,10 +131,7 @@ analytics.get('/:linkId', async (c) => { const link = await getLinkForUser(c.env, linkId, userId, role); if (!link) return c.json({ error: 'Link not found' }, 404); - const days = Math.min( - 365, - Math.max(1, parseInt(c.req.query('days') ?? '30', 10)), - ); + const days = parseIntParam(c.req.query('days'), 30, 1, 365); const now = Math.floor(Date.now() / 1000); const since = now - days * 86400; diff --git a/apps/worker/src/routes/auth.ts b/apps/worker/src/routes/auth.ts index f8b9895..90f0b35 100644 --- a/apps/worker/src/routes/auth.ts +++ b/apps/worker/src/routes/auth.ts @@ -6,7 +6,7 @@ import { sha256, verifyPassword, } from '../lib/crypto.js'; -import { tbl } from '../lib/db.js'; +import { isUniqueConstraintError, tbl } from '../lib/db.js'; import { otpEmailHtml, resetPasswordEmailHtml, @@ -236,17 +236,33 @@ auth.post('/register', async (c) => { const passwordHash = await hashPassword(password); + // BE-C3: The SELECT above is only a fast path — a concurrent registration with + // the same email/username can slip between it and the INSERT. The UNIQUE + // constraints are the real guard; report their violation as 409, not 500. + type NewUser = { id: string; email: string; username: string; role: string }; + const insertUser = async (sql: string): Promise => { + try { + return await c.env.DB.prepare(sql) + .bind(email, username, passwordHash) + .first(); + } catch (err) { + if (isUniqueConstraintError(err)) return 'taken'; + throw err; + } + }; + // If email verification is required (non-first user only), create account as inactive // and send a verification code before the user can log in. if (!isFirstUser && (await isEmailVerificationRequired(c.env))) { - const newUser = await c.env.DB.prepare( + const newUser = await insertUser( `INSERT INTO ${tbl(c.env, 'users')} (email, username, password_hash, role, is_active) VALUES (?1, ?2, ?3, 'user', 0) RETURNING id, email, username, role`, - ) - .bind(email, username, passwordHash) - .first<{ id: string; email: string; username: string; role: string }>(); + ); + if (newUser === 'taken') { + return c.json({ error: 'Email or username already taken' }, 409); + } if (!newUser) return c.json({ error: 'Failed to create user' }, 500); const code = generateOtp(6); @@ -282,14 +298,15 @@ auth.post('/register', async (c) => { } // H3: Role assigned atomically inside SQL — prevents bootstrap race condition - const result = await c.env.DB.prepare( + const result = await insertUser( `INSERT INTO ${tbl(c.env, 'users')} (email, username, password_hash, role) VALUES (?1, ?2, ?3, CASE WHEN (SELECT COUNT(*) FROM ${tbl(c.env, 'users')}) = 0 THEN 'admin' ELSE 'user' END) RETURNING id, email, username, role`, - ) - .bind(email, username, passwordHash) - .first<{ id: string; email: string; username: string; role: string }>(); + ); + if (result === 'taken') { + return c.json({ error: 'Email or username already taken' }, 409); + } if (!result) return c.json({ error: 'Failed to create user' }, 500); return c.json( diff --git a/apps/worker/src/routes/links.ts b/apps/worker/src/routes/links.ts index d69373b..aa81dcb 100644 --- a/apps/worker/src/routes/links.ts +++ b/apps/worker/src/routes/links.ts @@ -1,6 +1,7 @@ import { Hono } from 'hono'; import { tbl } from '../lib/db.js'; import { deleteCachedLink } from '../lib/kv.js'; +import { parsePagination } from '../lib/params.js'; import { generateSlug, isReservedSlug, isValidSlug } from '../lib/slug.js'; import { requireAuth } from '../middleware/auth.js'; import type { Env, LinkRow, Variables } from '../types.js'; @@ -35,13 +36,12 @@ async function getUniqueSlug( // ───────────────────────────────────────────────────────────────────────────── links.get('/', async (c) => { const userId = c.get('userId'); - const page = Math.max(1, parseInt(c.req.query('page') ?? '1', 10)); - const limit = Math.min( + const { page, limit, offset } = parsePagination( + c.req.query('page'), + c.req.query('limit'), 50, - Math.max(1, parseInt(c.req.query('limit') ?? '20', 10)), ); const search = c.req.query('search')?.trim() ?? ''; - const offset = (page - 1) * limit; let query: string; let countQuery: string; diff --git a/apps/worker/test/db.test.ts b/apps/worker/test/db.test.ts new file mode 100644 index 0000000..4f265df --- /dev/null +++ b/apps/worker/test/db.test.ts @@ -0,0 +1,34 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { isUniqueConstraintError } from '../src/lib/db.ts'; + +test('isUniqueConstraintError detects D1 UNIQUE violations (BE-C3)', () => { + assert.equal( + isUniqueConstraintError( + new Error( + 'D1_ERROR: UNIQUE constraint failed: users.email: SQLITE_CONSTRAINT', + ), + ), + true, + ); + assert.equal( + isUniqueConstraintError( + new Error('D1_ERROR', { + cause: new Error('UNIQUE constraint failed: SL_users.username'), + }), + ), + true, + ); +}); + +test('isUniqueConstraintError ignores other errors', () => { + assert.equal( + isUniqueConstraintError( + new Error('D1_ERROR: NOT NULL constraint failed: users.password_hash'), + ), + false, + ); + assert.equal(isUniqueConstraintError(new Error('network error')), false); + assert.equal(isUniqueConstraintError('UNIQUE constraint failed'), false); + assert.equal(isUniqueConstraintError(null), false); +}); diff --git a/apps/worker/test/params.test.ts b/apps/worker/test/params.test.ts new file mode 100644 index 0000000..b600e27 --- /dev/null +++ b/apps/worker/test/params.test.ts @@ -0,0 +1,48 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { MAX_PAGE, parseIntParam, parsePagination } from '../src/lib/params.ts'; + +test('parseIntParam falls back on missing or non-numeric input (BE-C1)', () => { + assert.equal(parseIntParam(undefined, 30, 1, 365), 30); + assert.equal(parseIntParam('', 30, 1, 365), 30); + assert.equal(parseIntParam('abc', 30, 1, 365), 30); + assert.equal(parseIntParam('NaN', 30, 1, 365), 30); + assert.equal(parseIntParam('Infinity', 30, 1, 365), 30); +}); + +test('parseIntParam clamps numeric input to [min, max]', () => { + assert.equal(parseIntParam('7', 30, 1, 365), 7); + assert.equal(parseIntParam('0', 30, 1, 365), 1); + assert.equal(parseIntParam('-5', 30, 1, 365), 1); + assert.equal(parseIntParam('1000', 30, 1, 365), 365); + assert.equal(parseIntParam('99999999999999999999999', 30, 1, 365), 365); +}); + +test('parsePagination never yields NaN and keeps offset a safe integer', () => { + assert.deepEqual(parsePagination(undefined, undefined, 50), { + page: 1, + limit: 20, + offset: 0, + }); + assert.deepEqual(parsePagination('abc', 'xyz', 50), { + page: 1, + limit: 20, + offset: 0, + }); + assert.deepEqual(parsePagination('3', '10', 50), { + page: 3, + limit: 10, + offset: 20, + }); + assert.deepEqual(parsePagination('2', '500', 100), { + page: 2, + limit: 100, + offset: 100, + }); + + const huge = parsePagination('1e400', '1e400', 100); + assert.equal(huge.page, 1); // parseInt stops at 'e' + const big = parsePagination('9'.repeat(30), '100', 100); + assert.equal(big.page, MAX_PAGE); + assert.ok(Number.isSafeInteger(big.offset)); +}); diff --git a/package.json b/package.json index 64d3734..90cd7ca 100644 --- a/package.json +++ b/package.json @@ -6,6 +6,7 @@ "dev": "turbo run dev", "build": "turbo run build", "typecheck": "turbo run typecheck", + "test": "turbo run test", "deploy": "turbo run deploy", "lint": "biome lint .", "format": "biome format .", diff --git a/turbo.json b/turbo.json index 48bd79f..fa1de95 100644 --- a/turbo.json +++ b/turbo.json @@ -12,6 +12,9 @@ "typecheck": { "dependsOn": ["^build"] }, + "test": { + "cache": false + }, "deploy": { "dependsOn": ["@shortlink/web#build", "build"], "cache": false, From a5752250933ddf4e18d994637c8e182ff4d85ccf Mon Sep 17 00:00:00 2001 From: Todos Date: Sat, 17 Oct 2026 23:22:31 +0800 Subject: [PATCH 2/2] fix(auth): keep sessions on transient refresh and restore failures - /auth/refresh returns 401 (and clears the cookie) only for invalid tokens; KV/D1 errors now return 503 and rotation runs after all reads - session restore keeps the transient outcome: guards show a retry screen instead of redirecting to /login, and retry when back online Co-Authored-By: Claude Code Checkpoint: xnld6jmMrKwfyDfiv40E_ --- apps/web/src/App.tsx | 37 +++++++++++++-- apps/web/src/api/client.ts | 11 ++--- apps/web/src/contexts/AuthContext.tsx | 68 +++++++++++++++++++-------- apps/web/src/i18n/locales/en.ts | 2 + apps/web/src/i18n/locales/zh-CN.ts | 1 + apps/worker/src/routes/auth.ts | 28 +++++++---- 6 files changed, 108 insertions(+), 39 deletions(-) diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index 5cfb4ed..6f76da1 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -1,6 +1,8 @@ import { lazy, type ReactNode, Suspense } from 'react'; -import { Navigate, Route, Routes } from 'react-router-dom'; +import { Link, Navigate, Route, Routes } from 'react-router-dom'; +import { Button } from './components/ui/button.tsx'; import { useAuth } from './contexts/AuthContext.tsx'; +import { useTranslation } from './i18n/index.tsx'; const AdminLayout = lazy(() => import('./components/layout/AdminLayout.tsx')); const DashboardLayout = lazy( @@ -27,23 +29,45 @@ function PageFallback() { ); } +// FE-R1: Shown instead of the login redirect when the session could not be +// restored for a transient reason — the refresh cookie may still be valid. +function SessionRestoreFailed() { + const { retryRestore } = useAuth(); + const { t } = useTranslation(); + return ( +
+

+ {t('auth.sessionRestoreFailed')} +

+ + + {t('auth.signInLink')} + +
+ ); +} + function ProtectedRoute({ children }: { children: ReactNode }) { - const { user, isLoading } = useAuth(); + const { user, isLoading, restoreFailed } = useAuth(); if (isLoading) return ; + if (!user && restoreFailed) return ; if (!user) return ; return <>{children}; } function AdminRoute({ children }: { children: ReactNode }) { - const { user, isLoading } = useAuth(); + const { user, isLoading, restoreFailed } = useAuth(); if (isLoading) return ; + if (!user && restoreFailed) return ; if (!user) return ; if (user.role !== 'admin') return ; return <>{children}; } export default function App() { - const { user, isLoading } = useAuth(); + const { user, isLoading, restoreFailed } = useAuth(); return ( }> @@ -91,7 +115,10 @@ export default function App() { isLoading ? ( ) : ( - + ) } /> diff --git a/apps/web/src/api/client.ts b/apps/web/src/api/client.ts index 82a7d9c..b9a0f1b 100644 --- a/apps/web/src/api/client.ts +++ b/apps/web/src/api/client.ts @@ -106,7 +106,7 @@ async function request( // rotating the refresh token out from under one another. // FE-R1: 'transient' (network failure, 5xx, 408/429) says nothing about the // session; only 'expired' — the server rejected the refresh cookie — ends it. -type RefreshOutcome = 'ok' | 'expired' | 'transient'; +export type RefreshOutcome = 'ok' | 'expired' | 'transient'; let refreshPromise: Promise | null = null; @@ -157,11 +157,10 @@ 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 outcome = await tryRefresh(); - return outcome === 'ok' ? getAccessToken() : null; +// initial session restore. On 'ok' the new access token is already set; callers +// must keep 'transient' distinct from 'expired' (FE-R1). +export function refreshSession(): Promise { + return tryRefresh(); } // ─── Auth API ───────────────────────────────────────────────────────────────── diff --git a/apps/web/src/contexts/AuthContext.tsx b/apps/web/src/contexts/AuthContext.tsx index 17fdf7b..c23fb5f 100644 --- a/apps/web/src/contexts/AuthContext.tsx +++ b/apps/web/src/contexts/AuthContext.tsx @@ -10,6 +10,7 @@ import { } from 'react'; import { authApi, + getAccessToken, type LoginResult, refreshSession, setAccessToken, @@ -20,6 +21,10 @@ import { interface AuthContextType { user: User | null; isLoading: boolean; + // FE-R1: The initial session restore could not reach the server (offline, + // 5xx). The refresh cookie may still be valid, so this is not "logged out". + restoreFailed: boolean; + retryRestore: () => void; pendingToken: string | null; pendingMethods: string[]; login: (email: string, password: string) => Promise; @@ -41,6 +46,7 @@ type ChannelMsg = { type: 'refresh' } | { type: 'logout' }; export function AuthProvider({ children }: { children: React.ReactNode }) { const [user, setUser] = useState(null); const [isLoading, setIsLoading] = useState(true); + const [restoreFailed, setRestoreFailed] = useState(false); const [pendingToken, setPendingToken] = useState(null); const [pendingMethods, setPendingMethods] = useState([]); // H-1: BroadcastChannel for cross-tab login/logout coordination (signal only) @@ -70,7 +76,39 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { } }, []); - // On mount, try to restore session via HttpOnly refresh cookie (H4) + // Restore the session via the HttpOnly refresh cookie (H4). A transient + // failure sets `restoreFailed` instead of treating the user as logged out. + const restoreSession = useCallback(async () => { + try { + const outcome = await refreshSession(); + setRestoreFailed(outcome === 'transient'); + if (outcome !== 'ok') return; + try { + const data = await authApi.me(); + setUser(data.user); + } catch { + // A rejected session clears the access token (handleSessionExpired); + // if it is still set, /me failed for a transient reason. + if (getAccessToken()) setRestoreFailed(true); + } + } finally { + setIsLoading(false); + } + }, []); + + const retryRestore = useCallback(() => { + setIsLoading(true); + void restoreSession(); + }, [restoreSession]); + + // Retry automatically once the browser reports it is back online. + useEffect(() => { + if (!restoreFailed) return; + window.addEventListener('online', retryRestore); + return () => window.removeEventListener('online', retryRestore); + }, [restoreFailed, retryRestore]); + + // On mount, open the cross-tab channel and restore the session useEffect(() => { // Open channel before init so we don't miss a sibling tab's token broadcast const channel = @@ -85,13 +123,14 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { // 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); + .then((outcome) => { + if (outcome !== 'ok') return; return authApi.me(); }) .then((d) => { - if (d) setUser(d.user); + if (!d) return; + setUser(d.user); + setRestoreFailed(false); }) .catch(() => {}); } else if (e.data?.type === 'logout') { @@ -101,25 +140,13 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { } }); - const init = async () => { - try { - const token = await refreshSession(); - if (!token) return; - setAccessToken(token); - await refreshUser(); - } catch { - // No valid session — user needs to log in - } finally { - setIsLoading(false); - } - }; - init(); + void restoreSession(); return () => { channel?.close(); channelRef.current = null; }; - }, [refreshUser]); + }, [restoreSession]); const login = useCallback( async (email: string, password: string): Promise => { @@ -128,6 +155,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { setAccessToken(result.accessToken); // H4: refresh token is set as HttpOnly cookie by the server — no localStorage setUser(result.user); + setRestoreFailed(false); channelRef.current?.postMessage({ type: 'refresh', } satisfies ChannelMsg); @@ -168,6 +196,8 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { value={{ user, isLoading, + restoreFailed, + retryRestore, pendingToken, pendingMethods, login, diff --git a/apps/web/src/i18n/locales/en.ts b/apps/web/src/i18n/locales/en.ts index 57e8565..2a5ec34 100644 --- a/apps/web/src/i18n/locales/en.ts +++ b/apps/web/src/i18n/locales/en.ts @@ -79,6 +79,8 @@ export const en = { accountCreated: 'Account created! Please sign in.', verifyCodeResent: 'Verification code resent.', emailVerifiedSignIn: 'Email verified. Please sign in.', + sessionRestoreFailed: + "Couldn't reach the server to restore your session. Check your connection and try again.", configLoadFailed: "Couldn't load site settings. Check your connection and try again.", }, diff --git a/apps/web/src/i18n/locales/zh-CN.ts b/apps/web/src/i18n/locales/zh-CN.ts index 6954bf3..28f85f0 100644 --- a/apps/web/src/i18n/locales/zh-CN.ts +++ b/apps/web/src/i18n/locales/zh-CN.ts @@ -79,6 +79,7 @@ export const zhCN: Translations = { accountCreated: '账户已创建!请登录。', verifyCodeResent: '验证码已重新发送。', emailVerifiedSignIn: '邮箱已验证,请登录。', + sessionRestoreFailed: '无法连接服务器以恢复登录状态,请检查网络后重试。', configLoadFailed: '无法加载站点配置,请检查网络后重试。', }, links: { diff --git a/apps/worker/src/routes/auth.ts b/apps/worker/src/routes/auth.ts index 90f0b35..fda0de4 100644 --- a/apps/worker/src/routes/auth.ts +++ b/apps/worker/src/routes/auth.ts @@ -558,20 +558,23 @@ auth.post('/refresh', async (c) => { const refreshToken = getRefreshCookie(c); if (!refreshToken) return c.json({ error: 'Unauthorized' }, 401); + // FE-R1: Only a bad token is a 401 (and clears the cookie). The client treats + // 401 as "session over", so KV/D1 failures must not be reported that way. + let payload: Awaited>; try { - const payload = await verifyRefreshToken(refreshToken, c.env.JWT_SECRET); + payload = await verifyRefreshToken(refreshToken, c.env.JWT_SECRET); + } catch { + clearRefreshCookie(c); + return c.json({ error: 'Invalid or expired refresh token' }, 401); + } + try { // C-2: Check denylist BEFORE rotating — prevents use of already-revoked tokens if (await isJtiDenylisted(c.env.LINKS_KV, payload.jti)) { clearRefreshCookie(c); return c.json({ error: 'Unauthorized' }, 401); } - // S1: Compute remaining TTL from token's actual exp claim - const refreshTtl = - Math.max(payload.exp - Math.floor(Date.now() / 1000), 0) + 60; - await denylistJti(c.env.LINKS_KV, payload.jti, refreshTtl); - const user = await c.env.DB.prepare( `SELECT * FROM ${tbl(c.env, 'users')} WHERE id = ?1`, ) @@ -586,12 +589,19 @@ auth.post('/refresh', async (c) => { return c.json({ error: 'Unauthorized' }, 401); } + // Rotate only after every read succeeded, so a D1 failure can't burn a + // still-valid refresh token. S1: TTL from the token's actual exp claim. + const refreshTtl = + Math.max(payload.exp - Math.floor(Date.now() / 1000), 0) + 60; + await denylistJti(c.env.LINKS_KV, payload.jti, refreshTtl); + const tokens = await issueTokens(user, c.env.JWT_SECRET); setRefreshCookie(c, tokens.refreshToken); return c.json({ accessToken: tokens.accessToken }); - } catch { - clearRefreshCookie(c); - return c.json({ error: 'Invalid or expired refresh token' }, 401); + } catch (err) { + // Infrastructure failure: keep the cookie, report a retryable 503. + console.error('refresh failed', err instanceof Error ? err.name : err); + return c.json({ error: 'Service temporarily unavailable' }, 503); } });