import { Middleware } from 'http-kernel/Types/mod.ts'; import { Env } from './env.ts'; /** * Middleware that checks for a valid API key via form param. * Also stores the body in ctx.state.body for later use. */ export const authMiddleware: Middleware = async (ctx, next) => { const contentType = ctx.req.headers.get('content-type') || ''; if (contentType.includes('application/x-www-form-urlencoded')) { const bodyBuffer = await ctx.req.arrayBuffer(); ctx.state.body = new Uint8Array(bodyBuffer); const text = new TextDecoder().decode(ctx.state.body as Uint8Array); const params = new URLSearchParams(text); const key = params.get('apiKey'); if (!key || !Env.apiKeys.includes(key)) { return new Response('Forbidden – Invalid API key', { status: 403 }); } } else { return new Response('Unsupported content type', { status: 415 }); } return await next(); }; export { authMiddleware as ltProxyAuth };