WFDASH-WEBAPP/src/lib/server/pos-auth.test.ts
Dave af7a74b4fa feat(pos): add assertPosAuth for POS_API_KEY-gated routes
Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-31 01:30:52 +02:00

53 lines
1.6 KiB
TypeScript

import { describe, it, expect, beforeEach, afterEach } from "vitest";
import { NextRequest } from "next/server";
import { assertPosAuth } from "./pos-auth";
describe("assertPosAuth", () => {
const ORIGINAL_KEY = process.env.POS_API_KEY;
beforeEach(() => {
process.env.POS_API_KEY = "test-pos-secret";
});
afterEach(() => {
if (ORIGINAL_KEY === undefined) {
delete process.env.POS_API_KEY;
} else {
process.env.POS_API_KEY = ORIGINAL_KEY;
}
});
function reqWith(authHeader: string | null) {
const headers: Record<string, string> = {};
if (authHeader !== null) headers.authorization = authHeader;
return new NextRequest("http://localhost/api/v1/pos/catalog", { headers });
}
it("throws when POS_API_KEY env var is missing", () => {
delete process.env.POS_API_KEY;
expect(() => assertPosAuth(reqWith("Bearer test-pos-secret"))).toThrow(
/POS_API_KEY is not configured/
);
});
it("accepts a matching bearer token", () => {
expect(() => assertPosAuth(reqWith("Bearer test-pos-secret"))).not.toThrow();
});
it("rejects a wrong bearer token", () => {
expect(() => assertPosAuth(reqWith("Bearer wrong"))).toThrow(/Unauthorized/);
});
it("rejects a request with no Authorization header", () => {
expect(() => assertPosAuth(reqWith(null))).toThrow(/Unauthorized/);
});
it("tags the thrown error with status 401", () => {
try {
assertPosAuth(reqWith("Bearer wrong"));
throw new Error("expected to throw");
} catch (err) {
expect((err as Error & { status?: number }).status).toBe(401);
}
});
});