UNPKG

better-auth-is-bot

Version:

A better-auth plugin to detect and block bots.

52 lines (48 loc) 1.33 kB
'use strict'; const isbot = require('isbot'); const escapeRegex = (str) => { return str.replace(/[-[\]/{}()+?.\\^$|]/g, "\\$&"); }; const pathToRegexp = (path) => { const pattern = escapeRegex(path).replace(/\*/g, ".*"); return new RegExp(`^${pattern}$`); }; const IsBot = (options = {}) => { return { id: "is-bot", onRequest: async (request) => { if (!request) return; const { method, url } = request; if (method !== "POST" && method !== "GET") { return; } const { protectedEndpoints } = options; const pathname = new URL(url).pathname; if (protectedEndpoints && protectedEndpoints.length > 0) { const isProtected = protectedEndpoints.some( (endpoint) => pathToRegexp(endpoint).test(pathname) ); if (!isProtected) { return; } } if (isbot.isbot(request.headers.get("user-agent") ?? "")) { const response = new Response( JSON.stringify({ message: "BOT_DETECTED", error: "BAD_REQUEST" }), { status: 400, headers: { "Content-Type": "application/json" } } ); return { response }; } }, $ERROR_CODES: { BOT_DETECTED: "You are a bot" } }; }; exports.IsBot = IsBot;