Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions apps/dashboard/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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"
}
140 changes: 140 additions & 0 deletions apps/dashboard/src/app/(app)/api/auth/ensure-login/route.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, string>();
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();
},
);
});
27 changes: 15 additions & 12 deletions apps/dashboard/src/app/(app)/api/auth/ensure-login/route.ts
Original file line number Diff line number Diff line change
@@ -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");

Expand All @@ -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);
Expand All @@ -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}`,
},
Expand All @@ -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
Expand All @@ -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);
};
14 changes: 14 additions & 0 deletions apps/dashboard/vitest.config.mts
Original file line number Diff line number Diff line change
@@ -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"],
},
});
6 changes: 6 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions turbo.json
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,10 @@
"wallet-ui#build": {
"dependsOn": ["^build"],
"outputs": [".next/**", "!.next/cache/**"]
},
"thirdweb-dashboard#test": {
"dependsOn": ["^build"],
"outputs": []
}
}
}
Loading