Skip to content

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.

fix(auth): limit the auth callback and confirm redirects to this site (#1219)

Gökhan Geyik4f03830db940
diff --git a/web/src/app/[locale]/(marketing)/auth/callback/route.ts b/web/src/app/[locale]/(marketing)/auth/callback/route.ts
index 65acabc50..b1d397f90 100644
--- a/web/src/app/[locale]/(marketing)/auth/callback/route.ts
+++ b/web/src/app/[locale]/(marketing)/auth/callback/route.ts
@@ -1,28 +1,7 @@
-import { NextResponse } from 'next/server';
-import { createClient } from '@/lib/supabase/server';
-
-export async function GET(request: Request) {
- const { searchParams, origin } = new URL(request.url);
- const code = searchParams.get('code');
- const next = searchParams.get('next') ?? '/dashboard';
-
- if (code) {
- const supabase = await createClient();
- const { error } = await supabase.auth.exchangeCodeForSession(code);
-
- if (!error) {
- const forwardedHost = request.headers.get('x-forwarded-host');
- const isLocalEnv = process.env.NODE_ENV === 'development';
-
- if (isLocalEnv) {
- return NextResponse.redirect(`${origin}${next}`);
- } else if (forwardedHost) {
- return NextResponse.redirect(`https://${forwardedHost}${next}`);
- } else {
- return NextResponse.redirect(`${origin}${next}`);
- }
- }
- }
-
- return NextResponse.redirect(`${origin}/sign-in?error=auth_callback_failed`);
-}
+/**
+ * GET /auth/callback, as served: next-intl's middleware rewrites `/auth/*` to
+ * `/[locale]/auth/*`, so this file answers the URL the OAuth providers come
+ * back to. It runs the root route's code, so the two can't drift apart
+ * (#1203): only a page on this site, and the OAuth buttons' `next` cookie.
+ */
+export { GET } from '@/app/auth/callback/route';
diff --git a/web/src/app/[locale]/(marketing)/auth/confirm/route.ts b/web/src/app/[locale]/(marketing)/auth/confirm/route.ts
index c336feccd..765334fe1 100644
--- a/web/src/app/[locale]/(marketing)/auth/confirm/route.ts
+++ b/web/src/app/[locale]/(marketing)/auth/confirm/route.ts
@@ -1,46 +1,7 @@
-import { NextResponse } from 'next/server';
-import { createClient } from '@/lib/supabase/server';
-import type { EmailOtpType } from '@supabase/supabase-js';
-
/**
- * GET /auth/confirm — locale-prefixed mirror of the root route.
- *
- * next-intl middleware rewrites every `/auth/*` request to `/[locale]/auth/*`,
- * so a root-only file at `/auth/confirm/route.ts` is never actually matched.
- * This file is what serves the URL the user clicks in their invite mail
- * (we keep the root sibling around to match the existing /auth/callback
- * convention, even though the locale version is what handles requests).
- *
- * Server-side OTP verification using the Supabase recommended SSR pattern:
- * read `token_hash` + `type` from the URL, call `verifyOtp` to set the
- * cookie session, then 302 to `redirect_to` or `next` (or `/dashboard`).
+ * GET /auth/confirm, as served: next-intl's middleware rewrites `/auth/*` to
+ * `/[locale]/auth/*`, so this file answers the links in invite and password
+ * reset e-mails. It runs the root route's code, so the two can't drift apart
+ * (#1203): only a page on this site.
*/
-export async function GET(request: Request) {
- const { searchParams, origin } = new URL(request.url);
- const tokenHash = searchParams.get('token_hash');
- const type = searchParams.get('type') as EmailOtpType | null;
- const rawRedirect = searchParams.get('redirect_to') ?? searchParams.get('next');
- const redirectTarget = resolveRedirect(rawRedirect, origin);
-
- if (!tokenHash || !type) {
- return NextResponse.redirect(`${origin}/sign-in?error=auth_confirm_missing_params`);
- }
-
- const supabase = await createClient();
- const { error } = await supabase.auth.verifyOtp({ type, token_hash: tokenHash });
-
- if (error) {
- return NextResponse.redirect(
- `${origin}/sign-in?error=auth_confirm_failed&reason=${encodeURIComponent(error.message)}`,
- );
- }
-
- return NextResponse.redirect(redirectTarget);
-}
-
-function resolveRedirect(value: string | null, origin: string): string {
- if (!value) return `${origin}/dashboard`;
- if (/^https?:\/\//i.test(value)) return value;
- if (value.startsWith('/')) return `${origin}${value}`;
- return `${origin}/dashboard`;
-}
+export { GET } from '@/app/auth/confirm/route';
diff --git a/web/src/app/[locale]/(marketing)/auth/routes.test.ts b/web/src/app/[locale]/(marketing)/auth/routes.test.ts
new file mode 100644
index 000000000..7c75d17f5
--- /dev/null
+++ b/web/src/app/[locale]/(marketing)/auth/routes.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it, vi } from 'vitest';
+
+/**
+ * next-intl rewrites `/auth/*` to `/[locale]/auth/*`, so these files answer
+ * the auth URLs. They must run the root routes' code, not a copy (#1203).
+ */
+
+vi.mock('@/lib/supabase/server', () => ({ createClient: vi.fn() }));
+
+describe('locale auth routes', () => {
+ it('serve the root callback and confirm handlers', async () => {
+ const [localeCallback, rootCallback, localeConfirm, rootConfirm] = await Promise.all([
+ import('./callback/route'),
+ import('@/app/auth/callback/route'),
+ import('./confirm/route'),
+ import('@/app/auth/confirm/route'),
+ ]);
+ expect(localeCallback.GET).toBe(rootCallback.GET);
+ expect(localeConfirm.GET).toBe(rootConfirm.GET);
+ });
+});
diff --git a/web/src/app/auth/confirm/route.test.ts b/web/src/app/auth/confirm/route.test.ts
new file mode 100644
index 000000000..26ceb9aab
--- /dev/null
+++ b/web/src/app/auth/confirm/route.test.ts
@@ -0,0 +1,75 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * /auth/confirm, where invite and password reset e-mails land: the OTP is
+ * verified, then on to the page the link names, and only to one of ours
+ * (#1203).
+ */
+
+const verifyOtp = vi.fn();
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: async () => ({ auth: { verifyOtp } }),
+}));
+
+const { GET } = await import('./route');
+
+const confirm = (query: string) =>
+ GET(new Request(`https://app.example.com/auth/confirm?token_hash=h1&type=invite&${query}`));
+
+beforeEach(() => verifyOtp.mockReset().mockResolvedValue({ error: null }));
+afterEach(() => vi.unstubAllEnvs());
+
+describe('GET /auth/confirm', () => {
+ it('goes on to the invite and password reset pages', async () => {
+ let res = await confirm(`next=${encodeURIComponent('/invite/t1')}`);
+ expect(res.headers.get('location')).toBe('https://app.example.com/invite/t1');
+
+ res = await confirm('next=/reset-password');
+ expect(res.headers.get('location')).toBe('https://app.example.com/reset-password');
+
+ // Supabase expands {{ .RedirectTo }}, which the resend builds from NEXT_PUBLIC_APP_URL.
+ vi.stubEnv('NEXT_PUBLIC_APP_URL', 'https://app.example.com');
+ res = await confirm(`redirect_to=${encodeURIComponent('https://app.example.com/invite/t1')}`);
+ expect(res.headers.get('location')).toBe('https://app.example.com/invite/t1');
+ expect(verifyOtp).toHaveBeenCalledWith({ type: 'invite', token_hash: 'h1' });
+ });
+
+ it('keeps a page on this site with its query and hash', async () => {
+ const res = await confirm(
+ `next=${encodeURIComponent('/dashboard/settings?tab=notifications#team')}`,
+ );
+ expect(res.headers.get('location')).toBe(
+ 'https://app.example.com/dashboard/settings?tab=notifications#team',
+ );
+ });
+
+ it('never leaves the site', async () => {
+ for (const target of [
+ '//evil.example',
+ '/\\evil.example',
+ '@evil.example',
+ 'https://evil.example/invite/t1',
+ 'javascript:alert(1)',
+ ]) {
+ for (const param of ['redirect_to', 'next']) {
+ const res = await confirm(`${param}=${encodeURIComponent(target)}`);
+ expect(res.headers.get('location'), `${param}=${target}`).toBe(
+ 'https://app.example.com/dashboard',
+ );
+ }
+ }
+ });
+
+ it('sends a failed or incomplete link back to the sign-in page', async () => {
+ let res = await GET(new Request('https://app.example.com/auth/confirm?next=/reset-password'));
+ expect(res.headers.get('location')).toBe(
+ 'https://app.example.com/sign-in?error=auth_confirm_missing_params',
+ );
+
+ verifyOtp.mockResolvedValue({ error: { message: 'expired' } });
+ res = await confirm('next=/reset-password');
+ expect(res.headers.get('location')).toBe(
+ 'https://app.example.com/sign-in?error=auth_confirm_failed&reason=expired',
+ );
+ });
+});
diff --git a/web/src/app/auth/confirm/route.ts b/web/src/app/auth/confirm/route.ts
index 981fde40f..7a49558c4 100644
--- a/web/src/app/auth/confirm/route.ts
+++ b/web/src/app/auth/confirm/route.ts
@@ -1,6 +1,7 @@
import { NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import type { EmailOtpType } from '@supabase/supabase-js';
+import { safeRedirectUrl } from '@/lib/auth-next';
/**
* GET /auth/confirm — server-side OTP verification for email-driven auth flows.
@@ -27,8 +28,12 @@ export async function GET(request: Request) {
const { searchParams, origin } = new URL(request.url);
const tokenHash = searchParams.get('token_hash');
const type = searchParams.get('type') as EmailOtpType | null;
- const rawRedirect = searchParams.get('redirect_to') ?? searchParams.get('next');
- const redirectTarget = resolveRedirect(rawRedirect, origin);
+ // Only to a page on this site (#1203): a crafted link can't send someone
+ // who just confirmed an e-mail to another site.
+ const redirectTarget = safeRedirectUrl(
+ searchParams.get('redirect_to') ?? searchParams.get('next'),
+ origin,
+ );
if (!tokenHash || !type) {
return NextResponse.redirect(`${origin}/sign-in?error=auth_confirm_missing_params`);
@@ -45,15 +50,3 @@ export async function GET(request: Request) {
return NextResponse.redirect(redirectTarget);
}
-
-/**
- * Accept either a full URL (already absolute, e.g. when Supabase expands
- * `{{ .RedirectTo }}` we pass during inviteUserByEmail) or a path; default
- * to /dashboard if neither was provided.
- */
-function resolveRedirect(value: string | null, origin: string): string {
- if (!value) return `${origin}/dashboard`;
- if (/^https?:\/\//i.test(value)) return value;
- if (value.startsWith('/')) return `${origin}${value}`;
- return `${origin}/dashboard`;
-}
diff --git a/web/src/lib/auth-next.test.ts b/web/src/lib/auth-next.test.ts
index da93461a7..379eccc0b 100644
--- a/web/src/lib/auth-next.test.ts
+++ b/web/src/lib/auth-next.test.ts
@@ -1,5 +1,11 @@
-import { describe, expect, it } from 'vitest';
-import { DEFAULT_NEXT, nextFromCookie, nextFromRequest, safeNextPath } from './auth-next';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import {
+ DEFAULT_NEXT,
+ nextFromCookie,
+ nextFromRequest,
+ safeNextPath,
+ safeRedirectUrl,
+} from './auth-next';
/** After signing in, back to the page asked for — and only to one of ours. */
@@ -34,6 +40,55 @@ describe('safeNextPath', () => {
});
});
+describe('safeRedirectUrl', () => {
+ const origin = 'https://app.example.com';
+ afterEach(() => vi.unstubAllEnvs());
+
+ it('keeps a path on this site, with its query and hash', () => {
+ expect(safeRedirectUrl('/reset-password', origin)).toBe(
+ 'https://app.example.com/reset-password',
+ );
+ expect(safeRedirectUrl('/dashboard/settings?tab=notifications#team', origin)).toBe(
+ 'https://app.example.com/dashboard/settings?tab=notifications#team',
+ );
+ });
+
+ it("keeps a whole URL only on the request's or the app's own origin", () => {
+ vi.stubEnv('NEXT_PUBLIC_APP_URL', 'https://www.app.example.com/');
+ expect(safeRedirectUrl('https://app.example.com/invite/t1', origin)).toBe(
+ 'https://app.example.com/invite/t1',
+ );
+ expect(safeRedirectUrl('https://www.app.example.com/invite/t1?x=1', origin)).toBe(
+ 'https://www.app.example.com/invite/t1?x=1',
+ );
+ expect(safeRedirectUrl('https://[email protected]/invite/t1', origin)).toBe(
+ 'https://app.example.com/invite/t1',
+ );
+ });
+
+ it('sends anything else to the dashboard', () => {
+ for (const value of [
+ null,
+ '',
+ 'dashboard',
+ '//evil.example',
+ '/\\evil.example',
+ '@evil.example',
+ 'javascript:alert(1)',
+ 'https://evil.example/invite/t1',
+ 'https://app.example.com.evil.example/',
+ 'https://[email protected]/',
+ 'http://app.example.com/dashboard',
+ 'https://app.example.com:8443/dashboard',
+ 'https://%zz',
+ ]) {
+ expect(safeRedirectUrl(value, origin), String(value)).toBe(
+ `https://app.example.com${DEFAULT_NEXT}`,
+ );
+ }
+ });
+});
+
describe('nextFromRequest', () => {
it('names the page without its locale prefix, query included', () => {
expect(nextFromRequest('/dashboard/traffic', '?tab=pages')).toBe(
diff --git a/web/src/lib/auth-next.ts b/web/src/lib/auth-next.ts
index 5b3804b91..218abcc3e 100644
--- a/web/src/lib/auth-next.ts
+++ b/web/src/lib/auth-next.ts
@@ -30,6 +30,39 @@ export function safeNextPath(value: string | null | undefined): string {
}
}
+/**
+ * The absolute URL to send a visitor to after an e-mail link (`/auth/confirm`).
+ * `redirect_to` can be a whole URL, since Supabase expands `{{ .RedirectTo }}`
+ * and we build that from NEXT_PUBLIC_APP_URL. Such a URL is kept only when its
+ * origin is the request's or the app's own. A path goes through safeNextPath.
+ * Anything else is the dashboard.
+ */
+export function safeRedirectUrl(value: string | null | undefined, origin: string): string {
+ if (value && /^https?:\/\//i.test(value)) {
+ try {
+ const url = new URL(value);
+ if (ownOrigins(origin).has(url.origin)) {
+ return `${url.origin}${safeNextPath(`${url.pathname}${url.search}${url.hash}`)}`;
+ }
+ } catch {
+ // Not a URL: falls through to the dashboard.
+ }
+ return `${origin}${DEFAULT_NEXT}`;
+ }
+ return `${origin}${safeNextPath(value)}`;
+}
+
+function ownOrigins(origin: string): Set<string> {
+ const origins = new Set([origin]);
+ try {
+ if (process.env.NEXT_PUBLIC_APP_URL)
+ origins.add(new URL(process.env.NEXT_PUBLIC_APP_URL).origin);
+ } catch {
+ // A malformed NEXT_PUBLIC_APP_URL adds nothing.
+ }
+ return origins;
+}
+
/** `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;