Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Add Vercel BotID to sign-in, sign-up and setup, off by default
Claudedaca4e589ae4
diff --git a/next.config.ts b/next.config.tsindex 8d86bdf..5b44178 100644--- a/next.config.ts+++ b/next.config.ts@@ -1,9 +1,17 @@import type { NextConfig } from "next";const nextConfig: NextConfig = {+ env: {+ // Whether Vercel BotID is on, decided once at build time so the browser+ // code that adds its proof and the server code that checks it cannot+ // disagree. It only works on Vercel, and is opt-in with BOTID=1. See+ // src/lib/security/botid.ts.+ NEXT_PUBLIC_BOTID:+ process.env.VERCEL === "1" && process.env.BOTID === "1" ? "1" : "",+ },images: {unoptimized: true,},};-export default nextConfig;\ No newline at end of file+export default nextConfig;diff --git a/package-lock.json b/package-lock.jsonindex 310e6e0..603293c 100644--- a/package-lock.json+++ b/package-lock.json@@ -13,6 +13,7 @@"@vercel/blob": "^2.9.0","@vercel/functions": "^3.11.1","better-auth": "^1.7.21",+ "botid": "^1.5.13","class-variance-authority": "^0.7.1","clsx": "^2.1.1","lucide-react": "^0.577.0",@@ -4954,6 +4955,23 @@}}},+ "node_modules/botid": {+ "version": "1.5.13",+ "resolved": "https://registry.npmjs.org/botid/-/botid-1.5.13.tgz",+ "integrity": "sha512-bd1oGgunQXOXQOctgLm/XuJKji5E8EUJdHYQAHJhJPgFeBo/mLQMeEsokO9nbrjjOZsSoKZfGHRfM/VAux44GA==",+ "peerDependencies": {+ "next": "*",+ "react": "^18.0.0 || ^19.0.0"+ },+ "peerDependenciesMeta": {+ "next": {+ "optional": true+ },+ "react": {+ "optional": true+ }+ }+ },"node_modules/brace-expansion": {"version": "1.1.22","resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.22.tgz",diff --git a/package.json b/package.jsonindex d4061f8..8300863 100644--- a/package.json+++ b/package.json@@ -28,6 +28,7 @@"@vercel/blob": "^2.9.0","@vercel/functions": "^3.11.1","better-auth": "^1.7.21",+ "botid": "^1.5.13","class-variance-authority": "^0.7.1","clsx": "^2.1.1","lucide-react": "^0.577.0",diff --git a/src/app/api/auth/[...all]/route.ts b/src/app/api/auth/[...all]/route.tsindex 7a56aa3..1fad9c1 100644--- a/src/app/api/auth/[...all]/route.ts+++ b/src/app/api/auth/[...all]/route.ts@@ -1,6 +1,7 @@import { toNextJsHandler } from "better-auth/next-js";import { getAuth } from "@/lib/auth/server";+import { rejectBots } from "@/lib/security/botid";type AuthHandlers = ReturnType<typeof toNextJsHandler>;@@ -26,8 +27,10 @@ export function PATCH(request: Request) {return getHandlers().PATCH(request);}-export function POST(request: Request) {- return getHandlers().POST(request);+export async function POST(request: Request) {+ // Sign-in, sign-up and the routes that send email are checked by BotID+ // first, where that is turned on.+ return (await rejectBots(request)) ?? getHandlers().POST(request);}export function PUT(request: Request) {diff --git a/src/app/api/contact/route.ts b/src/app/api/contact/route.tsindex 69e776f..d80866d 100644--- a/src/app/api/contact/route.ts+++ b/src/app/api/contact/route.ts@@ -4,6 +4,7 @@ import {ContactSubmissionError,submitPublicContactMessage,} from "@/lib/contact";+import { rejectBots } from "@/lib/security/botid";import { logRouteError, logSecurityEvent } from "@/lib/security/logging";import {applyRateLimit,@@ -40,6 +41,12 @@ export async function POST(request: Request) {return rateLimitResponse;}+ const botResponse = await rejectBots(request);++ if (botResponse) {+ return botResponse;+ }+const payload = (await request.json().catch(() => null)) as Record<string,unknowndiff --git a/src/app/api/setup/route.ts b/src/app/api/setup/route.tsindex 691ab03..bbef9dc 100644--- a/src/app/api/setup/route.ts+++ b/src/app/api/setup/route.ts@@ -3,6 +3,7 @@ import { NextResponse } from "next/server";import { getAuth, getAuthSessionFromHeaders } from "@/lib/auth/server";import { runAsSetup } from "@/lib/auth/setup-context";+import { rejectBots } from "@/lib/security/botid";import { logRouteError, logSecurityEvent } from "@/lib/security/logging";import {applyRateLimit,@@ -72,6 +73,12 @@ export async function POST(request: Request) {return rateLimitResponse;}+ const botResponse = await rejectBots(request);++ if (botResponse) {+ return botResponse;+ }+// A page on another site can make a browser send a form here, but it// cannot make it send JSON without this site's permission. Insisting on// JSON keeps a stranger's page from running setup in a visitor's browser.diff --git a/src/instrumentation-client.ts b/src/instrumentation-client.tsnew file mode 100644index 0000000..51ad163--- /dev/null+++ b/src/instrumentation-client.ts@@ -0,0 +1,14 @@+import { initBotId } from "botid/client/core";++import { BOT_PROTECTED_ROUTES } from "@/lib/security/botid-routes";++// Runs in the browser before the app starts.+//+// With Vercel BotID turned on (BOTID=1 on a Vercel deployment, fixed at+// build time), this makes the browser attach a proof to the requests listed+// in BOT_PROTECTED_ROUTES. The server checks that proof in+// src/lib/security/botid.ts. Everywhere else it does nothing.+// https://vercel.com/docs/botid/get-started+if (process.env.NEXT_PUBLIC_BOTID === "1") {+ initBotId({ protect: BOT_PROTECTED_ROUTES });+}diff --git a/src/lib/security/botid-routes.ts b/src/lib/security/botid-routes.tsnew file mode 100644index 0000000..faab71d--- /dev/null+++ b/src/lib/security/botid-routes.ts@@ -0,0 +1,33 @@+// The requests that Vercel BotID vouches for. The browser adds a proof to+// each of these (src/instrumentation-client.ts) and the server checks it+// (src/lib/security/botid.ts), so both sides read this one list. A request+// the browser does not mark is treated as a bot by the server, which is why+// the two must never drift apart.+//+// These are the doors a script would knock on: making accounts, guessing+// passwords, causing email to be sent, and claiming a new install.++export type BotProtectedRoute = {+ method: string;+ path: string;+};++export const BOT_PROTECTED_ROUTES: BotProtectedRoute[] = [+ { method: "POST", path: "/api/auth/sign-up/email" },+ { method: "POST", path: "/api/auth/sign-in/email" },+ { method: "POST", path: "/api/auth/request-password-reset" },+ { method: "POST", path: "/api/auth/send-verification-email" },+ { method: "POST", path: "/api/contact" },+ { method: "POST", path: "/api/setup" },+];++export function isBotProtectedRoute(method: string, pathname: string): boolean {+ const normalizedPath =+ pathname.length > 1 ? pathname.replace(/\/+$/, "") : pathname;++ return BOT_PROTECTED_ROUTES.some(+ (route) =>+ route.path === normalizedPath &&+ route.method.toUpperCase() === method.toUpperCase(),+ );+}diff --git a/src/lib/security/botid.test.ts b/src/lib/security/botid.test.tsnew file mode 100644index 0000000..01e5614--- /dev/null+++ b/src/lib/security/botid.test.ts@@ -0,0 +1,125 @@+import assert from "node:assert/strict";+import { test } from "node:test";++import { BOT_PROTECTED_ROUTES, isBotProtectedRoute } from "./botid-routes.ts";+import { BOT_REJECTION_MESSAGE, rejectBots } from "./botid.ts";++function post(path: string) {+ return new Request(`https://sign.example.com${path}`, { method: "POST" });+}++const human = () => Promise.resolve({ isBot: false });+const bot = () => Promise.resolve({ isBot: true });++test("the doors a script would knock on are the protected ones", () => {+ assert.deepEqual(+ BOT_PROTECTED_ROUTES.map((route) => `${route.method} ${route.path}`),+ [+ "POST /api/auth/sign-up/email",+ "POST /api/auth/sign-in/email",+ "POST /api/auth/request-password-reset",+ "POST /api/auth/send-verification-email",+ "POST /api/contact",+ "POST /api/setup",+ ],+ );+ assert.equal(isBotProtectedRoute("post", "/api/auth/sign-in/email/"), true);+ assert.equal(isBotProtectedRoute("GET", "/api/auth/sign-in/email"), false);+ assert.equal(isBotProtectedRoute("POST", "/api/auth/sign-out"), false);+ assert.equal(isBotProtectedRoute("POST", "/api/auth/get-session"), false);+});++test("turned off, nothing is checked", async () => {+ let checks = 0;+ const check = () => {+ checks += 1;++ return bot();+ };++ assert.equal(+ await rejectBots(post("/api/auth/sign-in/email"), {+ check,+ enabled: false,+ }),+ null,+ );+ assert.equal(checks, 0);+ // And it is off unless the build turned it on.+ assert.equal(+ await rejectBots(post("/api/auth/sign-in/email"), { check }),+ null,+ );+ assert.equal(checks, 0);+});++test("turned on, a person is let through and a bot gets a 403 the forms can show", async (t) => {+ t.mock.method(console, "warn", () => undefined);++ assert.equal(+ await rejectBots(post("/api/auth/sign-up/email"), {+ check: human,+ enabled: true,+ }),+ null,+ );++ const response = await rejectBots(post("/api/auth/sign-up/email"), {+ check: bot,+ enabled: true,+ });++ assert.equal(response?.status, 403);+ assert.deepEqual(await response?.json(), {+ code: "BOT_DETECTED",+ error: BOT_REJECTION_MESSAGE,+ message: BOT_REJECTION_MESSAGE,+ });+});++test("requests outside the list are not checked even when it is on", async () => {+ let checks = 0;+ const check = () => {+ checks += 1;++ return bot();+ };++ assert.equal(+ await rejectBots(post("/api/auth/sign-out"), { check, enabled: true }),+ null,+ );+ assert.equal(+ await rejectBots(+ new Request("https://sign.example.com/api/auth/get-session"),+ { check, enabled: true },+ ),+ null,+ );+ assert.equal(checks, 0);+});++test("a check that fails or never answers lets the request in rather than locking everyone out", async (t) => {+ const logged = t.mock.method(console, "error", () => undefined);++ assert.equal(+ await rejectBots(post("/api/auth/sign-in/email"), {+ check: () =>+ Promise.reject(+ new Error("The 'x-vercel-oidc-token' header is missing"),+ ),+ enabled: true,+ }),+ null,+ );+ assert.equal(+ await rejectBots(post("/api/auth/sign-in/email"), {+ check: () => new Promise<{ isBot: boolean }>(() => undefined),+ enabled: true,+ timeoutMs: 20,+ }),+ null,+ );+ // Both are logged, so a broken check does not go unnoticed.+ assert.equal(logged.mock.callCount(), 2);+});diff --git a/src/lib/security/botid.ts b/src/lib/security/botid.tsnew file mode 100644index 0000000..1aa0ace--- /dev/null+++ b/src/lib/security/botid.ts@@ -0,0 +1,112 @@+import { checkBotId } from "botid/server";++import { isBotProtectedRoute } from "./botid-routes.ts";+import { logSecurityEvent } from "./logging.ts";+import { getClientIpAddress, getRequestPathname } from "./request.ts";++// Vercel BotID: an invisible check that the request comes from a real+// browser. https://vercel.com/docs/botid+//+// It is off unless the deployment is on Vercel and sets BOTID=1. Whether it+// is on is fixed when the app is built (next.config.ts turns that into+// NEXT_PUBLIC_BOTID), so the browser code that adds the proof and this code+// that checks it always agree. If they disagreed, every sign-in would be+// refused.++type BotVerdict = { isBot: boolean };++type RejectBotsOptions = {+ check?: () => Promise<BotVerdict>;+ enabled?: boolean;+ timeoutMs?: number;+};++const CHECK_TIMEOUT_MS = 3000;++export const BOT_REJECTION_MESSAGE =+ "We could not confirm this request came from your browser. Reload the page and try again.";++export function isBotProtectionEnabled(): boolean {+ return process.env.NEXT_PUBLIC_BOTID === "1";+}++function withTimeout<T>(work: Promise<T>, timeoutMs: number): Promise<T> {+ let timer: ReturnType<typeof setTimeout> | undefined;+ const timeout = new Promise<never>((_, reject) => {+ timer = setTimeout(() => {+ reject(new Error(`No answer within ${String(timeoutMs)} ms.`));+ }, timeoutMs);+ });++ return Promise.race([work, timeout]).finally(() => {+ clearTimeout(timer);+ });+}++/**+ * Returns the 403 to send when BotID says this request is a bot, or null+ * when the request may go ahead.+ *+ * If the check itself cannot be made (BotID unreachable, or the project is+ * not set up for it) the request goes ahead: the rate limits still apply,+ * and a bot check that is down must not lock every person out of signing+ * in.+ */+export async function rejectBots(+ request: Request,+ {+ check = checkBotId,+ enabled = isBotProtectionEnabled(),+ timeoutMs = CHECK_TIMEOUT_MS,+ }: RejectBotsOptions = {},+): Promise<Response | null> {+ if (!enabled) {+ return null;+ }++ const path = getRequestPathname(request);++ if (!isBotProtectedRoute(request.method, path)) {+ return null;+ }++ let verdict: BotVerdict;++ try {+ verdict = await withTimeout(check(), timeoutMs);+ } catch (error) {+ logSecurityEvent("error", {+ category: "bot_check_unavailable",+ ipAddress: getClientIpAddress(request.headers),+ message: "The bot check could not be made, so the request was let in.",+ metadata: {+ reason: error instanceof Error ? error.message : String(error),+ },+ path,+ });++ return null;+ }++ if (!verdict.isBot) {+ return null;+ }++ logSecurityEvent("warn", {+ category: "bot_blocked",+ ipAddress: getClientIpAddress(request.headers),+ message: "A request was refused as automated.",+ path,+ });++ // "message" and "code" are what the sign-in and sign-up forms read;+ // "error" is what the app's own routes use.+ return Response.json(+ {+ code: "BOT_DETECTED",+ error: BOT_REJECTION_MESSAGE,+ message: BOT_REJECTION_MESSAGE,+ },+ { status: 403 },+ );+}diff --git a/src/proxy.ts b/src/proxy.tsindex 1a6d607..909a074 100644--- a/src/proxy.ts+++ b/src/proxy.ts@@ -52,6 +52,7 @@ function resolveBlobUploadSource() {function buildContentSecurityPolicy() {const preview = isVercelPreview();+ const botProtection = process.env.NEXT_PUBLIC_BOTID === "1";const directives: Array<[name: string, sources: Array<string | false>]> = [["default-src", ["'self'"]],["base-uri", ["'self'"]],@@ -85,7 +86,17 @@ function buildContentSecurityPolicy() {preview && "https://vercel.live wss://ws-us3.pusher.com",],],- ["frame-src", [preview ? "https://vercel.live" : "'none'"]],+ [+ "frame-src",+ [+ preview && "https://vercel.live",+ // BotID's deeper check runs in a hidden frame on this same site.+ // Not yet confirmed against a live deployment; see the note on+ // BotID in the README.+ botProtection && "'self'",+ !preview && !botProtection && "'none'",+ ],+ ],["worker-src", ["'self'", "blob:"]],["style-src",