Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

3.3 KB
Raw Blame
import { betterAuth } from "better-auth";
import { bearer, emailOTP } from "better-auth/plugins";

import type { ControlPlaneConfig } from "./config";
import { sendOTPEmail } from "./email";

export function createAuth(
  env: Env,
  ctx: ExecutionContext,
  config: ControlPlaneConfig,
  requestId: string,
) {
  return betterAuth({
    appName: "OpenMausBot",
    baseURL: config.authBaseURL,
    basePath: "/api/auth",
    secret: env.BETTER_AUTH_SECRET,
    database: env.DB,
    trustedOrigins: [...config.allowedOrigins],
    logger: { disabled: true },
    // Better Auth would otherwise delete expired verification rows inline on
    // every OTP check (two serial D1 round trips). Expired codes still fail
    // their expiresAt check; the sweep runs after the sign-in response.
    verification: { disableCleanup: true },
    rateLimit: {
      enabled: true,
      storage: "database",
      window: 60,
      max: 60,
      customRules: {
        "/email-otp/send-verification-otp": { window: 60, max: 5 },
        "/sign-in/email-otp": { window: 60, max: 10 },
      },
    },
    advanced: {
      useSecureCookies: true,
      ipAddress: {
        // Cloudflare writes this header at the edge. Do not trust a client-
        // supplied x-forwarded-for chain for rate limits or session metadata.
        ipAddressHeaders: ["cf-connecting-ip"],
      },
      // Better Auth 1.7.3+ introspects D1 as each auth instance starts (once per
      // request here) and makes auth requests wait on it: one more D1 round trip
      // per request for a schema the pinned migrations already fix.
      database: { generateId: "uuid", validateSchema: false },
      backgroundTasks: {
        handler(promise) {
          ctx.waitUntil(promise);
        },
      },
    },
    plugins: [
      emailOTP({
        otpLength: 8,
        expiresIn: 10 * 60,
        allowedAttempts: 5,
        storeOTP: "hashed",
        resendStrategy: "rotate",
        disableSignUp: false,
        rateLimit: { window: 60, max: 5 },
        async sendVerificationOTP(input) {
          await sendOTPEmail({
            async send(message) {
              await env.EMAIL.send(message);
            },
          }, config.emailFrom, input, requestId);
        },
      }),
      bearer({ requireSignature: true }),
    ],
  });
}

export type ControlPlaneAuth = ReturnType<typeof createAuth>;

/**
 * The expired-verification cleanup that `verification.disableCleanup` turns
 * off, as a single DELETE. It calls the adapter directly, so it skips
 * verification delete hooks. None are registered (emailOTP and bearer add
 * none); revisit this if databaseHooks are added or better-auth is upgraded.
 */
export async function deleteExpiredVerifications(auth: ControlPlaneAuth): Promise<void> {
  const context = await auth.$context;
  await context.adapter.deleteMany({
    model: "verification",
    where: [{ field: "expiresAt", operator: "lt", value: new Date() }],
  });
}

export async function accountSession(request: Request, auth: ControlPlaneAuth) {
  const authorization = request.headers.get("authorization");
  const match = authorization?.match(/^Bearer\s+([^\s]+)$/i);
  if (!match || match[1].startsWith("omb_install_")) return null;

  return auth.api.getSession({
    headers: new Headers({ authorization: `Bearer ${match[1]}` }),
  });
}