-
Notifications
You must be signed in to change notification settings - Fork 0
AUTH-11 Implement Supabase SSR clients, OTP helpers, and auth callback #3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
7b6b499
0055bc6
6f22971
17e3f84
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,19 +1,31 @@ | ||
| import { NextRequest, NextResponse } from "next/server"; | ||
| import { authErrorToQueryCode } from "@/lib/supabase/auth-errors"; | ||
| import { getSafeNextPath } from "@/lib/supabase/next-redirect"; | ||
| import { createServerSupabaseClient } from "@/lib/supabase/server"; | ||
|
|
||
| /** | ||
| * Auth callback route for Supabase OTP/magic link verification. | ||
| * Supabase redirects here with a `code` param after the user | ||
| * clicks the magic link or enters an OTP | ||
| * Auth callback for Supabase email (PKCE). Supabase redirects here with `code` | ||
| * after the user follows the magic link. | ||
| * | ||
| * Optional query `next`: path-only post-login destination, set when building | ||
| * `emailRedirectTo` (e.g. `${origin}/auth/callback?next=/dashboard`). | ||
| */ | ||
| export async function GET(request: NextRequest) { | ||
| const { searchParams, origin } = new URL(request.url); | ||
| const code = searchParams.get("code"); | ||
| const nextPath = getSafeNextPath(searchParams.get("next")); | ||
|
|
||
| if (!code) { | ||
| return NextResponse.redirect(`${origin}?error=missing_code`); | ||
| } | ||
|
|
||
| // TODO: Exchange code for a session via supabase | ||
| const supabase = await createServerSupabaseClient(); | ||
| const { error } = await supabase.auth.exchangeCodeForSession(code); | ||
|
|
||
| return NextResponse.redirect(origin); | ||
| if (error) { | ||
| const codeParam = authErrorToQueryCode(error); | ||
| return NextResponse.redirect(`${origin}?error=${codeParam}`); | ||
| } | ||
|
|
||
| return NextResponse.redirect(`${origin}${nextPath}`); | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| import "server-only"; | ||
| import { createClient, type SupabaseClient } from "@supabase/supabase-js"; | ||
| import { getSupabaseServiceRoleKey, getSupabaseUrl } from "./env"; | ||
|
|
||
| const globalForAdmin = globalThis as unknown as { | ||
| supabaseAdmin?: SupabaseClient; | ||
| }; | ||
|
|
||
| function createAdminClient(): SupabaseClient { | ||
| return createClient(getSupabaseUrl(), getSupabaseServiceRoleKey(), { | ||
| auth: { | ||
| autoRefreshToken: false, | ||
| persistSession: false, | ||
| }, | ||
| }); | ||
| } | ||
|
|
||
| /** | ||
| * Service-role client for trusted server-only operations (admin API). | ||
| * Reuses one instance per runtime (same pattern as Prisma in dev / long-lived Node). | ||
| * Never import this module from client components or public routes without authorization. | ||
| */ | ||
| export function createAdminSupabaseClient(): SupabaseClient { | ||
| if (!globalForAdmin.supabaseAdmin) { | ||
| globalForAdmin.supabaseAdmin = createAdminClient(); | ||
| } | ||
| return globalForAdmin.supabaseAdmin; | ||
| } | ||
|
|
||
| /** | ||
| * Loads a single user from `auth.users` by id (admin privilege). | ||
| */ | ||
| export function getAuthUser(supabaseUserId: string) { | ||
| return createAdminSupabaseClient().auth.admin.getUserById(supabaseUserId); | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| /** | ||
| * Defaults for org-wide OTP / magic-link behavior. Override per call via sendOtp options when needed. | ||
| */ | ||
| export const AUTH_CALLBACK_PATH = "/auth/callback"; | ||
|
|
||
| /** Supabase default is true; we set explicitly so behavior stays obvious in code review. */ | ||
| export const DEFAULT_OTP_SHOULD_CREATE_USER = true; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| import type { AuthError } from "@supabase/supabase-js"; | ||
|
|
||
| /** | ||
| * Maps Supabase Auth errors to stable query-param codes for the UI layer. | ||
| * Never expose raw provider messages in redirects. | ||
| */ | ||
| export function authErrorToQueryCode(error: AuthError): string { | ||
| const status = error.status; | ||
| const msg = error.message.toLowerCase(); | ||
|
|
||
| if (status === 400 || msg.includes("expired") || msg.includes("invalid")) { | ||
| return "session_invalid"; | ||
| } | ||
| if (msg.includes("rate limit") || status === 429) { | ||
| return "rate_limited"; | ||
| } | ||
| return "auth_failed"; | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| /** | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. HIGH — missing Every other module in Verified with a real build: importing the barrel ( Fix: add |
||
| * URL and anon key use NEXT_PUBLIC_* so Edge middleware and the browser share one name. | ||
| */ | ||
| export function getSupabaseUrl(): string { | ||
| const url = process.env.NEXT_PUBLIC_SUPABASE_URL; | ||
| if (!url) { | ||
| throw new Error("Missing NEXT_PUBLIC_SUPABASE_URL environment variable"); | ||
| } | ||
| return url; | ||
| } | ||
|
|
||
| export function getSupabaseAnonKey(): string { | ||
| const key = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY; | ||
| if (!key) { | ||
| throw new Error( | ||
| "Missing NEXT_PUBLIC_SUPABASE_ANON_KEY environment variable", | ||
| ); | ||
| } | ||
| return key; | ||
| } | ||
|
|
||
| export function getSupabaseServiceRoleKey(): string { | ||
| const key = process.env.SUPABASE_SERVICE_ROLE_KEY; | ||
| if (!key) { | ||
| throw new Error("Missing SUPABASE_SERVICE_ROLE_KEY environment variable"); | ||
| } | ||
| return key; | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| /** | ||
| * Server-oriented exports; individual modules use `server-only` where needed. | ||
| * Root middleware imports `updateSession` from here — do not add `import "server-only"` to this file. | ||
| */ | ||
| export { createAdminSupabaseClient, getAuthUser } from "./admin"; | ||
| export { | ||
| AUTH_CALLBACK_PATH, | ||
| DEFAULT_OTP_SHOULD_CREATE_USER, | ||
| } from "./auth-constants"; | ||
| export { authErrorToQueryCode } from "./auth-errors"; | ||
| export { | ||
| getSupabaseAnonKey, | ||
| getSupabaseServiceRoleKey, | ||
| getSupabaseUrl, | ||
| } from "./env"; | ||
| export { getSafeNextPath } from "./next-redirect"; | ||
| export { sendOtp, verifyOtp, type SendOtpOptions } from "./otp"; | ||
| export { createServerSupabaseClient } from "./server"; | ||
| export { updateSession } from "./middleware"; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| import { createServerClient } from "@supabase/ssr"; | ||
| import { type NextRequest, NextResponse } from "next/server"; | ||
| import { getSupabaseAnonKey, getSupabaseUrl } from "./env"; | ||
|
|
||
| /** | ||
| * Refreshes the Auth session and forwards updated cookies on the response. | ||
| * Call this from the root `middleware.ts` matcher so sessions stay valid. | ||
| */ | ||
| export async function updateSession(request: NextRequest) { | ||
| let supabaseResponse = NextResponse.next({ | ||
| request, | ||
| }); | ||
|
|
||
| const supabase = createServerClient(getSupabaseUrl(), getSupabaseAnonKey(), { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. HIGH — same missing Same issue as |
||
| cookies: { | ||
| getAll: () => request.cookies.getAll(), | ||
| setAll(cookiesToSet) { | ||
| cookiesToSet.forEach(({ name, value }) => | ||
| request.cookies.set(name, value), | ||
| ); | ||
| supabaseResponse = NextResponse.next({ | ||
| request, | ||
| }); | ||
| cookiesToSet.forEach(({ name, value, options }) => | ||
| supabaseResponse.cookies.set(name, value, options), | ||
| ); | ||
| }, | ||
| }, | ||
| }); | ||
|
|
||
| // Do not run logic between createServerClient and getUser() | ||
| await supabase.auth.getUser(); | ||
|
|
||
| return supabaseResponse; | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| /** | ||
| * `next` is supplied by our app when building magic-link URLs, e.g. | ||
| * `emailRedirectTo: `${origin}/auth/callback?next=${encodeURIComponent(returnPath)}``. | ||
| * Only same-origin path redirects are allowed (blocks open redirects). | ||
| */ | ||
| export function getSafeNextPath(raw: string | null): string { | ||
| const fallback = "/"; | ||
| if (raw == null || raw === "") { | ||
| return fallback; | ||
| } | ||
| const trimmed = raw.trim(); | ||
| if (trimmed === "") { | ||
| return fallback; | ||
| } | ||
| if (trimmed.includes("://") || trimmed.startsWith("//")) { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. MEDIUM — doesn't actually block open redirects, despite the docstring
Not exploitable today — Fix: reject backslashes and control characters before the existing checks, or validate positively via |
||
| return fallback; | ||
| } | ||
| return trimmed.startsWith("/") ? trimmed : `/${trimmed}`; | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| import "server-only"; | ||
| import type { AuthOtpResponse } from "@supabase/supabase-js"; | ||
| import { | ||
| AUTH_CALLBACK_PATH, | ||
| DEFAULT_OTP_SHOULD_CREATE_USER, | ||
| } from "./auth-constants"; | ||
| import { createServerSupabaseClient } from "./server"; | ||
|
|
||
| export type SendOtpOptions = { | ||
| /** Overrides default magic-link callback URL when set. */ | ||
| emailRedirectTo?: string; | ||
| shouldCreateUser?: boolean; | ||
| data?: Record<string, unknown>; | ||
| }; | ||
|
|
||
| function getDefaultEmailRedirectTo(): string | undefined { | ||
| const base = process.env.NEXT_PUBLIC_SITE_URL?.replace(/\/$/, ""); | ||
| if (!base) { | ||
| return undefined; | ||
| } | ||
| return `${base}${AUTH_CALLBACK_PATH}`; | ||
| } | ||
|
|
||
| /** | ||
| * Sends a one-time code / magic link via Supabase Auth (configured email provider). | ||
| */ | ||
| export async function sendOtp( | ||
| email: string, | ||
| options?: SendOtpOptions, | ||
|
loganravin4 marked this conversation as resolved.
|
||
| ): Promise<AuthOtpResponse> { | ||
| const supabase = await createServerSupabaseClient(); | ||
| return supabase.auth.signInWithOtp({ | ||
| email, | ||
| options: { | ||
| emailRedirectTo: options?.emailRedirectTo ?? getDefaultEmailRedirectTo(), | ||
| shouldCreateUser: | ||
| options?.shouldCreateUser ?? DEFAULT_OTP_SHOULD_CREATE_USER, | ||
| data: options?.data, | ||
| }, | ||
| }); | ||
| } | ||
|
|
||
| /** | ||
| * Verifies an email OTP and establishes a session (cookies via server client). | ||
| */ | ||
| export async function verifyOtp(email: string, token: string) { | ||
| const supabase = await createServerSupabaseClient(); | ||
| return supabase.auth.verifyOtp({ | ||
| email, | ||
| token, | ||
| type: "email", | ||
| }); | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| import "server-only"; | ||
| import { createServerClient } from "@supabase/ssr"; | ||
| import { cookies } from "next/headers"; | ||
| import { getSupabaseAnonKey, getSupabaseUrl } from "./env"; | ||
|
|
||
| /** | ||
| * Supabase client for Server Components, Server Actions, and Route Handlers. | ||
| * Persists session via HTTP-only cookies set by Auth responses. | ||
| */ | ||
| export async function createServerSupabaseClient() { | ||
| const cookieStore = await cookies(); | ||
|
|
||
| return createServerClient(getSupabaseUrl(), getSupabaseAnonKey(), { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. HIGH — session cookies missing
Any XSS on this origin can exfiltrate the refresh token and mint access tokens for all 6 downstream projects for over a year. The docstring above claims "HTTP-only cookies" — currently false. Fix: pass |
||
| cookies: { | ||
| getAll() { | ||
| return cookieStore.getAll(); | ||
| }, | ||
| setAll(cookiesToSet) { | ||
| try { | ||
| cookiesToSet.forEach(({ name, value, options }) => | ||
| cookieStore.set(name, value, options), | ||
| ); | ||
| } catch { | ||
| // Called from a Server Component where cookies are read-only; | ||
| // session refresh is handled by middleware. | ||
| } | ||
| }, | ||
| }, | ||
| }); | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| import { type NextRequest } from "next/server"; | ||
| import { updateSession } from "@/lib/supabase"; | ||
|
|
||
| export async function middleware(request: NextRequest) { | ||
| return updateSession(request); | ||
| } | ||
|
|
||
| export const config = { | ||
| matcher: [ | ||
| /* | ||
| * Match all request paths except static assets and image optimization files. | ||
| */ | ||
| "/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)", | ||
| ], | ||
| }; |
Uh oh!
There was an error while loading. Please reload this page.