import type { MiddlewareHandler } from 'hono'; import { auth } from '@/modules/auth/auth'; import type { BackendEnv } from './env'; import { problemJson, unauthorizedProblem } from './problem-details'; export const sessionAuthMiddleware: MiddlewareHandler = async (c, next) => { if (isPublicApiRequest(c.req.method, c.req.path)) { await next(); return; } const session = await auth.api.getSession({ headers: c.req.raw.headers }); if (!session) { return problemJson(c, unauthorizedProblem(c.req.path)); } c.set('user', session.user); c.set('session', session.session); await next(); }; export function isPublicApiRequest(method: string, path: string): boolean { if (method === 'OPTIONS') { return true; } const normalizedPath = normalizePath(path); // Absence notice sent with the attendee's personal token (no session). if (method === 'GET' && normalizedPath === '/api/v1/classes/absence') { return true; } if (method === 'POST' && normalizedPath === '/api/v1/classes/notify-absence') { return true; } // WhatsApp provider webhooks: no session, authenticated by their HMAC signature. if ( method === 'POST' && (normalizedPath === '/api/v1/whatsapp/webhooks/openwa' || normalizedPath === '/api/v1/whatsapp/webhooks/kapso') ) { return true; } // Mercado Pago notifications about Pro subscriptions, one URL per country: // no session, authenticated by Mercado Pago's `x-signature`. if (method === 'POST' && /^\/api\/v1\/billing\/webhooks\/mp\/[a-z]{2}$/i.test(normalizedPath)) { return true; } // Stripe notifications about Pro subscriptions: authenticated by `Stripe-Signature`. if (method === 'POST' && normalizedPath === '/api/v1/billing/webhooks/stripe') { return true; } return ( normalizedPath === '/api/v1/health' || matchesPublicPrefix(normalizedPath, '/api/v1/auth') || matchesPublicPrefix(normalizedPath, '/api/auth') || matchesPublicPrefix(normalizedPath, '/api/v1/invitations') // Student app: its own cookie and middleware (modules/student-portal), never // the teacher's session. || matchesPublicPrefix(normalizedPath, '/api/v1/student-portal') ); } function matchesPublicPrefix(path: string, prefix: string): boolean { return path === prefix || path.startsWith(`${prefix}/`); } function normalizePath(path: string): string { const withoutQuery = path.split('?')[0]?.split('#')[0] ?? path; return withoutQuery.length > 1 && withoutQuery.endsWith('/') ? withoutQuery.slice(0, -1) : withoutQuery; }