Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ DATABASE_URL="postgresql://postgres:postgres@127.0.0.1:54322/postgres?pgbouncer=
# Used by Prisma for migrations
DIRECT_URL="postgresql://postgres:postgres@127.0.0.1:54322/postgres"

# App origin for default OTP magic-link redirect (emailRedirectTo = SITE_URL + /auth/callback)
NEXT_PUBLIC_SITE_URL="http://localhost:3000"

# Supabase project URL
NEXT_PUBLIC_SUPABASE_URL="http://127.0.0.1:54321"

Expand Down
22 changes: 17 additions & 5 deletions src/app/auth/callback/route.ts
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}`);
}
35 changes: 35 additions & 0 deletions src/lib/supabase/admin.ts
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(), {
Comment thread
loganravin4 marked this conversation as resolved.
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);
}
7 changes: 7 additions & 0 deletions src/lib/supabase/auth-constants.ts
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;
18 changes: 18 additions & 0 deletions src/lib/supabase/auth-errors.ts
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";
}
28 changes: 28 additions & 0 deletions src/lib/supabase/env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HIGH — missing server-only guard

Every other module in src/lib/supabase/ (admin.ts, otp.ts, server.ts) starts with import "server-only";. This file doesn't, even though it exports getSupabaseServiceRoleKey().

Verified with a real build: importing the barrel (./index) from a "use client" component fails closed (Turbopack errors on the transitive server-only import). But importing @/lib/supabase/env directly from a client component builds successfully, and the service-role key gets rendered into SSR HTML output (confirmed with a canary value in .next/server/app/*.html). Not exploited today since nothing does this yet, but it's a one-line mistake away from a full identity-service compromise.

Fix: add import "server-only"; to this file, or move getSupabaseServiceRoleKey into a separately-guarded module and drop it from the shared barrel.

* 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;
}
19 changes: 19 additions & 0 deletions src/lib/supabase/index.ts
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";
35 changes: 35 additions & 0 deletions src/lib/supabase/middleware.ts
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(), {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HIGH — same missing cookieOptions as server.ts

Same issue as server.ts: no cookieOptions passed to createServerClient(), so session cookies default to httpOnly: false with no secure. Fix both call sites together.

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;
}
19 changes: 19 additions & 0 deletions src/lib/supabase/next-redirect.ts
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("//")) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MEDIUM — doesn't actually block open redirects, despite the docstring

trimmed.includes("://") || trimmed.startsWith("//") misses backslash-based authority injection. Under WHATWG URL parsing, a backslash behaves like a forward slash for special schemes, so a value like /\evil.com (or \evil.com, which this function rewrites to /\evil.com) resolves with host = evil.com when passed to redirect()/NextResponse.redirect() without an origin prefix.

Not exploitable today — auth/callback/route.ts always prefixes ${origin} before this path, which pins the authority. But this function is exported from the shared barrel specifically for reuse by the other 5 project adapters, and its docstring promises same-origin-only redirects — the first adapter author who calls redirect(getSafeNextPath(x)) without an origin prefix gets a working open redirect on the login flow.

Fix: reject backslashes and control characters before the existing checks, or validate positively via new URL(trimmed, "https://placeholder.invalid") and require the resolved origin to match the placeholder.

return fallback;
}
return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
}
53 changes: 53 additions & 0 deletions src/lib/supabase/otp.ts
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,
Comment thread
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",
});
}
30 changes: 30 additions & 0 deletions src/lib/supabase/server.ts
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(), {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HIGH — session cookies missing httpOnly/secure

createServerClient() is called with only { cookies: {...} } — no cookieOptions. @supabase/ssr's DEFAULT_COOKIE_OPTIONS is { httpOnly: false, sameSite: "lax" } with no secure, so the sb-<ref>-auth-token cookies (access + refresh token) are written readable by JS and over plaintext HTTP, with a 400-day lifetime.

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 cookieOptions: { httpOnly: true, secure: process.env.NODE_ENV === "production", sameSite: "lax", path: "/" }.

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.
}
},
},
});
}
15 changes: 15 additions & 0 deletions src/middleware.ts
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)$).*)",
],
};
Loading