From 12b5786e66bc98d562a45cc649b7fceddf32aeef Mon Sep 17 00:00:00 2001 From: Todos Date: Sun, 18 Oct 2026 08:43:23 +0800 Subject: [PATCH 1/3] feat(api): JSON 404 for unknown /api, biome 2.5.15, error codes - Unmatched /api/* now returns a JSON 404 with a stable code instead of the SPA fallback (covers wrong-method hits on known routes too); added tests. - Upgrade @biomejs/biome to 2.5.15; fix the new noUnsafeOptionalChaining rule in admin stats. No mass reformatting. - Add APP_URL/APP_NAME/RP_ID/APP_ORIGIN to the .dev.vars example in both READMEs. - Add stable error codes to auth/link responses; the frontend maps known codes through i18n (en + zh-CN) and falls back to the original message otherwise. Checkpoint: xRCMbetOksxXJ9bM_fzBA --- README.md | 4 + README.zh-CN.md | 4 + apps/web/package.json | 2 +- apps/web/src/api/client.ts | 9 +- apps/web/src/i18n/index.tsx | 5 + apps/web/src/i18n/locales/en.ts | 31 + apps/web/src/i18n/locales/zh-CN.ts | 30 + apps/web/src/lib/apiErrorCodes.test.ts | 61 ++ apps/web/src/lib/apiErrorCodes.ts | 32 + apps/web/src/lib/toast.ts | 35 +- apps/web/src/pages/admin/AdminLinksPage.tsx | 2 +- .../web/src/pages/admin/AdminSettingsPage.tsx | 8 +- apps/web/src/pages/admin/AdminUsersPage.tsx | 6 +- .../web/src/pages/auth/ForgotPasswordPage.tsx | 4 +- apps/web/src/pages/auth/LoginPage.tsx | 2 +- apps/web/src/pages/auth/RegisterPage.tsx | 6 +- apps/web/src/pages/auth/TwoFactorPage.tsx | 8 +- apps/web/src/pages/dashboard/LinksPage.tsx | 6 +- apps/web/src/pages/dashboard/SettingsPage.tsx | 18 +- apps/worker/src/index.ts | 14 +- apps/worker/src/lib/errors.ts | 16 + apps/worker/src/routes/admin.ts | 8 +- apps/worker/src/routes/auth.ts | 575 +++++++++++++----- apps/worker/src/routes/links.ts | 124 ++-- apps/worker/test/routing.test.ts | 100 +++ biome.json | 2 +- package.json | 2 +- pnpm-lock.yaml | 74 +-- 28 files changed, 926 insertions(+), 262 deletions(-) create mode 100644 apps/web/src/lib/apiErrorCodes.test.ts create mode 100644 apps/web/src/lib/apiErrorCodes.ts create mode 100644 apps/worker/src/lib/errors.ts create mode 100644 apps/worker/test/routing.test.ts diff --git a/README.md b/README.md index 82c3898..45e6631 100644 --- a/README.md +++ b/README.md @@ -145,6 +145,10 @@ Navigate to your deployed URL and register — the first account is automaticall ```bash # 1. Create apps/worker/.dev.vars cat > apps/worker/.dev.vars << 'EOF' +APP_URL=http://localhost:8787 +APP_NAME=ShortLink +RP_ID=localhost +APP_ORIGIN=http://localhost:8787 JWT_SECRET=dev-secret-at-least-32-characters-long TOTP_ENCRYPTION_KEY=0000000000000000000000000000000000000000000000000000000000000000 SETUP_SECRET=local-setup-secret diff --git a/README.zh-CN.md b/README.zh-CN.md index 7bd31c9..3c11691 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -140,6 +140,10 @@ curl -X POST https://your-worker.workers.dev/setup \ ```bash # 1. 创建 apps/worker/.dev.vars cat > apps/worker/.dev.vars << 'EOF' +APP_URL=http://localhost:8787 +APP_NAME=ShortLink +RP_ID=localhost +APP_ORIGIN=http://localhost:8787 JWT_SECRET=dev-secret-at-least-32-characters-long TOTP_ENCRYPTION_KEY=0000000000000000000000000000000000000000000000000000000000000000 SETUP_SECRET=local-setup-secret diff --git a/apps/web/package.json b/apps/web/package.json index 1f37f3e..4967367 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -7,7 +7,7 @@ "dev": "vite", "build": "tsc --noEmit && vite build", "typecheck": "tsc --noEmit", - "test": "node --test src/api/client.test.ts src/lib/utils.test.ts", + "test": "node --test src/api/client.test.ts src/lib/utils.test.ts src/lib/apiErrorCodes.test.ts", "preview": "vite preview" }, "dependencies": { diff --git a/apps/web/src/api/client.ts b/apps/web/src/api/client.ts index d3d433d..a93bc39 100644 --- a/apps/web/src/api/client.ts +++ b/apps/web/src/api/client.ts @@ -44,6 +44,7 @@ const BASE = '/api'; interface ApiError { error: string; + code?: string; } // FE-R4: react-query only retries transport failures and server errors. A 4xx @@ -51,11 +52,13 @@ interface ApiError { // delays the error the user needs to see. export class ApiRequestError extends Error { readonly status: number; + readonly code?: string; - constructor(message: string, status: number) { + constructor(message: string, status: number, code?: string) { super(message); this.name = 'ApiRequestError'; this.status = status; + this.code = code; } } @@ -136,7 +139,7 @@ async function request( const err = (await retryRes .json() .catch(() => ({ error: 'Request failed' }))) as ApiError; - throw new ApiRequestError(err.error, retryRes.status); + throw new ApiRequestError(err.error, retryRes.status, err.code); } return retryRes.json() as Promise; } @@ -155,7 +158,7 @@ async function request( const err = (await res .json() .catch(() => ({ error: 'Request failed' }))) as ApiError; - throw new ApiRequestError(err.error, res.status); + throw new ApiRequestError(err.error, res.status, err.code); } if (res.status === 204) return undefined as T; diff --git a/apps/web/src/i18n/index.tsx b/apps/web/src/i18n/index.tsx index 2966df5..09ccd8f 100644 --- a/apps/web/src/i18n/index.tsx +++ b/apps/web/src/i18n/index.tsx @@ -31,6 +31,11 @@ type DeepKeys = { export type TranslationKey = DeepKeys; +export type TFunction = ( + key: TranslationKey, + params?: Record, +) => string; + function resolve(obj: unknown, path: string): string { const parts = path.split('.'); let curr = obj; diff --git a/apps/web/src/i18n/locales/en.ts b/apps/web/src/i18n/locales/en.ts index 16353eb..a3ad51c 100644 --- a/apps/web/src/i18n/locales/en.ts +++ b/apps/web/src/i18n/locales/en.ts @@ -261,6 +261,37 @@ export const en = { appNameUpdated: 'App name updated', emailSettingsSaved: 'Email settings saved', }, + errors: { + emailOrUsernameTaken: 'This email or username is already taken.', + invalidCredentials: 'Incorrect email or password.', + invalidEmail: 'Please enter a valid email address.', + invalidUsername: + 'Username must be 3–32 characters using letters, numbers, dashes, or underscores.', + passwordTooShort: 'Password must be at least 8 characters.', + passwordTooLong: 'Password is too long.', + registrationDisabled: 'Registration is currently disabled.', + tooManyRequests: 'Too many requests. Please try again later.', + tooManyLoginAttempts: 'Too many login attempts. Please try again later.', + tooManyAttempts: 'Too many attempts. Please try again later.', + invalidCode: 'Invalid or incorrect code.', + currentPasswordIncorrect: 'Current password is incorrect.', + totpAlreadyEnabled: 'TOTP is already enabled.', + accountDisabled: 'This account is disabled.', + codeAlreadyUsed: 'This code was already used. Please use a new one.', + emailSendFailed: 'Failed to send the email. Please try again.', + invalidUrl: 'Please enter a valid URL.', + onlyHttpHttpsAllowed: 'Only http and https URLs are allowed.', + invalidSlug: + 'Invalid slug. Use 1–50 letters, numbers, dashes, or underscores.', + slugReserved: 'This slug is reserved.', + slugTaken: 'This slug is already taken.', + destinationUrlRequired: 'Please enter a destination URL.', + linkNotFound: 'Link not found.', + expiresAtInPast: 'Expiry must be in the future.', + failedToCreateLink: 'Failed to create the link.', + notFound: 'Not found.', + internalServerError: 'Internal server error.', + }, } as const; type DeepString = { diff --git a/apps/web/src/i18n/locales/zh-CN.ts b/apps/web/src/i18n/locales/zh-CN.ts index 439e1cf..86e9e77 100644 --- a/apps/web/src/i18n/locales/zh-CN.ts +++ b/apps/web/src/i18n/locales/zh-CN.ts @@ -251,4 +251,34 @@ export const zhCN: Translations = { appNameUpdated: '应用名称已更新', emailSettingsSaved: '邮件设置已保存', }, + errors: { + emailOrUsernameTaken: '该邮箱或用户名已被占用。', + invalidCredentials: '邮箱或密码不正确。', + invalidEmail: '请输入有效的邮箱地址。', + invalidUsername: + '用户名需为 3–32 个字符,可使用字母、数字、短横线或下划线。', + passwordTooShort: '密码至少需要 8 个字符。', + passwordTooLong: '密码过长。', + registrationDisabled: '当前已关闭注册。', + tooManyRequests: '请求过于频繁,请稍后再试。', + tooManyLoginAttempts: '登录尝试次数过多,请稍后再试。', + tooManyAttempts: '尝试次数过多,请稍后再试。', + invalidCode: '验证码无效或错误。', + currentPasswordIncorrect: '当前密码不正确。', + totpAlreadyEnabled: 'TOTP 已启用。', + accountDisabled: '该账户已被禁用。', + codeAlreadyUsed: '该验证码已被使用,请使用新的验证码。', + emailSendFailed: '邮件发送失败,请重试。', + invalidUrl: '请输入有效的 URL。', + onlyHttpHttpsAllowed: '仅支持 http 和 https 链接。', + invalidSlug: '别名无效,请使用 1–50 个字母、数字、短横线或下划线。', + slugReserved: '该别名为保留字。', + slugTaken: '该别名已被占用。', + destinationUrlRequired: '请输入目标 URL。', + linkNotFound: '链接不存在。', + expiresAtInPast: '过期时间必须在将来。', + failedToCreateLink: '创建链接失败。', + notFound: '未找到。', + internalServerError: '服务器内部错误。', + }, }; diff --git a/apps/web/src/lib/apiErrorCodes.test.ts b/apps/web/src/lib/apiErrorCodes.test.ts new file mode 100644 index 0000000..ae8ffcd --- /dev/null +++ b/apps/web/src/lib/apiErrorCodes.test.ts @@ -0,0 +1,61 @@ +import assert from 'node:assert/strict'; +import { describe, test } from 'node:test'; +import { en } from '../i18n/locales/en.ts'; +import { zhCN } from '../i18n/locales/zh-CN.ts'; +import { API_ERROR_CODES } from './apiErrorCodes.ts'; + +// Verifies every backend error code the frontend knows maps to a real, +// non-empty string in both locales, so the "backend error → localized toast" +// path can never silently fall back to English for a known code. + +function resolve(obj: unknown, path: string): unknown { + let curr = obj; + for (const p of path.split('.')) { + if (curr == null || typeof curr !== 'object') return undefined; + curr = (curr as Record)[p]; + } + return curr; +} + +describe('API_ERROR_CODES', () => { + test('every code maps to a non-empty string in both locales', () => { + for (const [code, key] of Object.entries(API_ERROR_CODES)) { + const enValue = resolve(en, key); + const zhValue = resolve(zhCN, key); + assert.equal( + typeof enValue, + 'string', + `${code} → ${key} must resolve to a string in en`, + ); + assert.equal( + typeof zhValue, + 'string', + `${code} → ${key} must resolve to a string in zh-CN`, + ); + assert.ok((enValue as string).length > 0, `${key} (en) is empty`); + assert.ok((zhValue as string).length > 0, `${key} (zh-CN) is empty`); + } + }); + + test('EMAIL_OR_USERNAME_TAKEN localizes in both languages', () => { + assert.equal( + resolve(en, 'errors.emailOrUsernameTaken'), + 'This email or username is already taken.', + ); + assert.equal( + resolve(zhCN, 'errors.emailOrUsernameTaken'), + '该邮箱或用户名已被占用。', + ); + }); + + test('INVALID_CREDENTIALS localizes in both languages', () => { + assert.equal( + resolve(en, 'errors.invalidCredentials'), + 'Incorrect email or password.', + ); + assert.equal( + resolve(zhCN, 'errors.invalidCredentials'), + '邮箱或密码不正确。', + ); + }); +}); diff --git a/apps/web/src/lib/apiErrorCodes.ts b/apps/web/src/lib/apiErrorCodes.ts new file mode 100644 index 0000000..3f81e59 --- /dev/null +++ b/apps/web/src/lib/apiErrorCodes.ts @@ -0,0 +1,32 @@ +// Maps backend error codes to i18n dot-path keys (defined in +// i18n/locales/*.ts). Kept as plain data (no React, no path aliases) so the +// mapping can be unit-tested and cross-checked against both locales. +export const API_ERROR_CODES: Record = { + EMAIL_OR_USERNAME_TAKEN: 'errors.emailOrUsernameTaken', + INVALID_CREDENTIALS: 'errors.invalidCredentials', + INVALID_EMAIL: 'errors.invalidEmail', + INVALID_USERNAME: 'errors.invalidUsername', + PASSWORD_TOO_SHORT: 'errors.passwordTooShort', + PASSWORD_TOO_LONG: 'errors.passwordTooLong', + REGISTRATION_DISABLED: 'errors.registrationDisabled', + TOO_MANY_REQUESTS: 'errors.tooManyRequests', + TOO_MANY_LOGIN_ATTEMPTS: 'errors.tooManyLoginAttempts', + TOO_MANY_ATTEMPTS: 'errors.tooManyAttempts', + INVALID_CODE: 'errors.invalidCode', + CURRENT_PASSWORD_INCORRECT: 'errors.currentPasswordIncorrect', + TOTP_ALREADY_ENABLED: 'errors.totpAlreadyEnabled', + ACCOUNT_DISABLED: 'errors.accountDisabled', + CODE_ALREADY_USED: 'errors.codeAlreadyUsed', + EMAIL_SEND_FAILED: 'errors.emailSendFailed', + INVALID_URL: 'errors.invalidUrl', + ONLY_HTTP_HTTPS_ALLOWED: 'errors.onlyHttpHttpsAllowed', + INVALID_SLUG: 'errors.invalidSlug', + SLUG_RESERVED: 'errors.slugReserved', + SLUG_TAKEN: 'errors.slugTaken', + DESTINATION_URL_REQUIRED: 'errors.destinationUrlRequired', + LINK_NOT_FOUND: 'errors.linkNotFound', + EXPIRES_AT_IN_PAST: 'errors.expiresAtInPast', + FAILED_TO_CREATE_LINK: 'errors.failedToCreateLink', + NOT_FOUND: 'errors.notFound', + INTERNAL_SERVER_ERROR: 'errors.internalServerError', +}; diff --git a/apps/web/src/lib/toast.ts b/apps/web/src/lib/toast.ts index a81cdb8..4b1b5be 100644 --- a/apps/web/src/lib/toast.ts +++ b/apps/web/src/lib/toast.ts @@ -1,12 +1,35 @@ import { toast } from 'sonner'; -import { isSessionExpiredError } from '@/api/client'; +import { ApiRequestError, isSessionExpiredError } from '@/api/client'; +import type { TFunction, TranslationKey } from '@/i18n'; +import { API_ERROR_CODES } from './apiErrorCodes'; + +// Resolve the message to show for an API error: a localized string when the +// error carries a known code, otherwise the backend's original `error` text, or +// the caller's `fallback` when neither is available. Returns null for a +// session-expired error so callers stay quiet (AuthProvider shows one toast). +export function resolveApiError( + error: unknown, + t: TFunction, + fallback: string, +): string | null { + if (isSessionExpiredError(error)) return null; + const code = error instanceof ApiRequestError ? error.code : undefined; + if (code) { + const key = API_ERROR_CODES[code] as TranslationKey | undefined; + if (key) return t(key); + } + return error instanceof Error && error.message ? error.message : fallback; +} // #6: an expired session fails every in-flight request at once. AuthProvider // shows a single "Session expired" toast, so per-request error toasts must stay // quiet — otherwise the user sees the same message once per request. -export function toastApiError(error: unknown, fallback: string): void { - if (isSessionExpiredError(error)) return; - toast.error( - error instanceof Error && error.message ? error.message : fallback, - ); +export function toastApiError( + error: unknown, + fallback: string, + t: TFunction, +): void { + const message = resolveApiError(error, t, fallback); + if (message === null) return; + toast.error(message); } diff --git a/apps/web/src/pages/admin/AdminLinksPage.tsx b/apps/web/src/pages/admin/AdminLinksPage.tsx index 4a53ae3..8e4c058 100644 --- a/apps/web/src/pages/admin/AdminLinksPage.tsx +++ b/apps/web/src/pages/admin/AdminLinksPage.tsx @@ -43,7 +43,7 @@ export default function AdminLinksPage() { toast.success(t('toast.linkDeleted')); setDeleteId(null); }, - onError: (err) => toastApiError(err, t('toast.deleteLinkFailed')), + onError: (err) => toastApiError(err, t('toast.deleteLinkFailed'), t), }); return ( diff --git a/apps/web/src/pages/admin/AdminSettingsPage.tsx b/apps/web/src/pages/admin/AdminSettingsPage.tsx index 7d77ab0..d21d585 100644 --- a/apps/web/src/pages/admin/AdminSettingsPage.tsx +++ b/apps/web/src/pages/admin/AdminSettingsPage.tsx @@ -86,7 +86,7 @@ export default function AdminSettingsPage() { ); } catch (err) { setRegistrationEnabled(!enabled); - toastApiError(err, t('toast.requestFailed')); + toastApiError(err, t('toast.requestFailed'), t); } }; @@ -103,7 +103,7 @@ export default function AdminSettingsPage() { ); } catch (err) { setRequireEmailVerification(!enabled); - toastApiError(err, t('toast.requestFailed')); + toastApiError(err, t('toast.requestFailed'), t); } }; @@ -115,7 +115,7 @@ export default function AdminSettingsPage() { reloadAppConfig(); toast.success(t('toast.appNameUpdated')); } catch (err) { - toastApiError(err, t('toast.requestFailed')); + toastApiError(err, t('toast.requestFailed'), t); } finally { setSavingAppName(false); } @@ -141,7 +141,7 @@ export default function AdminSettingsPage() { await adminApi.updateSettings(payload); toast.success(t('toast.emailSettingsSaved')); } catch (err) { - toastApiError(err, t('toast.requestFailed')); + toastApiError(err, t('toast.requestFailed'), t); } finally { setSavingEmail(false); } diff --git a/apps/web/src/pages/admin/AdminUsersPage.tsx b/apps/web/src/pages/admin/AdminUsersPage.tsx index 177cc90..167dcd8 100644 --- a/apps/web/src/pages/admin/AdminUsersPage.tsx +++ b/apps/web/src/pages/admin/AdminUsersPage.tsx @@ -51,7 +51,7 @@ export default function AdminUsersPage() { queryClient.invalidateQueries({ queryKey: ['admin-users'] }); toast.success(t('toast.userUpdated')); }, - onError: (err) => toastApiError(err, t('toast.updateUserFailed')), + onError: (err) => toastApiError(err, t('toast.updateUserFailed'), t), }); const deleteMutation = useMutation({ @@ -61,7 +61,7 @@ export default function AdminUsersPage() { toast.success(t('toast.userDeleted')); setDeleteId(null); }, - onError: (err) => toastApiError(err, t('toast.deleteUserFailed')), + onError: (err) => toastApiError(err, t('toast.deleteUserFailed'), t), }); // FE-C5: while any mutation (update or delete) is in flight for a user, all of @@ -297,7 +297,7 @@ function CreateUserDialog({ setForm({ email: '', username: '', password: '', role: 'user' }); onCreated(); } catch (err) { - toastApiError(err, t('toast.createUserFailed')); + toastApiError(err, t('toast.createUserFailed'), t); } finally { setLoading(false); } diff --git a/apps/web/src/pages/auth/ForgotPasswordPage.tsx b/apps/web/src/pages/auth/ForgotPasswordPage.tsx index aeeeef0..38a6df8 100644 --- a/apps/web/src/pages/auth/ForgotPasswordPage.tsx +++ b/apps/web/src/pages/auth/ForgotPasswordPage.tsx @@ -56,7 +56,7 @@ export default function ForgotPasswordPage() { await authApi.verifyResetCode(email, code); setStep('password'); } catch (err) { - toastApiError(err, t('toast.invalidCode')); + toastApiError(err, t('toast.invalidCode'), t); } finally { setLoading(false); } @@ -75,7 +75,7 @@ export default function ForgotPasswordPage() { toast.success(t('auth.resetSuccess')); navigate('/login'); } catch (err) { - toastApiError(err, t('toast.resetPasswordFailed')); + toastApiError(err, t('toast.resetPasswordFailed'), t); } finally { setLoading(false); } diff --git a/apps/web/src/pages/auth/LoginPage.tsx b/apps/web/src/pages/auth/LoginPage.tsx index 87d2a8d..47206b8 100644 --- a/apps/web/src/pages/auth/LoginPage.tsx +++ b/apps/web/src/pages/auth/LoginPage.tsx @@ -47,7 +47,7 @@ export default function LoginPage() { navigate(next ?? '/dashboard', { replace: true }); } } catch (err) { - toastApiError(err, t('toast.loginFailed')); + toastApiError(err, t('toast.loginFailed'), t); } finally { setLoading(false); } diff --git a/apps/web/src/pages/auth/RegisterPage.tsx b/apps/web/src/pages/auth/RegisterPage.tsx index 678f3c1..4fc8534 100644 --- a/apps/web/src/pages/auth/RegisterPage.tsx +++ b/apps/web/src/pages/auth/RegisterPage.tsx @@ -63,7 +63,7 @@ export default function RegisterPage() { navigate('/login'); } } catch (err) { - toastApiError(err, t('toast.registrationFailed')); + toastApiError(err, t('toast.registrationFailed'), t); } finally { setLoading(false); } @@ -91,7 +91,7 @@ export default function RegisterPage() { await refreshUser(); navigate('/dashboard', { replace: true }); } catch (err) { - toastApiError(err, t('toast.verificationFailed')); + toastApiError(err, t('toast.verificationFailed'), t); } finally { setLoading(false); } @@ -105,7 +105,7 @@ export default function RegisterPage() { startCountdown(RESEND_COUNTDOWN_SECONDS); toast.success(t('auth.verifyCodeResent')); } catch (err) { - toastApiError(err, t('toast.sendCodeFailed')); + toastApiError(err, t('toast.sendCodeFailed'), t); } finally { setLoading(false); } diff --git a/apps/web/src/pages/auth/TwoFactorPage.tsx b/apps/web/src/pages/auth/TwoFactorPage.tsx index c1b1c17..75bee6b 100644 --- a/apps/web/src/pages/auth/TwoFactorPage.tsx +++ b/apps/web/src/pages/auth/TwoFactorPage.tsx @@ -72,7 +72,7 @@ export default function TwoFactorPage() { const result = await authApi.totpVerify(pendingToken, code); await handleSuccess(result); } catch (err) { - toastApiError(err, t('toast.invalidCode')); + toastApiError(err, t('toast.invalidCode'), t); } finally { setLoading(false); } @@ -85,7 +85,7 @@ export default function TwoFactorPage() { setOtpSent(true); toast.success(t('toast.codeSent')); } catch (err) { - toastApiError(err, t('toast.sendCodeFailed')); + toastApiError(err, t('toast.sendCodeFailed'), t); } finally { setLoading(false); } @@ -98,7 +98,7 @@ export default function TwoFactorPage() { const result = await authApi.emailOtpVerify(pendingToken, code); await handleSuccess(result); } catch (err) { - toastApiError(err, t('toast.invalidCode')); + toastApiError(err, t('toast.invalidCode'), t); } finally { setLoading(false); } @@ -117,7 +117,7 @@ export default function TwoFactorPage() { ); await handleSuccess(result); } catch (err) { - toastApiError(err, t('toast.passkeyAuthFailed')); + toastApiError(err, t('toast.passkeyAuthFailed'), t); } finally { setLoading(false); } diff --git a/apps/web/src/pages/dashboard/LinksPage.tsx b/apps/web/src/pages/dashboard/LinksPage.tsx index 0ebb18d..298e2ea 100644 --- a/apps/web/src/pages/dashboard/LinksPage.tsx +++ b/apps/web/src/pages/dashboard/LinksPage.tsx @@ -58,7 +58,7 @@ export default function LinksPage() { queryClient.invalidateQueries({ queryKey: ['links'] }); setDeleteId(null); }, - onError: (err) => toastApiError(err, t('toast.deleteLinkFailed')), + onError: (err) => toastApiError(err, t('toast.deleteLinkFailed'), t), }); return ( @@ -256,7 +256,7 @@ function CreateLinkDialog({ setCustomExpiry(''); onCreated(); } catch (err) { - toastApiError(err, t('toast.createLinkFailed')); + toastApiError(err, t('toast.createLinkFailed'), t); } finally { setLoading(false); } @@ -397,7 +397,7 @@ export function EditLinkDialog({ toast.success(t('toast.linkUpdated')); onUpdated(); } catch (err) { - toastApiError(err, t('toast.updateLinkFailed')); + toastApiError(err, t('toast.updateLinkFailed'), t); } finally { setLoading(false); } diff --git a/apps/web/src/pages/dashboard/SettingsPage.tsx b/apps/web/src/pages/dashboard/SettingsPage.tsx index a592f3f..63ef760 100644 --- a/apps/web/src/pages/dashboard/SettingsPage.tsx +++ b/apps/web/src/pages/dashboard/SettingsPage.tsx @@ -139,7 +139,7 @@ function ChangePasswordCard() { toast.success(t('toast.passwordUpdated')); setForm({ currentPassword: '', newPassword: '', confirm: '' }); } catch (err) { - toastApiError(err, t('toast.requestFailed')); + toastApiError(err, t('toast.requestFailed'), t); } finally { setLoading(false); } @@ -239,7 +239,7 @@ function TotpCard({ setSetupData(data); setShowSetup(true); } catch (err) { - toastApiError(err, t('toast.requestFailed')); + toastApiError(err, t('toast.requestFailed'), t); } finally { setLoading(false); } @@ -254,7 +254,7 @@ function TotpCard({ toast.success(t('toast.totpEnabled')); onUpdate(); } catch (err) { - toastApiError(err, t('toast.invalidCode')); + toastApiError(err, t('toast.invalidCode'), t); } finally { setLoading(false); } @@ -269,7 +269,7 @@ function TotpCard({ setDisablePassword(''); onUpdate(); } catch (err) { - toastApiError(err, t('toast.requestFailed')); + toastApiError(err, t('toast.requestFailed'), t); } finally { setLoading(false); } @@ -460,7 +460,7 @@ function PasskeyCard({ onUpdate }: { onUpdate: () => Promise }) { queryClient.invalidateQueries({ queryKey: ['passkeys'] }); onUpdate(); } catch (err) { - toastApiError(err, t('toast.registrationFailed')); + toastApiError(err, t('toast.registrationFailed'), t); } finally { setLoading(false); } @@ -477,7 +477,7 @@ function PasskeyCard({ onUpdate }: { onUpdate: () => Promise }) { queryClient.invalidateQueries({ queryKey: ['passkeys'] }); onUpdate(); } catch (err) { - toastApiError(err, t('toast.requestFailed')); + toastApiError(err, t('toast.requestFailed'), t); } finally { setLoading(false); } @@ -606,7 +606,7 @@ function EmailOtpCard({ setCodeSent(true); startCountdown(RESEND_COUNTDOWN_SECONDS); } catch (err) { - toastApiError(err, t('toast.sendCodeFailed')); + toastApiError(err, t('toast.sendCodeFailed'), t); } finally { setLoading(false); } @@ -623,7 +623,7 @@ function EmailOtpCard({ setVerifyCode(''); onUpdate(); } catch (err) { - toastApiError(err, t('toast.requestFailed')); + toastApiError(err, t('toast.requestFailed'), t); } finally { setLoading(false); } @@ -645,7 +645,7 @@ function EmailOtpCard({ setDisablePassword(''); onUpdate(); } catch (err) { - toastApiError(err, t('toast.requestFailed')); + toastApiError(err, t('toast.requestFailed'), t); } finally { setLoading(false); } diff --git a/apps/worker/src/index.ts b/apps/worker/src/index.ts index 8c92e98..9ced1c2 100644 --- a/apps/worker/src/index.ts +++ b/apps/worker/src/index.ts @@ -1,6 +1,7 @@ import { Hono } from 'hono'; 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 { RESERVED_SLUGS } from './lib/slug.js'; @@ -32,7 +33,7 @@ app.onError((err, c) => { requestId: c.get('requestId'), }), ); - return c.json({ error: 'Internal Server Error' }, 500); + return apiError(c, 500, 'INTERNAL_SERVER_ERROR', 'Internal Server Error'); }); // ─── Security headers ───────────────────────────────────────────────────────── @@ -117,6 +118,15 @@ app.route('/setup', setupRoutes); // ─── Health check ───────────────────────────────────────────────────────────── app.get('/api/health', (c) => c.json({ status: 'ok', timestamp: Date.now() })); +// ─── Unmatched API requests ─────────────────────────────────────────────────── +// Any /api/* request that no route above handled (unknown path, or a known path +// with the wrong HTTP method — e.g. GET on a POST-only endpoint) must return a +// JSON 404, never the SPA's index.html. The SPA fallback below stays for +// non-/api paths only. +app.all('/api/*', (c) => { + return apiError(c, 404, 'NOT_FOUND', 'Not found'); +}); + // ─── Short link redirect ─────────────────────────────────────────────────────── const SPA_PREFIXES = new Set([...RESERVED_SLUGS].map((s) => `/${s}`)); @@ -146,6 +156,8 @@ app.all('*', async (c) => { return new Response(res.body, { status: res.status, headers }); }); +export { app }; + export default { fetch: app.fetch, diff --git a/apps/worker/src/lib/errors.ts b/apps/worker/src/lib/errors.ts new file mode 100644 index 0000000..99ecc7f --- /dev/null +++ b/apps/worker/src/lib/errors.ts @@ -0,0 +1,16 @@ +import type { Context } from 'hono'; +import type { ContentfulStatusCode } from 'hono/utils/http-status'; + +// Stable, machine-readable error codes so the frontend can localize error +// messages instead of rendering the backend's English prose verbatim. The +// `error` field is kept for backward compatibility with older clients; new +// clients map `code` through i18n and fall back to `error` when the code is +// unknown. +export function apiError( + c: Context, + status: ContentfulStatusCode, + code: string, + error: string, +) { + return c.json({ error, code }, status); +} diff --git a/apps/worker/src/routes/admin.ts b/apps/worker/src/routes/admin.ts index 27eb723..d166c07 100644 --- a/apps/worker/src/routes/admin.ts +++ b/apps/worker/src/routes/admin.ts @@ -59,10 +59,10 @@ admin.get('/stats', async (c) => { ]); return c.json({ - users: (users?.results[0] as { n: number }).n, - links: (links?.results[0] as { n: number }).n, - clicksToday: (clicksToday?.results[0] as { n: number }).n, - clicksTotal: (clicksTotal?.results[0] as { n: number }).n, + users: (users?.results[0] as { n: number } | undefined)?.n ?? 0, + links: (links?.results[0] as { n: number } | undefined)?.n ?? 0, + clicksToday: (clicksToday?.results[0] as { n: number } | undefined)?.n ?? 0, + clicksTotal: (clicksTotal?.results[0] as { n: number } | undefined)?.n ?? 0, }); }); diff --git a/apps/worker/src/routes/auth.ts b/apps/worker/src/routes/auth.ts index 4829cac..5e97794 100644 --- a/apps/worker/src/routes/auth.ts +++ b/apps/worker/src/routes/auth.ts @@ -13,6 +13,7 @@ import { sendEmail, verifyEmailHtml, } from '../lib/email.js'; +import { apiError } from '../lib/errors.js'; import { signAccessToken, signPendingToken, @@ -172,10 +173,15 @@ auth.post('/register', async (c) => { const body = await c.req .json<{ email: string; username: string; password: string }>() .catch(() => null); - if (!body) return c.json({ error: 'Invalid JSON body' }, 400); + if (!body) return apiError(c, 400, 'INVALID_JSON_BODY', 'Invalid JSON body'); if (!body.email || !body.username || !body.password) { - return c.json({ error: 'email, username, and password are required' }, 400); + return apiError( + c, + 400, + 'EMAIL_USERNAME_PASSWORD_REQUIRED', + 'email, username, and password are required', + ); } const email = body.email.trim().toLowerCase(); @@ -188,27 +194,36 @@ auth.post('/register', async (c) => { clientIp(c), ); if (!registerAllowed) { - return c.json({ error: 'Too many requests. Try again later.' }, 429); + return apiError( + c, + 429, + 'TOO_MANY_REQUESTS', + 'Too many requests. Try again later.', + ); } // M4: Input validation if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { - return c.json({ error: 'Invalid email address' }, 400); + return apiError(c, 400, 'INVALID_EMAIL', 'Invalid email address'); } if (!/^[a-zA-Z0-9_-]{3,32}$/.test(username)) { - return c.json( - { - error: - 'Username must be 3–32 characters: letters, numbers, dashes, or underscores', - }, + return apiError( + c, 400, + 'INVALID_USERNAME', + 'Username must be 3–32 characters: letters, numbers, dashes, or underscores', ); } if (password.length < 8) { - return c.json({ error: 'Password must be at least 8 characters' }, 400); + return apiError( + c, + 400, + 'PASSWORD_TOO_SHORT', + 'Password must be at least 8 characters', + ); } if (password.length > 256) { - return c.json({ error: 'Password too long' }, 400); + return apiError(c, 400, 'PASSWORD_TOO_LONG', 'Password too long'); } // H3: Check registration status before INSERT @@ -220,7 +235,12 @@ auth.post('/register', async (c) => { if (!isFirstUser) { const enabled = await isRegistrationEnabled(c.env); if (!enabled) { - return c.json({ error: 'Registration is currently disabled' }, 403); + return apiError( + c, + 403, + 'REGISTRATION_DISABLED', + 'Registration is currently disabled', + ); } } @@ -231,7 +251,12 @@ auth.post('/register', async (c) => { .bind(email, username) .first(); if (existing) { - return c.json({ error: 'Email or username already taken' }, 409); + return apiError( + c, + 409, + 'EMAIL_OR_USERNAME_TAKEN', + 'Email or username already taken', + ); } const passwordHash = await hashPassword(password); @@ -261,9 +286,15 @@ auth.post('/register', async (c) => { ); if (newUser === 'taken') { - return c.json({ error: 'Email or username already taken' }, 409); + return apiError( + c, + 409, + 'EMAIL_OR_USERNAME_TAKEN', + 'Email or username already taken', + ); } - if (!newUser) return c.json({ error: 'Failed to create user' }, 500); + if (!newUser) + return apiError(c, 500, 'FAILED_TO_CREATE_USER', 'Failed to create user'); const code = generateOtp(6); const codeHash = await sha256(code); @@ -282,9 +313,11 @@ auth.post('/register', async (c) => { await c.env.DB.prepare(`DELETE FROM ${tbl(c.env, 'users')} WHERE id = ?1`) .bind(newUser.id) .run(); - return c.json( - { error: 'Failed to send verification email. Please try again.' }, + return apiError( + c, 500, + 'EMAIL_SEND_FAILED', + 'Failed to send verification email. Please try again.', ); } @@ -313,9 +346,15 @@ auth.post('/register', async (c) => { ); if (result === 'taken') { - return c.json({ error: 'Email or username already taken' }, 409); + return apiError( + c, + 409, + 'EMAIL_OR_USERNAME_TAKEN', + 'Email or username already taken', + ); } - if (!result) return c.json({ error: 'Failed to create user' }, 500); + if (!result) + return apiError(c, 500, 'FAILED_TO_CREATE_USER', 'Failed to create user'); return c.json( { @@ -337,7 +376,7 @@ auth.post('/verify-email', async (c) => { const body = await c.req .json<{ userId: string; code: string }>() .catch(() => null); - if (!body) return c.json({ error: 'Invalid JSON body' }, 400); + if (!body) return apiError(c, 400, 'INVALID_JSON_BODY', 'Invalid JSON body'); if (!body.userId || !body.code || body.code.length > 6) { return c.json({ error: 'userId and code required' }, 400); } @@ -364,9 +403,11 @@ auth.post('/verify-email', async (c) => { } if (verification.attempts >= 3) { - return c.json( - { error: 'Too many failed attempts. Please request a new code.' }, + return apiError( + c, 429, + 'TOO_MANY_ATTEMPTS', + 'Too many failed attempts. Please request a new code.', ); } @@ -377,7 +418,7 @@ auth.post('/verify-email', async (c) => { ) .bind(verification.id) .run(); - return c.json({ error: 'Invalid code' }, 401); + return apiError(c, 401, 'INVALID_CODE', 'Invalid code'); } await c.env.DB.batch([ @@ -407,7 +448,7 @@ auth.post('/verify-email', async (c) => { // ───────────────────────────────────────────────────────────────────────────── auth.post('/resend-verify-email', async (c) => { const body = await c.req.json<{ userId: string }>().catch(() => null); - if (!body) return c.json({ error: 'Invalid JSON body' }, 400); + if (!body) return apiError(c, 400, 'INVALID_JSON_BODY', 'Invalid JSON body'); if (!body.userId) return c.json({ error: 'userId required' }, 400); const user = await c.env.DB.prepare( @@ -421,7 +462,12 @@ auth.post('/resend-verify-email', async (c) => { const allowed = await checkOtpRateLimit(c.env.LINKS_KV, user.email); if (!allowed) { - return c.json({ error: 'Too many requests. Try again later.' }, 429); + return apiError( + c, + 429, + 'TOO_MANY_REQUESTS', + 'Too many requests. Try again later.', + ); } const code = generateOtp(6); @@ -436,9 +482,11 @@ auth.post('/resend-verify-email', async (c) => { html: verifyEmailHtml(appName, code), }); } catch { - return c.json( - { error: 'Failed to send verification email. Please try again.' }, + return apiError( + c, 500, + 'EMAIL_SEND_FAILED', + 'Failed to send verification email. Please try again.', ); } @@ -464,10 +512,15 @@ auth.post('/login', async (c) => { const body = await c.req .json<{ email: string; password: string }>() .catch(() => null); - if (!body) return c.json({ error: 'Invalid JSON body' }, 400); + if (!body) return apiError(c, 400, 'INVALID_JSON_BODY', 'Invalid JSON body'); if (!body.email || !body.password) { - return c.json({ error: 'email and password are required' }, 400); + return apiError( + c, + 400, + 'EMAIL_PASSWORD_REQUIRED', + 'email and password are required', + ); } const email = body.email.trim().toLowerCase(); @@ -479,9 +532,11 @@ auth.post('/login', async (c) => { clientIp(c), ); if (!loginAllowed) { - return c.json( - { error: 'Too many login attempts. Please try again later.' }, + return apiError( + c, 429, + 'TOO_MANY_LOGIN_ATTEMPTS', + 'Too many login attempts. Please try again later.', ); } @@ -494,12 +549,12 @@ auth.post('/login', async (c) => { if (!user?.is_active) { // S4: Run dummy PBKDF2 to normalise response time and prevent user enumeration await verifyPassword(body.password, TIMING_DUMMY_HASH); - return c.json({ error: 'Invalid credentials' }, 401); + return apiError(c, 401, 'INVALID_CREDENTIALS', 'Invalid credentials'); } const valid = await verifyPassword(body.password, user.password_hash); if (!valid) { - return c.json({ error: 'Invalid credentials' }, 401); + return apiError(c, 401, 'INVALID_CREDENTIALS', 'Invalid credentials'); } // C1: Reset failed counter on successful login @@ -564,7 +619,7 @@ auth.post('/logout', requireAuth, async (c) => { auth.post('/refresh', async (c) => { // H4: Read refresh token from HttpOnly cookie const refreshToken = getRefreshCookie(c); - if (!refreshToken) return c.json({ error: 'Unauthorized' }, 401); + if (!refreshToken) return apiError(c, 401, 'UNAUTHORIZED', 'Unauthorized'); // 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. @@ -580,7 +635,7 @@ auth.post('/refresh', async (c) => { // 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); + return apiError(c, 401, 'UNAUTHORIZED', 'Unauthorized'); } const user = await c.env.DB.prepare( @@ -588,13 +643,14 @@ auth.post('/refresh', async (c) => { ) .bind(payload.sub) .first(); - if (!user?.is_active) return c.json({ error: 'User not found' }, 401); + if (!user?.is_active) + return apiError(c, 401, 'USER_NOT_FOUND', 'User not found'); // 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); + return apiError(c, 401, 'UNAUTHORIZED', 'Unauthorized'); } // Rotate only after every read succeeded, so a D1 failure can't burn a @@ -636,7 +692,7 @@ auth.get('/me', requireAuth, async (c) => { > >(); - if (!user) return c.json({ error: 'Not found' }, 404); + if (!user) return apiError(c, 404, 'NOT_FOUND', 'Not found'); return c.json({ user }); }); @@ -650,15 +706,25 @@ auth.post('/change-password', requireAuth, async (c) => { const body = await c.req .json<{ currentPassword: string; newPassword: string }>() .catch(() => null); - if (!body) return c.json({ error: 'Invalid JSON body' }, 400); + if (!body) return apiError(c, 400, 'INVALID_JSON_BODY', 'Invalid JSON body'); if (!body.currentPassword || !body.newPassword) { - return c.json({ error: 'currentPassword and newPassword required' }, 400); + return apiError( + c, + 400, + 'CURRENT_PASSWORD_NEW_PASSWORD_REQUIRED', + 'currentPassword and newPassword required', + ); } if (body.newPassword.length < 8) { - return c.json({ error: 'New password must be at least 8 characters' }, 400); + return apiError( + c, + 400, + 'PASSWORD_TOO_SHORT', + 'New password must be at least 8 characters', + ); } if (body.newPassword.length > 256) { - return c.json({ error: 'Password too long' }, 400); + return apiError(c, 400, 'PASSWORD_TOO_LONG', 'Password too long'); } const user = await c.env.DB.prepare( @@ -666,10 +732,16 @@ auth.post('/change-password', requireAuth, async (c) => { ) .bind(userId) .first(); - if (!user) return c.json({ error: 'Not found' }, 404); + if (!user) return apiError(c, 404, 'NOT_FOUND', 'Not found'); const valid = await verifyPassword(body.currentPassword, user.password_hash); - if (!valid) return c.json({ error: 'Current password is incorrect' }, 401); + if (!valid) + return apiError( + c, + 401, + 'CURRENT_PASSWORD_INCORRECT', + 'Current password is incorrect', + ); const newHash = await hashPassword(body.newPassword); await c.env.DB.prepare( @@ -717,7 +789,7 @@ auth.post('/2fa/totp/setup', requireAuth, async (c) => { .first>(); if (user?.totp_enabled) { - return c.json({ error: 'TOTP is already enabled' }, 409); + return apiError(c, 409, 'TOTP_ALREADY_ENABLED', 'TOTP is already enabled'); } const secret = generateTotpSecret(); @@ -738,10 +810,10 @@ auth.post('/2fa/totp/setup', requireAuth, async (c) => { auth.post('/2fa/totp/confirm', requireAuth, async (c) => { const userId = c.get('userId'); const body = await c.req.json<{ code: string }>().catch(() => null); - if (!body) return c.json({ error: 'Invalid JSON body' }, 400); + if (!body) return apiError(c, 400, 'INVALID_JSON_BODY', 'Invalid JSON body'); // R6-L1: TOTP confirm only ever validates a 6-digit code — reject anything longer if (!body.code || body.code.length > 6) - return c.json({ error: 'code required' }, 400); + return apiError(c, 400, 'CODE_REQUIRED', 'code required'); // R4-L4: Prevent brute-force of the 6-digit code during setup (max 10 per 2 min) const confirmAttempts = await incrementTotpConfirmAttempts( @@ -749,9 +821,11 @@ auth.post('/2fa/totp/confirm', requireAuth, async (c) => { userId, ); if (confirmAttempts > 10) { - return c.json( - { error: 'Too many attempts. Please set up TOTP again.' }, + return apiError( + c, 429, + 'TOO_MANY_ATTEMPTS', + 'Too many attempts. Please set up TOTP again.', ); } @@ -762,16 +836,21 @@ auth.post('/2fa/totp/confirm', requireAuth, async (c) => { .first>(); if (!user?.totp_secret) - return c.json({ error: 'No TOTP setup in progress' }, 400); + return apiError( + c, + 400, + 'NO_TOTP_SETUP_IN_PROGRESS', + 'No TOTP setup in progress', + ); if (user.totp_enabled) - return c.json({ error: 'TOTP already confirmed' }, 409); + return apiError(c, 409, 'TOTP_ALREADY_CONFIRMED', 'TOTP already confirmed'); const secret = await decryptTotpSecret( user.totp_secret, c.env.TOTP_ENCRYPTION_KEY, ); if (!verifyTotp(secret, body.code)) { - return c.json({ error: 'Invalid code' }, 400); + return apiError(c, 400, 'INVALID_CODE', 'Invalid code'); } await resetTotpConfirmAttempts(c.env.LINKS_KV, userId); @@ -798,16 +877,26 @@ auth.delete('/2fa/totp', requireAuth, async (c) => { .json<{ currentPassword?: string }>() .catch(() => ({}) as { currentPassword?: string }); if (!body.currentPassword) - return c.json({ error: 'currentPassword required' }, 400); + return apiError( + c, + 400, + 'CURRENT_PASSWORD_REQUIRED', + 'currentPassword required', + ); const user = await c.env.DB.prepare( `SELECT password_hash FROM ${tbl(c.env, 'users')} WHERE id = ?1`, ) .bind(userId) .first>(); - if (!user) return c.json({ error: 'Not found' }, 404); + if (!user) return apiError(c, 404, 'NOT_FOUND', 'Not found'); if (!(await verifyPassword(body.currentPassword, user.password_hash))) { - return c.json({ error: 'Current password is incorrect' }, 401); + return apiError( + c, + 401, + 'CURRENT_PASSWORD_INCORRECT', + 'Current password is incorrect', + ); } await c.env.DB.prepare( @@ -823,32 +912,54 @@ auth.post('/2fa/totp/verify', async (c) => { const body = await c.req .json<{ pendingToken: string; code: string }>() .catch(() => null); - if (!body) return c.json({ error: 'Invalid JSON body' }, 400); + if (!body) return apiError(c, 400, 'INVALID_JSON_BODY', 'Invalid JSON body'); if (!body.pendingToken || !body.code || body.code.length > 16) { - return c.json({ error: 'pendingToken and code required' }, 400); + return apiError( + c, + 400, + 'PENDING_TOKEN_AND_CODE_REQUIRED', + 'pendingToken and code required', + ); } let pending: Awaited>; try { pending = await verifyPendingToken(body.pendingToken, c.env.JWT_SECRET); } catch { - return c.json({ error: 'Invalid or expired pending token' }, 401); + return apiError( + c, + 401, + 'INVALID_OR_EXPIRED_PENDING_TOKEN', + 'Invalid or expired pending token', + ); } const storedUserId = await getPending2fa(c.env.LINKS_KV, pending.jti); if (!storedUserId) { - return c.json({ error: 'Invalid or expired pending token' }, 401); + return apiError( + c, + 401, + 'INVALID_OR_EXPIRED_PENDING_TOKEN', + 'Invalid or expired pending token', + ); } if (storedUserId !== pending.sub) { - return c.json({ error: 'Invalid or expired pending token' }, 401); + return apiError( + c, + 401, + 'INVALID_OR_EXPIRED_PENDING_TOKEN', + 'Invalid or expired pending token', + ); } const attempts = await increment2faAttempts(c.env.LINKS_KV, pending.jti); if (attempts > 5) { await deletePending2fa(c.env.LINKS_KV, pending.jti); - return c.json( - { error: 'Too many failed attempts. Please log in again.' }, + return apiError( + c, 429, + 'TOO_MANY_ATTEMPTS', + 'Too many failed attempts. Please log in again.', ); } @@ -859,9 +970,10 @@ auth.post('/2fa/totp/verify', async (c) => { .first(); if (!user?.totp_secret || !user.totp_enabled) { - return c.json({ error: 'TOTP not configured' }, 400); + return apiError(c, 400, 'TOTP_NOT_CONFIGURED', 'TOTP not configured'); } - if (!user.is_active) return c.json({ error: 'Account is disabled' }, 403); + if (!user.is_active) + return apiError(c, 403, 'ACCOUNT_DISABLED', 'Account is disabled'); const secret = await decryptTotpSecret( user.totp_secret, @@ -878,9 +990,11 @@ auth.post('/2fa/totp/verify', async (c) => { .bind(user.id, body.code) .run(); if (result.meta.changes === 0) { - return c.json( - { error: 'Code already used. Please wait for the next code.' }, + return apiError( + c, 401, + 'CODE_ALREADY_USED', + 'Code already used. Please wait for the next code.', ); } } @@ -891,7 +1005,7 @@ auth.post('/2fa/totp/verify', async (c) => { try { codes = JSON.parse(user.totp_backup_codes); } catch { - return c.json({ error: 'Invalid code' }, 401); + return apiError(c, 401, 'INVALID_CODE', 'Invalid code'); } const oldCodesJson = user.totp_backup_codes; const hashedBuf = new TextEncoder().encode(hashed); @@ -919,7 +1033,7 @@ auth.post('/2fa/totp/verify', async (c) => { } if (!isTotpCode && !isBackup) { - return c.json({ error: 'Invalid code' }, 401); + return apiError(c, 401, 'INVALID_CODE', 'Invalid code'); } await deletePending2fa(c.env.LINKS_KV, pending.jti); @@ -947,7 +1061,7 @@ auth.post('/2fa/email-otp/enable', requireAuth, async (c) => { const body = await c.req.json<{ code: string }>().catch(() => null); if (!body?.code || body.code.length > 6) - return c.json({ error: 'code required' }, 400); + return apiError(c, 400, 'CODE_REQUIRED', 'code required'); const now = Math.floor(Date.now() / 1000); const verification = await c.env.DB.prepare( @@ -957,15 +1071,19 @@ auth.post('/2fa/email-otp/enable', requireAuth, async (c) => { .first<{ id: string; code_hash: string; attempts: number }>(); if (!verification) - return c.json( - { error: 'No valid verification code. Please request a new one.' }, + return apiError( + c, 400, + 'NO_VALID_VERIFICATION_CODE', + 'No valid verification code. Please request a new one.', ); if (verification.attempts >= 3) { - return c.json( - { error: 'Too many failed attempts. Please request a new code.' }, + return apiError( + c, 429, + 'TOO_MANY_ATTEMPTS', + 'Too many failed attempts. Please request a new code.', ); } @@ -976,7 +1094,7 @@ auth.post('/2fa/email-otp/enable', requireAuth, async (c) => { ) .bind(verification.id) .run(); - return c.json({ error: 'Invalid code' }, 400); + return apiError(c, 400, 'INVALID_CODE', 'Invalid code'); } await c.env.DB.batch([ @@ -996,7 +1114,12 @@ auth.post('/2fa/email-otp/send-verify', requireAuth, async (c) => { const allowed = await checkOtpRateLimit(c.env.LINKS_KV, userEmail); if (!allowed) { - return c.json({ error: 'Too many requests. Try again later.' }, 429); + return apiError( + c, + 429, + 'TOO_MANY_REQUESTS', + 'Too many requests. Try again later.', + ); } const code = generateOtp(6); @@ -1011,9 +1134,11 @@ auth.post('/2fa/email-otp/send-verify', requireAuth, async (c) => { html: otpEmailHtml(appName, code), }); } catch { - return c.json( - { error: 'Failed to send verification email. Please try again.' }, + return apiError( + c, 500, + 'EMAIL_SEND_FAILED', + 'Failed to send verification email. Please try again.', ); } @@ -1040,16 +1165,26 @@ auth.delete('/2fa/email-otp', requireAuth, async (c) => { .json<{ currentPassword?: string }>() .catch(() => ({}) as { currentPassword?: string }); if (!body.currentPassword) - return c.json({ error: 'currentPassword required' }, 400); + return apiError( + c, + 400, + 'CURRENT_PASSWORD_REQUIRED', + 'currentPassword required', + ); const user = await c.env.DB.prepare( `SELECT password_hash FROM ${tbl(c.env, 'users')} WHERE id = ?1`, ) .bind(userId) .first>(); - if (!user) return c.json({ error: 'Not found' }, 404); + if (!user) return apiError(c, 404, 'NOT_FOUND', 'Not found'); if (!(await verifyPassword(body.currentPassword, user.password_hash))) { - return c.json({ error: 'Current password is incorrect' }, 401); + return apiError( + c, + 401, + 'CURRENT_PASSWORD_INCORRECT', + 'Current password is incorrect', + ); } await c.env.DB.prepare( @@ -1063,23 +1198,38 @@ auth.delete('/2fa/email-otp', requireAuth, async (c) => { // POST /api/auth/2fa/email-otp/send auth.post('/2fa/email-otp/send', async (c) => { const body = await c.req.json<{ pendingToken: string }>().catch(() => null); - if (!body) return c.json({ error: 'Invalid JSON body' }, 400); + if (!body) return apiError(c, 400, 'INVALID_JSON_BODY', 'Invalid JSON body'); if (!body.pendingToken) - return c.json({ error: 'pendingToken required' }, 400); + return apiError(c, 400, 'PENDING_TOKEN_REQUIRED', 'pendingToken required'); let pending: Awaited>; try { pending = await verifyPendingToken(body.pendingToken, c.env.JWT_SECRET); } catch { - return c.json({ error: 'Invalid or expired pending token' }, 401); + return apiError( + c, + 401, + 'INVALID_OR_EXPIRED_PENDING_TOKEN', + 'Invalid or expired pending token', + ); } const storedUserId = await getPending2fa(c.env.LINKS_KV, pending.jti); if (!storedUserId) { - return c.json({ error: 'Invalid or expired pending token' }, 401); + return apiError( + c, + 401, + 'INVALID_OR_EXPIRED_PENDING_TOKEN', + 'Invalid or expired pending token', + ); } if (storedUserId !== pending.sub) { - return c.json({ error: 'Invalid or expired pending token' }, 401); + return apiError( + c, + 401, + 'INVALID_OR_EXPIRED_PENDING_TOKEN', + 'Invalid or expired pending token', + ); } const user = await c.env.DB.prepare( @@ -1087,14 +1237,25 @@ auth.post('/2fa/email-otp/send', async (c) => { ) .bind(pending.sub) .first(); - if (!user) return c.json({ error: 'User not found' }, 404); - if (!user.is_active) return c.json({ error: 'Account is disabled' }, 403); + if (!user) return apiError(c, 404, 'USER_NOT_FOUND', 'User not found'); + if (!user.is_active) + return apiError(c, 403, 'ACCOUNT_DISABLED', 'Account is disabled'); if (!user.email_2fa_enabled) - return c.json({ error: 'Email OTP is not enabled for this account' }, 400); + return apiError( + c, + 400, + 'EMAIL_OTP_NOT_ENABLED', + 'Email OTP is not enabled for this account', + ); const allowed = await checkOtpRateLimit(c.env.LINKS_KV, user.email); if (!allowed) { - return c.json({ error: 'Too many OTP requests. Try again later.' }, 429); + return apiError( + c, + 429, + 'TOO_MANY_OTP_REQUESTS', + 'Too many OTP requests. Try again later.', + ); } const code = generateOtp(6); @@ -1110,9 +1271,11 @@ auth.post('/2fa/email-otp/send', async (c) => { html: otpEmailHtml(appName, code), }); } catch { - return c.json( - { error: 'Failed to send verification email. Please try again.' }, + return apiError( + c, 500, + 'EMAIL_SEND_FAILED', + 'Failed to send verification email. Please try again.', ); } @@ -1136,32 +1299,54 @@ auth.post('/2fa/email-otp/verify', async (c) => { const body = await c.req .json<{ pendingToken: string; code: string }>() .catch(() => null); - if (!body) return c.json({ error: 'Invalid JSON body' }, 400); + if (!body) return apiError(c, 400, 'INVALID_JSON_BODY', 'Invalid JSON body'); if (!body.pendingToken || !body.code || body.code.length > 6) { - return c.json({ error: 'pendingToken and code required' }, 400); + return apiError( + c, + 400, + 'PENDING_TOKEN_AND_CODE_REQUIRED', + 'pendingToken and code required', + ); } let pending: Awaited>; try { pending = await verifyPendingToken(body.pendingToken, c.env.JWT_SECRET); } catch { - return c.json({ error: 'Invalid or expired pending token' }, 401); + return apiError( + c, + 401, + 'INVALID_OR_EXPIRED_PENDING_TOKEN', + 'Invalid or expired pending token', + ); } const storedUserId = await getPending2fa(c.env.LINKS_KV, pending.jti); if (!storedUserId) { - return c.json({ error: 'Invalid or expired pending token' }, 401); + return apiError( + c, + 401, + 'INVALID_OR_EXPIRED_PENDING_TOKEN', + 'Invalid or expired pending token', + ); } if (storedUserId !== pending.sub) { - return c.json({ error: 'Invalid or expired pending token' }, 401); + return apiError( + c, + 401, + 'INVALID_OR_EXPIRED_PENDING_TOKEN', + 'Invalid or expired pending token', + ); } const attempts = await increment2faAttempts(c.env.LINKS_KV, pending.jti); if (attempts > 5) { await deletePending2fa(c.env.LINKS_KV, pending.jti); - return c.json( - { error: 'Too many failed attempts. Please log in again.' }, + return apiError( + c, 429, + 'TOO_MANY_ATTEMPTS', + 'Too many failed attempts. Please log in again.', ); } @@ -1170,10 +1355,16 @@ auth.post('/2fa/email-otp/verify', async (c) => { ) .bind(pending.sub) .first(); - if (!user) return c.json({ error: 'User not found' }, 404); - if (!user.is_active) return c.json({ error: 'Account is disabled' }, 403); + if (!user) return apiError(c, 404, 'USER_NOT_FOUND', 'User not found'); + if (!user.is_active) + return apiError(c, 403, 'ACCOUNT_DISABLED', 'Account is disabled'); if (!user.email_2fa_enabled) - return c.json({ error: 'Email OTP is not enabled for this account' }, 400); + return apiError( + c, + 400, + 'EMAIL_OTP_NOT_ENABLED', + 'Email OTP is not enabled for this account', + ); const now = Math.floor(Date.now() / 1000); const verification = await c.env.DB.prepare( @@ -1183,16 +1374,20 @@ auth.post('/2fa/email-otp/verify', async (c) => { .first<{ id: string; code_hash: string; attempts: number }>(); if (!verification) { - return c.json( - { error: 'No valid OTP found. Please request a new code.' }, + return apiError( + c, 400, + 'NO_VALID_OTP', + 'No valid OTP found. Please request a new code.', ); } if (verification.attempts >= 3) { - return c.json( - { error: 'Too many failed attempts. Please request a new code.' }, + return apiError( + c, 429, + 'TOO_MANY_ATTEMPTS', + 'Too many failed attempts. Please request a new code.', ); } @@ -1203,7 +1398,7 @@ auth.post('/2fa/email-otp/verify', async (c) => { ) .bind(verification.id) .run(); - return c.json({ error: 'Invalid code' }, 401); + return apiError(c, 401, 'INVALID_CODE', 'Invalid code'); } await c.env.DB.prepare( @@ -1291,14 +1486,19 @@ auth.post('/2fa/passkey/register-verify', requireAuth, async (c) => { name?: string; }>() .catch(() => null); - if (!body) return c.json({ error: 'Invalid JSON body' }, 400); + if (!body) return apiError(c, 400, 'INVALID_JSON_BODY', 'Invalid JSON body'); const stored = await getAndDeletePasskeyChallenge( c.env.LINKS_KV, body.challengeId, ); if (stored?.type !== 'registration' || stored.userId !== userId) { - return c.json({ error: 'Invalid or expired challenge' }, 400); + return apiError( + c, + 400, + 'INVALID_OR_EXPIRED_CHALLENGE', + 'Invalid or expired challenge', + ); } if (body.name && body.name.length > 64) { @@ -1317,11 +1517,21 @@ auth.post('/2fa/passkey/register-verify', requireAuth, async (c) => { c.env.APP_ORIGIN, ); } catch { - return c.json({ error: 'Passkey verification failed' }, 400); + return apiError( + c, + 400, + 'PASSKEY_VERIFICATION_FAILED', + 'Passkey verification failed', + ); } if (!verification.verified || !verification.registrationInfo) { - return c.json({ error: 'Passkey verification failed' }, 400); + return apiError( + c, + 400, + 'PASSKEY_VERIFICATION_FAILED', + 'Passkey verification failed', + ); } const { @@ -1369,16 +1579,26 @@ auth.delete('/2fa/passkey/:id', requireAuth, async (c) => { .json<{ currentPassword?: string }>() .catch(() => ({}) as { currentPassword?: string }); if (!body.currentPassword) - return c.json({ error: 'currentPassword required' }, 400); + return apiError( + c, + 400, + 'CURRENT_PASSWORD_REQUIRED', + 'currentPassword required', + ); const userCheck = await c.env.DB.prepare( `SELECT password_hash FROM ${tbl(c.env, 'users')} WHERE id = ?1`, ) .bind(userId) .first>(); - if (!userCheck) return c.json({ error: 'Not found' }, 404); + if (!userCheck) return apiError(c, 404, 'NOT_FOUND', 'Not found'); if (!(await verifyPassword(body.currentPassword, userCheck.password_hash))) { - return c.json({ error: 'Current password is incorrect' }, 401); + return apiError( + c, + 401, + 'CURRENT_PASSWORD_INCORRECT', + 'Current password is incorrect', + ); } await c.env.DB.prepare( @@ -1407,23 +1627,38 @@ auth.delete('/2fa/passkey/:id', requireAuth, async (c) => { // POST /api/auth/2fa/passkey/verify-options (during login flow) auth.post('/2fa/passkey/verify-options', async (c) => { const body = await c.req.json<{ pendingToken: string }>().catch(() => null); - if (!body) return c.json({ error: 'Invalid JSON body' }, 400); + if (!body) return apiError(c, 400, 'INVALID_JSON_BODY', 'Invalid JSON body'); if (!body.pendingToken) - return c.json({ error: 'pendingToken required' }, 400); + return apiError(c, 400, 'PENDING_TOKEN_REQUIRED', 'pendingToken required'); let pending: Awaited>; try { pending = await verifyPendingToken(body.pendingToken, c.env.JWT_SECRET); } catch { - return c.json({ error: 'Invalid or expired pending token' }, 401); + return apiError( + c, + 401, + 'INVALID_OR_EXPIRED_PENDING_TOKEN', + 'Invalid or expired pending token', + ); } const storedUserId = await getPending2fa(c.env.LINKS_KV, pending.jti); if (!storedUserId) { - return c.json({ error: 'Invalid or expired pending token' }, 401); + return apiError( + c, + 401, + 'INVALID_OR_EXPIRED_PENDING_TOKEN', + 'Invalid or expired pending token', + ); } if (storedUserId !== pending.sub) { - return c.json({ error: 'Invalid or expired pending token' }, 401); + return apiError( + c, + 401, + 'INVALID_OR_EXPIRED_PENDING_TOKEN', + 'Invalid or expired pending token', + ); } const optionsAttempts = await incrementPasskeyOptsAttempts( @@ -1432,7 +1667,12 @@ auth.post('/2fa/passkey/verify-options', async (c) => { ); if (optionsAttempts > 10) { await deletePending2fa(c.env.LINKS_KV, pending.jti); - return c.json({ error: 'Too many requests. Please log in again.' }, 429); + return apiError( + c, + 429, + 'TOO_MANY_ATTEMPTS', + 'Too many requests. Please log in again.', + ); } const userActive = await c.env.DB.prepare( @@ -1441,7 +1681,7 @@ auth.post('/2fa/passkey/verify-options', async (c) => { .bind(pending.sub) .first>(); if (!userActive?.is_active) - return c.json({ error: 'Account is disabled' }, 403); + return apiError(c, 403, 'ACCOUNT_DISABLED', 'Account is disabled'); const passkeys = await c.env.DB.prepare( `SELECT id, transports FROM ${tbl(c.env, 'passkeys')} WHERE user_id = ?1`, @@ -1478,21 +1718,36 @@ auth.post('/2fa/passkey/verify', async (c) => { challengeId: string; }>() .catch(() => null); - if (!body) return c.json({ error: 'Invalid JSON body' }, 400); + if (!body) return apiError(c, 400, 'INVALID_JSON_BODY', 'Invalid JSON body'); let pending: Awaited>; try { pending = await verifyPendingToken(body.pendingToken, c.env.JWT_SECRET); } catch { - return c.json({ error: 'Invalid or expired pending token' }, 401); + return apiError( + c, + 401, + 'INVALID_OR_EXPIRED_PENDING_TOKEN', + 'Invalid or expired pending token', + ); } const storedUserId = await getPending2fa(c.env.LINKS_KV, pending.jti); if (!storedUserId) { - return c.json({ error: 'Invalid or expired pending token' }, 401); + return apiError( + c, + 401, + 'INVALID_OR_EXPIRED_PENDING_TOKEN', + 'Invalid or expired pending token', + ); } if (storedUserId !== pending.sub) { - return c.json({ error: 'Invalid or expired pending token' }, 401); + return apiError( + c, + 401, + 'INVALID_OR_EXPIRED_PENDING_TOKEN', + 'Invalid or expired pending token', + ); } const passkeyAttempts = await increment2faAttempts( @@ -1501,9 +1756,11 @@ auth.post('/2fa/passkey/verify', async (c) => { ); if (passkeyAttempts > 5) { await deletePending2fa(c.env.LINKS_KV, pending.jti); - return c.json( - { error: 'Too many failed attempts. Please log in again.' }, + return apiError( + c, 429, + 'TOO_MANY_ATTEMPTS', + 'Too many failed attempts. Please log in again.', ); } @@ -1516,7 +1773,12 @@ auth.post('/2fa/passkey/verify', async (c) => { stored.userId !== pending.sub || stored.pendingJti !== pending.jti ) { - return c.json({ error: 'Invalid or expired challenge' }, 400); + return apiError( + c, + 400, + 'INVALID_OR_EXPIRED_CHALLENGE', + 'Invalid or expired challenge', + ); } const passkey = await c.env.DB.prepare( @@ -1525,7 +1787,8 @@ auth.post('/2fa/passkey/verify', async (c) => { .bind((body.response as { id: string }).id, pending.sub) .first(); - if (!passkey) return c.json({ error: 'Passkey not found' }, 404); + if (!passkey) + return apiError(c, 404, 'PASSKEY_NOT_FOUND', 'Passkey not found'); let verification: Awaited>; try { @@ -1537,19 +1800,30 @@ auth.post('/2fa/passkey/verify', async (c) => { passkey, ); } catch { - return c.json({ error: 'Passkey verification failed' }, 400); + return apiError( + c, + 400, + 'PASSKEY_VERIFICATION_FAILED', + 'Passkey verification failed', + ); } if (!verification.verified) - return c.json({ error: 'Passkey verification failed' }, 401); + return apiError( + c, + 401, + 'PASSKEY_VERIFICATION_FAILED', + 'Passkey verification failed', + ); const user = await c.env.DB.prepare( `SELECT * FROM ${tbl(c.env, 'users')} WHERE id = ?1`, ) .bind(pending.sub) .first(); - if (!user) return c.json({ error: 'User not found' }, 404); - if (!user.is_active) return c.json({ error: 'Account is disabled' }, 403); + if (!user) return apiError(c, 404, 'USER_NOT_FOUND', 'User not found'); + if (!user.is_active) + return apiError(c, 403, 'ACCOUNT_DISABLED', 'Account is disabled'); await c.env.DB.prepare( `UPDATE ${tbl(c.env, 'passkeys')} SET counter = ?1, last_used_at = unixepoch() WHERE id = ?2`, @@ -1603,9 +1877,11 @@ auth.post('/verify-reset-code', async (c) => { if (!verification) return c.json({ error: 'Invalid or expired code' }, 400); if (verification.attempts >= 3) { - return c.json( - { error: 'Too many failed attempts. Please request a new code.' }, + return apiError( + c, 429, + 'TOO_MANY_ATTEMPTS', + 'Too many failed attempts. Please request a new code.', ); } @@ -1616,7 +1892,7 @@ auth.post('/verify-reset-code', async (c) => { ) .bind(verification.id) .run(); - return c.json({ error: 'Invalid code' }, 400); + return apiError(c, 400, 'INVALID_CODE', 'Invalid code'); } return c.json({ success: true }); @@ -1639,7 +1915,12 @@ auth.post('/forgot-password', async (c) => { clientIp(c), ); if (!allowed || !ipAllowed) { - return c.json({ error: 'Too many requests. Try again later.' }, 429); + return apiError( + c, + 429, + 'TOO_MANY_REQUESTS', + 'Too many requests. Try again later.', + ); } const user = await c.env.DB.prepare( @@ -1698,15 +1979,21 @@ auth.post('/reset-password', async (c) => { const body = await c.req .json<{ email: string; code: string; newPassword: string }>() .catch(() => null); - if (!body) return c.json({ error: 'Invalid JSON body' }, 400); + if (!body) return apiError(c, 400, 'INVALID_JSON_BODY', 'Invalid JSON body'); if (!body.email || !body.code || !body.newPassword) { return c.json({ error: 'email, code, and newPassword are required' }, 400); } - if (body.code.length > 6) return c.json({ error: 'Invalid code' }, 400); + if (body.code.length > 6) + return apiError(c, 400, 'INVALID_CODE', 'Invalid code'); if (body.newPassword.length < 8) - return c.json({ error: 'Password must be at least 8 characters' }, 400); + return apiError( + c, + 400, + 'PASSWORD_TOO_SHORT', + 'Password must be at least 8 characters', + ); if (body.newPassword.length > 256) - return c.json({ error: 'Password too long' }, 400); + return apiError(c, 400, 'PASSWORD_TOO_LONG', 'Password too long'); const email = body.email.trim().toLowerCase(); @@ -1727,9 +2014,11 @@ auth.post('/reset-password', async (c) => { if (!verification) return c.json({ error: 'Invalid or expired code' }, 400); if (verification.attempts >= 3) { - return c.json( - { error: 'Too many failed attempts. Please request a new code.' }, + return apiError( + c, 429, + 'TOO_MANY_ATTEMPTS', + 'Too many failed attempts. Please request a new code.', ); } @@ -1740,7 +2029,7 @@ auth.post('/reset-password', async (c) => { ) .bind(verification.id) .run(); - return c.json({ error: 'Invalid code' }, 400); + return apiError(c, 400, 'INVALID_CODE', 'Invalid code'); } const newHash = await hashPassword(body.newPassword); diff --git a/apps/worker/src/routes/links.ts b/apps/worker/src/routes/links.ts index aa81dcb..af52c48 100644 --- a/apps/worker/src/routes/links.ts +++ b/apps/worker/src/routes/links.ts @@ -1,5 +1,6 @@ import { Hono } from 'hono'; import { tbl } from '../lib/db.js'; +import { apiError } from '../lib/errors.js'; import { deleteCachedLink } from '../lib/kv.js'; import { parsePagination } from '../lib/params.js'; import { generateSlug, isReservedSlug, isValidSlug } from '../lib/slug.js'; @@ -92,29 +93,46 @@ links.post('/', async (c) => { expiresAt?: number | null; }>() .catch(() => null); - if (!body) return c.json({ error: 'Invalid JSON body' }, 400); + if (!body) return apiError(c, 400, 'INVALID_JSON_BODY', 'Invalid JSON body'); if (!body.destinationUrl) { - return c.json({ error: 'destinationUrl is required' }, 400); + return apiError( + c, + 400, + 'DESTINATION_URL_REQUIRED', + 'destinationUrl is required', + ); } if (body.destinationUrl.length > 2048) { - return c.json( - { error: 'destinationUrl must be 2048 characters or fewer' }, + return apiError( + c, 400, + 'DESTINATION_URL_TOO_LONG', + 'destinationUrl must be 2048 characters or fewer', ); } if (body.title && body.title.length > 255) { - return c.json({ error: 'title must be 255 characters or fewer' }, 400); + return apiError( + c, + 400, + 'TITLE_TOO_LONG', + 'title must be 255 characters or fewer', + ); } try { const parsed = new URL(body.destinationUrl); if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { - return c.json({ error: 'Only http and https URLs are allowed' }, 400); + return apiError( + c, + 400, + 'ONLY_HTTP_HTTPS_ALLOWED', + 'Only http and https URLs are allowed', + ); } } catch { - return c.json({ error: 'Invalid URL' }, 400); + return apiError(c, 400, 'INVALID_URL', 'Invalid URL'); } const L = tbl(c.env, 'links'); @@ -122,16 +140,15 @@ links.post('/', async (c) => { if (body.customSlug) { const customSlug = body.customSlug.trim(); if (!isValidSlug(customSlug)) { - return c.json( - { - error: - 'Slug must be 1-50 alphanumeric characters, dashes, or underscores', - }, + return apiError( + c, 400, + 'INVALID_SLUG', + 'Slug must be 1-50 alphanumeric characters, dashes, or underscores', ); } if (isReservedSlug(customSlug)) { - return c.json({ error: 'This slug is reserved' }, 400); + return apiError(c, 400, 'SLUG_RESERVED', 'This slug is reserved'); } const existing = await c.env.DB.prepare( `SELECT 1 FROM ${L} WHERE slug = ?1`, @@ -139,7 +156,7 @@ links.post('/', async (c) => { .bind(customSlug) .first(); if (existing) { - return c.json({ error: 'This slug is already taken' }, 409); + return apiError(c, 409, 'SLUG_TAKEN', 'This slug is already taken'); } slug = customSlug; } else { @@ -150,18 +167,30 @@ links.post('/', async (c) => { const now = Math.floor(Date.now() / 1000); if (body.expiresAt) { if (!Number.isSafeInteger(body.expiresAt)) { - return c.json( - { error: 'expiresAt must be an integer Unix timestamp' }, + return apiError( + c, 400, + 'EXPIRES_AT_INVALID', + 'expiresAt must be an integer Unix timestamp', ); } if (body.expiresAt <= now) { - return c.json({ error: 'expiresAt must be in the future' }, 400); + return apiError( + c, + 400, + 'EXPIRES_AT_IN_PAST', + 'expiresAt must be in the future', + ); } expiresAt = body.expiresAt; } else if (body.expiryDays && body.expiryDays > 0) { if (body.expiryDays > 3650) { - return c.json({ error: 'expiryDays must be 3650 or fewer' }, 400); + return apiError( + c, + 400, + 'EXPIRY_DAYS_TOO_LARGE', + 'expiryDays must be 3650 or fewer', + ); } expiresAt = now + body.expiryDays * 86400; } @@ -174,7 +203,8 @@ links.post('/', async (c) => { .bind(userId, slug, body.destinationUrl, body.title ?? null, expiresAt) .first(); - if (!row) return c.json({ error: 'Failed to create link' }, 500); + if (!row) + return apiError(c, 500, 'FAILED_TO_CREATE_LINK', 'Failed to create link'); return c.json({ link: row }, 201); }); @@ -196,7 +226,7 @@ links.get('/:id', async (c) => { .bind(...binds) .first(); - if (!row) return c.json({ error: 'Link not found' }, 404); + if (!row) return apiError(c, 404, 'LINK_NOT_FOUND', 'Link not found'); return c.json({ link: row }); }); @@ -217,7 +247,7 @@ links.put('/:id', async (c) => { .bind(...(role === 'admin' ? [id] : [id, userId])) .first(); - if (!existing) return c.json({ error: 'Link not found' }, 404); + if (!existing) return apiError(c, 404, 'LINK_NOT_FOUND', 'Link not found'); const body = await c.req .json<{ @@ -229,45 +259,57 @@ links.put('/:id', async (c) => { customSlug?: string; }>() .catch(() => null); - if (!body) return c.json({ error: 'Invalid JSON body' }, 400); + if (!body) return apiError(c, 400, 'INVALID_JSON_BODY', 'Invalid JSON body'); let newSlug = existing.slug; if (body.customSlug !== undefined && body.customSlug !== existing.slug) { const customSlug = body.customSlug.trim(); if (!isValidSlug(customSlug)) { - return c.json({ error: 'Invalid slug' }, 400); + return apiError(c, 400, 'INVALID_SLUG', 'Invalid slug'); } if (isReservedSlug(customSlug)) { - return c.json({ error: 'This slug is reserved' }, 400); + return apiError(c, 400, 'SLUG_RESERVED', 'This slug is reserved'); } const conflict = await c.env.DB.prepare( `SELECT 1 FROM ${L} WHERE slug = ?1 AND id != ?2`, ) .bind(customSlug, id) .first(); - if (conflict) return c.json({ error: 'Slug already taken' }, 409); + if (conflict) return apiError(c, 409, 'SLUG_TAKEN', 'Slug already taken'); newSlug = customSlug; } if (body.destinationUrl) { if (body.destinationUrl.length > 2048) { - return c.json( - { error: 'destinationUrl must be 2048 characters or fewer' }, + return apiError( + c, 400, + 'DESTINATION_URL_TOO_LONG', + 'destinationUrl must be 2048 characters or fewer', ); } try { const parsed = new URL(body.destinationUrl); if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { - return c.json({ error: 'Only http and https URLs are allowed' }, 400); + return apiError( + c, + 400, + 'ONLY_HTTP_HTTPS_ALLOWED', + 'Only http and https URLs are allowed', + ); } } catch { - return c.json({ error: 'Invalid URL' }, 400); + return apiError(c, 400, 'INVALID_URL', 'Invalid URL'); } } if (body.title && body.title.length > 255) { - return c.json({ error: 'title must be 255 characters or fewer' }, 400); + return apiError( + c, + 400, + 'TITLE_TOO_LONG', + 'title must be 255 characters or fewer', + ); } let expiresAt = existing.expires_at; @@ -275,19 +317,31 @@ links.put('/:id', async (c) => { if (body.expiresAt !== undefined) { if (body.expiresAt !== null) { if (!Number.isSafeInteger(body.expiresAt)) { - return c.json( - { error: 'expiresAt must be an integer Unix timestamp' }, + return apiError( + c, 400, + 'EXPIRES_AT_INVALID', + 'expiresAt must be an integer Unix timestamp', ); } if (body.expiresAt <= now) { - return c.json({ error: 'expiresAt must be in the future' }, 400); + return apiError( + c, + 400, + 'EXPIRES_AT_IN_PAST', + 'expiresAt must be in the future', + ); } } expiresAt = body.expiresAt; } else if (body.expiryDays !== undefined) { if (body.expiryDays && body.expiryDays > 3650) { - return c.json({ error: 'expiryDays must be 3650 or fewer' }, 400); + return apiError( + c, + 400, + 'EXPIRY_DAYS_TOO_LARGE', + 'expiryDays must be 3650 or fewer', + ); } expiresAt = body.expiryDays && body.expiryDays > 0 @@ -343,7 +397,7 @@ links.delete('/:id', async (c) => { .bind(...(role === 'admin' ? [id] : [id, userId])) .first>(); - if (!existing) return c.json({ error: 'Link not found' }, 404); + if (!existing) return apiError(c, 404, 'LINK_NOT_FOUND', 'Link not found'); await c.env.DB.prepare(`DELETE FROM ${L} WHERE id = ?1`).bind(id).run(); await deleteCachedLink(c.env.LINKS_KV, existing.slug); diff --git a/apps/worker/test/routing.test.ts b/apps/worker/test/routing.test.ts new file mode 100644 index 0000000..c73fdd1 --- /dev/null +++ b/apps/worker/test/routing.test.ts @@ -0,0 +1,100 @@ +// Routing-level tests against the full app (index.ts): unmatched /api/* must +// return a JSON 404 instead of the SPA, and error responses carry a stable +// `code` for frontend i18n. +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { app } from '../src/index.ts'; +import { makeEnv, request, seedUser } from './helpers/app.ts'; + +test('未匹配的 /api/* 返回 JSON 404 而非 SPA', async () => { + const ctx = makeEnv(); + const res = await request(app, '/api/does-not-exist', { method: 'GET' }, ctx); + assert.equal(res.status, 404); + assert.match(res.headers.get('content-type') ?? '', /application\/json/); + const body = await res.json(); + assert.equal(body.error, 'Not found'); + assert.equal(body.code, 'NOT_FOUND'); +}); + +test('已知路径但 method 不匹配的 /api/* 也返回 JSON 404', async () => { + const ctx = makeEnv(); + // BE-S12: 2fa/totp/setup 只接受 POST,GET 必须落到 JSON 404。 + const res = await request( + app, + '/api/auth/2fa/totp/setup', + { method: 'GET' }, + ctx, + ); + assert.equal(res.status, 404); + const body = await res.json(); + assert.equal(body.error, 'Not found'); + assert.equal(body.code, 'NOT_FOUND'); +}); + +test('非 /api 路径仍然回退到 SPA(ASSETS)', async () => { + const ctx = makeEnv(); + const res = await request(app, '/login', { method: 'GET' }, ctx); + assert.equal(res.status, 200); + assert.equal(await res.text(), 'assets'); +}); + +test('注册已被占用的邮箱返回 409 且带 EMAIL_OR_USERNAME_TAKEN 码', async () => { + const ctx = makeEnv(); + await seedUser(ctx.db, { + id: 'u1', + email: 'alice@example.com', + username: 'alice', + role: 'user', + isActive: 1, + tokenVersion: 0, + password: 'password-1', + }); + const res = await request( + app, + '/api/auth/register', + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + email: 'alice@example.com', + username: 'bob', + password: 'password-1', + }), + }, + ctx, + ); + assert.equal(res.status, 409); + const body = await res.json(); + assert.equal(body.error, 'Email or username already taken'); + assert.equal(body.code, 'EMAIL_OR_USERNAME_TAKEN'); +}); + +test('登录密码错误返回 401 且带 INVALID_CREDENTIALS 码', async () => { + const ctx = makeEnv(); + await seedUser(ctx.db, { + id: 'u1', + email: 'alice@example.com', + username: 'alice', + role: 'user', + isActive: 1, + tokenVersion: 0, + password: 'correct-password', + }); + const res = await request( + app, + '/api/auth/login', + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + email: 'alice@example.com', + password: 'wrong-password', + }), + }, + ctx, + ); + assert.equal(res.status, 401); + const body = await res.json(); + assert.equal(body.error, 'Invalid credentials'); + assert.equal(body.code, 'INVALID_CREDENTIALS'); +}); diff --git a/biome.json b/biome.json index fc6888b..166d55d 100644 --- a/biome.json +++ b/biome.json @@ -1,5 +1,5 @@ { - "$schema": "https://biomejs.dev/schemas/2.5.0/schema.json", + "$schema": "https://biomejs.dev/schemas/2.5.15/schema.json", "vcs": { "enabled": true, "clientKind": "git", diff --git a/package.json b/package.json index 90cd7ca..44dd8a9 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,7 @@ "check": "biome check ." }, "devDependencies": { - "@biomejs/biome": "^2.5.0", + "@biomejs/biome": "^2.5.15", "turbo": "^2.9.18" }, "packageManager": "pnpm@11.8.0" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 55bd5d3..8e99921 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -9,8 +9,8 @@ importers: .: devDependencies: '@biomejs/biome': - specifier: ^2.5.0 - version: 2.5.2 + specifier: ^2.5.15 + version: 2.5.15 turbo: specifier: ^2.9.18 version: 2.9.18 @@ -112,59 +112,59 @@ importers: packages: - '@biomejs/biome@2.5.2': - resolution: {integrity: sha512-VQ3RCqr7JmDIX+w6stWYl+g/3bYofN3q2wDBHUKKc/c7i5QWrFKFBZYCYPWTE6agsUPMIZZe6/CMmVUfUAhkKA==} + '@biomejs/biome@2.5.15': + resolution: {integrity: sha512-WZTW4slm/pdkh92K6t/3aEN++44JD1PQ7squ7RCMLI1flHGl43DVOIGXvCjHiZgBMO1V4uYxoFNtqrIA4qGuIQ==} engines: {node: '>=14.21.3'} hasBin: true - '@biomejs/cli-darwin-arm64@2.5.2': - resolution: {integrity: sha512-e7P3P7EkwFc/KiX2AHw4YDLIBOMfG9CPCAwy52k5Bp0dfhkozx9hf6wCmIr2QeXy2XeccJ3V/Sg+hDmzYEqxSg==} + '@biomejs/cli-darwin-arm64@2.5.15': + resolution: {integrity: sha512-BZVzFhJ/mUvTLMYbc9x6el0o2Uv5zP7bACYyhFb6fSc1giroXm7PL0a5KqMJ9F+/BnkYRjagD/ROSDVOZ6eapg==} engines: {node: '>=14.21.3'} cpu: [arm64] os: [darwin] - '@biomejs/cli-darwin-x64@2.5.2': - resolution: {integrity: sha512-ymzMvjC1Jg0b9K0D26ZdARqFQXs7MocfLC5FOCGfkC0Ss+ACUJkX5364ZM5nT4NLZanHRZNVrZEy+Ibwcvux/g==} + '@biomejs/cli-darwin-x64@2.5.15': + resolution: {integrity: sha512-V5Kw63V+fVGNFhFrizDxMbGXAzZCh8kYzJpy3GI6gTapWDg7bZK9oYC9CbVgQSEdTnupz0U5Efz8Ev+5vdBBXw==} engines: {node: '>=14.21.3'} cpu: [x64] os: [darwin] - '@biomejs/cli-linux-arm64-musl@2.5.2': - resolution: {integrity: sha512-w+ANG0ZvTu9IeEg9QnstoOnk6L0fpwJifW6aHR18+cb5Z39bkANItYjAfMrnvce5tmMK+IQ6nPX7/kQFdam5iw==} + '@biomejs/cli-linux-arm64-musl@2.5.15': + resolution: {integrity: sha512-tGzZUTcJCV7tj5Adh/Gn6nR4MycqA3iohq2LEcrarAgRBkU0h0OKd2UzCRkOsOYOuUGaUJb4YmqRqyy2feGGSw==} engines: {node: '>=14.21.3'} cpu: [arm64] os: [linux] libc: [musl] - '@biomejs/cli-linux-arm64@2.5.2': - resolution: {integrity: sha512-t7sseOmqND57uUWTwlawU6BYj+J06T/9EkydzBhkrgw/FK3QVhjU2wsJR0frljrKZ0/I8A/rYw7284QgqjQfIQ==} + '@biomejs/cli-linux-arm64@2.5.15': + resolution: {integrity: sha512-XaG7P7eeSLYETD3K9grfB0mQmpLQZjygdbsxekWBJAg4am79fGAtRpfRyNnTvXB2fZFNnJZG3nXm7HBat0+VUw==} engines: {node: '>=14.21.3'} cpu: [arm64] os: [linux] libc: [glibc] - '@biomejs/cli-linux-x64-musl@2.5.2': - resolution: {integrity: sha512-VArNLAzND063tF+XY0yPyM+DyahpzOMzOAvb7qs259nhjJWRjvjZdssuA+Rfl+l07+NOesKZ0Xu2yFrXyBMtzw==} + '@biomejs/cli-linux-x64-musl@2.5.15': + resolution: {integrity: sha512-IlxUcyxilVGPsE008x13pWdkTbU3nQpP2i9b5UrbOYj6goBkKsRX1XB7yJLcV+O1H9LBchIIm4adOaVLZBX0ZQ==} engines: {node: '>=14.21.3'} cpu: [x64] os: [linux] libc: [musl] - '@biomejs/cli-linux-x64@2.5.2': - resolution: {integrity: sha512-M/lOZrewzTCRDINbjhQ1gYYru37KlD3kJBQwwKCG0ckz5E9IZwIoJ3X0wBwRXA+yBDIwWUuPBHS67HzJY4dTfA==} + '@biomejs/cli-linux-x64@2.5.15': + resolution: {integrity: sha512-xE4iEW/3LqlYj9GFgGrFsFSH51dEEpUbYWBfeOv0q87WkUDxK2o/HhreSb7qMJqck70RVM6Lg96hgedcAYcOkA==} engines: {node: '>=14.21.3'} cpu: [x64] os: [linux] libc: [glibc] - '@biomejs/cli-win32-arm64@2.5.2': - resolution: {integrity: sha512-kbjFFKyZlzYnAuw7sRy5qDoFG6zrP40UK08oPQsWK0ct3NMnGSt+Bs1iviEEyEIP57N5MrykGXdO/wRiaR4lww==} + '@biomejs/cli-win32-arm64@2.5.15': + resolution: {integrity: sha512-2kPKzhNlm8C+Ru3GcO0Me2ODkCBLrVOUNuyi84RJyWDVKAA4+Kjj3jMjL938lF6BRfvltC4vB2nPY9SvN51Ovg==} engines: {node: '>=14.21.3'} cpu: [arm64] os: [win32] - '@biomejs/cli-win32-x64@2.5.2': - resolution: {integrity: sha512-4InchVpdVmdkkkgjQqKpgvyu+VPnoF/7RPSw5YATgEVpt2j72wcCAeV5TwaE9ZGJUZWZn7v2CwSAj6CrMJEx8A==} + '@biomejs/cli-win32-x64@2.5.15': + resolution: {integrity: sha512-yAzh4UqEImV6Hcy0zjUqNfJAsUhoD64FBQCdTG8Md/Z2wQeVP/ZmJ3XRYAs1g8J9fjTFyl2fCtc5FB5til47+g==} engines: {node: '>=14.21.3'} cpu: [x64] os: [win32] @@ -1604,39 +1604,39 @@ packages: snapshots: - '@biomejs/biome@2.5.2': + '@biomejs/biome@2.5.15': optionalDependencies: - '@biomejs/cli-darwin-arm64': 2.5.2 - '@biomejs/cli-darwin-x64': 2.5.2 - '@biomejs/cli-linux-arm64': 2.5.2 - '@biomejs/cli-linux-arm64-musl': 2.5.2 - '@biomejs/cli-linux-x64': 2.5.2 - '@biomejs/cli-linux-x64-musl': 2.5.2 - '@biomejs/cli-win32-arm64': 2.5.2 - '@biomejs/cli-win32-x64': 2.5.2 + '@biomejs/cli-darwin-arm64': 2.5.15 + '@biomejs/cli-darwin-x64': 2.5.15 + '@biomejs/cli-linux-arm64': 2.5.15 + '@biomejs/cli-linux-arm64-musl': 2.5.15 + '@biomejs/cli-linux-x64': 2.5.15 + '@biomejs/cli-linux-x64-musl': 2.5.15 + '@biomejs/cli-win32-arm64': 2.5.15 + '@biomejs/cli-win32-x64': 2.5.15 - '@biomejs/cli-darwin-arm64@2.5.2': + '@biomejs/cli-darwin-arm64@2.5.15': optional: true - '@biomejs/cli-darwin-x64@2.5.2': + '@biomejs/cli-darwin-x64@2.5.15': optional: true - '@biomejs/cli-linux-arm64-musl@2.5.2': + '@biomejs/cli-linux-arm64-musl@2.5.15': optional: true - '@biomejs/cli-linux-arm64@2.5.2': + '@biomejs/cli-linux-arm64@2.5.15': optional: true - '@biomejs/cli-linux-x64-musl@2.5.2': + '@biomejs/cli-linux-x64-musl@2.5.15': optional: true - '@biomejs/cli-linux-x64@2.5.2': + '@biomejs/cli-linux-x64@2.5.15': optional: true - '@biomejs/cli-win32-arm64@2.5.2': + '@biomejs/cli-win32-arm64@2.5.15': optional: true - '@biomejs/cli-win32-x64@2.5.2': + '@biomejs/cli-win32-x64@2.5.15': optional: true '@cloudflare/kv-asset-handler@0.5.0': {} From bfda9880063ce2490d738a5c0acd11568e3803d7 Mon Sep 17 00:00:00 2001 From: Todos Date: Sun, 18 Oct 2026 08:55:43 +0800 Subject: [PATCH 2/3] fix(api): localize remaining auth errors, fix APP_ORIGIN, extend routing tests - Add stable error codes to verify-email, forgot/reset-password, refresh and passkey-registration responses, and map the missing 2FA/link codes through i18n (en + zh-CN). - Point the README .dev.vars APP_ORIGIN at the Vite origin (:5173) so passkeys verify against the page origin. - Add routing tests asserting /api/health still 200 and OPTIONS preflight still returns CORS 204. Checkpoint: c0Po49GriX6RBspR83CqL --- README.md | 2 +- README.zh-CN.md | 2 +- apps/web/src/i18n/locales/en.ts | 16 +++++ apps/web/src/i18n/locales/zh-CN.ts | 14 +++++ apps/web/src/lib/apiErrorCodes.ts | 17 ++++++ apps/worker/src/routes/auth.ts | 97 +++++++++++++++++++++++++----- apps/worker/test/routing.test.ts | 29 +++++++++ 7 files changed, 160 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 45e6631..05bce85 100644 --- a/README.md +++ b/README.md @@ -148,7 +148,7 @@ cat > apps/worker/.dev.vars << 'EOF' APP_URL=http://localhost:8787 APP_NAME=ShortLink RP_ID=localhost -APP_ORIGIN=http://localhost:8787 +APP_ORIGIN=http://localhost:5173 JWT_SECRET=dev-secret-at-least-32-characters-long TOTP_ENCRYPTION_KEY=0000000000000000000000000000000000000000000000000000000000000000 SETUP_SECRET=local-setup-secret diff --git a/README.zh-CN.md b/README.zh-CN.md index 3c11691..4d10e38 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -143,7 +143,7 @@ cat > apps/worker/.dev.vars << 'EOF' APP_URL=http://localhost:8787 APP_NAME=ShortLink RP_ID=localhost -APP_ORIGIN=http://localhost:8787 +APP_ORIGIN=http://localhost:5173 JWT_SECRET=dev-secret-at-least-32-characters-long TOTP_ENCRYPTION_KEY=0000000000000000000000000000000000000000000000000000000000000000 SETUP_SECRET=local-setup-secret diff --git a/apps/web/src/i18n/locales/en.ts b/apps/web/src/i18n/locales/en.ts index a3ad51c..ab1e50f 100644 --- a/apps/web/src/i18n/locales/en.ts +++ b/apps/web/src/i18n/locales/en.ts @@ -276,9 +276,23 @@ export const en = { invalidCode: 'Invalid or incorrect code.', currentPasswordIncorrect: 'Current password is incorrect.', totpAlreadyEnabled: 'TOTP is already enabled.', + totpNotConfigured: 'TOTP is not configured for this account.', accountDisabled: 'This account is disabled.', codeAlreadyUsed: 'This code was already used. Please use a new one.', emailSendFailed: 'Failed to send the email. Please try again.', + invalidOrExpiredPendingToken: + 'Your sign-in session has expired. Please sign in again.', + invalidOrExpiredChallenge: + 'Invalid or expired challenge. Please try again.', + passkeyVerificationFailed: 'Passkey verification failed.', + passkeyNotFound: 'Passkey not found.', + noValidCode: 'No valid code found. Please request a new one.', + emailOtpNotEnabled: 'Email OTP is not enabled for this account.', + invalidOrExpiredVerification: 'Invalid or expired verification.', + invalidOrExpiredCode: 'Invalid or expired code.', + tooManyPasskeys: 'Maximum of 10 passkeys allowed per account.', + passkeyNameTooLong: 'Passkey name must be 64 characters or fewer.', + serviceUnavailable: 'Service temporarily unavailable. Please try again.', invalidUrl: 'Please enter a valid URL.', onlyHttpHttpsAllowed: 'Only http and https URLs are allowed.', invalidSlug: @@ -286,6 +300,8 @@ export const en = { slugReserved: 'This slug is reserved.', slugTaken: 'This slug is already taken.', destinationUrlRequired: 'Please enter a destination URL.', + destinationUrlTooLong: 'Destination URL must be 2048 characters or fewer.', + titleTooLong: 'Title must be 255 characters or fewer.', linkNotFound: 'Link not found.', expiresAtInPast: 'Expiry must be in the future.', failedToCreateLink: 'Failed to create the link.', diff --git a/apps/web/src/i18n/locales/zh-CN.ts b/apps/web/src/i18n/locales/zh-CN.ts index 86e9e77..b0a4cbb 100644 --- a/apps/web/src/i18n/locales/zh-CN.ts +++ b/apps/web/src/i18n/locales/zh-CN.ts @@ -266,15 +266,29 @@ export const zhCN: Translations = { invalidCode: '验证码无效或错误。', currentPasswordIncorrect: '当前密码不正确。', totpAlreadyEnabled: 'TOTP 已启用。', + totpNotConfigured: '该账户未配置 TOTP。', accountDisabled: '该账户已被禁用。', codeAlreadyUsed: '该验证码已被使用,请使用新的验证码。', emailSendFailed: '邮件发送失败,请重试。', + invalidOrExpiredPendingToken: '登录会话已过期,请重新登录。', + invalidOrExpiredChallenge: '验证请求无效或已过期,请重试。', + passkeyVerificationFailed: '通行密钥验证失败。', + passkeyNotFound: '未找到通行密钥。', + noValidCode: '未找到有效验证码,请重新获取。', + emailOtpNotEnabled: '该账户未启用邮件 OTP。', + invalidOrExpiredVerification: '验证无效或已过期。', + invalidOrExpiredCode: '验证码无效或已过期。', + tooManyPasskeys: '每个账户最多 10 个通行密钥。', + passkeyNameTooLong: '通行密钥名称不能超过 64 个字符。', + serviceUnavailable: '服务暂时不可用,请稍后再试。', invalidUrl: '请输入有效的 URL。', onlyHttpHttpsAllowed: '仅支持 http 和 https 链接。', invalidSlug: '别名无效,请使用 1–50 个字母、数字、短横线或下划线。', slugReserved: '该别名为保留字。', slugTaken: '该别名已被占用。', destinationUrlRequired: '请输入目标 URL。', + destinationUrlTooLong: '目标 URL 不能超过 2048 个字符。', + titleTooLong: '标题不能超过 255 个字符。', linkNotFound: '链接不存在。', expiresAtInPast: '过期时间必须在将来。', failedToCreateLink: '创建链接失败。', diff --git a/apps/web/src/lib/apiErrorCodes.ts b/apps/web/src/lib/apiErrorCodes.ts index 3f81e59..be72ca2 100644 --- a/apps/web/src/lib/apiErrorCodes.ts +++ b/apps/web/src/lib/apiErrorCodes.ts @@ -12,18 +12,35 @@ export const API_ERROR_CODES: Record = { TOO_MANY_REQUESTS: 'errors.tooManyRequests', TOO_MANY_LOGIN_ATTEMPTS: 'errors.tooManyLoginAttempts', TOO_MANY_ATTEMPTS: 'errors.tooManyAttempts', + TOO_MANY_OTP_REQUESTS: 'errors.tooManyRequests', INVALID_CODE: 'errors.invalidCode', CURRENT_PASSWORD_INCORRECT: 'errors.currentPasswordIncorrect', TOTP_ALREADY_ENABLED: 'errors.totpAlreadyEnabled', + TOTP_NOT_CONFIGURED: 'errors.totpNotConfigured', ACCOUNT_DISABLED: 'errors.accountDisabled', CODE_ALREADY_USED: 'errors.codeAlreadyUsed', EMAIL_SEND_FAILED: 'errors.emailSendFailed', + INVALID_OR_EXPIRED_PENDING_TOKEN: 'errors.invalidOrExpiredPendingToken', + INVALID_OR_EXPIRED_CHALLENGE: 'errors.invalidOrExpiredChallenge', + PASSKEY_VERIFICATION_FAILED: 'errors.passkeyVerificationFailed', + PASSKEY_NOT_FOUND: 'errors.passkeyNotFound', + NO_VALID_VERIFICATION_CODE: 'errors.noValidCode', + NO_VALID_OTP: 'errors.noValidCode', + EMAIL_OTP_NOT_ENABLED: 'errors.emailOtpNotEnabled', + INVALID_OR_EXPIRED_VERIFICATION: 'errors.invalidOrExpiredVerification', + INVALID_OR_EXPIRED_VERIFICATION_CODE: 'errors.invalidOrExpiredVerification', + INVALID_OR_EXPIRED_CODE: 'errors.invalidOrExpiredCode', + TOO_MANY_PASSKEYS: 'errors.tooManyPasskeys', + PASSKEY_NAME_TOO_LONG: 'errors.passkeyNameTooLong', + SERVICE_UNAVAILABLE: 'errors.serviceUnavailable', INVALID_URL: 'errors.invalidUrl', ONLY_HTTP_HTTPS_ALLOWED: 'errors.onlyHttpHttpsAllowed', INVALID_SLUG: 'errors.invalidSlug', SLUG_RESERVED: 'errors.slugReserved', SLUG_TAKEN: 'errors.slugTaken', DESTINATION_URL_REQUIRED: 'errors.destinationUrlRequired', + DESTINATION_URL_TOO_LONG: 'errors.destinationUrlTooLong', + TITLE_TOO_LONG: 'errors.titleTooLong', LINK_NOT_FOUND: 'errors.linkNotFound', EXPIRES_AT_IN_PAST: 'errors.expiresAtInPast', FAILED_TO_CREATE_LINK: 'errors.failedToCreateLink', diff --git a/apps/worker/src/routes/auth.ts b/apps/worker/src/routes/auth.ts index 5e97794..45c0acb 100644 --- a/apps/worker/src/routes/auth.ts +++ b/apps/worker/src/routes/auth.ts @@ -378,7 +378,12 @@ auth.post('/verify-email', async (c) => { .catch(() => null); if (!body) return apiError(c, 400, 'INVALID_JSON_BODY', 'Invalid JSON body'); if (!body.userId || !body.code || body.code.length > 6) { - return c.json({ error: 'userId and code required' }, 400); + return apiError( + c, + 400, + 'USER_ID_AND_CODE_REQUIRED', + 'userId and code required', + ); } const user = await c.env.DB.prepare( @@ -388,7 +393,12 @@ auth.post('/verify-email', async (c) => { .first(); if (!user || user.is_active) { - return c.json({ error: 'Invalid or expired verification' }, 400); + return apiError( + c, + 400, + 'INVALID_OR_EXPIRED_VERIFICATION', + 'Invalid or expired verification', + ); } const now = Math.floor(Date.now() / 1000); @@ -399,7 +409,12 @@ auth.post('/verify-email', async (c) => { .first<{ id: string; code_hash: string; attempts: number }>(); if (!verification) { - return c.json({ error: 'Invalid or expired verification code' }, 400); + return apiError( + c, + 400, + 'INVALID_OR_EXPIRED_VERIFICATION_CODE', + 'Invalid or expired verification code', + ); } if (verification.attempts >= 3) { @@ -449,7 +464,8 @@ auth.post('/verify-email', async (c) => { auth.post('/resend-verify-email', async (c) => { const body = await c.req.json<{ userId: string }>().catch(() => null); if (!body) return apiError(c, 400, 'INVALID_JSON_BODY', 'Invalid JSON body'); - if (!body.userId) return c.json({ error: 'userId required' }, 400); + if (!body.userId) + return apiError(c, 400, 'USER_ID_REQUIRED', 'userId required'); const user = await c.env.DB.prepare( `SELECT * FROM ${tbl(c.env, 'users')} WHERE id = ?1`, @@ -628,7 +644,12 @@ auth.post('/refresh', async (c) => { payload = await verifyRefreshToken(refreshToken, c.env.JWT_SECRET); } catch { clearRefreshCookie(c); - return c.json({ error: 'Invalid or expired refresh token' }, 401); + return apiError( + c, + 401, + 'INVALID_OR_EXPIRED_REFRESH_TOKEN', + 'Invalid or expired refresh token', + ); } try { @@ -665,7 +686,12 @@ auth.post('/refresh', async (c) => { } 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); + return apiError( + c, + 503, + 'SERVICE_UNAVAILABLE', + 'Service temporarily unavailable', + ); } }); @@ -1448,7 +1474,12 @@ auth.post('/2fa/passkey/register-options', requireAuth, async (c) => { .all>(); if (existingPasskeys.results.length >= 10) { - return c.json({ error: 'Maximum of 10 passkeys allowed per account' }, 400); + return apiError( + c, + 400, + 'TOO_MANY_PASSKEYS', + 'Maximum of 10 passkeys allowed per account', + ); } const options = await generateRegistrationOptions({ @@ -1502,9 +1533,11 @@ auth.post('/2fa/passkey/register-verify', requireAuth, async (c) => { } if (body.name && body.name.length > 64) { - return c.json( - { error: 'Passkey name must be 64 characters or fewer' }, + return apiError( + c, 400, + 'PASSKEY_NAME_TOO_LONG', + 'Passkey name must be 64 characters or fewer', ); } @@ -1856,7 +1889,12 @@ auth.post('/verify-reset-code', async (c) => { .json<{ email: string; code: string }>() .catch(() => null); if (!body?.email || !body?.code || body.code.length > 6) { - return c.json({ error: 'email and code are required' }, 400); + return apiError( + c, + 400, + 'EMAIL_AND_CODE_REQUIRED', + 'email and code are required', + ); } const email = body.email.trim().toLowerCase(); @@ -1865,7 +1903,13 @@ auth.post('/verify-reset-code', async (c) => { ) .bind(email) .first<{ id: string }>(); - if (!user) return c.json({ error: 'Invalid or expired code' }, 400); + if (!user) + return apiError( + c, + 400, + 'INVALID_OR_EXPIRED_CODE', + 'Invalid or expired code', + ); const now = Math.floor(Date.now() / 1000); const verification = await c.env.DB.prepare( @@ -1874,7 +1918,13 @@ auth.post('/verify-reset-code', async (c) => { .bind(email, now) .first<{ id: string; code_hash: string; attempts: number }>(); - if (!verification) return c.json({ error: 'Invalid or expired code' }, 400); + if (!verification) + return apiError( + c, + 400, + 'INVALID_OR_EXPIRED_CODE', + 'Invalid or expired code', + ); if (verification.attempts >= 3) { return apiError( @@ -1981,7 +2031,12 @@ auth.post('/reset-password', async (c) => { .catch(() => null); if (!body) return apiError(c, 400, 'INVALID_JSON_BODY', 'Invalid JSON body'); if (!body.email || !body.code || !body.newPassword) { - return c.json({ error: 'email, code, and newPassword are required' }, 400); + return apiError( + c, + 400, + 'EMAIL_CODE_NEW_PASSWORD_REQUIRED', + 'email, code, and newPassword are required', + ); } if (body.code.length > 6) return apiError(c, 400, 'INVALID_CODE', 'Invalid code'); @@ -2002,7 +2057,13 @@ auth.post('/reset-password', async (c) => { ) .bind(email) .first<{ id: string }>(); - if (!user) return c.json({ error: 'Invalid or expired code' }, 400); + if (!user) + return apiError( + c, + 400, + 'INVALID_OR_EXPIRED_CODE', + 'Invalid or expired code', + ); const now = Math.floor(Date.now() / 1000); const verification = await c.env.DB.prepare( @@ -2011,7 +2072,13 @@ auth.post('/reset-password', async (c) => { .bind(email, now) .first<{ id: string; code_hash: string; attempts: number }>(); - if (!verification) return c.json({ error: 'Invalid or expired code' }, 400); + if (!verification) + return apiError( + c, + 400, + 'INVALID_OR_EXPIRED_CODE', + 'Invalid or expired code', + ); if (verification.attempts >= 3) { return apiError( diff --git a/apps/worker/test/routing.test.ts b/apps/worker/test/routing.test.ts index c73fdd1..a2db106 100644 --- a/apps/worker/test/routing.test.ts +++ b/apps/worker/test/routing.test.ts @@ -38,6 +38,35 @@ test('非 /api 路径仍然回退到 SPA(ASSETS)', async () => { assert.equal(await res.text(), 'assets'); }); +test('GET /api/health 仍返回 200(兜底不影响已有路由)', async () => { + const ctx = makeEnv(); + const res = await request(app, '/api/health', { method: 'GET' }, ctx); + assert.equal(res.status, 200); + const body = await res.json(); + assert.equal(body.status, 'ok'); +}); + +test('OPTIONS /api/* 预检仍由 CORS 处理(204 + Allow-Origin)', async () => { + const ctx = makeEnv(); + const res = await request( + app, + '/api/anything', + { + method: 'OPTIONS', + headers: { + Origin: 'https://example.com', + 'Access-Control-Request-Method': 'POST', + }, + }, + ctx, + ); + assert.equal(res.status, 204); + assert.equal( + res.headers.get('Access-Control-Allow-Origin'), + 'https://example.com', + ); +}); + test('注册已被占用的邮箱返回 409 且带 EMAIL_OR_USERNAME_TAKEN 码', async () => { const ctx = makeEnv(); await seedUser(ctx.db, { From 3451bc603c934bb37f4597db1fcd1216e2323d60 Mon Sep 17 00:00:00 2001 From: Todos Date: Sun, 18 Oct 2026 09:01:29 +0800 Subject: [PATCH 3/3] ci(workflows): run CI on tds/** pushes, harden deploy/tag branch guards - Add 'tds/**' to ci.yml push branches so platform conversation-branch pushes auto-run CI; pull_request and workflow_dispatch are unchanged. - Assert workflow_run.head_branch == 'main' in deploy.yml so a non-main CI run can never trigger the production deploy. - Pin tag.yml's CI lookup to branch: 'main' so a tds/** push run at the same commit cannot satisfy the pre-tag check. Checkpoint: RJ2gyK0wguvPmlXIIjvtw --- .github/workflows/ci.yml | 2 +- .github/workflows/deploy.yml | 8 ++++++-- .github/workflows/tag.yml | 5 ++++- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6a998d1..8312d2a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,7 +2,7 @@ name: CI on: push: - branches: [main] + branches: [main, 'tds/**'] pull_request: branches: [main] workflow_dispatch: diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index d1eace1..1880c1b 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -20,12 +20,16 @@ concurrency: jobs: deploy: # workflow_run: only after a successful CI run for a push to this repo's - # main (the `branches` filter alone also matches fork PRs from a branch - # named "main"). workflow_dispatch: only from main. + # main. The `branches: [main]` filter on the trigger already excludes other + # branches (including tds/**), and `head_branch == 'main'` below re-asserts + # it at the job level so a non-main CI run can never reach production. + # `head_repository` also blocks fork PRs whose branch happens to be "main". + # workflow_dispatch: only from main. if: >- (github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main') || (github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'push' && + github.event.workflow_run.head_branch == 'main' && github.event.workflow_run.head_repository.full_name == github.repository) runs-on: ubuntu-latest environment: diff --git a/.github/workflows/tag.yml b/.github/workflows/tag.yml index d33f14d..d5be3f1 100644 --- a/.github/workflows/tag.yml +++ b/.github/workflows/tag.yml @@ -59,13 +59,16 @@ jobs: const sha = stdout.trim(); core.info(`Checking CI status for main@${sha}`); // Filter by workflow file (not the repo-wide list) so this very tag - // workflow run is not mistaken for CI, and only accept a push run. + // workflow run is not mistaken for CI, and only accept a push run + // on main. `branch: 'main'` pins it to main so a tds/** push run at + // the same commit can never satisfy the check. const { data } = await github.rest.actions.listWorkflowRuns({ owner: context.repo.owner, repo: context.repo.repo, workflow_id: process.env.WORKFLOW_FILE, head_sha: sha, event: 'push', + branch: 'main', }); const ciRun = data.workflow_runs.find( (run) => run.status === 'completed' && run.conclusion === 'success',