import { BASE_PATH, appUrl } from "@/lib/base-path"; import { SignJWT, jwtVerify } from "jose"; import type { AuthProvider } from "@prisma/client"; import { prisma } from "@/lib/db"; import { audit } from "@/lib/audit"; import { GRAPH_API_VERSION, graphGet } from "@/lib/facebook/client"; // "Sign in with Google / Facebook" for accounts that already exist. There is // no self-signup: a SUPERADMIN creates the User, and the first social login // whose verified email matches User.email links that provider identity // (UserIdentity). Later logins match on the provider's stable user id. // // Facebook login reuses META_APP_ID but asks only for email + public_profile; // it is separate from the page-connection flow in lib/facebook/oauth.ts. export const SOCIAL_PROVIDERS = ["google", "facebook"] as const; export type SocialProvider = (typeof SOCIAL_PROVIDERS)[number]; export const SOCIAL_STATE_COOKIE = "pm_social_oauth"; export const SOCIAL_STATE_PATH = `${BASE_PATH}/api/auth/oauth`; export const SOCIAL_STATE_TTL_SECONDS = 10 * 60; const DB_PROVIDER: Record = { google: "GOOGLE", facebook: "FACEBOOK" }; /** Codes travel to /login?error=…; the login page maps them to fixed Thai text. */ export type SocialErrorCode = | "expired" | "cancelled" | "not_configured" | "no_email" | "no_account" | "inactive" | "linked_other" | "failed"; export class SocialLoginError extends Error { constructor( public readonly code: SocialErrorCode, public readonly email?: string ) { super(code); this.name = "SocialLoginError"; } } export interface SocialProfile { providerUserId: string; email: string | null; emailVerified: boolean; name: string; } function credentials(provider: SocialProvider): { id: string; secret: string } | null { // Facebook Login for Business (the only Login product available to a Business-type // app, which this project needs for Page/Messenger/Instagram) has no email/public_profile // permission to request — only business asset permissions (pages_show_list, etc). // There is no config_id that grants identity data, so this button stays disabled. if (provider === "facebook") return null; const id = process.env.GOOGLE_CLIENT_ID; const secret = process.env.GOOGLE_CLIENT_SECRET; return id && secret ? { id, secret } : null; } export function parseProvider(raw: string): SocialProvider | null { return (SOCIAL_PROVIDERS as readonly string[]).includes(raw) ? (raw as SocialProvider) : null; } export function enabledProviders(): SocialProvider[] { return SOCIAL_PROVIDERS.filter((p) => credentials(p) !== null); } /** Same-origin path only — rejects "//host" and "/\host", which browsers treat as another origin. */ export function safeRedirectPath(raw: string | null | undefined): string { if (!raw || !raw.startsWith("/") || raw.startsWith("//") || raw.startsWith("/\\")) return "/"; return raw; } function redirectUri(provider: SocialProvider, origin: string): string { return `${appUrl(origin)}/api/auth/oauth/${provider}/callback`; } // ---------- state ---------- function stateSecret() { const s = process.env.SESSION_SECRET; if (!s) throw new Error("SESSION_SECRET env var is not set"); return new TextEncoder().encode(s); } interface SocialState { from: string; remember: boolean; } /** * CSRF state carried in a signed SameSite=Lax cookie (the Strict session * cookie is not sent on the cross-site redirect back from the provider). */ export async function createSocialState(provider: SocialProvider, state: SocialState): Promise<{ nonce: string; cookie: string }> { const nonce = crypto.randomUUID(); const cookie = await new SignJWT({ nonce, provider, from: state.from, remember: state.remember }) .setProtectedHeader({ alg: "HS256" }) .setIssuedAt() .setExpirationTime(`${SOCIAL_STATE_TTL_SECONDS}s`) .sign(stateSecret()); return { nonce, cookie }; } export async function verifySocialState(cookie: string | undefined, nonce: string | null, provider: SocialProvider): Promise { if (!cookie || !nonce) return null; try { const { payload } = await jwtVerify(cookie, stateSecret()); if (payload.nonce !== nonce || payload.provider !== provider) return null; return { from: safeRedirectPath(typeof payload.from === "string" ? payload.from : null), remember: payload.remember !== false }; } catch { return null; } } // ---------- provider protocol ---------- export function authorizeUrl(provider: SocialProvider, origin: string, nonce: string): string { const creds = credentials(provider); if (!creds) throw new SocialLoginError("not_configured"); const url = provider === "google" ? new URL("https://accounts.google.com/o/oauth2/v2/auth") : new URL(`https://www.facebook.com/${GRAPH_API_VERSION}/dialog/oauth`); url.searchParams.set("client_id", creds.id); url.searchParams.set("redirect_uri", redirectUri(provider, origin)); url.searchParams.set("response_type", "code"); url.searchParams.set("state", nonce); if (provider === "google") { url.searchParams.set("scope", "openid email profile"); url.searchParams.set("prompt", "select_account"); } else { url.searchParams.set("scope", "email,public_profile"); } return url.toString(); } async function readJsonOrFail(res: Response, context: string) { const body = await res.json().catch(() => ({})); if (!res.ok || body.error) { // Provider error objects carry codes/descriptions only, never tokens. console.error(`[auth:social] ${context} failed`, res.status, body.error ?? ""); throw new SocialLoginError("failed"); } return body; } async function googleProfile(origin: string, code: string): Promise { const creds = credentials("google")!; const tokenRes = await fetch("https://oauth2.googleapis.com/token", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ code, client_id: creds.id, client_secret: creds.secret, redirect_uri: redirectUri("google", origin), grant_type: "authorization_code", }), cache: "no-store", }); const token = await readJsonOrFail(tokenRes, "google token exchange"); const infoRes = await fetch("https://openidconnect.googleapis.com/v1/userinfo", { headers: { Authorization: `Bearer ${token.access_token}` }, cache: "no-store", }); const info = await readJsonOrFail(infoRes, "google userinfo"); if (typeof info.sub !== "string") throw new SocialLoginError("failed"); return { providerUserId: info.sub, email: typeof info.email === "string" ? info.email : null, emailVerified: info.email_verified === true, name: typeof info.name === "string" ? info.name : "", }; } async function facebookProfile(origin: string, code: string): Promise { const creds = credentials("facebook")!; const url = new URL(`https://graph.facebook.com/${GRAPH_API_VERSION}/oauth/access_token`); url.searchParams.set("client_id", creds.id); url.searchParams.set("client_secret", creds.secret); url.searchParams.set("redirect_uri", redirectUri("facebook", origin)); url.searchParams.set("code", code); const token = await readJsonOrFail(await fetch(url, { cache: "no-store" }), "facebook token exchange"); let me; try { me = await graphGet("/me", token.access_token, { fields: "id,name,email" }); } catch (e) { console.error("[auth:social] facebook /me failed", e instanceof Error ? e.message : e); throw new SocialLoginError("failed"); } return { providerUserId: String(me.id), email: typeof me.email === "string" ? me.email : null, // Graph only returns `email` when the person has a confirmed address // (the field is omitted otherwise); there is no separate verified flag. emailVerified: typeof me.email === "string", name: typeof me.name === "string" ? me.name : "", }; } /** Exchanges the authorization code and returns who signed in. The provider token is not kept. */ export function fetchSocialProfile(provider: SocialProvider, origin: string, code: string): Promise { if (!credentials(provider)) throw new SocialLoginError("not_configured"); return provider === "google" ? googleProfile(origin, code) : facebookProfile(origin, code); } // ---------- account resolution ---------- const USER_SELECT = { id: true, email: true, name: true, globalRole: true, isActive: true } as const; /** Linked identity → that user; otherwise link by verified email to an existing user. */ export async function resolveSocialUser(provider: SocialProvider, profile: SocialProfile) { const dbProvider = DB_PROVIDER[provider]; const linked = await prisma.userIdentity.findUnique({ where: { provider_providerUserId: { provider: dbProvider, providerUserId: profile.providerUserId } }, select: { user: { select: USER_SELECT } }, }); if (linked) { if (!linked.user.isActive) throw new SocialLoginError("inactive"); return linked.user; } if (!profile.email || !profile.emailVerified) throw new SocialLoginError("no_email"); const email = profile.email.trim().toLowerCase(); const user = await prisma.user.findUnique({ where: { email }, select: { ...USER_SELECT, identities: { where: { provider: dbProvider }, select: { id: true } } }, }); if (!user) throw new SocialLoginError("no_account", email); if (!user.isActive) throw new SocialLoginError("inactive"); // Already linked to a different account of this provider (e.g. the email // was later added to a second Google account) — don't silently re-link. if (user.identities.length > 0) throw new SocialLoginError("linked_other"); await prisma.$transaction(async (tx) => { await tx.userIdentity.create({ data: { userId: user.id, provider: dbProvider, providerUserId: profile.providerUserId, email }, }); await audit( { action: "USER_IDENTITY_LINKED", actorId: user.id, actorLabel: user.name || user.email, detail: { provider: dbProvider, email }, }, tx ); }); return { id: user.id, email: user.email, name: user.name, globalRole: user.globalRole, isActive: user.isActive }; }