Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

✨ Set a password from security settings without the reset flow (#2709)

Luke Vella3b409f50696c
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.json
index a2eb80e51..a338a5260 100644
--- a/apps/web/public/locales/en/app.json
+++ b/apps/web/public/locales/en/app.json
@@ -493,8 +493,7 @@
"passwordIncorrect": "Current password is incorrect",
"passwordOrEmailIncorrect": "Invalid email or password",
"passwordRequired": "Password is required",
- "passwordSetupSuccess": "A password reset link has been sent to your email. Follow the link to set your password.",
- "passwordSetupSuccessful": "Password setup successful. You can now login with your email and password.",
+ "passwordSetSuccess": "Your password has been set successfully",
"passwordsMustBeDifferent": "New password must be different from current password",
"passwordStrength": "Password Strength",
"passwordStrengthFair": "Fair",
@@ -631,6 +630,9 @@
"sendResetLink": "Send reset link",
"setEnvironmentVariable": "This value can be changed by setting the <env /> environment variable.",
"setMaxAttendees": "Set max attendees",
+ "setPassword": "Set Password",
+ "setPasswordSectionDescription": "Your account doesn't have a password yet. Set one to sign in with your email address.",
+ "setPasswordTitle": "Set Password",
"settingCalendarSelection": "Setting calendar selection...",
"settingDefaultCalendar": "Setting default calendar...",
"settings": "Settings",
@@ -640,7 +642,6 @@
"setupPasswordAlertDesc": "Set up a password to make logging in faster and more convenient.",
"setupPasswordAlertTitle": "Login quicker with a password",
"setupPasswordButton": "Set up password",
- "setupPasswordDescription": "Your account doesn't have a password yet. Click the button below to send a secure link to your email to set a password.",
"share": "Share",
"showBrandingDescription": "Show your brand identity on your public pages and emails",
"showPassword": "Show password",
diff --git a/apps/web/src/app/[locale]/(space)/settings/security/components/setup-password-form.tsx b/apps/web/src/app/[locale]/(space)/settings/security/components/setup-password-form.tsx
index af2bc50d4..0434ee0b4 100644
--- a/apps/web/src/app/[locale]/(space)/settings/security/components/setup-password-form.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/security/components/setup-password-form.tsx
@@ -1,59 +1,88 @@
"use client";
-import { Alert, AlertDescription } from "@rallly/ui/alert";
+import { zodResolver } from "@hookform/resolvers/zod";
import { Button } from "@rallly/ui/button";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@rallly/ui/form";
import { toast } from "@rallly/ui/sonner";
-import { MailWarningIcon } from "lucide-react";
-import React from "react";
-import { Trans } from "@/i18n/client";
-import { authClient } from "@/lib/auth-client";
+import { useForm } from "react-hook-form";
+import * as z from "zod";
+import { PasswordInput } from "@/components/password-input";
+import { setPasswordAction } from "@/features/auth/actions";
+import { PasswordStrengthMeter } from "@/features/auth/components/password-strength-meter";
+import { usePasswordValidationSchema } from "@/features/auth/schema";
+import { Trans, useTranslation } from "@/i18n/client";
+import { useSafeAction } from "@/lib/safe-action/client";
-export function SetupPasswordForm({ email }: { email: string }) {
- const [isLoading, setIsLoading] = React.useState(false);
- const [isSuccess, setIsSuccess] = React.useState(false);
+export function SetupPasswordForm() {
+ const { t } = useTranslation();
+ const passwordValidation = usePasswordValidationSchema();
+ const form = useForm({
+ defaultValues: { password: "" },
+ resolver: zodResolver(z.object({ password: passwordValidation })),
+ });
+ const { formState } = form;
- const onSubmit = async () => {
- setIsLoading(true);
-
- // For users without passwords, we need to use the password reset flow
- // First request a password reset
- const resetRes = await authClient.requestPasswordReset({
- email,
- redirectTo: `/reset-password?redirectTo=${encodeURIComponent("/settings/security?setupPassword=true")}`,
- });
-
- setIsLoading(false);
-
- if (resetRes.error) {
- toast.error(resetRes.error.message);
- return;
- }
-
- setIsSuccess(true);
- };
+ const setPassword = useSafeAction(setPasswordAction, {
+ onSuccess: () => {
+ form.reset();
+ toast.success(
+ t("passwordSetSuccess", {
+ defaultValue: "Your password has been set successfully",
+ }),
+ );
+ },
+ });
return (
- <div className="space-y-4">
- <Button
- onClick={onSubmit}
- loading={isLoading}
- variant="primary"
- disabled={isSuccess}
+ <Form {...form}>
+ <form
+ onSubmit={form.handleSubmit(async (data) => {
+ await setPassword.executeAsync({ password: data.password });
+ })}
>
- <Trans i18nKey="sendResetLink" defaults="Send reset link" />
- </Button>
- {isSuccess ? (
- <Alert variant="info">
- <MailWarningIcon />
- <AlertDescription>
- <p>
- <Trans
- i18nKey="passwordSetupSuccess"
- defaults="A password reset link has been sent to your email. Follow the link to set your password."
- />
- </p>
- </AlertDescription>
- </Alert>
- ) : null}
- </div>
+ <div className="grid grid-cols-1 gap-4">
+ <FormField
+ control={form.control}
+ name="password"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>
+ <Trans i18nKey="newPassword" defaults="New Password" />
+ </FormLabel>
+ <FormControl>
+ <PasswordInput
+ {...field}
+ autoComplete="new-password"
+ disabled={formState.isSubmitting}
+ placeholder="••••••••"
+ />
+ </FormControl>
+ <PasswordStrengthMeter
+ password={field.value}
+ className="mt-2"
+ />
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+
+ <div className="mt-6">
+ <Button
+ type="submit"
+ loading={formState.isSubmitting}
+ variant="primary"
+ >
+ <Trans i18nKey="setPassword" defaults="Set Password" />
+ </Button>
+ </div>
+ </form>
+ </Form>
);
}
diff --git a/apps/web/src/app/[locale]/(space)/settings/security/page.tsx b/apps/web/src/app/[locale]/(space)/settings/security/page.tsx
index c784be240..d11c0d23f 100644
--- a/apps/web/src/app/[locale]/(space)/settings/security/page.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/security/page.tsx
@@ -1,5 +1,5 @@
import { Alert, AlertDescription } from "@rallly/ui/alert";
-import { InfoIcon, ShieldCheckIcon } from "lucide-react";
+import { InfoIcon } from "lucide-react";
import type { Metadata } from "next";
import type { Params } from "@/app/[locale]/types";
import {
@@ -25,12 +25,7 @@ import { isFeatureEnabled } from "@/lib/feature-flags/server";
import { ChangePasswordForm } from "./components/change-password-form";
import { SetupPasswordForm } from "./components/setup-password-form";
-export default async function SecurityPage({
- searchParams,
-}: {
- searchParams: Promise<{ setupPassword?: string }>;
-}) {
- const { setupPassword } = await searchParams;
+export default async function SecurityPage() {
const user = await requireUser();
const isEmailLoginEnabled = isFeatureEnabled("emailLogin");
@@ -53,64 +48,46 @@ export default async function SecurityPage({
</SettingsPageHeader>
<SettingsPageContent>
{isEmailLoginEnabled ? (
- <>
- {setupPassword ? (
- <Alert variant="success">
- <ShieldCheckIcon />
- <AlertDescription>
- <p>
+ <PageSectionGroup>
+ {hasPassword ? (
+ <PageSection variant="card">
+ <PageSectionHeader>
+ <PageSectionTitle>
<Trans
- i18nKey="passwordSetupSuccessful"
- defaults="Password setup successful. You can now login with your email and password."
+ i18nKey="changePassword"
+ defaults="Change Password"
/>
- </p>
- </AlertDescription>
- </Alert>
- ) : null}
- <PageSectionGroup>
- {hasPassword ? (
- <PageSection variant="card">
- <PageSectionHeader>
- <PageSectionTitle>
- <Trans
- i18nKey="changePassword"
- defaults="Change Password"
- />
- </PageSectionTitle>
- <PageSectionDescription>
- <Trans
- i18nKey="changePasswordDescription"
- defaults="Update your password to keep your account secure"
- />
- </PageSectionDescription>
- </PageSectionHeader>
- <PageSectionContent>
- <ChangePasswordForm />
- </PageSectionContent>
- </PageSection>
- ) : (
- <PageSection variant="card">
- <PageSectionHeader>
- <PageSectionTitle>
- <Trans
- i18nKey="resetPasswordTitle"
- defaults="Reset Password"
- />
- </PageSectionTitle>
- <PageSectionDescription className="max-w-lg">
- <Trans
- i18nKey="setupPasswordDescription"
- defaults="Your account doesn't have a password yet. Click the button below to send a secure link to your email to set a password."
- />
- </PageSectionDescription>
- </PageSectionHeader>
- <PageSectionContent>
- <SetupPasswordForm email={user.email} />
- </PageSectionContent>
- </PageSection>
- )}
- </PageSectionGroup>
- </>
+ </PageSectionTitle>
+ <PageSectionDescription>
+ <Trans
+ i18nKey="changePasswordDescription"
+ defaults="Update your password to keep your account secure"
+ />
+ </PageSectionDescription>
+ </PageSectionHeader>
+ <PageSectionContent>
+ <ChangePasswordForm />
+ </PageSectionContent>
+ </PageSection>
+ ) : (
+ <PageSection variant="card">
+ <PageSectionHeader>
+ <PageSectionTitle>
+ <Trans i18nKey="setPasswordTitle" defaults="Set Password" />
+ </PageSectionTitle>
+ <PageSectionDescription className="max-w-lg">
+ <Trans
+ i18nKey="setPasswordSectionDescription"
+ defaults="Your account doesn't have a password yet. Set one to sign in with your email address."
+ />
+ </PageSectionDescription>
+ </PageSectionHeader>
+ <PageSectionContent>
+ <SetupPasswordForm />
+ </PageSectionContent>
+ </PageSection>
+ )}
+ </PageSectionGroup>
) : (
<Alert>
<InfoIcon />
diff --git a/apps/web/src/features/auth/actions.test.ts b/apps/web/src/features/auth/actions.test.ts
new file mode 100644
index 000000000..c8be65353
--- /dev/null
+++ b/apps/web/src/features/auth/actions.test.ts
@@ -0,0 +1,83 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const setPassword = vi.fn();
+const getUserHasPassword = vi.fn();
+const sendPasswordAddedEmail = vi.fn();
+
+vi.mock("@/lib/auth", () => ({
+ default: { api: { setPassword } },
+}));
+vi.mock("@/features/user/data", () => ({ getUserHasPassword }));
+vi.mock("@rallly/emails/templates/password-added", () => ({
+ sendPasswordAddedEmail,
+}));
+// Infra the action touches after the guard, irrelevant to what these two
+// cases assert. authActionClient itself (via the rate-limit middleware)
+// transitively imports @/env, which isn't configured for vitest, so the
+// action body is tested through the setPasswordForUser export instead of
+// invoking the wrapped safe-action directly — see actions.ts for why.
+vi.mock("@/emails/branding", () => ({
+ getInstanceBranding: vi.fn().mockResolvedValue({}),
+}));
+vi.mock("@/lib/posthog", () => ({ track: vi.fn() }));
+vi.mock("@/i18n/server/get-locale", () => ({
+ getLocale: vi.fn().mockResolvedValue("en"),
+}));
+vi.mock("next/headers", () => ({
+ headers: vi.fn().mockResolvedValue(new Headers()),
+}));
+vi.mock("next/server", () => ({
+ after: vi.fn((fn: () => unknown) => fn()),
+}));
+// The wrapped action reads this flag; its real module imports @/env at load
+// time. setPasswordForUser doesn't touch it, but importing actions.ts pulls
+// the module graph in, so stub it.
+vi.mock("@/lib/feature-flags/server", () => ({
+ isFeatureEnabled: vi.fn().mockReturnValue(true),
+}));
+// actions.ts also defines setPasswordAction at module scope, which chains
+// off authActionClient — that module transitively imports @/env via the
+// rate-limit/KV client. Stub it so importing the module for
+// setPasswordForUser doesn't require a full env.
+const chainable = (): unknown =>
+ new Proxy(() => chainable(), { get: () => () => chainable() });
+vi.mock("@/lib/safe-action/server", () => ({
+ authActionClient: chainable(),
+ createRateLimitMiddleware: vi.fn(),
+}));
+
+describe("setPasswordForUser", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("refuses to overwrite an existing password", async () => {
+ getUserHasPassword.mockResolvedValue(true);
+
+ const { setPasswordForUser } = await import("./actions");
+
+ await expect(
+ setPasswordForUser({
+ user: { id: "user-1", email: "[email protected]", locale: undefined },
+ password: "correct horse battery staple",
+ }),
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
+ expect(setPassword).not.toHaveBeenCalled();
+ });
+
+ it("sets the password when no credential account exists", async () => {
+ getUserHasPassword.mockResolvedValue(false);
+
+ const { setPasswordForUser } = await import("./actions");
+ await setPasswordForUser({
+ user: { id: "user-1", email: "[email protected]", locale: undefined },
+ password: "correct horse battery staple",
+ });
+
+ expect(setPassword).toHaveBeenCalledWith(
+ expect.objectContaining({
+ body: { newPassword: "correct horse battery staple" },
+ }),
+ );
+ });
+});
diff --git a/apps/web/src/features/auth/actions.ts b/apps/web/src/features/auth/actions.ts
new file mode 100644
index 000000000..469c4d67e
--- /dev/null
+++ b/apps/web/src/features/auth/actions.ts
@@ -0,0 +1,85 @@
+"use server";
+import { sendPasswordAddedEmail } from "@rallly/emails/templates/password-added";
+import { headers } from "next/headers";
+import { after } from "next/server";
+import * as z from "zod";
+import { getInstanceBranding } from "@/emails/branding";
+import { passwordSchema } from "@/features/auth/schema";
+import { getUserHasPassword } from "@/features/user/data";
+import { getLocale } from "@/i18n/server/get-locale";
+import authLib from "@/lib/auth";
+import { AppError } from "@/lib/errors/app-error";
+import { isFeatureEnabled } from "@/lib/feature-flags/server";
+import { track } from "@/lib/posthog";
+import {
+ authActionClient,
+ createRateLimitMiddleware,
+} from "@/lib/safe-action/server";
+
+// Extracted from the action so it can be unit tested without going through
+// authActionClient: the rate-limit middleware it wraps with transitively
+// imports @/env (via the KV client), which isn't configured for unit tests.
+export async function setPasswordForUser({
+ user,
+ password,
+}: {
+ user: { id: string; email: string; locale?: string };
+ password: string;
+}) {
+ // Checked against the database, not the session: session snapshots are
+ // frozen in secondary storage. Better-Auth's setPassword already refuses
+ // to overwrite an existing credential (PASSWORD_ALREADY_SET); this guard is
+ // defense in depth and returns a clean FORBIDDEN for the expected case.
+ if (await getUserHasPassword(user.id)) {
+ throw new AppError({
+ code: "FORBIDDEN",
+ message: "This account already has a password",
+ });
+ }
+
+ await authLib.api.setPassword({
+ body: { newPassword: password },
+ headers: await headers(),
+ });
+
+ track({ id: user.id, isGuest: false }, { event: "password_set" });
+
+ const locale = user.locale ?? (await getLocale());
+ const branding = await getInstanceBranding();
+
+ after(() =>
+ sendPasswordAddedEmail({
+ to: user.email,
+ locale,
+ branding,
+ props: {},
+ }),
+ );
+}
+
+// The target user comes from the session, so this calls the Better-Auth
+// endpoint directly rather than going through a mutation.
+export const setPasswordAction = authActionClient
+ .metadata({ actionName: "set_password" })
+ .use(createRateLimitMiddleware(5, "1 h"))
+ .inputSchema(z.object({ password: passwordSchema }))
+ .action(async ({ ctx, parsedInput }) => {
+ // The UI hides this behind the emailLogin flag; gate the action too so a
+ // direct request can't set a password on an instance where password login
+ // is disabled.
+ if (!isFeatureEnabled("emailLogin")) {
+ throw new AppError({
+ code: "FORBIDDEN",
+ message: "Password login is not enabled",
+ });
+ }
+
+ await setPasswordForUser({
+ user: ctx.user,
+ password: parsedInput.password,
+ });
+ });
+
+// Other sessions are deliberately NOT revoked: adding a first credential is
+// additive, and revoking would log out the legitimate user without helping
+// them.
diff --git a/apps/web/src/features/auth/schema.ts b/apps/web/src/features/auth/schema.ts
index 5d9844e86..c9fe1ef9f 100644
--- a/apps/web/src/features/auth/schema.ts
+++ b/apps/web/src/features/auth/schema.ts
@@ -1,4 +1,3 @@
-"use client";
import * as z from "zod";
import {
calculatePasswordStrength,
@@ -6,13 +5,23 @@ import {
} from "@/features/auth/utils";
import { useTranslation } from "@/i18n/client";
+const isStrongEnough = (password: string) =>
+ calculatePasswordStrength(password) >= passwordQualityThresholds.good;
+
+export const passwordSchema = z
+ .string()
+ .max(128)
+ .refine(isStrongEnough, "Password is too weak");
+
export function usePasswordValidationSchema() {
const { t } = useTranslation();
- return z.string().refine(
- (password) =>
- calculatePasswordStrength(password) >= passwordQualityThresholds.good,
- t("passwordTooWeak", {
- defaultValue: "Password is too weak. Please use a stronger password.",
- }),
- );
+ return z
+ .string()
+ .max(128)
+ .refine(
+ isStrongEnough,
+ t("passwordTooWeak", {
+ defaultValue: "Password is too weak. Please use a stronger password.",
+ }),
+ );
}
diff --git a/packages/emails/locales/en/emails.json b/packages/emails/locales/en/emails.json
index 467694872..7a8c3bc5c 100644
--- a/packages/emails/locales/en/emails.json
+++ b/packages/emails/locales/en/emails.json
@@ -75,6 +75,11 @@
"newPoll_heading": "New Poll Created",
"newPoll_preview": "Share your participant link to start collecting responses.",
"newPoll_subject": "Let's find a date for {title}!",
+ "passwordAdded_content2": "You're receiving this email because a password was added to your account on <domain />. If this wasn't you, reset your password immediately and contact <a>{supportEmail}</a>.",
+ "passwordAdded_heading": "A password was added to your account",
+ "passwordAdded_preview": "A password was added to your account",
+ "passwordAdded_subject": "A password was added to your account",
+ "passwordAdded_text": "You can now sign in with your email address and password.",
"register_codeValid": "This code is valid for 15 minutes",
"register_heading": "Verify your email address",
"register_preview": "Your 6-digit code is: {code}",
diff --git a/packages/emails/src/templates/password-added.tsx b/packages/emails/src/templates/password-added.tsx
new file mode 100644
index 000000000..eca5d6971
--- /dev/null
+++ b/packages/emails/src/templates/password-added.tsx
@@ -0,0 +1,111 @@
+import { Head, Hr, Html, Img, Preview } from "@react-email/components";
+import { Trans } from "react-i18next/TransWithoutContext";
+
+import { resolveChrome } from "../chrome";
+import { PoweredBy } from "../components/powered-by";
+import { previewChrome } from "../components/preview-chrome";
+import {
+ Body,
+ Container,
+ Heading,
+ Link,
+ Text,
+} from "../components/styled-components";
+import { createEmailI18n } from "../i18n";
+import type { SendArgs } from "../send";
+import { sendRenderedEmail } from "../send";
+import type { EmailChrome } from "../types";
+
+type PasswordAddedEmailProps = {
+ locale?: string;
+ chrome: EmailChrome;
+};
+
+async function PasswordAddedEmail({
+ locale = "en",
+ chrome,
+}: PasswordAddedEmailProps) {
+ const { t, i18n } = await createEmailI18n(locale);
+ return (
+ <Html>
+ <Head />
+ <Preview>
+ {t("passwordAdded_preview", {
+ defaultValue: "A password was added to your account",
+ })}
+ </Preview>
+ <Body>
+ <Container>
+ <Img
+ src={chrome.logoUrl}
+ height="42"
+ style={{ marginBottom: 32, borderRadius: 6 }}
+ alt={chrome.appName}
+ />
+ <Heading>
+ {t("passwordAdded_heading", {
+ defaultValue: "A password was added to your account",
+ })}
+ </Heading>
+ <Text>
+ {t("passwordAdded_text", {
+ defaultValue:
+ "You can now sign in with your email address and password.",
+ })}
+ </Text>
+ <Hr />
+ <Text small light={true}>
+ <Trans
+ t={t}
+ i18n={i18n}
+ ns="emails"
+ i18nKey="passwordAdded_content2"
+ defaults="You're receiving this email because a password was added to your account on <domain />. If this wasn't you, reset your password immediately and contact <a>{supportEmail}</a>."
+ values={{ supportEmail: chrome.supportEmail }}
+ components={{
+ domain: (
+ <Link color={chrome.primaryColor} href={chrome.baseUrl}>
+ {chrome.domain}
+ </Link>
+ ),
+ a: (
+ <Link
+ color={chrome.primaryColor}
+ href={`mailto:${chrome.supportEmail}`}
+ />
+ ),
+ }}
+ />
+ </Text>
+ <PoweredBy chrome={chrome} locale={locale} />
+ </Container>
+ </Body>
+ </Html>
+ );
+}
+
+PasswordAddedEmail.PreviewProps = {
+ locale: "en",
+ chrome: previewChrome,
+} as PasswordAddedEmailProps;
+
+export default PasswordAddedEmail;
+
+export async function sendPasswordAddedEmail({
+ to,
+ locale = "en",
+ branding,
+ ...rest
+}: SendArgs<PasswordAddedEmailProps>) {
+ const { t } = await createEmailI18n(locale);
+ await sendRenderedEmail({
+ to,
+ subject: t("passwordAdded_subject", {
+ defaultValue: "A password was added to your account",
+ }),
+ element: (
+ <PasswordAddedEmail locale={locale} chrome={resolveChrome(branding)} />
+ ),
+ ...rest,
+ });
+}