/** * Auth Middleware * * Wraps user-provided Hono auth middleware to skip public paths. */ import type { Context, Next, MiddlewareHandler } from "hono"; import type { AuthConfig } from "../types.ts"; const DEFAULT_PUBLIC_PATHS = ["/health", "/.well-known/*", "/contracts/*"]; /** * Check if a path matches any public path pattern */ function isPublicPath(path: string, publicPaths: string[]): boolean { for (const pattern of publicPaths) { if (pattern.endsWith("/*")) { const prefix = pattern.slice(0, -1); // Remove trailing * if (path.startsWith(prefix)) return true; } else if (path === pattern) { return true; } } return false; } /** * Create auth middleware that wraps user-provided middleware with public path bypass * * @param config - Auth configuration with middleware and optional public paths * @param basePath - Base path prefix for routes (e.g., "/api") * @returns Hono middleware handler */ export function createAuthMiddleware( config: AuthConfig, basePath: string = "" ): MiddlewareHandler { const publicPaths = (config.publicPaths ?? DEFAULT_PUBLIC_PATHS).map( (p) => basePath + p ); return async (c: Context, next: Next) => { const path = new URL(c.req.url).pathname; // Skip auth for public paths if (isPublicPath(path, publicPaths)) { return next(); } // Call user's auth middleware return config.middleware(c, next); }; }