diff --git a/README.md b/README.md index b0d17e9..15a3a15 100644 --- a/README.md +++ b/README.md @@ -17,9 +17,11 @@ endorsed by HoYoverse. The repository and deployment resources retain the - **Accounts:** Sudloh Account OIDC sign-in with local Buzz sessions, IDs, and roles. Legacy email/password and registration OTP remain available only before `SUDLOH_OIDC_ONLY=true` cutover. Linked profiles are managed at Sudloh Account; - Guide refreshes their profile from UserInfo and checks Sudloh token activity on - protected requests at least every five minutes. Access tokens expire after - about an hour and require a new Sudloh authorization flow. + Guide refreshes their profile from UserInfo on request. Guide sessions follow + Better Auth's rolling session lifetime rather than the roughly one-hour Sudloh + access token. A fresh Sudloh authorization is needed to refresh a profile after + that token expires. Sudloh Account sign-out or revocation does not end an + existing Guide session; users must also sign out of Guide. - **Media:** S3-compatible uploads and publication-aware delivery for staged files. - **Catalog updates:** Discord-triggered synchronization with Lunaris. - **Commissions:** PromptPay checkout, Slip2Go verification, ticket attachments, diff --git a/app/api/auth/[...all]/route.test.ts b/app/api/auth/[...all]/route.test.ts index df808e6..91a73c6 100644 --- a/app/api/auth/[...all]/route.test.ts +++ b/app/api/auth/[...all]/route.test.ts @@ -1,7 +1,6 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; const session = vi.fn(); -const validate = vi.fn(); const handler = vi.fn(async () => Response.json({ passed: true })); vi.mock("server-only", () => ({})); @@ -10,7 +9,6 @@ vi.mock("@/lib/auth/server", () => ({ getAuth: () => ({ api: { getSession: session }, handler }), isSudlohOidcEnabled: () => true, })); -vi.mock("@/lib/auth/sudloh", () => ({ validateSudlohSession: validate })); const { GET, POST } = await import("./route"); @@ -19,30 +17,27 @@ beforeEach(() => { process.env.BETTER_AUTH_URL = "https://guide.sudloh.com"; process.env.SUDLOH_OIDC_ONLY = "true"; session.mockResolvedValue({ user: { id: "user-1" }, session: { id: "session-1" } }); - validate.mockResolvedValue(false); }); describe("Better Auth Sudloh boundary", () => { - it("returns no browser session after Sudloh revokes the bound token", async () => { + it("lets Better Auth serve the local browser session", async () => { const response = await GET(new Request("https://guide.sudloh.com/api/auth/get-session")); expect(response.status).toBe(200); - expect(await response.json()).toBeNull(); - expect(handler).not.toHaveBeenCalled(); + expect(await response.json()).toEqual({ passed: true }); + expect(handler).toHaveBeenCalledOnce(); }); - it("denies other account endpoints but permits the OIDC callback", async () => { - const denied = await GET(new Request("https://guide.sudloh.com/api/auth/list-sessions")); - expect(denied.status).toBe(401); + it("permits the OIDC callback", async () => { const callback = await GET(new Request("https://guide.sudloh.com/api/auth/callback/sudloh?code=code")); expect(callback.status).toBe(200); }); - it("denies Better Auth mutations with a revoked local session", async () => { + it("passes mutations to Better Auth for local session checks", async () => { const response = await POST(new Request("https://guide.sudloh.com/api/auth/admin/create-user", { method: "POST", headers: { Origin: "https://guide.sudloh.com", "Content-Type": "application/json" }, body: JSON.stringify({ password: "example-password" }), })); - expect(response.status).toBe(401); - expect(handler).not.toHaveBeenCalled(); + expect(response.status).toBe(200); + expect(handler).toHaveBeenCalledOnce(); }); }); diff --git a/app/api/auth/[...all]/route.ts b/app/api/auth/[...all]/route.ts index f31230a..a439ebc 100644 --- a/app/api/auth/[...all]/route.ts +++ b/app/api/auth/[...all]/route.ts @@ -2,32 +2,13 @@ import { toNextJsHandler } from "better-auth/next-js"; import { and, eq } from "drizzle-orm"; import { getAuth, isSudlohOidcEnabled } from "@/lib/auth/server"; -import { validateSudlohSession } from "@/lib/auth/sudloh"; import { getDb } from "@/db"; import { accounts } from "@/db/schema"; import { errorResponse, HttpError, readJson, requireSameOrigin } from "@/lib/security/http"; const handlers = toNextJsHandler((request) => getAuth().handler(request)); -async function hasActiveSudlohSession(request: Request): Promise { - if (!isSudlohOidcEnabled() || process.env.SUDLOH_OIDC_ONLY !== "true") return null; - const session = await getAuth().api.getSession({ headers: request.headers }); - if (!session) return null; - return validateSudlohSession(session.user.id, session.session.id); -} - export async function GET(request: Request) { - const path = new URL(request.url).pathname; - if (!path.endsWith("/callback/sudloh")) { - try { - const active = await hasActiveSudlohSession(request); - if (active === false) { - if (path.endsWith("/get-session")) - return Response.json(null, { headers: { "Cache-Control": "no-store" } }); - throw new HttpError(401, "unauthorized"); - } - } catch (cause) { return errorResponse(cause); } - } return handlers.GET(request); } @@ -36,8 +17,6 @@ async function mutate(request: Request) { requireSameOrigin(request); const input = await readJson(request.clone()); const path = new URL(request.url).pathname; - if (!path.endsWith("/sign-in/social") && !path.endsWith("/sign-out") && - await hasActiveSudlohSession(request) === false) throw new HttpError(401, "unauthorized"); if (["/update-user", "/change-email"].some((endpoint) => path.endsWith(endpoint))) { if (isSudlohOidcEnabled() && process.env.SUDLOH_OIDC_ONLY === "true") throw new HttpError(403, "manage-profile-at-sudloh"); diff --git a/app/api/profile/sync/route.ts b/app/api/profile/sync/route.ts index c2b05dd..65275e8 100644 --- a/app/api/profile/sync/route.ts +++ b/app/api/profile/sync/route.ts @@ -1,5 +1,5 @@ -import { getCustomerSession, isSudlohOidcEnabled } from "@/lib/auth/server"; -import { refreshLinkedSudlohProfile, validateSudlohSession } from "@/lib/auth/sudloh"; +import { getCustomerSession } from "@/lib/auth/server"; +import { refreshLinkedSudlohProfile } from "@/lib/auth/sudloh"; import { errorResponse, HttpError, requireSameOrigin } from "@/lib/security/http"; export async function POST(request: Request) { @@ -7,10 +7,7 @@ export async function POST(request: Request) { requireSameOrigin(request); const session = await getCustomerSession(); if (!session) throw new HttpError(401, "unauthorized"); - if (isSudlohOidcEnabled() && process.env.SUDLOH_OIDC_ONLY === "true") { - if (!await validateSudlohSession(session.user.id, session.session.id, true)) - throw new HttpError(401, "sudloh-session-expired"); - } else await refreshLinkedSudlohProfile(session.user.id); + await refreshLinkedSudlohProfile(session.user.id); return Response.json({ ok: true }, { headers: { "Cache-Control": "no-store" } }); } catch (cause) { return errorResponse(cause); } } diff --git a/components/admin/admin-header.tsx b/components/admin/admin-header.tsx index 3745bfe..0c317d8 100644 --- a/components/admin/admin-header.tsx +++ b/components/admin/admin-header.tsx @@ -15,7 +15,7 @@ import { } from "lucide-react"; import { Button } from "@/components/ui/button"; -import { AccountMenu } from "@/components/auth/account-menu"; +import { SignOutButton } from "@/components/auth/sign-out-button"; import { CommissionPushEntryPrompt } from "@/components/commission/push-entry-prompt"; export function AdminHeader() { @@ -100,7 +100,7 @@ export function AdminHeader() { > - + diff --git a/components/auth/account-menu.tsx b/components/auth/account-menu.tsx deleted file mode 100644 index 7c02474..0000000 --- a/components/auth/account-menu.tsx +++ /dev/null @@ -1,41 +0,0 @@ -"use client"; - -import Link from "next/link"; -import { useRouter } from "next/navigation"; -import { LogOutIcon, UserRoundIcon } from "lucide-react"; -import { Button } from "@/components/ui/button"; -import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, - DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; -import { authClient } from "@/lib/auth/client"; -import { markSudlohSignInAttempt } from "@/lib/auth/sudloh-redirect"; -import { unsubscribeCommissionPush } from "@/components/commission/push-client"; - -export function AccountMenu({ admin = false }: { admin?: boolean }) { - const router = useRouter(); - const { data } = authClient.useSession(); - if (!admin && !data?.user) return null; - - async function signOut() { - await unsubscribeCommissionPush().catch(() => undefined); - await authClient.signOut(); - markSudlohSignInAttempt(); - router.push(admin ? "/auth/login?next=%2Fadmin" : "/commission"); - router.refresh(); - } - - return - }> - - - - - {data?.user?.name || "บัญชีของฉัน"} - }>โปรไฟล์ของฉัน - - - - void signOut()}>ออกจากระบบ - - - ; -} diff --git a/components/auth/sign-out-button.tsx b/components/auth/sign-out-button.tsx new file mode 100644 index 0000000..790c1d2 --- /dev/null +++ b/components/auth/sign-out-button.tsx @@ -0,0 +1,26 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { LogOutIcon } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { authClient } from "@/lib/auth/client"; +import { markSudlohSignInAttempt } from "@/lib/auth/sudloh-redirect"; +import { unsubscribeCommissionPush } from "@/components/commission/push-client"; + +export function SignOutButton({ admin = false }: { admin?: boolean }) { + const router = useRouter(); + const { data } = authClient.useSession(); + if (!admin && !data?.user) return null; + + async function signOut() { + await unsubscribeCommissionPush().catch(() => undefined); + await authClient.signOut(); + markSudlohSignInAttempt(); + router.push(admin ? "/auth/login?next=%2Fadmin" : "/commission"); + router.refresh(); + } + + return ; +} diff --git a/components/public/site-header.tsx b/components/public/site-header.tsx index a46db4e..4f1640b 100644 --- a/components/public/site-header.tsx +++ b/components/public/site-header.tsx @@ -6,7 +6,7 @@ import { PencilIcon } from "lucide-react"; import { Button } from "@/components/ui/button"; import { VisitorPresence } from "@/components/public/visitor-presence"; import { PublicNavigation } from "@/components/public/public-navigation"; -import { AccountMenu } from "@/components/auth/account-menu"; +import { SignOutButton } from "@/components/auth/sign-out-button"; import { getAdminSession } from "@/lib/auth/server"; import { HttpError } from "@/lib/security/http"; @@ -45,7 +45,7 @@ export function SiteHeader({ editHref = "/admin", guideId }: { editHref?: string
- + ); diff --git a/lib/auth/oidc-flow.test.ts b/lib/auth/oidc-flow.test.ts index 8c2bc31..ff2e580 100644 --- a/lib/auth/oidc-flow.test.ts +++ b/lib/auth/oidc-flow.test.ts @@ -1,22 +1,16 @@ -import { describe, expect, it, vi } from "vitest"; +import { describe, expect, it } from "vitest"; import { betterAuth } from "better-auth"; import { memoryAdapter } from "better-auth/adapters/memory"; import { genericOAuth } from "better-auth/plugins"; -import { isSudlohCallback } from "./sudloh-callback"; const origin = "https://guide.test"; -function createReplica(database: Record[]>, onSession: (sessionId: string) => void) { +function createReplica(database: Record[]>) { return betterAuth({ baseURL: origin, secret: "a-shared-test-secret-with-enough-entropy-123", database: memoryAdapter(database), rateLimit: { enabled: false }, - databaseHooks: { session: { create: { after: async ( - session: { id: string }, context: { path: string; params?: { id?: string } } | null, - ) => { - if (isSudlohCallback(context)) onSession(session.id); - } } } }, plugins: [genericOAuth({ config: [{ providerId: "sudloh", clientId: "test-client", @@ -31,11 +25,10 @@ function createReplica(database: Record[]>, onSe } describe("Sudloh OAuth callback", () => { - it("completes across replicas, binds the Guide session, and consumes state once", async () => { + it("completes across replicas, creates the Guide session, and consumes state once", async () => { const database = { user: [], session: [], account: [], verification: [] }; - const bind = vi.fn(); - const first = createReplica(database, bind); - const second = createReplica(database, bind); + const first = createReplica(database); + const second = createReplica(database); const start = await first.handler(new Request(`${origin}/api/auth/sign-in/social`, { method: "POST", headers: { Origin: origin, "Content-Type": "application/json" }, body: JSON.stringify({ provider: "sudloh", callbackURL: "/profile" }), @@ -54,7 +47,6 @@ describe("Sudloh OAuth callback", () => { })); expect(callback.status).toBe(302); expect(callback.headers.get("location")).toBe("/profile"); - expect(bind).toHaveBeenCalledOnce(); const sessionCookie = callback.headers.getSetCookie() .find((cookie) => cookie.includes("session_token="))?.split(";", 1)[0]; const session = await second.api.getSession({ headers: new Headers({ Cookie: sessionCookie! }) }); @@ -63,15 +55,12 @@ describe("Sudloh OAuth callback", () => { headers: { Cookie: stateCookie! }, })); expect(replay.headers.get("location")).toContain("state_mismatch"); - expect(bind).toHaveBeenCalledOnce(); }); it("rejects a callback without state before exchanging a code", async () => { - const bind = vi.fn(); - const auth = createReplica({ user: [], session: [], account: [], verification: [] }, bind); + const auth = createReplica({ user: [], session: [], account: [], verification: [] }); const response = await auth.handler(new Request(`${origin}/api/auth/callback/sudloh?code=test-code`)); expect(response.status).toBe(302); expect(response.headers.get("location")).toContain("state_not_found"); - expect(bind).not.toHaveBeenCalled(); }); }); diff --git a/lib/auth/server.test.ts b/lib/auth/server.test.ts index 361face..bf864dc 100644 --- a/lib/auth/server.test.ts +++ b/lib/auth/server.test.ts @@ -1,7 +1,6 @@ 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() })); @@ -11,7 +10,6 @@ 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", "TRUSTED_CLIENT_IP_HEADER"] as const; const testEnv = process.env as Record; @@ -25,8 +23,6 @@ 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; @@ -98,25 +94,18 @@ describe("actual administrator session boundary", () => { expect(options.advanced.ipAddress.ipAddressHeaders).toEqual(["x-forwarded-for"]); 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/:id", params: { id: "sudloh" } }); - expect(sudloh.bind).toHaveBeenCalledWith("user-1", "guide-session"); - sudloh.bind.mockClear(); - await options.databaseHooks.session.create.after({ id: "other-session", userId: "user-1" }, - { path: "/callback/:id", params: { id: "other" } }); - expect(sudloh.bind).not.toHaveBeenCalled(); + expect(options.databaseHooks).toBeUndefined(); }); - it("denies a revoked Sudloh session", async () => { + it("keeps the local Guide session after the Sudloh access token expires", 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: "a@test.invalid", 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(); + expect(await getCustomerSession()).toMatchObject({ user: { id: "user-1" } }); + expect(await getAdminSession()).toMatchObject({ user: { id: "user-1" } }); }); it("rejects incomplete or mismatched Sudloh client configuration", async () => { const { getAuth, isSudlohOidcEnabled } = await import("./server"); diff --git a/lib/auth/server.ts b/lib/auth/server.ts index 12ba05f..3fd1720 100644 --- a/lib/auth/server.ts +++ b/lib/auth/server.ts @@ -19,8 +19,6 @@ 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"; -import { isSudlohCallback } from "./sudloh-callback"; function required(name: string): string { const value = process.env[name]; @@ -65,13 +63,6 @@ function createAuth() { }, transaction: true, }), - ...(oidcOnly ? { databaseHooks: { session: { create: { after: async ( - session: { id: string; userId: string }, - context: { path: string; params?: { id?: string } } | null, - ) => { - if (isSudlohCallback(context)) - await bindSudlohSession(session.userId, session.id); - } } } } } : {}), baseURL: required("BETTER_AUTH_URL"), trustedOrigins: process.env.BETTER_AUTH_TRUSTED_ORIGINS ?.split(",") @@ -173,8 +164,6 @@ 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; }); diff --git a/lib/auth/sudloh-callback.ts b/lib/auth/sudloh-callback.ts deleted file mode 100644 index a977ed5..0000000 --- a/lib/auth/sudloh-callback.ts +++ /dev/null @@ -1,3 +0,0 @@ -export function isSudlohCallback(context: { path: string; params?: { id?: string } } | null): boolean { - return context?.path === "/callback/:id" && context.params?.id === "sudloh"; -} diff --git a/lib/auth/sudloh.test.ts b/lib/auth/sudloh.test.ts index d059186..bcc3cef 100644 --- a/lib/auth/sudloh.test.ts +++ b/lib/auth/sudloh.test.ts @@ -1,29 +1,20 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; const rows: unknown[][] = []; -const values = new Map(); -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 }; +const { refreshLinkedSudlohProfile } = await import("./sudloh"); +const account = { accountId: "sub-1", accessToken: "access-1", + accessTokenExpiresAt: new Date(Date.now() + 60 * 60_000) }; 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"; @@ -31,7 +22,7 @@ beforeEach(() => { }); function provider(active: boolean, profileSub = "sub-1") { - const fetchMock = vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => { + return 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", @@ -44,63 +35,42 @@ function provider(active: boolean, profileSub = "sub-1") { email: "new@test.invalid", email_verified: true, picture: "https://account.test/avatar.png" }); throw new Error(`unexpected URL: ${url}`); }); - return fetchMock; } -describe("Sudloh session validation", () => { - it("rejects a new Guide session when the callback did not bind it", async () => { - rows.push([account]); - expect(await validateSudlohSession("user-1", "session-1")).toBe(false); - expect(removeSession).toHaveBeenCalledOnce(); +describe("Sudloh profile refresh", () => { + it("requires a new Sudloh sign-in after the access token expires", async () => { + rows.push([{ ...account, accessTokenExpiresAt: new Date(Date.now() - 1000) }]); + await expect(refreshLinkedSudlohProfile("user-1")) + .rejects.toMatchObject({ status: 401, message: "sudloh-sign-in-required" }); }); - 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: "old@test.invalid", 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"); + it("requires a new Sudloh sign-in when the token is revoked", async () => { const fetchMock = provider(false); rows.push([account]); - expect(await validateSudlohSession("user-1", "session-1")).toBe(false); - expect(removeSession).toHaveBeenCalledOnce(); + await expect(refreshLinkedSudlohProfile("user-1")) + .rejects.toMatchObject({ status: 401, message: "sudloh-sign-in-required" }); fetchMock.mockRestore(); }); - it("fails closed when UserInfo returns another subject", async () => { - rows.push([account]); - await bindSudlohSession("user-1", "session-1"); + it("rejects UserInfo for another subject", async () => { const fetchMock = provider(true, "someone-else"); rows.push([account]); - await expect(validateSudlohSession("user-1", "session-1")) + await expect(refreshLinkedSudlohProfile("user-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: "old@test.invalid", emailVerified: true, image: null }]); updateUser.mockRejectedValueOnce({ cause: { code: "23505" } }); - await expect(validateSudlohSession("user-1", "session-1")) + await expect(refreshLinkedSudlohProfile("user-1")) .rejects.toMatchObject({ status: 409, message: "sudloh-email-conflict" }); fetchMock.mockRestore(); }); - it("refreshes a linked profile during the legacy sign-in transition", async () => { + it("updates a linked profile while its token is active", async () => { const fetchMock = provider(true); rows.push([account], [{ name: "Old Name", email: "old@test.invalid", emailVerified: true, image: null }]); await refreshLinkedSudlohProfile("user-1"); diff --git a/lib/auth/sudloh.ts b/lib/auth/sudloh.ts index 11a9c0a..12ad366 100644 --- a/lib/auth/sudloh.ts +++ b/lib/auth/sudloh.ts @@ -1,19 +1,16 @@ 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 { accounts, users } from "@/db/schema"; 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 }; +type BoundToken = { token: string; accountId: string }; let discovery: { endpoints: Endpoints; until: number } | undefined; @@ -80,10 +77,6 @@ async function introspect(account: BoundToken): Promise { return true; } -function bindingKey(sessionId: string) { - return `${redisCachePrefix()}:sudloh:session:${sessionId}`; -} - async function updateProfile(userId: string, token: BoundToken): Promise { const profile = await userInfo(token); const [current] = await getDb().select({ name: users.name, email: users.email, @@ -111,54 +104,7 @@ export async function refreshLinkedSudlohProfile(userId: string): Promise )).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() }; + 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"); } - -export async function bindSudlohSession(userId: string, sessionId: 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) 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 { - 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"); - } -}