Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Passwordless registration folded into a single login/sign up flow (#2689)
Luke Vellae8888703f6e9
diff --git a/apps/landing/src/app/[locale]/(main)/layout.tsx b/apps/landing/src/app/[locale]/(main)/layout.tsxindex 248baeb83..64a7d9f83 100644--- a/apps/landing/src/app/[locale]/(main)/layout.tsx+++ b/apps/landing/src/app/[locale]/(main)/layout.tsx@@ -119,7 +119,7 @@ export default async function Root(props: {<Trans t={t} i18nKey="login" defaults="Login" /></LinkBase><LinkBase- href={linkToApp("/register")}+ href={linkToApp("/login")}className={buttonVariants({variant: "primary",className: "w-full",diff --git a/apps/landing/src/components/sign-up-button.tsx b/apps/landing/src/components/sign-up-button.tsxindex 96fa92d53..9247e6d74 100644--- a/apps/landing/src/components/sign-up-button.tsx+++ b/apps/landing/src/components/sign-up-button.tsx@@ -9,7 +9,7 @@ import { linkToApp } from "@/lib/linkToApp";export function SignUpButton() {return (<Link- href={linkToApp("/register")}+ href={linkToApp("/login")}className={buttonVariants({ variant: "primary" })}onClick={() => {posthog.capture("landing:sign_up_button_click");diff --git a/apps/web/next.config.ts b/apps/web/next.config.tsindex e02962dfa..38b8a2854 100644--- a/apps/web/next.config.ts+++ b/apps/web/next.config.ts@@ -73,6 +73,14 @@ const nextConfig: NextConfig = {destination: "/settings/profile",permanent: true,},+ // Login and registration are a single flow on /login: entering an+ // unknown email creates an account on OTP verification. redirectTo+ // and other query params are passed through automatically.+ {+ source: "/register",+ destination: "/login",+ permanent: false,+ },// Old email unsubscribe links pointed to these routes — redirect to the new settings page{source: "/auth/disable-notifications",diff --git a/apps/web/package.json b/apps/web/package.jsonindex 4bfcf8b90..cc1658fb2 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -28,7 +28,7 @@"@hono/zod-openapi": "^1.2.0","@hono/zod-validator": "^0.7.2","@hookform/resolvers": "^5.2.2",- "@marsidev/react-turnstile": "^1.4.2",+ "@marsidev/react-turnstile": "^1.5.3","@next/env": "16.2.6","@prisma/adapter-pg": "^7.8.0","@prisma/client": "^7.8.0",diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.jsonindex c7666615d..a607ef023 100644--- a/apps/web/public/locales/en/app.json+++ b/apps/web/public/locales/en/app.json@@ -40,7 +40,6 @@"allDay": "All day","allMembers": "All","allParticipants": "All Participants",- "alreadyHaveAccount": "Already have an account? <a>Log in</a>","alreadyLoggedInContinue": "Continue","alreadyLoggedInDescription": "Continue to your dashboard or sign out to use a different account.","alreadyLoggedInTitle": "You're already signed in",@@ -110,6 +109,7 @@"cancelingInvite": "Canceling invite...","cancelInvite": "Cancel invite","cancelInviteConfirmation": "Are you sure you want to cancel the invite for {email}?",+ "captchaFailed": "Verification failed. Please try again.","changeName": "Change name","changeNameDescription": "Enter a new name for this participant.","changeNameInfo": "This will not affect any votes you have already made.",@@ -247,7 +247,6 @@"emailChangeVerifyError": "Verification failed. Please try again.","emailDoesNotMatch": "The email address does not match.","emailMismatch": "Email does not match the account email",- "emailNotAllowed": "This email is not allowed.","emailPlaceholder": "[email protected]","enabled": "Enabled","endOfList": "You've reached the end of the list",@@ -330,11 +329,9 @@"inappropriateContent": "Inappropriate content","increaseSeats": "Increase seats","instanceSettingsDescription": "Configure your instance settings",- "invalidEmail": "Please enter a valid email address","invalidEmailAddress": "Please enter a valid email address","invalidFileType": "Invalid file type","invalidFileTypeDescription": "Please upload a JPG or PNG file.",- "invalidName": "Please enter a valid name, not a URL, email, or phone number","invalidSessionDescription": "Sign out and log in again to continue.","invalidSessionLabel": "Session","invalidSessionTitle": "Your session is no longer valid",@@ -381,8 +378,8 @@"locationPlaceholder": "Joe's Coffee Shop","login": "Login","loginDescription": "Login to your account to continue",- "loginFooter": "Don't have an account? <a>Sign up</a>","loginNotConfigured": "Login is currently not configured.",+ "loginOrSignUpDescription": "Log in to your account or create a new one","loginTitle": "Welcome","loginVerifyCheckEmail": "If an account exists with this email, you will receive a verification code at <b>{email}</b>","loginVerifyTitle": "Finish Logging In",@@ -470,6 +467,9 @@"optionalLabel": "(Optional)","optionCount": "{count, plural, one {# option} other {# options}}","or": "Or",+ "organizationName": "Organization Name",+ "organizationNamePlaceholder": "e.g. Acme Corp",+ "organizationNameRequired": "Organization name is required","outlook": "Outlook","owner": "Owner","ownerPermissionsRequired": "Only space owners can access billing settings.",@@ -502,7 +502,6 @@"pendingInvitesDescription": "Invite other users to share your space.","pendingInvitesUpgradeDescription": "Upgrade to Pro to invite members to your space.","perSeatMonth": "/seat/mo",- "personal": "Personal","planFree": "Free","planHobbyDescription": "For casual users","planProDescription": "For professionals and power users",@@ -543,8 +542,6 @@"quickCreateWhyCreateAnAccount": "Why create an account?","refreshLicense": "Refresh License","register": "Register",- "registerDescription": "Streamline your scheduling process and save time",- "registerTitle": "Create Your Account","remove": "Remove","removeImage": "Remove","removeLicense": "Remove License",@@ -598,6 +595,7 @@"rsvpVerifyDialogDescription": "Enter the 6-digit code we sent to {email}.","rsvpVerifyError": "We couldn't verify your email. Please try again.","rsvpVerifyPrompt": "Verify your email to manage your registration from any device.",+ "rsvpVerifySendError": "We couldn't send a code. Please try again.","rsvpVerifyTitle": "Verify your email","save": "Save","saved": "Saved",@@ -627,6 +625,10 @@"settingCalendarSelection": "Setting calendar selection...","settingDefaultCalendar": "Setting default calendar...","settings": "Settings",+ "setupAccountDescription": "Tell us a bit about yourself.",+ "setupAccountTitle": "Set Up Your Account",+ "setupFooterLoggedInAs": "Logged in as <email>{email}</email>",+ "setupFooterSignOut": "Sign out?","setupPasswordAlertDesc": "Set up a password to make logging in faster and more convenient.","setupPasswordAlertTitle": "Login quicker with a password","setupPasswordButton": "Set up password",@@ -641,12 +643,14 @@"skipToContent": "Skip to main content","space": "Space","spaceInviteMember": "Invite Member",- "spaceName": "Space Name","spaceNameMismatch": "Space name does not match","spaceNamePlaceholder": "My Team","spaces": "Spaces","spacesDescription": "Manage the spaces you belong to","spaceSettings": "Space Settings",+ "spaceTypeLabel": "What will you be using it for?",+ "spaceTypePersonal": "Personal",+ "spaceTypeWork": "Work","spaceUpdatedSuccess": "Space updated successfully","ssoAuthenticationOnly": "Authentication is managed through Single Sign-On (SSO). Password management is not available.","startOfWeek": "Start of week",@@ -709,7 +713,6 @@"urlInvalid": "Must be a valid URL","useCustomBranding": "Enable Custom Branding","user": "User",- "userAlreadyExists": "A user with that email already exists","userCount": "{count, number, ::compact-short}","userRegistration": "User Registration","userRegistrationDescription": "Allow new users to register an account.",@@ -723,6 +726,8 @@"verificationCodePlaceholder": "Enter your 6-digit code","verify": "Verify","verifyEmail": "Verify your email",+ "verifyEmailDescription": "Enter the 6-digit code we sent to <b>{email}</b>",+ "verifyEmailTitle": "Verify Your Email","viewPoll": "View poll","viewResults": "View results","weekView": "Week view",diff --git a/apps/web/src/app/[locale]/(auth)/login/components/login-email-form.tsx b/apps/web/src/app/[locale]/(auth)/login/components/login-email-form.tsxindex 4cf263fbb..5540f9d0e 100644--- a/apps/web/src/app/[locale]/(auth)/login/components/login-email-form.tsx+++ b/apps/web/src/app/[locale]/(auth)/login/components/login-email-form.tsx@@ -1,5 +1,7 @@"use client";import { zodResolver } from "@hookform/resolvers/zod";+import type { TurnstileInstance } from "@marsidev/react-turnstile";+import { Turnstile } from "@marsidev/react-turnstile";import { Button } from "@rallly/ui/button";import {Form,@@ -22,6 +24,9 @@ import { authClient } from "@/lib/auth-client";import { validateRedirectUrl } from "@/lib/utils/redirect";import { trpc } from "@/trpc/client";+const turnstileSiteKey = process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY;+const isTurnstileEnabled = !!turnstileSiteKey;+function useLoginWithEmailSchema() {const { t } = useTranslation();return React.useMemo(() => {@@ -32,11 +37,20 @@ function useLoginWithEmailSchema() {}, [t]);}-export function LoginWithEmailForm() {+export function LoginWithEmailForm({+ isRegistrationEnabled,+}: {+ isRegistrationEnabled: boolean;+}) {const router = useRouter();const loginWithEmailSchema = useLoginWithEmailSchema();const searchParams = useSearchParams();const [showPasswordField, setShowPasswordField] = React.useState(false);+ const [showCaptcha, setShowCaptcha] = React.useState(false);+ const turnstileRef = React.useRef<TurnstileInstance>(null);+ const [turnstileToken, setTurnstileToken] = React.useState<string | null>(+ null,+ );const form = useForm({defaultValues: {identifier: "",@@ -45,7 +59,7 @@ export function LoginWithEmailForm() {resolver: zodResolver(loginWithEmailSchema),});const { handleSubmit, formState } = form;- const { t } = useTranslation();+ const { t, i18n } = useTranslation();const getLoginMethod = trpc.auth.getLoginMethod.useMutation();const isPasswordLogin = showPasswordField && !!form.watch("password");@@ -94,31 +108,64 @@ export function LoginWithEmailForm() {window.location.href = validatedRedirectTo ?? "/";return;- } else {- if (!showPasswordField) {- const res = await getLoginMethod.mutateAsync({- email: identifier,- });-- if (res.method === "credential") {- // show password field- setShowPasswordField(true);- return;- }+ }++ if (!showPasswordField) {+ const res = await getLoginMethod.mutateAsync({+ email: identifier,+ });++ if (res.method === "credential") {+ // show password field+ setShowPasswordField(true);+ return;}+ }+ // The OTP send is captcha-gated. Reveal the widget on the first+ // attempt and wait for a token before sending.+ if (isTurnstileEnabled && !turnstileToken) {+ setShowCaptcha(true);+ return;+ }++ try {+ // When registration is enabled a "sign-in" OTP either signs+ // into an existing account or creates one on verification, so+ // known and unknown emails behave identically. When it's+ // disabled, "email-verification" only reaches existing users.const res = await authClient.emailOtp.sendVerificationOtp({email: identifier,- type: "email-verification",+ type: isRegistrationEnabled ? "sign-in" : "email-verification",+ fetchOptions: turnstileToken+ ? {+ headers: {+ "x-captcha-response": turnstileToken,+ },+ }+ : undefined,});if (res.error) {switch (res.error.code) {+ case "MISSING_RESPONSE":+ case "VERIFICATION_FAILED":+ form.setError("root", {+ message: t("captchaFailed", {+ defaultValue: "Verification failed. Please try again.",+ }),+ });+ break;case "EMAIL_BLOCKED":form.setError("identifier", {message: t("authErrorsEmailBlocked"),});break;+ case "TEMPORARY_EMAIL_NOT_ALLOWED":+ form.setError("identifier", {+ message: t("temporaryEmailNotAllowed"),+ });+ break;case "BANNED_USER":form.setError("identifier", {message: t("authErrorsUserBanned", {@@ -137,7 +184,6 @@ export function LoginWithEmailForm() {}await setVerificationEmail(identifier);- // redirect to verify page with redirectTorouter.push(`/login/verify${@@ -146,6 +192,11 @@ export function LoginWithEmailForm() {: ""}`,);+ } finally {+ if (isTurnstileEnabled) {+ setTurnstileToken(null);+ turnstileRef.current?.reset();+ }}})}>@@ -215,10 +266,31 @@ export function LoginWithEmailForm() {{form.formState.errors.root?.message ? (<FormMessage>{form.formState.errors.root.message}</FormMessage>) : null}+ {showCaptcha && turnstileSiteKey ? (+ <Turnstile+ ref={turnstileRef}+ siteKey={turnstileSiteKey}+ options={{+ language: i18n.language,+ size: "flexible",+ }}+ onSuccess={(token) => {+ setTurnstileToken(token);+ }}+ onError={() => {+ setTurnstileToken(null);+ }}+ onExpire={() => {+ setTurnstileToken(null);+ turnstileRef.current?.reset();+ }}+ />+ ) : null}<div><Buttonsize="xl"loading={form.formState.isSubmitting}+ disabled={showCaptcha && !isPasswordLogin && !turnstileToken}type="submit"className="w-full"variant="primary"diff --git a/apps/web/src/app/[locale]/(auth)/login/page.tsx b/apps/web/src/app/[locale]/(auth)/login/page.tsxindex 0b68173a1..6516f6a17 100644--- a/apps/web/src/app/[locale]/(auth)/login/page.tsx+++ b/apps/web/src/app/[locale]/(auth)/login/page.tsx@@ -14,11 +14,9 @@ import {AuthPageContainer,AuthPageContent,AuthPageDescription,- AuthPageExternal,AuthPageHeader,AuthPageTitle,} from "../components/auth-page";-import { LinkWithRedirectTo } from "../components/link-with-redirect-to";import { AuthErrors } from "./components/auth-errors";import { LoginWithEmailForm } from "./components/login-email-form";@@ -92,6 +90,13 @@ export default async function LoginPage(props: {i18nKey="loginNotConfigured"defaults="Login is currently not configured."/>+ ) : isRegistrationEnabled ? (+ <Trans+ t={t}+ ns="app"+ i18nKey="loginOrSignUpDescription"+ defaults="Log in to your account or create a new one"+ />) : (<Transt={t}@@ -103,7 +108,9 @@ export default async function LoginPage(props: {</AuthPageDescription></AuthPageHeader><AuthPageContent>- {isEmailLoginEnabled && <LoginWithEmailForm />}+ {isEmailLoginEnabled && (+ <LoginWithEmailForm isRegistrationEnabled={isRegistrationEnabled} />+ )}{isEmailLoginEnabled && hasAlternateLoginMethods ? <OrDivider /> : null}<div className="grid gap-3">{hasOidc ? (@@ -129,18 +136,6 @@ export default async function LoginPage(props: {</div></AuthPageContent><AuthErrors />- {isRegistrationEnabled ? (- <AuthPageExternal>- <Trans- t={t}- i18nKey="loginFooter"- defaults="Don't have an account? <a>Sign up</a>"- components={{- a: <LinkWithRedirectTo className="text-link" href="/register" />,- }}- />- </AuthPageExternal>- ) : null}</AuthPageContainer>);}diff --git a/apps/web/src/app/[locale]/(auth)/login/verify/components/otp-form.tsx b/apps/web/src/app/[locale]/(auth)/login/verify/components/otp-form.tsxindex 479242a73..52d0b538f 100644--- a/apps/web/src/app/[locale]/(auth)/login/verify/components/otp-form.tsx+++ b/apps/web/src/app/[locale]/(auth)/login/verify/components/otp-form.tsx@@ -24,7 +24,18 @@ const otpFormSchema = z.object({otp: z.string().length(6),});-export function OTPForm({ email }: { email: string }) {+export function OTPForm({+ email,+ mode,+}: {+ email: string;+ /**+ * "sign-in" verifies with signIn.emailOtp, which creates an account when+ * the email is new. "email-verification" only signs into existing+ * accounts — used when registration is disabled.+ */+ mode: "sign-in" | "email-verification";+}) {const { t } = useTranslation();const form = useForm({defaultValues: {@@ -35,10 +46,16 @@ export function OTPForm({ email }: { email: string }) {const searchParams = useSearchParams();const handleSubmit = form.handleSubmit(async (data) => {- const res = await authClient.emailOtp.verifyEmail({- email,- otp: data.otp,- });+ const res =+ mode === "sign-in"+ ? await authClient.signIn.emailOtp({+ email,+ otp: data.otp,+ })+ : await authClient.emailOtp.verifyEmail({+ email,+ otp: data.otp,+ });if (res.error) {posthog?.capture("login:otp_verify_error", {@@ -74,11 +91,22 @@ export function OTPForm({ email }: { email: string }) {form.setError("otp", {message: res.error.message,});+ return;}- } else {- window.location.href =- validateRedirectUrl(searchParams?.get("redirectTo")) ?? "/";}++ const redirectTo = validateRedirectUrl(searchParams?.get("redirectTo"));++ // A freshly created account has no name yet; send it through onboarding+ // to pick one up before continuing to its destination.+ if (mode === "sign-in" && !res.data?.user?.name) {+ window.location.href = redirectTo+ ? `/setup?redirectTo=${encodeURIComponent(redirectTo)}`+ : "/setup";+ return;+ }++ window.location.href = redirectTo ?? "/";});return (@@ -123,7 +151,7 @@ export function OTPForm({ email }: { email: string }) {form.formState.isSubmitting || form.formState.isSubmitSuccessful}>- <Trans i18nKey="login" defaults="Login" />+ <Trans i18nKey="continue" defaults="Continue" /></Button></form></Form>diff --git a/apps/web/src/app/[locale]/(auth)/login/verify/page.tsx b/apps/web/src/app/[locale]/(auth)/login/verify/page.tsxindex 4f02bc8ac..c25c9442e 100644--- a/apps/web/src/app/[locale]/(auth)/login/verify/page.tsx+++ b/apps/web/src/app/[locale]/(auth)/login/verify/page.tsx@@ -1,10 +1,10 @@import { buttonVariants } from "@rallly/ui";import type { Metadata } from "next";import { cookies } from "next/headers";-import Link from "next/link";import { redirect } from "next/navigation";import { Trans } from "react-i18next/TransWithoutContext";+import { getRegistrationEnabled } from "@/features/instance-settings/data";import { getTranslation } from "@/i18n/server";import { redirectIfLoggedIn } from "@/lib/auth";import {@@ -14,6 +14,7 @@ import {AuthPageHeader,AuthPageTitle,} from "../../components/auth-page";+import { LinkWithRedirectTo } from "../../components/link-with-redirect-to";import { OTPForm } from "./components/otp-form";export default async function VerifyPage() {@@ -23,33 +24,61 @@ export default async function VerifyPage() {if (!email) {redirect("/login");}++ const isRegistrationEnabled = await getRegistrationEnabled();+return (<AuthPageContainer><AuthPageHeader><AuthPageTitle>- <Trans- t={t}- ns="app"- i18nKey="loginVerifyTitle"- defaults="Finish Logging In"- />+ {isRegistrationEnabled ? (+ <Trans+ t={t}+ ns="app"+ i18nKey="verifyEmailTitle"+ defaults="Verify Your Email"+ />+ ) : (+ <Trans+ t={t}+ ns="app"+ i18nKey="loginVerifyTitle"+ defaults="Finish Logging In"+ />+ )}</AuthPageTitle><AuthPageDescription>- <Trans- t={t}- ns="app"- i18nKey="loginVerifyCheckEmail"- defaults="If an account exists with this email, you will receive a verification code at <b>{email}</b>"- values={{ email }}- components={{- b: <strong className="font-medium text-foreground" />,- }}- />+ {isRegistrationEnabled ? (+ <Trans+ t={t}+ ns="app"+ i18nKey="verifyEmailDescription"+ defaults="Enter the 6-digit code we sent to <b>{email}</b>"+ values={{ email }}+ components={{+ b: <strong className="font-medium text-foreground" />,+ }}+ />+ ) : (+ <Trans+ t={t}+ ns="app"+ i18nKey="loginVerifyCheckEmail"+ defaults="If an account exists with this email, you will receive a verification code at <b>{email}</b>"+ values={{ email }}+ components={{+ b: <strong className="font-medium text-foreground" />,+ }}+ />+ )}</AuthPageDescription></AuthPageHeader><AuthPageContent>- <OTPForm email={email} />- <Link+ <OTPForm+ email={email}+ mode={isRegistrationEnabled ? "sign-in" : "email-verification"}+ />+ <LinkWithRedirectTohref="/login"className={buttonVariants({size: "xl",@@ -58,7 +87,7 @@ export default async function VerifyPage() {})}><Trans t={t} ns="app" i18nKey="back" defaults="Back" />- </Link>+ </LinkWithRedirectTo></AuthPageContent></AuthPageContainer>);diff --git a/apps/web/src/app/[locale]/(auth)/register/components/register-name-form.tsx b/apps/web/src/app/[locale]/(auth)/register/components/register-name-form.tsxdeleted file mode 100644index dd918d4a3..000000000--- a/apps/web/src/app/[locale]/(auth)/register/components/register-name-form.tsx+++ /dev/null@@ -1,241 +0,0 @@-"use client";-import { zodResolver } from "@hookform/resolvers/zod";-import type { TurnstileInstance } from "@marsidev/react-turnstile";-import { Turnstile } from "@marsidev/react-turnstile";-import { Button } from "@rallly/ui/button";-import {- Form,- FormControl,- FormField,- FormItem,- FormLabel,- FormMessage,-} from "@rallly/ui/form";-import { Input } from "@rallly/ui/input";-import { absoluteUrl } from "@rallly/utils/absolute-url";-import { useRouter, useSearchParams } from "next/navigation";-import React from "react";-import { useForm } from "react-hook-form";-import { setVerificationEmail } from "@/app/[locale]/(auth)/login/actions";-import { PasswordInput } from "@/components/password-input";-import { PasswordStrengthMeter } from "@/features/auth/components/password-strength-meter";-import { Trans, useTranslation } from "@/i18n/client";-import { authClient } from "@/lib/auth-client";-import { getBrowserTimeZone } from "@/lib/utils/date-time-utils";-import { validateRedirectUrl } from "@/lib/utils/redirect";-import { useRegisterNameFormSchema } from "./schema";--const turnstileSiteKey = process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY;-const isTurnstileEnabled = !!turnstileSiteKey;--export function RegisterNameForm() {- const schema = useRegisterNameFormSchema();- const { t, i18n } = useTranslation();- const searchParams = useSearchParams();- const router = useRouter();- const turnstileRef = React.useRef<TurnstileInstance>(null);- const [turnstileToken, setTurnstileToken] = React.useState<string | null>(- null,- );- const form = useForm({- defaultValues: {- name: "",- email: "",- password: "",- },- resolver: zodResolver(schema),- });-- return (- <Form {...form}>- <form- onSubmit={form.handleSubmit(async (data) => {- const validatedRedirectTo = validateRedirectUrl(- searchParams.get("redirectTo"),- );-- const verifyURL = absoluteUrl(- `/login/verify${- validatedRedirectTo- ? `?redirectTo=${encodeURIComponent(validatedRedirectTo)}`- : ""- }`,- );-- try {- const res = await authClient.signUp.email({- email: data.email,- password: data.password,- name: data.name,- timeZone: getBrowserTimeZone(),- locale: i18n.language,- callbackURL: verifyURL,- fetchOptions: turnstileToken- ? {- headers: {- "x-captcha-response": turnstileToken,- },- }- : undefined,- });-- if (res.error) {- switch (res.error.code) {- case "USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL":- form.setError("email", {- message: t("userAlreadyExists"),- });- break;- case "EMAIL_BLOCKED":- form.setError("email", {- message: t("emailNotAllowed"),- });- break;- case "TEMPORARY_EMAIL_NOT_ALLOWED":- form.setError("email", {- message: t("temporaryEmailNotAllowed"),- });- break;- default:- form.setError("email", {- message: res.error.message,- });- break;- }- }-- if (res.data?.user?.email) {- await setVerificationEmail(res.data.user.email);- router.push(verifyURL);- }- } catch (error) {- if (error instanceof Error) {- form.setError("root", {- message: error.message,- });- }- console.error(error);- } finally {- if (isTurnstileEnabled) {- setTurnstileToken(null);- turnstileRef.current?.reset();- }- }- })}- >- <div className="space-y-4">- <FormField- control={form.control}- name="name"- render={({ field }) => {- return (- <FormItem>- <FormLabel>- <Trans i18nKey="name" defaults="Name" />- </FormLabel>- <FormControl>- <Input- {...field}- large- autoComplete="name"- data-1p-ignore- placeholder={t("namePlaceholder")}- disabled={form.formState.isSubmitting}- autoFocus={true}- />- </FormControl>- <FormMessage />- </FormItem>- );- }}- />- <FormField- control={form.control}- name="email"- render={({ field }) => (- <FormItem>- <FormLabel>- <Trans i18nKey="email" defaults="Email" />- </FormLabel>- <FormControl>- <Input- large- type="email"- autoComplete="email"- placeholder={t("emailPlaceholder")}- disabled={form.formState.isSubmitting}- {...field}- />- </FormControl>- <FormMessage />- </FormItem>- )}- />- <FormField- control={form.control}- name="password"- render={({ field }) => (- <FormItem>- <FormLabel>- <Trans i18nKey="password" defaults="Password" />- </FormLabel>- <FormControl>- <PasswordInput- large- autoComplete="new-password"- placeholder="••••••••"- disabled={form.formState.isSubmitting}- {...field}- type="password"- />- </FormControl>- <PasswordStrengthMeter- password={field.value}- className="mt-2"- />- <FormMessage />- </FormItem>- )}- />- </div>- {form.formState.errors.root?.message ? (- <FormMessage>{form.formState.errors.root.message}</FormMessage>- ) : null}- {turnstileSiteKey ? (- <div className="mt-6">- <Turnstile- ref={turnstileRef}- siteKey={turnstileSiteKey}- options={{- language: i18n.language,- size: "flexible",- }}- onSuccess={(token) => {- setTurnstileToken(token);- }}- onError={() => {- setTurnstileToken(null);- }}- onExpire={() => {- setTurnstileToken(null);- turnstileRef.current?.reset();- }}- />- </div>- ) : null}- <div className="mt-6">- <Button- loading={form.formState.isSubmitting}- disabled={isTurnstileEnabled && !turnstileToken}- className="w-full"- variant="primary"- type="submit"- size="xl"- >- <Trans i18nKey="continue" />- </Button>- </div>- </form>- </Form>- );-}diff --git a/apps/web/src/app/[locale]/(auth)/register/components/schema.ts b/apps/web/src/app/[locale]/(auth)/register/components/schema.tsdeleted file mode 100644index a85847949..000000000--- a/apps/web/src/app/[locale]/(auth)/register/components/schema.ts+++ /dev/null@@ -1,29 +0,0 @@-import * as z from "zod";-import { usePasswordValidationSchema } from "@/features/auth/schema";-import { useTranslation } from "@/i18n/client";-import { isValidName } from "@/lib/utils/is-valid-name";--export const useRegisterNameFormSchema = () => {- const { t } = useTranslation();- const passwordValidation = usePasswordValidationSchema();- return z.object({- name: z- .string()- .trim()- .min(1)- .max(100)- .refine(- isValidName,- t("invalidName", {- defaultValue:- "Please enter a valid name, not a URL, email, or phone number",- }),- ),- email: z.email(- t("invalidEmail", {- defaultValue: "Please enter a valid email address",- }),- ),- password: passwordValidation,- });-};diff --git a/apps/web/src/app/[locale]/(auth)/register/page.tsx b/apps/web/src/app/[locale]/(auth)/register/page.tsxdeleted file mode 100644index 334dc9880..000000000--- a/apps/web/src/app/[locale]/(auth)/register/page.tsx+++ /dev/null@@ -1,116 +0,0 @@-import type { Metadata } from "next";-import { notFound } from "next/navigation";-import { Trans } from "react-i18next/TransWithoutContext";-import { env } from "@/env";-import { LoginWithOIDC } from "@/features/auth/components/login-with-oidc";-import { OrDivider } from "@/features/auth/components/or-divider";-import { SSOProvider } from "@/features/auth/components/sso-provider";-import { getRegistrationEnabled } from "@/features/instance-settings/data";-import { getTranslation } from "@/i18n/server";-import { authLib, redirectIfLoggedIn } from "@/lib/auth";-import {- AuthPageContainer,- AuthPageContent,- AuthPageDescription,- AuthPageExternal,- AuthPageHeader,- AuthPageTitle,-} from "../components/auth-page";-import { LinkWithRedirectTo } from "../components/link-with-redirect-to";-import { RegisterNameForm } from "./components/register-name-form";--export default async function Register(props: {- params: Promise<{ locale: string }>;- searchParams?: Promise<{ redirectTo?: string }>;-}) {- await redirectIfLoggedIn();- const params = await props.params;- const searchParams = await props.searchParams;- const { t } = await getTranslation(params.locale);- const isRegistrationEnabled = await getRegistrationEnabled();-- if (!isRegistrationEnabled) {- notFound();- }-- const hasGoogleProvider = !!authLib.options.socialProviders.google;- const hasMicrosoftProvider = !!authLib.options.socialProviders.microsoft;- const hasOidc = !!authLib.options.plugins.find(- (plugin) => plugin.id === "generic-oauth",- );-- const hasAlternateSignUpMethods =- hasGoogleProvider || hasMicrosoftProvider || hasOidc;-- return (- <AuthPageContainer>- <AuthPageHeader>- <AuthPageTitle>- <Trans- t={t}- ns="app"- i18nKey="registerTitle"- defaults="Create Your Account"- />- </AuthPageTitle>- <AuthPageDescription>- <Trans- t={t}- ns="app"- i18nKey="registerDescription"- defaults="Streamline your scheduling process and save time"- />- </AuthPageDescription>- </AuthPageHeader>- <AuthPageContent>- <RegisterNameForm />- {hasAlternateSignUpMethods ? <OrDivider /> : null}- {hasAlternateSignUpMethods ? (- <div className="grid gap-3">- {hasOidc ? (- <LoginWithOIDC- name={env.OIDC_NAME}- redirectTo={searchParams?.redirectTo}- />- ) : null}- {hasGoogleProvider ? (- <SSOProvider- providerId="google"- name="Google"- redirectTo={searchParams?.redirectTo}- />- ) : null}- {hasMicrosoftProvider ? (- <SSOProvider- providerId="microsoft"- name="Microsoft"- redirectTo={searchParams?.redirectTo}- />- ) : null}- </div>- ) : null}- </AuthPageContent>- <AuthPageExternal>- <Trans- t={t}- ns="app"- i18nKey="alreadyHaveAccount"- defaults="Already have an account? <a>Log in</a>"- components={{- a: <LinkWithRedirectTo className="text-link" href="/login" />,- }}- />- </AuthPageExternal>- </AuthPageContainer>- );-}--export async function generateMetadata(props: {- params: Promise<{ locale: string }>;-}): Promise<Metadata> {- const params = await props.params;- const { t } = await getTranslation(params.locale);- return {- title: t("register"),- };-}diff --git a/apps/web/src/app/[locale]/admin-setup/actions.ts b/apps/web/src/app/[locale]/admin-setup/actions.tsindex 7e498e500..20c5561b7 100644--- a/apps/web/src/app/[locale]/admin-setup/actions.ts+++ b/apps/web/src/app/[locale]/admin-setup/actions.ts@@ -2,7 +2,7 @@import { headers } from "next/headers";import { redirect } from "next/navigation";-import { isInitialAdmin } from "@/features/setup/utils";+import { isInitialAdmin } from "@/features/instance-settings/utils";import { updateUserRole } from "@/features/user/mutations";import { authLib } from "@/lib/auth";import { AppError } from "@/lib/errors/app-error";diff --git a/apps/web/src/app/[locale]/admin-setup/page.tsx b/apps/web/src/app/[locale]/admin-setup/page.tsxindex 14bcd2497..41dec40e7 100644--- a/apps/web/src/app/[locale]/admin-setup/page.tsx+++ b/apps/web/src/app/[locale]/admin-setup/page.tsx@@ -10,7 +10,7 @@ import {EmptyStateIcon,EmptyStateTitle,} from "@/components/empty-state";-import { isInitialAdmin } from "@/features/setup/utils";+import { isInitialAdmin } from "@/features/instance-settings/utils";import { getCurrentUser } from "@/features/user/data";import { Trans } from "@/i18n/client";import { getTranslation } from "@/i18n/server";diff --git a/apps/web/src/app/[locale]/e/[id]/components/rsvp-verify-email.tsx b/apps/web/src/app/[locale]/e/[id]/components/rsvp-verify-email.tsxindex 1c246b9bf..566d8c40a 100644--- a/apps/web/src/app/[locale]/e/[id]/components/rsvp-verify-email.tsx+++ b/apps/web/src/app/[locale]/e/[id]/components/rsvp-verify-email.tsx@@ -1,6 +1,8 @@"use client";import { zodResolver } from "@hookform/resolvers/zod";+import type { TurnstileInstance } from "@marsidev/react-turnstile";+import { Turnstile } from "@marsidev/react-turnstile";import { Button } from "@rallly/ui/button";import {Dialog,@@ -18,12 +20,16 @@ import {FormMessage,} from "@rallly/ui/form";import { useRouter } from "next/navigation";+import React from "react";import { useForm } from "react-hook-form";import * as z from "zod";import { InputOTP } from "@/components/input-otp";import { Trans, useTranslation } from "@/i18n/client";import { authClient } from "@/lib/auth-client";+const turnstileSiteKey = process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY;+const isTurnstileEnabled = !!turnstileSiteKey;+const otpSchema = z.object({ otp: z.string().regex(/^\d{6}$/) });export function RsvpVerifyEmail({@@ -33,14 +39,41 @@ export function RsvpVerifyEmail({email: string;name: string;}) {- const { t } = useTranslation();+ const { t, i18n } = useTranslation();const router = useRouter();const dialog = useDialog();+ const turnstileRef = React.useRef<TurnstileInstance>(null);+ const [otpSent, setOtpSent] = React.useState(false);const form = useForm({defaultValues: { otp: "" },resolver: zodResolver(otpSchema),});+ const sendOtp = async (captchaToken?: string) => {+ const res = await authClient.emailOtp.sendVerificationOtp({+ email,+ type: "sign-in",+ fetchOptions: captchaToken+ ? {+ headers: {+ "x-captcha-response": captchaToken,+ },+ }+ : undefined,+ });++ if (res.error) {+ form.setError("otp", {+ message: t("rsvpVerifySendError", {+ defaultValue: "We couldn't send a code. Please try again.",+ }),+ });+ return;+ }++ setOtpSent(true);+ };+const handleSubmit = form.handleSubmit(async (data) => {// Verifying signs the guest in: into their existing account if the email// is already in use, otherwise into a freshly created one. The anonymous@@ -111,11 +144,13 @@ export function RsvpVerifyEmail({className="self-start"onClick={() => {form.reset();+ setOtpSent(false);dialog.trigger();- void authClient.emailOtp.sendVerificationOtp({- email,- type: "sign-in",- });+ // With Turnstile configured, the send waits for the widget in the+ // dialog to produce a token.+ if (!isTurnstileEnabled) {+ void sendOtp();+ }}}><Trans i18nKey="rsvpVerifyCta" defaults="Verify your email" />@@ -134,6 +169,19 @@ export function RsvpVerifyEmail({/></DialogDescription></DialogHeader>+ {turnstileSiteKey && !otpSent ? (+ <Turnstile+ ref={turnstileRef}+ siteKey={turnstileSiteKey}+ options={{+ language: i18n.language,+ size: "flexible",+ }}+ onSuccess={(token) => {+ void sendOtp(token);+ }}+ />+ ) : null}<Form {...form}><form onSubmit={handleSubmit}><FormField@@ -144,7 +192,10 @@ export function RsvpVerifyEmail({<FormControl><InputOTPautoFocus- disabled={form.formState.isSubmitting}+ disabled={+ form.formState.isSubmitting ||+ (isTurnstileEnabled && !otpSent)+ }onValidCode={() => handleSubmit()}{...field}/>diff --git a/apps/web/src/app/[locale]/setup/actions.ts b/apps/web/src/app/[locale]/setup/actions.tsnew file mode 100644index 000000000..3f082011e--- /dev/null+++ b/apps/web/src/app/[locale]/setup/actions.ts@@ -0,0 +1,93 @@+"use server";++import { subject } from "@casl/ability";+import * as z from "zod";+import { adoptOrphanedPolls } from "@/features/poll/mutations";+import { getActiveSpaceForUser } from "@/features/space/data";+import { defineAbilityForMember } from "@/features/space/member/ability";+import { createSpace, updateSpace } from "@/features/space/mutations";+import { identifyGroup, track } from "@/lib/posthog";+import { authActionClient } from "@/lib/safe-action/server";++const setupSpaceSchema = z.discriminatedUnion("spaceType", [+ z.object({ spaceType: z.literal("personal") }),+ z.object({+ spaceType: z.literal("work"),+ organizationName: z.string().min(1).max(100),+ }),+]);++/**+ * Names the user's space during onboarding: renames the active space when+ * they're allowed to (every new account owns an auto-created "Personal"+ * space), or creates one when they have none. A member of someone else's+ * space who owns no space of their own gets nothing renamed or relabeled.+ */+export const setupSpaceAction = authActionClient+ .metadata({ actionName: "setup_space" })+ .inputSchema(setupSpaceSchema)+ .action(async ({ ctx, parsedInput }) => {+ const name =+ parsedInput.spaceType === "work"+ ? parsedInput.organizationName+ : "Personal";++ const existingSpace = await getActiveSpaceForUser(ctx.user.id);++ let spaceId: string | null = null;++ if (!existingSpace) {+ const space = await createSpace({+ name,+ ownerId: ctx.user.id,+ });+ // Guest linking into an account without a space migrates polls with+ // no space; pull them into the one just created.+ await adoptOrphanedPolls({+ userId: ctx.user.id,+ spaceId: space.id,+ });+ spaceId = space.id;+ } else {+ const ability = defineAbilityForMember({+ user: ctx.user,+ space: existingSpace,+ });++ if (ability.can("update", subject("Space", existingSpace))) {+ await updateSpace({+ spaceId: existingSpace.id,+ name,+ });+ spaceId = existingSpace.id;+ }+ }++ if (spaceId) {+ identifyGroup({+ groupType: "space",+ groupKey: spaceId,+ properties: {+ type: parsedInput.spaceType,+ },+ });++ track(ctx.user, {+ event: "space_setup",+ properties: {+ space_type: parsedInput.spaceType,+ // The register event $sets these from the user row at creation+ // time, which for OTP signups is an empty name and no timezone.+ // The form updates both right before this action runs, so patch+ // the person profile here.+ $set: {+ name: ctx.user.name,+ timeZone: ctx.user.timeZone ?? undefined,+ },+ },+ groups: {+ space: spaceId,+ },+ });+ }+ });diff --git a/apps/web/src/app/[locale]/setup/components/setup-footer.tsx b/apps/web/src/app/[locale]/setup/components/setup-footer.tsxnew file mode 100644index 000000000..1fe792852--- /dev/null+++ b/apps/web/src/app/[locale]/setup/components/setup-footer.tsx@@ -0,0 +1,43 @@+"use client";++import { Button } from "@rallly/ui/button";+import React from "react";+import { Trans } from "@/i18n/client";+import { signOut } from "@/lib/auth-client";++export function SetupFooter({ email }: { email: string }) {+ const [isSigningOut, setIsSigningOut] = React.useState(false);++ return (+ <p className="flex flex-col items-center gap-4 text-muted-foreground text-sm">+ <span>+ <Trans+ i18nKey="setupFooterLoggedInAs"+ defaults="Logged in as <email>{email}</email>"+ values={{ email }}+ components={{+ email: <span className="font-medium text-foreground" />,+ }}+ />+ </span>+ <Button+ variant="ghost"+ size="sm"+ loading={isSigningOut}+ onClick={() => {+ setIsSigningOut(true);+ signOut()+ .catch(() => {+ // Reload even if sign out fails: the server re-renders from+ // the real cookie state.+ })+ .finally(() => {+ window.location.reload();+ });+ }}+ >+ <Trans i18nKey="signOut" defaults="Sign out" />+ </Button>+ </p>+ );+}diff --git a/apps/web/src/app/[locale]/setup/components/setup-form.tsx b/apps/web/src/app/[locale]/setup/components/setup-form.tsxnew file mode 100644index 000000000..09de60898--- /dev/null+++ b/apps/web/src/app/[locale]/setup/components/setup-form.tsx@@ -0,0 +1,310 @@+"use client";++import { zodResolver } from "@hookform/resolvers/zod";+import { Button } from "@rallly/ui/button";+import { ButtonGroup, ButtonGroupItem } from "@rallly/ui/button-group";+import {+ Form,+ FormControl,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from "@rallly/ui/form";+import { Input } from "@rallly/ui/input";+import { RadioGroup, RadioGroupItem } from "@rallly/ui/radio-group";+import { BriefcaseIcon, UserIcon } from "lucide-react";+import { useRouter } from "next/navigation";+import React from "react";+import { useForm } from "react-hook-form";+import * as z from "zod";+import { setupSpaceAction } from "@/app/[locale]/setup/actions";+import { TimeZoneSelect } from "@/components/time-zone-picker/time-zone-select";+import { Trans, useTranslation } from "@/i18n/client";+import { authClient } from "@/lib/auth-client";+import { getLocaleDefaults } from "@/lib/datetime/locales";+import type { TimeFormat } from "@/lib/datetime/types";+import { useSafeAction } from "@/lib/safe-action/client";+import { getBrowserTimeZone } from "@/lib/utils/date-time-utils";++function useSetupFormSchema() {+ const { t } = useTranslation();+ return React.useMemo(() => {+ return z+ .object({+ name: z.string().min(1).max(100),+ timeZone: z.string().min(1),+ timeFormat: z.enum(["hours12", "hours24"]),+ spaceType: z.enum(["personal", "work"]),+ organizationName: z.string().max(100),+ })+ .refine(+ (data) =>+ data.spaceType === "personal" ||+ data.organizationName.trim().length > 0,+ {+ path: ["organizationName"],+ message: t("organizationNameRequired", {+ defaultValue: "Organization name is required",+ }),+ },+ );+ }, [t]);+}++function SpaceTypeOption({+ value,+ icon,+ label,+}: {+ value: string;+ icon: React.ReactNode;+ label: string;+}) {+ const id = React.useId();+ return (+ <label+ htmlFor={id}+ className="group flex h-9 cursor-pointer items-center gap-2 rounded-lg border border-input bg-card px-3 text-sm transition-colors hover:bg-accent has-data-checked:border-primary has-data-checked:bg-primary/5"+ >+ <span className="text-muted-foreground group-has-data-checked:text-primary">+ {icon}+ </span>+ <span className="flex-1 font-normal">{label}</span>+ <RadioGroupItem className="hidden" id={id} value={value} />+ </label>+ );+}++export function SetupForm({+ defaultName,+ defaultTimeZone,+ defaultTimeFormat,+}: {+ defaultName: string;+ defaultTimeZone?: string;+ defaultTimeFormat?: TimeFormat;+}) {+ const { t, i18n } = useTranslation();+ const router = useRouter();+ const schema = useSetupFormSchema();+ const setupSpace = useSafeAction(setupSpaceAction);++ const form = useForm({+ resolver: zodResolver(schema),+ defaultValues: {+ name: defaultName,+ timeZone: defaultTimeZone || getBrowserTimeZone(),+ timeFormat:+ defaultTimeFormat ?? getLocaleDefaults(i18n.language).timeFormat,+ spaceType: "personal" as const,+ organizationName: "",+ },+ });++ const spaceType = form.watch("spaceType");++ return (+ <Form {...form}>+ <form+ onSubmit={form.handleSubmit(+ async ({+ name,+ timeZone,+ timeFormat,+ spaceType,+ organizationName,+ }) => {+ const res = await authClient.updateUser({+ name,+ timeZone,+ timeFormat,+ locale: i18n.language,+ });++ if (res.error) {+ form.setError("root", {+ message: res.error.message,+ });+ return;+ }++ const result = await setupSpace.executeAsync(+ spaceType === "work"+ ? { spaceType, organizationName: organizationName.trim() }+ : { spaceType },+ );++ // Server errors surface through the global useSafeAction toast;+ // stay on the form so the user can retry. On success the hook+ // refreshes the router and the page redirects onward.+ if (result?.serverError || result?.validationErrors) {+ return;+ }++ router.refresh();+ },+ )}+ className="space-y-4"+ >+ <FormField+ control={form.control}+ name="name"+ render={({ field }) => (+ <FormItem>+ <FormLabel>+ <Trans i18nKey="name" defaults="Name" />+ </FormLabel>+ <FormControl>+ <Input+ {...field}+ autoComplete="name"+ data-1p-ignore+ placeholder={t("namePlaceholder", {+ defaultValue: "Jessie Smith",+ })}+ disabled={form.formState.isSubmitting}+ autoFocus={true}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ <div className="grid grid-cols-2 gap-2">+ <FormField+ control={form.control}+ name="timeZone"+ render={({ field }) => (+ <FormItem>+ <FormLabel>+ <Trans i18nKey="timeZone" defaults="Time zone" />+ </FormLabel>+ <FormControl>+ <TimeZoneSelect+ // The combobox input group is h-8 by default; match the+ // h-9 controls in the rest of the form+ className="min-w-0 [&_[data-slot=input-group]]:h-9"+ value={field.value}+ onValueChange={field.onChange}+ disabled={form.formState.isSubmitting}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="timeFormat"+ render={({ field }) => (+ <FormItem>+ <FormLabel>+ <Trans i18nKey="timeFormat" defaults="Time format" />+ </FormLabel>+ <FormControl>+ <ButtonGroup+ className="w-full"+ value={field.value}+ onValueChange={field.onChange}+ disabled={form.formState.isSubmitting}+ >+ <ButtonGroupItem value="hours12">+ <Trans i18nKey="12h" defaults="12-hour" />+ </ButtonGroupItem>+ <ButtonGroupItem value="hours24">+ <Trans i18nKey="24h" defaults="24-hour" />+ </ButtonGroupItem>+ </ButtonGroup>+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ </div>+ <FormField+ control={form.control}+ name="spaceType"+ render={({ field }) => (+ <FormItem>+ <FormLabel>+ <Trans+ i18nKey="spaceTypeLabel"+ defaults="What will you be using it for?"+ />+ </FormLabel>+ <FormControl>+ <RadioGroup+ value={field.value}+ onValueChange={(value) => {+ field.onChange(value);+ form.clearErrors("organizationName");+ }}+ className="grid grid-cols-2 gap-2"+ >+ <SpaceTypeOption+ value="personal"+ icon={<UserIcon className="size-4" />}+ label={t("spaceTypePersonal", {+ defaultValue: "Personal",+ })}+ />+ <SpaceTypeOption+ value="work"+ icon={<BriefcaseIcon className="size-4" />}+ label={t("spaceTypeWork", { defaultValue: "Work" })}+ />+ </RadioGroup>+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ {spaceType === "work" ? (+ <FormField+ control={form.control}+ name="organizationName"+ render={({ field }) => (+ <FormItem>+ <FormLabel>+ <Trans+ i18nKey="organizationName"+ defaults="Organization Name"+ />+ </FormLabel>+ <FormControl>+ <Input+ {...field}+ data-1p-ignore+ autoFocus={true}+ placeholder={t("organizationNamePlaceholder", {+ defaultValue: "e.g. Acme Corp",+ })}+ disabled={form.formState.isSubmitting}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ ) : null}+ {form.formState.errors.root?.message ? (+ <FormMessage>{form.formState.errors.root.message}</FormMessage>+ ) : null}+ <div className="mt-6">+ <Button+ type="submit"+ variant="primary"+ size="lg"+ loading={+ form.formState.isSubmitting || form.formState.isSubmitSuccessful+ }+ className="w-full"+ >+ <Trans i18nKey="continue" defaults="Continue" />+ </Button>+ </div>+ </form>+ </Form>+ );+}diff --git a/apps/web/src/app/[locale]/setup/page.tsx b/apps/web/src/app/[locale]/setup/page.tsxindex fc93f8cc5..05e6b79c8 100644--- a/apps/web/src/app/[locale]/setup/page.tsx+++ b/apps/web/src/app/[locale]/setup/page.tsx@@ -1,42 +1,70 @@import type { Metadata } from "next";import { redirect } from "next/navigation";+import { SetupFooter } from "@/app/[locale]/setup/components/setup-footer";+import { SetupForm } from "@/app/[locale]/setup/components/setup-form";+import { ThemeSwitcher } from "@/components/theme-switcher";import { Logo } from "@/features/branding/components/logo";-import { CreateSpaceForm } from "@/features/setup/components/create-space-form";-import { userHasSpaces } from "@/features/setup/utils";+import { getActiveSpaceForUser } from "@/features/space/data";import { Trans } from "@/i18n/client";import { getTranslation } from "@/i18n/server";import { requireUser } from "@/lib/auth";+import { getDeviceDateTimeConfig } from "@/lib/datetime/server";+import { validateRedirectUrl } from "@/lib/utils/redirect";-export default async function SetupPage() {+export default async function SetupPage(props: {+ searchParams?: Promise<{ redirectTo?: string }>;+}) {const user = await requireUser();+ const searchParams = await props.searchParams;- if (await userHasSpaces(user.id)) {- redirect("/");+ const space = await getActiveSpaceForUser(user.id);++ if (user.name && user.timeZone && user.timeFormat && space) {+ redirect(validateRedirectUrl(searchParams?.redirectTo) ?? "/");}+ // Prefill from the device: the timeZone cookie tracks the browser's zone+ // on every visit, and the format cookie holds a per-device choice.+ const device = await getDeviceDateTimeConfig();+return (- <div className="flex min-h-dvh justify-center bg-background p-4 sm:items-center">- <main id="main-content" tabIndex={-1} className="w-full max-w-sm">- <article className="space-y-8">- <div className="flex justify-center py-8">- <Logo />- </div>- <header className="text-center">+ <div className="flex min-h-dvh flex-col bg-background">+ <header className="flex items-center justify-between px-4 py-3">+ <Logo size="sm" />+ <ThemeSwitcher />+ </header>+ <main+ id="main-content"+ tabIndex={-1}+ className="flex flex-1 overflow-y-auto p-4"+ >+ <article className="m-auto w-full max-w-sm space-y-8">+ <header><h1 className="font-bold text-2xl">- <Trans i18nKey="createSpace" defaults="Create Space" />+ <Trans+ i18nKey="setupAccountTitle"+ defaults="Set Up Your Account"+ /></h1><p className="mt-1 text-muted-foreground"><Trans- i18nKey="createSpaceDescription"- defaults="Create a space to organize your polls and events."+ i18nKey="setupAccountDescription"+ defaults="Tell us a bit about yourself."/></p></header><div>- <CreateSpaceForm />+ <SetupForm+ defaultName={user.name}+ defaultTimeZone={user.timeZone ?? device.timeZone}+ defaultTimeFormat={user.timeFormat ?? device.timeFormat}+ /></div></article></main>+ <footer className="flex justify-center p-16">+ <SetupFooter email={user.email} />+ </footer></div>);}@@ -44,8 +72,8 @@ export default async function SetupPage() {export async function generateMetadata(): Promise<Metadata> {const { t } = await getTranslation();return {- title: t("createSpace", {- defaultValue: "Create Space",+ title: t("setupAccountTitle", {+ defaultValue: "Set Up Your Account",}),};}diff --git a/apps/web/src/components/theme-switcher.tsx b/apps/web/src/components/theme-switcher.tsxnew file mode 100644index 000000000..dafb787c3--- /dev/null+++ b/apps/web/src/components/theme-switcher.tsx@@ -0,0 +1,50 @@+"use client";++import { ButtonGroup, ButtonGroupItem } from "@rallly/ui/button-group";+import { MonitorIcon, MoonIcon, SunIcon } from "lucide-react";+import React from "react";+import { useTranslation } from "@/i18n/client";+import { useTheme } from "@/lib/theme";++export function ThemeSwitcher() {+ const { t } = useTranslation();+ const { theme, setTheme } = useTheme();+ // next-themes reads localStorage during the first client render, which+ // the server can't know — show no selection until mounted so hydration+ // matches. The empty string (not undefined) keeps the group controlled+ // for its whole life.+ const [isMounted, setIsMounted] = React.useState(false);+ React.useEffect(() => {+ setIsMounted(true);+ }, []);++ return (+ <ButtonGroup+ aria-label={t("theme", { defaultValue: "Theme" })}+ value={isMounted ? (theme ?? "") : ""}+ onValueChange={setTheme}+ >+ <ButtonGroupItem+ value="system"+ className="px-2"+ aria-label={t("themeSystem", { defaultValue: "System" })}+ >+ <MonitorIcon className="size-4" />+ </ButtonGroupItem>+ <ButtonGroupItem+ value="light"+ className="px-2"+ aria-label={t("themeLight", { defaultValue: "Light" })}+ >+ <SunIcon className="size-4" />+ </ButtonGroupItem>+ <ButtonGroupItem+ value="dark"+ className="px-2"+ aria-label={t("themeDark", { defaultValue: "Dark" })}+ >+ <MoonIcon className="size-4" />+ </ButtonGroupItem>+ </ButtonGroup>+ );+}diff --git a/apps/web/src/features/auth/mutations.ts b/apps/web/src/features/auth/mutations.tsindex c4f9fe587..7f77d33aa 100644--- a/apps/web/src/features/auth/mutations.ts+++ b/apps/web/src/features/auth/mutations.ts@@ -54,49 +54,54 @@ export const linkAnonymousUser = async (userId: authenticatedUserId,});- if (spaceId) {- await prisma.$transaction(async (tx) => {- // Transfer space-scoped data from anonymous user to authenticated user- await Promise.all([- // Transfer polls- tx.poll.updateMany({- where: {- userId: anonymousUserId,- },- data: {- userId: authenticatedUserId,- spaceId,- },- }),-- // Transfer participants- tx.participant.updateMany({- where: {- userId: anonymousUserId,- },- data: {- userId: authenticatedUserId,- },- }),-- // Transfer comments- tx.comment.updateMany({- where: {- userId: anonymousUserId,- },- data: {- userId: authenticatedUserId,- },- }),- ]);- });- } else {- logger.error(+ if (!spaceId) {+ // A sign-in that creates the account links the guest before the+ // user-create hook has provisioned the space. Transfer ownership+ // anyway — the anonymous user is deleted right after linking and+ // polls cascade with it — and leave spaceId null for the hook to+ // adopt once the space exists.+ logger.info({ userId: authenticatedUserId },- "User has no active space; skipped poll/participant/comment migration",+ "User has no active space yet; migrating polls without a space",);}+ await prisma.$transaction(async (tx) => {+ // Transfer space-scoped data from anonymous user to authenticated user+ await Promise.all([+ // Transfer polls+ tx.poll.updateMany({+ where: {+ userId: anonymousUserId,+ },+ data: {+ userId: authenticatedUserId,+ ...(spaceId ? { spaceId } : {}),+ },+ }),++ // Transfer participants+ tx.participant.updateMany({+ where: {+ userId: anonymousUserId,+ },+ data: {+ userId: authenticatedUserId,+ },+ }),++ // Transfer comments+ tx.comment.updateMany({+ where: {+ userId: anonymousUserId,+ },+ data: {+ userId: authenticatedUserId,+ },+ }),+ ]);+ });+// Merge user identities in PostHogposthog()?.capture({distinctId: authenticatedUserId,diff --git a/apps/web/src/features/instance-settings/utils.ts b/apps/web/src/features/instance-settings/utils.tsnew file mode 100644index 000000000..14753c9c8--- /dev/null+++ b/apps/web/src/features/instance-settings/utils.ts@@ -0,0 +1,8 @@+import "server-only";++export function isInitialAdmin(email: string) {+ return (+ process.env.INITIAL_ADMIN_EMAIL &&+ email.toLowerCase() === process.env.INITIAL_ADMIN_EMAIL.toLowerCase()+ );+}diff --git a/apps/web/src/features/poll/mutations.ts b/apps/web/src/features/poll/mutations.tsindex 51aadbdf5..f99981141 100644--- a/apps/web/src/features/poll/mutations.ts+++ b/apps/web/src/features/poll/mutations.ts@@ -111,6 +111,30 @@ export const deletePoll = async (return { id: pollId };};+/**+ * Assigns a user's space-less polls to the given space. Guest linking can+ * migrate polls before the user has a space (the linking runs ahead of+ * space provisioning on sign-up, and an existing account may have lost all+ * its spaces), so every place that creates a user's space adopts them.+ */+export async function adoptOrphanedPolls({+ userId,+ spaceId,+}: {+ userId: string;+ spaceId: string;+}) {+ await prisma.poll.updateMany({+ where: {+ userId,+ spaceId: null,+ },+ data: {+ spaceId,+ },+ });+}+/*** Marks inactive polls as deleted. Polls are inactive if they have not been* updated in the last 30 days and all dates are in the past.diff --git a/apps/web/src/features/setup/components/create-space-form.tsx b/apps/web/src/features/setup/components/create-space-form.tsxdeleted file mode 100644index 41c0e7335..000000000--- a/apps/web/src/features/setup/components/create-space-form.tsx+++ /dev/null@@ -1,82 +0,0 @@-"use client";--import { zodResolver } from "@hookform/resolvers/zod";-import { Button } from "@rallly/ui/button";-import {- Form,- FormControl,- FormField,- FormItem,- FormLabel,- FormMessage,-} from "@rallly/ui/form";-import { Input } from "@rallly/ui/input";-import { useRouter } from "next/navigation";-import { useForm } from "react-hook-form";-import * as z from "zod";-import { Trans, useTranslation } from "@/i18n/client";-import { trpc } from "@/trpc/client";--const createSpaceFormSchema = z.object({- name: z.string().min(1).max(100),-});--export function CreateSpaceForm() {- const { t } = useTranslation();- const router = useRouter();-- const form = useForm({- resolver: zodResolver(createSpaceFormSchema),- defaultValues: {- name: t("personal", { defaultValue: "Personal" }),- },- });-- const createSpace = trpc.spaces.create.useMutation({- onSuccess: () => {- router.refresh();- },- });-- return (- <Form {...form}>- <form- onSubmit={form.handleSubmit(({ name }) => {- createSpace.mutate({ name });- })}- className="space-y-4"- >- <FormField- control={form.control}- name="name"- render={({ field }) => (- <FormItem>- <FormLabel>- <Trans i18nKey="spaceName" defaults="Space Name" />- </FormLabel>- <FormControl>- <Input- data-1p-ignore="true"- placeholder={t("spaceNamePlaceholder", {- defaultValue: "e.g. Acme Corp",- })}- {...field}- />- </FormControl>- <FormMessage />- </FormItem>- )}- />-- <Button- type="submit"- variant="primary"- loading={createSpace.isPending}- className="w-full"- >- <Trans i18nKey="createSpace" defaults="Create Space" />- </Button>- </form>- </Form>- );-}diff --git a/apps/web/src/features/setup/utils.ts b/apps/web/src/features/setup/utils.tsdeleted file mode 100644index 3266be24a..000000000--- a/apps/web/src/features/setup/utils.ts+++ /dev/null@@ -1,19 +0,0 @@-import "server-only";--import { prisma } from "@rallly/database";--export function isInitialAdmin(email: string) {- return (- process.env.INITIAL_ADMIN_EMAIL &&- email.toLowerCase() === process.env.INITIAL_ADMIN_EMAIL.toLowerCase()- );-}--export const userHasSpaces = async (userId: string): Promise<boolean> => {- const spaceCount = await prisma.spaceMember.count({- where: {- userId: userId,- },- });- return spaceCount > 0;-};diff --git a/apps/web/src/features/space/data.ts b/apps/web/src/features/space/data.tsindex dcd70308f..4e02d0044 100644--- a/apps/web/src/features/space/data.ts+++ b/apps/web/src/features/space/data.ts@@ -120,7 +120,8 @@ export function getSpaceBranding(spaceId: string) {/*** The active space for the signed-in user, gated for server rendering:* redirects to /login when unauthenticated or a guest, redirects to /setup- * when the user has no space, and throws InvalidSessionError when banned.+ * when the user has no name, timezone, time format, or space, and throws+ * InvalidSessionError when banned.* React cached, so every page and layout that needs the space in a request* shares one gate and one query. Server component/page use only — the* redirects make it unsuitable for route handlers and tRPC procedures.@@ -152,6 +153,19 @@ export const getActiveSpace = cache(async () => {throw new InvalidSessionError();}+ // Accounts created through the OTP registration flow start without a+ // name, timezone, or time format; /setup collects them before they can+ // use the app. Pre-existing accounts missing any of these go through+ // the same (prefilled) form once.+ if (!user.name || !user.timeZone || !user.timeFormat) {+ redirect(+ buildSafeRedirectUrl({+ destination: "/setup",+ returnUrl: await getPathname(),+ }),+ );+ }+const space = await getActiveSpaceForUser(user.id);if (!space) {diff --git a/apps/web/src/lib/auth.ts b/apps/web/src/lib/auth.tsindex bd37cb542..14f3d97d3 100644--- a/apps/web/src/lib/auth.ts+++ b/apps/web/src/lib/auth.ts@@ -27,6 +27,7 @@ import { env } from "@/env";import { linkAnonymousUser } from "@/features/auth/mutations";import { isEmailBlocked, isTemporaryEmail } from "@/features/auth/utils";import { getStripe } from "@/features/billing/service";+import { adoptOrphanedPolls } from "@/features/poll/mutations";import { createSpace } from "@/features/space/mutations";import type { UserDTO } from "@/features/user/schema";import { getTranslation } from "@/i18n/server";@@ -55,6 +56,15 @@ if (env.OIDC_ISSUER_URL) {);}+// The site key renders the widget and the secret key verifies its tokens;+// with only one of them set, captcha is either silently skipped or blocks+// every OTP send. Fail at boot instead.+if (!!env.TURNSTILE_SECRET_KEY !== !!env.NEXT_PUBLIC_TURNSTILE_SITE_KEY) {+ throw new Error(+ "NEXT_PUBLIC_TURNSTILE_SITE_KEY and TURNSTILE_SECRET_KEY must be set together",+ );+}+// Conditional plugins are typed as BetterAuthPlugin[] — they don't add user// fields so losing their specific types doesn't affect session type inference.const conditionalPlugins: BetterAuthPlugin[] = [@@ -63,7 +73,10 @@ const conditionalPlugins: BetterAuthPlugin[] = [captcha({provider: "cloudflare-turnstile",secretKey: env.TURNSTILE_SECRET_KEY,- endpoints: ["/sign-up/email"],+ // Every caller of the OTP send endpoint (combined login/signup+ // page, event RSVP verification) renders the Turnstile widget and+ // sends the token via the x-captcha-response header.+ endpoints: ["/sign-up/email", "/email-otp/send-verification-otp"],}),]: []),@@ -474,6 +487,14 @@ export const authLib = betterAuth({ownerId: user.id,});+ // Guest linking can run before this hook (a sign-in that+ // creates the account links the anonymous user first), leaving+ // migrated polls without a space. Adopt them now.+ await adoptOrphanedPolls({+ userId: user.id,+ spaceId: space.id,+ });+identifyGroup({groupType: "space",groupKey: space.id,diff --git a/apps/web/src/trpc/server/create-ssr-helper.ts b/apps/web/src/trpc/server/create-ssr-helper.tsindex f5b9b9813..3f312086c 100644--- a/apps/web/src/trpc/server/create-ssr-helper.ts+++ b/apps/web/src/trpc/server/create-ssr-helper.ts@@ -2,7 +2,7 @@ import { createServerSideHelpers } from "@trpc/react-query/server";import { notFound, redirect } from "next/navigation";import { cache } from "react";import superjson from "superjson";-import { isInitialAdmin } from "@/features/setup/utils";+import { isInitialAdmin } from "@/features/instance-settings/utils";import { getCurrentUser } from "@/features/user/data";import { getSession, requireUser } from "@/lib/auth";import { getPathname } from "@/lib/pathname";diff --git a/apps/web/tests/accessibility.spec.ts b/apps/web/tests/accessibility.spec.tsindex 3ef411882..13a524e23 100644--- a/apps/web/tests/accessibility.spec.ts+++ b/apps/web/tests/accessibility.spec.ts@@ -34,9 +34,18 @@ test.describe("accessibility (axe-core, WCAG 2.1 A/AA)", () => {expect(await scan(page)).toEqual([]);});- test("register page", async ({ page }) => {- await page.goto("/register");- await page.getByRole("heading", { name: "Create Your Account" }).waitFor();+ test("login verify page", async ({ page }) => {+ await page.goto("/login");+ await page.getByText("Welcome").waitFor();+ await expect(async () => {+ await page+ .getByPlaceholder("[email protected]")+ .fill("[email protected]");+ await page.getByRole("button", { name: "Continue with email" }).click();+ await page+ .getByRole("heading", { name: "Verify Your Email" })+ .waitFor({ timeout: 5000 });+ }).toPass();expect(await scan(page)).toEqual([]);});diff --git a/apps/web/tests/authentication.spec.ts b/apps/web/tests/authentication.spec.tsindex a3b149c42..8a7f17ace 100644--- a/apps/web/tests/authentication.spec.ts+++ b/apps/web/tests/authentication.spec.ts@@ -10,7 +10,6 @@ import { createUserInDb, loginWithEmail } from "./test-utils";const testUserEmail = "[email protected]";const testExistingUserEmail = "[email protected]";-const testPassword = "TestPassword123!";test.describe.serial(() => {test.afterAll(async () => {@@ -34,29 +33,25 @@ test.describe.serial(() => {await registerPage.register({name: "Test User",email: testUserEmail,- password: testPassword,});});});test.describe("Existing User", () => {- test("sends OTP to existing user when registering with existing email", async ({+ test("signs in existing user when registering with existing email", async ({page,}) => {- await page.goto("/register");-- await page.getByText("Create Your Account").waitFor();+ await page.goto("/login");+ await page.getByText("Welcome").waitFor();- await page.getByPlaceholder("Jessie Smith").fill("Test User");await page.getByPlaceholder("[email protected]").fill(testUserEmail);- await page.getByPlaceholder("••••••••").fill(testPassword);- await page.getByRole("button", { name: "Continue", exact: true }).click();+ await page.getByRole("button", { name: "Continue with email" }).click();// Should show the verification code prompt (not an error) to prevent email enumeration- await page.getByRole("heading", { name: "Finish Logging In" }).waitFor();+ await page.getByRole("heading", { name: "Verify Your Email" }).waitFor();// The existing user should have received a sign-in OTPconst code = await getCode(testUserEmail);@@ -66,24 +61,6 @@ test.describe.serial(() => {await expect(page.getByText("Test User")).toBeVisible();});- test("can login with password", async ({ page }) => {- await page.goto("/login");-- await page- .getByPlaceholder("[email protected]")- .fill(testUserEmail);-- await page.getByRole("button", { name: "Continue with email" }).click();-- // Password field should appear since user has a credential account- await page.getByPlaceholder("••••••••").waitFor();- await page.getByPlaceholder("••••••••").fill(testPassword);-- await page.getByRole("button", { name: "Login with password" }).click();-- await expect(page.getByText("Test User")).toBeVisible();- });-test("shows error for invalid verification code", async ({ page }) => {await page.goto("/login");@@ -93,9 +70,7 @@ test.describe.serial(() => {await page.getByRole("button", { name: "Continue with email" }).click();- expect(page.getByPlaceholder("••••••••")).toBeVisible();-- await page.getByRole("button", { name: "Login with email" }).click();+ await page.getByRole("heading", { name: "Verify Your Email" }).waitFor();await page.getByLabel("Enter your 6-digit code").fill("000000");@@ -113,9 +88,7 @@ test.describe.serial(() => {await page.getByRole("button", { name: "Continue with email" }).click();- expect(page.getByPlaceholder("••••••••")).toBeVisible();-- await page.getByRole("button", { name: "Login with email" }).click();+ await page.getByRole("heading", { name: "Verify Your Email" }).waitFor();const code = await getCode(testUserEmail);@@ -127,49 +100,23 @@ test.describe.serial(() => {test("allow using different case in email", async ({ page }) => {await page.goto("/login");const testDifferentCaseEmail = "[email protected]"; // different case than the test user email+await page.getByPlaceholder("[email protected]").fill(testDifferentCaseEmail);await page.getByRole("button", { name: "Continue with email" }).click();- await page.getByPlaceholder("••••••••").fill(testPassword);+ await page.getByRole("heading", { name: "Verify Your Email" }).waitFor();++ const code = await getCode(testUserEmail);- await page.getByRole("button", { name: "Login with password" }).click();+ await page.getByLabel("Enter your 6-digit code").fill(code);await expect(page.getByText("Test User")).toBeVisible();});test.describe("Password Reset", () => {- test("can access forgot password page from login", async ({ page }) => {- await page.goto("/login");-- // Wait for login page to load- await page.getByText("Welcome").waitFor();-- // Enter email to trigger password field rendering- await page- .getByPlaceholder("[email protected]")- .fill(testUserEmail);- await page.getByRole("button", { name: "Continue with email" }).click();-- // Password field should now be visible since user has a credential account- await page.getByPlaceholder("••••••••").waitFor();-- // Now click forgot password link- await page.getByRole("link", { name: "Forgot password?" }).click();-- // Verify we're on the forgot password page- await expect(page).toHaveURL(/\/forgot-password/);- await expect(- page.getByRole("heading", { name: "Forgot Password" }),- ).toBeVisible();-- // Verify email is pre-filled as a UX improvement- const emailInput = page.getByRole("textbox", { name: "Email" });- await expect(emailInput).toHaveValue(testUserEmail);- });-test("can request password reset with email", async ({ page }) => {await page.goto("/forgot-password");@@ -230,7 +177,8 @@ test.describe.serial(() => {});test("can reset password with valid token", async ({ page }) => {- // Request a password reset+ // Request a password reset. The account was created without a+ // password, so this doubles as the way to set one up.await page.goto("/forgot-password");await page.getByPlaceholder("[email protected]")@@ -259,6 +207,36 @@ test.describe.serial(() => {await expect(page).toHaveURL(/\/login/);});+ test("can access forgot password page from login", async ({ page }) => {+ await page.goto("/login");++ // Wait for login page to load+ await page.getByText("Welcome").waitFor();++ // Enter email to trigger password field rendering+ await page+ .getByPlaceholder("[email protected]")+ .fill(testUserEmail);+ await page.getByRole("button", { name: "Continue with email" }).click();++ // Password field should now be visible since the reset gave the user+ // a credential account+ await page.getByPlaceholder("••••••••").waitFor();++ // Now click forgot password link+ await page.getByRole("link", { name: "Forgot password?" }).click();++ // Verify we're on the forgot password page+ await expect(page).toHaveURL(/\/forgot-password/);+ await expect(+ page.getByRole("heading", { name: "Forgot Password" }),+ ).toBeVisible();++ // Verify email is pre-filled as a UX improvement+ const emailInput = page.getByRole("textbox", { name: "Email" });+ await expect(emailInput).toHaveValue(testUserEmail);+ });+test("shows error for invalid token", async ({ page }) => {// Navigate to reset password with invalid tokenawait page.goto("/reset-password?token=invalid-token-123");diff --git a/apps/web/tests/cross-timezone.spec.ts b/apps/web/tests/cross-timezone.spec.tsindex 2906084c9..a041ad360 100644--- a/apps/web/tests/cross-timezone.spec.ts+++ b/apps/web/tests/cross-timezone.spec.ts@@ -96,6 +96,7 @@ async function seed() {name: "Cross TZ Host",locale: "en",timeZone: "Europe/London",+ timeFormat: "hours24",emailVerified: true,},});diff --git a/apps/web/tests/guest-to-user-migration.spec.ts b/apps/web/tests/guest-to-user-migration.spec.tsindex c4bc9ec89..5efff1965 100644--- a/apps/web/tests/guest-to-user-migration.spec.ts+++ b/apps/web/tests/guest-to-user-migration.spec.ts@@ -8,7 +8,6 @@ import { RegisterPage } from "./register-page";const testUser = {name: "Test User",email: "[email protected]",- password: "TestPassword456!",};test.describe.serial(() => {@@ -34,9 +33,9 @@ test.describe.serial(() => {const dialog = await newPollPage.create({ name: "Monthly Meetup" });await dialog.goToPollPage();- // Step 2: Navigate to registration+ // Step 2: Navigate to registration (redirects to the combined login page)await page.click("text=Create an account");- await expect(page).toHaveURL(/register/);+ await expect(page).toHaveURL(/login/);// Step 3: Complete registrationconst registerPage = new RegisterPage(page);@@ -63,7 +62,6 @@ test.describe.serial(() => {const loginPage = new LoginPage(page);await loginPage.login({email: testUser.email,- password: testUser.password,});// Step 4: Verify the poll has been linked to the logged-in userdiff --git a/apps/web/tests/login-page.ts b/apps/web/tests/login-page.tsindex 3f668c13e..b45147e7f 100644--- a/apps/web/tests/login-page.ts+++ b/apps/web/tests/login-page.ts@@ -29,7 +29,7 @@ export class LoginPage {// Handle verification code for email OTP loginconst code = await getCode(email);await this.page- .getByRole("heading", { name: "Finish Logging In" })+ .getByRole("heading", { name: "Verify Your Email" }).waitFor();await this.page.getByLabel("Enter your 6-digit code").fill(code);}diff --git a/apps/web/tests/register-page.ts b/apps/web/tests/register-page.tsindex 09a4c4838..2048f9a19 100644--- a/apps/web/tests/register-page.ts+++ b/apps/web/tests/register-page.ts@@ -3,41 +3,43 @@ import { expect } from "@playwright/test";import { getCode } from "@rallly/test-helpers";+/**+ * Registration happens through the combined login flow: an email that+ * doesn't have an account gets one created on OTP verification, followed by+ * name onboarding.+ */export class RegisterPage {constructor(private readonly page: Page) {}async goto() {- await this.page.goto("/register");- await this.page- .getByRole("heading", { name: "Create Your Account" })- .waitFor();+ await this.page.goto("/login");+ await this.page.getByText("Welcome").waitFor();}- async register({- name,- email,- password,- }: {- name: string;- email: string;- password: string;- }) {- // Fill in registration form- await this.page.getByPlaceholder("Jessie Smith").fill(name);+ async register({ name, email }: { name: string; email: string }) {+ // Request a verification codeawait this.page.getByPlaceholder("[email protected]").fill(email);- await this.page.getByPlaceholder("••••••••").fill(password);-await this.page- .getByRole("button", { name: "Continue", exact: true })+ .getByRole("button", { name: "Continue with email" }).click();// Handle verification codeconst code = await getCode(email);await this.page- .getByRole("heading", { name: "Finish Logging In" })+ .getByRole("heading", { name: "Verify Your Email" }).waitFor();await this.page.getByLabel("Enter your 6-digit code").fill(code);+ // New accounts have no name and go through onboarding. The space name+ // is prefilled, so only the name needs to be entered.+ await this.page+ .getByRole("heading", { name: "Set Up Your Account" })+ .waitFor();+ await this.page.getByPlaceholder("Jessie Smith").fill(name);+ await this.page+ .getByRole("button", { name: "Continue", exact: true })+ .click();+// Verify successful registrationawait expect(this.page.getByText(name)).toBeVisible();}diff --git a/apps/web/tests/rsvp-confirmation-email.spec.ts b/apps/web/tests/rsvp-confirmation-email.spec.tsindex 2e514e296..2c06a3e67 100644--- a/apps/web/tests/rsvp-confirmation-email.spec.ts+++ b/apps/web/tests/rsvp-confirmation-email.spec.ts@@ -34,6 +34,7 @@ async function seed() {name: "RSVP Email Host",locale: "en",timeZone: "Europe/London",+ timeFormat: "hours24",emailVerified: true,},});diff --git a/apps/web/tests/test-utils.ts b/apps/web/tests/test-utils.tsindex e30ee959e..7f6cabc3e 100644--- a/apps/web/tests/test-utils.ts+++ b/apps/web/tests/test-utils.ts@@ -21,6 +21,7 @@ export async function createUserInDb({role,locale: "en",timeZone: "Europe/London",+ timeFormat: "hours24",emailVerified: true,},});diff --git a/packages/test-helpers/src/login.ts b/packages/test-helpers/src/login.tsindex 6cd5400c9..880069189 100644--- a/packages/test-helpers/src/login.ts+++ b/packages/test-helpers/src/login.ts@@ -18,7 +18,7 @@ export async function loginWithEmail(await page.getByPlaceholder("[email protected]").fill(email);await page.getByRole("button", { name: "Continue with email" }).click();await page- .getByRole("heading", { name: "Finish Logging In" })+ .getByRole("heading", { name: /Verify Your Email|Finish Logging In/ }).or(page.getByLabel("Password")).first().waitFor({ timeout: 5000 });diff --git a/packages/ui/src/button-group.tsx b/packages/ui/src/button-group.tsxnew file mode 100644index 000000000..15a19ae39--- /dev/null+++ b/packages/ui/src/button-group.tsx@@ -0,0 +1,54 @@+"use client";++import { Toggle } from "@base-ui/react/toggle";+import { ToggleGroup as ToggleGroupPrimitive } from "@base-ui/react/toggle-group";++import { cn } from "./lib/utils";++/**+ * A segmented control: a group of joined buttons where exactly one is+ * selected. Built on Base UI's single-select toggle group, so items are+ * real buttons with aria-pressed state and arrow key navigation.+ */+function ButtonGroup({+ className,+ value,+ onValueChange,+ ...props+}: Omit<ToggleGroupPrimitive.Props, "value" | "onValueChange" | "multiple"> & {+ value?: string;+ onValueChange?: (value: string) => void;+}) {+ return (+ <ToggleGroupPrimitive+ data-slot="button-group"+ value={value !== undefined ? [value] : undefined}+ onValueChange={(groupValue) => {+ // Ignore deselection so one item is always active+ if (groupValue[0] !== undefined) {+ onValueChange?.(groupValue[0]);+ }+ }}+ className={cn(+ "inline-flex h-9 items-center gap-0.5 rounded-lg border border-input bg-background p-0.5",+ className,+ )}+ {...props}+ />+ );+}++function ButtonGroupItem({ className, ...props }: Toggle.Props) {+ return (+ <Toggle+ data-slot="button-group-item"+ className={cn(+ "inline-flex h-full flex-1 cursor-pointer select-none items-center justify-center whitespace-nowrap rounded-md px-3 font-medium text-muted-foreground text-sm transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring data-disabled:pointer-events-none data-pressed:bg-accent data-pressed:text-foreground data-disabled:opacity-50",+ className,+ )}+ {...props}+ />+ );+}++export { ButtonGroup, ButtonGroupItem };diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 48f5e06d9..b4fac8556 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -217,8 +217,8 @@ importers:specifier: ^5.2.2'@marsidev/react-turnstile':- specifier: ^1.4.2+ specifier: ^1.5.3'@next/env':specifier: 16.2.6version: 16.2.6@@ -3046,8 +3046,8 @@ packages:'@leichtgewicht/[email protected]':resolution: {integrity: sha512-Vo+PSpZG2/fmgmiNzYK9qWRh8h/CHrwD0mo1h1DzL4yzHNSfWYujGTYsWGreD000gcgmZ7K4Ys6Tx9TxtsKdDw==}- '@marsidev/[email protected]':- resolution: {integrity: sha512-xs1qOuyeMOz6t9BXXCXWiukC0/0+48vR08B7uwNdG05wCMnbcNgxiFmdFKDOFbM76qFYFRYlGeRfhfq1U/iZmA==}+ '@marsidev/[email protected]':+ resolution: {integrity: sha512-8Dij2jiNGNczq1U4EKpO4do2XepcTPxSMc2ZzvHndO+gcp68tvMULm27z2P99rGkdB89hc3452NZeu2Rti4g6A==}peerDependencies:react: ^17.0.2 || ^18.0.0 || ^19.0react-dom: ^17.0.2 || ^18.0.0 || ^19.0@@ -13946,7 +13946,7 @@ snapshots:'@leichtgewicht/[email protected]': {}dependencies:react: 19.2.6react-dom: 19.2.6([email protected])