Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,10 @@ vi.mock("@/lib/db", () => ({
},
}));

vi.mock("@/lib/db/usernameLookup", () => ({
normalizeUsernameCacheKey: (username: string) => username.toLowerCase(),
}));

type ModuleExports = typeof import("../../src/app/api/settings/submitted-data/route");

let DELETE: ModuleExports["DELETE"];
Expand Down Expand Up @@ -120,7 +124,7 @@ describe("DELETE /api/settings/submitted-data", () => {
it("deletes submitted data and revalidates public caches", async () => {
mockState.getSession.mockResolvedValue({
id: "user-1",
username: "alice",
username: "Alice",
displayName: "Alice",
avatarUrl: null,
isAdmin: false,
Expand Down Expand Up @@ -153,9 +157,9 @@ describe("DELETE /api/settings/submitted-data", () => {
expect(mockState.revalidateTag).toHaveBeenNthCalledWith(7, "embed-user:alice:cost", "max");
expect(mockState.revalidatePath).toHaveBeenNthCalledWith(1, "/leaderboard");
expect(mockState.revalidatePath).toHaveBeenNthCalledWith(2, "/profile");
expect(mockState.revalidatePath).toHaveBeenNthCalledWith(3, "/u/alice");
expect(mockState.revalidatePath).toHaveBeenNthCalledWith(4, "/api/users/alice");
expect(mockState.revalidatePath).toHaveBeenNthCalledWith(5, "/api/embed/alice/svg");
expect(mockState.revalidatePath).toHaveBeenNthCalledWith(3, "/u/Alice");
expect(mockState.revalidatePath).toHaveBeenNthCalledWith(4, "/api/users/Alice");
expect(mockState.revalidatePath).toHaveBeenNthCalledWith(5, "/api/embed/Alice/svg");
});

it("returns success and still revalidates caches when no submitted data exists", async () => {
Expand Down
4 changes: 4 additions & 0 deletions packages/frontend/__tests__/api/submitAuth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,10 @@ vi.mock("@/lib/db/helpers", () => ({
mergeTimestampMs: vi.fn(),
}));

vi.mock("@/lib/db/usernameLookup", () => ({
normalizeUsernameCacheKey: (username: string) => username.toLowerCase(),
}));

type ModuleExports = typeof import("../../src/app/api/submit/route");

let POST: ModuleExports["POST"];
Expand Down
117 changes: 114 additions & 3 deletions packages/frontend/__tests__/api/usersProfile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vite
const mockState = vi.hoisted(() => {
const selectResults: Array<Array<Record<string, unknown>>> = [];
const executeResults: Array<Array<Record<string, unknown>>> = [];
const limitCalls: unknown[] = [];

const tables = {
users: {
Expand Down Expand Up @@ -48,9 +49,11 @@ const mockState = vi.hoisted(() => {
const and = vi.fn(() => "and");
const gte = vi.fn(() => "gte");
const sql = Object.assign(
() => ({
vi.fn((strings: TemplateStringsArray, ...values: unknown[]) => ({
strings: Array.from(strings),
values,
as: () => ({}),
}),
})),
{
raw: vi.fn(),
}
Expand All @@ -67,7 +70,10 @@ const mockState = vi.hoisted(() => {
where: vi.fn(() => builder),
innerJoin: vi.fn(() => builder),
orderBy: vi.fn(() => builder),
limit: vi.fn(() => builder),
limit: vi.fn((value: unknown) => {
limitCalls.push(value);
return builder;
}),
then: (resolve: (value: unknown) => unknown) => resolve(nextSelectResult()),
};

Expand All @@ -87,12 +93,14 @@ const mockState = vi.hoisted(() => {
reset() {
selectResults.length = 0;
executeResults.length = 0;
limitCalls.length = 0;
db.select.mockClear();
db.execute.mockClear();
eq.mockClear();
desc.mockClear();
and.mockClear();
gte.mockClear();
sql.mockClear();
sql.raw.mockClear();
},
pushSelectResult(rows: Array<Record<string, unknown>>) {
Expand All @@ -101,6 +109,7 @@ const mockState = vi.hoisted(() => {
pushExecuteResult(rows: Array<Record<string, unknown>>) {
executeResults.push(rows);
},
limitCalls,
};
});

Expand All @@ -111,6 +120,24 @@ vi.mock("@/lib/db", () => ({
dailyBreakdown: mockState.tables.dailyBreakdown,
}));

vi.mock("@/lib/db/usernameLookup", () => {
class AmbiguousUsernameError extends Error {}

return {
AmbiguousUsernameError,
USERNAME_LOOKUP_LIMIT: 2,
getSingleUsernameMatch: (rows: readonly unknown[], username: string) => {
if (rows.length > 1) {
throw new AmbiguousUsernameError(`Multiple users match username ${username} case-insensitively`);
}
return rows[0] ?? null;
},
normalizeUsernameCacheKey: (username: string) => username.toLowerCase(),
usernameEqualsIgnoreCase: (username: string) =>
mockState.sql`lower(${mockState.tables.users.username}) = ${username.toLowerCase()}`,
};
});

vi.mock("@/lib/submissionFreshness", async () =>
import("../../src/lib/submissionFreshness")
);
Expand All @@ -127,6 +154,18 @@ type ModuleExports = typeof import("../../src/app/api/users/[username]/route");

let GET: ModuleExports["GET"];

function serializeSqlCalls(): string[] {
return mockState.sql.mock.calls.map((call) => {
const [strings, ...values] = call as [TemplateStringsArray, ...unknown[]];
const textParts = Array.from(strings);

return textParts.reduce((text, part, index) => {
const nextValue = index < values.length ? String(values[index]) : "";
return `${text}${part}${nextValue}`;
}, "");
});
}

beforeAll(async () => {
const routeModule = await import("../../src/app/api/users/[username]/route");
GET = routeModule.GET;
Expand All @@ -141,6 +180,78 @@ afterEach(() => {
});

describe("GET /api/users/[username]", () => {
it("looks up usernames case-insensitively and returns the canonical username", async () => {
mockState.pushSelectResult([
{
id: "user-imlunahey",
username: "ImLunaHey",
displayName: "Luna",
avatarUrl: null,
createdAt: "2026-01-01T00:00:00.000Z",
},
]);
mockState.pushSelectResult([
{
totalTokens: 0,
totalCost: 0,
inputTokens: 0,
outputTokens: 0,
cacheReadTokens: 0,
cacheCreationTokens: 0,
reasoningTokens: 0,
submissionCount: 0,
earliestDate: null,
latestDate: null,
},
]);
mockState.pushSelectResult([]);
mockState.pushSelectResult([]);
mockState.pushExecuteResult([]);

const response = await GET(
new Request("http://localhost:3000/api/users/imlunahey"),
{ params: Promise.resolve({ username: "imlunahey" }) }
);
const body = await response.json();
const sqlTexts = serializeSqlCalls();

expect(response.status).toBe(200);
expect(body.user.username).toBe("ImLunaHey");
expect(mockState.limitCalls[0]).toBe(2);
expect(sqlTexts.some((text) =>
text.toLowerCase().includes("lower(users.username) = imlunahey")
)).toBe(true);
});

it("rejects ambiguous case-insensitive username matches", async () => {
mockState.pushSelectResult([
{
id: "user-1",
username: "ImLunaHey",
displayName: "Luna",
avatarUrl: null,
createdAt: "2026-01-01T00:00:00.000Z",
},
{
id: "user-2",
username: "imlunahey",
displayName: "Luna Duplicate",
avatarUrl: null,
createdAt: "2026-01-02T00:00:00.000Z",
},
]);

const response = await GET(
new Request("http://localhost:3000/api/users/imlunahey"),
{ params: Promise.resolve({ username: "imlunahey" }) }
);
const body = await response.json();

expect(response.status).toBe(409);
expect(body).toEqual({ error: "Username is ambiguous" });
expect(mockState.limitCalls[0]).toBe(2);
});

it("returns submission freshness metadata for the latest submission", async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-03-11T12:00:00.000Z"));
Expand Down
63 changes: 61 additions & 2 deletions packages/frontend/__tests__/lib/getLeaderboard.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,11 @@ const mockState = vi.hoisted(() => {
const gte = vi.fn(() => "gte");
const lte = vi.fn(() => "lte");
const sql = Object.assign(
() => ({
vi.fn((strings: TemplateStringsArray, ...values: unknown[]) => ({
strings: Array.from(strings),
values,
as: () => ({}),
}),
})),
{
raw: vi.fn(),
}
Expand Down Expand Up @@ -81,6 +83,7 @@ const mockState = vi.hoisted(() => {
and.mockClear();
gte.mockClear();
lte.mockClear();
sql.mockClear();
sql.raw.mockClear();
},
setPeriodRows(rows: Array<Record<string, unknown>>) {
Expand All @@ -101,6 +104,24 @@ vi.mock("@/lib/db", () => ({
dailyBreakdown: mockState.tables.dailyBreakdown,
}));

vi.mock("@/lib/db/usernameLookup", () => {
class AmbiguousUsernameError extends Error {}

return {
AmbiguousUsernameError,
USERNAME_LOOKUP_LIMIT: 2,
getSingleUsernameMatch: (rows: readonly unknown[], username: string) => {
if (rows.length > 1) {
throw new AmbiguousUsernameError(`Multiple users match username ${username} case-insensitively`);
}
return rows[0] ?? null;
},
normalizeUsernameCacheKey: (username: string) => username.toLowerCase(),
usernameEqualsIgnoreCase: (username: string) =>
mockState.sql`lower(${mockState.tables.users.username}) = ${username.toLowerCase()}`,
};
});

vi.mock("@/lib/submissionFreshness", async () =>
import("../../src/lib/submissionFreshness")
);
Expand Down Expand Up @@ -294,4 +315,42 @@ describe("period leaderboard data", () => {
},
});
});

it("matches period user rank usernames case-insensitively", async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-03-07T18:45:00Z"));
mockState.setPeriodRows(rows);

const rank = await getUserRank("ALICE", "week", "tokens");

expect(rank).toMatchObject({
rank: 2,
username: "alice",
totalTokens: 250,
totalCost: 3,
});
});

it("rejects ambiguous case-insensitive period user rank matches", async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-03-07T18:45:00Z"));
mockState.setPeriodRows([
...rows,
{
userId: "user-alice-duplicate",
username: "ALICE",
displayName: "Alice Duplicate",
avatarUrl: null,
tokens: 50,
cost: 0.5,
updatedAt: "2026-03-07T11:00:00.000Z",
cliVersion: "1.5.0",
schemaVersion: 1,
},
]);

await expect(getUserRank("alice", "week", "tokens")).rejects.toThrow(
"Multiple users match username alice case-insensitively"
);
});
});
Loading