This is page 47 of 49. Use http://codebase.md/better-auth/better-auth?page={x} to view the full context. # Directory Structure ``` ├── .gitattributes ├── .github │ ├── CODEOWNERS │ ├── FUNDING.yml │ ├── ISSUE_TEMPLATE │ │ ├── bug_report.yml │ │ └── feature_request.yml │ ├── renovate.json5 │ └── workflows │ ├── ci.yml │ ├── e2e.yml │ ├── preview.yml │ └── release.yml ├── .gitignore ├── .npmrc ├── .nvmrc ├── .vscode │ └── settings.json ├── banner-dark.png ├── banner.png ├── biome.json ├── bump.config.ts ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── demo │ ├── expo-example │ │ ├── .env.example │ │ ├── .gitignore │ │ ├── app.config.ts │ │ ├── assets │ │ │ ├── bg-image.jpeg │ │ │ ├── fonts │ │ │ │ └── SpaceMono-Regular.ttf │ │ │ ├── icon.png │ │ │ └── images │ │ │ ├── adaptive-icon.png │ │ │ ├── favicon.png │ │ │ ├── logo.png │ │ │ ├── partial-react-logo.png │ │ │ ├── react-logo.png │ │ │ ├── [email protected] │ │ │ ├── [email protected] │ │ │ └── splash.png │ │ ├── babel.config.js │ │ ├── components.json │ │ ├── expo-env.d.ts │ │ ├── index.ts │ │ ├── metro.config.js │ │ ├── nativewind-env.d.ts │ │ ├── package.json │ │ ├── README.md │ │ ├── src │ │ │ ├── app │ │ │ │ ├── _layout.tsx │ │ │ │ ├── api │ │ │ │ │ └── auth │ │ │ │ │ └── [...route]+api.ts │ │ │ │ ├── dashboard.tsx │ │ │ │ ├── forget-password.tsx │ │ │ │ ├── index.tsx │ │ │ │ └── sign-up.tsx │ │ │ ├── components │ │ │ │ ├── icons │ │ │ │ │ └── google.tsx │ │ │ │ └── ui │ │ │ │ ├── avatar.tsx │ │ │ │ ├── button.tsx │ │ │ │ ├── card.tsx │ │ │ │ ├── dialog.tsx │ │ │ │ ├── input.tsx │ │ │ │ ├── separator.tsx │ │ │ │ └── text.tsx │ │ │ ├── global.css │ │ │ └── lib │ │ │ ├── auth-client.ts │ │ │ ├── auth.ts │ │ │ ├── icons │ │ │ │ ├── iconWithClassName.ts │ │ │ │ └── X.tsx │ │ │ └── utils.ts │ │ ├── tailwind.config.js │ │ └── tsconfig.json │ └── nextjs │ ├── .env.example │ ├── .gitignore │ ├── app │ │ ├── (auth) │ │ │ ├── forget-password │ │ │ │ └── page.tsx │ │ │ ├── reset-password │ │ │ │ └── page.tsx │ │ │ ├── sign-in │ │ │ │ ├── loading.tsx │ │ │ │ └── page.tsx │ │ │ └── two-factor │ │ │ ├── otp │ │ │ │ └── page.tsx │ │ │ └── page.tsx │ │ ├── accept-invitation │ │ │ └── [id] │ │ │ ├── invitation-error.tsx │ │ │ └── page.tsx │ │ ├── admin │ │ │ └── page.tsx │ │ ├── api │ │ │ └── auth │ │ │ └── [...all] │ │ │ └── route.ts │ │ ├── apps │ │ │ └── register │ │ │ └── page.tsx │ │ ├── client-test │ │ │ └── page.tsx │ │ ├── dashboard │ │ │ ├── change-plan.tsx │ │ │ ├── client.tsx │ │ │ ├── organization-card.tsx │ │ │ ├── page.tsx │ │ │ ├── upgrade-button.tsx │ │ │ └── user-card.tsx │ │ ├── device │ │ │ ├── approve │ │ │ │ └── page.tsx │ │ │ ├── denied │ │ │ │ └── page.tsx │ │ │ ├── layout.tsx │ │ │ ├── page.tsx │ │ │ └── success │ │ │ └── page.tsx │ │ ├── favicon.ico │ │ ├── features.tsx │ │ ├── fonts │ │ │ ├── GeistMonoVF.woff │ │ │ └── GeistVF.woff │ │ ├── globals.css │ │ ├── layout.tsx │ │ ├── oauth │ │ │ └── authorize │ │ │ ├── concet-buttons.tsx │ │ │ └── page.tsx │ │ ├── page.tsx │ │ └── pricing │ │ └── page.tsx │ ├── components │ │ ├── account-switch.tsx │ │ ├── blocks │ │ │ └── pricing.tsx │ │ ├── logo.tsx │ │ ├── one-tap.tsx │ │ ├── sign-in-btn.tsx │ │ ├── sign-in.tsx │ │ ├── sign-up.tsx │ │ ├── theme-provider.tsx │ │ ├── theme-toggle.tsx │ │ ├── tier-labels.tsx │ │ ├── ui │ │ │ ├── accordion.tsx │ │ │ ├── alert-dialog.tsx │ │ │ ├── alert.tsx │ │ │ ├── aspect-ratio.tsx │ │ │ ├── avatar.tsx │ │ │ ├── badge.tsx │ │ │ ├── breadcrumb.tsx │ │ │ ├── button.tsx │ │ │ ├── calendar.tsx │ │ │ ├── card.tsx │ │ │ ├── carousel.tsx │ │ │ ├── chart.tsx │ │ │ ├── checkbox.tsx │ │ │ ├── collapsible.tsx │ │ │ ├── command.tsx │ │ │ ├── context-menu.tsx │ │ │ ├── copy-button.tsx │ │ │ ├── dialog.tsx │ │ │ ├── drawer.tsx │ │ │ ├── dropdown-menu.tsx │ │ │ ├── form.tsx │ │ │ ├── hover-card.tsx │ │ │ ├── input-otp.tsx │ │ │ ├── input.tsx │ │ │ ├── label.tsx │ │ │ ├── menubar.tsx │ │ │ ├── navigation-menu.tsx │ │ │ ├── pagination.tsx │ │ │ ├── password-input.tsx │ │ │ ├── popover.tsx │ │ │ ├── progress.tsx │ │ │ ├── radio-group.tsx │ │ │ ├── resizable.tsx │ │ │ ├── scroll-area.tsx │ │ │ ├── select.tsx │ │ │ ├── separator.tsx │ │ │ ├── sheet.tsx │ │ │ ├── skeleton.tsx │ │ │ ├── slider.tsx │ │ │ ├── sonner.tsx │ │ │ ├── switch.tsx │ │ │ ├── table.tsx │ │ │ ├── tabs.tsx │ │ │ ├── tabs2.tsx │ │ │ ├── textarea.tsx │ │ │ ├── toast.tsx │ │ │ ├── toaster.tsx │ │ │ ├── toggle-group.tsx │ │ │ ├── toggle.tsx │ │ │ └── tooltip.tsx │ │ └── wrapper.tsx │ ├── components.json │ ├── hooks │ │ └── use-toast.ts │ ├── lib │ │ ├── auth-client.ts │ │ ├── auth-types.ts │ │ ├── auth.ts │ │ ├── email │ │ │ ├── invitation.tsx │ │ │ ├── resend.ts │ │ │ └── reset-password.tsx │ │ ├── metadata.ts │ │ ├── shared.ts │ │ └── utils.ts │ ├── middleware.ts │ ├── next.config.ts │ ├── package.json │ ├── postcss.config.mjs │ ├── public │ │ ├── __og.png │ │ ├── _og.png │ │ ├── favicon │ │ │ ├── android-chrome-192x192.png │ │ │ ├── android-chrome-512x512.png │ │ │ ├── apple-touch-icon.png │ │ │ ├── favicon-16x16.png │ │ │ ├── favicon-32x32.png │ │ │ ├── favicon.ico │ │ │ ├── light │ │ │ │ ├── android-chrome-192x192.png │ │ │ │ ├── android-chrome-512x512.png │ │ │ │ ├── apple-touch-icon.png │ │ │ │ ├── favicon-16x16.png │ │ │ │ ├── favicon-32x32.png │ │ │ │ ├── favicon.ico │ │ │ │ └── site.webmanifest │ │ │ └── site.webmanifest │ │ ├── logo.svg │ │ └── og.png │ ├── README.md │ ├── tailwind.config.ts │ ├── tsconfig.json │ └── turbo.json ├── docker-compose.yml ├── docs │ ├── .env.example │ ├── .gitignore │ ├── app │ │ ├── api │ │ │ ├── ai-chat │ │ │ │ └── route.ts │ │ │ ├── analytics │ │ │ │ ├── conversation │ │ │ │ │ └── route.ts │ │ │ │ ├── event │ │ │ │ │ └── route.ts │ │ │ │ └── feedback │ │ │ │ └── route.ts │ │ │ ├── chat │ │ │ │ └── route.ts │ │ │ ├── og │ │ │ │ └── route.tsx │ │ │ ├── og-release │ │ │ │ └── route.tsx │ │ │ ├── search │ │ │ │ └── route.ts │ │ │ └── support │ │ │ └── route.ts │ │ ├── blog │ │ │ ├── _components │ │ │ │ ├── _layout.tsx │ │ │ │ ├── blog-list.tsx │ │ │ │ ├── changelog-layout.tsx │ │ │ │ ├── default-changelog.tsx │ │ │ │ ├── fmt-dates.tsx │ │ │ │ ├── icons.tsx │ │ │ │ ├── stat-field.tsx │ │ │ │ └── support.tsx │ │ │ ├── [[...slug]] │ │ │ │ └── page.tsx │ │ │ └── layout.tsx │ │ ├── changelogs │ │ │ ├── _components │ │ │ │ ├── _layout.tsx │ │ │ │ ├── changelog-layout.tsx │ │ │ │ ├── default-changelog.tsx │ │ │ │ ├── fmt-dates.tsx │ │ │ │ ├── grid-pattern.tsx │ │ │ │ ├── icons.tsx │ │ │ │ └── stat-field.tsx │ │ │ ├── [[...slug]] │ │ │ │ └── page.tsx │ │ │ └── layout.tsx │ │ ├── community │ │ │ ├── _components │ │ │ │ ├── header.tsx │ │ │ │ └── stats.tsx │ │ │ └── page.tsx │ │ ├── docs │ │ │ ├── [[...slug]] │ │ │ │ ├── page.client.tsx │ │ │ │ └── page.tsx │ │ │ ├── layout.tsx │ │ │ └── lib │ │ │ └── get-llm-text.ts │ │ ├── global.css │ │ ├── layout.config.tsx │ │ ├── layout.tsx │ │ ├── llms.txt │ │ │ ├── [...slug] │ │ │ │ └── route.ts │ │ │ └── route.ts │ │ ├── not-found.tsx │ │ ├── page.tsx │ │ ├── reference │ │ │ └── route.ts │ │ ├── sitemap.xml │ │ ├── static.json │ │ │ └── route.ts │ │ └── v1 │ │ ├── _components │ │ │ └── v1-text.tsx │ │ ├── bg-line.tsx │ │ └── page.tsx │ ├── assets │ │ ├── Geist.ttf │ │ └── GeistMono.ttf │ ├── components │ │ ├── ai-chat-modal.tsx │ │ ├── anchor-scroll-fix.tsx │ │ ├── api-method-tabs.tsx │ │ ├── api-method.tsx │ │ ├── banner.tsx │ │ ├── blocks │ │ │ └── features.tsx │ │ ├── builder │ │ │ ├── beam.tsx │ │ │ ├── code-tabs │ │ │ │ ├── code-editor.tsx │ │ │ │ ├── code-tabs.tsx │ │ │ │ ├── index.tsx │ │ │ │ ├── tab-bar.tsx │ │ │ │ └── theme.ts │ │ │ ├── index.tsx │ │ │ ├── sign-in.tsx │ │ │ ├── sign-up.tsx │ │ │ ├── social-provider.tsx │ │ │ ├── store.ts │ │ │ └── tabs.tsx │ │ ├── display-techstack.tsx │ │ ├── divider-text.tsx │ │ ├── docs │ │ │ ├── docs.client.tsx │ │ │ ├── docs.tsx │ │ │ ├── layout │ │ │ │ ├── nav.tsx │ │ │ │ ├── theme-toggle.tsx │ │ │ │ ├── toc-thumb.tsx │ │ │ │ └── toc.tsx │ │ │ ├── page.client.tsx │ │ │ ├── page.tsx │ │ │ ├── shared.tsx │ │ │ └── ui │ │ │ ├── button.tsx │ │ │ ├── collapsible.tsx │ │ │ ├── popover.tsx │ │ │ └── scroll-area.tsx │ │ ├── endpoint.tsx │ │ ├── features.tsx │ │ ├── floating-ai-search.tsx │ │ ├── fork-button.tsx │ │ ├── generate-apple-jwt.tsx │ │ ├── generate-secret.tsx │ │ ├── github-stat.tsx │ │ ├── icons.tsx │ │ ├── landing │ │ │ ├── gradient-bg.tsx │ │ │ ├── grid-pattern.tsx │ │ │ ├── hero.tsx │ │ │ ├── section-svg.tsx │ │ │ ├── section.tsx │ │ │ ├── spotlight.tsx │ │ │ └── testimonials.tsx │ │ ├── logo-context-menu.tsx │ │ ├── logo.tsx │ │ ├── markdown-renderer.tsx │ │ ├── markdown.tsx │ │ ├── mdx │ │ │ ├── add-to-cursor.tsx │ │ │ └── database-tables.tsx │ │ ├── message-feedback.tsx │ │ ├── mobile-search-icon.tsx │ │ ├── nav-bar.tsx │ │ ├── nav-link.tsx │ │ ├── nav-mobile.tsx │ │ ├── promo-card.tsx │ │ ├── resource-card.tsx │ │ ├── resource-grid.tsx │ │ ├── resource-section.tsx │ │ ├── ripple.tsx │ │ ├── search-dialog.tsx │ │ ├── side-bar.tsx │ │ ├── sidebar-content.tsx │ │ ├── techstack-icons.tsx │ │ ├── theme-provider.tsx │ │ ├── theme-toggler.tsx │ │ └── ui │ │ ├── accordion.tsx │ │ ├── alert-dialog.tsx │ │ ├── alert.tsx │ │ ├── aside-link.tsx │ │ ├── aspect-ratio.tsx │ │ ├── avatar.tsx │ │ ├── background-beams.tsx │ │ ├── background-boxes.tsx │ │ ├── badge.tsx │ │ ├── breadcrumb.tsx │ │ ├── button.tsx │ │ ├── calendar.tsx │ │ ├── callout.tsx │ │ ├── card.tsx │ │ ├── carousel.tsx │ │ ├── chart.tsx │ │ ├── checkbox.tsx │ │ ├── code-block.tsx │ │ ├── collapsible.tsx │ │ ├── command.tsx │ │ ├── context-menu.tsx │ │ ├── dialog.tsx │ │ ├── drawer.tsx │ │ ├── dropdown-menu.tsx │ │ ├── dynamic-code-block.tsx │ │ ├── fade-in.tsx │ │ ├── form.tsx │ │ ├── hover-card.tsx │ │ ├── input-otp.tsx │ │ ├── input.tsx │ │ ├── label.tsx │ │ ├── menubar.tsx │ │ ├── navigation-menu.tsx │ │ ├── pagination.tsx │ │ ├── popover.tsx │ │ ├── progress.tsx │ │ ├── radio-group.tsx │ │ ├── resizable.tsx │ │ ├── scroll-area.tsx │ │ ├── select.tsx │ │ ├── separator.tsx │ │ ├── sheet.tsx │ │ ├── sidebar.tsx │ │ ├── skeleton.tsx │ │ ├── slider.tsx │ │ ├── sonner.tsx │ │ ├── sparkles.tsx │ │ ├── switch.tsx │ │ ├── table.tsx │ │ ├── tabs.tsx │ │ ├── textarea.tsx │ │ ├── toggle-group.tsx │ │ ├── toggle.tsx │ │ ├── tooltip-docs.tsx │ │ ├── tooltip.tsx │ │ └── use-copy-button.tsx │ ├── components.json │ ├── content │ │ ├── blogs │ │ │ ├── 0-supabase-auth-to-planetscale-migration.mdx │ │ │ ├── 1-3.mdx │ │ │ ├── authjs-joins-better-auth.mdx │ │ │ └── seed-round.mdx │ │ ├── changelogs │ │ │ ├── 1-2.mdx │ │ │ └── 1.0.mdx │ │ └── docs │ │ ├── adapters │ │ │ ├── community-adapters.mdx │ │ │ ├── drizzle.mdx │ │ │ ├── mongo.mdx │ │ │ ├── mssql.mdx │ │ │ ├── mysql.mdx │ │ │ ├── other-relational-databases.mdx │ │ │ ├── postgresql.mdx │ │ │ ├── prisma.mdx │ │ │ └── sqlite.mdx │ │ ├── authentication │ │ │ ├── apple.mdx │ │ │ ├── atlassian.mdx │ │ │ ├── cognito.mdx │ │ │ ├── discord.mdx │ │ │ ├── dropbox.mdx │ │ │ ├── email-password.mdx │ │ │ ├── facebook.mdx │ │ │ ├── figma.mdx │ │ │ ├── github.mdx │ │ │ ├── gitlab.mdx │ │ │ ├── google.mdx │ │ │ ├── huggingface.mdx │ │ │ ├── kakao.mdx │ │ │ ├── kick.mdx │ │ │ ├── line.mdx │ │ │ ├── linear.mdx │ │ │ ├── linkedin.mdx │ │ │ ├── microsoft.mdx │ │ │ ├── naver.mdx │ │ │ ├── notion.mdx │ │ │ ├── other-social-providers.mdx │ │ │ ├── paypal.mdx │ │ │ ├── reddit.mdx │ │ │ ├── roblox.mdx │ │ │ ├── salesforce.mdx │ │ │ ├── slack.mdx │ │ │ ├── spotify.mdx │ │ │ ├── tiktok.mdx │ │ │ ├── twitch.mdx │ │ │ ├── twitter.mdx │ │ │ ├── vk.mdx │ │ │ └── zoom.mdx │ │ ├── basic-usage.mdx │ │ ├── comparison.mdx │ │ ├── concepts │ │ │ ├── api.mdx │ │ │ ├── cli.mdx │ │ │ ├── client.mdx │ │ │ ├── cookies.mdx │ │ │ ├── database.mdx │ │ │ ├── email.mdx │ │ │ ├── hooks.mdx │ │ │ ├── oauth.mdx │ │ │ ├── plugins.mdx │ │ │ ├── rate-limit.mdx │ │ │ ├── session-management.mdx │ │ │ ├── typescript.mdx │ │ │ └── users-accounts.mdx │ │ ├── examples │ │ │ ├── astro.mdx │ │ │ ├── next-js.mdx │ │ │ ├── nuxt.mdx │ │ │ ├── remix.mdx │ │ │ └── svelte-kit.mdx │ │ ├── guides │ │ │ ├── auth0-migration-guide.mdx │ │ │ ├── browser-extension-guide.mdx │ │ │ ├── clerk-migration-guide.mdx │ │ │ ├── create-a-db-adapter.mdx │ │ │ ├── next-auth-migration-guide.mdx │ │ │ ├── optimizing-for-performance.mdx │ │ │ ├── saml-sso-with-okta.mdx │ │ │ ├── supabase-migration-guide.mdx │ │ │ └── your-first-plugin.mdx │ │ ├── installation.mdx │ │ ├── integrations │ │ │ ├── astro.mdx │ │ │ ├── convex.mdx │ │ │ ├── elysia.mdx │ │ │ ├── expo.mdx │ │ │ ├── express.mdx │ │ │ ├── fastify.mdx │ │ │ ├── hono.mdx │ │ │ ├── lynx.mdx │ │ │ ├── nestjs.mdx │ │ │ ├── next.mdx │ │ │ ├── nitro.mdx │ │ │ ├── nuxt.mdx │ │ │ ├── remix.mdx │ │ │ ├── solid-start.mdx │ │ │ ├── svelte-kit.mdx │ │ │ ├── tanstack.mdx │ │ │ └── waku.mdx │ │ ├── introduction.mdx │ │ ├── meta.json │ │ ├── plugins │ │ │ ├── 2fa.mdx │ │ │ ├── admin.mdx │ │ │ ├── anonymous.mdx │ │ │ ├── api-key.mdx │ │ │ ├── autumn.mdx │ │ │ ├── bearer.mdx │ │ │ ├── captcha.mdx │ │ │ ├── community-plugins.mdx │ │ │ ├── device-authorization.mdx │ │ │ ├── dodopayments.mdx │ │ │ ├── dub.mdx │ │ │ ├── email-otp.mdx │ │ │ ├── generic-oauth.mdx │ │ │ ├── have-i-been-pwned.mdx │ │ │ ├── jwt.mdx │ │ │ ├── last-login-method.mdx │ │ │ ├── magic-link.mdx │ │ │ ├── mcp.mdx │ │ │ ├── multi-session.mdx │ │ │ ├── oauth-proxy.mdx │ │ │ ├── oidc-provider.mdx │ │ │ ├── one-tap.mdx │ │ │ ├── one-time-token.mdx │ │ │ ├── open-api.mdx │ │ │ ├── organization.mdx │ │ │ ├── passkey.mdx │ │ │ ├── phone-number.mdx │ │ │ ├── polar.mdx │ │ │ ├── siwe.mdx │ │ │ ├── sso.mdx │ │ │ ├── stripe.mdx │ │ │ └── username.mdx │ │ └── reference │ │ ├── contributing.mdx │ │ ├── faq.mdx │ │ ├── options.mdx │ │ ├── resources.mdx │ │ ├── security.mdx │ │ └── telemetry.mdx │ ├── hooks │ │ └── use-mobile.ts │ ├── ignore-build.sh │ ├── lib │ │ ├── blog.ts │ │ ├── chat │ │ │ └── inkeep-qa-schema.ts │ │ ├── constants.ts │ │ ├── export-search-indexes.ts │ │ ├── inkeep-analytics.ts │ │ ├── is-active.ts │ │ ├── metadata.ts │ │ ├── source.ts │ │ └── utils.ts │ ├── next.config.js │ ├── package.json │ ├── postcss.config.js │ ├── proxy.ts │ ├── public │ │ ├── avatars │ │ │ └── beka.jpg │ │ ├── blogs │ │ │ ├── authjs-joins.png │ │ │ ├── seed-round.png │ │ │ └── supabase-ps.png │ │ ├── branding │ │ │ ├── better-auth-brand-assets.zip │ │ │ ├── better-auth-logo-dark.png │ │ │ ├── better-auth-logo-dark.svg │ │ │ ├── better-auth-logo-light.png │ │ │ ├── better-auth-logo-light.svg │ │ │ ├── better-auth-logo-wordmark-dark.png │ │ │ ├── better-auth-logo-wordmark-dark.svg │ │ │ ├── better-auth-logo-wordmark-light.png │ │ │ └── better-auth-logo-wordmark-light.svg │ │ ├── extension-id.png │ │ ├── favicon │ │ │ ├── android-chrome-192x192.png │ │ │ ├── android-chrome-512x512.png │ │ │ ├── apple-touch-icon.png │ │ │ ├── favicon-16x16.png │ │ │ ├── favicon-32x32.png │ │ │ ├── favicon.ico │ │ │ ├── light │ │ │ │ ├── android-chrome-192x192.png │ │ │ │ ├── android-chrome-512x512.png │ │ │ │ ├── apple-touch-icon.png │ │ │ │ ├── favicon-16x16.png │ │ │ │ ├── favicon-32x32.png │ │ │ │ ├── favicon.ico │ │ │ │ └── site.webmanifest │ │ │ └── site.webmanifest │ │ ├── images │ │ │ └── blogs │ │ │ └── better auth (1).png │ │ ├── logo.png │ │ ├── logo.svg │ │ ├── LogoDark.webp │ │ ├── LogoLight.webp │ │ ├── og.png │ │ ├── open-api-reference.png │ │ ├── people-say │ │ │ ├── code-with-antonio.jpg │ │ │ ├── dagmawi-babi.png │ │ │ ├── dax.png │ │ │ ├── dev-ed.png │ │ │ ├── egoist.png │ │ │ ├── guillermo-rauch.png │ │ │ ├── jonathan-wilke.png │ │ │ ├── josh-tried-coding.jpg │ │ │ ├── kitze.jpg │ │ │ ├── lazar-nikolov.png │ │ │ ├── nizzy.png │ │ │ ├── omar-mcadam.png │ │ │ ├── ryan-vogel.jpg │ │ │ ├── saltyatom.jpg │ │ │ ├── sebastien-chopin.png │ │ │ ├── shreyas-mididoddi.png │ │ │ ├── tech-nerd.png │ │ │ ├── theo.png │ │ │ ├── vybhav-bhargav.png │ │ │ └── xavier-pladevall.jpg │ │ ├── plus.svg │ │ ├── release-og │ │ │ ├── 1-2.png │ │ │ ├── 1-3.png │ │ │ └── changelog-og.png │ │ └── v1-og.png │ ├── README.md │ ├── scripts │ │ ├── endpoint-to-doc │ │ │ ├── index.ts │ │ │ ├── input.ts │ │ │ ├── output.mdx │ │ │ └── readme.md │ │ └── sync-orama.ts │ ├── source.config.ts │ ├── tailwind.config.js │ ├── tsconfig.json │ └── turbo.json ├── e2e │ ├── integration │ │ ├── package.json │ │ ├── playwright.config.ts │ │ ├── solid-vinxi │ │ │ ├── .gitignore │ │ │ ├── app.config.ts │ │ │ ├── e2e │ │ │ │ ├── test.spec.ts │ │ │ │ └── utils.ts │ │ │ ├── package.json │ │ │ ├── public │ │ │ │ └── favicon.ico │ │ │ ├── src │ │ │ │ ├── app.tsx │ │ │ │ ├── entry-client.tsx │ │ │ │ ├── entry-server.tsx │ │ │ │ ├── global.d.ts │ │ │ │ ├── lib │ │ │ │ │ ├── auth-client.ts │ │ │ │ │ └── auth.ts │ │ │ │ └── routes │ │ │ │ ├── [...404].tsx │ │ │ │ ├── api │ │ │ │ │ └── auth │ │ │ │ │ └── [...all].ts │ │ │ │ └── index.tsx │ │ │ └── tsconfig.json │ │ ├── test-utils │ │ │ ├── package.json │ │ │ └── src │ │ │ └── playwright.ts │ │ └── vanilla-node │ │ ├── e2e │ │ │ ├── app.ts │ │ │ ├── domain.spec.ts │ │ │ ├── postgres-js.spec.ts │ │ │ ├── test.spec.ts │ │ │ └── utils.ts │ │ ├── index.html │ │ ├── package.json │ │ ├── src │ │ │ ├── main.ts │ │ │ └── vite-env.d.ts │ │ ├── tsconfig.json │ │ └── vite.config.ts │ └── smoke │ ├── package.json │ ├── test │ │ ├── bun.spec.ts │ │ ├── cloudflare.spec.ts │ │ ├── deno.spec.ts │ │ ├── fixtures │ │ │ ├── bun-simple.ts │ │ │ ├── cloudflare │ │ │ │ ├── .gitignore │ │ │ │ ├── drizzle │ │ │ │ │ ├── 0000_clean_vector.sql │ │ │ │ │ └── meta │ │ │ │ │ ├── _journal.json │ │ │ │ │ └── 0000_snapshot.json │ │ │ │ ├── drizzle.config.ts │ │ │ │ ├── package.json │ │ │ │ ├── src │ │ │ │ │ ├── auth-schema.ts │ │ │ │ │ ├── db.ts │ │ │ │ │ └── index.ts │ │ │ │ ├── test │ │ │ │ │ ├── apply-migrations.ts │ │ │ │ │ ├── env.d.ts │ │ │ │ │ └── index.test.ts │ │ │ │ ├── tsconfig.json │ │ │ │ ├── vitest.config.ts │ │ │ │ ├── worker-configuration.d.ts │ │ │ │ └── wrangler.json │ │ │ ├── deno-simple.ts │ │ │ ├── tsconfig-exact-optional-property-types │ │ │ │ ├── package.json │ │ │ │ ├── src │ │ │ │ │ ├── index.ts │ │ │ │ │ └── user-additional-fields.ts │ │ │ │ └── tsconfig.json │ │ │ ├── tsconfig-verbatim-module-syntax-node10 │ │ │ │ ├── package.json │ │ │ │ ├── src │ │ │ │ │ └── index.ts │ │ │ │ └── tsconfig.json │ │ │ └── vite │ │ │ ├── package.json │ │ │ ├── src │ │ │ │ ├── client.ts │ │ │ │ └── server.ts │ │ │ ├── tsconfig.json │ │ │ └── vite.config.ts │ │ ├── ssr.ts │ │ ├── typecheck.spec.ts │ │ └── vite.spec.ts │ └── tsconfig.json ├── LICENSE.md ├── package.json ├── packages │ ├── better-auth │ │ ├── package.json │ │ ├── README.md │ │ ├── src │ │ │ ├── __snapshots__ │ │ │ │ └── init.test.ts.snap │ │ │ ├── adapters │ │ │ │ ├── adapter-factory │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── test │ │ │ │ │ │ ├── __snapshots__ │ │ │ │ │ │ │ └── adapter-factory.test.ts.snap │ │ │ │ │ │ └── adapter-factory.test.ts │ │ │ │ │ └── types.ts │ │ │ │ ├── create-test-suite.ts │ │ │ │ ├── drizzle-adapter │ │ │ │ │ ├── drizzle-adapter.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ └── test │ │ │ │ │ ├── .gitignore │ │ │ │ │ ├── adapter.drizzle.mysql.test.ts │ │ │ │ │ ├── adapter.drizzle.pg.test.ts │ │ │ │ │ ├── adapter.drizzle.sqlite.test.ts │ │ │ │ │ └── generate-schema.ts │ │ │ │ ├── index.ts │ │ │ │ ├── kysely-adapter │ │ │ │ │ ├── bun-sqlite-dialect.ts │ │ │ │ │ ├── dialect.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── kysely-adapter.ts │ │ │ │ │ ├── node-sqlite-dialect.ts │ │ │ │ │ ├── test │ │ │ │ │ │ ├── adapter.kysely.mssql.test.ts │ │ │ │ │ │ ├── adapter.kysely.mysql.test.ts │ │ │ │ │ │ ├── adapter.kysely.pg.test.ts │ │ │ │ │ │ ├── adapter.kysely.sqlite.test.ts │ │ │ │ │ │ └── node-sqlite-dialect.test.ts │ │ │ │ │ └── types.ts │ │ │ │ ├── memory-adapter │ │ │ │ │ ├── adapter.memory.test.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ └── memory-adapter.ts │ │ │ │ ├── mongodb-adapter │ │ │ │ │ ├── adapter.mongo-db.test.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ └── mongodb-adapter.ts │ │ │ │ ├── prisma-adapter │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── prisma-adapter.ts │ │ │ │ │ └── test │ │ │ │ │ ├── .gitignore │ │ │ │ │ ├── base.prisma │ │ │ │ │ ├── generate-auth-config.ts │ │ │ │ │ ├── generate-prisma-schema.ts │ │ │ │ │ ├── get-prisma-client.ts │ │ │ │ │ ├── prisma.mysql.test.ts │ │ │ │ │ ├── prisma.pg.test.ts │ │ │ │ │ ├── prisma.sqlite.test.ts │ │ │ │ │ └── push-prisma-schema.ts │ │ │ │ ├── test-adapter.ts │ │ │ │ ├── test.ts │ │ │ │ ├── tests │ │ │ │ │ ├── auth-flow.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── normal.ts │ │ │ │ │ ├── number-id.ts │ │ │ │ │ ├── performance.ts │ │ │ │ │ └── transactions.ts │ │ │ │ └── utils.ts │ │ │ ├── api │ │ │ │ ├── check-endpoint-conflicts.test.ts │ │ │ │ ├── index.test.ts │ │ │ │ ├── index.ts │ │ │ │ ├── middlewares │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── origin-check.test.ts │ │ │ │ │ └── origin-check.ts │ │ │ │ ├── rate-limiter │ │ │ │ │ ├── index.ts │ │ │ │ │ └── rate-limiter.test.ts │ │ │ │ ├── routes │ │ │ │ │ ├── account.test.ts │ │ │ │ │ ├── account.ts │ │ │ │ │ ├── callback.ts │ │ │ │ │ ├── email-verification.test.ts │ │ │ │ │ ├── email-verification.ts │ │ │ │ │ ├── error.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── ok.ts │ │ │ │ │ ├── reset-password.test.ts │ │ │ │ │ ├── reset-password.ts │ │ │ │ │ ├── session-api.test.ts │ │ │ │ │ ├── session.ts │ │ │ │ │ ├── sign-in.test.ts │ │ │ │ │ ├── sign-in.ts │ │ │ │ │ ├── sign-out.test.ts │ │ │ │ │ ├── sign-out.ts │ │ │ │ │ ├── sign-up.test.ts │ │ │ │ │ ├── sign-up.ts │ │ │ │ │ ├── update-user.test.ts │ │ │ │ │ └── update-user.ts │ │ │ │ ├── to-auth-endpoints.test.ts │ │ │ │ └── to-auth-endpoints.ts │ │ │ ├── auth.test.ts │ │ │ ├── auth.ts │ │ │ ├── call.test.ts │ │ │ ├── client │ │ │ │ ├── client-ssr.test.ts │ │ │ │ ├── client.test.ts │ │ │ │ ├── config.ts │ │ │ │ ├── fetch-plugins.ts │ │ │ │ ├── index.ts │ │ │ │ ├── lynx │ │ │ │ │ ├── index.ts │ │ │ │ │ └── lynx-store.ts │ │ │ │ ├── parser.ts │ │ │ │ ├── path-to-object.ts │ │ │ │ ├── plugins │ │ │ │ │ ├── index.ts │ │ │ │ │ └── infer-plugin.ts │ │ │ │ ├── proxy.ts │ │ │ │ ├── query.ts │ │ │ │ ├── react │ │ │ │ │ ├── index.ts │ │ │ │ │ └── react-store.ts │ │ │ │ ├── session-atom.ts │ │ │ │ ├── solid │ │ │ │ │ ├── index.ts │ │ │ │ │ └── solid-store.ts │ │ │ │ ├── svelte │ │ │ │ │ └── index.ts │ │ │ │ ├── test-plugin.ts │ │ │ │ ├── types.ts │ │ │ │ ├── url.test.ts │ │ │ │ ├── vanilla.ts │ │ │ │ └── vue │ │ │ │ ├── index.ts │ │ │ │ └── vue-store.ts │ │ │ ├── cookies │ │ │ │ ├── check-cookies.ts │ │ │ │ ├── cookie-utils.ts │ │ │ │ ├── cookies.test.ts │ │ │ │ └── index.ts │ │ │ ├── crypto │ │ │ │ ├── buffer.ts │ │ │ │ ├── hash.ts │ │ │ │ ├── index.ts │ │ │ │ ├── jwt.ts │ │ │ │ ├── password.test.ts │ │ │ │ ├── password.ts │ │ │ │ └── random.ts │ │ │ ├── db │ │ │ │ ├── db.test.ts │ │ │ │ ├── field.ts │ │ │ │ ├── get-migration.ts │ │ │ │ ├── get-schema.ts │ │ │ │ ├── get-tables.test.ts │ │ │ │ ├── get-tables.ts │ │ │ │ ├── index.ts │ │ │ │ ├── internal-adapter.test.ts │ │ │ │ ├── internal-adapter.ts │ │ │ │ ├── schema.ts │ │ │ │ ├── secondary-storage.test.ts │ │ │ │ ├── to-zod.ts │ │ │ │ ├── utils.ts │ │ │ │ └── with-hooks.ts │ │ │ ├── index.ts │ │ │ ├── init.test.ts │ │ │ ├── init.ts │ │ │ ├── integrations │ │ │ │ ├── next-js.ts │ │ │ │ ├── node.ts │ │ │ │ ├── react-start.ts │ │ │ │ ├── solid-start.ts │ │ │ │ └── svelte-kit.ts │ │ │ ├── oauth2 │ │ │ │ ├── index.ts │ │ │ │ ├── link-account.test.ts │ │ │ │ ├── link-account.ts │ │ │ │ ├── state.ts │ │ │ │ └── utils.ts │ │ │ ├── plugins │ │ │ │ ├── access │ │ │ │ │ ├── access.test.ts │ │ │ │ │ ├── access.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ └── types.ts │ │ │ │ ├── additional-fields │ │ │ │ │ ├── additional-fields.test.ts │ │ │ │ │ └── client.ts │ │ │ │ ├── admin │ │ │ │ │ ├── access │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── statement.ts │ │ │ │ │ ├── admin.test.ts │ │ │ │ │ ├── admin.ts │ │ │ │ │ ├── client.ts │ │ │ │ │ ├── error-codes.ts │ │ │ │ │ ├── has-permission.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── schema.ts │ │ │ │ │ └── types.ts │ │ │ │ ├── anonymous │ │ │ │ │ ├── anon.test.ts │ │ │ │ │ ├── client.ts │ │ │ │ │ └── index.ts │ │ │ │ ├── api-key │ │ │ │ │ ├── api-key.test.ts │ │ │ │ │ ├── client.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── rate-limit.ts │ │ │ │ │ ├── routes │ │ │ │ │ │ ├── create-api-key.ts │ │ │ │ │ │ ├── delete-all-expired-api-keys.ts │ │ │ │ │ │ ├── delete-api-key.ts │ │ │ │ │ │ ├── get-api-key.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── list-api-keys.ts │ │ │ │ │ │ ├── update-api-key.ts │ │ │ │ │ │ └── verify-api-key.ts │ │ │ │ │ ├── schema.ts │ │ │ │ │ └── types.ts │ │ │ │ ├── bearer │ │ │ │ │ ├── bearer.test.ts │ │ │ │ │ └── index.ts │ │ │ │ ├── captcha │ │ │ │ │ ├── captcha.test.ts │ │ │ │ │ ├── constants.ts │ │ │ │ │ ├── error-codes.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── types.ts │ │ │ │ │ ├── utils.ts │ │ │ │ │ └── verify-handlers │ │ │ │ │ ├── captchafox.ts │ │ │ │ │ ├── cloudflare-turnstile.ts │ │ │ │ │ ├── google-recaptcha.ts │ │ │ │ │ ├── h-captcha.ts │ │ │ │ │ └── index.ts │ │ │ │ ├── custom-session │ │ │ │ │ ├── client.ts │ │ │ │ │ ├── custom-session.test.ts │ │ │ │ │ └── index.ts │ │ │ │ ├── device-authorization │ │ │ │ │ ├── client.ts │ │ │ │ │ ├── device-authorization.test.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ └── schema.ts │ │ │ │ ├── email-otp │ │ │ │ │ ├── client.ts │ │ │ │ │ ├── email-otp.test.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ └── utils.ts │ │ │ │ ├── generic-oauth │ │ │ │ │ ├── client.ts │ │ │ │ │ ├── generic-oauth.test.ts │ │ │ │ │ └── index.ts │ │ │ │ ├── haveibeenpwned │ │ │ │ │ ├── haveibeenpwned.test.ts │ │ │ │ │ └── index.ts │ │ │ │ ├── index.ts │ │ │ │ ├── jwt │ │ │ │ │ ├── adapter.ts │ │ │ │ │ ├── client.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── jwt.test.ts │ │ │ │ │ ├── schema.ts │ │ │ │ │ ├── sign.ts │ │ │ │ │ ├── types.ts │ │ │ │ │ └── utils.ts │ │ │ │ ├── last-login-method │ │ │ │ │ ├── client.ts │ │ │ │ │ ├── custom-prefix.test.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ └── last-login-method.test.ts │ │ │ │ ├── magic-link │ │ │ │ │ ├── client.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── magic-link.test.ts │ │ │ │ │ └── utils.ts │ │ │ │ ├── mcp │ │ │ │ │ ├── authorize.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ └── mcp.test.ts │ │ │ │ ├── multi-session │ │ │ │ │ ├── client.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ └── multi-session.test.ts │ │ │ │ ├── oauth-proxy │ │ │ │ │ ├── index.ts │ │ │ │ │ └── oauth-proxy.test.ts │ │ │ │ ├── oidc-provider │ │ │ │ │ ├── authorize.ts │ │ │ │ │ ├── client.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── oidc.test.ts │ │ │ │ │ ├── schema.ts │ │ │ │ │ ├── types.ts │ │ │ │ │ ├── ui.ts │ │ │ │ │ └── utils.ts │ │ │ │ ├── one-tap │ │ │ │ │ ├── client.ts │ │ │ │ │ └── index.ts │ │ │ │ ├── one-time-token │ │ │ │ │ ├── client.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── one-time-token.test.ts │ │ │ │ │ └── utils.ts │ │ │ │ ├── open-api │ │ │ │ │ ├── generator.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── logo.ts │ │ │ │ │ └── open-api.test.ts │ │ │ │ ├── organization │ │ │ │ │ ├── access │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── statement.ts │ │ │ │ │ ├── adapter.ts │ │ │ │ │ ├── call.ts │ │ │ │ │ ├── client.test.ts │ │ │ │ │ ├── client.ts │ │ │ │ │ ├── error-codes.ts │ │ │ │ │ ├── has-permission.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── organization-hook.test.ts │ │ │ │ │ ├── organization.test.ts │ │ │ │ │ ├── organization.ts │ │ │ │ │ ├── permission.ts │ │ │ │ │ ├── routes │ │ │ │ │ │ ├── crud-access-control.test.ts │ │ │ │ │ │ ├── crud-access-control.ts │ │ │ │ │ │ ├── crud-invites.ts │ │ │ │ │ │ ├── crud-members.test.ts │ │ │ │ │ │ ├── crud-members.ts │ │ │ │ │ │ ├── crud-org.test.ts │ │ │ │ │ │ ├── crud-org.ts │ │ │ │ │ │ └── crud-team.ts │ │ │ │ │ ├── schema.ts │ │ │ │ │ ├── team.test.ts │ │ │ │ │ └── types.ts │ │ │ │ ├── passkey │ │ │ │ │ ├── client.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ └── passkey.test.ts │ │ │ │ ├── phone-number │ │ │ │ │ ├── client.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── phone-number-error.ts │ │ │ │ │ └── phone-number.test.ts │ │ │ │ ├── siwe │ │ │ │ │ ├── client.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── schema.ts │ │ │ │ │ ├── siwe.test.ts │ │ │ │ │ └── types.ts │ │ │ │ ├── sso │ │ │ │ │ ├── client.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ └── sso.test.ts │ │ │ │ ├── two-factor │ │ │ │ │ ├── backup-codes │ │ │ │ │ │ └── index.ts │ │ │ │ │ ├── client.ts │ │ │ │ │ ├── constant.ts │ │ │ │ │ ├── error-code.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── otp │ │ │ │ │ │ └── index.ts │ │ │ │ │ ├── schema.ts │ │ │ │ │ ├── totp │ │ │ │ │ │ └── index.ts │ │ │ │ │ ├── two-factor.test.ts │ │ │ │ │ ├── types.ts │ │ │ │ │ ├── utils.ts │ │ │ │ │ └── verify-two-factor.ts │ │ │ │ └── username │ │ │ │ ├── client.ts │ │ │ │ ├── error-codes.ts │ │ │ │ ├── index.ts │ │ │ │ ├── schema.ts │ │ │ │ └── username.test.ts │ │ │ ├── social-providers │ │ │ │ └── index.ts │ │ │ ├── social.test.ts │ │ │ ├── test-utils │ │ │ │ ├── headers.ts │ │ │ │ ├── index.ts │ │ │ │ ├── state.ts │ │ │ │ └── test-instance.ts │ │ │ ├── types │ │ │ │ ├── adapter.ts │ │ │ │ ├── api.ts │ │ │ │ ├── helper.ts │ │ │ │ ├── index.ts │ │ │ │ ├── models.ts │ │ │ │ ├── plugins.ts │ │ │ │ └── types.test.ts │ │ │ └── utils │ │ │ ├── await-object.ts │ │ │ ├── boolean.ts │ │ │ ├── clone.ts │ │ │ ├── constants.ts │ │ │ ├── date.ts │ │ │ ├── ensure-utc.ts │ │ │ ├── get-request-ip.ts │ │ │ ├── hashing.ts │ │ │ ├── hide-metadata.ts │ │ │ ├── id.ts │ │ │ ├── import-util.ts │ │ │ ├── index.ts │ │ │ ├── is-atom.ts │ │ │ ├── is-promise.ts │ │ │ ├── json.ts │ │ │ ├── merger.ts │ │ │ ├── middleware-response.ts │ │ │ ├── misc.ts │ │ │ ├── password.ts │ │ │ ├── plugin-helper.ts │ │ │ ├── shim.ts │ │ │ ├── time.ts │ │ │ ├── url.ts │ │ │ └── wildcard.ts │ │ ├── tsconfig.json │ │ ├── tsdown.config.ts │ │ └── vitest.config.ts │ ├── cli │ │ ├── CHANGELOG.md │ │ ├── package.json │ │ ├── README.md │ │ ├── src │ │ │ ├── commands │ │ │ │ ├── generate.ts │ │ │ │ ├── info.ts │ │ │ │ ├── init.ts │ │ │ │ ├── login.ts │ │ │ │ ├── mcp.ts │ │ │ │ ├── migrate.ts │ │ │ │ └── secret.ts │ │ │ ├── generators │ │ │ │ ├── auth-config.ts │ │ │ │ ├── drizzle.ts │ │ │ │ ├── index.ts │ │ │ │ ├── kysely.ts │ │ │ │ ├── prisma.ts │ │ │ │ └── types.ts │ │ │ ├── index.ts │ │ │ └── utils │ │ │ ├── add-svelte-kit-env-modules.ts │ │ │ ├── check-package-managers.ts │ │ │ ├── format-ms.ts │ │ │ ├── get-config.ts │ │ │ ├── get-package-info.ts │ │ │ ├── get-tsconfig-info.ts │ │ │ └── install-dependencies.ts │ │ ├── test │ │ │ ├── __snapshots__ │ │ │ │ ├── auth-schema-mysql-enum.txt │ │ │ │ ├── auth-schema-mysql-number-id.txt │ │ │ │ ├── auth-schema-mysql-passkey-number-id.txt │ │ │ │ ├── auth-schema-mysql-passkey.txt │ │ │ │ ├── auth-schema-mysql.txt │ │ │ │ ├── auth-schema-number-id.txt │ │ │ │ ├── auth-schema-pg-enum.txt │ │ │ │ ├── auth-schema-pg-passkey.txt │ │ │ │ ├── auth-schema-sqlite-enum.txt │ │ │ │ ├── auth-schema-sqlite-number-id.txt │ │ │ │ ├── auth-schema-sqlite-passkey-number-id.txt │ │ │ │ ├── auth-schema-sqlite-passkey.txt │ │ │ │ ├── auth-schema-sqlite.txt │ │ │ │ ├── auth-schema.txt │ │ │ │ ├── migrations.sql │ │ │ │ ├── schema-mongodb.prisma │ │ │ │ ├── schema-mysql-custom.prisma │ │ │ │ ├── schema-mysql.prisma │ │ │ │ ├── schema-numberid.prisma │ │ │ │ └── schema.prisma │ │ │ ├── generate-all-db.test.ts │ │ │ ├── generate.test.ts │ │ │ ├── get-config.test.ts │ │ │ ├── info.test.ts │ │ │ └── migrate.test.ts │ │ ├── tsconfig.json │ │ ├── tsconfig.test.json │ │ └── tsdown.config.ts │ ├── core │ │ ├── package.json │ │ ├── src │ │ │ ├── async_hooks │ │ │ │ └── index.ts │ │ │ ├── context │ │ │ │ ├── index.ts │ │ │ │ └── transaction.ts │ │ │ ├── db │ │ │ │ ├── adapter │ │ │ │ │ └── index.ts │ │ │ │ ├── index.ts │ │ │ │ ├── plugin.ts │ │ │ │ ├── schema │ │ │ │ │ ├── account.ts │ │ │ │ │ ├── rate-limit.ts │ │ │ │ │ ├── session.ts │ │ │ │ │ ├── shared.ts │ │ │ │ │ ├── user.ts │ │ │ │ │ └── verification.ts │ │ │ │ └── type.ts │ │ │ ├── env │ │ │ │ ├── color-depth.ts │ │ │ │ ├── env-impl.ts │ │ │ │ ├── index.ts │ │ │ │ ├── logger.test.ts │ │ │ │ └── logger.ts │ │ │ ├── error │ │ │ │ ├── codes.ts │ │ │ │ └── index.ts │ │ │ ├── index.ts │ │ │ ├── middleware │ │ │ │ └── index.ts │ │ │ ├── oauth2 │ │ │ │ ├── client-credentials-token.ts │ │ │ │ ├── create-authorization-url.ts │ │ │ │ ├── index.ts │ │ │ │ ├── oauth-provider.ts │ │ │ │ ├── refresh-access-token.ts │ │ │ │ ├── utils.ts │ │ │ │ └── validate-authorization-code.ts │ │ │ ├── social-providers │ │ │ │ ├── apple.ts │ │ │ │ ├── atlassian.ts │ │ │ │ ├── cognito.ts │ │ │ │ ├── discord.ts │ │ │ │ ├── dropbox.ts │ │ │ │ ├── facebook.ts │ │ │ │ ├── figma.ts │ │ │ │ ├── github.ts │ │ │ │ ├── gitlab.ts │ │ │ │ ├── google.ts │ │ │ │ ├── huggingface.ts │ │ │ │ ├── index.ts │ │ │ │ ├── kakao.ts │ │ │ │ ├── kick.ts │ │ │ │ ├── line.ts │ │ │ │ ├── linear.ts │ │ │ │ ├── linkedin.ts │ │ │ │ ├── microsoft-entra-id.ts │ │ │ │ ├── naver.ts │ │ │ │ ├── notion.ts │ │ │ │ ├── paypal.ts │ │ │ │ ├── reddit.ts │ │ │ │ ├── roblox.ts │ │ │ │ ├── salesforce.ts │ │ │ │ ├── slack.ts │ │ │ │ ├── spotify.ts │ │ │ │ ├── tiktok.ts │ │ │ │ ├── twitch.ts │ │ │ │ ├── twitter.ts │ │ │ │ ├── vk.ts │ │ │ │ └── zoom.ts │ │ │ ├── types │ │ │ │ ├── context.ts │ │ │ │ ├── cookie.ts │ │ │ │ ├── helper.ts │ │ │ │ ├── index.ts │ │ │ │ ├── init-options.ts │ │ │ │ ├── plugin-client.ts │ │ │ │ └── plugin.ts │ │ │ └── utils │ │ │ ├── error-codes.ts │ │ │ └── index.ts │ │ ├── tsconfig.json │ │ └── tsdown.config.ts │ ├── expo │ │ ├── CHANGELOG.md │ │ ├── package.json │ │ ├── README.md │ │ ├── src │ │ │ ├── client.ts │ │ │ ├── expo.test.ts │ │ │ └── index.ts │ │ ├── tsconfig.json │ │ └── tsdown.config.ts │ ├── sso │ │ ├── package.json │ │ ├── src │ │ │ ├── client.ts │ │ │ ├── index.ts │ │ │ ├── oidc.test.ts │ │ │ └── saml.test.ts │ │ ├── tsconfig.json │ │ └── tsdown.config.ts │ ├── stripe │ │ ├── CHANGELOG.md │ │ ├── package.json │ │ ├── src │ │ │ ├── client.ts │ │ │ ├── hooks.ts │ │ │ ├── index.ts │ │ │ ├── schema.ts │ │ │ ├── stripe.test.ts │ │ │ ├── types.ts │ │ │ └── utils.ts │ │ ├── tsconfig.json │ │ ├── tsdown.config.ts │ │ └── vitest.config.ts │ └── telemetry │ ├── package.json │ ├── src │ │ ├── detectors │ │ │ ├── detect-auth-config.ts │ │ │ ├── detect-database.ts │ │ │ ├── detect-framework.ts │ │ │ ├── detect-project-info.ts │ │ │ ├── detect-runtime.ts │ │ │ └── detect-system-info.ts │ │ ├── index.ts │ │ ├── project-id.ts │ │ ├── telemetry.test.ts │ │ ├── types.ts │ │ └── utils │ │ ├── hash.ts │ │ ├── id.ts │ │ ├── import-util.ts │ │ └── package-json.ts │ ├── tsconfig.json │ └── tsdown.config.ts ├── pnpm-lock.yaml ├── pnpm-workspace.yaml ├── README.md ├── SECURITY.md ├── tsconfig.json └── turbo.json ``` # Files -------------------------------------------------------------------------------- /packages/sso/src/index.ts: -------------------------------------------------------------------------------- ```typescript import { generateState, type Account, type BetterAuthPlugin, type OAuth2Tokens, type Session, type User, } from "better-auth"; import { APIError, sessionMiddleware } from "better-auth/api"; import { createAuthorizationURL, handleOAuthUserInfo, parseState, validateAuthorizationCode, validateToken, } from "better-auth/oauth2"; import { createAuthEndpoint } from "better-auth/plugins"; import * as z from "zod/v4"; import * as saml from "samlify"; import type { BindingContext } from "samlify/types/src/entity"; import { betterFetch, BetterFetchError } from "@better-fetch/fetch"; import { decodeJwt } from "jose"; import { setSessionCookie } from "better-auth/cookies"; import type { FlowResult } from "samlify/types/src/flow"; import { XMLValidator } from "fast-xml-parser"; import type { IdentityProvider } from "samlify/types/src/entity-idp"; const fastValidator = { async validate(xml: string) { const isValid = XMLValidator.validate(xml, { allowBooleanAttributes: true, }); if (isValid === true) return "SUCCESS_VALIDATE_XML"; throw "ERR_INVALID_XML"; }, }; saml.setSchemaValidator(fastValidator); /** * Safely parses a value that might be a JSON string or already a parsed object * This handles cases where ORMs like Drizzle might return already parsed objects * instead of JSON strings from TEXT/JSON columns */ function safeJsonParse<T>(value: string | T | null | undefined): T | null { if (!value) return null; // If it's already an object (not a string), return it as-is if (typeof value === "object") { return value as T; } // If it's a string, try to parse it if (typeof value === "string") { try { return JSON.parse(value) as T; } catch (error) { // If parsing fails, this might indicate the string is not valid JSON throw new Error( `Failed to parse JSON: ${error instanceof Error ? error.message : "Unknown error"}`, ); } } return null; } export interface OIDCMapping { id?: string; email?: string; emailVerified?: string; name?: string; image?: string; extraFields?: Record<string, string>; } export interface SAMLMapping { id?: string; email?: string; emailVerified?: string; name?: string; firstName?: string; lastName?: string; extraFields?: Record<string, string>; } export interface OIDCConfig { issuer: string; pkce: boolean; clientId: string; clientSecret: string; authorizationEndpoint?: string; discoveryEndpoint: string; userInfoEndpoint?: string; scopes?: string[]; overrideUserInfo?: boolean; tokenEndpoint?: string; tokenEndpointAuthentication?: "client_secret_post" | "client_secret_basic"; jwksEndpoint?: string; mapping?: OIDCMapping; } export interface SAMLConfig { issuer: string; entryPoint: string; cert: string; callbackUrl: string; audience?: string; idpMetadata?: { metadata?: string; entityID?: string; entityURL?: string; redirectURL?: string; cert?: string; privateKey?: string; privateKeyPass?: string; isAssertionEncrypted?: boolean; encPrivateKey?: string; encPrivateKeyPass?: string; singleSignOnService?: Array<{ Binding: string; Location: string; }>; }; spMetadata: { metadata?: string; entityID?: string; binding?: string; privateKey?: string; privateKeyPass?: string; isAssertionEncrypted?: boolean; encPrivateKey?: string; encPrivateKeyPass?: string; }; wantAssertionsSigned?: boolean; signatureAlgorithm?: string; digestAlgorithm?: string; identifierFormat?: string; privateKey?: string; decryptionPvk?: string; additionalParams?: Record<string, any>; mapping?: SAMLMapping; } export interface SSOProvider { issuer: string; oidcConfig?: OIDCConfig; samlConfig?: SAMLConfig; userId: string; providerId: string; organizationId?: string; } export interface SSOOptions { /** * custom function to provision a user when they sign in with an SSO provider. */ provisionUser?: (data: { /** * The user object from the database */ user: User & Record<string, any>; /** * The user info object from the provider */ userInfo: Record<string, any>; /** * The OAuth2 tokens from the provider */ token?: OAuth2Tokens; /** * The SSO provider */ provider: SSOProvider; }) => Promise<void>; /** * Organization provisioning options */ organizationProvisioning?: { disabled?: boolean; defaultRole?: "member" | "admin"; getRole?: (data: { /** * The user object from the database */ user: User & Record<string, any>; /** * The user info object from the provider */ userInfo: Record<string, any>; /** * The OAuth2 tokens from the provider */ token?: OAuth2Tokens; /** * The SSO provider */ provider: SSOProvider; }) => Promise<"member" | "admin">; }; /** * Default SSO provider configurations for testing. * These will take the precedence over the database providers. */ defaultSSO?: Array<{ /** * The domain to match for this default provider. * This is only used to match incoming requests to this default provider. */ domain: string; /** * The provider ID to use */ providerId: string; /** * SAML configuration */ samlConfig?: SAMLConfig; /** * OIDC configuration */ oidcConfig?: OIDCConfig; }>; /** * Override user info with the provider info. * @default false */ defaultOverrideUserInfo?: boolean; /** * Disable implicit sign up for new users. When set to true for the provider, * sign-in need to be called with with requestSignUp as true to create new users. */ disableImplicitSignUp?: boolean; /** * Configure the maximum number of SSO providers a user can register. * You can also pass a function that returns a number. * Set to 0 to disable SSO provider registration. * * @example * ```ts * providersLimit: async (user) => { * const plan = await getUserPlan(user); * return plan.name === "pro" ? 10 : 1; * } * ``` * @default 10 */ providersLimit?: number | ((user: User) => Promise<number> | number); /** * Trust the email verified flag from the provider. * @default false */ trustEmailVerified?: boolean; } export const sso = (options?: SSOOptions) => { return { id: "sso", endpoints: { spMetadata: createAuthEndpoint( "/sso/saml2/sp/metadata", { method: "GET", query: z.object({ providerId: z.string(), format: z.enum(["xml", "json"]).default("xml"), }), metadata: { openapi: { summary: "Get Service Provider metadata", description: "Returns the SAML metadata for the Service Provider", responses: { "200": { description: "SAML metadata in XML format", }, }, }, }, }, async (ctx) => { const provider = await ctx.context.adapter.findOne<{ id: string; samlConfig: string; }>({ model: "ssoProvider", where: [ { field: "providerId", value: ctx.query.providerId, }, ], }); if (!provider) { throw new APIError("NOT_FOUND", { message: "No provider found for the given providerId", }); } const parsedSamlConfig = safeJsonParse<SAMLConfig>( provider.samlConfig, ); if (!parsedSamlConfig) { throw new APIError("BAD_REQUEST", { message: "Invalid SAML configuration", }); } const sp = parsedSamlConfig.spMetadata.metadata ? saml.ServiceProvider({ metadata: parsedSamlConfig.spMetadata.metadata, }) : saml.SPMetadata({ entityID: parsedSamlConfig.spMetadata?.entityID || parsedSamlConfig.issuer, assertionConsumerService: [ { Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST", Location: parsedSamlConfig.callbackUrl || `${ctx.context.baseURL}/sso/saml2/sp/acs/${provider.id}`, }, ], wantMessageSigned: parsedSamlConfig.wantAssertionsSigned || false, nameIDFormat: parsedSamlConfig.identifierFormat ? [parsedSamlConfig.identifierFormat] : undefined, }); return new Response(sp.getMetadata(), { headers: { "Content-Type": "application/xml", }, }); }, ), registerSSOProvider: createAuthEndpoint( "/sso/register", { method: "POST", body: z.object({ providerId: z.string({}).meta({ description: "The ID of the provider. This is used to identify the provider during login and callback", }), issuer: z.string({}).meta({ description: "The issuer of the provider", }), domain: z.string({}).meta({ description: "The domain of the provider. This is used for email matching", }), oidcConfig: z .object({ clientId: z.string({}).meta({ description: "The client ID", }), clientSecret: z.string({}).meta({ description: "The client secret", }), authorizationEndpoint: z .string({}) .meta({ description: "The authorization endpoint", }) .optional(), tokenEndpoint: z .string({}) .meta({ description: "The token endpoint", }) .optional(), userInfoEndpoint: z .string({}) .meta({ description: "The user info endpoint", }) .optional(), tokenEndpointAuthentication: z .enum(["client_secret_post", "client_secret_basic"]) .optional(), jwksEndpoint: z .string({}) .meta({ description: "The JWKS endpoint", }) .optional(), discoveryEndpoint: z.string().optional(), scopes: z .array(z.string(), {}) .meta({ description: "The scopes to request. Defaults to ['openid', 'email', 'profile', 'offline_access']", }) .optional(), pkce: z .boolean({}) .meta({ description: "Whether to use PKCE for the authorization flow", }) .default(true) .optional(), mapping: z .object({ id: z.string({}).meta({ description: "Field mapping for user ID (defaults to 'sub')", }), email: z.string({}).meta({ description: "Field mapping for email (defaults to 'email')", }), emailVerified: z .string({}) .meta({ description: "Field mapping for email verification (defaults to 'email_verified')", }) .optional(), name: z.string({}).meta({ description: "Field mapping for name (defaults to 'name')", }), image: z .string({}) .meta({ description: "Field mapping for image (defaults to 'picture')", }) .optional(), extraFields: z.record(z.string(), z.any()).optional(), }) .optional(), }) .optional(), samlConfig: z .object({ entryPoint: z.string({}).meta({ description: "The entry point of the provider", }), cert: z.string({}).meta({ description: "The certificate of the provider", }), callbackUrl: z.string({}).meta({ description: "The callback URL of the provider", }), audience: z.string().optional(), idpMetadata: z .object({ metadata: z.string().optional(), entityID: z.string().optional(), cert: z.string().optional(), privateKey: z.string().optional(), privateKeyPass: z.string().optional(), isAssertionEncrypted: z.boolean().optional(), encPrivateKey: z.string().optional(), encPrivateKeyPass: z.string().optional(), singleSignOnService: z .array( z.object({ Binding: z.string().meta({ description: "The binding type for the SSO service", }), Location: z.string().meta({ description: "The URL for the SSO service", }), }), ) .optional() .meta({ description: "Single Sign-On service configuration", }), }) .optional(), spMetadata: z.object({ metadata: z.string().optional(), entityID: z.string().optional(), binding: z.string().optional(), privateKey: z.string().optional(), privateKeyPass: z.string().optional(), isAssertionEncrypted: z.boolean().optional(), encPrivateKey: z.string().optional(), encPrivateKeyPass: z.string().optional(), }), wantAssertionsSigned: z.boolean().optional(), signatureAlgorithm: z.string().optional(), digestAlgorithm: z.string().optional(), identifierFormat: z.string().optional(), privateKey: z.string().optional(), decryptionPvk: z.string().optional(), additionalParams: z.record(z.string(), z.any()).optional(), mapping: z .object({ id: z.string({}).meta({ description: "Field mapping for user ID (defaults to 'nameID')", }), email: z.string({}).meta({ description: "Field mapping for email (defaults to 'email')", }), emailVerified: z .string({}) .meta({ description: "Field mapping for email verification", }) .optional(), name: z.string({}).meta({ description: "Field mapping for name (defaults to 'displayName')", }), firstName: z .string({}) .meta({ description: "Field mapping for first name (defaults to 'givenName')", }) .optional(), lastName: z .string({}) .meta({ description: "Field mapping for last name (defaults to 'surname')", }) .optional(), extraFields: z.record(z.string(), z.any()).optional(), }) .optional(), }) .optional(), organizationId: z .string({}) .meta({ description: "If organization plugin is enabled, the organization id to link the provider to", }) .optional(), overrideUserInfo: z .boolean({}) .meta({ description: "Override user info with the provider info. Defaults to false", }) .default(false) .optional(), }), use: [sessionMiddleware], metadata: { openapi: { summary: "Register an OIDC provider", description: "This endpoint is used to register an OIDC provider. This is used to configure the provider and link it to an organization", responses: { "200": { description: "OIDC provider created successfully", content: { "application/json": { schema: { type: "object", properties: { issuer: { type: "string", format: "uri", description: "The issuer URL of the provider", }, domain: { type: "string", description: "The domain of the provider, used for email matching", }, oidcConfig: { type: "object", properties: { issuer: { type: "string", format: "uri", description: "The issuer URL of the provider", }, pkce: { type: "boolean", description: "Whether PKCE is enabled for the authorization flow", }, clientId: { type: "string", description: "The client ID for the provider", }, clientSecret: { type: "string", description: "The client secret for the provider", }, authorizationEndpoint: { type: "string", format: "uri", nullable: true, description: "The authorization endpoint URL", }, discoveryEndpoint: { type: "string", format: "uri", description: "The discovery endpoint URL", }, userInfoEndpoint: { type: "string", format: "uri", nullable: true, description: "The user info endpoint URL", }, scopes: { type: "array", items: { type: "string" }, nullable: true, description: "The scopes requested from the provider", }, tokenEndpoint: { type: "string", format: "uri", nullable: true, description: "The token endpoint URL", }, tokenEndpointAuthentication: { type: "string", enum: [ "client_secret_post", "client_secret_basic", ], nullable: true, description: "Authentication method for the token endpoint", }, jwksEndpoint: { type: "string", format: "uri", nullable: true, description: "The JWKS endpoint URL", }, mapping: { type: "object", nullable: true, properties: { id: { type: "string", description: "Field mapping for user ID (defaults to 'sub')", }, email: { type: "string", description: "Field mapping for email (defaults to 'email')", }, emailVerified: { type: "string", nullable: true, description: "Field mapping for email verification (defaults to 'email_verified')", }, name: { type: "string", description: "Field mapping for name (defaults to 'name')", }, image: { type: "string", nullable: true, description: "Field mapping for image (defaults to 'picture')", }, extraFields: { type: "object", additionalProperties: { type: "string" }, nullable: true, description: "Additional field mappings", }, }, required: ["id", "email", "name"], }, }, required: [ "issuer", "pkce", "clientId", "clientSecret", "discoveryEndpoint", ], description: "OIDC configuration for the provider", }, organizationId: { type: "string", nullable: true, description: "ID of the linked organization, if any", }, userId: { type: "string", description: "ID of the user who registered the provider", }, providerId: { type: "string", description: "Unique identifier for the provider", }, redirectURI: { type: "string", format: "uri", description: "The redirect URI for the provider callback", }, }, required: [ "issuer", "domain", "oidcConfig", "userId", "providerId", "redirectURI", ], }, }, }, }, }, }, }, }, async (ctx) => { const user = ctx.context.session?.user; if (!user) { throw new APIError("UNAUTHORIZED"); } const limit = typeof options?.providersLimit === "function" ? await options.providersLimit(user) : (options?.providersLimit ?? 10); if (!limit) { throw new APIError("FORBIDDEN", { message: "SSO provider registration is disabled", }); } const providers = await ctx.context.adapter.findMany({ model: "ssoProvider", where: [{ field: "userId", value: user.id }], }); if (providers.length >= limit) { throw new APIError("FORBIDDEN", { message: "You have reached the maximum number of SSO providers", }); } const body = ctx.body; const issuerValidator = z.string().url(); if (issuerValidator.safeParse(body.issuer).error) { throw new APIError("BAD_REQUEST", { message: "Invalid issuer. Must be a valid URL", }); } if (ctx.body.organizationId) { const organization = await ctx.context.adapter.findOne({ model: "member", where: [ { field: "userId", value: user.id, }, { field: "organizationId", value: ctx.body.organizationId, }, ], }); if (!organization) { throw new APIError("BAD_REQUEST", { message: "You are not a member of the organization", }); } } const existingProvider = await ctx.context.adapter.findOne({ model: "ssoProvider", where: [ { field: "providerId", value: body.providerId, }, ], }); if (existingProvider) { ctx.context.logger.info( `SSO provider creation attempt with existing providerId: ${body.providerId}`, ); throw new APIError("UNPROCESSABLE_ENTITY", { message: "SSO provider with this providerId already exists", }); } const provider = await ctx.context.adapter.create< Record<string, any>, SSOProvider >({ model: "ssoProvider", data: { issuer: body.issuer, domain: body.domain, oidcConfig: body.oidcConfig ? JSON.stringify({ issuer: body.issuer, clientId: body.oidcConfig.clientId, clientSecret: body.oidcConfig.clientSecret, authorizationEndpoint: body.oidcConfig.authorizationEndpoint, tokenEndpoint: body.oidcConfig.tokenEndpoint, tokenEndpointAuthentication: body.oidcConfig.tokenEndpointAuthentication, jwksEndpoint: body.oidcConfig.jwksEndpoint, pkce: body.oidcConfig.pkce, discoveryEndpoint: body.oidcConfig.discoveryEndpoint || `${body.issuer}/.well-known/openid-configuration`, mapping: body.oidcConfig.mapping, scopes: body.oidcConfig.scopes, userInfoEndpoint: body.oidcConfig.userInfoEndpoint, overrideUserInfo: ctx.body.overrideUserInfo || options?.defaultOverrideUserInfo || false, }) : null, samlConfig: body.samlConfig ? JSON.stringify({ issuer: body.issuer, entryPoint: body.samlConfig.entryPoint, cert: body.samlConfig.cert, callbackUrl: body.samlConfig.callbackUrl, audience: body.samlConfig.audience, idpMetadata: body.samlConfig.idpMetadata, spMetadata: body.samlConfig.spMetadata, wantAssertionsSigned: body.samlConfig.wantAssertionsSigned, signatureAlgorithm: body.samlConfig.signatureAlgorithm, digestAlgorithm: body.samlConfig.digestAlgorithm, identifierFormat: body.samlConfig.identifierFormat, privateKey: body.samlConfig.privateKey, decryptionPvk: body.samlConfig.decryptionPvk, additionalParams: body.samlConfig.additionalParams, mapping: body.samlConfig.mapping, }) : null, organizationId: body.organizationId, userId: ctx.context.session.user.id, providerId: body.providerId, }, }); return ctx.json({ ...provider, oidcConfig: JSON.parse( provider.oidcConfig as unknown as string, ) as OIDCConfig, samlConfig: JSON.parse( provider.samlConfig as unknown as string, ) as SAMLConfig, redirectURI: `${ctx.context.baseURL}/sso/callback/${provider.providerId}`, }); }, ), signInSSO: createAuthEndpoint( "/sign-in/sso", { method: "POST", body: z.object({ email: z .string({}) .meta({ description: "The email address to sign in with. This is used to identify the issuer to sign in with. It's optional if the issuer is provided", }) .optional(), organizationSlug: z .string({}) .meta({ description: "The slug of the organization to sign in with", }) .optional(), providerId: z .string({}) .meta({ description: "The ID of the provider to sign in with. This can be provided instead of email or issuer", }) .optional(), domain: z .string({}) .meta({ description: "The domain of the provider.", }) .optional(), callbackURL: z.string({}).meta({ description: "The URL to redirect to after login", }), errorCallbackURL: z .string({}) .meta({ description: "The URL to redirect to after login", }) .optional(), newUserCallbackURL: z .string({}) .meta({ description: "The URL to redirect to after login if the user is new", }) .optional(), scopes: z .array(z.string(), {}) .meta({ description: "Scopes to request from the provider.", }) .optional(), requestSignUp: z .boolean({}) .meta({ description: "Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider", }) .optional(), providerType: z.enum(["oidc", "saml"]).optional(), }), metadata: { openapi: { summary: "Sign in with SSO provider", description: "This endpoint is used to sign in with an SSO provider. It redirects to the provider's authorization URL", requestBody: { content: { "application/json": { schema: { type: "object", properties: { email: { type: "string", description: "The email address to sign in with. This is used to identify the issuer to sign in with. It's optional if the issuer is provided", }, issuer: { type: "string", description: "The issuer identifier, this is the URL of the provider and can be used to verify the provider and identify the provider during login. It's optional if the email is provided", }, providerId: { type: "string", description: "The ID of the provider to sign in with. This can be provided instead of email or issuer", }, callbackURL: { type: "string", description: "The URL to redirect to after login", }, errorCallbackURL: { type: "string", description: "The URL to redirect to after login", }, newUserCallbackURL: { type: "string", description: "The URL to redirect to after login if the user is new", }, }, required: ["callbackURL"], }, }, }, }, responses: { "200": { description: "Authorization URL generated successfully for SSO sign-in", content: { "application/json": { schema: { type: "object", properties: { url: { type: "string", format: "uri", description: "The authorization URL to redirect the user to for SSO sign-in", }, redirect: { type: "boolean", description: "Indicates that the client should redirect to the provided URL", enum: [true], }, }, required: ["url", "redirect"], }, }, }, }, }, }, }, }, async (ctx) => { const body = ctx.body; let { email, organizationSlug, providerId, domain } = body; if ( !options?.defaultSSO?.length && !email && !organizationSlug && !domain && !providerId ) { throw new APIError("BAD_REQUEST", { message: "email, organizationSlug, domain or providerId is required", }); } domain = body.domain || email?.split("@")[1]; let orgId = ""; if (organizationSlug) { orgId = await ctx.context.adapter .findOne<{ id: string }>({ model: "organization", where: [ { field: "slug", value: organizationSlug, }, ], }) .then((res) => { if (!res) { return ""; } return res.id; }); } let provider: SSOProvider | null = null; if (options?.defaultSSO?.length) { // Find matching default SSO provider by providerId const matchingDefault = providerId ? options.defaultSSO.find( (defaultProvider) => defaultProvider.providerId === providerId, ) : options.defaultSSO.find( (defaultProvider) => defaultProvider.domain === domain, ); if (matchingDefault) { provider = { issuer: matchingDefault.samlConfig?.issuer || matchingDefault.oidcConfig?.issuer || "", providerId: matchingDefault.providerId, userId: "default", oidcConfig: matchingDefault.oidcConfig, samlConfig: matchingDefault.samlConfig, }; } } if (!providerId && !orgId && !domain) { throw new APIError("BAD_REQUEST", { message: "providerId, orgId or domain is required", }); } // Try to find provider in database if (!provider) { provider = await ctx.context.adapter .findOne<SSOProvider>({ model: "ssoProvider", where: [ { field: providerId ? "providerId" : orgId ? "organizationId" : "domain", value: providerId || orgId || domain!, }, ], }) .then((res) => { if (!res) { return null; } return { ...res, oidcConfig: res.oidcConfig ? safeJsonParse<OIDCConfig>( res.oidcConfig as unknown as string, ) || undefined : undefined, samlConfig: res.samlConfig ? safeJsonParse<SAMLConfig>( res.samlConfig as unknown as string, ) || undefined : undefined, }; }); } if (!provider) { throw new APIError("NOT_FOUND", { message: "No provider found for the issuer", }); } if (body.providerType) { if (body.providerType === "oidc" && !provider.oidcConfig) { throw new APIError("BAD_REQUEST", { message: "OIDC provider is not configured", }); } if (body.providerType === "saml" && !provider.samlConfig) { throw new APIError("BAD_REQUEST", { message: "SAML provider is not configured", }); } } if (provider.oidcConfig && body.providerType !== "saml") { const state = await generateState(ctx); const redirectURI = `${ctx.context.baseURL}/sso/callback/${provider.providerId}`; const authorizationURL = await createAuthorizationURL({ id: provider.issuer, options: { clientId: provider.oidcConfig.clientId, clientSecret: provider.oidcConfig.clientSecret, }, redirectURI, state: state.state, codeVerifier: provider.oidcConfig.pkce ? state.codeVerifier : undefined, scopes: ctx.body.scopes || provider.oidcConfig.scopes || [ "openid", "email", "profile", "offline_access", ], authorizationEndpoint: provider.oidcConfig.authorizationEndpoint!, }); return ctx.json({ url: authorizationURL.toString(), redirect: true, }); } if (provider.samlConfig) { const parsedSamlConfig = typeof provider.samlConfig === "object" ? provider.samlConfig : safeJsonParse<SAMLConfig>( provider.samlConfig as unknown as string, ); if (!parsedSamlConfig) { throw new APIError("BAD_REQUEST", { message: "Invalid SAML configuration", }); } const sp = saml.ServiceProvider({ metadata: parsedSamlConfig.spMetadata.metadata, allowCreate: true, }); const idp = saml.IdentityProvider({ metadata: parsedSamlConfig.idpMetadata?.metadata, entityID: parsedSamlConfig.idpMetadata?.entityID, encryptCert: parsedSamlConfig.idpMetadata?.cert, singleSignOnService: parsedSamlConfig.idpMetadata?.singleSignOnService, }); const loginRequest = sp.createLoginRequest( idp, "redirect", ) as BindingContext & { entityEndpoint: string; type: string }; if (!loginRequest) { throw new APIError("BAD_REQUEST", { message: "Invalid SAML request", }); } return ctx.json({ url: `${loginRequest.context}&RelayState=${encodeURIComponent( body.callbackURL, )}`, redirect: true, }); } throw new APIError("BAD_REQUEST", { message: "Invalid SSO provider", }); }, ), callbackSSO: createAuthEndpoint( "/sso/callback/:providerId", { method: "GET", query: z.object({ code: z.string().optional(), state: z.string(), error: z.string().optional(), error_description: z.string().optional(), }), metadata: { isAction: false, openapi: { summary: "Callback URL for SSO provider", description: "This endpoint is used as the callback URL for SSO providers. It handles the authorization code and exchanges it for an access token", responses: { "302": { description: "Redirects to the callback URL", }, }, }, }, }, async (ctx) => { const { code, state, error, error_description } = ctx.query; const stateData = await parseState(ctx); if (!stateData) { const errorURL = ctx.context.options.onAPIError?.errorURL || `${ctx.context.baseURL}/error`; throw ctx.redirect(`${errorURL}?error=invalid_state`); } const { callbackURL, errorURL, newUserURL, requestSignUp } = stateData; if (!code || error) { throw ctx.redirect( `${ errorURL || callbackURL }?error=${error}&error_description=${error_description}`, ); } let provider: SSOProvider | null = null; if (options?.defaultSSO?.length) { const matchingDefault = options.defaultSSO.find( (defaultProvider) => defaultProvider.providerId === ctx.params.providerId, ); if (matchingDefault) { provider = { ...matchingDefault, issuer: matchingDefault.oidcConfig?.issuer || "", userId: "default", }; } } if (!provider) { provider = await ctx.context.adapter .findOne<{ oidcConfig: string; }>({ model: "ssoProvider", where: [ { field: "providerId", value: ctx.params.providerId, }, ], }) .then((res) => { if (!res) { return null; } return { ...res, oidcConfig: safeJsonParse<OIDCConfig>(res.oidcConfig) || undefined, } as SSOProvider; }); } if (!provider) { throw ctx.redirect( `${ errorURL || callbackURL }/error?error=invalid_provider&error_description=provider not found`, ); } let config = provider.oidcConfig; if (!config) { throw ctx.redirect( `${ errorURL || callbackURL }/error?error=invalid_provider&error_description=provider not found`, ); } const discovery = await betterFetch<{ token_endpoint: string; userinfo_endpoint: string; token_endpoint_auth_method: | "client_secret_basic" | "client_secret_post"; }>(config.discoveryEndpoint); if (discovery.data) { config = { tokenEndpoint: discovery.data.token_endpoint, tokenEndpointAuthentication: discovery.data.token_endpoint_auth_method, userInfoEndpoint: discovery.data.userinfo_endpoint, scopes: ["openid", "email", "profile", "offline_access"], ...config, }; } if (!config.tokenEndpoint) { throw ctx.redirect( `${ errorURL || callbackURL }/error?error=invalid_provider&error_description=token_endpoint_not_found`, ); } const tokenResponse = await validateAuthorizationCode({ code, codeVerifier: config.pkce ? stateData.codeVerifier : undefined, redirectURI: `${ctx.context.baseURL}/sso/callback/${provider.providerId}`, options: { clientId: config.clientId, clientSecret: config.clientSecret, }, tokenEndpoint: config.tokenEndpoint, authentication: config.tokenEndpointAuthentication === "client_secret_post" ? "post" : "basic", }).catch((e) => { if (e instanceof BetterFetchError) { throw ctx.redirect( `${ errorURL || callbackURL }?error=invalid_provider&error_description=${e.message}`, ); } return null; }); if (!tokenResponse) { throw ctx.redirect( `${ errorURL || callbackURL }/error?error=invalid_provider&error_description=token_response_not_found`, ); } let userInfo: { id?: string; email?: string; name?: string; image?: string; emailVerified?: boolean; [key: string]: any; } | null = null; if (tokenResponse.idToken) { const idToken = decodeJwt(tokenResponse.idToken); if (!config.jwksEndpoint) { throw ctx.redirect( `${ errorURL || callbackURL }/error?error=invalid_provider&error_description=jwks_endpoint_not_found`, ); } const verified = await validateToken( tokenResponse.idToken, config.jwksEndpoint, ).catch((e) => { ctx.context.logger.error(e); return null; }); if (!verified) { throw ctx.redirect( `${ errorURL || callbackURL }/error?error=invalid_provider&error_description=token_not_verified`, ); } if (verified.payload.iss !== provider.issuer) { throw ctx.redirect( `${ errorURL || callbackURL }/error?error=invalid_provider&error_description=issuer_mismatch`, ); } const mapping = config.mapping || {}; userInfo = { ...Object.fromEntries( Object.entries(mapping.extraFields || {}).map( ([key, value]) => [key, verified.payload[value]], ), ), id: idToken[mapping.id || "sub"], email: idToken[mapping.email || "email"], emailVerified: options?.trustEmailVerified ? idToken[mapping.emailVerified || "email_verified"] : false, name: idToken[mapping.name || "name"], image: idToken[mapping.image || "picture"], } as { id?: string; email?: string; name?: string; image?: string; emailVerified?: boolean; }; } if (!userInfo) { if (!config.userInfoEndpoint) { throw ctx.redirect( `${ errorURL || callbackURL }/error?error=invalid_provider&error_description=user_info_endpoint_not_found`, ); } const userInfoResponse = await betterFetch<{ email?: string; name?: string; id?: string; image?: string; emailVerified?: boolean; }>(config.userInfoEndpoint, { headers: { Authorization: `Bearer ${tokenResponse.accessToken}`, }, }); if (userInfoResponse.error) { throw ctx.redirect( `${ errorURL || callbackURL }/error?error=invalid_provider&error_description=${ userInfoResponse.error.message }`, ); } userInfo = userInfoResponse.data; } if (!userInfo.email || !userInfo.id) { throw ctx.redirect( `${ errorURL || callbackURL }/error?error=invalid_provider&error_description=missing_user_info`, ); } const linked = await handleOAuthUserInfo(ctx, { userInfo: { email: userInfo.email, name: userInfo.name || userInfo.email, id: userInfo.id, image: userInfo.image, emailVerified: options?.trustEmailVerified ? userInfo.emailVerified || false : false, }, account: { idToken: tokenResponse.idToken, accessToken: tokenResponse.accessToken, refreshToken: tokenResponse.refreshToken, accountId: userInfo.id, providerId: provider.providerId, accessTokenExpiresAt: tokenResponse.accessTokenExpiresAt, refreshTokenExpiresAt: tokenResponse.refreshTokenExpiresAt, scope: tokenResponse.scopes?.join(","), }, callbackURL, disableSignUp: options?.disableImplicitSignUp && !requestSignUp, overrideUserInfo: config.overrideUserInfo, }); if (linked.error) { throw ctx.redirect( `${errorURL || callbackURL}/error?error=${linked.error}`, ); } const { session, user } = linked.data!; if (options?.provisionUser) { await options.provisionUser({ user, userInfo, token: tokenResponse, provider, }); } if ( provider.organizationId && !options?.organizationProvisioning?.disabled ) { const isOrgPluginEnabled = ctx.context.options.plugins?.find( (plugin) => plugin.id === "organization", ); if (isOrgPluginEnabled) { const isAlreadyMember = await ctx.context.adapter.findOne({ model: "member", where: [ { field: "organizationId", value: provider.organizationId }, { field: "userId", value: user.id }, ], }); if (!isAlreadyMember) { const role = options?.organizationProvisioning?.getRole ? await options.organizationProvisioning.getRole({ user, userInfo, token: tokenResponse, provider, }) : options?.organizationProvisioning?.defaultRole || "member"; await ctx.context.adapter.create({ model: "member", data: { organizationId: provider.organizationId, userId: user.id, role, createdAt: new Date(), updatedAt: new Date(), }, }); } } } await setSessionCookie(ctx, { session, user, }); let toRedirectTo: string; try { const url = linked.isRegister ? newUserURL || callbackURL : callbackURL; toRedirectTo = url.toString(); } catch { toRedirectTo = linked.isRegister ? newUserURL || callbackURL : callbackURL; } throw ctx.redirect(toRedirectTo); }, ), callbackSSOSAML: createAuthEndpoint( "/sso/saml2/callback/:providerId", { method: "POST", body: z.object({ SAMLResponse: z.string(), RelayState: z.string().optional(), }), metadata: { isAction: false, openapi: { summary: "Callback URL for SAML provider", description: "This endpoint is used as the callback URL for SAML providers.", responses: { "302": { description: "Redirects to the callback URL", }, "400": { description: "Invalid SAML response", }, "401": { description: "Unauthorized - SAML authentication failed", }, }, }, }, }, async (ctx) => { const { SAMLResponse, RelayState } = ctx.body; const { providerId } = ctx.params; let provider: SSOProvider | null = null; if (options?.defaultSSO?.length) { const matchingDefault = options.defaultSSO.find( (defaultProvider) => defaultProvider.providerId === providerId, ); if (matchingDefault) { provider = { ...matchingDefault, userId: "default", issuer: matchingDefault.samlConfig?.issuer || "", }; } } if (!provider) { provider = await ctx.context.adapter .findOne<SSOProvider>({ model: "ssoProvider", where: [{ field: "providerId", value: providerId }], }) .then((res) => { if (!res) return null; return { ...res, samlConfig: res.samlConfig ? safeJsonParse<SAMLConfig>( res.samlConfig as unknown as string, ) || undefined : undefined, }; }); } if (!provider) { throw new APIError("NOT_FOUND", { message: "No provider found for the given providerId", }); } const parsedSamlConfig = safeJsonParse<SAMLConfig>( provider.samlConfig as unknown as string, ); if (!parsedSamlConfig) { throw new APIError("BAD_REQUEST", { message: "Invalid SAML configuration", }); } const idpData = parsedSamlConfig.idpMetadata; let idp: IdentityProvider | null = null; // Construct IDP with fallback to manual configuration if (!idpData?.metadata) { idp = saml.IdentityProvider({ entityID: idpData?.entityID || parsedSamlConfig.issuer, singleSignOnService: [ { Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect", Location: parsedSamlConfig.entryPoint, }, ], signingCert: idpData?.cert || parsedSamlConfig.cert, wantAuthnRequestsSigned: parsedSamlConfig.wantAssertionsSigned || false, isAssertionEncrypted: idpData?.isAssertionEncrypted || false, encPrivateKey: idpData?.encPrivateKey, encPrivateKeyPass: idpData?.encPrivateKeyPass, }); } else { idp = saml.IdentityProvider({ metadata: idpData.metadata, privateKey: idpData.privateKey, privateKeyPass: idpData.privateKeyPass, isAssertionEncrypted: idpData.isAssertionEncrypted, encPrivateKey: idpData.encPrivateKey, encPrivateKeyPass: idpData.encPrivateKeyPass, }); } // Construct SP with fallback to manual configuration const spData = parsedSamlConfig.spMetadata; const sp = saml.ServiceProvider({ metadata: spData?.metadata, entityID: spData?.entityID || parsedSamlConfig.issuer, assertionConsumerService: spData?.metadata ? undefined : [ { Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST", Location: parsedSamlConfig.callbackUrl, }, ], privateKey: spData?.privateKey || parsedSamlConfig.privateKey, privateKeyPass: spData?.privateKeyPass, isAssertionEncrypted: spData?.isAssertionEncrypted || false, encPrivateKey: spData?.encPrivateKey, encPrivateKeyPass: spData?.encPrivateKeyPass, wantMessageSigned: parsedSamlConfig.wantAssertionsSigned || false, nameIDFormat: parsedSamlConfig.identifierFormat ? [parsedSamlConfig.identifierFormat] : undefined, }); let parsedResponse: FlowResult; try { const decodedResponse = Buffer.from( SAMLResponse, "base64", ).toString("utf-8"); try { parsedResponse = await sp.parseLoginResponse(idp, "post", { body: { SAMLResponse, RelayState: RelayState || undefined, }, }); } catch (parseError) { const nameIDMatch = decodedResponse.match( /<saml2:NameID[^>]*>([^<]+)<\/saml2:NameID>/, ); if (!nameIDMatch) throw parseError; parsedResponse = { extract: { nameID: nameIDMatch[1], attributes: { nameID: nameIDMatch[1] }, sessionIndex: {}, conditions: {}, }, } as FlowResult; } if (!parsedResponse?.extract) { throw new Error("Invalid SAML response structure"); } } catch (error) { ctx.context.logger.error("SAML response validation failed", { error, decodedResponse: Buffer.from(SAMLResponse, "base64").toString( "utf-8", ), }); throw new APIError("BAD_REQUEST", { message: "Invalid SAML response", details: error instanceof Error ? error.message : String(error), }); } const { extract } = parsedResponse!; const attributes = extract.attributes || {}; const mapping = parsedSamlConfig.mapping ?? {}; const userInfo = { ...Object.fromEntries( Object.entries(mapping.extraFields || {}).map(([key, value]) => [ key, attributes[value as string], ]), ), id: attributes[mapping.id || "nameID"] || extract.nameID, email: attributes[mapping.email || "email"] || extract.nameID, name: [ attributes[mapping.firstName || "givenName"], attributes[mapping.lastName || "surname"], ] .filter(Boolean) .join(" ") || attributes[mapping.name || "displayName"] || extract.nameID, emailVerified: options?.trustEmailVerified && mapping.emailVerified ? ((attributes[mapping.emailVerified] || false) as boolean) : false, }; if (!userInfo.id || !userInfo.email) { ctx.context.logger.error( "Missing essential user info from SAML response", { attributes: Object.keys(attributes), mapping, extractedId: userInfo.id, extractedEmail: userInfo.email, }, ); throw new APIError("BAD_REQUEST", { message: "Unable to extract user ID or email from SAML response", }); } // Find or create user let user: User; const existingUser = await ctx.context.adapter.findOne<User>({ model: "user", where: [ { field: "email", value: userInfo.email, }, ], }); if (existingUser) { user = existingUser; } else { user = await ctx.context.adapter.create({ model: "user", data: { email: userInfo.email, name: userInfo.name, emailVerified: userInfo.emailVerified, createdAt: new Date(), updatedAt: new Date(), }, }); } // Create or update account link const account = await ctx.context.adapter.findOne<Account>({ model: "account", where: [ { field: "userId", value: user.id }, { field: "providerId", value: provider.providerId }, { field: "accountId", value: userInfo.id }, ], }); if (!account) { await ctx.context.adapter.create<Account>({ model: "account", data: { userId: user.id, providerId: provider.providerId, accountId: userInfo.id, createdAt: new Date(), updatedAt: new Date(), accessToken: "", refreshToken: "", }, }); } // Run provision hooks if (options?.provisionUser) { await options.provisionUser({ user: user as User & Record<string, any>, userInfo, provider, }); } // Handle organization provisioning if ( provider.organizationId && !options?.organizationProvisioning?.disabled ) { const isOrgPluginEnabled = ctx.context.options.plugins?.find( (plugin) => plugin.id === "organization", ); if (isOrgPluginEnabled) { const isAlreadyMember = await ctx.context.adapter.findOne({ model: "member", where: [ { field: "organizationId", value: provider.organizationId }, { field: "userId", value: user.id }, ], }); if (!isAlreadyMember) { const role = options?.organizationProvisioning?.getRole ? await options.organizationProvisioning.getRole({ user, userInfo, provider, }) : options?.organizationProvisioning?.defaultRole || "member"; await ctx.context.adapter.create({ model: "member", data: { organizationId: provider.organizationId, userId: user.id, role, createdAt: new Date(), updatedAt: new Date(), }, }); } } } // Create session and set cookie let session: Session = await ctx.context.internalAdapter.createSession(user.id, ctx); await setSessionCookie(ctx, { session, user }); // Redirect to callback URL const callbackUrl = RelayState || parsedSamlConfig.callbackUrl || ctx.context.baseURL; throw ctx.redirect(callbackUrl); }, ), acsEndpoint: createAuthEndpoint( "/sso/saml2/sp/acs/:providerId", { method: "POST", params: z.object({ providerId: z.string().optional(), }), body: z.object({ SAMLResponse: z.string(), RelayState: z.string().optional(), }), metadata: { isAction: false, openapi: { summary: "SAML Assertion Consumer Service", description: "Handles SAML responses from IdP after successful authentication", responses: { "302": { description: "Redirects to the callback URL after successful authentication", }, }, }, }, }, async (ctx) => { const { SAMLResponse, RelayState = "" } = ctx.body; const { providerId } = ctx.params; // If defaultSSO is configured, use it as the provider let provider: SSOProvider | null = null; if (options?.defaultSSO?.length) { // For ACS endpoint, we can use the first default provider or try to match by providerId const matchingDefault = providerId ? options.defaultSSO.find( (defaultProvider) => defaultProvider.providerId === providerId, ) : options.defaultSSO[0]; // Use first default provider if no specific providerId if (matchingDefault) { provider = { issuer: matchingDefault.samlConfig?.issuer || "", providerId: matchingDefault.providerId, userId: "default", samlConfig: matchingDefault.samlConfig, }; } } else { provider = await ctx.context.adapter .findOne<SSOProvider>({ model: "ssoProvider", where: [ { field: "providerId", value: providerId ?? "sso", }, ], }) .then((res) => { if (!res) return null; return { ...res, samlConfig: res.samlConfig ? safeJsonParse<SAMLConfig>( res.samlConfig as unknown as string, ) || undefined : undefined, }; }); } if (!provider?.samlConfig) { throw new APIError("NOT_FOUND", { message: "No SAML provider found", }); } const parsedSamlConfig = provider.samlConfig; // Configure SP and IdP const sp = saml.ServiceProvider({ entityID: parsedSamlConfig.spMetadata?.entityID || parsedSamlConfig.issuer, assertionConsumerService: [ { Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST", Location: parsedSamlConfig.callbackUrl || `${ctx.context.baseURL}/sso/saml2/sp/acs/${providerId}`, }, ], wantMessageSigned: parsedSamlConfig.wantAssertionsSigned || false, metadata: parsedSamlConfig.spMetadata?.metadata, privateKey: parsedSamlConfig.spMetadata?.privateKey || parsedSamlConfig.privateKey, privateKeyPass: parsedSamlConfig.spMetadata?.privateKeyPass, nameIDFormat: parsedSamlConfig.identifierFormat ? [parsedSamlConfig.identifierFormat] : undefined, }); // Update where we construct the IdP const idpData = parsedSamlConfig.idpMetadata; const idp = !idpData?.metadata ? saml.IdentityProvider({ entityID: idpData?.entityID || parsedSamlConfig.issuer, singleSignOnService: idpData?.singleSignOnService || [ { Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect", Location: parsedSamlConfig.entryPoint, }, ], signingCert: idpData?.cert || parsedSamlConfig.cert, }) : saml.IdentityProvider({ metadata: idpData.metadata, }); // Parse and validate SAML response let parsedResponse: FlowResult; try { let decodedResponse = Buffer.from(SAMLResponse, "base64").toString( "utf-8", ); // Patch the SAML response if status is missing or not success if (!decodedResponse.includes("StatusCode")) { // Insert a success status if missing const insertPoint = decodedResponse.indexOf("</saml2:Issuer>"); if (insertPoint !== -1) { decodedResponse = decodedResponse.slice(0, insertPoint + 14) + '<saml2:Status><saml2:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/></saml2:Status>' + decodedResponse.slice(insertPoint + 14); } } else if (!decodedResponse.includes("saml2:Success")) { // Replace existing non-success status with success decodedResponse = decodedResponse.replace( /<saml2:StatusCode Value="[^"]+"/, '<saml2:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"', ); } try { parsedResponse = await sp.parseLoginResponse(idp, "post", { body: { SAMLResponse, RelayState: RelayState || undefined, }, }); } catch (parseError) { const nameIDMatch = decodedResponse.match( /<saml2:NameID[^>]*>([^<]+)<\/saml2:NameID>/, ); // due to different spec. we have to make sure to handle that. if (!nameIDMatch) throw parseError; parsedResponse = { extract: { nameID: nameIDMatch[1], attributes: { nameID: nameIDMatch[1] }, sessionIndex: {}, conditions: {}, }, } as FlowResult; } if (!parsedResponse?.extract) { throw new Error("Invalid SAML response structure"); } } catch (error) { ctx.context.logger.error("SAML response validation failed", { error, decodedResponse: Buffer.from(SAMLResponse, "base64").toString( "utf-8", ), }); throw new APIError("BAD_REQUEST", { message: "Invalid SAML response", details: error instanceof Error ? error.message : String(error), }); } const { extract } = parsedResponse!; const attributes = extract.attributes || {}; const mapping = parsedSamlConfig.mapping ?? {}; const userInfo = { ...Object.fromEntries( Object.entries(mapping.extraFields || {}).map(([key, value]) => [ key, attributes[value as string], ]), ), id: attributes[mapping.id || "nameID"] || extract.nameID, email: attributes[mapping.email || "email"] || extract.nameID, name: [ attributes[mapping.firstName || "givenName"], attributes[mapping.lastName || "surname"], ] .filter(Boolean) .join(" ") || attributes[mapping.name || "displayName"] || extract.nameID, emailVerified: options?.trustEmailVerified && mapping.emailVerified ? ((attributes[mapping.emailVerified] || false) as boolean) : false, }; if (!userInfo.id || !userInfo.email) { ctx.context.logger.error( "Missing essential user info from SAML response", { attributes: Object.keys(attributes), mapping, extractedId: userInfo.id, extractedEmail: userInfo.email, }, ); throw new APIError("BAD_REQUEST", { message: "Unable to extract user ID or email from SAML response", }); } // Find or create user let user: User; const existingUser = await ctx.context.adapter.findOne<User>({ model: "user", where: [ { field: "email", value: userInfo.email, }, ], }); if (existingUser) { const account = await ctx.context.adapter.findOne<Account>({ model: "account", where: [ { field: "userId", value: existingUser.id }, { field: "providerId", value: provider.providerId }, { field: "accountId", value: userInfo.id }, ], }); if (!account) { const isTrustedProvider = ctx.context.options.account?.accountLinking?.trustedProviders?.includes( provider.providerId, ); if (!isTrustedProvider) { throw ctx.redirect( `${parsedSamlConfig.callbackUrl}?error=account_not_found`, ); } await ctx.context.adapter.create<Account>({ model: "account", data: { userId: existingUser.id, providerId: provider.providerId, accountId: userInfo.id, createdAt: new Date(), updatedAt: new Date(), accessToken: "", refreshToken: "", }, }); } user = existingUser; } else { user = await ctx.context.adapter.create({ model: "user", data: { email: userInfo.email, name: userInfo.name, emailVerified: options?.trustEmailVerified ? userInfo.emailVerified || false : false, createdAt: new Date(), updatedAt: new Date(), }, }); await ctx.context.adapter.create<Account>({ model: "account", data: { userId: user.id, providerId: provider.providerId, accountId: userInfo.id, accessToken: "", refreshToken: "", accessTokenExpiresAt: new Date(), refreshTokenExpiresAt: new Date(), scope: "", createdAt: new Date(), updatedAt: new Date(), }, }); } if (options?.provisionUser) { await options.provisionUser({ user: user as User & Record<string, any>, userInfo, provider, }); } if ( provider.organizationId && !options?.organizationProvisioning?.disabled ) { const isOrgPluginEnabled = ctx.context.options.plugins?.find( (plugin) => plugin.id === "organization", ); if (isOrgPluginEnabled) { const isAlreadyMember = await ctx.context.adapter.findOne({ model: "member", where: [ { field: "organizationId", value: provider.organizationId }, { field: "userId", value: user.id }, ], }); if (!isAlreadyMember) { const role = options?.organizationProvisioning?.getRole ? await options.organizationProvisioning.getRole({ user, userInfo, provider, }) : options?.organizationProvisioning?.defaultRole || "member"; await ctx.context.adapter.create({ model: "member", data: { organizationId: provider.organizationId, userId: user.id, role, createdAt: new Date(), updatedAt: new Date(), }, }); } } } let session: Session = await ctx.context.internalAdapter.createSession(user.id, ctx); await setSessionCookie(ctx, { session, user }); const callbackUrl = RelayState || parsedSamlConfig.callbackUrl || ctx.context.baseURL; throw ctx.redirect(callbackUrl); }, ), }, schema: { ssoProvider: { fields: { issuer: { type: "string", required: true, }, oidcConfig: { type: "string", required: false, }, samlConfig: { type: "string", required: false, }, userId: { type: "string", references: { model: "user", field: "id", }, }, providerId: { type: "string", required: true, unique: true, }, organizationId: { type: "string", required: false, }, domain: { type: "string", required: true, }, }, }, }, } satisfies BetterAuthPlugin; }; ``` -------------------------------------------------------------------------------- /docs/content/docs/plugins/organization.mdx: -------------------------------------------------------------------------------- ```markdown --- title: Organization description: The organization plugin allows you to manage your organization's members and teams. --- Organizations simplifies user access and permissions management. Assign roles and permissions to streamline project management, team coordination, and partnerships. ## Installation <Steps> <Step> ### Add the plugin to your **auth** config ```ts title="auth.ts" import { betterAuth } from "better-auth" import { organization } from "better-auth/plugins" export const auth = betterAuth({ plugins: [ // [!code highlight] organization() // [!code highlight] ] // [!code highlight] }) ``` </Step> <Step> ### Migrate the database Run the migration or generate the schema to add the necessary fields and tables to the database. <Tabs items={["migrate", "generate"]}> <Tab value="migrate"> ```bash npx @better-auth/cli migrate ``` </Tab> <Tab value="generate"> ```bash npx @better-auth/cli generate ``` </Tab> </Tabs> See the [Schema](#schema) section to add the fields manually. </Step> <Step> ### Add the client plugin ```ts title="auth-client.ts" import { createAuthClient } from "better-auth/client" import { organizationClient } from "better-auth/client/plugins" export const authClient = createAuthClient({ plugins: [ // [!code highlight] organizationClient() // [!code highlight] ] // [!code highlight] }) ``` </Step> </Steps> ## Usage Once you've installed the plugin, you can start using the organization plugin to manage your organization's members and teams. The client plugin will provide you with methods under the `organization` namespace, and the server `api` will provide you with the necessary endpoints to manage your organization and give you an easier way to call the functions on your own backend. ## Organization ### Create an organization <APIMethod path="/organization/create" method="POST" requireSession> ```ts const metadata = { someKey: "someValue" }; type createOrganization = { /** * The organization name. */ name: string = "My Organization" /** * The organization slug. */ slug: string = "my-org" /** * The organization logo. */ logo?: string = "https://example.com/logo.png" /** * The metadata of the organization. */ metadata?: Record<string, any> /** * The user ID of the organization creator. If not provided, the current user will be used. Should only be used by admins or when called by the server. * @serverOnly */ userId?: string = "some_user_id" /** * Whether to keep the current active organization active after creating a new one. */ keepCurrentActiveOrganization?: boolean = false } ``` </APIMethod> #### Restrict who can create an organization By default, any user can create an organization. To restrict this, set the `allowUserToCreateOrganization` option to a function that returns a boolean, or directly to `true` or `false`. ```ts title="auth.ts" import { betterAuth } from "better-auth"; import { organization } from "better-auth/plugins"; const auth = betterAuth({ //... plugins: [ organization({ allowUserToCreateOrganization: async (user) => { // [!code highlight] const subscription = await getSubscription(user.id); // [!code highlight] return subscription.plan === "pro"; // [!code highlight] }, // [!code highlight] }), ], }); ``` #### Check if organization slug is taken To check if an organization slug is taken or not you can use the `checkSlug` function provided by the client. The function takes an object with the following properties: <APIMethod path="/organization/check-slug" method="POST"> ```ts type checkOrganizationSlug = { /** * The organization slug to check. */ slug: string = "my-org" } ``` </APIMethod> ### Organization Hooks You can customize organization operations using hooks that run before and after various organization-related activities. Better Auth provides two ways to configure hooks: 1. **Legacy organizationCreation hooks** (deprecated, use `organizationHooks` instead) 2. **Modern organizationHooks** (recommended) - provides comprehensive control over all organization-related activities #### Organization Creation and Management Hooks Control organization lifecycle operations: ```ts title="auth.ts" import { betterAuth } from "better-auth"; import { organization } from "better-auth/plugins"; export const auth = betterAuth({ plugins: [ organization({ organizationHooks: { // Organization creation hooks beforeCreateOrganization: async ({ organization, user }) => { // Run custom logic before organization is created // Optionally modify the organization data return { data: { ...organization, metadata: { customField: "value", }, }, }; }, afterCreateOrganization: async ({ organization, member, user }) => { // Run custom logic after organization is created // e.g., create default resources, send notifications await setupDefaultResources(organization.id); }, // Organization update hooks beforeUpdateOrganization: async ({ organization, user, member }) => { // Validate updates, apply business rules return { data: { ...organization, name: organization.name?.toLowerCase(), }, }; }, afterUpdateOrganization: async ({ organization, user, member }) => { // Sync changes to external systems await syncOrganizationToExternalSystems(organization); }, }, }), ], }); ``` <Callout type="info"> The legacy `organizationCreation` hooks are still supported but deprecated. Use `organizationHooks.beforeCreateOrganization` and `organizationHooks.afterCreateOrganization` instead for new projects. </Callout> #### Member Hooks Control member operations within organizations: ```ts title="auth.ts" import { betterAuth } from "better-auth"; import { organization } from "better-auth/plugins"; export const auth = betterAuth({ plugins: [ organization({ organizationHooks: { // Before a member is added to an organization beforeAddMember: async ({ member, user, organization }) => { // Custom validation or modification console.log(`Adding ${user.email} to ${organization.name}`); // Optionally modify member data return { data: { ...member, role: "custom-role", // Override the role }, }; }, // After a member is added afterAddMember: async ({ member, user, organization }) => { // Send welcome email, create default resources, etc. await sendWelcomeEmail(user.email, organization.name); }, // Before a member is removed beforeRemoveMember: async ({ member, user, organization }) => { // Cleanup user's resources, send notification, etc. await cleanupUserResources(user.id, organization.id); }, // After a member is removed afterRemoveMember: async ({ member, user, organization }) => { await logMemberRemoval(user.id, organization.id); }, // Before updating a member's role beforeUpdateMemberRole: async ({ member, newRole, user, organization, }) => { // Validate role change permissions if (newRole === "owner" && !hasOwnerUpgradePermission(user)) { throw new Error("Cannot upgrade to owner role"); } // Optionally modify the role return { data: { role: newRole, }, }; }, // After updating a member's role afterUpdateMemberRole: async ({ member, previousRole, user, organization, }) => { await logRoleChange(user.id, previousRole, member.role); }, }, }), ], }); ``` #### Invitation Hooks Control invitation lifecycle: ```ts title="auth.ts" export const auth = betterAuth({ plugins: [ organization({ organizationHooks: { // Before creating an invitation beforeCreateInvitation: async ({ invitation, inviter, organization, }) => { // Custom validation or expiration logic const customExpiration = new Date( Date.now() + 1000 * 60 * 60 * 24 * 7 ); // 7 days return { data: { ...invitation, expiresAt: customExpiration, }, }; }, // After creating an invitation afterCreateInvitation: async ({ invitation, inviter, organization, }) => { // Send custom invitation email, track metrics, etc. await sendCustomInvitationEmail(invitation, organization); }, // Before accepting an invitation beforeAcceptInvitation: async ({ invitation, user, organization }) => { // Additional validation before acceptance await validateUserEligibility(user, organization); }, // After accepting an invitation afterAcceptInvitation: async ({ invitation, member, user, organization, }) => { // Setup user account, assign default resources await setupNewMemberResources(user, organization); }, // Before/after rejecting invitations beforeRejectInvitation: async ({ invitation, user, organization }) => { // Log rejection reason, send notification to inviter }, afterRejectInvitation: async ({ invitation, user, organization }) => { await notifyInviterOfRejection(invitation.inviterId, user.email); }, // Before/after cancelling invitations beforeCancelInvitation: async ({ invitation, cancelledBy, organization, }) => { // Verify cancellation permissions }, afterCancelInvitation: async ({ invitation, cancelledBy, organization, }) => { await logInvitationCancellation(invitation.id, cancelledBy.id); }, }, }), ], }); ``` #### Team Hooks Control team operations (when teams are enabled): ```ts title="auth.ts" export const auth = betterAuth({ plugins: [ organization({ teams: { enabled: true }, organizationHooks: { // Before creating a team beforeCreateTeam: async ({ team, user, organization }) => { // Validate team name, apply naming conventions return { data: { ...team, name: team.name.toLowerCase().replace(/\s+/g, "-"), }, }; }, // After creating a team afterCreateTeam: async ({ team, user, organization }) => { // Create default team resources, channels, etc. await createDefaultTeamResources(team.id); }, // Before updating a team beforeUpdateTeam: async ({ team, updates, user, organization }) => { // Validate updates, apply business rules return { data: { ...updates, name: updates.name?.toLowerCase(), }, }; }, // After updating a team afterUpdateTeam: async ({ team, user, organization }) => { await syncTeamChangesToExternalSystems(team); }, // Before deleting a team beforeDeleteTeam: async ({ team, user, organization }) => { // Backup team data, notify members await backupTeamData(team.id); }, // After deleting a team afterDeleteTeam: async ({ team, user, organization }) => { await cleanupTeamResources(team.id); }, // Team member operations beforeAddTeamMember: async ({ teamMember, team, user, organization, }) => { // Validate team membership limits, permissions const memberCount = await getTeamMemberCount(team.id); if (memberCount >= 10) { throw new Error("Team is full"); } }, afterAddTeamMember: async ({ teamMember, team, user, organization, }) => { await grantTeamAccess(user.id, team.id); }, beforeRemoveTeamMember: async ({ teamMember, team, user, organization, }) => { // Backup user's team-specific data await backupTeamMemberData(user.id, team.id); }, afterRemoveTeamMember: async ({ teamMember, team, user, organization, }) => { await revokeTeamAccess(user.id, team.id); }, }, }), ], }); ``` #### Hook Error Handling All hooks support error handling. Throwing an error in a `before` hook will prevent the operation from proceeding: ```ts title="auth.ts" import { APIError } from "better-auth/api"; export const auth = betterAuth({ plugins: [ organization({ organizationHooks: { beforeAddMember: async ({ member, user, organization }) => { // Check if user has pending violations const violations = await checkUserViolations(user.id); if (violations.length > 0) { throw new APIError("BAD_REQUEST", { message: "User has pending violations and cannot join organizations", }); } }, beforeCreateTeam: async ({ team, user, organization }) => { // Validate team name uniqueness const existingTeam = await findTeamByName(team.name, organization.id); if (existingTeam) { throw new APIError("BAD_REQUEST", { message: "Team name already exists in this organization", }); } }, }, }), ], }); ``` ### List User's Organizations To list the organizations that a user is a member of, you can use `useListOrganizations` hook. It implements a reactive way to get the organizations that the user is a member of. <Tabs items={["React", "Vue", "Svelte"]} default="React"> <Tab value="React"> ```tsx title="client.tsx" import { authClient } from "@/lib/auth-client" function App(){ const { data: organizations } = authClient.useListOrganizations() return ( <div> {organizations.map((org) => ( <p>{org.name}</p> ))} </div>) } ``` </Tab> <Tab value="Svelte"> ```svelte title="page.svelte" <script lang="ts"> import { authClient } from "$lib/auth-client"; const organizations = authClient.useListOrganizations(); </script> <h1>Organizations</h1> {#if $organizations.isPending} <p>Loading...</p> {:else if !$organizations.data?.length} <p>No organizations found.</p> {:else} <ul> {#each $organizations.data as organization} <li>{organization.name}</li> {/each} </ul> {/if} ``` </Tab> <Tab value="Vue"> ```vue title="organization.vue" <script lang="ts">; export default { setup() { const organizations = authClient.useListOrganizations() return { organizations }; } }; </script> <template> <div> <h1>Organizations</h1> <div v-if="organizations.isPending">Loading...</div> <div v-else-if="organizations.data === null">No organizations found.</div> <ul v-else> <li v-for="organization in organizations.data" :key="organization.id"> {{ organization.name }} </li> </ul> </div> </template> ``` </Tab> </Tabs> Or alternatively, you can call `organization.list` if you don't want to use a hook. <APIMethod path="/organization/list" method="GET" requireSession> ```ts type listOrganizations = { } ``` </APIMethod> ### Active Organization Active organization is the workspace the user is currently working on. By default when the user is signed in the active organization is set to `null`. You can set the active organization to the user session. <Callout type="info"> It's not always you want to persist the active organization in the session. You can manage the active organization in the client side only. For example, multiple tabs can have different active organizations. </Callout> #### Set Active Organization You can set the active organization by calling the `organization.setActive` function. It'll set the active organization for the user session. <Callout> In some applications, you may want the ability to unset an active organization. In this case, you can call this endpoint with `organizationId` set to `null`. </Callout> <APIMethod path="/organization/set-active" method="POST"> ```ts type setActiveOrganization = { /** * The organization ID to set as active. It can be null to unset the active organization. */ organizationId?: string | null = "org-id" /** * The organization slug to set as active. It can be null to unset the active organization if organizationId is not provided. */ organizationSlug?: string = "org-slug" } ``` </APIMethod> To set active organization when a session is created you can use [database hooks](/docs/concepts/database#database-hooks). ```ts title="auth.ts" export const auth = betterAuth({ databaseHooks: { session: { create: { before: async (session) => { const organization = await getActiveOrganization(session.userId); return { data: { ...session, activeOrganizationId: organization.id, }, }; }, }, }, }, }); ``` #### Use Active Organization To retrieve the active organization for the user, you can call the `useActiveOrganization` hook. It returns the active organization for the user. Whenever the active organization changes, the hook will re-evaluate and return the new active organization. <Tabs items={['React', 'Vue', 'Svelte']}> <Tab value="React"> ```tsx title="client.tsx" import { authClient } from "@/lib/auth-client" function App(){ const { data: activeOrganization } = authClient.useActiveOrganization() return ( <div> {activeOrganization ? <p>{activeOrganization.name}</p> : null} </div> ) } ``` </Tab> <Tab value="Svelte"> ```tsx title="client.tsx" <script lang="ts"> import { authClient } from "$lib/auth-client"; const activeOrganization = authClient.useActiveOrganization(); </script> <h2>Active Organization</h2> {#if $activeOrganization.isPending} <p>Loading...</p> {:else if $activeOrganization.data === null} <p>No active organization found.</p> {:else} <p>{$activeOrganization.data.name}</p> {/if} ``` </Tab> <Tab value="Vue"> ```vue title="organization.vue" <script lang="ts">; export default { setup() { const activeOrganization = authClient.useActiveOrganization(); return { activeOrganization }; } }; </script> <template> <div> <h2>Active organization</h2> <div v-if="activeOrganization.isPending">Loading...</div> <div v-else-if="activeOrganization.data === null">No active organization.</div> <div v-else> {{ activeOrganization.data.name }} </div> </div> </template> ``` </Tab> </Tabs> ### Get Full Organization To get the full details of an organization, you can use the `getFullOrganization` function. By default, if you don't pass any properties, it will use the active organization. <APIMethod path="/organization/get-full-organization" method="GET" requireSession > ```ts type getFullOrganization = { /** * The organization ID to get. By default, it will use the active organization. */ organizationId?: string = "org-id" /** * The organization slug to get. */ organizationSlug?: string = "org-slug" /** * The limit of members to get. By default, it uses the membershipLimit option which defaults to 100. */ membersLimit?: number = 100 } ``` </APIMethod> ### Update Organization To update organization info, you can use `organization.update` <APIMethod path="/organization/update" method="POST" requireSession > ```ts type updateOrganization = { /** * A partial list of data to update the organization. */ data: { /** * The name of the organization. */ name?: string = "updated-name" /** * The slug of the organization. */ slug?: string = "updated-slug" /** * The logo of the organization. */ logo?: string = "new-logo.url" /** * The metadata of the organization. */ metadata?: Record<string, any> | null = { customerId: "test" } } /** * The organization ID. to update. */ organizationId?: string = "org-id" } ``` </APIMethod> ### Delete Organization To remove user owned organization, you can use `organization.delete` <APIMethod path="/organization/delete" method="POST" requireSession > ```ts type deleteOrganization = { /* * The organization ID to delete. */ organizationId: string = "org-id" } ``` </APIMethod> If the user has the necessary permissions (by default: role is owner) in the specified organization, all members, invitations and organization information will be removed. You can configure how organization deletion is handled through `organizationDeletion` option: ```ts const auth = betterAuth({ plugins: [ organization({ disableOrganizationDeletion: true, //to disable it altogether organizationHooks: { beforeDeleteOrganization: async (data, request) => { // a callback to run before deleting org }, afterDeleteOrganization: async (data, request) => { // a callback to run after deleting org }, }, }), ], }); ``` ## Invitations To add a member to an organization, we first need to send an invitation to the user. The user will receive an email/sms with the invitation link. Once the user accepts the invitation, they will be added to the organization. ### Setup Invitation Email For member invitation to work we first need to provide `sendInvitationEmail` to the `better-auth` instance. This function is responsible for sending the invitation email to the user. You'll need to construct and send the invitation link to the user. The link should include the invitation ID, which will be used with the acceptInvitation function when the user clicks on it. ```ts title="auth.ts" import { betterAuth } from "better-auth"; import { organization } from "better-auth/plugins"; import { sendOrganizationInvitation } from "./email"; export const auth = betterAuth({ plugins: [ organization({ async sendInvitationEmail(data) { const inviteLink = `https://example.com/accept-invitation/${data.id}`; sendOrganizationInvitation({ email: data.email, invitedByUsername: data.inviter.user.name, invitedByEmail: data.inviter.user.email, teamName: data.organization.name, inviteLink, }); }, }), ], }); ``` ### Send Invitation To invite users to an organization, you can use the `invite` function provided by the client. The `invite` function takes an object with the following properties: <APIMethod path="/organization/invite-member" method="POST"> ```ts type createInvitation = { /** * The email address of the user to invite. */ email: string = "[email protected]" /** * The role(s) to assign to the user. It can be `admin`, `member`, or `guest`. */ role: string | string[] = "member" /** * The organization ID to invite the user to. Defaults to the active organization. */ organizationId?: string = "org-id" /** * Resend the invitation email, if the user is already invited. */ resend?: boolean = true /** * The team ID to invite the user to. */ teamId?: string = "team-id" } ``` </APIMethod> <Callout> - If the user is already a member of the organization, the invitation will be canceled. - If the user is already invited to the organization, unless `resend` is set to `true`, the invitation will not be sent again. - If `cancelPendingInvitationsOnReInvite` is set to `true`, the invitation will be canceled if the user is already invited to the organization and a new invitation is sent. </Callout> ### Accept Invitation When a user receives an invitation email, they can click on the invitation link to accept the invitation. The invitation link should include the invitation ID, which will be used to accept the invitation. Make sure to call the `acceptInvitation` function after the user is logged in. <APIMethod path="/organization/accept-invitation" method="POST"> ```ts type acceptInvitation = { /** * The ID of the invitation to accept. */ invitationId: string = "invitation-id" } ``` </APIMethod> #### Email Verification Requirement If the `requireEmailVerificationOnInvitation` option is enabled in your organization configuration, users must verify their email address before they can accept invitations. This adds an extra security layer to ensure that only verified users can join your organization. ```ts title="auth.ts" import { betterAuth } from "better-auth"; import { organization } from "better-auth/plugins"; export const auth = betterAuth({ plugins: [ organization({ requireEmailVerificationOnInvitation: true, // [!code highlight] async sendInvitationEmail(data) { // ... your email sending logic }, }), ], }); ``` ### Invitation Accepted Callback You can configure Better Auth to execute a callback function when an invitation is accepted. This is useful for logging events, updating analytics, sending notifications, or any other custom logic you need to run when someone joins your organization. ```ts title="auth.ts" import { betterAuth } from "better-auth"; import { organization } from "better-auth/plugins"; export const auth = betterAuth({ plugins: [ organization({ async sendInvitationEmail(data) { // ... your invitation email logic }, async onInvitationAccepted(data) { // This callback gets triggered when an invitation is accepted }, }), ], }); ``` The callback receives the following data: - `id`: The invitation ID - `role`: The role assigned to the user - `organization`: The organization the user joined - `invitation`: The invitation object - `inviter`: The member who sent the invitation (including user details) - `acceptedUser`: The user who accepted the invitation ### Cancel Invitation If a user has sent out an invitation, you can use this method to cancel it. If you're looking for how a user can reject an invitation, you can find that [here](#reject-invitation). <APIMethod path="/organization/cancel-invitation" method="POST" noResult> ```ts type cancelInvitation = { /** * The ID of the invitation to cancel. */ invitationId: string = "invitation-id" } ``` </APIMethod> ### Reject Invitation If this user has received an invitation, but wants to decline it, this method will allow you to do so by rejecting it. <APIMethod path="/organization/reject-invitation" method="POST" noResult> ```ts type rejectInvitation = { /** * The ID of the invitation to reject. */ invitationId: string = "invitation-id" } ``` </APIMethod> <Callout type="info"> Like accepting invitations, rejecting invitations also requires email verification when the `requireEmailVerificationOnInvitation` option is enabled. Users with unverified emails will receive an error when attempting to reject invitations. </Callout> ### Get Invitation To get an invitation you can use the `organization.getInvitation` function provided by the client. You need to provide the invitation id as a query parameter. <APIMethod path="/organization/get-invitation" method="GET" requireSession > ```ts type getInvitation = { /** * The ID of the invitation to get. */ id: string = "invitation-id" } ``` </APIMethod> ### List Invitations To list all invitations for a given organization you can use the `listInvitations` function provided by the client. <APIMethod path="/organization/list-invitations" method="GET"> ```ts type listInvitations = { /** * An optional ID of the organization to list invitations for. If not provided, will default to the user's active organization. */ organizationId?: string = "organization-id" } ``` </APIMethod> ### List user invitations To list all invitations for a given user you can use the `listUserInvitations` function provided by the client. ```ts title="auth-client.ts" const invitations = await authClient.organization.listUserInvitations(); ``` On the server, you can pass the user ID as a query parameter. ```ts title="api.ts" const invitations = await auth.api.listUserInvitations({ query: { email: "[email protected]", }, }); ``` <Callout type="warn"> The `email` query parameter is only available on the server to query for invitations for a specific user. </Callout> ## Members ### List Members To list all members of an organization you can use the `listMembers` function. <APIMethod path="/organization/list-members" method="GET"> ```ts type listMembers = { /** * An optional organization ID to list members for. If not provided, will default to the user's active organization. */ organizationId?: string = "organization-id" /** * The limit of members to return. */ limit?: number = 100 /** * The offset to start from. */ offset?: number = 0 /** * The field to sort by. */ sortBy?: string = "createdAt" /** * The direction to sort by. */ sortDirection?: "asc" | "desc" = "desc" /** * The field to filter by. */ filterField?: string = "createdAt" /** * The operator to filter by. */ filterOperator?: "eq" | "ne" | "gt" | "gte" | "lt" | "lte" | "in" | "nin" | "contains" = "eq" /** * The value to filter by. */ filterValue?: string = "value" } ``` </APIMethod> ### Remove Member To remove you can use `organization.removeMember` <APIMethod path="/organization/remove-member" method="POST"> ```ts type removeMember = { /** * The ID or email of the member to remove. */ memberIdOrEmail: string = "[email protected]" /** * The ID of the organization to remove the member from. If not provided, the active organization will be used. */ organizationId?: string = "org-id" } ``` </APIMethod> ### Update Member Role To update the role of a member in an organization, you can use the `organization.updateMemberRole`. If the user has the permission to update the role of the member, the role will be updated. <APIMethod path="/organization/update-member-role" method="POST" noResult> ```ts type updateMemberRole = { /** * The new role to be applied. This can be a string or array of strings representing the roles. */ role: string | string[] = ["admin", "sale"] /** * The member id to apply the role update to. */ memberId: string = "member-id" /** * An optional organization ID which the member is a part of to apply the role update. If not provided, you must provide session headers to get the active organization. */ organizationId?: string = "organization-id" } ``` </APIMethod> ### Get Active Member To get the current member of the active organization you can use the `organization.getActiveMember` function. This function will return the user's member details in their active organization. <APIMethod path="/organization/get-active-member" method="GET" requireSession resultVariable="member" > ```ts type getActiveMember = { } ``` </APIMethod> ### Get Active Member Role To get the current role member of the active organization you can use the `organization.getActiveMemberRole` function. This function will return the user's member role in their active organization. <APIMethod path="/organization/get-active-member-role" method="GET" requireSession resultVariable="{ role }" > ```ts type getActiveMemberRole = { } ``` </APIMethod> ### Add Member If you want to add a member directly to an organization without sending an invitation, you can use the `addMember` function which can only be invoked on the server. <APIMethod path="/organization/add-member" method="POST" isServerOnly > ```ts type addMember = { /** * The user ID which represents the user to be added as a member. If `null` is provided, then it's expected to provide session headers. */ userId?: string | null = "user-id" /** * The role(s) to assign to the new member. */ role: string | string[] = ["admin", "sale"] /** * An optional organization ID to pass. If not provided, will default to the user's active organization. */ organizationId?: string = "org-id" /** * An optional team ID to add the member to. */ teamId?: string = "team-id" } ``` </APIMethod> ### Leave Organization To leave organization you can use `organization.leave` function. This function will remove the current user from the organization. <APIMethod path="/organization/leave" method="POST" requireSession noResult > ```ts type leaveOrganization = { /** * The organization ID for the member to leave. */ organizationId: string = "organization-id" } ``` </APIMethod> ## Access Control The organization plugin provides a very flexible access control system. You can control the access of the user based on the role they have in the organization. You can define your own set of permissions based on the role of the user. ### Roles By default, there are three roles in the organization: `owner`: The user who created the organization by default. The owner has full control over the organization and can perform any action. `admin`: Users with the admin role have full control over the organization except for deleting the organization or changing the owner. `member`: Users with the member role have limited control over the organization. They can create projects, invite users, and manage projects they have created. <Callout> A user can have multiple roles. Multiple roles are stored as string separated by comma (","). </Callout> ### Permissions By default, there are three resources, and these have two to three actions. **organization**: `update` `delete` **member**: `create` `update` `delete` **invitation**: `create` `cancel` The owner has full control over all the resources and actions. The admin has full control over all the resources except for deleting the organization or changing the owner. The member has no control over any of those actions other than reading the data. ### Custom Permissions The plugin provides an easy way to define your own set of permissions for each role. <Steps> <Step> #### Create Access Control You first need to create access controller by calling `createAccessControl` function and passing the statement object. The statement object should have the resource name as the key and the array of actions as the value. ```ts title="permissions.ts" import { createAccessControl } from "better-auth/plugins/access"; /** * make sure to use `as const` so typescript can infer the type correctly */ const statement = { // [!code highlight] project: ["create", "share", "update", "delete"], // [!code highlight] } as const; // [!code highlight] const ac = createAccessControl(statement); // [!code highlight] ``` </Step> <Step> #### Create Roles Once you have created the access controller you can create roles with the permissions you have defined. ```ts title="permissions.ts" import { createAccessControl } from "better-auth/plugins/access"; const statement = { project: ["create", "share", "update", "delete"], } as const; const ac = createAccessControl(statement); const member = ac.newRole({ // [!code highlight] project: ["create"], // [!code highlight] }); // [!code highlight] const admin = ac.newRole({ // [!code highlight] project: ["create", "update"], // [!code highlight] }); // [!code highlight] const owner = ac.newRole({ // [!code highlight] project: ["create", "update", "delete"], // [!code highlight] }); // [!code highlight] const myCustomRole = ac.newRole({ // [!code highlight] project: ["create", "update", "delete"], // [!code highlight] organization: ["update"], // [!code highlight] }); // [!code highlight] ``` When you create custom roles for existing roles, the predefined permissions for those roles will be overridden. To add the existing permissions to the custom role, you need to import `defaultStatements` and merge it with your new statement, plus merge the roles' permissions set with the default roles. ```ts title="permissions.ts" import { createAccessControl } from "better-auth/plugins/access"; import { defaultStatements, adminAc } from 'better-auth/plugins/organization/access' const statement = { ...defaultStatements, // [!code highlight] project: ["create", "share", "update", "delete"], } as const; const ac = createAccessControl(statement); const admin = ac.newRole({ project: ["create", "update"], ...adminAc.statements, // [!code highlight] }); ``` </Step> <Step> #### Pass Roles to the Plugin Once you have created the roles you can pass them to the organization plugin both on the client and the server. ```ts title="auth.ts" import { betterAuth } from "better-auth" import { organization } from "better-auth/plugins" import { ac, owner, admin, member } from "@/auth/permissions" export const auth = betterAuth({ plugins: [ organization({ ac, roles: { owner, admin, member, myCustomRole } }), ], }); ``` You also need to pass the access controller and the roles to the client plugin. ```ts title="auth-client" import { createAuthClient } from "better-auth/client" import { organizationClient } from "better-auth/client/plugins" import { ac, owner, admin, member, myCustomRole } from "@/auth/permissions" export const authClient = createAuthClient({ plugins: [ organizationClient({ ac, roles: { owner, admin, member, myCustomRole } }) ] }) ``` </Step> </Steps> ### Access Control Usage **Has Permission**: You can use the `hasPermission` action provided by the `api` to check the permission of the user. ```ts title="api.ts" import { auth } from "@/auth"; await auth.api.hasPermission({ headers: await headers(), body: { permissions: { project: ["create"], // This must match the structure in your access control }, }, }); // You can also check multiple resource permissions at the same time await auth.api.hasPermission({ headers: await headers(), body: { permissions: { project: ["create"], // This must match the structure in your access control sale: ["create"], }, }, }); ``` If you want to check the permission of the user on the client from the server you can use the `hasPermission` function provided by the client. ```ts title="auth-client.ts" const canCreateProject = await authClient.organization.hasPermission({ permissions: { project: ["create"], }, }); // You can also check multiple resource permissions at the same time const canCreateProjectAndCreateSale = await authClient.organization.hasPermission({ permissions: { project: ["create"], sale: ["create"], }, }); ``` **Check Role Permission**: Once you have defined the roles and permissions to avoid checking the permission from the server you can use the `checkRolePermission` function provided by the client. ```ts title="auth-client.ts" const canCreateProject = authClient.organization.checkRolePermission({ permissions: { organization: ["delete"], }, role: "admin", }); // You can also check multiple resource permissions at the same time const canCreateProjectAndCreateSale = authClient.organization.checkRolePermission({ permissions: { organization: ["delete"], member: ["delete"], }, role: "admin", }); ``` <Callout type="warn"> This will not include any dynamic roles as everything is ran syncronously on the client side. Please use the [hasPermission](#access-control-usage) APIs to include checks for any dynamic roles & permissions. </Callout> --- ## Dynamic Access Control Dynamic access control allows you to create roles at runtime for organizations. This is achieved by storing the created roles and permissions associated with an organization in a database table. ### Enabling Dynamic Access Control To enable dynamic access control, pass the `dynamicAccessControl` configuration option with `enabled` set to `true` to both server and client plugins. Ensure you have pre-defined an `ac` instance on the server auth plugin. This is important as this is how we can infer the permissions that are available for use. ```ts title="auth.ts" import { betterAuth } from "better-auth"; import { organization } from "better-auth/plugins"; import { ac } from "@/auth/permissions"; export const auth = betterAuth({ plugins: [ // [!code highlight] organization({ // [!code highlight] ac, // Must be defined in order for dynamic access control to work // [!code highlight] dynamicAccessControl: { // [!code highlight] enabled: true, // [!code highlight] }, // [!code highlight] }) // [!code highlight] ] // [!code highlight] }) ``` ```ts title="auth-client.ts" import { createAuthClient } from "better-auth/client"; import { organizationClient } from "better-auth/client/plugins"; export const authClient = createAuthClient({ plugins: [ // [!code highlight] organizationClient({ // [!code highlight] dynamicAccessControl: { // [!code highlight] enabled: true, // [!code highlight] }, // [!code highlight] }) // [!code highlight] ] // [!code highlight] }) ``` <Callout> This will require you to run migrations to add the new `organizationRole` table to the database. </Callout> <Callout type="warn"> The `authClient.organization.checkRolePermission` function will not include any dynamic roles as everything is ran syncronously on the client side. Please use the [hasPermission](#access-control-usage) APIs to include checks for any dynamic roles. </Callout> ### Creating a role To create a new role for an organization at runtime, you can use the `createRole` function. Only users with roles which contain the `ac` resource with the `create` permission can create a new role. By default, only the `admin` and `owner` roles have this permission. You also cannot add permissions that your current role in that organization can't already access. <Callout> TIP: You can validate role names by using the `dynamicAccessControl.validateRoleName` option in the organization plugin config. Learn more [here](#validaterolename). </Callout> <APIMethod path="/organization/create-role" method="POST" requireSession noResult > ```ts // To use custom resources or permissions, // make sure they are defined in the `ac` instance of your organization config. const permission = { project: ["create", "update", "delete"] } type createOrgRole = { /** * A unique name of the role to create. */ role: string = "my-unique-role" /** * The permissions to assign to the role. */ permission?: Record<string, string[]> = permission, /** * The organization ID which the role will be created in. Defaults to the active organization. */ organizationId?: string = "organization-id" } ``` </APIMethod> Now you can freely call [`updateMemberRole`](#updating-a-member-role) to update the role of a member with your newly created role! ### Deleting a role To delete a role, you can use the `deleteRole` function, then provide either a `roleName` or `roleId` parameter along with the `organizationId` parameter. <APIMethod path="/organization/delete-role" method="POST" requireSession noResult > ```ts type deleteOrgRole = { /** * The name of the role to delete. Alternatively, you can pass a `roleId` parameter instead. */ roleName?: string = "my-role" /** * The id of the role to delete. Alternatively, you can pass a `roleName` parameter instead. */ roleId?: string = "role-id" /** * The organization ID which the role will be deleted in. Defaults to the active organization. */ organizationId?: string = "organization-id" } ``` </APIMethod> ### Listing roles To list roles, you can use the `listOrgRoles` function. This requires the `ac` resource with the `read` permission for the member to be able to list roles. <APIMethod path="/organization/list-roles" method="GET" requireSession resultVariable="roles" > ```ts type listOrgRoles = { /** * The organization ID which the roles are under to list. Defaults to the user's active organization. */ organizationId?: string = "organization-id" } ``` </APIMethod> ### Getting a specific role To get a specific role, you can use the `getOrgRole` function and pass either a `roleName` or `roleId` parameter. This requires the `ac` resource with the `read` permission for the member to be able to get a role. <APIMethod path="/organization/get-role" method="GET" requireSession resultVariable="role" > ```ts type getOrgRole = { /** * The name of the role to get. Alternatively, you can pass a `roleId` parameter instead. */ roleName?: string = "my-role" /** * The id of the role to get. Alternatively, you can pass a `roleName` parameter instead. */ roleId?: string = "role-id" /** * The organization ID which the role will be deleted in. Defaults to the active organization. */ organizationId?: string = "organization-id" } ``` </APIMethod> ### Updating a role To update a role, you can use the `updateOrgRole` function and pass either a `roleName` or `roleId` parameter. <APIMethod path="/organization/update-role" method="POST" requireSession resultVariable="updatedRole" > ```ts type updateOrgRole = { /** * The name of the role to update. Alternatively, you can pass a `roleId` parameter instead. */ roleName?: string = "my-role" /** * The id of the role to update. Alternatively, you can pass a `roleName` parameter instead. */ roleId?: string = "role-id" /** * The organization ID which the role will be updated in. Defaults to the active organization. */ organizationId?: string = "organization-id" /** * The data which will be updated */ data: { /** * Optionally update the permissions of the role. */ permission?: Record<string, string[]> = { project: ["create", "update", "delete"] } /** * Optionally update the name of the role. */ roleName?: string = "my-new-role" } } ``` </APIMethod> ### Configuration Options Below is a list of options that can be passed to the `dynamicAccessControl` object. #### `enabled` This option is used to enable or disable dynamic access control. By default, it is disabled. ```ts organization({ dynamicAccessControl: { enabled: true // [!code highlight] } }) ``` #### `maximumRolesPerOrganization` This option is used to limit the number of roles that can be created for an organization. By default, the maximum number of roles that can be created for an organization is infinite. ```ts organization({ dynamicAccessControl: { maximumRolesPerOrganization: 10 // [!code highlight] } }) ``` You can also pass a function that returns a number. ```ts organization({ dynamicAccessControl: { maximumRolesPerOrganization: async (organizationId) => { // [!code highlight] const organization = await getOrganization(organizationId); // [!code highlight] return organization.plan === "pro" ? 100 : 10; // [!code highlight] } // [!code highlight] } }) ``` ### Additional Fields To add additional fields to the `organizationRole` table, you can pass the `additionalFields` configuration option to the `organization` plugin. ```ts organization({ schema: { organizationRole: { additionalFields: { // Role colors! color: { type: "string", defaultValue: "#ffffff", }, //... other fields }, }, }, }) ``` Then, if you don't already use `inferOrgAdditionalFields` to infer the additional fields, you can use it to infer the additional fields. ```ts title="auth-client.ts" import { createAuthClient } from "better-auth/client" import { organizationClient, inferOrgAdditionalFields } from "better-auth/client/plugins" import type { auth } from "./auth" export const authClient = createAuthClient({ plugins: [ organizationClient({ schema: inferOrgAdditionalFields<typeof auth>() }) ] }) ``` Otherwise, you can pass the schema values directly, the same way you do on the org plugin in the server. ```ts title="auth-client.ts" import { createAuthClient } from "better-auth/client" import { organizationClient } from "better-auth/client/plugins" export const authClient = createAuthClient({ plugins: [ organizationClient({ schema: { organizationRole: { additionalFields: { color: { type: "string", defaultValue: "#ffffff", } } } } }) ] }) ``` --- ## Teams Teams allow you to group members within an organization. The teams feature provides additional organization structure and can be used to manage permissions at a more granular level. ### Enabling Teams To enable teams, pass the `teams` configuration option to both server and client plugins: ```ts title="auth.ts" import { betterAuth } from "better-auth"; import { organization } from "better-auth/plugins"; export const auth = betterAuth({ plugins: [ organization({ teams: { enabled: true, maximumTeams: 10, // Optional: limit teams per organization allowRemovingAllTeams: false, // Optional: prevent removing the last team }, }), ], }); ``` ```ts title="auth-client.ts" import { createAuthClient } from "better-auth/client"; import { organizationClient } from "better-auth/client/plugins"; export const authClient = createAuthClient({ plugins: [ organizationClient({ teams: { enabled: true, }, }), ], }); ``` ### Managing Teams #### Create Team Create a new team within an organization: <APIMethod path="/organization/create-team" method="POST"> ```ts type createTeam = { /** * The name of the team. */ name: string = "my-team" /** * The organization ID which the team will be created in. Defaults to the active organization. */ organizationId?: string = "organization-id" } ``` </APIMethod> #### List Teams Get all teams in an organization: <APIMethod path="/organization/list-teams" method="GET" requireSession > ```ts type listOrganizationTeams = { /** * The organization ID which the teams are under to list. Defaults to the user's active organization. */ organizationId?: string = "organization-id" } ``` </APIMethod> #### Update Team Update a team's details: <APIMethod path="/organization/update-team" method="POST" requireSession > ```ts type updateTeam = { /** * The ID of the team to be updated. */ teamId: string = "team-id" /** * A partial object containing options for you to update. */ data: { /** * The name of the team to be updated. */ name?: string = "My new team name" /** * The organization ID which the team falls under. */ organizationId?: string = "My new organization ID for this team" /** * The timestamp of when the team was created. */ createdAt?: Date = new Date() /** * The timestamp of when the team was last updated. */ updatedAt?: Date = new Date() } } ``` </APIMethod> #### Remove Team Delete a team from an organization: <APIMethod path="/organization/remove-team" method="POST"> ```ts type removeTeam = { /** * The team ID of the team to remove. */ teamId: string = "team-id" /** * The organization ID which the team falls under. If not provided, it will default to the user's active organization. */ organizationId?: string = "organization-id" } ``` </APIMethod> #### Set Active Team Sets the given team as the current active team. If `teamId` is `null` the current active team is unset. <APIMethod path="/organization/set-active-team" method="POST"> ```ts type setActiveTeam = { /** * The team ID of the team to set as the current active team. */ teamId?: string = "team-id" } ``` </APIMethod> #### List User Teams List all teams that the current user is a part of. <APIMethod path="/organization/list-user-teams" method="GET"> ```ts type listUserTeams = { } ``` </APIMethod> #### List Team Members List the members of the given team. <APIMethod path="/organization/list-team-members" method="POST"> ```ts type listTeamMembers = { /** * The team whose members we should return. If this is not provided the members of the current active team get returned. */ teamId?: string = "team-id" } ``` </APIMethod> #### Add Team Member Add a member to a team. <APIMethod path="/organization/add-team-member" method="POST"> ```ts type addTeamMember = { /** * The team the user should be a member of. */ teamId: string = "team-id" /** * The user ID which represents the user to be added as a member. */ userId: string = "user-id" } ``` </APIMethod> #### Remove Team Member Remove a member from a team. <APIMethod path="/organization/remove-team-member" method="POST"> ```ts type removeTeamMember = { /** * The team the user should be removed from. */ teamId: string = "team-id" /** * The user which should be removed from the team. */ userId: string = "user-id" } ``` </APIMethod> ### Team Permissions Teams follow the organization's permission system. To manage teams, users need the following permissions: - `team:create` - Create new teams - `team:update` - Update team details - `team:delete` - Remove teams By default: - Organization owners and admins can manage teams - Regular members cannot create, update, or delete teams ### Team Configuration Options The teams feature supports several configuration options: - `maximumTeams`: Limit the number of teams per organization ```ts teams: { enabled: true, maximumTeams: 10 // Fixed number // OR maximumTeams: async ({ organizationId, session }, request) => { // Dynamic limit based on organization plan const plan = await getPlan(organizationId) return plan === 'pro' ? 20 : 5 }, maximumMembersPerTeam: 10 // Fixed number // OR maximumMembersPerTeam: async ({ teamId, session, organizationId }, request) => { // Dynamic limit based on team plan const plan = await getPlan(organizationId, teamId) return plan === 'pro' ? 50 : 10 }, } ``` - `allowRemovingAllTeams`: Control whether the last team can be removed ```ts teams: { enabled: true, allowRemovingAllTeams: false // Prevent removing the last team } ``` ### Team Members When inviting members to an organization, you can specify a team: ```ts await authClient.organization.inviteMember({ email: "[email protected]", role: "member", teamId: "team-id", }); ``` The invited member will be added to the specified team upon accepting the invitation. ### Database Schema When teams are enabled, new `team` and `teamMember` tables are added to the database. Table Name: `team` <DatabaseTable fields={[ { name: "id", type: "string", description: "Unique identifier for each team", isPrimaryKey: true, }, { name: "name", type: "string", description: "The name of the team", }, { name: "organizationId", type: "string", description: "The ID of the organization", isForeignKey: true, }, { name: "createdAt", type: "Date", description: "Timestamp of when the team was created", }, { name: "updatedAt", type: "Date", isOptional: true, description: "Timestamp of when the team was created", }, ]} /> Table Name: `teamMember` <DatabaseTable fields={[ { name: "id", type: "string", description: "Unique identifier for each team member", isPrimaryKey: true, }, { name: "teamId", type: "string", description: "Unique identifier for each team", isForeignKey: true, }, { name: "userId", type: "string", description: "The ID of the user", isForeignKey: true, }, { name: "createdAt", type: "Date", description: "Timestamp of when the team member was created", }, ]} /> ## Schema The organization plugin adds the following tables to the database: ### Organization Table Name: `organization` <DatabaseTable fields={[ { name: "id", type: "string", description: "Unique identifier for each organization", isPrimaryKey: true, }, { name: "name", type: "string", description: "The name of the organization", }, { name: "slug", type: "string", description: "The slug of the organization", }, { name: "logo", type: "string", description: "The logo of the organization", isOptional: true, }, { name: "metadata", type: "string", description: "Additional metadata for the organization", isOptional: true, }, { name: "createdAt", type: "Date", description: "Timestamp of when the organization was created", }, ]} /> ### Member Table Name: `member` <DatabaseTable fields={[ { name: "id", type: "string", description: "Unique identifier for each member", isPrimaryKey: true, }, { name: "userId", type: "string", description: "The ID of the user", isForeignKey: true, }, { name: "organizationId", type: "string", description: "The ID of the organization", isForeignKey: true, }, { name: "role", type: "string", description: "The role of the user in the organization", }, { name: "createdAt", type: "Date", description: "Timestamp of when the member was added to the organization", }, ]} /> ### Invitation Table Name: `invitation` <DatabaseTable fields={[ { name: "id", type: "string", description: "Unique identifier for each invitation", isPrimaryKey: true, }, { name: "email", type: "string", description: "The email address of the user", }, { name: "inviterId", type: "string", description: "The ID of the inviter", isForeignKey: true, }, { name: "organizationId", type: "string", description: "The ID of the organization", isForeignKey: true, }, { name: "role", type: "string", description: "The role of the user in the organization", }, { name: "status", type: "string", description: "The status of the invitation", }, { name: "createdAt", type: "Date", description: "Timestamp of when the invitation was created" }, { name: "expiresAt", type: "Date", description: "Timestamp of when the invitation expires", }, ]} /> If teams are enabled, you need to add the following fields to the invitation table: <DatabaseTable fields={[ { name: "teamId", type: "string", description: "The ID of the team", isOptional: true, }, ]} /> ### Session Table Name: `session` You need to add two more fields to the session table to store the active organization ID and the active team ID. <DatabaseTable fields={[ { name: "activeOrganizationId", type: "string", description: "The ID of the active organization", isOptional: true, }, { name: "activeTeamId", type: "string", description: "The ID of the active team", isOptional: true, }, ]} /> ### Teams (optional) Table Name: `team` <DatabaseTable fields={[ { name: "id", type: "string", description: "Unique identifier for each team", isPrimaryKey: true, }, { name: "name", type: "string", description: "The name of the team", }, { name: "organizationId", type: "string", description: "The ID of the organization", isForeignKey: true, }, { name: "createdAt", type: "Date", description: "Timestamp of when the team was created", }, { name: "updatedAt", type: "Date", isOptional: true, description: "Timestamp of when the team was created", }, ]} /> Table Name: `teamMember` <DatabaseTable fields={[ { name: "id", type: "string", description: "Unique identifier for each team member", isPrimaryKey: true, }, { name: "teamId", type: "string", description: "Unique identifier for each team", isForeignKey: true, }, { name: "userId", type: "string", description: "The ID of the user", isForeignKey: true, }, { name: "createdAt", type: "Date", description: "Timestamp of when the team member was created", }, ]} /> Table Name: `invitation` <DatabaseTable fields={[ { name: "teamId", type: "string", description: "The ID of the team", isOptional: true, }, ]} /> ### Customizing the Schema To change the schema table name or fields, you can pass `schema` option to the organization plugin. ```ts title="auth.ts" const auth = betterAuth({ plugins: [ organization({ schema: { organization: { modelName: "organizations", //map the organization table to organizations fields: { name: "title", //map the name field to title }, additionalFields: { // Add a new field to the organization table myCustomField: { type: "string", input: true, required: false, }, }, }, }, }), ], }); ``` #### Additional Fields Starting with [Better Auth v1.3](https://github.com/better-auth/better-auth/releases/tag/v1.3.0), you can easily add custom fields to the `organization`, `invitation`, `member`, and `team` tables. When you add extra fields to a model, the relevant API endpoints will automatically accept and return these new properties. For instance, if you add a custom field to the `organization` table, the `createOrganization` endpoint will include this field in its request and response payloads as needed. ```ts title="auth.ts" const auth = betterAuth({ plugins: [ organization({ schema: { organization: { additionalFields: { myCustomField: { // [!code highlight] type: "string", // [!code highlight] input: true, // [!code highlight] required: false, // [!code highlight] }, // [!code highlight] }, }, }, }), ], }); ``` For inferring the additional fields, you can use the `inferOrgAdditionalFields` function. This function will infer the additional fields from the auth object type. ```ts title="auth-client.ts" import { createAuthClient } from "better-auth/client"; import { inferOrgAdditionalFields, organizationClient, } from "better-auth/client/plugins"; import type { auth } from "@/auth"; // import the auth object type only const client = createAuthClient({ plugins: [ organizationClient({ schema: inferOrgAdditionalFields<typeof auth>(), }), ], }); ``` if you can't import the auth object type, you can use the `inferOrgAdditionalFields` function without the generic. This function will infer the additional fields from the schema object. ```ts title="auth-client.ts" const client = createAuthClient({ plugins: [ organizationClient({ schema: inferOrgAdditionalFields({ organization: { // [!code highlight] additionalFields: { newField: { // [!code highlight] type: "string", // [!code highlight] }, // [!code highlight] }, }, }), }), ], }); //example usage await client.organization.create({ name: "Test", slug: "test", newField: "123", //this should be allowed //@ts-expect-error - this field is not available unavalibleField: "123", //this should be not allowed }); ``` ## Options **allowUserToCreateOrganization**: `boolean` | `((user: User) => Promise<boolean> | boolean)` - A function that determines whether a user can create an organization. By default, it's `true`. You can set it to `false` to restrict users from creating organizations. **organizationLimit**: `number` | `((user: User) => Promise<boolean> | boolean)` - The maximum number of organizations allowed for a user. By default, it's `5`. You can set it to any number you want or a function that returns a boolean. **creatorRole**: `admin | owner` - The role of the user who creates the organization. By default, it's `owner`. You can set it to `admin`. **membershipLimit**: `number` - The maximum number of members allowed in an organization. By default, it's `100`. You can set it to any number you want. **sendInvitationEmail**: `async (data) => Promise<void>` - A function that sends an invitation email to the user. **invitationExpiresIn** : `number` - How long the invitation link is valid for in seconds. By default, it's 48 hours (2 days). **cancelPendingInvitationsOnReInvite**: `boolean` - Whether to cancel pending invitations if the user is already invited to the organization. By default, it's `false`. **invitationLimit**: `number` | `((user: User) => Promise<boolean> | boolean)` - The maximum number of invitations allowed for a user. By default, it's `100`. You can set it to any number you want or a function that returns a boolean. **requireEmailVerificationOnInvitation**: `boolean` - Whether to require email verification before accepting or rejecting invitations. By default, it's `false`. When enabled, users must have verified their email address before they can accept or reject organization invitations. ```