feat(auth) : sync Sudloh profiles and validate sessions

This commit is contained in:
2026-10-06 00:48:29 +07:00 Unverified
parent d6153be50d
commit c856904c12
16 changed files with 520 additions and 32 deletions
+20
View File
@@ -1,6 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mocks = { session: vi.fn(), auth: vi.fn() };
const sudloh = { bind: vi.fn(), validate: vi.fn() };
vi.mock("server-only", () => ({}));
vi.mock("@/db", () => ({ getDb: () => ({}) }));
vi.mock("next/headers", () => ({ headers: async () => new Headers() }));
@@ -10,6 +11,7 @@ vi.mock("better-auth/next-js", () => ({ nextCookies: () => ({}) }));
vi.mock("better-auth/plugins", () => ({ admin: (options: unknown) => options, captcha: () => ({}),
genericOAuth: (options: unknown) => ({ id: "generic-oauth", options }),
emailOTP: (options: unknown) => ({ id: "email-otp", options }) }));
vi.mock("./sudloh", () => ({ bindSudlohSession: sudloh.bind, validateSudlohSession: sudloh.validate }));
const envNames = ["NODE_ENV", "DATABASE_URL", "BETTER_AUTH_URL", "BETTER_AUTH_SECRET", "BUZZ_DEMO_MODE", "RESEND_API_KEY", "SUDLOH_OIDC_CLIENT_ID", "SUDLOH_OIDC_CLIENT_SECRET", "SUDLOH_OIDC_REDIRECT_URI", "SUDLOH_OIDC_ISSUER", "SUDLOH_OIDC_ONLY"] as const;
const testEnv = process.env as Record<string, string | undefined>;
@@ -23,6 +25,8 @@ beforeEach(() => {
testEnv.BETTER_AUTH_SECRET = "a-test-secret-with-more-than-32-characters";
mocks.auth.mockReturnValue({ api: { getSession: mocks.session } });
mocks.session.mockResolvedValue(null);
sudloh.bind.mockReset();
sudloh.validate.mockReset().mockResolvedValue(true);
delete testEnv.SUDLOH_OIDC_CLIENT_ID;
delete testEnv.SUDLOH_OIDC_CLIENT_SECRET;
delete testEnv.SUDLOH_OIDC_REDIRECT_URI;
@@ -77,6 +81,7 @@ describe("actual administrator session boundary", () => {
expect(options.plugins.find((plugin: { id?: string }) => plugin.id === "generic-oauth").options.config[0]).toMatchObject({
providerId: "sudloh", authentication: "basic", requireIdTokenVerification: true,
requireEmailVerification: true, disableProviderLogout: true,
overrideUserInfo: true,
scopes: ["openid", "profile", "email"],
redirectURI: "https://guide.example.test/api/auth/callback/sudloh",
});
@@ -90,6 +95,21 @@ describe("actual administrator session boundary", () => {
const options = mocks.auth.mock.calls.at(-1)![0];
expect(options.emailAndPassword).toMatchObject({ enabled: false, disableSignUp: true });
expect(options.plugins.some((plugin: { id?: string }) => plugin.id === "email-otp")).toBe(false);
await options.databaseHooks.session.create.after({ id: "guide-session", userId: "user-1" },
{ path: "/callback/sudloh" });
expect(sudloh.bind).toHaveBeenCalledWith("user-1", "guide-session");
});
it("denies a revoked Sudloh session", async () => {
testEnv.SUDLOH_OIDC_CLIENT_ID = "client";
testEnv.SUDLOH_OIDC_CLIENT_SECRET = "secret";
testEnv.SUDLOH_OIDC_REDIRECT_URI = "https://guide.example.test/api/auth/callback/sudloh";
testEnv.SUDLOH_OIDC_ONLY = "true";
mocks.session.mockResolvedValue({ user: { id: "user-1", email: "[email protected]",
emailVerified: true, role: "admin" }, session: { id: "guide-session" } });
sudloh.validate.mockResolvedValue(false);
const { getAdminSession, getCustomerSession } = await import("./server");
expect(await getCustomerSession()).toBeNull();
expect(await getAdminSession()).toBeNull();
});
it("rejects incomplete or mismatched Sudloh client configuration", async () => {
const { getAuth, isSudlohOidcEnabled } = await import("./server");
+18 -3
View File
@@ -19,6 +19,7 @@ import { isAuthorizedAdmin, type SessionUserLike } from "./authorization";
import { HttpError } from "@/lib/security/http";
import { consumeRateLimit } from "@/lib/security/rate-limit";
import { sendAuthEmail } from "./email";
import { bindSudlohSession, validateSudlohSession } from "./sudloh";
function required(name: string): string {
const value = process.env[name];
@@ -63,6 +64,11 @@ function createAuth() {
},
transaction: true,
}),
...(oidcOnly ? { databaseHooks: { session: { create: { after: async (
session: { id: string; userId: string }, context: { path: string } | null,
) => {
if (context?.path.endsWith("/callback/sudloh")) await bindSudlohSession(session.userId, session.id);
} } } } } : {}),
baseURL: required("BETTER_AUTH_URL"),
trustedOrigins: process.env.BETTER_AUTH_TRUSTED_ORIGINS
?.split(",")
@@ -125,6 +131,7 @@ function createAuth() {
requireIdTokenVerification: true,
requireEmailVerification: true,
disableProviderLogout: true,
overrideUserInfo: true,
}] })] : []),
...(!oidcOnly ? [emailOTP({
sendVerificationOnSignUp: true,
@@ -159,13 +166,22 @@ export interface AdminSession {
session: { id: string };
}
export const getVerifiedSession = cache(async () => {
if (!hasAuthConfiguration()) return null;
const session = await getAuth().api.getSession({ headers: await headers() });
if (!session?.session) return null;
if (isSudlohOidcEnabled() && process.env.SUDLOH_OIDC_ONLY === "true" &&
!await validateSudlohSession(session.user.id, session.session.id)) return null;
return session;
});
export const getAdminSession = cache(async (): Promise<AdminSession | null> => {
// Public pages can be prerendered without the runtime auth secret. In that
// case the header simply omits the admin link; auth routes still fail loudly
// through getAuth() when authentication is actually used.
if (!hasAuthConfiguration()) return null;
const session = await getAuth().api.getSession({ headers: await headers() });
const session = await getVerifiedSession();
if (
!session?.session ||
!isAuthorizedAdmin(session.user)
@@ -192,8 +208,7 @@ export async function requireAdmin(): Promise<AdminSession> {
}
export const getCustomerSession = cache(async () => {
if (!hasAuthConfiguration()) return null;
const session = await getAuth().api.getSession({ headers: await headers() });
const session = await getVerifiedSession();
if (!session?.session) return null;
return { user: session.user, session: { id: session.session.id } };
});
+104
View File
@@ -0,0 +1,104 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const rows: unknown[][] = [];
const values = new Map<string, string>();
const set = vi.fn(async (key: string, value: string) => { values.set(key, value); });
const removeSession = vi.fn(async () => undefined);
const updateUser = vi.fn(async () => undefined);
const redis = { get: vi.fn(async (key: string) => values.get(key) ?? null), set };
vi.mock("server-only", () => ({}));
vi.mock("@/db", () => ({ getDb: () => ({
select: () => ({ from: () => ({ where: () => ({ limit: async () => rows.shift() ?? [] }) }) }),
update: () => ({ set: () => ({ where: updateUser }) }),
delete: () => ({ where: removeSession }),
}) }));
vi.mock("@/lib/redis/client", () => ({
getRedisClient: async () => redis, redisCachePrefix: () => "test",
}));
const { bindSudlohSession, refreshLinkedSudlohProfile, validateSudlohSession } = await import("./sudloh");
const expiresAt = new Date(Date.now() + 60 * 60_000);
const account = { id: "account-1", accountId: "sub-1", accessToken: "access-1", accessTokenExpiresAt: expiresAt };
beforeEach(() => {
rows.length = 0;
values.clear();
vi.clearAllMocks();
process.env.SUDLOH_OIDC_ISSUER = "https://account.test/api/auth";
process.env.SUDLOH_OIDC_CLIENT_ID = "client";
process.env.SUDLOH_OIDC_CLIENT_SECRET = "secret";
});
function provider(active: boolean, profileSub = "sub-1") {
const fetchMock = vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => {
const url = String(input);
if (url.endsWith("openid-configuration")) return Response.json({
issuer: "https://account.test/api/auth",
introspection_endpoint: "https://account.test/api/auth/oauth2/introspect",
userinfo_endpoint: "https://account.test/api/auth/oauth2/userinfo",
});
if (url.endsWith("introspect")) return Response.json({ active, sub: "sub-1",
exp: Math.floor(Date.now() / 1000) + 3600 });
if (url.endsWith("userinfo")) return Response.json({ sub: profileSub, name: "New Name",
email: "[email protected]", email_verified: true, picture: "https://account.test/avatar.png" });
throw new Error(`unexpected URL: ${url}`);
});
return fetchMock;
}
describe("Sudloh session validation", () => {
it("binds the callback token to its Guide session and caches a verified check", async () => {
rows.push([account]);
await bindSudlohSession("user-1", "session-1");
const fetchMock = provider(true);
rows.push([account], [{ name: "Old Name", email: "[email protected]", emailVerified: true, image: null }]);
expect(await validateSudlohSession("user-1", "session-1")).toBe(true);
expect(updateUser).toHaveBeenCalledOnce();
const fetchCount = fetchMock.mock.calls.length;
rows.push([account]);
expect(await validateSudlohSession("user-1", "session-1")).toBe(true);
expect(fetchMock).toHaveBeenCalledTimes(fetchCount);
fetchMock.mockRestore();
});
it("ends the Guide session when Sudloh reports the bound token inactive", async () => {
rows.push([account]);
await bindSudlohSession("user-1", "session-1");
const fetchMock = provider(false);
rows.push([account]);
expect(await validateSudlohSession("user-1", "session-1")).toBe(false);
expect(removeSession).toHaveBeenCalledOnce();
fetchMock.mockRestore();
});
it("fails closed when UserInfo returns another subject", async () => {
rows.push([account]);
await bindSudlohSession("user-1", "session-1");
const fetchMock = provider(true, "someone-else");
rows.push([account]);
await expect(validateSudlohSession("user-1", "session-1"))
.rejects.toMatchObject({ status: 503 });
expect(updateUser).not.toHaveBeenCalled();
fetchMock.mockRestore();
});
it("reports a verified Sudloh email that conflicts with another Guide account", async () => {
rows.push([account]);
await bindSudlohSession("user-1", "session-1");
const fetchMock = provider(true);
rows.push([account], [{ name: "Old Name", email: "[email protected]", emailVerified: true, image: null }]);
updateUser.mockRejectedValueOnce({ cause: { code: "23505" } });
await expect(validateSudlohSession("user-1", "session-1"))
.rejects.toMatchObject({ status: 409, message: "sudloh-email-conflict" });
fetchMock.mockRestore();
});
it("refreshes a linked profile during the legacy sign-in transition", async () => {
const fetchMock = provider(true);
rows.push([account], [{ name: "Old Name", email: "[email protected]", emailVerified: true, image: null }]);
await refreshLinkedSudlohProfile("user-1");
expect(updateUser).toHaveBeenCalledOnce();
fetchMock.mockRestore();
});
});
+164
View File
@@ -0,0 +1,164 @@
import "server-only";
import { createHash } from "node:crypto";
import { and, eq } from "drizzle-orm";
import { getDb } from "@/db";
import { accounts, sessions, users } from "@/db/schema";
import { getRedisClient, redisCachePrefix } from "@/lib/redis/client";
import { HttpError } from "@/lib/security/http";
const CHECK_SECONDS = 300;
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; expiresAt: string };
let discovery: { endpoints: Endpoints; until: number } | undefined;
async function endpoints(): Promise<Endpoints> {
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<boolean> {
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;
}
function bindingKey(sessionId: string) {
return `${redisCachePrefix()}:sudloh:session:${sessionId}`;
}
async function updateProfile(userId: string, token: BoundToken): Promise<boolean> {
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<void> {
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,
expiresAt: account.accessTokenExpiresAt.toISOString() };
if (!await introspect(token)) throw new HttpError(401, "sudloh-sign-in-required");
if (!await updateProfile(userId, token)) throw new HttpError(401, "unauthorized");
}
export async function bindSudlohSession(userId: string, sessionId: string): Promise<void> {
const [account] = await getDb().select().from(accounts).where(and(
eq(accounts.userId, userId), eq(accounts.providerId, "sudloh"),
)).limit(1);
if (!account?.accessToken || !account.accessTokenExpiresAt) throw new HttpError(503, "sudloh-token-missing");
const seconds = Math.floor((account.accessTokenExpiresAt.getTime() - Date.now()) / 1000);
if (seconds <= 0) throw new HttpError(503, "sudloh-token-expired");
const bound: BoundToken = { token: account.accessToken, accountId: account.accountId,
expiresAt: account.accessTokenExpiresAt.toISOString() };
await (await getRedisClient()).set(bindingKey(sessionId), JSON.stringify(bound), "EX", seconds);
}
export async function validateSudlohSession(userId: string, sessionId: string, force = false): Promise<boolean> {
const [account] = await getDb().select({ id: accounts.id, accountId: accounts.accountId })
.from(accounts).where(and(eq(accounts.userId, userId), eq(accounts.providerId, "sudloh"))).limit(1);
const invalidate = async () => {
await getDb().delete(sessions).where(eq(sessions.id, sessionId));
return false;
};
if (!account) return invalidate();
const redis = await getRedisClient().catch(() => null);
if (!redis) throw new HttpError(503, "sudloh-check-unavailable");
const raw = await redis.get(bindingKey(sessionId)).catch(() => { throw new HttpError(503, "sudloh-check-unavailable"); });
if (!raw) return invalidate();
let bound: BoundToken;
try { bound = JSON.parse(raw) as BoundToken; }
catch { throw new HttpError(503, "sudloh-check-unavailable"); }
if (bound.accountId !== account.accountId || !bound.token ||
!Number.isFinite(Date.parse(bound.expiresAt)) || Date.parse(bound.expiresAt) <= Date.now()) return invalidate();
const digest = createHash("sha256").update(bound.token).digest("hex");
const key = `${redisCachePrefix()}:sudloh:active:${sessionId}:${digest}`;
if (!force && await redis.get(key).catch(() => null) === "1") return true;
try {
if (!await introspect(bound)) return invalidate();
if (!await updateProfile(userId, bound)) return invalidate();
const remaining = Math.floor((Date.parse(bound.expiresAt) - Date.now()) / 1000);
if (remaining > 0) await redis.set(key, "1", "EX", Math.min(CHECK_SECONDS, remaining)).catch(() => undefined);
return true;
} catch (cause) {
if (cause instanceof HttpError) throw cause;
throw new HttpError(503, "sudloh-unavailable");
}
}
+2 -3
View File
@@ -1,7 +1,6 @@
import "server-only";
import { headers } from "next/headers";
import { getAuth } from "@/lib/auth/server";
import { getVerifiedSession } from "@/lib/auth/server";
import { getDb } from "@/db";
import { users } from "@/db/schema";
import { eq } from "drizzle-orm";
@@ -9,7 +8,7 @@ import { HttpError } from "@/lib/security/http";
import { getRedisClient, redisEventChannel } from "@/lib/redis/client";
export async function requireCommissionUser() {
const session = await getAuth().api.getSession({ headers: await headers() });
const session = await getVerifiedSession();
if (!session?.user) throw new HttpError(401, "unauthorized");
const [user] = await getDb().select().from(users).where(eq(users.id, session.user.id)).limit(1);
if (!user || user.banned) throw new HttpError(401, "unauthorized");