Files
elysium/apps/api/test/middleware/auth.spec.ts
T
hikari 2bc47b79aa
Security Scan and Upload / Security & DefectDojo Upload (push) Successful in 1m4s
CI / Lint, Build & Test (push) Successful in 1m11s
fix: suppress expired-token log noise and redirect expired sessions to login (#241)
## Summary

- **Server**: `authMiddleware` no longer calls `logger.error` for expired tokens — expiry is expected behaviour, not an error. Only tampered signatures and malformed tokens (genuinely suspicious) still log.
- **Client**: `fetchJson` now handles 401 responses by clearing `elysium_token` and `elysium_save_signature` from localStorage and redirecting to `/`. Players whose 30-day token has expired will see the login page instead of a stuck "Invalid or expired token" error screen with no recovery path.

Closes #241

 This PR was created with help from Hikari~ 🌸

Reviewed-on: #241
Co-authored-by: Hikari <hikari@nhcarrigan.com>
Co-committed-by: Hikari <hikari@nhcarrigan.com>
2026-04-06 20:17:28 -07:00

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();
});
});