2025-12-02 09:54:38 +01:00
|
|
|
import { Context, Next } from 'hono';
|
|
|
|
|
|
|
|
|
|
import { env } from '@api/config/env';
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Middleware to authenticate requests using API key
|
|
|
|
|
* Checks for Authorization: Bearer <api-key> header
|
2026-03-09 11:18:22 +01:00
|
|
|
* Used for server-to-server communication (webhooks, dashboard SSR, etc.)
|
2025-12-02 09:54:38 +01:00
|
|
|
*/
|
|
|
|
|
export const apiKeyMiddleware = async (c: Context, next: Next) => {
|
|
|
|
|
try {
|
|
|
|
|
const authHeader = c.req.header('Authorization');
|
|
|
|
|
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
|
|
|
|
return c.json(
|
|
|
|
|
{
|
|
|
|
|
success: false,
|
|
|
|
|
message: 'Unauthorized: Missing or invalid API key'
|
|
|
|
|
},
|
|
|
|
|
401
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const apiKey = authHeader.replace('Bearer ', '').trim();
|
2026-03-09 11:18:22 +01:00
|
|
|
const expectedApiKey = env.PRIVATE_SERVER_KEY;
|
2025-12-02 09:54:38 +01:00
|
|
|
|
|
|
|
|
if (!expectedApiKey) {
|
2026-03-09 11:18:22 +01:00
|
|
|
console.error('PRIVATE_SERVER_KEY not configured in environment');
|
2025-12-02 09:54:38 +01:00
|
|
|
return c.json(
|
|
|
|
|
{
|
|
|
|
|
success: false,
|
|
|
|
|
message: 'Server configuration error'
|
|
|
|
|
},
|
|
|
|
|
500
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (apiKey !== expectedApiKey) {
|
|
|
|
|
return c.json(
|
|
|
|
|
{
|
|
|
|
|
success: false,
|
|
|
|
|
message: 'Unauthorized: Invalid API key'
|
|
|
|
|
},
|
|
|
|
|
401
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// API key is valid, continue
|
|
|
|
|
await next();
|
|
|
|
|
} catch (error) {
|
|
|
|
|
return c.json(
|
|
|
|
|
{
|
|
|
|
|
success: false,
|
|
|
|
|
message: 'Unauthorized'
|
|
|
|
|
},
|
|
|
|
|
401
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
};
|