(config: ProtectedRouteConfig)
| 76 | * @returns Middleware that enforces payment or cookie authentication |
| 77 | */ |
| 78 | export function createProtectedRoute(config: ProtectedRouteConfig) { |
| 79 | return async (c: Context<AppContext>, next: Next) => { |
| 80 | // Get the route path from the request context |
| 81 | // Normalize the path by removing trailing slashes (except for root "/") |
| 82 | // This matches how x402's findMatchingRoute normalizes incoming request paths |
| 83 | const rawPath = c.req.path; |
| 84 | const routePath = |
| 85 | rawPath.length > 1 ? rawPath.replace(/\/+$/, "") : rawPath; |
| 86 | |
| 87 | // Create payment middleware dynamically with config from env |
| 88 | // Facilitator is optional - x402 uses its own default when not provided |
| 89 | const facilitator = c.env.FACILITATOR_URL |
| 90 | ? { url: c.env.FACILITATOR_URL } |
| 91 | : undefined; |
| 92 | |
| 93 | const paymentMw = paymentMiddleware( |
| 94 | c.env.PAY_TO as `0x${string}`, |
| 95 | { |
| 96 | [routePath]: { |
| 97 | price: config.price, |
| 98 | network: c.env.NETWORK, |
| 99 | config: { |
| 100 | description: config.description, |
| 101 | }, |
| 102 | }, |
| 103 | }, |
| 104 | facilitator |
| 105 | ); |
| 106 | |
| 107 | // Apply the combined auth/payment middleware |
| 108 | return await requirePaymentOrCookie(paymentMw)(c, next); |
| 109 | }; |
| 110 | } |
no test coverage detected