import { Hono } from "jsr:@hono/hono@4"; import { assertEquals } from "jsr:@std/assert"; import { createAuthMiddleware } from "./hono.ts"; import { stub } from "jsr:@std/testing/mock"; import { AuthSdk } from "./mod.ts"; type Variables = { userId: string; }; Deno.test("AuthMiddleware - Authorized request sets userId and calls next", async () => { const sdk = new AuthSdk({ authApiUrl: "http://localhost" }); const requireAuthStub = stub( sdk, "requireAuth", () => Promise.resolve("test-user-id"), ); const app = new Hono<{ Variables: Variables }>(); app.use("*", createAuthMiddleware(sdk)); app.get("/", (c) => c.text(`User: ${c.get("userId")}`)); const req = new Request("http://localhost/", { headers: { "Authorization": "Bearer valid-token", }, }); const res = await app.request(req); assertEquals(res.status, 200); const text = await res.text(); assertEquals(text, "User: test-user-id"); requireAuthStub.restore(); }); Deno.test("AuthMiddleware - Unauthorized request (missing token)", async () => { const sdk = new AuthSdk({ authApiUrl: "http://localhost" }); const requireAuthStub = stub( sdk, "requireAuth", () => Promise.reject(new Error("Unauthorized")), ); const app = new Hono<{ Variables: Variables }>(); app.use("*", createAuthMiddleware(sdk)); app.get("/", (c) => c.text(`User: ${c.get("userId")}`)); const req = new Request("http://localhost/"); const res = await app.request(req); assertEquals(res.status, 401); const json = await res.json(); assertEquals(json, { error: "Unauthorized" }); requireAuthStub.restore(); }); Deno.test("AuthMiddleware - Unauthorized request (invalid token)", async () => { const sdk = new AuthSdk({ authApiUrl: "http://localhost" }); const requireAuthStub = stub( sdk, "requireAuth", () => Promise.reject(new Error("Unauthorized")), ); const app = new Hono<{ Variables: Variables }>(); app.use("*", createAuthMiddleware(sdk)); app.get("/", (c) => c.text(`User: ${c.get("userId")}`)); const req = new Request("http://localhost/", { headers: { "Authorization": "Bearer invalid-token", }, }); const res = await app.request(req); assertEquals(res.status, 401); const json = await res.json(); assertEquals(json, { error: "Unauthorized" }); requireAuthStub.restore(); });