diff --git a/app/api/auth/[...nextauth]/auth.config.ts b/app/api/auth/[...nextauth]/auth.config.ts index 6eb6a2f34..1bbdb7339 100644 --- a/app/api/auth/[...nextauth]/auth.config.ts +++ b/app/api/auth/[...nextauth]/auth.config.ts @@ -4,7 +4,6 @@ import GoogleProvider from 'next-auth/providers/google'; import TwitterProvider from 'next-auth/providers/twitter'; import CredentialsProvider from 'next-auth/providers/credentials'; import { AuthService } from '@/services/auth.service'; -import { AuthSharingService } from '@/services/auth-sharing.service'; // Debug flag - set to true to enable detailed authentication logging const DEBUG_AUTH = true; @@ -70,7 +69,7 @@ export const authOptions: NextAuthOptions = { }, async authorize(credentials, req) { try { - // If we have an authToken from the shared cookie, use that directly + // Email verification and MFA sign in with an already-issued token. if (credentials?.authToken) { try { // Fetch user data using the provided authToken @@ -83,7 +82,6 @@ export const authOptions: NextAuthOptions = { authToken: credentials.authToken, }; } catch (error) { - AuthSharingService.removeSharedAuthToken(); return promptInvalidCredentials(); } } diff --git a/app/api/auth/logout/route.ts b/app/api/auth/logout/route.ts deleted file mode 100644 index f5e671bba..000000000 --- a/app/api/auth/logout/route.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { NextResponse } from 'next/server'; -import { AuthSharingService } from '@/services/auth-sharing.service'; - -/** - * Gets the cookie prefix based on the environment - * @returns The next-auth cookie prefix - */ -function getCookiePrefix(): string { - const env = process.env.NEXT_PUBLIC_VERCEL_ENV; - if (env === 'production' || env === 'preview') { - return '__Secure-'; - } - return ''; -} - -/** - * Handles the shared logout process by clearing the authentication cookies - * and redirecting to the callback URL or the origin. - * - * @param request - The HTTP request object - * @returns A redirect response to the callback URL or origin - */ -export async function GET(request: Request) { - const { searchParams, origin } = new URL(request.url); - const callbackUrl = searchParams.get('callbackUrl') || origin; - - try { - const expiredDate = new Date(0).toUTCString(); - const prefix = getCookiePrefix(); - - return new Response(null, { - status: 307, - headers: { - Location: callbackUrl, - 'Set-Cookie': [ - `${prefix}next-auth.session-token=; Expires=${expiredDate}; Path=/; HttpOnly; Secure`, - `${prefix}next-auth.csrf-token=; Expires=${expiredDate}; Path=/; HttpOnly; Secure`, - `${AuthSharingService.getAuthCookieName()}=; Expires=${expiredDate}; Path=/; Domain=${AuthSharingService.getParentDomain()}; HttpOnly; Secure`, - ].join(', '), - }, - }); - } catch (error) { - return NextResponse.redirect(callbackUrl, 307); - } -} diff --git a/components/AuthSharingWrapper.tsx b/components/AuthSharingWrapper.tsx deleted file mode 100644 index 065b2f9c0..000000000 --- a/components/AuthSharingWrapper.tsx +++ /dev/null @@ -1,88 +0,0 @@ -'use client'; - -import { Dialog, Transition } from '@headlessui/react'; -import { Fragment } from 'react'; -import { useSession, signIn } from 'next-auth/react'; -import { useEffect, useState } from 'react'; -import { AuthSharingService } from '@/services/auth-sharing.service'; -import { Loader2 } from 'lucide-react'; - -export function AuthSharingWrapper({ children }: { children: React.ReactNode }) { - const { data: session, status } = useSession(); - const [isChecking, setIsChecking] = useState(false); - - useEffect(() => { - const checkSharedToken = async () => { - // Only check if we're not authenticated - if (status === 'unauthenticated') { - const sharedToken = AuthSharingService.getSharedAuthToken(); - - if (sharedToken) { - setIsChecking(true); - await signIn('credentials', { - authToken: sharedToken, - redirect: false, - }); - AuthSharingService.removeSharedAuthToken(); - setIsChecking(false); - } - } - }; - - checkSharedToken(); - }, [status]); - - useEffect(() => { - if (session?.authToken) { - AuthSharingService.setSharedAuthToken(session.authToken); - } - }, [session?.authToken]); - - return ( - <> - {children} - - - {}}> - - - - - - - - - - - - Authorizing... - - - We found your existing session. Signing you in automatically... - - - - - - - - - > - ); -} diff --git a/components/LegacyAuthCookieCleanup.tsx b/components/LegacyAuthCookieCleanup.tsx new file mode 100644 index 000000000..276dcba13 --- /dev/null +++ b/components/LegacyAuthCookieCleanup.tsx @@ -0,0 +1,30 @@ +'use client'; + +import Cookies from 'js-cookie'; +import { useEffect } from 'react'; + +// +// FIXME: Remove this file once the legacy auth cookie is no longer valid (14 days after deploy) +// +// The retired cross-app auth sharing kept the API token in a script-readable +// cookie on the parent domain, where every subdomain could read it. Each write +// set a 14-day expiry, so this can be deleted two weeks after deploy. +const LEGACY_AUTH_COOKIE = (() => { + switch (process.env.NEXT_PUBLIC_VERCEL_ENV) { + case 'production': + return { name: 'prod.researchhub.auth.token', domain: '.researchhub.com' }; + case 'preview': + case 'development': + return { name: 'stg.researchhub.auth.token', domain: '.staging.researchhub.com' }; + default: + return { name: 'local.researchhub.auth.token', domain: 'localhost' }; + } +})(); + +export function LegacyAuthCookieCleanup() { + useEffect(() => { + Cookies.remove(LEGACY_AUTH_COOKIE.name, { domain: LEGACY_AUTH_COOKIE.domain, path: '/' }); + }, []); + + return null; +} diff --git a/components/You/YouMoreCard.tsx b/components/You/YouMoreCard.tsx index bcaceef18..8b76ea84a 100644 --- a/components/You/YouMoreCard.tsx +++ b/components/You/YouMoreCard.tsx @@ -25,7 +25,7 @@ import { useChangelogSeen } from '@/components/changelog/useChangelogSeen'; import { BaseMenu } from '@/components/ui/form/BaseMenu'; import { ResearchCoinIcon } from '@/components/ui/icons/ResearchCoinIcon'; import { useVerification } from '@/contexts/VerificationContext'; -import { AuthSharingService } from '@/services/auth-sharing.service'; +import { signOutUser } from '@/utils/auth'; import type { User } from '@/types/user'; import { cn } from '@/utils/styles'; import { CurrencySwitch } from './CurrencySwitch'; @@ -245,7 +245,7 @@ export function YouAccountCard({ AuthSharingService.signOutFromBothApps()} + onClick={() => signOutUser()} className={YOU_ROW} data-testid="user-menu-signout" > diff --git a/components/events/catalyst/CatalystLoggedInBody.tsx b/components/events/catalyst/CatalystLoggedInBody.tsx index bc2663e36..3295b6585 100644 --- a/components/events/catalyst/CatalystLoggedInBody.tsx +++ b/components/events/catalyst/CatalystLoggedInBody.tsx @@ -1,9 +1,7 @@ 'use client'; import { useRouter } from 'next/navigation'; -import { signOut } from 'next-auth/react'; -import AnalyticsService from '@/services/analytics.service'; -import { AuthSharingService } from '@/services/auth-sharing.service'; +import { signOutUser } from '@/utils/auth'; import { CATALYST_NYC_EVENT, formatCredit } from './constants'; const { footer, loggedIn, creditAmount, route } = CATALYST_NYC_EVENT; @@ -23,9 +21,7 @@ export function CatalystLoggedInBody({ const isMobile = variant === 'mobile'; const handleSignOut = () => { - AuthSharingService.removeSharedAuthToken(); - AnalyticsService.clearUserSession(); - signOut({ callbackUrl: route }); + void signOutUser(route); }; return ( diff --git a/components/menus/UserMenu.tsx b/components/menus/UserMenu.tsx index dca1e8853..bd3cc3a91 100644 --- a/components/menus/UserMenu.tsx +++ b/components/menus/UserMenu.tsx @@ -18,7 +18,7 @@ import { BaseMenu, BaseMenuItem } from '@/components/ui/form/BaseMenu'; import { VerifiedBadge } from '@/components/ui/VerifiedBadge'; import { ResearchCoinIcon } from '@/components/ui/icons/ResearchCoinIcon'; import Link from 'next/link'; -import { AuthSharingService } from '@/services/auth-sharing.service'; +import { signOutUser } from '@/utils/auth'; import { navigateToAuthorProfile } from '@/utils/navigation'; import { useVerification } from '@/contexts/VerificationContext'; import { YouPanel } from '@/components/You/YouPanel'; @@ -213,7 +213,7 @@ export default function UserMenu({ AuthSharingService.signOutFromBothApps()} + onClick={() => signOutUser()} className="w-full px-4 py-2" data-testid="user-menu-signout" > diff --git a/components/providers/ClientProviders.tsx b/components/providers/ClientProviders.tsx index f909e61fe..ee8b0f128 100644 --- a/components/providers/ClientProviders.tsx +++ b/components/providers/ClientProviders.tsx @@ -13,7 +13,7 @@ import { UserProvider } from '@/contexts/UserContext'; import { OrganizationProvider } from '@/contexts/OrganizationContext'; import { OnchainProvider } from '@/contexts/OnchainContext'; import { NavigationProvider } from '@/contexts/NavigationContext'; -import { AuthSharingWrapper } from '@/components/AuthSharingWrapper'; +import { LegacyAuthCookieCleanup } from '@/components/LegacyAuthCookieCleanup'; import { VerificationProvider } from '@/contexts/VerificationContext'; import SignupModalContainer from '@/components/modals/SignupModalContainer'; import { ShareModalProvider } from '@/contexts/ShareContext'; @@ -34,49 +34,48 @@ export function ClientProviders({ children, session }: ClientProvidersProps) { return ( <> + - - - <> - - - - - - {/* Above the layouts because the left sidebar - carries the funding power card and mounts - outside PageLayout on some routes. */} - - - - {/* Above the layouts: every page's left - sidebar lists these documents, and - navigating must not fetch them again. */} - - - - {/* Inside the user providers: the share - modal's post preview shows the sharer. */} - {children} - - - - - - - - - - - - - - > - - + + <> + + + + + + {/* Above the layouts because the left sidebar + carries the funding power card and mounts + outside PageLayout on some routes. */} + + + + {/* Above the layouts: every page's left + sidebar lists these documents, and + navigating must not fetch them again. */} + + + + {/* Inside the user providers: the share + modal's post preview shows the sharer. */} + {children} + + + + + + + + + + + + + + > + diff --git a/config/constants.ts b/config/constants.ts index fece7f703..84cda053d 100644 --- a/config/constants.ts +++ b/config/constants.ts @@ -1,6 +1,3 @@ -// Authentication token key used in cookies - it matches the old app's token name (rh-web/config/constants.js) -export const AUTH_TOKEN = 'researchhub.auth.token'; - // ResearchHub Foundation account user ID - bounties created by this account display a flat $150 USD amount // Set via NEXT_PUBLIC_FOUNDATION_USER_ID environment variable export const FOUNDATION_USER_ID = process.env.NEXT_PUBLIC_FOUNDATION_USER_ID diff --git a/contexts/UserContext.tsx b/contexts/UserContext.tsx index 6ef9555d8..7e2a8608a 100644 --- a/contexts/UserContext.tsx +++ b/contexts/UserContext.tsx @@ -4,7 +4,7 @@ import { createContext, useContext, ReactNode, useState, useEffect } from 'react import { useSession } from 'next-auth/react'; import { AuthError, AuthService } from '@/services/auth.service'; import type { User } from '@/types/user'; -import { AuthSharingService } from '@/services/auth-sharing.service'; +import { signOutUser } from '@/utils/auth'; import AnalyticsService from '@/services/analytics.service'; interface UserContextType { @@ -41,7 +41,7 @@ export function UserProvider({ children }: { children: ReactNode }) { } catch (err) { if (err instanceof AuthError) { if (err.code === 401) { - await AuthSharingService.signOutFromBothApps(); + await signOutUser(); } } if (!silent) setError(err instanceof Error ? err : new Error('Failed to load user data')); diff --git a/services/auth-sharing.service.ts b/services/auth-sharing.service.ts deleted file mode 100644 index 902372c6c..000000000 --- a/services/auth-sharing.service.ts +++ /dev/null @@ -1,97 +0,0 @@ -import Cookies from 'js-cookie'; -import { AUTH_TOKEN } from '@/config/constants'; -import { signOut } from 'next-auth/react'; -import AnalyticsService from './analytics.service'; - -/** - * Service to handle authentication sharing between the old and new ResearchHub applications - */ -export class AuthSharingService { - private static readonly ENV_PREFIX = (() => { - switch (process.env.NEXT_PUBLIC_VERCEL_ENV) { - case 'production': - return 'prod'; - case 'preview': - case 'development': - return 'stg'; - default: - return 'local'; - } - })(); - - private static readonly AUTH_COOKIE_NAME = `${AuthSharingService.ENV_PREFIX}.${AUTH_TOKEN}`; - - /** - * The parent domain that both applications share (for cookie sharing) - */ - private static readonly PARENT_DOMAIN = (() => { - switch (process.env.NEXT_PUBLIC_VERCEL_ENV) { - case 'production': - return '.researchhub.com'; - case 'preview': - case 'development': - return '.staging.researchhub.com'; - default: - return 'localhost'; - } - })(); - - public static getAuthCookieName(): string { - return this.AUTH_COOKIE_NAME; - } - - public static getParentDomain(): string { - return this.PARENT_DOMAIN; - } - - /** - * Sets the authentication token in a shared cookie that can be accessed by both domains - * @param token The authentication token to store - * @param expiryDays Number of days until the cookie expires (default: 14) - */ - static setSharedAuthToken(token: string, expiryDays = 14): void { - const cookieOptions: Cookies.CookieAttributes = { - expires: new Date(Date.now() + expiryDays * 24 * 60 * 60 * 1000), - path: '/', - domain: this.PARENT_DOMAIN, - secure: process.env.NEXT_PUBLIC_VERCEL_ENV !== undefined, - sameSite: 'lax', - }; - - Cookies.set(this.AUTH_COOKIE_NAME, token, cookieOptions); - } - - /** - * Gets the authentication token from the shared cookie - * @returns The authentication token or null if not found - */ - static getSharedAuthToken(): string | null { - const token = Cookies.get(this.AUTH_COOKIE_NAME); - - return token || null; - } - - /** - * Removes the shared authentication token (logout) - */ - static removeSharedAuthToken(): void { - Cookies.remove(this.AUTH_COOKIE_NAME, { - domain: this.PARENT_DOMAIN, - path: '/', - }); - } - - /** - * Signs out from both applications by removing the token - * and calling the signOut method - */ - static async signOutFromBothApps(): Promise { - // First remove the shared cookie - this.removeSharedAuthToken(); - // Reset analytics session - AnalyticsService.clearUserSession(); - - // Finally, sign out from NextAuth - await signOut({ callbackUrl: '/' }); - } -} diff --git a/utils/auth.ts b/utils/auth.ts new file mode 100644 index 000000000..b9ad0c11a --- /dev/null +++ b/utils/auth.ts @@ -0,0 +1,7 @@ +import { signOut } from 'next-auth/react'; +import AnalyticsService from '@/services/analytics.service'; + +export async function signOutUser(callbackUrl = '/'): Promise { + AnalyticsService.clearUserSession(); + await signOut({ callbackUrl }); +}
- We found your existing session. Signing you in automatically... -