Files
template-app/better-auth/functions/auth.ts
T

38 lines
1.7 KiB
TypeScript

// SPDX-License-Identifier: LicenseRef-ConusAI-Template-1.0
// Better Auth for this app, on Convex. SITE_URL is the app's public origin (CONUSAI_PUBLIC_URL), the
// only origin Better Auth trusts; BETTER_AUTH_SECRET signs its cookies and tokens. Both are this
// deployment's environment, installed by ../deploy.mjs, and never reach the app's browser bundle.
import { revocationTriggers } from "@conusai-kit/auth-convex-better-auth/convex"
import { type AuthFunctions, createClient, type GenericCtx } from "@convex-dev/better-auth"
import { betterAuth } from "better-auth/minimal"
import { components, internal } from "./_generated/api"
import type { DataModel } from "./_generated/dataModel"
import authConfig from "./auth.config"
import { betterAuthOptions } from "./betterAuth/options"
import authSchema from "./betterAuth/schema"
const authFunctions: AuthFunctions = internal.auth
// The triggers write the revocation outbox in the same mutation that ends a session or an account.
export const authComponent = createClient<DataModel, typeof authSchema>(components.betterAuth, {
authFunctions,
triggers: revocationTriggers(),
local: { schema: authSchema },
})
export const { onCreate, onUpdate, onDelete } = authComponent.triggersApi()
export const createAuthOptions = (ctx: GenericCtx<DataModel>) => {
const siteUrl = process.env.SITE_URL
return {
...(siteUrl ? { baseURL: siteUrl, trustedOrigins: [siteUrl] } : {}),
database: authComponent.adapter(ctx),
...betterAuthOptions(authConfig),
}
}
export const createAuth = (ctx: GenericCtx<DataModel>) => {
if (!process.env.SITE_URL) throw new Error("SITE_URL is not set: deploy.mjs installs the app's public origin")
return betterAuth(createAuthOptions(ctx))
}