diff --git a/apps/dashboard/package.json b/apps/dashboard/package.json index 2296758562f..c6f19b326c8 100644 --- a/apps/dashboard/package.json +++ b/apps/dashboard/package.json @@ -104,11 +104,13 @@ "eslint-plugin-react-compiler": "19.1.0-rc.2", "eslint-plugin-storybook": "9.1.20", "knip": "5.60.2", + "msw": "2.7.5", "next-sitemap": "^4.2.3", "postcss": "8.5.23", "storybook": "9.1.21", "tailwindcss": "3.4.17", - "typescript": "5.8.3" + "typescript": "5.8.3", + "vitest": "4.1.11" }, "name": "thirdweb-dashboard", "private": true, @@ -125,7 +127,9 @@ "preinstall": "npx only-allow pnpm", "start": "next start", "storybook": "storybook dev -p 6006", - "typecheck": "tsc --noEmit" + "typecheck": "tsc --noEmit", + "test:unit": "turbo run test --filter=thirdweb-dashboard", + "test": "vitest run" }, "version": "3.0.0" } diff --git a/apps/dashboard/src/app/(app)/api/auth/ensure-login/route.test.ts b/apps/dashboard/src/app/(app)/api/auth/ensure-login/route.test.ts new file mode 100644 index 00000000000..9231ca0a229 --- /dev/null +++ b/apps/dashboard/src/app/(app)/api/auth/ensure-login/route.test.ts @@ -0,0 +1,140 @@ +import { HttpResponse, http } from "msw"; +import { setupServer } from "msw/node"; +import { NextRequest } from "next/server"; +import { getAddress } from "thirdweb/utils"; +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from "vitest"; +import { COOKIE_ACTIVE_ACCOUNT, COOKIE_PREFIX_TOKEN } from "@/constants/cookie"; +import { GET } from "./route"; + +const { values, cookieStore } = vi.hoisted(() => { + const values = new Map(); + return { + values, + cookieStore: { + get: vi.fn((name: string) => { + const value = values.get(name); + return value === undefined ? undefined : { name, value }; + }), + getAll: vi.fn(() => + Array.from(values, ([name, value]) => ({ name, value })), + ), + delete: vi.fn((name: string) => values.delete(name)), + set: vi.fn(), + }, + }; +}); + +vi.mock("next/headers", () => ({ cookies: async () => cookieStore })); +vi.mock("@/constants/public-envs", () => ({ + NEXT_PUBLIC_THIRDWEB_API_HOST: "https://api.example.test", +})); + +const address = getAddress("0x0000000000000000000000000000000000000001"); +const token = "test-token-not-a-real-credential"; +const server = setupServer(); + +function request(value: string | undefined = address): NextRequest { + const url = new URL("https://dashboard.example.test/api/auth/ensure-login"); + if (value !== undefined) { + url.searchParams.set("address", value); + } + return new NextRequest(url); +} + +describe("ensure-login", () => { + beforeAll(() => server.listen({ onUnhandledRequest: "error" })); + afterAll(() => server.close()); + afterEach(() => { + server.resetHandlers(); + vi.restoreAllMocks(); + }); + beforeEach(() => { + values.clear(); + vi.clearAllMocks(); + }); + + it("returns only login status and keeps the bearer token server-side", async () => { + const fetchSpy = vi.spyOn(globalThis, "fetch"); + values.set(COOKIE_PREFIX_TOKEN + address, token); + server.use( + http.get("https://api.example.test/v1/account/me", ({ request }) => { + expect(request.headers.get("authorization")).toBe(`Bearer ${token}`); + return HttpResponse.json({ id: "test-account" }); + }), + ); + + const response = await GET(request()); + expect(fetchSpy).toHaveBeenCalledWith( + "https://api.example.test/v1/account/me", + expect.objectContaining({ cache: "no-store" }), + ); + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ isLoggedIn: true }); + expect(response.headers.get("cache-control")).toBe("no-store"); + expect(cookieStore.set).toHaveBeenCalledWith( + COOKIE_ACTIVE_ACCOUNT, + address, + { + httpOnly: true, + maxAge: 3 * 24 * 60 * 60, + sameSite: "strict", + secure: true, + }, + ); + expect(values.get(COOKIE_PREFIX_TOKEN + address)).toBe(token); + }); + + it("does not cache logged-out status without a token", async () => { + const response = await GET(request()); + expect(await response.json()).toEqual({ isLoggedIn: false }); + expect(response.headers.get("cache-control")).toBe("no-store"); + expect(cookieStore.delete).toHaveBeenCalledWith(COOKIE_ACTIVE_ACCOUNT); + }); + + it("clears account cookies and does not cache logout", async () => { + values.set(COOKIE_PREFIX_TOKEN + address, token); + values.set(COOKIE_ACTIVE_ACCOUNT, address); + values.set("unrelated", "keep"); + const url = new URL("https://dashboard.example.test/api/auth/ensure-login"); + const response = await GET(new NextRequest(url)); + expect(await response.json()).toEqual({ isLoggedIn: false }); + expect(response.headers.get("cache-control")).toBe("no-store"); + expect(values.has(COOKIE_PREFIX_TOKEN + address)).toBe(false); + expect(values.has(COOKIE_ACTIVE_ACCOUNT)).toBe(false); + expect(values.get("unrelated")).toBe("keep"); + }); + + it("does not cache invalid-token status and removes the rejected token", async () => { + values.set(COOKIE_PREFIX_TOKEN + address, token); + server.use( + http.get( + "https://api.example.test/v1/account/me", + () => new HttpResponse(null, { status: 401 }), + ), + ); + const response = await GET(request()); + expect(await response.json()).toEqual({ isLoggedIn: false }); + expect(response.headers.get("cache-control")).toBe("no-store"); + expect(values.has(COOKIE_PREFIX_TOKEN + address)).toBe(false); + }); + + it.each(["invalid", "0x1234", `0x${"z".repeat(40)}`])( + "rejects malformed address %s without reading token cookies", + async (invalidAddress) => { + const response = await GET(request(invalidAddress)); + expect(response.status).toBe(400); + expect(await response.json()).toEqual({ error: "Invalid address" }); + expect(response.headers.get("cache-control")).toBe("no-store"); + expect(cookieStore.get).not.toHaveBeenCalled(); + }, + ); +}); diff --git a/apps/dashboard/src/app/(app)/api/auth/ensure-login/route.ts b/apps/dashboard/src/app/(app)/api/auth/ensure-login/route.ts index 066855a8ed5..61a4b7f5bb9 100644 --- a/apps/dashboard/src/app/(app)/api/auth/ensure-login/route.ts +++ b/apps/dashboard/src/app/(app)/api/auth/ensure-login/route.ts @@ -1,14 +1,15 @@ import { cookies } from "next/headers"; import { type NextRequest, NextResponse } from "next/server"; -import { getAddress } from "thirdweb/utils"; +import { getAddress, isAddress } from "thirdweb/utils"; import { COOKIE_ACTIVE_ACCOUNT, COOKIE_PREFIX_TOKEN } from "@/constants/cookie"; import { NEXT_PUBLIC_THIRDWEB_API_HOST } from "@/constants/public-envs"; export type EnsureLoginResponse = { isLoggedIn: boolean; - jwt?: string; }; +const responseInit = { headers: { "Cache-Control": "no-store" } }; + export const GET = async (req: NextRequest) => { const address = req.nextUrl.searchParams.get("address"); @@ -25,9 +26,14 @@ export const GET = async (req: NextRequest) => { } // also delete the active account cookie cookieStore.delete(COOKIE_ACTIVE_ACCOUNT); - return NextResponse.json({ - isLoggedIn: false, - }); + return NextResponse.json({ isLoggedIn: false }, responseInit); + } + + if (!isAddress(address)) { + return NextResponse.json( + { error: "Invalid address" }, + { ...responseInit, status: 400 }, + ); } const authCookieName = COOKIE_PREFIX_TOKEN + getAddress(address); @@ -39,15 +45,14 @@ export const GET = async (req: NextRequest) => { if (!token) { // delete the active account cookie (the account is not logged in) cookieStore.delete(COOKIE_ACTIVE_ACCOUNT); - return NextResponse.json({ - isLoggedIn: false, - }); + return NextResponse.json({ isLoggedIn: false }, responseInit); } // check that the token is valid by checking for the user account const accountRes = await fetch( `${NEXT_PUBLIC_THIRDWEB_API_HOST}/v1/account/me`, { + cache: "no-store", headers: { Authorization: `Bearer ${token}`, }, @@ -57,9 +62,7 @@ export const GET = async (req: NextRequest) => { if (accountRes.status !== 200) { // if the account is not found, clear the token and redirect to login cookieStore.delete(authCookieName); - return NextResponse.json({ - isLoggedIn: false, - }); + return NextResponse.json({ isLoggedIn: false }, responseInit); } // make sure the active account cookie is set to the correct address @@ -78,5 +81,5 @@ export const GET = async (req: NextRequest) => { } // if everything is good simply return true - return NextResponse.json({ isLoggedIn: true, jwt: token }); + return NextResponse.json({ isLoggedIn: true }, responseInit); }; diff --git a/apps/dashboard/vitest.config.mts b/apps/dashboard/vitest.config.mts new file mode 100644 index 00000000000..7392e1e2ce3 --- /dev/null +++ b/apps/dashboard/vitest.config.mts @@ -0,0 +1,14 @@ +import { fileURLToPath } from "node:url"; +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + resolve: { + alias: { + "@": fileURLToPath(new URL("./src/@", import.meta.url)), + }, + }, + test: { + environment: "node", + include: ["src/**/*.test.ts"], + }, +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d39867ac255..277c4fa0599 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -456,6 +456,9 @@ importers: knip: specifier: 5.60.2 version: 5.60.2(@types/node@22.14.1)(typescript@5.8.3) + msw: + specifier: 2.7.5 + version: 2.7.5(@types/node@24.0.10)(typescript@5.8.3) next-sitemap: specifier: ^4.2.3 version: 4.2.3(next@15.5.27(@opentelemetry/api@1.9.1)(@playwright/test@1.53.2)(@types/node@22.14.1)(react-dom@19.2.1(react@19.2.1))(react@19.2.1)) @@ -471,6 +474,9 @@ importers: typescript: specifier: 5.8.3 version: 5.8.3 + vitest: + specifier: 4.1.11 + version: 4.1.11(@opentelemetry/api@1.9.1)(@types/node@24.0.10)(@vitest/coverage-v8@4.1.11)(@vitest/ui@4.1.11)(happy-dom@20.14.3(bufferutil@4.0.9)(utf-8-validate@5.0.10))(msw@2.7.5(@types/node@24.0.10)(typescript@5.8.3))(vite@7.3.7(@types/node@24.0.10)(jiti@2.7.0)(lightningcss@1.30.1)(terser@5.43.1)(tsx@4.20.3)(yaml@2.8.4)) apps/nebula: dependencies: diff --git a/turbo.json b/turbo.json index aeeca3aace2..0e54e099cf6 100644 --- a/turbo.json +++ b/turbo.json @@ -107,6 +107,10 @@ "wallet-ui#build": { "dependsOn": ["^build"], "outputs": [".next/**", "!.next/cache/**"] + }, + "thirdweb-dashboard#test": { + "dependsOn": ["^build"], + "outputs": [] } } }