Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
fix(auth): return signed-out visitors to the page they asked for after signing in (#1197)
Cihan475771afe75e
diff --git a/web/src/app/auth/callback/route.test.ts b/web/src/app/auth/callback/route.test.tsnew file mode 100644index 000000000..62c0650e1--- /dev/null+++ b/web/src/app/auth/callback/route.test.ts@@ -0,0 +1,57 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { NextRequest } from 'next/server';++/**+ * /auth/callback, where GitHub and Google sign-in come back: on to the page+ * the visitor asked for (`?next=` or the OAuth buttons' cookie), only one of+ * ours, and the cookie is cleared.+ */++const exchange = vi.fn();+vi.mock('@/lib/supabase/server', () => ({+ createClient: async () => ({ auth: { exchangeCodeForSession: exchange } }),+}));++const { GET } = await import('./route');++const callback = (query: string, cookie?: string) =>+ GET(+ new NextRequest(`https://app.example.com/auth/callback?${query}`, {+ headers: cookie ? { cookie } : {},+ }),+ );++beforeEach(() => exchange.mockReset().mockResolvedValue({ error: null }));++describe('GET /auth/callback', () => {+ it('goes on to ?next=, or the page the OAuth buttons kept, and clears the cookie', async () => {+ let res = await callback('code=c1&next=%2Fdashboard%2Ftraffic%3Ftab%3Dpages');+ expect(res.headers.get('location')).toBe('https://app.example.com/dashboard/traffic?tab=pages');++ res = await callback(+ 'code=c1',+ `auth_next=${encodeURIComponent('/dashboard/settings?tab=notifications')}`,+ );+ expect(res.headers.get('location')).toBe(+ 'https://app.example.com/dashboard/settings?tab=notifications',+ );+ expect(res.headers.get('set-cookie')).toMatch(+ /^auth_next=;.*Max-Age=0|Expires=Thu, 01 Jan 1970/,+ );+ });++ it('never leaves the site, and goes to the dashboard without a page', async () => {+ for (const next of ['@evil.example', '//evil.example', 'https://evil.example']) {+ const res = await callback(`code=c1&next=${encodeURIComponent(next)}`);+ expect(res.headers.get('location'), next).toBe('https://app.example.com/dashboard');+ }+ const res = await callback('code=c1');+ expect(res.headers.get('location')).toBe('https://app.example.com/dashboard');+ });++ it('sends a failed sign-in back to the sign-in page', async () => {+ exchange.mockResolvedValue({ error: { message: 'bad code' } });+ const res = await callback('code=c1&next=%2Fdashboard%2Ftraffic');+ expect(res.headers.get('location')).toBe('https://app.example.com/sign-in?error=auth');+ });+});diff --git a/web/src/app/auth/callback/route.ts b/web/src/app/auth/callback/route.tsindex fe0ee56bb..e127c66c6 100644--- a/web/src/app/auth/callback/route.ts+++ b/web/src/app/auth/callback/route.ts@@ -1,16 +1,27 @@-import { NextResponse } from 'next/server';+import { NextResponse, type NextRequest } from 'next/server';import { createClient } from '@/lib/supabase/server';+import { NEXT_COOKIE, nextFromCookie, safeNextPath } from '@/lib/auth-next';-export async function GET(request: Request) {+/**+ * GET /auth/callback — where GitHub and Google sign-in come back. Goes on to+ * the page the visitor asked for: `?next=`, or the cookie the OAuth buttons+ * set before leaving (the provider's redirect URL stays the same), and only+ * to a page on this site.+ */+export async function GET(request: NextRequest) {const { searchParams, origin } = new URL(request.url);const code = searchParams.get('code');- const next = searchParams.get('next') ?? '/dashboard';+ const next = safeNextPath(+ searchParams.get('next') ?? nextFromCookie(request.cookies.get(NEXT_COOKIE)?.value),+ );if (code) {const supabase = await createClient();const { error } = await supabase.auth.exchangeCodeForSession(code);if (!error) {- return NextResponse.redirect(`${origin}${next}`);+ const response = NextResponse.redirect(`${origin}${next}`);+ response.cookies.delete(NEXT_COOKIE);+ return response;}}diff --git a/web/src/components/auth/oauth-buttons.tsx b/web/src/components/auth/oauth-buttons.tsxindex 139dec24d..a9ca098d4 100644--- a/web/src/components/auth/oauth-buttons.tsx+++ b/web/src/components/auth/oauth-buttons.tsx@@ -2,6 +2,7 @@import { useState } from 'react';import { createClient } from '@/lib/supabase/client';+import { NEXT_COOKIE, NEXT_COOKIE_MAX_AGE, safeNextPath } from '@/lib/auth-next';import { Button } from '@/components/ui/button';import { Loader2 } from 'lucide-react';@@ -38,12 +39,21 @@ function GoogleIcon({ className }: { className?: string }) {type Provider = 'github' | 'google';-export function OAuthButtons() {+/**+ * GitHub and Google sign-in. `next` is the page to come back to: kept in a+ * short-lived cookie for /auth/callback, so the redirect URL the providers+ * and Supabase allow stays exactly the same.+ */+export function OAuthButtons({ next }: { next?: string | null } = {}) {const [loadingProvider, setLoadingProvider] = useState<Provider | null>(null);async function handleOAuth(provider: Provider) {setLoadingProvider(provider);const supabase = createClient();+ const secure = window.location.protocol === 'https:' ? '; Secure' : '';+ document.cookie = next+ ? `${NEXT_COOKIE}=${encodeURIComponent(safeNextPath(next))}; Path=/; Max-Age=${NEXT_COOKIE_MAX_AGE}; SameSite=Lax${secure}`+ : `${NEXT_COOKIE}=; Path=/; Max-Age=0; SameSite=Lax${secure}`;const { error } = await supabase.auth.signInWithOAuth({provider,diff --git a/web/src/components/auth/sign-in-form.tsx b/web/src/components/auth/sign-in-form.tsxindex d66eafe36..f65a81e75 100644--- a/web/src/components/auth/sign-in-form.tsx+++ b/web/src/components/auth/sign-in-form.tsx@@ -14,12 +14,14 @@ import { ArrowRight, Loader2 } from 'lucide-react';import { OAuthButtons } from '@/components/auth/oauth-buttons';import { OrDivider } from '@/components/auth/or-divider';import { track } from '@/lib/analytics';+import { safeNextPath } from '@/lib/auth-next';export function SignInForm() {const t = useTranslations('auth');const router = useRouter();const searchParams = useSearchParams();- const nextPath = searchParams.get('next');+ // The page the visitor was on before signing in; only one of ours.+ const nextPath = safeNextPath(searchParams.get('next'));const [email, setEmail] = useState('');const [password, setPassword] = useState('');const [isLoading, setIsLoading] = useState(false);@@ -52,7 +54,7 @@ export function SignInForm() {// so the form just needs to capture the funnel event.track('signin_completed', { source: 'email' });- router.push(nextPath && nextPath.startsWith('/') ? nextPath : '/dashboard');+ router.push(nextPath);router.refresh();}@@ -112,7 +114,7 @@ export function SignInForm() {</form><OrDivider label={t('orContinueWith')} />- <OAuthButtons />+ <OAuthButtons next={searchParams.get('next') ? nextPath : null} /></div>);}diff --git a/web/src/components/auth/sign-up-form.tsx b/web/src/components/auth/sign-up-form.tsxindex e22e3d45a..0e88e7799 100644--- a/web/src/components/auth/sign-up-form.tsx+++ b/web/src/components/auth/sign-up-form.tsx@@ -139,7 +139,7 @@ export function SignUpForm() {</form><OrDivider label={t('orContinueWith')} />- <OAuthButtons />+ <OAuthButtons next={nextPath} /><p className="text-center text-sm text-muted-foreground">{t('termsAgreement')}{' '}diff --git a/web/src/lib/auth-next.test.ts b/web/src/lib/auth-next.test.tsnew file mode 100644index 000000000..da93461a7--- /dev/null+++ b/web/src/lib/auth-next.test.ts@@ -0,0 +1,54 @@+import { describe, expect, it } from 'vitest';+import { DEFAULT_NEXT, nextFromCookie, nextFromRequest, safeNextPath } from './auth-next';++/** After signing in, back to the page asked for — and only to one of ours. */++describe('safeNextPath', () => {+ it('keeps a page on this site, with its query and hash', () => {+ expect(safeNextPath('/dashboard/traffic')).toBe('/dashboard/traffic');+ expect(safeNextPath('/dashboard/settings?tab=notifications')).toBe(+ '/dashboard/settings?tab=notifications',+ );+ expect(safeNextPath('/dashboard/action-center/actions?action=a1#tasks')).toBe(+ '/dashboard/action-center/actions?action=a1#tasks',+ );+ });++ it('sends anything that could leave the site to the dashboard', () => {+ for (const value of [+ null,+ undefined,+ '',+ 'dashboard',+ '//evil.example',+ '/\\evil.example',+ '/\\/evil.example',+ 'https://evil.example/dashboard',+ 'javascript:alert(1)',+ '@evil.example',+ '/dash\tboard',+ '/\nevil',+ ]) {+ expect(safeNextPath(value), String(value)).toBe(DEFAULT_NEXT);+ }+ });+});++describe('nextFromRequest', () => {+ it('names the page without its locale prefix, query included', () => {+ expect(nextFromRequest('/dashboard/traffic', '?tab=pages')).toBe(+ '/dashboard/traffic?tab=pages',+ );+ expect(nextFromRequest('/dashboard', '')).toBe('/dashboard');+ });+});++describe('nextFromCookie', () => {+ it('reads the page the OAuth buttons stored, encoded', () => {+ expect(nextFromCookie(encodeURIComponent('/dashboard/traffic?tab=pages'))).toBe(+ '/dashboard/traffic?tab=pages',+ );+ expect(nextFromCookie(undefined)).toBeNull();+ expect(nextFromCookie('%E0%A4%A')).toBeNull();+ });+});diff --git a/web/src/lib/auth-next.ts b/web/src/lib/auth-next.tsnew file mode 100644index 000000000..5b3804b91--- /dev/null+++ b/web/src/lib/auth-next.ts@@ -0,0 +1,46 @@+/**+ * Where a visitor goes after signing in: the page they asked for before the+ * sign-in page stopped them, carried as `?next=` (the proxy writes it, the+ * sign-in form and the OAuth callback read it). Only a page on this site:+ * anything that could leave it — `//host`, `/\host`, a scheme, `@host` —+ * falls back to the dashboard, so a crafted link can't send someone who+ * just signed in to another site.+ */++export const DEFAULT_NEXT = '/dashboard';++/** The cookie that carries `next` through an OAuth round trip (10 minutes). */+export const NEXT_COOKIE = 'auth_next';+export const NEXT_COOKIE_MAX_AGE = 600;++// Any origin works: a path has to resolve on it to be one of ours.+const BASE = 'https://app.invalid';++export function safeNextPath(value: string | null | undefined): string {+ if (!value || !value.startsWith('/') || value.startsWith('//')) return DEFAULT_NEXT;+ // A backslash reads as a slash in browsers (`/\evil.com`), and control+ // characters are stripped before parsing.+ if (/[\\\u0000-\u001f]/.test(value)) return DEFAULT_NEXT;+ try {+ const url = new URL(value, BASE);+ if (url.origin !== BASE) return DEFAULT_NEXT;+ return `${url.pathname}${url.search}${url.hash}`;+ } catch {+ return DEFAULT_NEXT;+ }+}++/** `next` as the OAuth buttons stored it in NEXT_COOKIE (URI-encoded). */+export function nextFromCookie(value: string | null | undefined): string | null {+ if (!value) return null;+ try {+ return decodeURIComponent(value);+ } catch {+ return null;+ }+}++/** The page a signed-out visitor asked for, as `next`: without the locale prefix, with its query. */+export function nextFromRequest(pathnameWithoutLocale: string, search: string): string {+ return safeNextPath(`${pathnameWithoutLocale}${search}`);+}diff --git a/web/src/proxy.test.ts b/web/src/proxy.test.tsnew file mode 100644index 000000000..687407867--- /dev/null+++ b/web/src/proxy.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it, vi } from 'vitest';+import { NextRequest, NextResponse } from 'next/server';++/**+ * A signed-out visitor of a dashboard page goes to sign-in with the page as+ * `?next=`, query included, so signing in brings them back to it — an+ * e-mail's "Open AI Traffic" button, say.+ */++// The locale routing isn't what's tested here (and its ESM build doesn't load in Vitest).+vi.mock('next-intl/middleware', () => ({ default: () => () => NextResponse.next() }));+vi.mock('@/lib/supabase/middleware', () => ({+ updateSession: async () => ({ supabaseResponse: NextResponse.next(), user: null }),+}));++const { proxy } = await import('./proxy');++describe('proxy', () => {+ it('sends a signed-out visitor to sign-in with the page they asked for', async () => {+ const res = await proxy(+ new NextRequest('https://app.example.com/dashboard/settings?tab=notifications'),+ );+ expect(res.status).toBe(307);+ const location = new URL(res.headers.get('location')!);+ expect(location.pathname).toBe('/sign-in');+ expect(location.searchParams.get('next')).toBe('/dashboard/settings?tab=notifications');+ });++ it('names the page without its locale prefix', async () => {+ const res = await proxy(new NextRequest('https://app.example.com/en/dashboard/traffic'));+ expect(new URL(res.headers.get('location')!).searchParams.get('next')).toBe(+ '/dashboard/traffic',+ );+ });+});diff --git a/web/src/proxy.ts b/web/src/proxy.tsindex fbaf5f190..d6daa265d 100644--- a/web/src/proxy.ts+++ b/web/src/proxy.ts@@ -2,6 +2,7 @@ import createMiddleware from 'next-intl/middleware';import { type NextRequest, NextResponse } from 'next/server';import { routing } from '@/i18n/routing';import { updateSession } from '@/lib/supabase/middleware';+import { nextFromRequest } from '@/lib/auth-next';const intlMiddleware = createMiddleware(routing);@@ -46,8 +47,14 @@ export async function proxy(request: NextRequest) {}if (isProtected(pathnameWithoutLocale) && !user) {+ // Back to this page after signing in, query included (an e-mail's+ // `?tab=notifications`): `next` is what the sign-in form and the OAuth+ // callback read.const signInUrl = new URL('/sign-in', request.url);- signInUrl.searchParams.set('redirectTo', pathname);+ signInUrl.searchParams.set(+ 'next',+ nextFromRequest(pathnameWithoutLocale, request.nextUrl.search),+ );return NextResponse.redirect(signInUrl);}