Compare commits
4
Commits
7852e2f5fe
...
501e717fe9
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
501e717fe9 | ||
|
|
d5ea115d31 | ||
|
|
f762db9ef9 | ||
|
|
62f4861705 |
No files matched your search
+196
-58
@@ -1,84 +1,222 @@
|
|||||||
// @ts-nocheck
|
|
||||||
import { revalidatePath } from "next/cache";
|
|
||||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
import { requirePermissionRateLimited } from "@/lib/admin/guard";
|
|
||||||
import { rcon } from "@/lib/services/rcon";
|
// Mock next/server, next-auth and @/lib/auth before imports
|
||||||
|
vi.mock("next/server", () => ({
|
||||||
|
NextResponse: {
|
||||||
|
json: vi.fn(),
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("next-auth", () => ({
|
||||||
|
default: vi.fn(() => ({
|
||||||
|
handlers: {},
|
||||||
|
auth: vi.fn(),
|
||||||
|
signOut: vi.fn(),
|
||||||
|
})),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/lib/auth", () => ({
|
||||||
|
auth: vi.fn(),
|
||||||
|
handlers: {},
|
||||||
|
signOut: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { Ban, db, User } from "@/lib/db";
|
||||||
|
import { PERMS } from "@/lib/permissions";
|
||||||
import { createBan, liftBan } from "./admin-bans";
|
import { createBan, liftBan } from "./admin-bans";
|
||||||
|
|
||||||
const { selectLimit, insertValues, deleteWhere } = vi.hoisted(() => {
|
// Mock eq from drizzle-orm
|
||||||
const selectLimit = vi.fn();
|
const mockEq = vi.hoisted(() => vi.fn());
|
||||||
const insertValues = vi.fn().mockResolvedValue([{ insertId: 1 }]);
|
vi.mock("drizzle-orm", async (importOriginal) => {
|
||||||
const deleteWhere = vi.fn().mockResolvedValue([{ affectedRows: 1 }]);
|
const original = await importOriginal<typeof import("drizzle-orm")>();
|
||||||
return { selectLimit, insertValues, deleteWhere };
|
return {
|
||||||
|
...original,
|
||||||
|
eq: mockEq,
|
||||||
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
vi.mock("@/lib/admin/guard", () => ({ requirePermissionRateLimited: vi.fn() }));
|
// Mock external services
|
||||||
vi.mock("@/lib/permissions", () => ({ PERMS: { USERS_BAN: "users.ban" } }));
|
const mockRequirePermissionRateLimited = vi.hoisted(() => vi.fn());
|
||||||
vi.mock("@/lib/db", () => ({
|
vi.mock("@/lib/admin/guard", () => ({
|
||||||
db: {
|
requirePermissionRateLimited: mockRequirePermissionRateLimited,
|
||||||
select: vi.fn(() => ({
|
|
||||||
from: vi.fn(() => ({
|
|
||||||
where: vi.fn(() => ({
|
|
||||||
limit: selectLimit,
|
|
||||||
})),
|
|
||||||
})),
|
|
||||||
})),
|
|
||||||
insert: vi.fn(() => ({ values: insertValues })),
|
|
||||||
delete: vi.fn(() => ({ where: deleteWhere })),
|
|
||||||
},
|
|
||||||
Ban: { id: "id", userId: "userId" },
|
|
||||||
User: { id: "id", username: "username" },
|
|
||||||
}));
|
}));
|
||||||
vi.mock("@/lib/services/rcon", () => ({ rcon: { disconnectUser: vi.fn() } }));
|
|
||||||
vi.mock("@/lib/services/staff-activity", () => ({ logStaffActivity: vi.fn() }));
|
|
||||||
vi.mock("next/cache", () => ({ revalidatePath: vi.fn() }));
|
|
||||||
|
|
||||||
const staff = { id: 1, rank: 7, username: "admin" };
|
// Hoisted mocks for internal db functions
|
||||||
const fakeForm = (data: Record<string, string>) => ({
|
const hoistedInsertValues = vi.hoisted(() => vi.fn());
|
||||||
get: (key: string) => data[key] ?? null,
|
const hoistedDeleteWhere = vi.hoisted(() => vi.fn());
|
||||||
|
const hoistedSelectLimit = vi.hoisted(() => vi.fn());
|
||||||
|
const hoistedSelectWhere = vi.hoisted(() =>
|
||||||
|
vi.fn(() => ({ limit: hoistedSelectLimit })),
|
||||||
|
);
|
||||||
|
const hoistedSelectFrom = vi.hoisted(() =>
|
||||||
|
vi.fn(() => ({ where: hoistedSelectWhere })),
|
||||||
|
);
|
||||||
|
|
||||||
|
vi.mock("@/lib/db", () => {
|
||||||
|
return {
|
||||||
|
db: {
|
||||||
|
insert: vi.fn(() => ({ values: hoistedInsertValues })),
|
||||||
|
delete: vi.fn(() => ({ where: hoistedDeleteWhere })),
|
||||||
|
select: vi.fn(() => ({ from: hoistedSelectFrom })),
|
||||||
|
},
|
||||||
|
Ban: { id: "Ban.id", userId: "Ban.userId" },
|
||||||
|
User: { id: "User.id", username: "User.username" },
|
||||||
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const mockRconDisconnectUser = vi.hoisted(() => vi.fn());
|
||||||
|
vi.mock("@/lib/services/rcon", () => ({
|
||||||
|
rcon: {
|
||||||
|
disconnectUser: mockRconDisconnectUser,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
const mockLogStaffActivity = vi.hoisted(() => vi.fn());
|
||||||
|
vi.mock("@/lib/services/staff-activity", () => ({
|
||||||
|
logStaffActivity: mockLogStaffActivity,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const mockRevalidatePath = vi.hoisted(() => vi.fn());
|
||||||
|
vi.mock("next/cache", () => ({
|
||||||
|
revalidatePath: mockRevalidatePath,
|
||||||
|
unstable_cache: (fn: any) => fn,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const mockHeaders = vi.hoisted(() => vi.fn());
|
||||||
|
vi.mock("next/headers", () => ({
|
||||||
|
headers: mockHeaders,
|
||||||
|
}));
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks();
|
vi.clearAllMocks();
|
||||||
vi.mocked(requirePermissionRateLimited).mockResolvedValue(staff as never);
|
mockRequirePermissionRateLimited.mockResolvedValue({ id: 100, rank: 7 });
|
||||||
selectLimit.mockResolvedValue([{ username: "baduser" }]);
|
hoistedInsertValues.mockResolvedValue([{ insertId: 1 }]);
|
||||||
insertValues.mockResolvedValue([{ insertId: 1 }]);
|
hoistedDeleteWhere.mockResolvedValue([{ affectedRows: 1 }]);
|
||||||
deleteWhere.mockResolvedValue([{ affectedRows: 1 }]);
|
hoistedSelectLimit.mockResolvedValue([{ username: "testuser" }]);
|
||||||
|
mockHeaders.mockReturnValue(new Map());
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("createBan", () => {
|
describe("createBan", () => {
|
||||||
it("creates a ban for valid inputs", async () => {
|
it("requires USERS_BAN permission and logs activity", async () => {
|
||||||
await createBan(
|
const formData = new FormData();
|
||||||
fakeForm({
|
formData.append("userId", "1");
|
||||||
userId: "42",
|
formData.append("reason", "Test ban");
|
||||||
reason: "Spam",
|
formData.append("hours", "24");
|
||||||
hours: "24",
|
formData.append("type", "account");
|
||||||
|
|
||||||
|
await createBan(formData);
|
||||||
|
|
||||||
|
expect(mockRequirePermissionRateLimited).toHaveBeenCalledWith(
|
||||||
|
PERMS.USERS_BAN,
|
||||||
|
);
|
||||||
|
expect(db.insert).toHaveBeenCalledWith(Ban);
|
||||||
|
expect(hoistedInsertValues).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
userId: 1,
|
||||||
|
banReason: "Test ban",
|
||||||
|
banExpire: expect.any(Number),
|
||||||
type: "account",
|
type: "account",
|
||||||
}) as unknown as FormData,
|
}),
|
||||||
);
|
);
|
||||||
expect(insertValues).toHaveBeenCalledWith(
|
expect(mockLogStaffActivity).toHaveBeenCalledWith(
|
||||||
expect.objectContaining({ userId: 42, type: "account" }),
|
expect.objectContaining({
|
||||||
|
action: "user_ban",
|
||||||
|
targetId: 1,
|
||||||
|
description: expect.stringContaining("Banned user #1"),
|
||||||
|
}),
|
||||||
);
|
);
|
||||||
expect(rcon.disconnectUser).toHaveBeenCalledWith(42, "baduser");
|
expect(mockRevalidatePath).toHaveBeenCalledWith("/admin/bans");
|
||||||
expect(revalidatePath).toHaveBeenCalledWith("/admin/bans");
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("returns early when userId is invalid", async () => {
|
it("sets permanent ban (expire 0) if hours is 0", async () => {
|
||||||
await createBan(
|
const formData = new FormData();
|
||||||
fakeForm({
|
formData.append("userId", "2");
|
||||||
userId: "0",
|
formData.append("reason", "Permanent ban");
|
||||||
hours: "1",
|
formData.append("hours", "0");
|
||||||
type: "account",
|
formData.append("type", "ip");
|
||||||
}) as unknown as FormData,
|
|
||||||
|
await createBan(formData);
|
||||||
|
|
||||||
|
expect(hoistedInsertValues).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
userId: 2,
|
||||||
|
banExpire: 0,
|
||||||
|
type: "ip",
|
||||||
|
}),
|
||||||
);
|
);
|
||||||
expect(insertValues).not.toHaveBeenCalled();
|
});
|
||||||
|
|
||||||
|
it("aborts when userId is invalid or zero", async () => {
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append("userId", "0");
|
||||||
|
formData.append("reason", "Invalid user");
|
||||||
|
formData.append("hours", "1");
|
||||||
|
formData.append("type", "account");
|
||||||
|
|
||||||
|
await createBan(formData);
|
||||||
|
|
||||||
|
expect(db.insert).not.toHaveBeenCalled();
|
||||||
|
expect(mockLogStaffActivity).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("aborts when ban type is unsupported", async () => {
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append("userId", "10");
|
||||||
|
formData.append("reason", "Invalid type");
|
||||||
|
formData.append("hours", "1");
|
||||||
|
formData.append("type", "invalid_type");
|
||||||
|
|
||||||
|
await createBan(formData);
|
||||||
|
|
||||||
|
expect(db.insert).not.toHaveBeenCalled();
|
||||||
|
expect(mockLogStaffActivity).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("disconnects user via RCON if user found", async () => {
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append("userId", "3");
|
||||||
|
formData.append("type", "account");
|
||||||
|
formData.append("reason", "Test reason");
|
||||||
|
|
||||||
|
hoistedSelectLimit.mockResolvedValueOnce([{ username: "anotheruser" }]);
|
||||||
|
|
||||||
|
await createBan(formData);
|
||||||
|
|
||||||
|
expect(mockRconDisconnectUser).toHaveBeenCalledWith(3, "anotheruser");
|
||||||
|
expect(mockEq).toHaveBeenCalledWith(User.id, 3);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("liftBan", () => {
|
describe("liftBan", () => {
|
||||||
it("deletes ban and revalidates", async () => {
|
it("lifts an existing ban and logs activity", async () => {
|
||||||
await liftBan(fakeForm({ id: "42" }) as unknown as FormData);
|
const formData = new FormData();
|
||||||
expect(deleteWhere).toHaveBeenCalled();
|
formData.append("id", "123");
|
||||||
expect(revalidatePath).toHaveBeenCalledWith("/admin/bans");
|
|
||||||
|
await liftBan(formData);
|
||||||
|
|
||||||
|
expect(mockRequirePermissionRateLimited).toHaveBeenCalledWith(
|
||||||
|
PERMS.USERS_BAN,
|
||||||
|
);
|
||||||
|
expect(db.delete).toHaveBeenCalledWith(Ban);
|
||||||
|
expect(hoistedDeleteWhere).toHaveBeenCalledWith(mockEq(Ban.id, 123));
|
||||||
|
expect(mockLogStaffActivity).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
action: "ban_lift",
|
||||||
|
description: "Lifted ban #123",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(mockRevalidatePath).toHaveBeenCalledWith("/admin/bans");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not delete if ban id is not positive", async () => {
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append("id", "0");
|
||||||
|
|
||||||
|
await liftBan(formData);
|
||||||
|
|
||||||
|
expect(db.delete).not.toHaveBeenCalled();
|
||||||
|
expect(hoistedDeleteWhere).not.toHaveBeenCalled();
|
||||||
|
expect(mockLogStaffActivity).not.toHaveBeenCalled();
|
||||||
|
expect(mockRevalidatePath).toHaveBeenCalledWith("/admin/bans");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -0,0 +1,208 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
// Hoisted mocks
|
||||||
|
const mockRedirect = vi.hoisted(() =>
|
||||||
|
vi.fn((url: string) => {
|
||||||
|
const err = new Error(`NEXT_REDIRECT: ${url}`);
|
||||||
|
// biome-ignore lint/suspicious/noExplicitAny: Next.js redirect signature
|
||||||
|
(err as any).digest = `NEXT_REDIRECT;replace;${url};307;;`;
|
||||||
|
throw err;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
vi.mock("next/navigation", () => ({
|
||||||
|
redirect: mockRedirect,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const mockRevalidatePath = vi.hoisted(() => vi.fn());
|
||||||
|
vi.mock("next/cache", () => ({
|
||||||
|
revalidatePath: mockRevalidatePath,
|
||||||
|
unstable_cache: (fn: unknown) => fn,
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("next/server", () => ({
|
||||||
|
NextResponse: {
|
||||||
|
json: vi.fn(),
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("next-auth", () => ({
|
||||||
|
default: vi.fn(() => ({
|
||||||
|
handlers: {},
|
||||||
|
auth: vi.fn(),
|
||||||
|
signOut: vi.fn(),
|
||||||
|
})),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const mockAuth = vi.hoisted(() => vi.fn());
|
||||||
|
vi.mock("@/lib/auth", () => ({
|
||||||
|
auth: mockAuth,
|
||||||
|
handlers: {},
|
||||||
|
signOut: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const mockRateLimit = vi.hoisted(() => vi.fn());
|
||||||
|
vi.mock("@/lib/rate-limit", () => ({
|
||||||
|
rateLimit: mockRateLimit,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const mockVerifyTotp = vi.hoisted(() => vi.fn());
|
||||||
|
const mockGenerateTotpSecret = vi.hoisted(() => vi.fn());
|
||||||
|
vi.mock("@/lib/auth/totp", () => ({
|
||||||
|
verifyTotp: mockVerifyTotp,
|
||||||
|
generateTotpSecret: mockGenerateTotpSecret,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const mockEncrypt = vi.hoisted(() => vi.fn());
|
||||||
|
const mockDecrypt = vi.hoisted(() => vi.fn());
|
||||||
|
vi.mock("@/lib/auth/laravel-encrypter", () => ({
|
||||||
|
LaravelEncrypter: class {
|
||||||
|
encrypt = mockEncrypt;
|
||||||
|
decrypt = mockDecrypt;
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/env", () => ({
|
||||||
|
env: {
|
||||||
|
APP_KEY: "base64:dGVzdGtleXRlc3RrZXl0ZXN0a2V5dGVzdGtleTEyMw==",
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
const hoistedInsertValues = vi.hoisted(() => vi.fn());
|
||||||
|
const hoistedSelectLimit = vi.hoisted(() => vi.fn());
|
||||||
|
const hoistedSelectWhere = vi.hoisted(() =>
|
||||||
|
vi.fn(() => ({ limit: hoistedSelectLimit })),
|
||||||
|
);
|
||||||
|
const hoistedSelectFrom = vi.hoisted(() =>
|
||||||
|
vi.fn(() => ({ where: hoistedSelectWhere })),
|
||||||
|
);
|
||||||
|
const hoistedUpdateWhere = vi.hoisted(() => vi.fn());
|
||||||
|
const hoistedUpdateSet = vi.hoisted(() =>
|
||||||
|
vi.fn(() => ({ where: hoistedUpdateWhere })),
|
||||||
|
);
|
||||||
|
|
||||||
|
vi.mock("@/lib/db", () => ({
|
||||||
|
db: {
|
||||||
|
select: vi.fn(() => ({ from: hoistedSelectFrom })),
|
||||||
|
insert: vi.fn(() => ({ values: hoistedInsertValues })),
|
||||||
|
update: vi.fn(() => ({ set: hoistedUpdateSet })),
|
||||||
|
},
|
||||||
|
User: {
|
||||||
|
id: "user.id",
|
||||||
|
twoFactorSecret: "user.twoFactorSecret",
|
||||||
|
twoFactorConfirmedAt: "user.twoFactorConfirmedAt",
|
||||||
|
twoFactorRecoveryCodes: "user.twoFactorRecoveryCodes",
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { db, User } from "@/lib/db";
|
||||||
|
import {
|
||||||
|
beginTwoFactor,
|
||||||
|
confirmTwoFactor,
|
||||||
|
disableTwoFactor,
|
||||||
|
} from "./twofactor";
|
||||||
|
|
||||||
|
const fakeForm = (data: Record<string, string>) =>
|
||||||
|
({
|
||||||
|
get: (key: string) => data[key] ?? null,
|
||||||
|
}) as unknown as FormData;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
mockAuth.mockResolvedValue({ user: { id: "42" } });
|
||||||
|
mockRateLimit.mockResolvedValue({ ok: true });
|
||||||
|
mockGenerateTotpSecret.mockReturnValue("JBSWY3DPEHPK3PXP");
|
||||||
|
mockEncrypt.mockReturnValue("encrypted-secret-payload");
|
||||||
|
mockDecrypt.mockReturnValue("JBSWY3DPEHPK3PXP");
|
||||||
|
hoistedUpdateWhere.mockResolvedValue([]);
|
||||||
|
hoistedSelectLimit.mockResolvedValue([
|
||||||
|
{
|
||||||
|
twoFactorSecret: "encrypted-secret-payload",
|
||||||
|
twoFactorRecoveryCodes: JSON.stringify(["CODE-1234", "CODE-5678"]),
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("beginTwoFactor", () => {
|
||||||
|
it("redirects to login if not signed in", async () => {
|
||||||
|
mockAuth.mockResolvedValueOnce(null);
|
||||||
|
await expect(beginTwoFactor()).rejects.toThrow("NEXT_REDIRECT: /login");
|
||||||
|
expect(mockRedirect).toHaveBeenCalledWith("/login");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("generates secret, updates database, and revalidates path", async () => {
|
||||||
|
await beginTwoFactor();
|
||||||
|
expect(mockGenerateTotpSecret).toHaveBeenCalled();
|
||||||
|
expect(mockEncrypt).toHaveBeenCalledWith("JBSWY3DPEHPK3PXP");
|
||||||
|
expect(db.update).toHaveBeenCalledWith(User);
|
||||||
|
expect(hoistedUpdateSet).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
twoFactorSecret: "encrypted-secret-payload",
|
||||||
|
twoFactorConfirmedAt: null,
|
||||||
|
twoFactorRecoveryCodes: expect.any(String),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(mockRevalidatePath).toHaveBeenCalledWith("/settings/2fa");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("confirmTwoFactor", () => {
|
||||||
|
it("redirects on rate limit", async () => {
|
||||||
|
mockRateLimit.mockResolvedValueOnce({ ok: false });
|
||||||
|
await expect(
|
||||||
|
confirmTwoFactor(fakeForm({ code: "123456" })),
|
||||||
|
).rejects.toThrow("NEXT_REDIRECT: /settings/2fa?error=ratelimit");
|
||||||
|
expect(mockRedirect).toHaveBeenCalledWith("/settings/2fa?error=ratelimit");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("redirects on invalid TOTP and recovery code", async () => {
|
||||||
|
mockVerifyTotp.mockReturnValueOnce(false);
|
||||||
|
await expect(
|
||||||
|
confirmTwoFactor(fakeForm({ code: "INVALID" })),
|
||||||
|
).rejects.toThrow("NEXT_REDIRECT: /settings/2fa?error=badcode");
|
||||||
|
expect(mockRedirect).toHaveBeenCalledWith("/settings/2fa?error=badcode");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("confirms when TOTP code is valid", async () => {
|
||||||
|
mockVerifyTotp.mockReturnValueOnce(true);
|
||||||
|
await expect(
|
||||||
|
confirmTwoFactor(fakeForm({ code: "123456" })),
|
||||||
|
).rejects.toThrow("NEXT_REDIRECT: /settings/2fa?enabled=1");
|
||||||
|
expect(hoistedUpdateSet).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
twoFactorConfirmedAt: expect.any(Date),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(mockRedirect).toHaveBeenCalledWith("/settings/2fa?enabled=1");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("confirms when recovery code is valid", async () => {
|
||||||
|
mockVerifyTotp.mockReturnValueOnce(false);
|
||||||
|
await expect(
|
||||||
|
confirmTwoFactor(fakeForm({ code: "CODE-1234" })),
|
||||||
|
).rejects.toThrow("NEXT_REDIRECT: /settings/2fa?enabled=1");
|
||||||
|
expect(mockRedirect).toHaveBeenCalledWith("/settings/2fa?enabled=1");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("disableTwoFactor", () => {
|
||||||
|
it("redirects on invalid code", async () => {
|
||||||
|
mockVerifyTotp.mockReturnValueOnce(false);
|
||||||
|
await expect(
|
||||||
|
disableTwoFactor(fakeForm({ code: "INVALID" })),
|
||||||
|
).rejects.toThrow("NEXT_REDIRECT: /settings/2fa?error=badcode");
|
||||||
|
expect(mockRedirect).toHaveBeenCalledWith("/settings/2fa?error=badcode");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("clears two-factor secret and recovery codes on valid verification", async () => {
|
||||||
|
mockVerifyTotp.mockReturnValueOnce(true);
|
||||||
|
await expect(
|
||||||
|
disableTwoFactor(fakeForm({ code: "123456" })),
|
||||||
|
).rejects.toThrow("NEXT_REDIRECT: /settings/2fa?disabled=1");
|
||||||
|
expect(hoistedUpdateSet).toHaveBeenCalledWith({
|
||||||
|
twoFactorSecret: null,
|
||||||
|
twoFactorRecoveryCodes: null,
|
||||||
|
twoFactorConfirmedAt: null,
|
||||||
|
});
|
||||||
|
expect(mockRedirect).toHaveBeenCalledWith("/settings/2fa?disabled=1");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,291 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
vi.mock("next/server", () => ({
|
||||||
|
NextResponse: { json: vi.fn() },
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("next-auth", () => ({
|
||||||
|
default: vi.fn(() => ({ handlers: {}, auth: vi.fn(), signOut: vi.fn() })),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/lib/auth", () => ({
|
||||||
|
auth: vi.fn(),
|
||||||
|
invalidateLoginCache: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/lib/auth/password", () => ({
|
||||||
|
hashPassword: vi.fn().mockResolvedValue("hashed_pass_123"),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const { insertValues, deleteWhere, updateSet, selectLimit } = vi.hoisted(
|
||||||
|
() => ({
|
||||||
|
insertValues: vi.fn(),
|
||||||
|
deleteWhere: vi.fn(),
|
||||||
|
updateSet: vi.fn(),
|
||||||
|
selectLimit: vi.fn(),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
vi.mock("@/lib/db", () => ({
|
||||||
|
db: {
|
||||||
|
insert: vi.fn(() => ({
|
||||||
|
values: insertValues,
|
||||||
|
onDuplicateKeyUpdate: vi.fn().mockResolvedValue([]),
|
||||||
|
})),
|
||||||
|
update: vi.fn(() => ({ set: vi.fn(() => ({ where: updateSet })) })),
|
||||||
|
delete: vi.fn(() => ({ where: deleteWhere })),
|
||||||
|
select: vi.fn(() => ({
|
||||||
|
from: vi.fn(() => ({
|
||||||
|
where: vi.fn(() => ({ limit: selectLimit })),
|
||||||
|
})),
|
||||||
|
})),
|
||||||
|
transaction: vi.fn(async (cb: (tx: any) => Promise<any>) => {
|
||||||
|
const mockTx = {
|
||||||
|
insert: vi.fn(() => ({
|
||||||
|
values: vi.fn().mockResolvedValue([{ insertId: 42n }]),
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
return cb(mockTx);
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
User: { id: "User.id", username: "User.username", rank: "User.rank" },
|
||||||
|
Ban: { userId: "Ban.userId" },
|
||||||
|
UsersSettings: {},
|
||||||
|
UsersCurrency: {},
|
||||||
|
UsersBadges: { id: "UsersBadges.id" },
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/lib/permissions", () => ({
|
||||||
|
PERMS: {
|
||||||
|
USERS_EDIT: "users.edit",
|
||||||
|
USERS_BAN: "users.ban",
|
||||||
|
USERS_RESET_PASSWORD: "users.reset_password",
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/lib/safe-action", () => ({
|
||||||
|
adminAction: vi.fn((_o: unknown, f: (...args: unknown[]) => unknown) => f),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/lib/safe-action-shared", () => ({
|
||||||
|
ActionError: class ActionError extends Error {},
|
||||||
|
actionOk: vi.fn((res) => ({ ok: true, data: res })),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/lib/services/audit", () => ({
|
||||||
|
logAudit: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/lib/services/webhook", () => ({
|
||||||
|
notify: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/lib/services/rcon", () => ({
|
||||||
|
rcon: {
|
||||||
|
disconnectUser: vi.fn().mockResolvedValue(true),
|
||||||
|
giveBadge: vi.fn().mockResolvedValue(true),
|
||||||
|
removeBadge: vi.fn().mockResolvedValue(true),
|
||||||
|
alertUser: vi.fn().mockResolvedValue(true),
|
||||||
|
muteUser: vi.fn().mockResolvedValue(true),
|
||||||
|
unmuteUser: vi.fn().mockResolvedValue(true),
|
||||||
|
giveCredits: vi.fn().mockResolvedValue(true),
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { ActionError } from "@/lib/safe-action-shared";
|
||||||
|
import { logAudit } from "@/lib/services/audit";
|
||||||
|
import { rcon } from "@/lib/services/rcon";
|
||||||
|
import {
|
||||||
|
alertUser,
|
||||||
|
banUser,
|
||||||
|
createUser,
|
||||||
|
disconnectUser,
|
||||||
|
giveBadge,
|
||||||
|
muteUser,
|
||||||
|
removeBadge,
|
||||||
|
resetPassword,
|
||||||
|
unbanUser,
|
||||||
|
unmuteUser,
|
||||||
|
} from "./users";
|
||||||
|
|
||||||
|
const mockContext = (data: any, rank = 7) => ({
|
||||||
|
data,
|
||||||
|
session: {
|
||||||
|
user: {
|
||||||
|
id: 1,
|
||||||
|
username: "superadmin",
|
||||||
|
rank,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
selectLimit.mockResolvedValue([
|
||||||
|
{ username: "targetuser", rank: 1, mail: "[email protected]" },
|
||||||
|
]);
|
||||||
|
deleteWhere.mockResolvedValue([{ affectedRows: 1 }]);
|
||||||
|
updateSet.mockResolvedValue([{ affectedRows: 1 }]);
|
||||||
|
insertValues.mockResolvedValue([{ insertId: 100n }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("createUser action", () => {
|
||||||
|
it("creates a user successfully and logs audit", async () => {
|
||||||
|
const ctx = mockContext({
|
||||||
|
username: "newuser",
|
||||||
|
mail: "[email protected]",
|
||||||
|
password: "password123",
|
||||||
|
rank: 1,
|
||||||
|
motto: "Hello world",
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await (createUser as any)(ctx);
|
||||||
|
|
||||||
|
expect(res).toEqual({ ok: true, data: { id: 42, username: "newuser" } });
|
||||||
|
expect(logAudit).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
action: "user_create",
|
||||||
|
targetId: 42,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("throws error if admin assigns rank equal or higher than their own", async () => {
|
||||||
|
const ctx = mockContext(
|
||||||
|
{
|
||||||
|
username: "moduser",
|
||||||
|
mail: "[email protected]",
|
||||||
|
password: "password123",
|
||||||
|
rank: 5,
|
||||||
|
},
|
||||||
|
5, // admin with rank 5 trying to set rank 5
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect((createUser as any)(ctx)).rejects.toThrow(ActionError);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("banUser & unbanUser actions", () => {
|
||||||
|
it("bans target user, disconnects via RCON, and logs audit", async () => {
|
||||||
|
const ctx = mockContext({
|
||||||
|
userId: 10,
|
||||||
|
reason: "Rule breaking",
|
||||||
|
duration: 24,
|
||||||
|
type: "account",
|
||||||
|
});
|
||||||
|
|
||||||
|
await (banUser as any)(ctx);
|
||||||
|
|
||||||
|
expect(rcon.disconnectUser).toHaveBeenCalledWith(10);
|
||||||
|
expect(logAudit).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
action: "ban",
|
||||||
|
targetId: 10,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("unbans target user and logs audit", async () => {
|
||||||
|
const ctx = mockContext({ userId: 10 });
|
||||||
|
|
||||||
|
await (unbanUser as any)(ctx);
|
||||||
|
|
||||||
|
expect(logAudit).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
action: "unban",
|
||||||
|
targetId: 10,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("giveBadge & removeBadge actions", () => {
|
||||||
|
it("gives badge if user doesn't have it yet", async () => {
|
||||||
|
selectLimit.mockResolvedValueOnce([
|
||||||
|
{ username: "targetuser", rank: 1, mail: "[email protected]" },
|
||||||
|
]); // guardRank
|
||||||
|
selectLimit.mockResolvedValueOnce([]); // existing badge check (none)
|
||||||
|
|
||||||
|
const ctx = mockContext({ userId: 10, badgeCode: "ADM" });
|
||||||
|
await (giveBadge as any)(ctx);
|
||||||
|
|
||||||
|
expect(rcon.giveBadge).toHaveBeenCalledWith(10, "ADM");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("throws ActionError if user already has the badge", async () => {
|
||||||
|
selectLimit.mockResolvedValueOnce([
|
||||||
|
{ username: "targetuser", rank: 1, mail: "[email protected]" },
|
||||||
|
]); // guardRank
|
||||||
|
selectLimit.mockResolvedValueOnce([{ id: 1 }]); // existing badge check (found)
|
||||||
|
|
||||||
|
const ctx = mockContext({ userId: 10, badgeCode: "ADM" });
|
||||||
|
await expect((giveBadge as any)(ctx)).rejects.toThrow(
|
||||||
|
"Badge already assigned",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("removes badge if user has it", async () => {
|
||||||
|
selectLimit.mockResolvedValueOnce([
|
||||||
|
{ username: "targetuser", rank: 1, mail: "[email protected]" },
|
||||||
|
]); // guardRank
|
||||||
|
selectLimit.mockResolvedValueOnce([{ id: 99 }]); // existing badge check (found)
|
||||||
|
|
||||||
|
const ctx = mockContext({ userId: 10, badgeCode: "ADM" });
|
||||||
|
await (removeBadge as any)(ctx);
|
||||||
|
|
||||||
|
expect(rcon.removeBadge).toHaveBeenCalledWith(10, "ADM");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("resetPassword action", () => {
|
||||||
|
it("resets password, invalidates login cache and logs audit", async () => {
|
||||||
|
const ctx = mockContext({ userId: 10 });
|
||||||
|
const res = await (resetPassword as any)(ctx);
|
||||||
|
|
||||||
|
expect(res.data).toHaveProperty("newPassword");
|
||||||
|
expect(logAudit).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
action: "reset_password",
|
||||||
|
targetId: 10,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("moderation tools (disconnect, alert, mute, unmute)", () => {
|
||||||
|
it("disconnects user via RCON", async () => {
|
||||||
|
const ctx = mockContext({ userId: 10 });
|
||||||
|
await (disconnectUser as any)(ctx);
|
||||||
|
expect(rcon.disconnectUser).toHaveBeenCalledWith(10);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("alerts user via RCON", async () => {
|
||||||
|
const ctx = mockContext({ userId: 10, message: "Hello user!" });
|
||||||
|
await (alertUser as any)(ctx);
|
||||||
|
expect(rcon.alertUser).toHaveBeenCalledWith(10, "Hello user!");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("mutes user via RCON and logs audit", async () => {
|
||||||
|
const ctx = mockContext({ userId: 10, duration: 600 });
|
||||||
|
await (muteUser as any)(ctx);
|
||||||
|
expect(rcon.muteUser).toHaveBeenCalledWith(10, 600);
|
||||||
|
expect(logAudit).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
action: "user_mute",
|
||||||
|
targetId: 10,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("unmutes user via RCON and logs audit", async () => {
|
||||||
|
const ctx = mockContext({ userId: 10 });
|
||||||
|
await (unmuteUser as any)(ctx);
|
||||||
|
expect(rcon.unmuteUser).toHaveBeenCalledWith(10);
|
||||||
|
expect(logAudit).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
action: "user_unmute",
|
||||||
|
targetId: 10,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
vi.mock("next/server", () => ({
|
||||||
|
NextResponse: {
|
||||||
|
json: vi.fn(),
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("next-auth", () => ({
|
||||||
|
default: vi.fn(() => ({
|
||||||
|
handlers: {},
|
||||||
|
auth: vi.fn(),
|
||||||
|
signOut: vi.fn(),
|
||||||
|
})),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/lib/auth", () => ({
|
||||||
|
auth: vi.fn(),
|
||||||
|
handlers: {},
|
||||||
|
signOut: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const mockAuth = vi.hoisted(() => vi.fn());
|
||||||
|
vi.mock("@/lib/auth", () => ({
|
||||||
|
auth: mockAuth,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const hoistedInsertValues = vi.hoisted(() => vi.fn());
|
||||||
|
const hoistedDeleteWhere = vi.hoisted(() => vi.fn());
|
||||||
|
const hoistedSelectLimit = vi.hoisted(() => vi.fn());
|
||||||
|
const hoistedSelectWhere = vi.hoisted(() =>
|
||||||
|
vi.fn(() => ({ limit: hoistedSelectLimit })),
|
||||||
|
);
|
||||||
|
const hoistedSelectFrom = vi.hoisted(() =>
|
||||||
|
vi.fn(() => ({ where: hoistedSelectWhere })),
|
||||||
|
);
|
||||||
|
const hoistedUpdateWhere = vi.hoisted(() => vi.fn());
|
||||||
|
const hoistedUpdateSetObj = vi.hoisted(() => ({
|
||||||
|
set: vi.fn(() => ({ where: hoistedUpdateWhere })),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/lib/db", () => ({
|
||||||
|
db: {
|
||||||
|
select: vi.fn(() => ({ from: hoistedSelectFrom })),
|
||||||
|
insert: vi.fn(() => ({ values: hoistedInsertValues })),
|
||||||
|
update: vi.fn(() => hoistedUpdateSetObj),
|
||||||
|
delete: vi.fn(() => ({ where: hoistedDeleteWhere })),
|
||||||
|
},
|
||||||
|
WebsiteShopVouchers: {
|
||||||
|
id: "voucher.id",
|
||||||
|
code: "voucher.code",
|
||||||
|
amount: "voucher.amount",
|
||||||
|
maxUses: "voucher.maxUses",
|
||||||
|
useCount: "voucher.useCount",
|
||||||
|
expiresAt: "voucher.expiresAt",
|
||||||
|
},
|
||||||
|
WebsiteUsedShopVouchers: {
|
||||||
|
id: "used.id",
|
||||||
|
userId: "used.userId",
|
||||||
|
voucherId: "used.voucherId",
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
const mockSendCurrency = vi.hoisted(() => vi.fn());
|
||||||
|
vi.mock("@/lib/services/send-currency", () => ({
|
||||||
|
currencyDb: {},
|
||||||
|
sendCurrency: mockSendCurrency,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const mockRateLimit = vi.hoisted(() => vi.fn());
|
||||||
|
vi.mock("@/lib/rate-limit", () => ({
|
||||||
|
clientIp: vi.fn().mockResolvedValue("127.0.0.1"),
|
||||||
|
rateLimit: mockRateLimit,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const mockRevalidatePath = vi.hoisted(() => vi.fn());
|
||||||
|
vi.mock("next/cache", () => ({
|
||||||
|
revalidatePath: mockRevalidatePath,
|
||||||
|
unstable_cache: (fn: any) => fn,
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { redeem } from "./voucher";
|
||||||
|
|
||||||
|
const fakeForm = (data: Record<string, string>) =>
|
||||||
|
({
|
||||||
|
get: (key: string) => data[key] ?? null,
|
||||||
|
}) as unknown as FormData;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
mockAuth.mockResolvedValue({ user: { id: "1" } });
|
||||||
|
mockRateLimit.mockResolvedValue({ ok: true });
|
||||||
|
hoistedSelectLimit.mockResolvedValue([]);
|
||||||
|
hoistedInsertValues.mockResolvedValue([]);
|
||||||
|
hoistedUpdateWhere.mockResolvedValue([]);
|
||||||
|
mockSendCurrency.mockResolvedValue(undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("redeem action", () => {
|
||||||
|
it("rejects if user is not signed in", async () => {
|
||||||
|
mockAuth.mockResolvedValueOnce(null);
|
||||||
|
const result = await redeem(null, fakeForm({ code: "TEST" }));
|
||||||
|
expect(result).toEqual({
|
||||||
|
ok: false,
|
||||||
|
message: "You must be signed in to redeem a voucher.",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects if rate limited", async () => {
|
||||||
|
mockRateLimit.mockResolvedValueOnce({ ok: false });
|
||||||
|
const result = await redeem(null, fakeForm({ code: "TEST" }));
|
||||||
|
expect(result?.ok).toBe(false);
|
||||||
|
expect(result?.message).toContain("too fast");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects empty codes", async () => {
|
||||||
|
const result = await redeem(null, fakeForm({ code: "" }));
|
||||||
|
expect(result).toEqual({
|
||||||
|
ok: false,
|
||||||
|
message: "Please enter a voucher code.",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects if voucher does not exist or is expired", async () => {
|
||||||
|
hoistedSelectLimit.mockResolvedValueOnce([]); // voucher query
|
||||||
|
const result = await redeem(null, fakeForm({ code: "INVALID" }));
|
||||||
|
expect(result).toEqual({
|
||||||
|
ok: false,
|
||||||
|
message: "No active voucher with the given code was found.",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("successfully redeems a valid voucher", async () => {
|
||||||
|
const futureDate = new Date(Date.now() + 86400000);
|
||||||
|
// 1st call: voucher query, 2nd call: already used check, 3rd & 4th calls: bump useCount / check maxUses
|
||||||
|
hoistedSelectLimit
|
||||||
|
.mockResolvedValueOnce([
|
||||||
|
{
|
||||||
|
id: 10n,
|
||||||
|
amount: 500,
|
||||||
|
maxUses: 10,
|
||||||
|
useCount: 2,
|
||||||
|
expiresAt: futureDate,
|
||||||
|
},
|
||||||
|
])
|
||||||
|
.mockResolvedValueOnce([]) // not used yet
|
||||||
|
.mockResolvedValueOnce([{ maxUses: 10, useCount: 3 }]); // updated count
|
||||||
|
|
||||||
|
const result = await redeem(null, fakeForm({ code: "VALIDCODE" }));
|
||||||
|
expect(result?.ok).toBe(true);
|
||||||
|
expect(result?.message).toContain("500 credits");
|
||||||
|
expect(mockSendCurrency).toHaveBeenCalledWith(
|
||||||
|
expect.any(Object),
|
||||||
|
1,
|
||||||
|
"credits",
|
||||||
|
500,
|
||||||
|
);
|
||||||
|
expect(db.insert).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user