diff --git a/src/app/api/onboarding/route.ts b/src/app/api/onboarding/route.ts index 216c51e6f..070a0ae68 100644 --- a/src/app/api/onboarding/route.ts +++ b/src/app/api/onboarding/route.ts @@ -6,6 +6,8 @@ import { getRuntimeSnapshot } from "@/db/queries/runtime-snapshots"; import { getProjectStatesByUserId } from "@/db/queries/project-states"; import { isRuntimeAvailable } from "@/lib/runtime"; import { hasValidUsername, isOnboardingComplete, suggestUsername } from "@/lib/onboarding"; +import { healReturningUserOnboarding } from "@/lib/onboarding-heal"; +import { countActiveProjects } from "@/db/queries/user-projects"; async function getDaemonConnectionStatus(userId: string) { const [snapshot, states] = await Promise.all([ @@ -29,25 +31,33 @@ export async function GET() { const userId = await getSessionUserId(); if (!userId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - const user = await getUserById(userId); + let user = await getUserById(userId); if (!user) return NextResponse.json({ error: "Not found" }, { status: 404 }); - const [teamInvitee, daemon] = await Promise.all([ + user = await healReturningUserOnboarding(user); + + const [teamInvitee, daemon, projectCount] = await Promise.all([ isTeamInvitee(userId), isRuntimeAvailable() ? Promise.resolve({ connected: true, live: true, lastPushedAt: new Date().toISOString() }) : getDaemonConnectionStatus(userId), + countActiveProjects(userId), ]); + const complete = isOnboardingComplete(user); + return NextResponse.json({ - complete: isOnboardingComplete(user), + complete, username: user.username, suggestedUsername: suggestUsername(user.name, user.email), isTeamInvitee: teamInvitee, + isReturningUser: projectCount > 0, runtimeAvailable: isRuntimeAvailable(), daemonConnected: daemon.connected, daemonLive: daemon.live, daemonLastPushedAt: daemon.lastPushedAt, + /** Client should call session.update() when true so middleware JWT catches up. */ + needsSessionRefresh: complete, }); } @@ -55,9 +65,11 @@ export async function POST() { const userId = await getSessionUserId(); if (!userId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - const user = await getUserById(userId); + let user = await getUserById(userId); if (!user) return NextResponse.json({ error: "Not found" }, { status: 404 }); + user = await healReturningUserOnboarding(user); + if (!hasValidUsername(user.username)) { return NextResponse.json( { error: "Choose a username before finishing onboarding." }, diff --git a/src/app/onboarding/page.tsx b/src/app/onboarding/page.tsx index 28a98b4a6..d6fe1efb0 100644 --- a/src/app/onboarding/page.tsx +++ b/src/app/onboarding/page.tsx @@ -29,6 +29,8 @@ type OnboardingBootstrap = { complete?: boolean; suggestedUsername?: string; isTeamInvitee?: boolean; + isReturningUser?: boolean; + needsSessionRefresh?: boolean; }; function stepIndex(step: OnboardingStep): number { @@ -52,22 +54,48 @@ export default function OnboardingPage() { const [error, setError] = useState(""); useEffect(() => { - getJson("/api/onboarding") - .then((data) => { + let cancelled = false; + + async function bootstrap() { + try { + // Sync JWT from DB (fixes migrated accounts with stale cookies). + await update(); + const data = await getJson("/api/onboarding"); + if (cancelled) return; + if (data.complete) { + if (data.needsSessionRefresh) await update(); router.replace(ROUTES.APP_HOME); return; } + + if (data.isReturningUser) { + await postJson("/api/onboarding", {}); + await update(); + router.replace(ROUTES.APP_HOME); + return; + } + if (data.suggestedUsername) { setUsername((prev) => prev || data.suggestedUsername || ""); } if (data.isTeamInvitee) { setIsTeamInvitee(true); } - }) - .catch(() => { /* stay on page */ }) - .finally(() => setBootstrapping(false)); - }, [router]); + } catch (e) { + if (!cancelled) { + setError(e instanceof Error ? e.message : "Could not load onboarding"); + } + } finally { + if (!cancelled) setBootstrapping(false); + } + } + + void bootstrap(); + return () => { + cancelled = true; + }; + }, [router, update]); async function finishOnboarding() { setSaving(true); diff --git a/src/app/page.tsx b/src/app/page.tsx index daf4f1b0a..da6796354 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -19,7 +19,10 @@ export default async function LandingPage() { const session = await auth(); if (session?.user) { - redirect(session.user.onboardedAt ? ROUTES.APP_HOME : ROUTES.ONBOARDING); + const done = + session.user.onboardingComplete === true || + Boolean(session.user.onboardedAt && session.user.username); + redirect(done ? ROUTES.APP_HOME : ROUTES.ONBOARDING); } const stripeReady = isStripeReady(); diff --git a/src/auth.config.ts b/src/auth.config.ts index 042cdf403..aa8f60608 100644 --- a/src/auth.config.ts +++ b/src/auth.config.ts @@ -1,6 +1,15 @@ import type { NextAuthConfig } from "next-auth"; import { ROUTES } from "@/config/auth"; +function sessionOnboardingDone(user: { + onboardingComplete?: boolean; + onboardedAt?: Date | string | null; + username?: string | null; +}): boolean { + if (user.onboardingComplete === true) return true; + return Boolean(user.onboardedAt && user.username); +} + // Edge-safe auth config — no DB adapter, no Node.js crypto. // Used by src/middleware.ts (Edge Runtime). // Full auth with DB adapter lives in src/auth.ts. @@ -16,7 +25,9 @@ export const authConfig = { // The jwt() callback in auth.ts stores this field on every sign-in/token refresh. session({ session, token }) { if (session.user) { + session.user.username = (token.username as string | null) ?? null; session.user.onboardedAt = (token.onboardedAt as Date | null) ?? null; + session.user.onboardingComplete = token.onboardingComplete === true; } return session; }, @@ -63,8 +74,10 @@ export const authConfig = { // Redirect authenticated-but-not-onboarded users to the onboarding flow. // API routes are excluded so onboarding page API calls (/api/me, /api/user-projects) // work normally. Sign-out is excluded to avoid a redirect loop on logout. + // Gate until onboarding is complete in JWT (refreshed from DB on sign-in / session.update). + const onboardingDone = sessionOnboardingDone(auth.user); if ( - !auth.user.onboardedAt && + !onboardingDone && !pathname.startsWith(ROUTES.ONBOARDING) && !pathname.startsWith("/api/") && !pathname.startsWith(ROUTES.SIGN_OUT) diff --git a/src/auth.ts b/src/auth.ts index 756d3eaae..1161844d2 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -13,6 +13,8 @@ import { verifyPassword } from "@/lib/password"; import { getDefaultUser, getUserById, getUserByEmail, updateUser } from "@/db/queries/users"; import { getOrgMembershipCount, createPersonalOrg } from "@/db/queries/orgs"; import { logDebug } from "@/db/queries/debug-logs"; +import { healReturningUserOnboarding, onboardingCompleteFlag } from "@/lib/onboarding-heal"; +import { isValidUuid } from "@/lib/utils"; /** * Auth.js wraps every authorize()→null return in a generic CredentialsSignin @@ -64,10 +66,17 @@ declare module "next-auth" { image: string | null; username: string | null; onboardedAt: Date | null; + onboardingComplete?: boolean; }; } } +declare module "@auth/core/jwt" { + interface JWT { + onboardingComplete?: boolean; + } +} + export const { handlers, auth, signIn, signOut } = NextAuth({ adapter: DrizzleAdapter(db, { @@ -150,6 +159,11 @@ export const { handlers, auth, signIn, signOut } = NextAuth({ // queries that join on uuid columns are safe. try { if (message.user?.id) { + const existing = await getUserById(message.user.id); + if (existing) { + await healReturningUserOnboarding(existing); + } + const memberCount = await getOrgMembershipCount(message.user.id); if (memberCount === 0) { const displayName = message.user.name ?? message.user.email?.split("@")[0] ?? "user"; @@ -290,15 +304,23 @@ export const { handlers, auth, signIn, signOut } = NextAuth({ } return true; }, - async jwt({ token, user, trigger }) { + async jwt({ token, user }) { + const email = user?.email ?? (token.email as string | undefined); const userId = user?.id ?? (token.id as string | undefined); - if (userId && (user?.id || trigger === "update")) { - token.id = userId; - const dbUser = await getUserById(userId); - if (dbUser) { - token.username = dbUser.username ?? null; - token.onboardedAt = dbUser.onboardedAt ?? null; - } + + let dbUser = userId && isValidUuid(userId) ? await getUserById(userId) : null; + if (!dbUser && email) { + dbUser = await getUserByEmail(email); + } + if (dbUser) { + dbUser = await healReturningUserOnboarding(dbUser); + token.id = dbUser.id; + token.email = dbUser.email ?? email ?? null; + token.username = dbUser.username ?? null; + token.onboardedAt = dbUser.onboardedAt ?? null; + token.onboardingComplete = onboardingCompleteFlag(dbUser); + } else if (email) { + token.email = email; } return token; }, @@ -310,6 +332,7 @@ export const { handlers, auth, signIn, signOut } = NextAuth({ id: (token.id as string) ?? "", username: (token.username as string | null) ?? null, onboardedAt: (token.onboardedAt as Date | null) ?? null, + onboardingComplete: token.onboardingComplete === true, }, }; }, diff --git a/src/lib/onboarding-heal.ts b/src/lib/onboarding-heal.ts new file mode 100644 index 000000000..3f469259a --- /dev/null +++ b/src/lib/onboarding-heal.ts @@ -0,0 +1,47 @@ +import { countActiveProjects } from "@/db/queries/user-projects"; +import { getUserByUsername, updateUser } from "@/db/queries/users"; +import type { users } from "@/db/schema"; +import { + hasValidUsername, + isOnboardingComplete, + suggestUsername, +} from "@/lib/onboarding"; + +type UserRow = typeof users.$inferSelect; + +/** + * Returning / migrated users: skip onboarding when they already have app data. + * Sets username + onboarded_at when missing so JWT + middleware can unblock. + */ +export async function healReturningUserOnboarding(user: UserRow): Promise { + const projectCount = await countActiveProjects(user.id); + const isReturning = projectCount > 0 || user.onboardedAt != null; + if (!isReturning) return user; + + let username = user.username; + if (!hasValidUsername(username)) { + const suggested = suggestUsername(user.name, user.email); + if (suggested) { + const taken = await getUserByUsername(suggested); + if (!taken || taken.id === user.id) username = suggested; + } + } + + const needsUsername = !hasValidUsername(user.username) && hasValidUsername(username); + const needsOnboarded = user.onboardedAt == null; + + if (!needsUsername && !needsOnboarded) return user; + + const updated = await updateUser(user.id, { + ...(needsUsername && username ? { username } : {}), + ...(needsOnboarded ? { onboardedAt: new Date() } : {}), + }); + return updated ?? user; +} + +export function onboardingCompleteFlag(user: { + username: string | null | undefined; + onboardedAt: Date | null | undefined; +}): boolean { + return isOnboardingComplete(user); +} diff --git a/src/lib/session.ts b/src/lib/session.ts index 33fdc1b8b..2cc29ebb5 100644 --- a/src/lib/session.ts +++ b/src/lib/session.ts @@ -4,7 +4,32 @@ import { auth } from "@/auth"; import { DEFAULT_USER_NAME } from "@/lib/constants"; import { ROUTES } from "@/config/auth"; import { validateAgentToken } from "@/db/queries/agent-tokens"; +import { getUserByEmail, getUserById } from "@/db/queries/users"; import { envAlias, envAliasBool } from "@/lib/brand-env"; +import { isValidUuid } from "@/lib/utils"; + +/** + * Resolve the DB user id from a session. OAuth JWTs may briefly carry the + * provider id instead of our UUID — fall back to email lookup. + */ +export async function resolveSessionUserId(): Promise { + const session = await auth(); + if (!session?.user) return null; + + const id = session.user.id; + if (id && isValidUuid(id)) { + const byId = await getUserById(id); + if (byId) return byId.id; + } + + const email = session.user.email; + if (email) { + const byEmail = await getUserByEmail(email); + if (byEmail) return byEmail.id; + } + + return id && isValidUuid(id) ? id : null; +} /** * Returns the authenticated user's ID, or null if there is no session. @@ -12,8 +37,7 @@ import { envAlias, envAliasBool } from "@/lib/brand-env"; * Middleware already blocks browser clients without a session — this is defense-in-depth. */ export async function getSessionUserId(): Promise { - const session = await auth(); - return session?.user?.id ?? null; + return resolveSessionUserId(); } /** @@ -22,9 +46,9 @@ export async function getSessionUserId(): Promise { * Use in server components and server actions. */ export async function requirePageUserId(): Promise { - const session = await auth(); - if (!session?.user?.id) redirect(ROUTES.SIGN_IN); - return session.user.id; + const userId = await resolveSessionUserId(); + if (!userId) redirect(ROUTES.SIGN_IN); + return userId; } export async function getCurrentUserName(): Promise { @@ -44,8 +68,8 @@ let warnedDeprecatedDaemonToken = false; */ export async function getApiUserId(): Promise { // Cookie-based session (web UI). - const session = await auth(); - if (session?.user?.id) return session.user.id; + const userId = await resolveSessionUserId(); + if (userId) return userId; // Bearer token (daemon / CLI agent). const headersList = await headers(); diff --git a/src/proxy.ts b/src/proxy.ts index cdfccdaae..ac49205e5 100644 --- a/src/proxy.ts +++ b/src/proxy.ts @@ -6,7 +6,7 @@ import { authConfig } from "@/auth.config"; // // What this activates: // • Unauthenticated users → redirect to /sign-in with callbackUrl -// • Authenticated + onboardedAt null → redirect to /onboarding +// • Authenticated + onboarding incomplete → redirect to /onboarding // • Daemon bearer-token requests → pass through to individual routes // // The matcher intentionally excludes public routes so they stay accessible