Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 18 additions & 5 deletions src/middleware/auth.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import type { Context, Next } from "hono";
import { timingSafeEqual, createHash } from "node:crypto";
import { createLogger } from "@percolator/shared";

const logger = createLogger("api:auth");

/**
* C2: API key auth middleware for mutation endpoints.
Expand All @@ -17,29 +20,39 @@ export function requireApiKey() {
}
return next();
}

const provided = c.req.header("x-api-key");
if (!provided) {
logger.warn("Auth failure: missing x-api-key", {
path: c.req.path,
method: c.req.method,
ip: c.req.header("x-forwarded-for")?.split(",")[0]?.trim() ?? "unknown",
});
return c.json({ error: "Unauthorized: invalid or missing x-api-key" }, 401);
}

// Use timing-safe comparison to prevent timing attacks
// Hash both values to ensure equal length for timingSafeEqual
const providedHash = createHash("sha256").update(provided).digest();
const expectedHash = createHash("sha256").update(apiAuthKey).digest();

let isValid = false;
try {
isValid = timingSafeEqual(providedHash, expectedHash);
} catch {
// timingSafeEqual throws if buffers are different lengths (shouldn't happen with hashes)
isValid = false;
}

if (!isValid) {
logger.warn("Auth failure: invalid x-api-key", {
path: c.req.path,
method: c.req.method,
ip: c.req.header("x-forwarded-for")?.split(",")[0]?.trim() ?? "unknown",
});
return c.json({ error: "Unauthorized: invalid or missing x-api-key" }, 401);
}

return next();
};
}
Loading