⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
feat(auth): add password recovery from the login screen (#1773)
Tin Sever38da6af0fd55
diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.tsindex 3ffc2bc6f..4bcb1a91e 100644--- a/apps/api/src/auth.ts+++ b/apps/api/src/auth.ts@@ -1,8 +1,10 @@import { apiKey } from "@better-auth/api-key";import {+ isSmtpConfigured,OTP_EXPIRY_SECONDS,sendMagicLinkEmail,sendOtpEmail,+ sendPasswordResetEmail,sendWorkspaceInvitationEmail,} from "@kaneo/email";import {@@ -59,6 +61,7 @@ import {import { isCloud } from "./utils/is-cloud";import { isDisposableEmail } from "./utils/is-disposable-email";import { isLocalSignInPath } from "./utils/is-local-sign-in-path";+import { trackPasswordResetDelivery } from "./utils/password-reset-delivery";import {assertGuestRegistrationAllowed,assertUserRegistrationAllowed,@@ -134,6 +137,7 @@ function getAuthEmailCopy(locale?: string | null) {return {magicLinkSubject: "Anmeldelink für Kaneo",otpSubject: "Bestätigungscode für Kaneo",+ passwordResetSubject: "Kaneo-Passwort zurücksetzen",};}@@ -141,6 +145,7 @@ function getAuthEmailCopy(locale?: string | null) {return {magicLinkSubject: "Liên kết đăng nhập Kaneo",otpSubject: "Mã xác minh Kaneo",+ passwordResetSubject: "Đặt lại mật khẩu Kaneo",};}@@ -148,12 +153,14 @@ function getAuthEmailCopy(locale?: string | null) {return {magicLinkSubject: "Kaneo ログインリンク",otpSubject: "Kaneo 認証コード",+ passwordResetSubject: "Kaneo のパスワードをリセット",};}return {magicLinkSubject: "Login for Kaneo",otpSubject: "Authentication code for Kaneo",+ passwordResetSubject: "Reset your Kaneo password",};}@@ -228,6 +235,20 @@ export const auth = betterAuth({emailAndPassword: {enabled: true,autoSignIn: true,+ revokeSessionsOnPasswordReset: true,+ resetPasswordTokenExpiresIn: 60 * 60,+ sendResetPassword: async ({ user, url }) => {+ // Keep SMTP latency out of the response so it cannot reveal accounts.+ trackPasswordResetDelivery(+ getUserLocale(user.email).then((locale) =>+ sendPasswordResetEmail(+ user.email,+ getAuthEmailCopy(locale).passwordResetSubject,+ { resetLink: url, userName: user.name, locale },+ ),+ ),+ );+ },password: {hash: async (password) => {return await bcrypt.hash(password, 10);@@ -364,14 +385,8 @@ export const auth = betterAuth({// (owner/admin/member/viewer) don't apply until after a workspace// is joined.//- // `user` here comes from the session, which may be served out of- // the cookie cache (see `session.cookieCache` below). The- // first-user bootstrap promotes the user to admin in- // `databaseHooks.user.create.after`, but that happens after- // `signUpEmail` has already returned/cached the pre-promotion- // role, so a cached session can still say `role: "user"` for up- // to `cookieCache.maxAge`. Re-read the role from the database- // instead of trusting the (possibly stale) cached role.+ // Read the current instance role rather than a session's user snapshot,+ // which can predate first-user promotion or an administrator's changes.allowUserToCreateOrganization: isWorkspaceCreationDisabled? async (user) => {const [freshUser] = await db@@ -538,8 +553,9 @@ export const auth = betterAuth({],session: {cookieCache: {- enabled: true,- maxAge: 5 * 60,+ // Consult the session store on every request so password recovery+ // immediately rejects revoked cookies, including caches issued before upgrade.+ enabled: false,},},rateLimit: {@@ -595,6 +611,12 @@ export const auth = betterAuth({});}+ if (ctx.path === "/request-password-reset" && !isSmtpConfigured()) {+ throw new APIError("FORBIDDEN", {+ message: "Password reset requires email delivery to be configured.",+ });+ }+if (ctx.path === "/sign-in/anonymous") {await assertGuestRegistrationAllowed();}diff --git a/apps/api/src/index.ts b/apps/api/src/index.tsindex 49b8ead07..68918edf5 100644--- a/apps/api/src/index.ts+++ b/apps/api/src/index.ts@@ -1,3 +1,4 @@+import { drainPasswordResetDeliveries } from "./utils/password-reset-delivery";import "./instrument";import { dirname } from "node:path";@@ -958,6 +959,7 @@ export async function startServer(shutdownScheduler();await shutdownWebSocketAdapter();server.close();+ await drainPasswordResetDeliveries();process.exit(0);};diff --git a/apps/api/src/utils/is-local-sign-in-path.ts b/apps/api/src/utils/is-local-sign-in-path.tsindex 5f07eac71..4a23e742f 100644--- a/apps/api/src/utils/is-local-sign-in-path.ts+++ b/apps/api/src/utils/is-local-sign-in-path.ts@@ -1,10 +1,16 @@const localSignInPaths = new Set(["/sign-in/email",+ "/request-password-reset",+ "/reset-password","/sign-in/magic-link","/magic-link/verify","/sign-in/email-otp",]);export function isLocalSignInPath(path: string) {- return localSignInPaths.has(path) || path.startsWith("/email-otp/");+ return (+ localSignInPaths.has(path) ||+ path.startsWith("/email-otp/") ||+ path.startsWith("/reset-password/")+ );}diff --git a/apps/api/src/utils/password-reset-delivery.ts b/apps/api/src/utils/password-reset-delivery.tsnew file mode 100644index 000000000..c1803a3b9--- /dev/null+++ b/apps/api/src/utils/password-reset-delivery.ts@@ -0,0 +1,34 @@+const pendingDeliveries = new Set<Promise<void>>();++export function trackPasswordResetDelivery(delivery: Promise<void>) {+ const settled = delivery+ .catch(() => {+ console.error("Password reset email preparation failed");+ })+ .finally(() => pendingDeliveries.delete(settled));+ pendingDeliveries.add(settled);+}++// HTTP responses must not wait on mail, but normal shutdown should give+// already accepted recovery requests time to finish delivery.+export async function drainPasswordResetDeliveries(timeoutMs = 10_000) {+ if (pendingDeliveries.size === 0) return;+ let timeout: ReturnType<typeof setTimeout> | undefined;+ try {+ await Promise.race([+ (async () => {+ while (pendingDeliveries.size > 0) {+ await Promise.all([...pendingDeliveries]);+ }+ })(),+ new Promise<void>((resolve) => {+ timeout = setTimeout(() => {+ console.warn("Timed out waiting for password reset email delivery");+ resolve();+ }, timeoutMs);+ }),+ ]);+ } finally {+ clearTimeout(timeout);+ }+}diff --git a/apps/api/src/utils/verify-turnstile.ts b/apps/api/src/utils/verify-turnstile.tsindex 8760c49f4..523f3c47b 100644--- a/apps/api/src/utils/verify-turnstile.ts+++ b/apps/api/src/utils/verify-turnstile.ts@@ -10,6 +10,7 @@ export const authCaptchaPaths = new Set(["/sign-in/oauth2","/sign-in/anonymous","/sign-in/magic-link",+ "/request-password-reset","/email-otp/send-verification-otp",]);diff --git a/apps/docs/core/installation/environment-variables.mdx b/apps/docs/core/installation/environment-variables.mdxindex a19c93e76..0059e8ab1 100644--- a/apps/docs/core/installation/environment-variables.mdx+++ b/apps/docs/core/installation/environment-variables.mdx@@ -105,7 +105,7 @@ Name | Description | Default || `DISABLE_GUEST_ACCESS` | Disable anonymous/guest sign-in. Guests are also blocked before initial instance setup and when registration, local registration, or the local login form is disabled. | `false` || `DISABLE_REGISTRATION` | Disable public user registration. When set to `true`, the sign-up option will not be shown on the sign-in page and new user creation is blocked (including via SSO). **Note:** Invited password signups must present the matching invitation link. OAuth, OTP, and magic-link signups may match an invitation by email only after that email has been verified. The first non-guest user can complete initial instance setup. | `false` || `DISABLE_PASSWORD_REGISTRATION` | Disable local account creation through password, email OTP, magic link, and guest access. Existing accounts can still use email sign-in unless `DISABLE_LOGIN_FORM=true`. Social/OIDC registration remains available unless `DISABLE_REGISTRATION=true`. The initial administrator can still be created through password signup. | `false` |-| `DISABLE_EMAIL_OTP_SIGN_IN` | When SMTP is configured, sign-in uses email verification codes by default. Set to `true` to use email/password sign-in instead. Workspace invitation emails still use SMTP. | `false` |+| `DISABLE_EMAIL_OTP_SIGN_IN` | When SMTP is configured, sign-in uses email verification codes by default. Set to `true` to use email/password sign-in instead. Workspace invitation and password-reset emails still use SMTP. | `false` || `DISABLE_LOGIN_FORM` | Hide the email/password login form on the sign-in page. When set to `true`, only SSO/OAuth buttons are shown. Useful when you want to enforce authentication exclusively through an external identity provider. | `false` || `CUSTOM_OAUTH_AUTO_LOGIN` | Automatically redirect to the custom OAuth/OIDC provider instead of showing the sign-in page. When set to `true`, users are immediately redirected to your identity provider without seeing the login page. Requires a custom OAuth provider to be configured. | `false` |@@ -237,7 +237,7 @@ When upgrading, remove `SMTP_IGNORE_TLS=true` and verify delivery with the corre- If you enable Google SSO, you need to set up the Google app which is used to authenticate users in the [Google Cloud Console](https://console.cloud.google.com/). See the [Google SSO guide](/core/social-providers/google).- If you enable Discord SSO, you need to set up the Discord application which is used to authenticate users in the [Discord Developer Portal](https://discord.com/developers/applications). See the [Discord SSO guide](/core/social-providers/discord).- If you enable Custom OAuth/OIDC, you need to configure your identity provider with the appropriate redirect URI. See the [Custom OAuth/OIDC guide](/core/social-providers/custom-oauth).-- If you have enabled SMTP, sign-in uses email verification codes by default. Set `DISABLE_EMAIL_OTP_SIGN_IN=true` to use email/password sign-in instead.+- If you have enabled SMTP, sign-in uses email verification codes by default. Set `DISABLE_EMAIL_OTP_SIGN_IN=true` to use email/password sign-in instead. The password form includes **Forgot password?**, which emails a single-use reset link valid for one hour. Resetting a password revokes existing sessions. Password reset requires SMTP and is unavailable when `DISABLE_LOGIN_FORM=true`.- If you need device authorization for clients beyond the defaults (`kaneo-cli`, `kaneo-mcp` when `DEVICE_AUTH_CLIENT_IDS` is unset), set `DEVICE_AUTH_CLIENT_IDS` to the full comma-separated list of trusted client IDs for your deployment.## Authentication CAPTCHAdiff --git a/apps/web/src/components/auth/sign-in-form.tsx b/apps/web/src/components/auth/sign-in-form.tsxindex 30a37b4f3..2b50a8219 100644--- a/apps/web/src/components/auth/sign-in-form.tsx+++ b/apps/web/src/components/auth/sign-in-form.tsx@@ -1,4 +1,5 @@import { standardSchemaResolver } from "@hookform/resolvers/standard-schema";+import { Link } from "@tanstack/react-router";import { Eye, EyeOff } from "lucide-react";import { useState } from "react";import { useForm } from "react-hook-form";@@ -25,6 +26,7 @@ export type SignInFormValues = {type SignInFormProps = {onSuccess?: () => void;defaultEmail?: string;+ canResetPassword?: boolean;};const signInSchema = z.object({@@ -32,7 +34,11 @@ const signInSchema = z.object({password: z.string(),});-export function SignInForm({ onSuccess, defaultEmail }: SignInFormProps) {+export function SignInForm({+ onSuccess,+ defaultEmail,+ canResetPassword = false,+}: SignInFormProps) {const { t } = useTranslation();const [showPassword, setShowPassword] = useState(false);const [isPending, setIsPending] = useState(false);@@ -134,6 +140,17 @@ export function SignInForm({ onSuccess, defaultEmail }: SignInFormProps) {/></div>+ {canResetPassword && (+ <div className="text-right">+ <Link+ to="/auth/forgot-password"+ className="text-sm text-muted-foreground hover:text-foreground hover:underline"+ >+ {t("auth:passwordReset.forgotPassword")}+ </Link>+ </div>+ )}+<Buttontype="submit"disabled={isPending}diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.tsindex 7206c05b9..3c3f5a3f4 100644--- a/apps/web/src/routeTree.gen.ts+++ b/apps/web/src/routeTree.gen.ts@@ -16,6 +16,8 @@ import { Route as DeviceRouteImport } from './routes/device'import { Route as TestErrorRouteImport } from './routes/test-error'import { Route as LayoutAuthenticatedRouteImport } from './routes/_layout/_authenticated'import { Route as AuthCheckEmailRouteImport } from './routes/auth/check-email'+import { Route as AuthForgotPasswordRouteImport } from './routes/auth/forgot-password'+import { Route as AuthResetPasswordRouteImport } from './routes/auth/reset-password'import { Route as AuthSignInRouteImport } from './routes/auth/sign-in'import { Route as AuthSignUpRouteImport } from './routes/auth/sign-up'import { Route as AuthVerifyOtpRouteImport } from './routes/auth/verify-otp'@@ -93,6 +95,16 @@ const AuthCheckEmailRoute = AuthCheckEmailRouteImport.update({path: '/check-email',getParentRoute: () => AuthRoute,} as any)+const AuthForgotPasswordRoute = AuthForgotPasswordRouteImport.update({+ id: '/forgot-password',+ path: '/forgot-password',+ getParentRoute: () => AuthRoute,+} as any)+const AuthResetPasswordRoute = AuthResetPasswordRouteImport.update({+ id: '/reset-password',+ path: '/reset-password',+ getParentRoute: () => AuthRoute,+} as any)const AuthSignInRoute = AuthSignInRouteImport.update({id: '/sign-in',path: '/sign-in',@@ -377,6 +389,8 @@ export interface FileRoutesByFullPath {'/device': typeof DeviceRouteWithChildren'/test-error': typeof TestErrorRoute'/auth/check-email': typeof AuthCheckEmailRoute+ '/auth/forgot-password': typeof AuthForgotPasswordRoute+ '/auth/reset-password': typeof AuthResetPasswordRoute'/auth/sign-in': typeof AuthSignInRoute'/auth/sign-up': typeof AuthSignUpRoute'/auth/verify-otp': typeof AuthVerifyOtpRoute@@ -426,6 +440,8 @@ export interface FileRoutesByTo {'/auth': typeof AuthRouteWithChildren'/test-error': typeof TestErrorRoute'/auth/check-email': typeof AuthCheckEmailRoute+ '/auth/forgot-password': typeof AuthForgotPasswordRoute+ '/auth/reset-password': typeof AuthResetPasswordRoute'/auth/sign-in': typeof AuthSignInRoute'/auth/sign-up': typeof AuthSignUpRoute'/auth/verify-otp': typeof AuthVerifyOtpRoute@@ -477,6 +493,8 @@ export interface FileRoutesById {'/test-error': typeof TestErrorRoute'/_layout/_authenticated': typeof LayoutAuthenticatedRouteWithChildren'/auth/check-email': typeof AuthCheckEmailRoute+ '/auth/forgot-password': typeof AuthForgotPasswordRoute+ '/auth/reset-password': typeof AuthResetPasswordRoute'/auth/sign-in': typeof AuthSignInRoute'/auth/sign-up': typeof AuthSignUpRoute'/auth/verify-otp': typeof AuthVerifyOtpRoute@@ -529,6 +547,8 @@ export interface FileRouteTypes {| '/device'| '/test-error'| '/auth/check-email'+ | '/auth/forgot-password'+ | '/auth/reset-password'| '/auth/sign-in'| '/auth/sign-up'| '/auth/verify-otp'@@ -578,6 +598,8 @@ export interface FileRouteTypes {| '/auth'| '/test-error'| '/auth/check-email'+ | '/auth/forgot-password'+ | '/auth/reset-password'| '/auth/sign-in'| '/auth/sign-up'| '/auth/verify-otp'@@ -628,6 +650,8 @@ export interface FileRouteTypes {| '/test-error'| '/_layout/_authenticated'| '/auth/check-email'+ | '/auth/forgot-password'+ | '/auth/reset-password'| '/auth/sign-in'| '/auth/sign-up'| '/auth/verify-otp'@@ -735,6 +759,20 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof AuthCheckEmailRouteImportparentRoute: typeof AuthRoute}+ '/auth/forgot-password': {+ id: '/auth/forgot-password'+ path: '/forgot-password'+ fullPath: '/auth/forgot-password'+ preLoaderRoute: typeof AuthForgotPasswordRouteImport+ parentRoute: typeof AuthRoute+ }+ '/auth/reset-password': {+ id: '/auth/reset-password'+ path: '/reset-password'+ fullPath: '/auth/reset-password'+ preLoaderRoute: typeof AuthResetPasswordRouteImport+ parentRoute: typeof AuthRoute+ }'/auth/sign-in': {id: '/auth/sign-in'path: '/sign-in'@@ -1247,6 +1285,8 @@ const LayoutRouteWithChildren =interface AuthRouteChildren {AuthCheckEmailRoute: typeof AuthCheckEmailRoute+ AuthForgotPasswordRoute: typeof AuthForgotPasswordRoute+ AuthResetPasswordRoute: typeof AuthResetPasswordRouteAuthSignInRoute: typeof AuthSignInRouteAuthSignUpRoute: typeof AuthSignUpRouteAuthVerifyOtpRoute: typeof AuthVerifyOtpRoute@@ -1254,6 +1294,8 @@ interface AuthRouteChildren {const AuthRouteChildren: AuthRouteChildren = {AuthCheckEmailRoute: AuthCheckEmailRoute,+ AuthForgotPasswordRoute: AuthForgotPasswordRoute,+ AuthResetPasswordRoute: AuthResetPasswordRoute,AuthSignInRoute: AuthSignInRoute,AuthSignUpRoute: AuthSignUpRoute,AuthVerifyOtpRoute: AuthVerifyOtpRoute,diff --git a/apps/web/src/routes/auth.test.tsx b/apps/web/src/routes/auth.test.tsxnew file mode 100644index 000000000..a312a0dcb--- /dev/null+++ b/apps/web/src/routes/auth.test.tsx@@ -0,0 +1,45 @@+import { beforeEach, expect, it, vi } from "vitest";+import { Route } from "./auth";++const mocks = vi.hoisted(() => ({ getSession: vi.fn() }));+vi.mock("@/lib/auth-client", () => ({ authClient: mocks }));+vi.mock("@tanstack/react-router", () => ({+ createFileRoute: () => (options: unknown) => ({ options }),+ redirect: ({ to }: { to: string }) => new Error(`Redirect to ${to}`),+}));+const beforeLoad = Route.options.beforeLoad as (context: {+ location: { pathname: string };+}) => Promise<unknown>;++beforeEach(() => mocks.getSession.mockReset());++it.each([+ "/auth/reset-password",+ "/auth/forgot-password",+ "/auth/reset-password/",+])("allows an existing session to open %s", async (pathname) => {+ const session = { user: { id: "existing-user" } };+ mocks.getSession.mockResolvedValue({ data: session });+ await expect(beforeLoad({ location: { pathname } })).resolves.toEqual({+ session,+ });+});++it.each(["/auth/sign-in", "/auth/sign-up", "/auth/verify-otp"])(+ "keeps the authenticated redirect on %s",+ async (pathname) => {+ mocks.getSession.mockResolvedValue({+ data: { user: { id: "existing-user" } },+ });+ await expect(beforeLoad({ location: { pathname } })).rejects.toThrow(+ "Redirect to /dashboard",+ );+ },+);++it("allows signed-out visitors to recover their password", async () => {+ mocks.getSession.mockResolvedValue({ data: null });+ await expect(+ beforeLoad({ location: { pathname: "/auth/reset-password" } }),+ ).resolves.toEqual({ session: null });+});diff --git a/apps/web/src/routes/auth.tsx b/apps/web/src/routes/auth.tsxindex 5ae5c991b..3e066bd0b 100644--- a/apps/web/src/routes/auth.tsx+++ b/apps/web/src/routes/auth.tsx@@ -2,7 +2,7 @@ import { createFileRoute, redirect } from "@tanstack/react-router";import { authClient } from "@/lib/auth-client";export const Route = createFileRoute("/auth")({- beforeLoad: async () => {+ beforeLoad: async ({ location }) => {let session = null;try {const { data } = await authClient.getSession();@@ -11,7 +11,11 @@ export const Route = createFileRoute("/auth")({if (import.meta.env.DEV) console.warn("getSession failed", error);// getSession() rejected (e.g. network error) — treat as unauthenticated, allow auth pages to render}- if (session) {+ const isPasswordRecovery = [+ "/auth/forgot-password",+ "/auth/reset-password",+ ].includes(location.pathname.replace(/\/$/, ""));+ if (session && !isPasswordRecovery) {throw redirect({to: "/dashboard",});diff --git a/apps/web/src/routes/auth/forgot-password.tsx b/apps/web/src/routes/auth/forgot-password.tsxnew file mode 100644index 000000000..1ab9de985--- /dev/null+++ b/apps/web/src/routes/auth/forgot-password.tsx@@ -0,0 +1,136 @@+import { createFileRoute, Link } from "@tanstack/react-router";+import { useState } from "react";+import { useTranslation } from "react-i18next";+import { AuthLayout } from "@/components/auth/layout";+import { Turnstile } from "@/components/auth/turnstile";+import PageTitle from "@/components/page-title";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import useGetConfig from "@/hooks/queries/config/use-get-config";+import { authClient } from "@/lib/auth-client";++const TURNSTILE_SITE_KEY = import.meta.env.VITE_TURNSTILE_SITE_KEY as+ | string+ | undefined;++export const Route = createFileRoute("/auth/forgot-password")({+ component: ForgotPassword,+});++function ForgotPassword() {+ const { t } = useTranslation();+ const { data: config, isLoading, isError } = useGetConfig();+ const [email, setEmail] = useState("");+ const [isPending, setIsPending] = useState(false);+ const [sent, setSent] = useState(false);+ const [error, setError] = useState(false);+ const [turnstileToken, setTurnstileToken] = useState<string | null>(null);+ const [captchaKey, setCaptchaKey] = useState(0);+ const available = config?.hasSmtp && !config.disableLoginForm;+ const captchaPending = Boolean(TURNSTILE_SITE_KEY) && !turnstileToken;++ const onSubmit = async (event: React.FormEvent<HTMLFormElement>) => {+ event.preventDefault();+ if (isPending || !available || captchaPending) return;+ setIsPending(true);+ setError(false);+ try {+ const result = await authClient.requestPasswordReset(+ {+ email,+ redirectTo: new URL("/auth/reset-password", window.location.origin)+ .href,+ },+ {+ headers: turnstileToken+ ? { "x-turnstile-token": turnstileToken }+ : undefined,+ },+ );+ if (result.error) setError(true);+ else setSent(true);+ } catch {+ setError(true);+ } finally {+ setIsPending(false);+ setTurnstileToken(null);+ setCaptchaKey((key) => key + 1);+ }+ };++ return (+ <>+ <PageTitle title={t("auth:passwordReset.requestTitle")} />+ <AuthLayout+ title={t("auth:passwordReset.requestTitle")}+ subtitle={t("auth:passwordReset.requestSubtitle")}+ >+ <div className="space-y-4 mt-4">+ {sent ? (+ <p role="status" className="text-sm text-muted-foreground">+ {t("auth:passwordReset.sent")}+ </p>+ ) : isError ? (+ <p role="alert" className="text-sm text-destructive">+ {t("auth:passwordReset.configError")}+ </p>+ ) : !isLoading && !available ? (+ <p role="status" className="text-sm text-muted-foreground">+ {t("auth:passwordReset.unavailable")}+ </p>+ ) : (+ <form onSubmit={onSubmit} className="space-y-3">+ <div className="space-y-2">+ <Label htmlFor="reset-email">{t("auth:forms.email")}</Label>+ <Input+ id="reset-email"+ type="email"+ autoComplete="email"+ required+ value={email}+ onChange={(event) => setEmail(event.target.value)}+ disabled={isPending || isLoading}+ placeholder={t("auth:forms.emailPlaceholder")}+ />+ </div>+ {TURNSTILE_SITE_KEY && (+ <Turnstile+ key={captchaKey}+ siteKey={TURNSTILE_SITE_KEY}+ onVerify={setTurnstileToken}+ onExpire={() => setTurnstileToken(null)}+ onError={() => setTurnstileToken(null)}+ />+ )}+ {error && (+ <p role="alert" className="text-sm text-destructive">+ {t("auth:passwordReset.requestError")}+ </p>+ )}+ <Button+ type="submit"+ size="sm"+ className="w-full"+ disabled={+ isPending || isLoading || !available || captchaPending+ }+ >+ {isPending+ ? t("auth:passwordReset.sending")+ : t("auth:passwordReset.sendLink")}+ </Button>+ </form>+ )}+ <Button+ variant="ghost"+ render={<Link to="/auth/sign-in" />}+ className="w-full text-muted-foreground"+ >+ {t("auth:passwordReset.backToSignIn")}+ </Button>+ </div>+ </AuthLayout>+ </>+ );+}diff --git a/apps/web/src/routes/auth/password-reset.test.tsx b/apps/web/src/routes/auth/password-reset.test.tsxnew file mode 100644index 000000000..f8551e5a4--- /dev/null+++ b/apps/web/src/routes/auth/password-reset.test.tsx@@ -0,0 +1,242 @@+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import type { ComponentType, ReactNode } from "react";+import {+ afterAll,+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vitest";+import { SignInForm } from "@/components/auth/sign-in-form";++const mocks = vi.hoisted(() => ({+ request: vi.fn(),+ reset: vi.fn(),+ search: {} as { token?: string; error?: string },+ config: { hasSmtp: true, disableLoginForm: false },+}));+vi.mock("@tanstack/react-router", () => ({+ createFileRoute: () => (options: unknown) => options,+ useSearch: () => mocks.search,+ Link: ({ children, to, ...props }: { children?: ReactNode; to: string }) => (+ <a href={to} {...props}>+ {children}+ </a>+ ),+}));+vi.mock("@/lib/auth-client", () => ({+ authClient: {+ requestPasswordReset: mocks.request,+ resetPassword: mocks.reset,+ },+}));+vi.mock("@/hooks/queries/config/use-get-config", () => ({+ default: () => ({ data: mocks.config, isLoading: false, isError: false }),+}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));+vi.mock("@/components/auth/layout", () => ({+ AuthLayout: ({ children }: { children: ReactNode }) => children,+}));+vi.mock("@/components/auth/turnstile", () => ({+ Turnstile: ({ onVerify }: { onVerify: (token: string) => void }) => (+ <button type="button" onClick={() => onVerify("captcha-token")}>+ Solve CAPTCHA+ </button>+ ),+}));+vi.mock("@/lib/toast", () => ({ toast: { error: vi.fn(), success: vi.fn() } }));+vi.stubEnv("VITE_TURNSTILE_SITE_KEY", "test-key");+const { Route: forgotRoute } = await import("./forgot-password");+const { Route: resetRoute } = await import("./reset-password");+const ForgotPassword = (forgotRoute as unknown as { component: ComponentType })+ .component;+const ResetPassword = (resetRoute as unknown as { component: ComponentType })+ .component;+afterAll(() => vi.unstubAllEnvs());+afterEach(cleanup);+beforeEach(() => {+ vi.clearAllMocks();+ mocks.request.mockResolvedValue({ error: null });+ mocks.reset.mockResolvedValue({ error: null });+ mocks.search = { token: "reset-token" };+ mocks.config = { hasSmtp: true, disableLoginForm: false };+});++function submitPasswords(password = "new-password", confirmation = password) {+ fireEvent.change(screen.getByLabelText("auth:passwordReset.newPassword"), {+ target: { value: password },+ });+ fireEvent.change(+ screen.getByLabelText("auth:passwordReset.confirmPassword"),+ { target: { value: confirmation } },+ );+ fireEvent.submit(+ screen+ .getByLabelText("auth:passwordReset.newPassword")+ .closest("form") as HTMLFormElement,+ );+}+function submitEmail() {+ fireEvent.change(screen.getByLabelText("auth:forms.email"), {+ target: { value: "[email protected]" },+ });+ fireEvent.click(screen.getByRole("button", { name: "Solve CAPTCHA" }));+ fireEvent.click(+ screen.getByRole("button", { name: "auth:passwordReset.sendLink" }),+ );+}++describe("password recovery", () => {+ it("shows the login link only when password reset is available", () => {+ const { rerender } = render(<SignInForm />);+ expect(+ screen.queryByRole("link", { name: "auth:passwordReset.forgotPassword" }),+ ).toBeNull();+ rerender(<SignInForm canResetPassword />);+ expect(+ screen.getByRole("link", { name: "auth:passwordReset.forgotPassword" }),+ ).toHaveAttribute("href", "/auth/forgot-password");+ });++ it("requests a link with CAPTCHA and confirms without disclosing account existence", async () => {+ render(<ForgotPassword />);+ expect(+ screen.getByRole("button", { name: "auth:passwordReset.sendLink" }),+ ).toBeDisabled();+ submitEmail();+ await waitFor(() =>+ expect(screen.getByRole("status")).toHaveTextContent(+ "auth:passwordReset.sent",+ ),+ );+ expect(mocks.request).toHaveBeenCalledWith(+ {+ email: "[email protected]",+ redirectTo: `${window.location.origin}/auth/reset-password`,+ },+ { headers: { "x-turnstile-token": "captcha-token" } },+ );+ });++ it("allows retry after a network failure with a fresh CAPTCHA", async () => {+ mocks.request.mockRejectedValueOnce(new Error("Network failed"));+ render(<ForgotPassword />);+ submitEmail();+ await waitFor(() =>+ expect(screen.getByRole("alert")).toHaveTextContent(+ "auth:passwordReset.requestError",+ ),+ );+ expect(+ screen.getByRole("button", { name: "auth:passwordReset.sendLink" }),+ ).toBeDisabled();+ submitEmail();+ await waitFor(() =>+ expect(screen.getByRole("status")).toHaveTextContent(+ "auth:passwordReset.sent",+ ),+ );+ });++ it.each([+ { hasSmtp: false, disableLoginForm: false },+ { hasSmtp: true, disableLoginForm: true },+ ])("blocks reset requests for unavailable configuration %j", (config) => {+ mocks.config = config;+ render(<ForgotPassword />);+ expect(screen.getByRole("status")).toHaveTextContent(+ "auth:passwordReset.unavailable",+ );+ expect(screen.queryByRole("textbox")).toBeNull();+ expect(mocks.request).not.toHaveBeenCalled();+ });++ it.each([{}, { error: "INVALID_TOKEN" }])(+ "offers another link when the URL cannot be used %j",+ (search) => {+ mocks.search = search;+ render(<ResetPassword />);+ expect(screen.getByRole("alert")).toHaveTextContent(+ "auth:passwordReset.invalidLink",+ );+ expect(+ screen.getByRole("link", { name: "auth:passwordReset.requestNewLink" }),+ ).toHaveAttribute("href", "/auth/forgot-password");+ expect(mocks.reset).not.toHaveBeenCalled();+ },+ );++ it("validates password length and confirmation before submitting", () => {+ render(<ResetPassword />);+ submitPasswords("short");+ expect(screen.getByRole("alert")).toHaveTextContent(+ "auth:passwordReset.passwordLength",+ );+ submitPasswords("new-password", "different-password");+ expect(screen.getByRole("alert")).toHaveTextContent(+ "auth:passwordReset.passwordMismatch",+ );+ expect(mocks.reset).not.toHaveBeenCalled();+ });++ it("submits the token and offers sign-in on success", async () => {+ render(<ResetPassword />);+ submitPasswords();+ await waitFor(() =>+ expect(screen.getByRole("status")).toHaveTextContent(+ "auth:passwordReset.success",+ ),+ );+ expect(mocks.reset).toHaveBeenCalledWith({+ newPassword: "new-password",+ token: "reset-token",+ });+ expect(+ screen.queryByLabelText("auth:passwordReset.newPassword"),+ ).toBeNull();+ expect(+ screen.getByRole("link", { name: "auth:passwordReset.backToSignIn" }),+ ).toHaveAttribute("href", "/auth/sign-in");+ });++ it("handles a token that expires before submission", async () => {+ mocks.reset.mockResolvedValue({ error: { code: "INVALID_TOKEN" } });+ render(<ResetPassword />);+ submitPasswords();+ await waitFor(() =>+ expect(screen.getByRole("alert")).toHaveTextContent(+ "auth:passwordReset.invalidLink",+ ),+ );+ expect(+ screen.queryByLabelText("auth:passwordReset.newPassword"),+ ).toBeNull();+ });++ it("keeps the form usable after a reset network error", async () => {+ mocks.reset.mockRejectedValueOnce(new Error("Network failed"));+ render(<ResetPassword />);+ submitPasswords();+ await waitFor(() =>+ expect(screen.getByRole("alert")).toHaveTextContent(+ "auth:passwordReset.resetError",+ ),+ );+ submitPasswords();+ await waitFor(() =>+ expect(screen.getByRole("status")).toHaveTextContent(+ "auth:passwordReset.success",+ ),+ );+ });+});diff --git a/apps/web/src/routes/auth/reset-password.tsx b/apps/web/src/routes/auth/reset-password.tsxnew file mode 100644index 000000000..6db3a8c8e--- /dev/null+++ b/apps/web/src/routes/auth/reset-password.tsx@@ -0,0 +1,155 @@+import { createFileRoute, Link, useSearch } from "@tanstack/react-router";+import { useState } from "react";+import { useTranslation } from "react-i18next";+import { z } from "zod/v4";+import { AuthLayout } from "@/components/auth/layout";+import PageTitle from "@/components/page-title";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { authClient } from "@/lib/auth-client";++export const Route = createFileRoute("/auth/reset-password")({+ component: ResetPassword,+ validateSearch: z.object({+ token: z.string().optional(),+ error: z.string().optional(),+ }),+});++function ResetPassword() {+ const { t } = useTranslation();+ const search = useSearch({ from: "/auth/reset-password" });+ const [password, setPassword] = useState("");+ const [confirmation, setConfirmation] = useState("");+ const [isPending, setIsPending] = useState(false);+ const [success, setSuccess] = useState(false);+ const [invalidToken, setInvalidToken] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const invalidLink = !search.token || Boolean(search.error) || invalidToken;++ const onSubmit = async (event: React.FormEvent<HTMLFormElement>) => {+ event.preventDefault();+ if (isPending || invalidLink) return;+ if (password.length < 8 || password.length > 128) {+ setError(t("auth:passwordReset.passwordLength"));+ return;+ }+ if (password !== confirmation) {+ setError(t("auth:passwordReset.passwordMismatch"));+ return;+ }+ setIsPending(true);+ setError(null);+ try {+ const result = await authClient.resetPassword({+ newPassword: password,+ token: search.token,+ });+ if (result.error) {+ if (result.error.code === "INVALID_TOKEN") setInvalidToken(true);+ else setError(t("auth:passwordReset.resetError"));+ } else {+ setPassword("");+ setConfirmation("");+ setSuccess(true);+ }+ } catch {+ setError(t("auth:passwordReset.resetError"));+ } finally {+ setIsPending(false);+ }+ };++ return (+ <>+ <PageTitle title={t("auth:passwordReset.resetTitle")} />+ <AuthLayout+ title={t("auth:passwordReset.resetTitle")}+ subtitle={t("auth:passwordReset.resetSubtitle")}+ >+ <div className="space-y-4 mt-4">+ {success ? (+ <p role="status" className="text-sm text-muted-foreground">+ {t("auth:passwordReset.success")}+ </p>+ ) : invalidLink ? (+ <>+ <p role="alert" className="text-sm text-destructive">+ {t("auth:passwordReset.invalidLink")}+ </p>+ <Button+ render={<Link to="/auth/forgot-password" />}+ className="w-full"+ >+ {t("auth:passwordReset.requestNewLink")}+ </Button>+ </>+ ) : (+ <form onSubmit={onSubmit} className="space-y-3">+ <div className="space-y-2">+ <Label htmlFor="new-password">+ {t("auth:passwordReset.newPassword")}+ </Label>+ <Input+ id="new-password"+ type="password"+ autoComplete="new-password"+ required+ minLength={8}+ maxLength={128}+ value={password}+ onChange={(event) => setPassword(event.target.value)}+ disabled={isPending}+ />+ </div>+ <div className="space-y-2">+ <Label htmlFor="confirm-password">+ {t("auth:passwordReset.confirmPassword")}+ </Label>+ <Input+ id="confirm-password"+ type="password"+ autoComplete="new-password"+ required+ minLength={8}+ maxLength={128}+ value={confirmation}+ onChange={(event) => setConfirmation(event.target.value)}+ disabled={isPending}+ aria-describedby={error ? "reset-error" : undefined}+ />+ </div>+ {error && (+ <p+ id="reset-error"+ role="alert"+ className="text-sm text-destructive"+ >+ {error}+ </p>+ )}+ <Button+ type="submit"+ size="sm"+ className="w-full"+ disabled={isPending}+ >+ {isPending+ ? t("auth:passwordReset.resetting")+ : t("auth:passwordReset.resetPassword")}+ </Button>+ </form>+ )}+ <Button+ variant="ghost"+ render={<Link to="/auth/sign-in" />}+ className="w-full text-muted-foreground"+ >+ {t("auth:passwordReset.backToSignIn")}+ </Button>+ </div>+ </AuthLayout>+ </>+ );+}diff --git a/apps/web/src/routes/auth/sign-in.tsx b/apps/web/src/routes/auth/sign-in.tsxindex 9ba6e695a..2197db2bb 100644--- a/apps/web/src/routes/auth/sign-in.tsx+++ b/apps/web/src/routes/auth/sign-in.tsx@@ -523,6 +523,7 @@ function SignIn() {/>) : (<SignInForm+ canResetPassword={config?.hasSmtp}defaultEmail={defaultEmail}onSuccess={handleSignInSuccess}/>diff --git a/i18n/az-AZ.json b/i18n/az-AZ.jsonindex 4b21a3408..dd737bd87 100644--- a/i18n/az-AZ.json+++ b/i18n/az-AZ.json@@ -340,6 +340,30 @@"nameRequired": "Ad tələb olunur","nameShort": "Ad ən azı 2 simvoldan ibarət olmalıdır"}+ },+ "passwordReset": {+ "forgotPassword": "Forgot password?",+ "requestTitle": "Reset your password",+ "requestSubtitle": "Enter your email and we’ll send you a password reset link.",+ "sendLink": "Send reset link",+ "sending": "Sending…",+ "sent": "If an account exists for this email, you’ll receive a password reset link. Check your inbox and spam folder.",+ "requestError": "Could not request a reset link. Please try again.",+ "unavailable": "Password reset is unavailable. Contact your instance administrator.",+ "configError": "Could not reach the server. Please reload the page to try again.",+ "resetTitle": "Choose a new password",+ "resetSubtitle": "Use 8–128 characters for your new password.",+ "newPassword": "New password",+ "confirmPassword": "Confirm new password",+ "passwordMismatch": "The passwords do not match.",+ "passwordLength": "Use between 8 and 128 characters.",+ "resetPassword": "Reset password",+ "resetting": "Resetting…",+ "invalidLink": "This reset link is invalid or has expired. Request a new link to continue.",+ "requestNewLink": "Request a new link",+ "resetError": "Could not reset your password. Please try again.",+ "success": "Your password has been reset. Sign in with your new password.",+ "backToSignIn": "Back to sign in"}},"settings": {diff --git a/i18n/de-DE.json b/i18n/de-DE.jsonindex 31fae6311..bdaa5b66e 100644--- a/i18n/de-DE.json+++ b/i18n/de-DE.json@@ -340,6 +340,30 @@"nameRequired": "Name ist erforderlich","nameShort": "Der Name muss mindestens 2 Zeichen lang sein"}+ },+ "passwordReset": {+ "forgotPassword": "Passwort vergessen?",+ "requestTitle": "Passwort zurücksetzen",+ "requestSubtitle": "Gib deine E-Mail-Adresse ein. Wir senden dir einen Link zum Zurücksetzen deines Passworts.",+ "sendLink": "Link senden",+ "sending": "Wird gesendet…",+ "sent": "Wenn ein Konto mit dieser E-Mail-Adresse existiert, erhältst du einen Link zum Zurücksetzen deines Passworts. Prüfe deinen Posteingang und Spamordner.",+ "requestError": "Der Link konnte nicht angefordert werden. Bitte versuche es erneut.",+ "unavailable": "Das Zurücksetzen des Passworts ist nicht verfügbar. Wende dich an die Administration deiner Instanz.",+ "configError": "Der Server ist nicht erreichbar. Lade die Seite neu, um es erneut zu versuchen.",+ "resetTitle": "Neues Passwort wählen",+ "resetSubtitle": "Verwende 8–128 Zeichen für dein neues Passwort.",+ "newPassword": "Neues Passwort",+ "confirmPassword": "Neues Passwort bestätigen",+ "passwordMismatch": "Die Passwörter stimmen nicht überein.",+ "passwordLength": "Verwende zwischen 8 und 128 Zeichen.",+ "resetPassword": "Passwort zurücksetzen",+ "resetting": "Wird zurückgesetzt…",+ "invalidLink": "Dieser Link ist ungültig oder abgelaufen. Fordere einen neuen Link an.",+ "requestNewLink": "Neuen Link anfordern",+ "resetError": "Das Passwort konnte nicht zurückgesetzt werden. Bitte versuche es erneut.",+ "success": "Dein Passwort wurde zurückgesetzt. Melde dich mit deinem neuen Passwort an.",+ "backToSignIn": "Zurück zur Anmeldung"}},"settings": {diff --git a/i18n/el-GR.json b/i18n/el-GR.jsonindex f98b5d1dd..fca9d57bd 100644--- a/i18n/el-GR.json+++ b/i18n/el-GR.json@@ -340,6 +340,30 @@"nameRequired": "Το όνομα είναι υποχρεωτικό","nameShort": "Το όνομα πρέπει να έχει τουλάχιστον 2 χαρακτήρες"}+ },+ "passwordReset": {+ "forgotPassword": "Forgot password?",+ "requestTitle": "Reset your password",+ "requestSubtitle": "Enter your email and we’ll send you a password reset link.",+ "sendLink": "Send reset link",+ "sending": "Sending…",+ "sent": "If an account exists for this email, you’ll receive a password reset link. Check your inbox and spam folder.",+ "requestError": "Could not request a reset link. Please try again.",+ "unavailable": "Password reset is unavailable. Contact your instance administrator.",+ "configError": "Could not reach the server. Please reload the page to try again.",+ "resetTitle": "Choose a new password",+ "resetSubtitle": "Use 8–128 characters for your new password.",+ "newPassword": "New password",+ "confirmPassword": "Confirm new password",+ "passwordMismatch": "The passwords do not match.",+ "passwordLength": "Use between 8 and 128 characters.",+ "resetPassword": "Reset password",+ "resetting": "Resetting…",+ "invalidLink": "This reset link is invalid or has expired. Request a new link to continue.",+ "requestNewLink": "Request a new link",+ "resetError": "Could not reset your password. Please try again.",+ "success": "Your password has been reset. Sign in with your new password.",+ "backToSignIn": "Back to sign in"}},"settings": {diff --git a/i18n/en-US.json b/i18n/en-US.jsonindex f91e4e674..da0deae5b 100644--- a/i18n/en-US.json+++ b/i18n/en-US.json@@ -340,6 +340,30 @@"nameRequired": "Name is required","nameShort": "Name must be at least 2 characters"}+ },+ "passwordReset": {+ "forgotPassword": "Forgot password?",+ "requestTitle": "Reset your password",+ "requestSubtitle": "Enter your email and we’ll send you a password reset link.",+ "sendLink": "Send reset link",+ "sending": "Sending…",+ "sent": "If an account exists for this email, you’ll receive a password reset link. Check your inbox and spam folder.",+ "requestError": "Could not request a reset link. Please try again.",+ "unavailable": "Password reset is unavailable. Contact your instance administrator.",+ "configError": "Could not reach the server. Please reload the page to try again.",+ "resetTitle": "Choose a new password",+ "resetSubtitle": "Use 8–128 characters for your new password.",+ "newPassword": "New password",+ "confirmPassword": "Confirm new password",+ "passwordMismatch": "The passwords do not match.",+ "passwordLength": "Use between 8 and 128 characters.",+ "resetPassword": "Reset password",+ "resetting": "Resetting…",+ "invalidLink": "This reset link is invalid or has expired. Request a new link to continue.",+ "requestNewLink": "Request a new link",+ "resetError": "Could not reset your password. Please try again.",+ "success": "Your password has been reset. Sign in with your new password.",+ "backToSignIn": "Back to sign in"}},"settings": {diff --git a/i18n/es-ES.json b/i18n/es-ES.jsonindex 30d8f7f5b..9f264a776 100644--- a/i18n/es-ES.json+++ b/i18n/es-ES.json@@ -340,6 +340,30 @@"nameRequired": "El nombre es obligatorio","nameShort": "Tu nombre debe tener al menos 2 caracteres"}+ },+ "passwordReset": {+ "forgotPassword": "Forgot password?",+ "requestTitle": "Reset your password",+ "requestSubtitle": "Enter your email and we’ll send you a password reset link.",+ "sendLink": "Send reset link",+ "sending": "Sending…",+ "sent": "If an account exists for this email, you’ll receive a password reset link. Check your inbox and spam folder.",+ "requestError": "Could not request a reset link. Please try again.",+ "unavailable": "Password reset is unavailable. Contact your instance administrator.",+ "configError": "Could not reach the server. Please reload the page to try again.",+ "resetTitle": "Choose a new password",+ "resetSubtitle": "Use 8–128 characters for your new password.",+ "newPassword": "New password",+ "confirmPassword": "Confirm new password",+ "passwordMismatch": "The passwords do not match.",+ "passwordLength": "Use between 8 and 128 characters.",+ "resetPassword": "Reset password",+ "resetting": "Resetting…",+ "invalidLink": "This reset link is invalid or has expired. Request a new link to continue.",+ "requestNewLink": "Request a new link",+ "resetError": "Could not reset your password. Please try again.",+ "success": "Your password has been reset. Sign in with your new password.",+ "backToSignIn": "Back to sign in"}},"settings": {diff --git a/i18n/fr-FR.json b/i18n/fr-FR.jsonindex 7a0849e70..8f0eaa0e2 100644--- a/i18n/fr-FR.json+++ b/i18n/fr-FR.json@@ -340,6 +340,30 @@"nameRequired": "Le nom est requis","nameShort": "Le nom doit contenir au moins 2 caractères"}+ },+ "passwordReset": {+ "forgotPassword": "Forgot password?",+ "requestTitle": "Reset your password",+ "requestSubtitle": "Enter your email and we’ll send you a password reset link.",+ "sendLink": "Send reset link",+ "sending": "Sending…",+ "sent": "If an account exists for this email, you’ll receive a password reset link. Check your inbox and spam folder.",+ "requestError": "Could not request a reset link. Please try again.",+ "unavailable": "Password reset is unavailable. Contact your instance administrator.",+ "configError": "Could not reach the server. Please reload the page to try again.",+ "resetTitle": "Choose a new password",+ "resetSubtitle": "Use 8–128 characters for your new password.",+ "newPassword": "New password",+ "confirmPassword": "Confirm new password",+ "passwordMismatch": "The passwords do not match.",+ "passwordLength": "Use between 8 and 128 characters.",+ "resetPassword": "Reset password",+ "resetting": "Resetting…",+ "invalidLink": "This reset link is invalid or has expired. Request a new link to continue.",+ "requestNewLink": "Request a new link",+ "resetError": "Could not reset your password. Please try again.",+ "success": "Your password has been reset. Sign in with your new password.",+ "backToSignIn": "Back to sign in"}},"settings": {diff --git a/i18n/hi-IN.json b/i18n/hi-IN.jsonindex 65ab3d7a3..ddd30fab9 100644--- a/i18n/hi-IN.json+++ b/i18n/hi-IN.json@@ -340,6 +340,30 @@"nameRequired": "नाम आवश्यक है","nameShort": "नाम कम से कम 2 अक्षरों का होना चाहिए"}+ },+ "passwordReset": {+ "forgotPassword": "Forgot password?",+ "requestTitle": "Reset your password",+ "requestSubtitle": "Enter your email and we’ll send you a password reset link.",+ "sendLink": "Send reset link",+ "sending": "Sending…",+ "sent": "If an account exists for this email, you’ll receive a password reset link. Check your inbox and spam folder.",+ "requestError": "Could not request a reset link. Please try again.",+ "unavailable": "Password reset is unavailable. Contact your instance administrator.",+ "configError": "Could not reach the server. Please reload the page to try again.",+ "resetTitle": "Choose a new password",+ "resetSubtitle": "Use 8–128 characters for your new password.",+ "newPassword": "New password",+ "confirmPassword": "Confirm new password",+ "passwordMismatch": "The passwords do not match.",+ "passwordLength": "Use between 8 and 128 characters.",+ "resetPassword": "Reset password",+ "resetting": "Resetting…",+ "invalidLink": "This reset link is invalid or has expired. Request a new link to continue.",+ "requestNewLink": "Request a new link",+ "resetError": "Could not reset your password. Please try again.",+ "success": "Your password has been reset. Sign in with your new password.",+ "backToSignIn": "Back to sign in"}},"settings": {diff --git a/i18n/id-ID.json b/i18n/id-ID.jsonindex 80a3e666f..16f736037 100644--- a/i18n/id-ID.json+++ b/i18n/id-ID.json@@ -340,6 +340,30 @@"nameRequired": "Nama wajib diisi","nameShort": "Nama harus minimal 2 karakter"}+ },+ "passwordReset": {+ "forgotPassword": "Forgot password?",+ "requestTitle": "Reset your password",+ "requestSubtitle": "Enter your email and we’ll send you a password reset link.",+ "sendLink": "Send reset link",+ "sending": "Sending…",+ "sent": "If an account exists for this email, you’ll receive a password reset link. Check your inbox and spam folder.",+ "requestError": "Could not request a reset link. Please try again.",+ "unavailable": "Password reset is unavailable. Contact your instance administrator.",+ "configError": "Could not reach the server. Please reload the page to try again.",+ "resetTitle": "Choose a new password",+ "resetSubtitle": "Use 8–128 characters for your new password.",+ "newPassword": "New password",+ "confirmPassword": "Confirm new password",+ "passwordMismatch": "The passwords do not match.",+ "passwordLength": "Use between 8 and 128 characters.",+ "resetPassword": "Reset password",+ "resetting": "Resetting…",+ "invalidLink": "This reset link is invalid or has expired. Request a new link to continue.",+ "requestNewLink": "Request a new link",+ "resetError": "Could not reset your password. Please try again.",+ "success": "Your password has been reset. Sign in with your new password.",+ "backToSignIn": "Back to sign in"}},"settings": {diff --git a/i18n/it-IT.json b/i18n/it-IT.jsonindex b9b65634f..f671f1cda 100644--- a/i18n/it-IT.json+++ b/i18n/it-IT.json@@ -340,6 +340,30 @@"nameRequired": "Il nome è obbligatorio","nameShort": "Il nome deve essere di almeno 2 caratteri"}+ },+ "passwordReset": {+ "forgotPassword": "Forgot password?",+ "requestTitle": "Reset your password",+ "requestSubtitle": "Enter your email and we’ll send you a password reset link.",+ "sendLink": "Send reset link",+ "sending": "Sending…",+ "sent": "If an account exists for this email, you’ll receive a password reset link. Check your inbox and spam folder.",+ "requestError": "Could not request a reset link. Please try again.",+ "unavailable": "Password reset is unavailable. Contact your instance administrator.",+ "configError": "Could not reach the server. Please reload the page to try again.",+ "resetTitle": "Choose a new password",+ "resetSubtitle": "Use 8–128 characters for your new password.",+ "newPassword": "New password",+ "confirmPassword": "Confirm new password",+ "passwordMismatch": "The passwords do not match.",+ "passwordLength": "Use between 8 and 128 characters.",+ "resetPassword": "Reset password",+ "resetting": "Resetting…",+ "invalidLink": "This reset link is invalid or has expired. Request a new link to continue.",+ "requestNewLink": "Request a new link",+ "resetError": "Could not reset your password. Please try again.",+ "success": "Your password has been reset. Sign in with your new password.",+ "backToSignIn": "Back to sign in"}},"settings": {diff --git a/i18n/ja-JP.json b/i18n/ja-JP.jsonindex b897e63d7..030ad1969 100644--- a/i18n/ja-JP.json+++ b/i18n/ja-JP.json@@ -340,6 +340,30 @@"nameRequired": "名前を入力してください","nameShort": "名前は2文字以上で入力してください"}+ },+ "passwordReset": {+ "forgotPassword": "Forgot password?",+ "requestTitle": "Reset your password",+ "requestSubtitle": "Enter your email and we’ll send you a password reset link.",+ "sendLink": "Send reset link",+ "sending": "Sending…",+ "sent": "If an account exists for this email, you’ll receive a password reset link. Check your inbox and spam folder.",+ "requestError": "Could not request a reset link. Please try again.",+ "unavailable": "Password reset is unavailable. Contact your instance administrator.",+ "configError": "Could not reach the server. Please reload the page to try again.",+ "resetTitle": "Choose a new password",+ "resetSubtitle": "Use 8–128 characters for your new password.",+ "newPassword": "New password",+ "confirmPassword": "Confirm new password",+ "passwordMismatch": "The passwords do not match.",+ "passwordLength": "Use between 8 and 128 characters.",+ "resetPassword": "Reset password",+ "resetting": "Resetting…",+ "invalidLink": "This reset link is invalid or has expired. Request a new link to continue.",+ "requestNewLink": "Request a new link",+ "resetError": "Could not reset your password. Please try again.",+ "success": "Your password has been reset. Sign in with your new password.",+ "backToSignIn": "Back to sign in"}},"settings": {diff --git a/i18n/ko-KR.json b/i18n/ko-KR.jsonindex 4b249968b..9621eb5c7 100644--- a/i18n/ko-KR.json+++ b/i18n/ko-KR.json@@ -340,6 +340,30 @@"nameRequired": "이름은 필수입니다","nameShort": "이름은 2자 이상이어야 합니다"}+ },+ "passwordReset": {+ "forgotPassword": "Forgot password?",+ "requestTitle": "Reset your password",+ "requestSubtitle": "Enter your email and we’ll send you a password reset link.",+ "sendLink": "Send reset link",+ "sending": "Sending…",+ "sent": "If an account exists for this email, you’ll receive a password reset link. Check your inbox and spam folder.",+ "requestError": "Could not request a reset link. Please try again.",+ "unavailable": "Password reset is unavailable. Contact your instance administrator.",+ "configError": "Could not reach the server. Please reload the page to try again.",+ "resetTitle": "Choose a new password",+ "resetSubtitle": "Use 8–128 characters for your new password.",+ "newPassword": "New password",+ "confirmPassword": "Confirm new password",+ "passwordMismatch": "The passwords do not match.",+ "passwordLength": "Use between 8 and 128 characters.",+ "resetPassword": "Reset password",+ "resetting": "Resetting…",+ "invalidLink": "This reset link is invalid or has expired. Request a new link to continue.",+ "requestNewLink": "Request a new link",+ "resetError": "Could not reset your password. Please try again.",+ "success": "Your password has been reset. Sign in with your new password.",+ "backToSignIn": "Back to sign in"}},"settings": {diff --git a/i18n/mk-MK.json b/i18n/mk-MK.jsonindex 33e6e77d9..28e117aa8 100644--- a/i18n/mk-MK.json+++ b/i18n/mk-MK.json@@ -340,6 +340,30 @@"nameRequired": "Името е задолжително","nameShort": "Името мора да има најмалку 2 знаци"}+ },+ "passwordReset": {+ "forgotPassword": "Forgot password?",+ "requestTitle": "Reset your password",+ "requestSubtitle": "Enter your email and we’ll send you a password reset link.",+ "sendLink": "Send reset link",+ "sending": "Sending…",+ "sent": "If an account exists for this email, you’ll receive a password reset link. Check your inbox and spam folder.",+ "requestError": "Could not request a reset link. Please try again.",+ "unavailable": "Password reset is unavailable. Contact your instance administrator.",+ "configError": "Could not reach the server. Please reload the page to try again.",+ "resetTitle": "Choose a new password",+ "resetSubtitle": "Use 8–128 characters for your new password.",+ "newPassword": "New password",+ "confirmPassword": "Confirm new password",+ "passwordMismatch": "The passwords do not match.",+ "passwordLength": "Use between 8 and 128 characters.",+ "resetPassword": "Reset password",+ "resetting": "Resetting…",+ "invalidLink": "This reset link is invalid or has expired. Request a new link to continue.",+ "requestNewLink": "Request a new link",+ "resetError": "Could not reset your password. Please try again.",+ "success": "Your password has been reset. Sign in with your new password.",+ "backToSignIn": "Back to sign in"}},"settings": {diff --git a/i18n/nl-NL.json b/i18n/nl-NL.jsonindex 193549204..450a6f55b 100644--- a/i18n/nl-NL.json+++ b/i18n/nl-NL.json@@ -340,6 +340,30 @@"nameRequired": "Naam is verplicht","nameShort": "Naam moet minimaal 2 tekens bevatten"}+ },+ "passwordReset": {+ "forgotPassword": "Forgot password?",+ "requestTitle": "Reset your password",+ "requestSubtitle": "Enter your email and we’ll send you a password reset link.",+ "sendLink": "Send reset link",+ "sending": "Sending…",+ "sent": "If an account exists for this email, you’ll receive a password reset link. Check your inbox and spam folder.",+ "requestError": "Could not request a reset link. Please try again.",+ "unavailable": "Password reset is unavailable. Contact your instance administrator.",+ "configError": "Could not reach the server. Please reload the page to try again.",+ "resetTitle": "Choose a new password",+ "resetSubtitle": "Use 8–128 characters for your new password.",+ "newPassword": "New password",+ "confirmPassword": "Confirm new password",+ "passwordMismatch": "The passwords do not match.",+ "passwordLength": "Use between 8 and 128 characters.",+ "resetPassword": "Reset password",+ "resetting": "Resetting…",+ "invalidLink": "This reset link is invalid or has expired. Request a new link to continue.",+ "requestNewLink": "Request a new link",+ "resetError": "Could not reset your password. Please try again.",+ "success": "Your password has been reset. Sign in with your new password.",+ "backToSignIn": "Back to sign in"}},"settings": {diff --git a/i18n/pl-PL.json b/i18n/pl-PL.jsonindex d316da923..2c6bb1243 100644--- a/i18n/pl-PL.json+++ b/i18n/pl-PL.json@@ -340,6 +340,30 @@"nameRequired": "Imię jest wymagane","nameShort": "Imię musi mieć co najmniej 2 znaki"}+ },+ "passwordReset": {+ "forgotPassword": "Forgot password?",+ "requestTitle": "Reset your password",+ "requestSubtitle": "Enter your email and we’ll send you a password reset link.",+ "sendLink": "Send reset link",+ "sending": "Sending…",+ "sent": "If an account exists for this email, you’ll receive a password reset link. Check your inbox and spam folder.",+ "requestError": "Could not request a reset link. Please try again.",+ "unavailable": "Password reset is unavailable. Contact your instance administrator.",+ "configError": "Could not reach the server. Please reload the page to try again.",+ "resetTitle": "Choose a new password",+ "resetSubtitle": "Use 8–128 characters for your new password.",+ "newPassword": "New password",+ "confirmPassword": "Confirm new password",+ "passwordMismatch": "The passwords do not match.",+ "passwordLength": "Use between 8 and 128 characters.",+ "resetPassword": "Reset password",+ "resetting": "Resetting…",+ "invalidLink": "This reset link is invalid or has expired. Request a new link to continue.",+ "requestNewLink": "Request a new link",+ "resetError": "Could not reset your password. Please try again.",+ "success": "Your password has been reset. Sign in with your new password.",+ "backToSignIn": "Back to sign in"}},"navigation": {diff --git a/i18n/pt-BR.json b/i18n/pt-BR.jsonindex b80fa805d..1c528943b 100644--- a/i18n/pt-BR.json+++ b/i18n/pt-BR.json@@ -340,6 +340,30 @@"nameRequired": "O nome é obrigatório","nameShort": "O nome deve ter pelo menos 2 caracteres"}+ },+ "passwordReset": {+ "forgotPassword": "Forgot password?",+ "requestTitle": "Reset your password",+ "requestSubtitle": "Enter your email and we’ll send you a password reset link.",+ "sendLink": "Send reset link",+ "sending": "Sending…",+ "sent": "If an account exists for this email, you’ll receive a password reset link. Check your inbox and spam folder.",+ "requestError": "Could not request a reset link. Please try again.",+ "unavailable": "Password reset is unavailable. Contact your instance administrator.",+ "configError": "Could not reach the server. Please reload the page to try again.",+ "resetTitle": "Choose a new password",+ "resetSubtitle": "Use 8–128 characters for your new password.",+ "newPassword": "New password",+ "confirmPassword": "Confirm new password",+ "passwordMismatch": "The passwords do not match.",+ "passwordLength": "Use between 8 and 128 characters.",+ "resetPassword": "Reset password",+ "resetting": "Resetting…",+ "invalidLink": "This reset link is invalid or has expired. Request a new link to continue.",+ "requestNewLink": "Request a new link",+ "resetError": "Could not reset your password. Please try again.",+ "success": "Your password has been reset. Sign in with your new password.",+ "backToSignIn": "Back to sign in"}},"settings": {diff --git a/i18n/ru-RU.json b/i18n/ru-RU.jsonindex 7540f2424..045efd812 100644--- a/i18n/ru-RU.json+++ b/i18n/ru-RU.json@@ -340,6 +340,30 @@"nameRequired": "Имя обязательно","nameShort": "Имя должно содержать не менее 2 символов"}+ },+ "passwordReset": {+ "forgotPassword": "Forgot password?",+ "requestTitle": "Reset your password",+ "requestSubtitle": "Enter your email and we’ll send you a password reset link.",+ "sendLink": "Send reset link",+ "sending": "Sending…",+ "sent": "If an account exists for this email, you’ll receive a password reset link. Check your inbox and spam folder.",+ "requestError": "Could not request a reset link. Please try again.",+ "unavailable": "Password reset is unavailable. Contact your instance administrator.",+ "configError": "Could not reach the server. Please reload the page to try again.",+ "resetTitle": "Choose a new password",+ "resetSubtitle": "Use 8–128 characters for your new password.",+ "newPassword": "New password",+ "confirmPassword": "Confirm new password",+ "passwordMismatch": "The passwords do not match.",+ "passwordLength": "Use between 8 and 128 characters.",+ "resetPassword": "Reset password",+ "resetting": "Resetting…",+ "invalidLink": "This reset link is invalid or has expired. Request a new link to continue.",+ "requestNewLink": "Request a new link",+ "resetError": "Could not reset your password. Please try again.",+ "success": "Your password has been reset. Sign in with your new password.",+ "backToSignIn": "Back to sign in"}},"settings": {diff --git a/i18n/schema.json b/i18n/schema.jsonindex a6bad11d0..2ed428dbd 100644--- a/i18n/schema.json+++ b/i18n/schema.json@@ -1343,6 +1343,102 @@"toast","validation"]+ },+ "passwordReset": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "forgotPassword": {+ "type": "string"+ },+ "requestTitle": {+ "type": "string"+ },+ "requestSubtitle": {+ "type": "string"+ },+ "sendLink": {+ "type": "string"+ },+ "sending": {+ "type": "string"+ },+ "sent": {+ "type": "string"+ },+ "requestError": {+ "type": "string"+ },+ "unavailable": {+ "type": "string"+ },+ "configError": {+ "type": "string"+ },+ "resetTitle": {+ "type": "string"+ },+ "resetSubtitle": {+ "type": "string"+ },+ "newPassword": {+ "type": "string"+ },+ "confirmPassword": {+ "type": "string"+ },+ "passwordMismatch": {+ "type": "string"+ },+ "passwordLength": {+ "type": "string"+ },+ "resetPassword": {+ "type": "string"+ },+ "resetting": {+ "type": "string"+ },+ "invalidLink": {+ "type": "string"+ },+ "requestNewLink": {+ "type": "string"+ },+ "resetError": {+ "type": "string"+ },+ "success": {+ "type": "string"+ },+ "backToSignIn": {+ "type": "string"+ }+ },+ "required": [+ "forgotPassword",+ "requestTitle",+ "requestSubtitle",+ "sendLink",+ "sending",+ "sent",+ "requestError",+ "unavailable",+ "configError",+ "resetTitle",+ "resetSubtitle",+ "newPassword",+ "confirmPassword",+ "passwordMismatch",+ "passwordLength",+ "resetPassword",+ "resetting",+ "invalidLink",+ "requestNewLink",+ "resetError",+ "success",+ "backToSignIn"+ ]}},"required": [@@ -1357,7 +1453,8 @@"signUpForm","invitation","onboarding",- "profileSetup"+ "profileSetup",+ "passwordReset"]},"settings": {diff --git a/i18n/tr-TR.json b/i18n/tr-TR.jsonindex d34a6bbbb..61de9779c 100644--- a/i18n/tr-TR.json+++ b/i18n/tr-TR.json@@ -340,6 +340,30 @@"nameRequired": "Ad gereklidir","nameShort": "Ad en az 2 karakter olmalıdır"}+ },+ "passwordReset": {+ "forgotPassword": "Forgot password?",+ "requestTitle": "Reset your password",+ "requestSubtitle": "Enter your email and we’ll send you a password reset link.",+ "sendLink": "Send reset link",+ "sending": "Sending…",+ "sent": "If an account exists for this email, you’ll receive a password reset link. Check your inbox and spam folder.",+ "requestError": "Could not request a reset link. Please try again.",+ "unavailable": "Password reset is unavailable. Contact your instance administrator.",+ "configError": "Could not reach the server. Please reload the page to try again.",+ "resetTitle": "Choose a new password",+ "resetSubtitle": "Use 8–128 characters for your new password.",+ "newPassword": "New password",+ "confirmPassword": "Confirm new password",+ "passwordMismatch": "The passwords do not match.",+ "passwordLength": "Use between 8 and 128 characters.",+ "resetPassword": "Reset password",+ "resetting": "Resetting…",+ "invalidLink": "This reset link is invalid or has expired. Request a new link to continue.",+ "requestNewLink": "Request a new link",+ "resetError": "Could not reset your password. Please try again.",+ "success": "Your password has been reset. Sign in with your new password.",+ "backToSignIn": "Back to sign in"}},"settings": {diff --git a/i18n/uk-UA.json b/i18n/uk-UA.jsonindex 4b08f14ac..547306e00 100644--- a/i18n/uk-UA.json+++ b/i18n/uk-UA.json@@ -340,6 +340,30 @@"nameRequired": "Ім'я є обов'язковим","nameShort": "Ім'я має містити щонайменше 2 символи"}+ },+ "passwordReset": {+ "forgotPassword": "Forgot password?",+ "requestTitle": "Reset your password",+ "requestSubtitle": "Enter your email and we’ll send you a password reset link.",+ "sendLink": "Send reset link",+ "sending": "Sending…",+ "sent": "If an account exists for this email, you’ll receive a password reset link. Check your inbox and spam folder.",+ "requestError": "Could not request a reset link. Please try again.",+ "unavailable": "Password reset is unavailable. Contact your instance administrator.",+ "configError": "Could not reach the server. Please reload the page to try again.",+ "resetTitle": "Choose a new password",+ "resetSubtitle": "Use 8–128 characters for your new password.",+ "newPassword": "New password",+ "confirmPassword": "Confirm new password",+ "passwordMismatch": "The passwords do not match.",+ "passwordLength": "Use between 8 and 128 characters.",+ "resetPassword": "Reset password",+ "resetting": "Resetting…",+ "invalidLink": "This reset link is invalid or has expired. Request a new link to continue.",+ "requestNewLink": "Request a new link",+ "resetError": "Could not reset your password. Please try again.",+ "success": "Your password has been reset. Sign in with your new password.",+ "backToSignIn": "Back to sign in"}},"settings": {diff --git a/i18n/vi-VN.json b/i18n/vi-VN.jsonindex 2820c45ce..9d79e0fe5 100644--- a/i18n/vi-VN.json+++ b/i18n/vi-VN.json@@ -340,6 +340,30 @@"nameRequired": "Cần có tên","nameShort": "Tên phải có ít nhất 2 ký tự"}+ },+ "passwordReset": {+ "forgotPassword": "Forgot password?",+ "requestTitle": "Reset your password",+ "requestSubtitle": "Enter your email and we’ll send you a password reset link.",+ "sendLink": "Send reset link",+ "sending": "Sending…",+ "sent": "If an account exists for this email, you’ll receive a password reset link. Check your inbox and spam folder.",+ "requestError": "Could not request a reset link. Please try again.",+ "unavailable": "Password reset is unavailable. Contact your instance administrator.",+ "configError": "Could not reach the server. Please reload the page to try again.",+ "resetTitle": "Choose a new password",+ "resetSubtitle": "Use 8–128 characters for your new password.",+ "newPassword": "New password",+ "confirmPassword": "Confirm new password",+ "passwordMismatch": "The passwords do not match.",+ "passwordLength": "Use between 8 and 128 characters.",+ "resetPassword": "Reset password",+ "resetting": "Resetting…",+ "invalidLink": "This reset link is invalid or has expired. Request a new link to continue.",+ "requestNewLink": "Request a new link",+ "resetError": "Could not reset your password. Please try again.",+ "success": "Your password has been reset. Sign in with your new password.",+ "backToSignIn": "Back to sign in"}},"settings": {diff --git a/i18n/zh-CN.json b/i18n/zh-CN.jsonindex 6e80af28e..d682f54a6 100644--- a/i18n/zh-CN.json+++ b/i18n/zh-CN.json@@ -340,6 +340,30 @@"nameRequired": "名称不能为空","nameShort": "姓名至少需要 2 个字符"}+ },+ "passwordReset": {+ "forgotPassword": "Forgot password?",+ "requestTitle": "Reset your password",+ "requestSubtitle": "Enter your email and we’ll send you a password reset link.",+ "sendLink": "Send reset link",+ "sending": "Sending…",+ "sent": "If an account exists for this email, you’ll receive a password reset link. Check your inbox and spam folder.",+ "requestError": "Could not request a reset link. Please try again.",+ "unavailable": "Password reset is unavailable. Contact your instance administrator.",+ "configError": "Could not reach the server. Please reload the page to try again.",+ "resetTitle": "Choose a new password",+ "resetSubtitle": "Use 8–128 characters for your new password.",+ "newPassword": "New password",+ "confirmPassword": "Confirm new password",+ "passwordMismatch": "The passwords do not match.",+ "passwordLength": "Use between 8 and 128 characters.",+ "resetPassword": "Reset password",+ "resetting": "Resetting…",+ "invalidLink": "This reset link is invalid or has expired. Request a new link to continue.",+ "requestNewLink": "Request a new link",+ "resetError": "Could not reset your password. Please try again.",+ "success": "Your password has been reset. Sign in with your new password.",+ "backToSignIn": "Back to sign in"}},"settings": {diff --git a/packages/email/src/send-email.tsx b/packages/email/src/send-email.tsxindex d08f8adf2..792d21215 100644--- a/packages/email/src/send-email.tsx+++ b/packages/email/src/send-email.tsx@@ -2,6 +2,7 @@ import { render } from "@react-email/components";import { config } from "dotenv-mono";import * as nodemailer from "nodemailer";import { getSmtpTransportOptions, isSmtpConfigured } from "./smtp-config";+import { getSmtpErrorDetails } from "./smtp-error-details";import type { MagicLinkEmailProps } from "./templates/magic-link";import MagicLinkEmail from "./templates/magic-link";import NotificationEmail, {@@ -64,7 +65,13 @@ export const sendPasswordResetEmail = async (subject: string,data: PasswordResetEmailProps,) => {- const emailTemplate = await render(PasswordResetEmail(data));+ let emailTemplate: string;+ try {+ emailTemplate = await render(PasswordResetEmail(data));+ } catch {+ console.error("Error rendering password reset email");+ return;+ }try {await transporter.sendMail({from: process.env.SMTP_FROM,@@ -73,7 +80,10 @@ export const sendPasswordResetEmail = async (html: emailTemplate,});} catch (error) {- console.error("Error sending password reset email", error);+ console.error(+ "Error sending password reset email",+ getSmtpErrorDetails(error),+ );}};diff --git a/packages/email/src/smtp-error-details.test.ts b/packages/email/src/smtp-error-details.test.tsnew file mode 100644index 000000000..c3dfab9ce--- /dev/null+++ b/packages/email/src/smtp-error-details.test.ts@@ -0,0 +1,25 @@+import { expect, it } from "vitest";+import { getSmtpErrorDetails } from "./smtp-error-details";++it("retains safe SMTP diagnostics and omits private fields", () => {+ expect(+ getSmtpErrorDetails({+ code: "EAUTH",+ responseCode: 535,+ response: "[email protected]",+ message: "password",+ command: "AUTH secret",+ stack: "token",+ }),+ ).toEqual({ code: "EAUTH", responseCode: 535 });+});++it.each([+ null,+ "private",+ new Error("private"),+ { code: "private-token", responseCode: "private-response" },+ { code: "private-token", responseCode: Number.POSITIVE_INFINITY },+])("does not pass arbitrary provider data through to logs: %j", (error) => {+ expect(getSmtpErrorDetails(error)).toEqual({ code: "UNKNOWN" });+});diff --git a/packages/email/src/smtp-error-details.ts b/packages/email/src/smtp-error-details.tsnew file mode 100644index 000000000..ee4926595--- /dev/null+++ b/packages/email/src/smtp-error-details.ts@@ -0,0 +1,30 @@+const smtpErrorCodes = new Set([+ "EAUTH",+ "ECONNECTION",+ "EDNS",+ "EENVELOPE",+ "EMESSAGE",+ "ESOCKET",+ "ESTREAM",+ "ETIMEDOUT",+ "ETLS",+]);++// SMTP messages, responses, commands, and stacks can contain addresses,+// credentials or mail content. Only log known categories and numeric status.+export function getSmtpErrorDetails(error: unknown) {+ const details = error && typeof error === "object" ? error : {};+ const code = "code" in details ? details.code : undefined;+ const responseCode =+ "responseCode" in details ? details.responseCode : undefined;+ return {+ code:+ typeof code === "string" && smtpErrorCodes.has(code) ? code : "UNKNOWN",+ ...(typeof responseCode === "number" &&+ Number.isInteger(responseCode) &&+ responseCode >= 400 &&+ responseCode <= 599+ ? { responseCode }+ : {}),+ };+}diff --git a/packages/email/src/templates/password-reset.tsx b/packages/email/src/templates/password-reset.tsxindex d9a40654c..8cdb606e5 100644--- a/packages/email/src/templates/password-reset.tsx+++ b/packages/email/src/templates/password-reset.tsx@@ -24,16 +24,16 @@ const messages = {footer: "Kaneo security email",},de: {- preview: "Setze dein Kaneo-Passwort zurueck",- title: "Passwort zuruecksetzen",+ preview: "Setze dein Kaneo-Passwort zurück",+ title: "Passwort zurücksetzen",subtitleWithName: (name: string) =>- `Hallo ${name}, verwende die Schaltflaeche unten, um ein neues Passwort festzulegen.`,+ `Hallo ${name}, verwende die Schaltfläche unten, um ein neues Passwort festzulegen.`,subtitleDefault:- "Verwende die Schaltflaeche unten, um ein neues Passwort festzulegen.",- cta: "Passwort zuruecksetzen",- expiry: "Dieser Link laeuft in 1 Stunde ab.",+ "Verwende die Schaltfläche unten, um ein neues Passwort festzulegen.",+ cta: "Passwort zurücksetzen",+ expiry: "Dieser Link läuft in 1 Stunde ab.",ignore:- "Wenn du das nicht angefordert hast, werden keine Aenderungen vorgenommen.",+ "Wenn du das nicht angefordert hast, werden keine Änderungen vorgenommen.",footer: "Kaneo Sicherheits-E-Mail",},vi: {diff --git a/tests/api-integration/auth-captcha.test.ts b/tests/api-integration/auth-captcha.test.tsindex 6ef077cad..ae888ec46 100644--- a/tests/api-integration/auth-captcha.test.ts+++ b/tests/api-integration/auth-captcha.test.ts@@ -1,3 +1,4 @@+import * as email from "@kaneo/email";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import db, { schema } from "../../apps/api/src/database";import { createApp } from "../../apps/api/src/index";@@ -22,6 +23,7 @@ const endpoints = [{ providerId: "custom", callbackURL: "http://localhost:5173/dashboard" },],["/sign-in/anonymous", {}],+ ["/request-password-reset", { email: "[email protected]" }],["/sign-in/magic-link",{@@ -50,6 +52,7 @@ function post(path: string, body: unknown, token?: string) {describe("server-side auth CAPTCHA enforcement", () => {beforeEach(async () => {await resetTestDatabase();+ vi.spyOn(email, "isSmtpConfigured").mockReturnValue(true);await createWorkspaceMember();vi.stubEnv("TURNSTILE_SECRET_KEY", "test-only-secret");});diff --git a/tests/api-integration/mocks/email.ts b/tests/api-integration/mocks/email.tsindex 7ccea0d56..d6dfae6c7 100644--- a/tests/api-integration/mocks/email.ts+++ b/tests/api-integration/mocks/email.ts@@ -29,3 +29,11 @@ export async function sendWorkspaceInvitationEmail(export function isSmtpConfigured(): boolean {return false;}++export async function sendPasswordResetEmail(+ _to: string,+ _subject: string,+ _data: unknown,+): Promise<void> {+ return undefined;+}diff --git a/tests/api-integration/password-reset-disabled.test.ts b/tests/api-integration/password-reset-disabled.test.tsnew file mode 100644index 000000000..13b3969ee--- /dev/null+++ b/tests/api-integration/password-reset-disabled.test.ts@@ -0,0 +1,31 @@+import { expect, it, vi } from "vitest";+import { auth } from "../../apps/api/src/auth";++vi.hoisted(() => {+ process.env.DISABLE_LOGIN_FORM = "true";+});++it.each([+ ["/request-password-reset", "POST", { email: "[email protected]" }],+ ["/reset-password", "POST", { token: "token", newPassword: "new-password" }],+ [+ "/reset-password/token?callbackURL=http://localhost:5173/auth/reset-password",+ "GET",+ undefined,+ ],+] as const)(+ "blocks %s when local login is disabled",+ async (path, method, body) => {+ const response = await auth.handler(+ new Request(`http://localhost:1337/api/auth${path}`, {+ method,+ headers: {+ "content-type": "application/json",+ Origin: "http://localhost:5173",+ },+ body: body ? JSON.stringify(body) : undefined,+ }),+ );+ expect(response.status).toBe(403);+ },+);diff --git a/tests/api-integration/password-reset.test.ts b/tests/api-integration/password-reset.test.tsnew file mode 100644index 000000000..ae14b9df1--- /dev/null+++ b/tests/api-integration/password-reset.test.ts@@ -0,0 +1,212 @@+import * as email from "@kaneo/email";+import { eq } from "drizzle-orm";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { auth } from "../../apps/api/src/auth";+import db, { schema } from "../../apps/api/src/database";+import { createApp } from "../../apps/api/src/index";+import { resetTestDatabase } from "./helpers/database";++vi.hoisted(() => {+ process.env.DISABLE_EMAIL_OTP_SIGN_IN = "true";+});++const origin = "http://localhost:5173";+const address = "[email protected]";+const password = "old-password-123";+const newPassword = "new-password-456";+const redirectTo = `${origin}/auth/reset-password`;+function post(path: string, body: unknown) {+ return createApp().app.request(`/api/auth${path}`, {+ method: "POST",+ headers: { "content-type": "application/json", Origin: origin },+ body: JSON.stringify(body),+ });+}++beforeEach(async () => {+ await resetTestDatabase();+ // Better Auth skips origin checks in test mode unless explicitly enabled.+ (await auth.$context).skipOriginCheck = false;+ vi.spyOn(email, "isSmtpConfigured").mockReturnValue(true);+ vi.spyOn(email, "sendPasswordResetEmail").mockResolvedValue();+ expect(+ (+ await post("/sign-up/email", {+ name: "Reset user",+ email: address,+ password,+ locale: "de-DE",+ })+ ).status,+ ).toBe(200);+});+afterEach(() => vi.unstubAllEnvs());++async function requestReset() {+ const response = await post("/request-password-reset", {+ email: address,+ redirectTo,+ });+ expect(response.status).toBe(200);+ await vi.waitFor(() =>+ expect(email.sendPasswordResetEmail).toHaveBeenCalled(),+ );+ const props = vi.mocked(email.sendPasswordResetEmail).mock.calls.at(-1)?.[2];+ expect(props).toEqual(+ expect.objectContaining({ locale: "de-DE", userName: "Reset user" }),+ );+ const link = new URL((props as { resetLink: string }).resetLink);+ expect(link.origin).toBe("http://localhost:1337");+ expect(link.searchParams.get("callbackURL")).toBe(redirectTo);+ expect(vi.mocked(email.sendPasswordResetEmail).mock.calls.at(-1)?.[1]).toBe(+ "Kaneo-Passwort zurücksetzen",+ );+ return { link, token: link.pathname.split("/").at(-1) };+}++describe("password reset with email OTP disabled", () => {+ it("emails a one-hour link, changes the password, revokes sessions and rejects reuse", async () => {+ expect(+ auth.options.plugins.some((plugin) => plugin.id === "email-otp"),+ ).toBe(false);+ const { link, token } = await requestReset();+ const [verification] = await db.select().from(schema.verificationTable);+ expect(verification.expiresAt.getTime() - Date.now()).toBeGreaterThan(+ 3_500_000,+ );+ expect(verification.expiresAt.getTime() - Date.now()).toBeLessThanOrEqual(+ 3_600_000,+ );+ const callback = await createApp().app.request(+ `${link.pathname}${link.search}`,+ );+ expect(callback.status).toBe(302);+ const destination = new URL(callback.headers.get("location") as string);+ expect(destination.origin + destination.pathname).toBe(redirectTo);+ expect(destination.searchParams.get("token")).toBe(token);+ expect(await db.select().from(schema.sessionTable)).not.toHaveLength(0);+ expect((await post("/reset-password", { token, newPassword })).status).toBe(+ 200,+ );+ expect(await db.select().from(schema.sessionTable)).toHaveLength(0);+ expect(+ (await post("/sign-in/email", { email: address, password })).status,+ ).toBe(401);+ expect(+ (await post("/sign-in/email", { email: address, password: newPassword }))+ .status,+ ).toBe(200);+ expect(+ (await post("/reset-password", { token, newPassword: password })).status,+ ).toBe(400);+ });++ it("immediately rejects old cached cookies on session and protected API requests", async () => {+ const context = await auth.$context;+ const cookieCache = context.options.session?.cookieCache;+ if (!cookieCache) throw new Error("Missing cookie cache configuration");+ const originalEnabled = cookieCache.enabled;+ let cookie: string;+ try {+ // Model a cookie issued before upgrading from the cached-session config.+ cookieCache.enabled = true;+ const signIn = await post("/sign-in/email", { email: address, password });+ expect(signIn.status).toBe(200);+ cookie = signIn.headers+ .getSetCookie()+ .map((value) => value.split(";")[0])+ .join("; ");+ expect(cookie.includes("session_data=")).toBe(true);+ } finally {+ cookieCache.enabled = originalEnabled;+ }+ const headers = { Cookie: cookie, Origin: origin };+ const { app } = createApp();+ expect((await app.request("/api/notification", { headers })).status).toBe(+ 200,+ );+ const { token } = await requestReset();+ expect((await post("/reset-password", { token, newPassword })).status).toBe(+ 200,+ );+ expect(await db.select().from(schema.sessionTable)).toHaveLength(0);+ expect((await app.request("/api/notification", { headers })).status).toBe(+ 401,+ );+ const session = await app.request("/api/auth/get-session", { headers });+ expect(await session.json()).toBeNull();+ });++ it("gives the same confirmation for existing and unknown accounts without sending unknown-account mail", async () => {+ const known = await post("/request-password-reset", {+ email: address,+ redirectTo,+ });+ await vi.waitFor(() =>+ expect(email.sendPasswordResetEmail).toHaveBeenCalledTimes(1),+ );+ const unknown = await post("/request-password-reset", {+ email: "[email protected]",+ redirectTo,+ });+ expect(unknown.status).toBe(known.status);+ expect(await unknown.json()).toEqual(await known.json());+ expect(email.sendPasswordResetEmail).toHaveBeenCalledTimes(1);+ });++ it("rejects expired and invalid tokens without changing the password", async () => {+ const { link, token } = await requestReset();+ await db+ .update(schema.verificationTable)+ .set({ expiresAt: new Date(Date.now() - 1000) })+ .where(+ eq(schema.verificationTable.identifier, `reset-password:${token}`),+ );+ const callback = await createApp().app.request(+ `${link.pathname}${link.search}`,+ );+ expect(+ new URL(callback.headers.get("location") as string).searchParams.get(+ "error",+ ),+ ).toBe("INVALID_TOKEN");+ for (const invalid of [token, "invalid-token"]) {+ expect(+ (await post("/reset-password", { token: invalid, newPassword })).status,+ ).toBe(400);+ }+ expect(+ (await post("/sign-in/email", { email: address, password })).status,+ ).toBe(200);+ });++ it("validates passwords without consuming the reset token", async () => {+ const { token } = await requestReset();+ for (const invalid of ["short", "x".repeat(129)]) {+ expect(+ (await post("/reset-password", { token, newPassword: invalid })).status,+ ).toBe(400);+ }+ expect((await post("/reset-password", { token, newPassword })).status).toBe(+ 200,+ );+ });++ it("rejects untrusted redirects and requests without SMTP", async () => {+ expect(+ (+ await post("/request-password-reset", {+ email: address,+ redirectTo: "https://untrusted.example/reset",+ })+ ).status,+ ).toBe(403);+ vi.mocked(email.isSmtpConfigured).mockReturnValue(false);+ expect(+ (await post("/request-password-reset", { email: address, redirectTo }))+ .status,+ ).toBe(403);+ expect(email.sendPasswordResetEmail).not.toHaveBeenCalled();+ expect(await db.select().from(schema.verificationTable)).toHaveLength(0);+ });+});diff --git a/tests/api-integration/session-freshness.test.ts b/tests/api-integration/session-freshness.test.tsindex ce0192a6b..5023f2fc2 100644--- a/tests/api-integration/session-freshness.test.ts+++ b/tests/api-integration/session-freshness.test.ts@@ -53,7 +53,7 @@ describe("API integration: session freshness after profile updates", () => {await resetTestDatabase();});- it("serves the updated user when the session cookie cache is bypassed", async () => {+ it("serves the updated user with and without a cookie-cache bypass", async () => {const { app } = createApp();const cookies = await signUp(app);@@ -64,12 +64,12 @@ describe("API integration: session freshness after profile updates", () => {});expect(update.status).toBe(200);- const cached = (await (+ const current = (await (await app.request("/api/auth/get-session", {headers: { cookie: cookies },})).json()) as SessionResponse;- expect(cached?.user.image).toBeNull();+ expect(current?.user.image).toBe("/api/user/avatar/new-avatar-id");const fresh = (await (await app.request("/api/auth/get-session?disableCookieCache=true", {@@ -79,7 +79,7 @@ describe("API integration: session freshness after profile updates", () => {expect(fresh?.user.image).toBe("/api/user/avatar/new-avatar-id");});- it("refreshes the cached session cookie on get-session", async () => {+ it("keeps profile changes fresh without issuing session-data cookies", async () => {const { app } = createApp();const cookies = await signUp(app);@@ -94,15 +94,19 @@ describe("API integration: session freshness after profile updates", () => {{ headers: { cookie: cookies } },);- expect(refreshed.headers.getSetCookie().length).toBeGreaterThan(0);+ expect(+ refreshed.headers+ .getSetCookie()+ .some((cookie) => cookie.includes("session_data=")),+ ).toBe(false);const nextCookies = applyCookies(cookies, refreshed);- const cached = (await (+ const current = (await (await app.request("/api/auth/get-session", {headers: { cookie: nextCookies },})).json()) as SessionResponse;- expect(cached?.user.name).toBe("Renamed User");+ expect(current?.user.name).toBe("Renamed User");});});diff --git a/tests/api/utils/password-reset-delivery.test.ts b/tests/api/utils/password-reset-delivery.test.tsnew file mode 100644index 000000000..78d8e4738--- /dev/null+++ b/tests/api/utils/password-reset-delivery.test.ts@@ -0,0 +1,62 @@+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import {+ drainPasswordResetDeliveries,+ trackPasswordResetDelivery,+} from "../../../apps/api/src/utils/password-reset-delivery";++beforeEach(() => vi.useFakeTimers());+afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+});++it("waits for pending delivery without delaying the HTTP callback", async () => {+ const delivery = Promise.withResolvers<void>();+ expect(trackPasswordResetDelivery(delivery.promise)).toBeUndefined();+ const drained = vi.fn();+ const drain = drainPasswordResetDeliveries().then(drained);+ await vi.advanceTimersByTimeAsync(1);+ expect(drained).not.toHaveBeenCalled();+ delivery.resolve();+ await drain;+ expect(drained).toHaveBeenCalledOnce();+ expect(vi.getTimerCount()).toBe(0);+});++it("also drains deliveries registered while waiting", async () => {+ const first = Promise.withResolvers<void>();+ const second = Promise.withResolvers<void>();+ trackPasswordResetDelivery(first.promise);+ const drained = vi.fn();+ const drain = drainPasswordResetDeliveries().then(drained);+ trackPasswordResetDelivery(second.promise);+ first.resolve();+ await vi.advanceTimersByTimeAsync(1);+ expect(drained).not.toHaveBeenCalled();+ second.resolve();+ await drain;+});++it("bounds shutdown when the mail server does not respond", async () => {+ const delivery = Promise.withResolvers<void>();+ trackPasswordResetDelivery(delivery.promise);+ const warning = vi.spyOn(console, "warn").mockImplementation(() => {});+ const drain = drainPasswordResetDeliveries(100);+ await vi.advanceTimersByTimeAsync(100);+ await drain;+ expect(warning).toHaveBeenCalledWith(+ "Timed out waiting for password reset email delivery",+ );+ delivery.resolve();+ await drainPasswordResetDeliveries();+});++it("handles rejected preparation without leaking private error details", async () => {+ const log = vi.spyOn(console, "error").mockImplementation(() => {});+ trackPasswordResetDelivery(Promise.reject(new Error("private-reset-token")));+ await drainPasswordResetDeliveries();+ expect(log).toHaveBeenCalledExactlyOnceWith(+ "Password reset email preparation failed",+ );+ expect(vi.getTimerCount()).toBe(0);+});