generated from nhcarrigan/template
d5284ff78c
- authMiddleware no longer logs token expiry as an error; only tampered or malformed tokens (genuinely suspicious) trigger logger.error - fetchJson clears elysium_token and elysium_save_signature from localStorage and redirects to / on any 401, so players with expired sessions see the login page instead of a stuck error screen
101 lines
3.8 KiB
TypeScript
101 lines
3.8 KiB
TypeScript
/* eslint-disable max-lines-per-function -- Test suites naturally have many cases */
|
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { Hono } from "hono";
|
|
|
|
vi.mock("../../src/services/jwt.js", () => ({
|
|
verifyToken: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("../../src/services/logger.js", () => ({
|
|
logger: {
|
|
error: vi.fn().mockResolvedValue(undefined),
|
|
},
|
|
}));
|
|
|
|
describe("authMiddleware", () => {
|
|
beforeEach(() => {
|
|
vi.resetModules();
|
|
vi.clearAllMocks();
|
|
});
|
|
|
|
const makeApp = async () => {
|
|
const { authMiddleware } = await import("../../src/middleware/auth.js");
|
|
const { verifyToken } = await import("../../src/services/jwt.js");
|
|
const { logger } = await import("../../src/services/logger.js");
|
|
const app = new Hono<{ Variables: { discordId: string } }>();
|
|
app.use("*", authMiddleware);
|
|
app.get("/test", (c) => c.json({ discordId: c.get("discordId") }));
|
|
return { app, logger, verifyToken };
|
|
};
|
|
|
|
it("returns 401 when Authorization header is missing", async () => {
|
|
const { app } = await makeApp();
|
|
const res = await app.fetch(new Request("http://localhost/test"));
|
|
expect(res.status).toBe(401);
|
|
});
|
|
|
|
it("returns 401 when Authorization header does not start with Bearer", async () => {
|
|
const { app } = await makeApp();
|
|
const res = await app.fetch(new Request("http://localhost/test", {
|
|
headers: { Authorization: "Basic abc123" },
|
|
}));
|
|
expect(res.status).toBe(401);
|
|
});
|
|
|
|
it("sets discordId in context when token is valid", async () => {
|
|
const { app, verifyToken } = await makeApp();
|
|
vi.mocked(verifyToken).mockReturnValueOnce({ discordId: "user_123", iat: 0, exp: 9999999999 });
|
|
const res = await app.fetch(new Request("http://localhost/test", {
|
|
headers: { Authorization: "Bearer valid_token" },
|
|
}));
|
|
expect(res.status).toBe(200);
|
|
const body = await res.json() as { discordId: string };
|
|
expect(body.discordId).toBe("user_123");
|
|
});
|
|
|
|
it("returns 401 and logs when verifyToken throws a non-expiry error", async () => {
|
|
const { app, logger, verifyToken } = await makeApp();
|
|
vi.mocked(verifyToken).mockImplementationOnce(() => {
|
|
throw new Error("Invalid token");
|
|
});
|
|
const res = await app.fetch(new Request("http://localhost/test", {
|
|
headers: { Authorization: "Bearer bad_token" },
|
|
}));
|
|
expect(res.status).toBe(401);
|
|
/* eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- logger mock requires cast */
|
|
expect((logger.error as ReturnType<typeof vi.fn>)).toHaveBeenCalledWith(
|
|
"auth_middleware",
|
|
expect.any(Error),
|
|
);
|
|
});
|
|
|
|
it("returns 401 and logs when verifyToken throws a non-Error value", async () => {
|
|
const { app, logger, verifyToken } = await makeApp();
|
|
vi.mocked(verifyToken).mockImplementationOnce(() => {
|
|
throw "raw string error";
|
|
});
|
|
const res = await app.fetch(new Request("http://localhost/test", {
|
|
headers: { Authorization: "Bearer bad_token" },
|
|
}));
|
|
expect(res.status).toBe(401);
|
|
/* eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- logger mock requires cast */
|
|
expect((logger.error as ReturnType<typeof vi.fn>)).toHaveBeenCalledWith(
|
|
"auth_middleware",
|
|
expect.any(Error),
|
|
);
|
|
});
|
|
|
|
it("returns 401 without logging when token has expired", async () => {
|
|
const { app, logger, verifyToken } = await makeApp();
|
|
vi.mocked(verifyToken).mockImplementationOnce(() => {
|
|
throw new Error("Token has expired");
|
|
});
|
|
const res = await app.fetch(new Request("http://localhost/test", {
|
|
headers: { Authorization: "Bearer expired_token" },
|
|
}));
|
|
expect(res.status).toBe(401);
|
|
/* eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- logger mock requires cast */
|
|
expect((logger.error as ReturnType<typeof vi.fn>)).not.toHaveBeenCalled();
|
|
});
|
|
});
|