import "server-only"; import { and, eq } from "drizzle-orm"; import { getDb } from "@/db"; import { accounts, users } from "@/db/schema"; import { HttpError } from "@/lib/security/http"; const ACCOUNT_SETTINGS_URL = "https://account.sudloh.com/account"; export { ACCOUNT_SETTINGS_URL }; type Endpoints = { issuer: string; userinfo_endpoint: string; introspection_endpoint: string }; type BoundToken = { token: string; accountId: string }; let discovery: { endpoints: Endpoints; until: number } | undefined; async function endpoints(): Promise { if (discovery && discovery.until > Date.now()) return discovery.endpoints; const issuer = (process.env.SUDLOH_OIDC_ISSUER || "https://account.sudloh.com/api/auth").replace(/\/$/, ""); const response = await fetch(`${issuer}/.well-known/openid-configuration`, { cache: "no-store", signal: AbortSignal.timeout(5000), }); if (!response.ok) throw new HttpError(503, "sudloh-unavailable"); const data: unknown = await response.json(); if (!data || typeof data !== "object" || !("issuer" in data) || data.issuer !== issuer || !("userinfo_endpoint" in data) || typeof data.userinfo_endpoint !== "string" || !("introspection_endpoint" in data) || typeof data.introspection_endpoint !== "string") { throw new HttpError(503, "sudloh-discovery-invalid"); } const result = data as Endpoints; for (const url of [result.userinfo_endpoint, result.introspection_endpoint]) { if (new URL(url).origin !== new URL(issuer).origin) throw new HttpError(503, "sudloh-discovery-invalid"); } discovery = { endpoints: result, until: Date.now() + 10 * 60_000 }; return result; } async function userInfo(account: BoundToken) { const response = await fetch((await endpoints()).userinfo_endpoint, { headers: { Authorization: `Bearer ${account.token}` }, cache: "no-store", signal: AbortSignal.timeout(5000), }); if (!response.ok) throw new HttpError(503, "sudloh-unavailable"); const data: unknown = await response.json(); if (!data || typeof data !== "object" || !("sub" in data) || data.sub !== account.accountId || !("name" in data) || typeof data.name !== "string" || !("email" in data) || typeof data.email !== "string" || !("email_verified" in data) || data.email_verified !== true || !("picture" in data) || typeof data.picture !== "string") { throw new HttpError(503, "sudloh-profile-invalid"); } return data as { sub: string; name: string; email: string; email_verified: true; picture: string }; } async function introspect(account: BoundToken): Promise { const clientId = process.env.SUDLOH_OIDC_CLIENT_ID; const clientSecret = process.env.SUDLOH_OIDC_CLIENT_SECRET; if (!clientId || !clientSecret) throw new HttpError(503, "sudloh-not-configured"); const response = await fetch((await endpoints()).introspection_endpoint, { method: "POST", headers: { Authorization: `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString("base64")}`, "Content-Type": "application/x-www-form-urlencoded", }, body: new URLSearchParams({ token: account.token, token_type_hint: "access_token" }), cache: "no-store", signal: AbortSignal.timeout(5000), }); if (!response.ok) throw new HttpError(503, "sudloh-unavailable"); const data: unknown = await response.json(); if (!data || typeof data !== "object" || !("active" in data) || typeof data.active !== "boolean") { throw new HttpError(503, "sudloh-introspection-invalid"); } if (!data.active) return false; if (!("sub" in data) || data.sub !== account.accountId || !("exp" in data) || typeof data.exp !== "number" || data.exp <= Date.now() / 1000) return false; return true; } async function updateProfile(userId: string, token: BoundToken): Promise { const profile = await userInfo(token); const [current] = await getDb().select({ name: users.name, email: users.email, emailVerified: users.emailVerified, image: users.image }).from(users).where(eq(users.id, userId)).limit(1); if (!current) return false; const email = profile.email.toLowerCase(); if (current.name !== profile.name || current.email !== email || !current.emailVerified || current.image !== profile.picture) { try { await getDb().update(users).set({ name: profile.name, email, emailVerified: true, image: profile.picture }).where(eq(users.id, userId)); } catch (cause) { const dbError = cause && typeof cause === "object" && "cause" in cause ? cause.cause : cause; if (dbError && typeof dbError === "object" && "code" in dbError && dbError.code === "23505") throw new HttpError(409, "sudloh-email-conflict"); throw cause; } } return true; } export async function refreshLinkedSudlohProfile(userId: string): Promise { const [account] = await getDb().select().from(accounts).where(and( eq(accounts.userId, userId), eq(accounts.providerId, "sudloh"), )).limit(1); if (!account?.accessToken || !account.accessTokenExpiresAt || account.accessTokenExpiresAt.getTime() <= Date.now()) throw new HttpError(401, "sudloh-sign-in-required"); const token: BoundToken = { token: account.accessToken, accountId: account.accountId }; if (!await introspect(token)) throw new HttpError(401, "sudloh-sign-in-required"); if (!await updateProfile(userId, token)) throw new HttpError(401, "unauthorized"); }