import * as better_auth_plugins from 'better-auth/plugins'; import * as better_auth from 'better-auth'; import { JWTPayload as JWTPayload$1 } from 'better-auth'; export { APIError } from 'better-auth'; import * as zod from 'zod'; import zod__default, { z } from 'zod'; import * as better_auth_client from 'better-auth/client'; import { BetterFetchOption } from 'better-auth/client'; import * as _better_auth_api_key from '@better-auth/api-key'; import { ApiKey as ApiKey$1 } from '@better-auth/api-key'; import * as jose from 'jose'; import * as zod_v4_core from 'zod/v4/core'; import * as _better_auth_sso from '@better-auth/sso'; declare const AMRBrand: unique symbol; declare const AALBrand: unique symbol; declare const ACRBrand: unique symbol; declare const AuthMethodBrand: unique symbol; declare const AMRs: { readonly Pwd: ("sso" & zod__default.core.$brand) | ("saml" & zod__default.core.$brand) | ("otp" & zod__default.core.$brand) | ("pwd" & zod__default.core.$brand) | ("oauth" & zod__default.core.$brand); readonly Otp: ("sso" & zod__default.core.$brand) | ("saml" & zod__default.core.$brand) | ("otp" & zod__default.core.$brand) | ("pwd" & zod__default.core.$brand) | ("oauth" & zod__default.core.$brand); readonly Oauth: ("sso" & zod__default.core.$brand) | ("saml" & zod__default.core.$brand) | ("otp" & zod__default.core.$brand) | ("pwd" & zod__default.core.$brand) | ("oauth" & zod__default.core.$brand); readonly Sso: ("sso" & zod__default.core.$brand) | ("saml" & zod__default.core.$brand) | ("otp" & zod__default.core.$brand) | ("pwd" & zod__default.core.$brand) | ("oauth" & zod__default.core.$brand); readonly Saml: ("sso" & zod__default.core.$brand) | ("saml" & zod__default.core.$brand) | ("otp" & zod__default.core.$brand) | ("pwd" & zod__default.core.$brand) | ("oauth" & zod__default.core.$brand); }; declare const AALs: { readonly Aal1: ("aal1" & zod__default.core.$brand) | ("aal2" & zod__default.core.$brand) | ("aal3" & zod__default.core.$brand); readonly Aal2: ("aal1" & zod__default.core.$brand) | ("aal2" & zod__default.core.$brand) | ("aal3" & zod__default.core.$brand); readonly Aal3: ("aal1" & zod__default.core.$brand) | ("aal2" & zod__default.core.$brand) | ("aal3" & zod__default.core.$brand); }; declare const ACRs: { readonly Unspecified: "urn:tela:auth:unspecified" & zod__default.core.$brand; }; declare const AuthMethods: { readonly Password: ("sso" & zod__default.core.$brand) | ("unknown" & zod__default.core.$brand) | ("password" & zod__default.core.$brand) | ("saml" & zod__default.core.$brand) | ("oauth" & zod__default.core.$brand) | ("email_otp" & zod__default.core.$brand); readonly EmailOTP: ("sso" & zod__default.core.$brand) | ("unknown" & zod__default.core.$brand) | ("password" & zod__default.core.$brand) | ("saml" & zod__default.core.$brand) | ("oauth" & zod__default.core.$brand) | ("email_otp" & zod__default.core.$brand); readonly OAuth: ("sso" & zod__default.core.$brand) | ("unknown" & zod__default.core.$brand) | ("password" & zod__default.core.$brand) | ("saml" & zod__default.core.$brand) | ("oauth" & zod__default.core.$brand) | ("email_otp" & zod__default.core.$brand); readonly SSO: ("sso" & zod__default.core.$brand) | ("unknown" & zod__default.core.$brand) | ("password" & zod__default.core.$brand) | ("saml" & zod__default.core.$brand) | ("oauth" & zod__default.core.$brand) | ("email_otp" & zod__default.core.$brand); readonly SAML: ("sso" & zod__default.core.$brand) | ("unknown" & zod__default.core.$brand) | ("password" & zod__default.core.$brand) | ("saml" & zod__default.core.$brand) | ("oauth" & zod__default.core.$brand) | ("email_otp" & zod__default.core.$brand); readonly Unknown: ("sso" & zod__default.core.$brand) | ("unknown" & zod__default.core.$brand) | ("password" & zod__default.core.$brand) | ("saml" & zod__default.core.$brand) | ("oauth" & zod__default.core.$brand) | ("email_otp" & zod__default.core.$brand); }; /** * Reads the legacy `saml` AMR as `sso`, so sessions and application policies * created before SAML and OIDC were unified keep matching each other. */ declare function normalizeAmr(amr: AMR): AMR; declare const AMR: zod__default.core.$ZodBranded, typeof AMRBrand, "out">; type AMR = zod__default.infer; declare const AAL: zod__default.core.$ZodBranded, typeof AALBrand, "out">; type AAL = zod__default.infer; declare const ACR: zod__default.core.$ZodBranded, typeof ACRBrand, "out">; type ACR = zod__default.infer; declare const AuthMethod: zod__default.core.$ZodBranded, typeof AuthMethodBrand, "out">; type AuthMethod = zod__default.infer; declare const assuranceFields: { authMethod: { type: "string"; required: true; }; amr: { type: "json"; required: true; }; aal: { type: "string"; required: true; }; acr: { type: "string"; required: true; }; assuredAt: { type: "date"; required: true; }; }; type AssuranceFields = { authMethod: AuthMethod; amr: AMR[]; aal: AAL; acr: ACR; assuredAt: Date; }; declare const ac: { newRole(statements: better_auth_plugins.RoleInput<{ access: string[]; organization: readonly ["update", "delete"]; member: readonly ["create", "update", "delete"]; invitation: readonly ["create", "cancel"]; team: readonly ["create", "update", "delete"]; ac: readonly ["create", "read", "update", "delete"]; }, TRoleStatements>): better_auth_plugins.Role, { access: string[]; organization: readonly ["update", "delete"]; member: readonly ["create", "update", "delete"]; invitation: readonly ["create", "cancel"]; team: readonly ["create", "update", "delete"]; ac: readonly ["create", "read", "update", "delete"]; }>; statements: { access: string[]; organization: readonly ["update", "delete"]; member: readonly ["create", "update", "delete"]; invitation: readonly ["create", "cancel"]; team: readonly ["create", "update", "delete"]; ac: readonly ["create", "read", "update", "delete"]; }; }; /** * Predefined organization roles. * * @example * ```typescript * import { Roles } from '@meistrari/auth-core' * * // Invite user with specific role * await authClient.organization.inviteUserToOrganization({ * userEmail: 'user@example.com', * role: Roles.ORG_ADMIN * }) * ``` */ declare const Roles: { readonly ORG_ADMIN: "org:admin"; readonly ORG_MEMBER: "org:member"; readonly ORG_REVIEWER: "org:reviewer"; }; /** * Type representing a valid organization role. */ type Role = typeof Roles[keyof typeof Roles]; /** * Role-based access control definitions mapping each role to its permissions. * * Used internally by the organization plugin to enforce access control. */ declare const rolesAccessControl: { "org:admin": better_auth_plugins.Role, { access: string[]; organization: readonly ["update", "delete"]; member: readonly ["create", "update", "delete"]; invitation: readonly ["create", "cancel"]; team: readonly ["create", "update", "delete"]; ac: readonly ["create", "read", "update", "delete"]; }>; "org:member": better_auth_plugins.Role, { access: string[]; organization: readonly ["update", "delete"]; member: readonly ["create", "update", "delete"]; invitation: readonly ["create", "cancel"]; team: readonly ["create", "update", "delete"]; ac: readonly ["create", "read", "update", "delete"]; }>; "org:reviewer": better_auth_plugins.Role, { access: string[]; organization: readonly ["update", "delete"]; member: readonly ["create", "update", "delete"]; invitation: readonly ["create", "cancel"]; team: readonly ["create", "update", "delete"]; ac: readonly ["create", "read", "update", "delete"]; }>; }; /** * Additional database fields added to the `user` table. * * @internal */ declare const userAdditionalFields: { lastActiveAt: { type: "date"; required: false; defaultValue: null; }; displayName: { type: "string"; input: true; required: false; defaultValue: null; }; title: { type: "string"; input: true; required: false; defaultValue: null; }; pronouns: { type: "string"; input: true; required: false; defaultValue: null; }; preferredLanguage: { type: "string"; input: true; required: true; defaultValue: string; }; }; /** * Additional database fields added to the `organization` table. * * @internal */ declare const organizationAdditionalFields: { settings: { type: "json"; input: true; required: false; }; }; /** * Additional database fields added to the `member` table. * * @internal */ declare const memberAdditionalFields: { deletedAt: { type: "date"; required: false; defaultValue: null; }; lastActiveAt: { type: "date"; required: false; defaultValue: null; }; }; /** * Additional database fields added to the `invitation` table. * * @internal */ declare const invitationAdditionalFields: { applicationId: { type: "string"; input: true; required: false; }; /** Application role granted when an application invitation is accepted. */ applicationRole: { type: "string"; input: true; required: false; }; }; /** * Zod schema and type for the `user` claim within a JWT payload. */ declare const JWTPayloadUser: z.ZodObject<{ id: z.ZodString; name: z.ZodString; image: z.ZodOptional>; role: z.ZodNullable; }, z.core.$strip>; type JWTPayloadUser = z.infer; /** * Zod schema and type for the `workspace` claim within a JWT payload. */ declare const JWTPayloadWorkspace: z.ZodObject<{ id: z.ZodString; title: z.ZodString; }, z.core.$strip>; type JWTPayloadWorkspace = z.infer; type JWTPayloadAssurance = { authMethod: AuthMethod; amr: AMR[]; aal: AAL; acr: ACR; assuredAt: string; }; declare const JWTPayloadAssurance: z.ZodType; declare const DEFAULT_JWT_ASSURANCE: JWTPayloadAssurance; type JWTPayloadData = { email: string; user: JWTPayloadUser; workspace: JWTPayloadWorkspace; sessionKey: string; assurance: JWTPayloadAssurance; }; /** * Zod schema and type for the full JWT payload issued by the auth API. * * Includes `email`, `user`, `workspace`, and `sessionKey` claims * on top of the standard Better Auth JWT fields (`sub`, `iss`, `exp`, etc.). */ declare const JWTPayload: z.ZodType; type JWTPayload = JWTPayload$1 & JWTPayloadData; /** * Checks if a JWT token has expired or will expire within a specified time window. * * @param token - The JWT token string to check * @param expiresInMs - Optional time window in milliseconds. If provided, returns `true` if the token will expire within this time window * @returns `true` if the token is expired (or will expire within the specified window), `false` otherwise * * @example * ```typescript * const token = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...' * * // Check if token is already expired * if (isTokenExpired(token)) { * console.log('Token has expired') * } * * // Check if token will expire in the next 5 minutes * if (isTokenExpired(token, 5 * 60 * 1000)) { * console.log('Token will expire in the next 5 minutes') * } * ``` */ declare function isTokenExpired(token: string, expiresInMs?: number): boolean; declare const OAuthStepUpProvider: zod__default.ZodEnum<{ google: "google"; microsoft: "microsoft"; }>; type OAuthStepUpProvider = zod__default.infer; type StepUpOption = { method: typeof AMRs.Pwd; } | { method: typeof AMRs.Otp; } | { method: typeof AMRs.Oauth; providers: OAuthStepUpProvider[]; }; declare const StepUpOption: zod__default.ZodType; type SessionAssurancePolicy = { minAal: typeof AALs.Aal1 | typeof AALs.Aal2 | typeof AALs.Aal3; acceptedAmr: AMR[]; }; declare const SessionAssurancePolicy: zod__default.ZodType; declare const SENSITIVE_ACTION_ASSURANCE_POLICY: SessionAssurancePolicy; /** * Maximum age of an elevated (stepped-up) assurance, in seconds. Enforced by * `isAssuranceSufficientForPolicy` for any policy that requires AAL2 or higher, * so a one-time step-up cannot satisfy a sensitive-action policy indefinitely. * Baseline AAL1 policies impose no freshness requirement, so ordinary sessions * and their token refreshes are unaffected. */ declare const STEP_UP_MAX_AGE_SECONDS: number; declare function getAalRank(aal: JWTPayload['assurance']['aal']): number; declare function isAssuranceSufficientForPolicy(assurance: JWTPayload['assurance'] | null | undefined, policy: SessionAssurancePolicy, now?: Date): boolean; declare function canStepUpWithAmr(assurance: JWTPayload['assurance'], amr: AMR): boolean; declare function mergeStepUpAssurance(assurance: JWTPayload['assurance'], amr: AMR, now?: Date): JWTPayload['assurance']; /** * Base error class for all SDK errors. * * Extends the native `Error` with a machine-readable `code` property * that can be used for programmatic error handling. */ declare class BaseError extends Error { /** Machine-readable error code (e.g. `"INVALID_SOCIAL_PROVIDER"`). */ code: string; /** * @param code - A machine-readable error code * @param message - A human-readable error message * @param options - Standard `ErrorOptions` (e.g. `cause`) */ constructor(code: string, message: string, options?: ErrorOptions); } declare const SessionAssuranceRequiredPayload: zod__default.ZodObject<{ code: zod__default.ZodEnum<{ session_assurance_required: "session_assurance_required"; application_session_assurance_not_met: "application_session_assurance_not_met"; }>; currentAssurance: zod__default.ZodPipe, zod__default.ZodType>>; requiredAssurance: zod__default.ZodType>; validStepUps: zod__default.ZodArray>>; }, zod__default.core.$strip>; type SessionAssuranceRequiredPayload = zod__default.infer; declare function parseSessionAssuranceRequiredPayload(error: unknown): { code: "session_assurance_required" | "application_session_assurance_not_met"; currentAssurance: JWTPayloadAssurance; requiredAssurance: SessionAssurancePolicy; validStepUps: StepUpOption[]; } | null; declare class SessionAssuranceRequiredError extends BaseError { readonly payload: SessionAssuranceRequiredPayload; readonly currentAssurance: SessionAssuranceRequiredPayload['currentAssurance']; readonly requiredAssurance: SessionAssuranceRequiredPayload['requiredAssurance']; readonly validStepUps: SessionAssuranceRequiredPayload['validStepUps']; constructor(payload: SessionAssuranceRequiredPayload, options?: ErrorOptions); } declare function sessionAssurancePluginClient(): { id: "session-assurance"; getActions: ($fetch: better_auth_client.BetterFetch) => { sessionAssurance: { getSessionAssurance: () => Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: unknown; error: null; }>; stepUpWithPassword: (body: { password: string; }) => Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: unknown; error: null; }>; sendOtp: () => Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: unknown; error: null; }>; verifyOtp: (body: { otp: string; }) => Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: unknown; error: null; }>; beginOAuthStepUp: (body: { provider: OAuthStepUpProvider; returnUrl?: string; }) => Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: unknown; error: null; }>; completeOAuthStepUp: (body: { stepUpToken: string; }) => Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: unknown; error: null; }>; }; }; }; type SessionAssuranceActions = ReturnType['getActions']>['sessionAssurance']; type BeginOAuthStepUpParams = { provider: OAuthStepUpProvider; returnUrl?: string; }; declare const SessionAssuranceResponse: zod__default.ZodObject<{ assurance: zod__default.ZodType>; validStepUps: zod__default.ZodArray>>; }, zod__default.core.$strip>; type SessionAssuranceResponse = zod__default.infer; declare const OAuthBeginStepUpResponse: zod__default.ZodObject<{ stepUpToken: zod__default.ZodString; callbackURL: zod__default.ZodString; }, zod__default.core.$strip>; type OAuthBeginStepUpResponse = zod__default.infer; declare const OAuthCompleteStepUpResponse: zod__default.ZodObject<{ assurance: zod__default.ZodType>; validStepUps: zod__default.ZodArray>>; returnPath: zod__default.ZodString; }, zod__default.core.$strip>; type OAuthCompleteStepUpResponse = zod__default.infer; declare const SendOtpResponse: zod__default.ZodObject<{ success: zod__default.ZodBoolean; }, zod__default.core.$strip>; type SendOtpResponse = zod__default.infer; declare class SessionAssuranceService { private readonly client; constructor(client: APIClient); get(): Promise; stepUpWithPassword(password: string): Promise; sendOtp(): Promise; verifyOtp(otp: string): Promise; beginOAuthStepUp(params: BeginOAuthStepUpParams): Promise; completeOAuthStepUp(stepUpToken: string): Promise; } /** * Options for signing in with a social provider (Google or Microsoft). */ type SocialSignInOptions = { /** The social identity provider to authenticate with. */ provider: 'google' | 'microsoft'; /** URL to redirect to after successful authentication. */ callbackURL: string; /** URL to redirect to if authentication fails. Falls back to the API's default error page if not provided. */ errorCallbackURL?: string; /** Email address to preselect at the provider, sent as the `login_hint` authorization parameter. */ loginHint?: string; }; /** * Options for signing in via Single Sign-On (SAML or OIDC). */ type SignInWithSsoOptions = { /** The user's email address, used to resolve the correct SSO identity provider. */ email: string; /** URL to redirect to after successful authentication. */ callbackURL: string; /** URL to redirect to if authentication fails. Falls back to the API's default error page if not provided. */ errorCallbackURL?: string; }; /** * Options for signing in with email and password credentials. */ type SignInWithEmailAndPasswordOptions = { /** The user's email address. */ email: string; /** The user's password. */ password: string; /** URL to redirect to after successful authentication. */ callbackURL: string; }; /** * Interactive login methods an environment can enable (`AUTH_LOGIN_METHODS`). * Session-carrying mechanisms (JWT, API keys, application tokens) are not * login methods. */ declare const LOGIN_METHODS: readonly ["password", "google", "microsoft", "sso", "otp"]; type LoginMethod = typeof LOGIN_METHODS[number]; /** * Response of the public `GET /login-methods` endpoint. */ type LoginMethodsResponse = { /** Login methods enabled in the environment, regardless of application. */ loginMethods: LoginMethod[]; }; declare const DEFAULT_SESSION_ASSURANCE_CONFIG: ApplicationSessionAssuranceConfig; declare const DEFAULT_APPLICATION_CONFIG: { version: 1; sessionAssurance: ApplicationSessionAssuranceConfig; }; type ApplicationSessionAssuranceConfig = { acceptedAmr: AMR[]; minAal: AAL; }; declare const ApplicationSessionAssuranceConfig: zod__default.ZodType; type ApplicationConfig = { version: 1; sessionAssurance: ApplicationSessionAssuranceConfig; }; declare const ApplicationConfig: zod__default.ZodType; /** * Keys of the organization's related collections that can be optionally * included in the "who am I" response. */ type WhoAmIInclude = 'members' | 'teams' | 'invitations'; /** * Represents a registered OAuth application. */ type Application = { /** Unique application identifier. */ id: string; /** Display name of the application. */ name: string; /** Human-readable description of the application. */ description: string; /** Allowed OAuth redirect URIs for this application. */ redirectUris: string[]; /** Additional configuration for this application. */ config?: ApplicationConfig; }; /** * Fields that can be optionally included when listing candidate organizations. */ type ListCandidateOrganizationsInclude = 'lastUsed'; /** * Options accepted by the candidate organizations client method. */ type ListCandidateOrganizationsOptions = { /** * Fields to include on each returned organization. When omitted or empty, * only the base organization fields are returned. */ include?: ListCandidateOrganizationsInclude[]; }; /** * Response returned when listing candidate organizations for an application. */ type ListCandidateOrganizationsResponse = Array; /** * Whether an application refuses sign-ins, and the notice shown to users who * try to sign in through it. */ type ApplicationDeprecation = { /** Whether the application is disabled. A disabled application refuses every sign-in. */ disabled: boolean; /** Plain-text notice written by an admin, or `null` when the application is enabled or has none. */ deprecationNotice: string | null; }; /** * Public application context used to preserve continuity during auth redirects. */ type ApplicationAuthContextResponse = { /** Minimal application identity shown in the hosted auth flow. */ application: Pick & ApplicationDeprecation; /** * Login methods usable for this application: the environment allowlist * intersected with the application's accepted AMRs. */ loginMethods: LoginMethod[]; }; /** * Response returned when starting an authorization flow. */ type StartAuthorizationFlowResponse = { /** The authorization code to exchange for tokens. */ code: string; }; /** * Response returned when completing an authorization flow or refreshing tokens. */ type CompleteAuthorizationFlowResponse = { /** Short-lived JWT access token. */ accessToken: string; /** Long-lived refresh token for obtaining new access tokens. */ refreshToken: string; /** The authenticated user. */ user: User; /** The organization the tokens are scoped to. */ organization: FullOrganization; /** Assurance context embedded in the issued access token. */ assurance: JWTPayload['assurance']; }; /** * Credentials used to authenticate an application service account. */ type ClientCredentialsGrant = { /** The application identifier. */ clientId: string; /** A valid secret issued for the application. */ clientSecret: string; /** The organization to scope the access token to. */ organizationId: string; }; /** * Response returned after a successful client credentials exchange. * * Client credentials issue only a short-lived access token, so this response * intentionally does not include a refresh token. */ type ClientCredentialsTokenResponse = Omit; /** * Response returned by the "who am I" endpoint. * * By default, the `organization` only contains the base organization fields. * The `members`, `teams`, and `invitations` collections are only populated * when explicitly requested via the `include` query parameter. */ type WhoAmIResponse = { /** The authenticated user. */ user: User; /** The user's active organization. */ organization: WhoAmIOrganization; /** Assurance context embedded in the verified access token. */ assurance: JWTPayload['assurance']; }; /** * Options accepted by the "who am I" client method. */ type WhoAmIOptions = { /** * Collections to include in the returned organization. When omitted or * empty, only the base organization fields are returned. */ include?: WhoAmIInclude[]; }; /** * Response returned when starting a device authorization flow (RFC 8628). */ type DeviceAuthorizationResponse = { /** The device verification code for polling. */ device_code: string; /** The user-facing code to enter on the verification page. */ user_code: string; /** The URI the user should visit to authorize the device. */ verification_uri: string; /** A complete URI including the user code for convenience. */ verification_uri_complete: string; /** Number of seconds until the device code expires. */ expires_in: number; /** Minimum polling interval in seconds. */ interval: number; }; /** * Minimal application info shown in device authorization context. * * @internal */ type DeviceContextApplication = { /** Unique application identifier. */ id: string; /** Display name of the application. */ name: string; /** Human-readable description, or `null` if not set. */ description: string | null; } & ApplicationDeprecation; /** * Context information for a pending device authorization request. */ type DeviceAuthorizationContextResponse = { /** The application that initiated the device flow, with verification status. */ requester: DeviceContextApplication & { isVerified: boolean; }; /** The target application the requester wants access to. */ target: DeviceContextApplication; /** Organizations the user can authorize the device for. Empty when the requester or the target is disabled. */ organizations: FullOrganization[]; /** Organization pre-selected by the requester, if any. */ preselectedOrganizationId: string | null; /** Current status of the device authorization request. */ status: 'pending' | 'approved' | 'denied'; /** Seconds remaining before the device code expires. */ expiresIn: number; }; /** * Role of the application an application session was issued for. */ type ApplicationRole = { applicationId: string; name: string; displayName: string; description: string; /** Roles of the same application this role may grant, change, revoke and invite. */ manageableRoles: string[]; }; /** * Response returned when approving or denying a device authorization request. */ type DeviceAuthorizationActionResponse = { /** Whether the action was performed successfully. */ success: boolean; }; /** * Generic error thrown by the `ApplicationService`. * * All application-specific errors extend this class, so you can catch * `ApplicationError` to handle any application-related failure. */ declare class ApplicationError extends BaseError { /** * HTTP status of the upstream failure, when one was received. */ readonly status?: number; constructor(message: string, options?: ErrorOptions & { status?: number; }); } /** * Thrown when a refresh token has expired or been revoked. * * The client should discard its stored tokens and prompt the user * to re-authenticate. */ declare class RefreshTokenExpiredError extends ApplicationError { constructor(options?: ErrorOptions & { status?: number; }); } /** * Thrown when an authorization flow fails unexpectedly. */ declare class AuthorizationFlowError extends ApplicationError { constructor(message: string, options?: ErrorOptions); } /** * Thrown when the authenticated session no longer satisfies the target * application's assurance policy. * * During device-code token exchange this is a final error: the consumed flow * cannot be retried and the client must start a new device authorization flow. */ declare class ApplicationSessionAssuranceError extends ApplicationError { readonly payload: SessionAssuranceRequiredPayload | null; readonly currentAssurance: SessionAssuranceRequiredPayload['currentAssurance'] | null; readonly requiredAssurance: SessionAssuranceRequiredPayload['requiredAssurance'] | null; readonly validStepUps: SessionAssuranceRequiredPayload['validStepUps']; constructor(payload?: SessionAssuranceRequiredPayload | null, options?: ErrorOptions); } /** * Payload the API attaches to an `application_disabled` error. */ type ApplicationDisabledPayload = { applicationId: string; applicationName: string; deprecationNotice: string | null; }; /** * Reads the {@link ApplicationDisabledPayload} from an error returned by the * API, following `cause` chains. Returns `null` when the error is not an * `application_disabled` error. * * @param error - The caught error value */ declare function parseApplicationDisabledPayload(error: unknown): ApplicationDisabledPayload | null; /** * Thrown when the application was disabled by an admin. Every sign-in, token * exchange and refresh through it fails until it is enabled again, so clients * must not retry or start a new flow. * * The message is the application's deprecation notice when it has one. */ declare class ApplicationDisabledError extends ApplicationError { readonly applicationId: string | null; readonly applicationName: string | null; readonly deprecationNotice: string | null; constructor(payload?: ApplicationDisabledPayload | null, options?: ErrorOptions & { status?: number; }); } /** * Thrown when an operation requires an authenticated user but no session exists. */ declare class UserNotLoggedInError extends ApplicationError { constructor(message: string, options?: ErrorOptions); } /** * Thrown during device code polling when the user has not yet authorized the request. * * The client should continue polling at the specified interval. */ declare class DeviceAuthorizationPendingError extends ApplicationError { constructor(options?: ErrorOptions); } /** * Thrown when the client is polling too frequently during the device flow. * * The client should increase its polling interval before retrying. */ declare class DeviceAuthorizationSlowDownError extends ApplicationError { constructor(options?: ErrorOptions); } /** * Thrown when the user explicitly denies the device authorization request. */ declare class DeviceAccessDeniedError extends ApplicationError { constructor(options?: ErrorOptions); } /** * Thrown when the device code has expired or has already been consumed. * * The client must start a new device authorization flow. */ declare class DeviceCodeExpiredError extends ApplicationError { constructor(options?: ErrorOptions); } /** * Thrown when the authorization server returns a transient error during the device flow. * * The token exchange can be safely retried. */ declare class DeviceTransientServerError extends ApplicationError { constructor(options?: ErrorOptions); } /** * Checks whether a session assurance value satisfies an application policy. */ declare function isSessionAssuranceSufficient(sessionAssurance: JWTPayload['assurance'] | null | undefined, config?: ApplicationConfig): boolean; /** * Service for managing applications and their candidate organizations. * * Provides functionality for: * - OAuth authorization code flow (PKCE) * - Device authorization flow (RFC 8628) * - Client credentials flow for service accounts * - Token management (refresh, exchange) * - Organization switching */ declare class ApplicationService { private client; /** * Creates a new ApplicationService instance. * * @param client - The API client for making application requests */ constructor(client: APIClient); /** * Gets public display context for an application auth redirect. * * @param applicationId - The application ID to get public auth context for * @returns The minimal application identity safe to show before login */ getApplicationAuthContext(applicationId: string): Promise; /** * Lists candidate organizations for a specific application. * * Returns organizations where the authenticated user is a member and * the effective entitlement grants access through its rules. An enabled global * entitlement is selected first; organization entitlements are considered only * when no global entitlement is enabled. * * Pass `options.include` with `lastUsed` to flag the organization the user * last signed in to the application with. * * @param applicationId - The application ID to get candidate organizations for * @param options - Optional include list controlling which fields are returned * @returns The list of candidate organizations */ listCandidateOrganizations(applicationId: string, options?: ListCandidateOrganizationsOptions): Promise; /** * Starts an authorization flow for a specific application. * * @param applicationId - The application ID to start the authorization flow for * @param redirectUri - The redirect URI to use for the authorization flow * @param codeChallenge - The code challenge to use for the authorization flow * @param organizationId - The organization ID to start the authorization flow for */ startAuthorizationFlow(applicationId: string, redirectUri: string, codeChallenge: string, organizationId: string): Promise; /** * Starts a device authorization flow (RFC 8628). * * Returns a device code and user code that the end user must enter * on the verification URI to authorize the device. * * @param requesterApplicationId - The application requesting authorization * @param targetApplicationId - The target application to gain access to. Omit it to sign the user in to the requester application itself. * @returns Device authorization details including codes and verification URI */ startDeviceAuthorizationFlow(requesterApplicationId: string, targetApplicationId?: string): Promise; /** * Retrieves the context for a pending device authorization request. * * Used by the authorization page to display details about the requesting * and target applications before the user approves or denies. * * @param userCode - The user code from the device authorization response * @returns Context including application info, available organizations, and status */ getDeviceAuthorizationContext(userCode: string): Promise; /** * Approves a pending device authorization request. * * @param userCode - The user code identifying the device authorization request * @param organizationId - The organization to authorize the device for * @returns Confirmation of the approval action */ approveDeviceAuthorizationFlow(userCode: string, organizationId: string): Promise; /** * Denies a pending device authorization request. * * @param userCode - The user code identifying the device authorization request * @returns Confirmation of the denial action */ denyDeviceAuthorizationFlow(userCode: string): Promise; /** * Exchanges a device code for access and refresh tokens. * * This should be called by the device client while polling. It will throw * typed errors to indicate the polling state (pending, slow down, denied, expired). * * @param deviceCode - The device code obtained from {@link startDeviceAuthorizationFlow} * @returns Access and refresh tokens along with user and organization info * * @throws {DeviceAuthorizationPendingError} The user hasn't authorized yet — keep polling * @throws {DeviceAuthorizationSlowDownError} Polling too fast — increase the interval * @throws {DeviceAccessDeniedError} The user denied the request * @throws {DeviceCodeExpiredError} The device code has expired * @throws {DeviceTransientServerError} Transient server error — safe to retry * @throws {ApplicationSessionAssuranceError} Assurance policy changed or is no longer met — start a new flow * @throws {ApplicationDisabledError} The requester or target application is disabled — stop polling */ exchangeDeviceCodeForTokens(deviceCode: string): Promise; /** * Exchanges application client credentials for a service-account access token. * * The returned token is scoped to the requested organization and cannot be * refreshed. Exchange the credentials again when a new token is needed. * * @param credentials - Application credentials and target organization * @returns A short-lived access token with service-account and organization details */ exchangeClientCredentialsForToken(credentials: ClientCredentialsGrant): Promise; /** * Completes an authorization flow for a specific application. * * @param code - The code to use for the authorization flow * @param codeVerifier - The code verifier to use for the authorization flow */ completeAuthorizationFlow(code: string, codeVerifier: string): Promise; /** * Refreshes an authentication token for a specific application. * * @param refreshToken - The refresh token to use for the authentication token refresh * @throws {RefreshTokenExpiredError} When the refresh token has expired or is invalid * @throws {ApplicationDisabledError} When the application has been disabled * @throws {ApplicationError} For other API errors */ refreshAccessToken(refreshToken: string): Promise; /** * Gets the current user and organization for a specific application. * * By default, the returned organization does not include its `members`, * `teams`, or `invitations` collections. Pass `options.include` to request * any of them explicitly. * * @param accessToken - The access token to use for the who am I request * @param options - Optional include list controlling which relations are loaded * @returns The current user and organization */ whoAmI(accessToken: string, options?: WhoAmIOptions): Promise; /** * Switches the active organization for the authenticated user. * * Issues new access and refresh tokens scoped to the specified organization. * Requires active membership in the target organization and an enabled entitlement * whose rules allow the user. The global entitlement is selected first, and its * denial never falls back to an organization entitlement. Organization entitlements * are considered only when no global entitlement is enabled. * * @param organizationId - The ID of the organization to switch to * @param accessToken - Access token for authentication, sent as the `x-tela-access-token` header * @returns New authentication tokens and user/organization details */ switchOrganization(organizationId: string, accessToken: string): Promise; /** * Logs out the user by invalidating their refresh token. * * Revokes the refresh token on the server, preventing further token refreshes * and effectively ending the user's session. * * @param refreshToken - The refresh token to invalidate */ logout(refreshToken: string): Promise; /** * Lists the roles of the application the current session was issued for. * * @returns The application's roles */ listRoles(): Promise; } declare const ApiKeyMetadata: zod__default.ZodObject<{ user: zod__default.ZodObject<{ id: zod__default.ZodString; email: zod__default.ZodString; }, zod__default.core.$strip>; workspace: zod__default.ZodObject<{ id: zod__default.ZodString; title: zod__default.ZodString; }, zod__default.core.$strip>; application: zod__default.ZodNullable>>; }, zod__default.core.$strip>; /** * Metadata attached to an API key, identifying the owning user and workspace. */ type ApiKeyMetadata = zod__default.infer & Record; /** * A full API key including the secret key value. * * The secret `key` field is only returned once at creation time. */ type ApiKey = Omit & { /** Display name of the API key. */ name: string; /** Metadata identifying the key's owner and workspace. */ metadata: ApiKeyMetadata; }; /** * An API key with the secret key value omitted. * * Used in list and get operations where the secret should not be exposed. */ type ApiKeyWithoutSecret = Omit; /** * Payload for creating a new API key. */ type CreateApiKeyPayload = { /** Display name for the API key. */ name: string; /** Time in seconds until the key expires. Omit for a non-expiring key. */ expiresIn?: number; /** Optional prefix prepended to the generated key for identification. */ prefix?: string; /** Optional metadata to attach to the key. */ metadata?: ApiKeyMetadata; }; /** * Payload for updating an existing API key. */ type UpdateApiKeyPayload = { /** The ID of the API key to update. */ id: string; /** The new display name for the API key. */ name: string; }; /** * Removes index signatures from a type * @template T - The type to remove index signatures from * @example * ```typescript * type MyType = { * foo: string * bar: number * [key: string]: any * } * * type StrictMyType = Strict // { foo: string; bar: number; } * ``` */ type Strict = { [K in keyof T as string extends K ? never : number extends K ? never : K]: T[K]; }; /** * Creates a configured Better Auth API client with all required plugins. * * @param apiUrl - The base URL of the authentication API * @param fetchOptions - Custom fetch options to include in all API requests * @returns A fully-configured Better Auth client instance * * @internal */ declare function createAPIClient(apiUrl: string, fetchOptions?: BetterFetchOption): better_auth_client.AuthClient<{ baseURL: string; plugins: ({ id: "organization"; version: string; $InferServerPlugin: better_auth_plugins.OrganizationPlugin<{ ac: { newRole(statements: better_auth_plugins.RoleInput<{ access: string[]; organization: readonly ["update", "delete"]; member: readonly ["create", "update", "delete"]; invitation: readonly ["create", "cancel"]; team: readonly ["create", "update", "delete"]; ac: readonly ["create", "read", "update", "delete"]; }, TRoleStatements>): better_auth_plugins.Role, { access: string[]; organization: readonly ["update", "delete"]; member: readonly ["create", "update", "delete"]; invitation: readonly ["create", "cancel"]; team: readonly ["create", "update", "delete"]; ac: readonly ["create", "read", "update", "delete"]; }>; statements: { access: string[]; organization: readonly ["update", "delete"]; member: readonly ["create", "update", "delete"]; invitation: readonly ["create", "cancel"]; team: readonly ["create", "update", "delete"]; ac: readonly ["create", "read", "update", "delete"]; }; }; roles: { "org:admin": better_auth_plugins.Role, { access: string[]; organization: readonly ["update", "delete"]; member: readonly ["create", "update", "delete"]; invitation: readonly ["create", "cancel"]; team: readonly ["create", "update", "delete"]; ac: readonly ["create", "read", "update", "delete"]; }>; "org:member": better_auth_plugins.Role, { access: string[]; organization: readonly ["update", "delete"]; member: readonly ["create", "update", "delete"]; invitation: readonly ["create", "cancel"]; team: readonly ["create", "update", "delete"]; ac: readonly ["create", "read", "update", "delete"]; }>; "org:reviewer": better_auth_plugins.Role, { access: string[]; organization: readonly ["update", "delete"]; member: readonly ["create", "update", "delete"]; invitation: readonly ["create", "cancel"]; team: readonly ["create", "update", "delete"]; ac: readonly ["create", "read", "update", "delete"]; }>; }; teams: { enabled: true; }; schema: undefined; dynamicAccessControl: { enabled: false; }; }>; getActions: ($fetch: better_auth_client.BetterFetch, _$store: better_auth.ClientStore, co: better_auth.BetterAuthClientOptions | undefined) => { $Infer: { ActiveOrganization: { members: { id: string; organizationId: string; role: "org:admin" | "org:member" | "org:reviewer"; createdAt: Date; userId: string; teamId?: string | undefined | undefined; user: { id: string; email: string; name: string; image?: string | undefined; }; }[]; invitations: { id: string; organizationId: string; email: string; role: "org:admin" | "org:member" | "org:reviewer"; status: better_auth_plugins.InvitationStatus; inviterId: string; expiresAt: Date; createdAt: Date; teamId?: string | undefined | undefined; }[]; teams: { id: string; name: string; organizationId: string; createdAt: Date; updatedAt?: Date | undefined; }[]; } & { id: string; name: string; slug: string; createdAt: Date; logo?: string | null | undefined | undefined; metadata?: any; }; Organization: { id: string; name: string; slug: string; createdAt: Date; logo?: string | null | undefined; metadata?: any; }; Invitation: { id: string; organizationId: string; email: string; role: "org:admin" | "org:member" | "org:reviewer"; status: better_auth_plugins.InvitationStatus; inviterId: string; expiresAt: Date; createdAt: Date; teamId?: string | undefined | undefined; }; Member: { id: string; organizationId: string; role: "org:admin" | "org:member" | "org:reviewer"; createdAt: Date; userId: string; teamId?: string | undefined | undefined; user: { id: string; email: string; name: string; image?: string | undefined; }; }; Team: { id: string; name: string; organizationId: string; createdAt: Date; updatedAt?: Date | undefined; }; }; organization: { checkRolePermission: (data: { permissions: { access?: string[] | undefined; organization?: ("update" | "delete")[] | undefined; member?: ("update" | "delete" | "create")[] | undefined; invitation?: ("create" | "cancel")[] | undefined; team?: ("update" | "delete" | "create")[] | undefined; ac?: ("update" | "delete" | "create" | "read")[] | undefined; }; } & { role: R; }) => boolean; }; }; getAtoms: ($fetch: better_auth_client.BetterFetch) => { $listOrg: better_auth_client.PreinitializedWritableAtom & object; $activeOrgSignal: better_auth_client.PreinitializedWritableAtom & object; $activeMemberSignal: better_auth_client.PreinitializedWritableAtom & object; $activeMemberRoleSignal: better_auth_client.PreinitializedWritableAtom & object; activeOrganization: better_auth_client.AuthQueryAtom>; listOrganizations: better_auth_client.AuthQueryAtom<{ id: string; name: string; slug: string; createdAt: Date; logo?: string | null | undefined | undefined; metadata?: any; }[]>; activeMember: better_auth_client.AuthQueryAtom<{ id: string; organizationId: string; userId: string; role: string; createdAt: Date; }>; activeMemberRole: better_auth_client.AuthQueryAtom<{ role: string; }>; }; pathMethods: { "/organization/get-full-organization": "GET"; "/organization/list-user-teams": "GET"; }; atomListeners: ({ matcher(path: string): path is "/organization/create" | "/organization/update" | "/organization/delete"; signal: "$listOrg"; } | { matcher(path: string): boolean; signal: "$activeOrgSignal"; } | { matcher(path: string): boolean; signal: "$sessionSignal"; } | { matcher(path: string): boolean; signal: "$activeMemberSignal"; } | { matcher(path: string): boolean; signal: "$activeMemberRoleSignal"; })[]; $ERROR_CODES: { YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION">; YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS: better_auth.RawError<"YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS">; ORGANIZATION_ALREADY_EXISTS: better_auth.RawError<"ORGANIZATION_ALREADY_EXISTS">; ORGANIZATION_SLUG_ALREADY_TAKEN: better_auth.RawError<"ORGANIZATION_SLUG_ALREADY_TAKEN">; ORGANIZATION_NOT_FOUND: better_auth.RawError<"ORGANIZATION_NOT_FOUND">; USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION: better_auth.RawError<"USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION">; YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION">; YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION">; NO_ACTIVE_ORGANIZATION: better_auth.RawError<"NO_ACTIVE_ORGANIZATION">; USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION: better_auth.RawError<"USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION">; MEMBER_NOT_FOUND: better_auth.RawError<"MEMBER_NOT_FOUND">; ROLE_NOT_FOUND: better_auth.RawError<"ROLE_NOT_FOUND">; YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM">; TEAM_ALREADY_EXISTS: better_auth.RawError<"TEAM_ALREADY_EXISTS">; TEAM_NOT_FOUND: better_auth.RawError<"TEAM_NOT_FOUND">; YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER: better_auth.RawError<"YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER">; YOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER: better_auth.RawError<"YOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER">; YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER">; YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION">; USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION: better_auth.RawError<"USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION">; INVITATION_NOT_FOUND: better_auth.RawError<"INVITATION_NOT_FOUND">; YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION: better_auth.RawError<"YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION">; EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION: better_auth.RawError<"EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION">; EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION: better_auth.RawError<"EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION">; YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION">; INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION: better_auth.RawError<"INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION">; YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE">; FAILED_TO_RETRIEVE_INVITATION: better_auth.RawError<"FAILED_TO_RETRIEVE_INVITATION">; YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS: better_auth.RawError<"YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS">; UNABLE_TO_REMOVE_LAST_TEAM: better_auth.RawError<"UNABLE_TO_REMOVE_LAST_TEAM">; YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER">; ORGANIZATION_MEMBERSHIP_LIMIT_REACHED: better_auth.RawError<"ORGANIZATION_MEMBERSHIP_LIMIT_REACHED">; YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION">; YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION">; YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM">; YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM">; INVITATION_LIMIT_REACHED: better_auth.RawError<"INVITATION_LIMIT_REACHED">; TEAM_MEMBER_LIMIT_REACHED: better_auth.RawError<"TEAM_MEMBER_LIMIT_REACHED">; USER_IS_NOT_A_MEMBER_OF_THE_TEAM: better_auth.RawError<"USER_IS_NOT_A_MEMBER_OF_THE_TEAM">; YOU_CAN_NOT_ACCESS_THE_MEMBERS_OF_THIS_TEAM: better_auth.RawError<"YOU_CAN_NOT_ACCESS_THE_MEMBERS_OF_THIS_TEAM">; YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM: better_auth.RawError<"YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM">; YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER">; YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER">; YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION">; YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION: better_auth.RawError<"YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION">; MISSING_AC_INSTANCE: better_auth.RawError<"MISSING_AC_INSTANCE">; YOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE: better_auth.RawError<"YOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE">; YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE">; YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE">; YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE">; YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE">; YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE">; YOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE">; TOO_MANY_ROLES: better_auth.RawError<"TOO_MANY_ROLES">; INVALID_RESOURCE: better_auth.RawError<"INVALID_RESOURCE">; ROLE_NAME_IS_ALREADY_TAKEN: better_auth.RawError<"ROLE_NAME_IS_ALREADY_TAKEN">; CANNOT_DELETE_A_PRE_DEFINED_ROLE: better_auth.RawError<"CANNOT_DELETE_A_PRE_DEFINED_ROLE">; ROLE_IS_ASSIGNED_TO_MEMBERS: better_auth.RawError<"ROLE_IS_ASSIGNED_TO_MEMBERS">; INVALID_TEAM_ID: better_auth.RawError<"INVALID_TEAM_ID">; }; } | { id: "custom-endpoints"; getActions: ($fetch: better_auth_client.BetterFetch) => { customEndpoints: { organizations: { apiKeys: (organizationId?: string) => Promise; }; teams: { members: (teamId: string) => Promise; }; }; }; } | { id: "invitation-signup"; getActions: ($fetch: better_auth_client.BetterFetch) => { invitationSignup: { status: (invitationId: string) => Promise; setupPassword: (invitationId: string, password: string) => Promise; }; }; } | { id: "sso-client"; version: string; $InferServerPlugin: _better_auth_sso.SSOPlugin<{ domainVerification: { enabled: false; }; }>; pathMethods: { "/sso/providers": "GET"; "/sso/get-provider": "GET"; }; } | { id: "two-factor"; version: string; $InferServerPlugin: ReturnType<((options?: O) => { id: "two-factor"; version: string; endpoints: { enableTwoFactor: better_auth.StrictEndpoint<"/two-factor/enable", { method: "POST"; body: zod.ZodObject<{ password: zod.ZodOptional; issuer: zod.ZodOptional; }, zod_v4_core.$strip> | zod.ZodObject<{ password: zod.ZodString; issuer: zod.ZodOptional; }, zod_v4_core.$strip>; use: ((inputContext: better_auth.MiddlewareInputContext) => Promise<{ session: { session: Record & { id: string; createdAt: Date; updatedAt: Date; userId: string; expiresAt: Date; token: string; ipAddress?: string | null | undefined; userAgent?: string | null | undefined; }; user: Record & { id: string; createdAt: Date; updatedAt: Date; email: string; emailVerified: boolean; name: string; image?: string | null | undefined; }; }; }>)[]; metadata: { openapi: { summary: string; description: string; responses: { 200: { description: string; content: { "application/json": { schema: { type: "object"; properties: { totpURI: { type: string; description: string; }; backupCodes: { type: string; items: { type: string; }; description: string; }; }; }; }; }; }; }; }; }; }, { totpURI: string; backupCodes: string[]; }>; disableTwoFactor: better_auth.StrictEndpoint<"/two-factor/disable", { method: "POST"; body: zod.ZodObject<{ password: zod.ZodOptional; }, zod_v4_core.$strip> | zod.ZodObject<{ password: zod.ZodString; }, zod_v4_core.$strip>; use: ((inputContext: better_auth.MiddlewareInputContext) => Promise<{ session: { session: Record & { id: string; createdAt: Date; updatedAt: Date; userId: string; expiresAt: Date; token: string; ipAddress?: string | null | undefined; userAgent?: string | null | undefined; }; user: Record & { id: string; createdAt: Date; updatedAt: Date; email: string; emailVerified: boolean; name: string; image?: string | null | undefined; }; }; }>)[]; metadata: { openapi: { summary: string; description: string; responses: { 200: { description: string; content: { "application/json": { schema: { type: "object"; properties: { status: { type: string; }; }; }; }; }; }; }; }; }; }, { status: boolean; }>; verifyBackupCode: better_auth.StrictEndpoint<"/two-factor/verify-backup-code", { method: "POST"; body: zod.ZodObject<{ code: zod.ZodString; disableSession: zod.ZodOptional; trustDevice: zod.ZodOptional; }, zod_v4_core.$strip>; metadata: { openapi: { description: string; responses: { "200": { description: string; content: { "application/json": { schema: { type: "object"; properties: { user: { type: string; properties: { id: { type: string; description: string; }; email: { type: string; format: string; nullable: boolean; description: string; }; emailVerified: { type: string; nullable: boolean; description: string; }; name: { type: string; nullable: boolean; description: string; }; image: { type: string; format: string; nullable: boolean; description: string; }; twoFactorEnabled: { type: string; description: string; }; createdAt: { type: string; format: string; description: string; }; updatedAt: { type: string; format: string; description: string; }; }; required: string[]; description: string; }; session: { type: string; properties: { token: { type: string; description: string; }; userId: { type: string; description: string; }; createdAt: { type: string; format: string; description: string; }; expiresAt: { type: string; format: string; description: string; }; }; required: string[]; description: string; }; }; required: string[]; }; }; }; }; }; }; }; }, { token: string | undefined; user: (Record & { id: string; createdAt: Date; updatedAt: Date; email: string; emailVerified: boolean; name: string; image?: string | null | undefined; }) | better_auth_plugins.UserWithTwoFactor; }>; generateBackupCodes: better_auth.StrictEndpoint<"/two-factor/generate-backup-codes", { method: "POST"; body: zod.ZodObject<{ password: zod.ZodOptional; }, zod_v4_core.$strip> | zod.ZodObject<{ password: zod.ZodString; }, zod_v4_core.$strip>; use: ((inputContext: better_auth.MiddlewareInputContext) => Promise<{ session: { session: Record & { id: string; createdAt: Date; updatedAt: Date; userId: string; expiresAt: Date; token: string; ipAddress?: string | null | undefined; userAgent?: string | null | undefined; }; user: Record & { id: string; createdAt: Date; updatedAt: Date; email: string; emailVerified: boolean; name: string; image?: string | null | undefined; }; }; }>)[]; metadata: { openapi: { description: string; responses: { "200": { description: string; content: { "application/json": { schema: { type: "object"; properties: { status: { type: string; description: string; enum: boolean[]; }; backupCodes: { type: string; items: { type: string; }; description: string; }; }; required: string[]; }; }; }; }; }; }; }; }, { status: boolean; backupCodes: string[]; }>; viewBackupCodes: better_auth.StrictEndpoint; }, zod_v4_core.$strip>; }, { status: boolean; backupCodes: string[]; }>; sendTwoFactorOTP: better_auth.StrictEndpoint<"/two-factor/send-otp", { method: "POST"; body: zod.ZodOptional; }, zod_v4_core.$strip>>; metadata: { openapi: { summary: string; description: string; responses: { 200: { description: string; content: { "application/json": { schema: { type: "object"; properties: { status: { type: string; }; }; }; }; }; }; }; }; }; }, { status: boolean; }>; verifyTwoFactorOTP: better_auth.StrictEndpoint<"/two-factor/verify-otp", { method: "POST"; body: zod.ZodObject<{ code: zod.ZodString; trustDevice: zod.ZodOptional; }, zod_v4_core.$strip>; metadata: { openapi: { summary: string; description: string; responses: { "200": { description: string; content: { "application/json": { schema: { type: "object"; properties: { token: { type: string; description: string; }; user: { type: string; properties: { id: { type: string; description: string; }; email: { type: string; format: string; nullable: boolean; description: string; }; emailVerified: { type: string; nullable: boolean; description: string; }; name: { type: string; nullable: boolean; description: string; }; image: { type: string; format: string; nullable: boolean; description: string; }; createdAt: { type: string; format: string; description: string; }; updatedAt: { type: string; format: string; description: string; }; }; required: string[]; description: string; }; }; required: string[]; }; }; }; }; }; }; }; }, { token: string; user: better_auth_plugins.UserWithTwoFactor; } | { token: string; user: Record & { id: string; createdAt: Date; updatedAt: Date; email: string; emailVerified: boolean; name: string; image?: string | null | undefined; }; }>; generateTOTP: better_auth.StrictEndpoint; metadata: { openapi: { summary: string; description: string; responses: { 200: { description: string; content: { "application/json": { schema: { type: "object"; properties: { code: { type: string; }; }; }; }; }; }; }; }; }; }, { code: string; }>; getTOTPURI: better_auth.StrictEndpoint<"/two-factor/get-totp-uri", { method: "POST"; use: ((inputContext: better_auth.MiddlewareInputContext) => Promise<{ session: { session: Record & { id: string; createdAt: Date; updatedAt: Date; userId: string; expiresAt: Date; token: string; ipAddress?: string | null | undefined; userAgent?: string | null | undefined; }; user: Record & { id: string; createdAt: Date; updatedAt: Date; email: string; emailVerified: boolean; name: string; image?: string | null | undefined; }; }; }>)[]; body: zod.ZodObject<{ password: zod.ZodOptional; }, zod_v4_core.$strip> | zod.ZodObject<{ password: zod.ZodString; }, zod_v4_core.$strip>; metadata: { openapi: { summary: string; description: string; responses: { 200: { description: string; content: { "application/json": { schema: { type: "object"; properties: { totpURI: { type: string; }; }; }; }; }; }; }; }; }; }, { totpURI: string; }>; verifyTOTP: better_auth.StrictEndpoint<"/two-factor/verify-totp", { method: "POST"; body: zod.ZodObject<{ code: zod.ZodString; trustDevice: zod.ZodOptional; }, zod_v4_core.$strip>; metadata: { openapi: { summary: string; description: string; responses: { 200: { description: string; content: { "application/json": { schema: { type: "object"; properties: { status: { type: string; }; }; }; }; }; }; }; }; }; }, { token: string; user: better_auth_plugins.UserWithTwoFactor; } | { token: string; user: Record & { id: string; createdAt: Date; updatedAt: Date; email: string; emailVerified: boolean; name: string; image?: string | null | undefined; }; }>; }; options: NoInfer; hooks: { after: { matcher(context: better_auth.HookEndpointContext): boolean; handler: (inputContext: better_auth.MiddlewareInputContext) => Promise<{ twoFactorRedirect: boolean; twoFactorMethods: string[]; } | undefined>; }[]; }; schema: { user: { fields: { twoFactorEnabled: { type: "boolean"; required: false; defaultValue: false; input: false; }; }; }; twoFactor: { fields: { secret: { type: "string"; required: true; returned: false; index: true; }; backupCodes: { type: "string"; required: true; returned: false; }; userId: { type: "string"; required: true; returned: false; references: { model: string; field: string; }; index: true; }; verified: { type: "boolean"; required: false; defaultValue: true; input: false; }; failedVerificationCount: { type: "number"; required: false; defaultValue: number; input: false; returned: false; }; lockedUntil: { type: "date"; required: false; input: false; returned: false; }; }; }; }; rateLimit: { pathMatcher(path: string): boolean; window: number; max: number; }[]; $ERROR_CODES: { OTP_NOT_ENABLED: better_auth.RawError<"OTP_NOT_ENABLED">; OTP_HAS_EXPIRED: better_auth.RawError<"OTP_HAS_EXPIRED">; TOTP_NOT_ENABLED: better_auth.RawError<"TOTP_NOT_ENABLED">; TWO_FACTOR_NOT_ENABLED: better_auth.RawError<"TWO_FACTOR_NOT_ENABLED">; BACKUP_CODES_NOT_ENABLED: better_auth.RawError<"BACKUP_CODES_NOT_ENABLED">; INVALID_BACKUP_CODE: better_auth.RawError<"INVALID_BACKUP_CODE">; INVALID_CODE: better_auth.RawError<"INVALID_CODE">; TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE: better_auth.RawError<"TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE">; ACCOUNT_TEMPORARILY_LOCKED: better_auth.RawError<"ACCOUNT_TEMPORARILY_LOCKED">; INVALID_TWO_FACTOR_COOKIE: better_auth.RawError<"INVALID_TWO_FACTOR_COOKIE">; }; })>; atomListeners: { matcher: (path: string) => boolean; signal: "$sessionSignal"; }[]; pathMethods: { "/two-factor/disable": "POST"; "/two-factor/enable": "POST"; "/two-factor/send-otp": "POST"; "/two-factor/generate-backup-codes": "POST"; "/two-factor/get-totp-uri": "POST"; "/two-factor/verify-totp": "POST"; "/two-factor/verify-otp": "POST"; "/two-factor/verify-backup-code": "POST"; }; fetchPlugins: { id: string; name: string; hooks: { onSuccess(context: better_auth_client.SuccessContext): Promise; }; }[]; $ERROR_CODES: { OTP_NOT_ENABLED: better_auth.RawError<"OTP_NOT_ENABLED">; OTP_HAS_EXPIRED: better_auth.RawError<"OTP_HAS_EXPIRED">; TOTP_NOT_ENABLED: better_auth.RawError<"TOTP_NOT_ENABLED">; TWO_FACTOR_NOT_ENABLED: better_auth.RawError<"TWO_FACTOR_NOT_ENABLED">; BACKUP_CODES_NOT_ENABLED: better_auth.RawError<"BACKUP_CODES_NOT_ENABLED">; INVALID_BACKUP_CODE: better_auth.RawError<"INVALID_BACKUP_CODE">; INVALID_CODE: better_auth.RawError<"INVALID_CODE">; TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE: better_auth.RawError<"TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE">; ACCOUNT_TEMPORARILY_LOCKED: better_auth.RawError<"ACCOUNT_TEMPORARILY_LOCKED">; INVALID_TWO_FACTOR_COOKIE: better_auth.RawError<"INVALID_TWO_FACTOR_COOKIE">; }; } | { id: "better-auth-client"; version: string; $InferServerPlugin: ReturnType<((options?: O) => { id: "jwt"; version: string; options: NoInfer; endpoints: { getJwks: better_auth.StrictEndpoint; getToken: better_auth.StrictEndpoint<"/token", { method: "GET"; requireHeaders: true; use: ((inputContext: better_auth.MiddlewareInputContext) => Promise<{ session: { session: Record & { id: string; createdAt: Date; updatedAt: Date; userId: string; expiresAt: Date; token: string; ipAddress?: string | null | undefined; userAgent?: string | null | undefined; }; user: Record & { id: string; createdAt: Date; updatedAt: Date; email: string; emailVerified: boolean; name: string; image?: string | null | undefined; }; }; }>)[]; metadata: { openapi: { operationId: string; description: string; responses: { 200: { description: string; content: { "application/json": { schema: { type: "object"; properties: { token: { type: string; }; }; }; }; }; }; }; }; }; }, { token: string; }>; signJWT: better_auth.StrictEndpoint; overrideOptions: zod.ZodOptional>; }, zod_v4_core.$strip>; }, { token: string; }>; verifyJWT: better_auth.StrictEndpoint; }, zod_v4_core.$strip>; }, { payload: (jose.JWTPayload & Required>) | null; }>; }; hooks: { after: { matcher(context: better_auth.HookEndpointContext): boolean; handler: (inputContext: better_auth.MiddlewareInputContext) => Promise; }[]; }; schema: { jwks: { fields: { publicKey: { type: "string"; required: true; }; privateKey: { type: "string"; required: true; }; createdAt: { type: "date"; required: true; }; expiresAt: { type: "date"; required: false; }; }; }; }; })>; pathMethods: { [x: string]: "GET"; }; getActions: ($fetch: better_auth_client.BetterFetch, _$store: better_auth.ClientStore, _options: better_auth.BetterAuthClientOptions | undefined) => { jwks: (fetchOptions?: better_auth.ClientFetchOption) => Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: jose.JSONWebKeySet; error: null; }>; }; } | { id: "api-key"; version: string; $InferServerPlugin: ReturnType; pathMethods: { "/api-key/create": "POST"; "/api-key/delete": "POST"; "/api-key/delete-all-expired-api-keys": "POST"; }; $ERROR_CODES: { INVALID_METADATA_TYPE: better_auth.RawError<"INVALID_METADATA_TYPE">; REFILL_AMOUNT_AND_INTERVAL_REQUIRED: better_auth.RawError<"REFILL_AMOUNT_AND_INTERVAL_REQUIRED">; REFILL_INTERVAL_AND_AMOUNT_REQUIRED: better_auth.RawError<"REFILL_INTERVAL_AND_AMOUNT_REQUIRED">; USER_BANNED: better_auth.RawError<"USER_BANNED">; UNAUTHORIZED_SESSION: better_auth.RawError<"UNAUTHORIZED_SESSION">; KEY_NOT_FOUND: better_auth.RawError<"KEY_NOT_FOUND">; KEY_DISABLED: better_auth.RawError<"KEY_DISABLED">; KEY_EXPIRED: better_auth.RawError<"KEY_EXPIRED">; USAGE_EXCEEDED: better_auth.RawError<"USAGE_EXCEEDED">; KEY_NOT_RECOVERABLE: better_auth.RawError<"KEY_NOT_RECOVERABLE">; EXPIRES_IN_IS_TOO_SMALL: better_auth.RawError<"EXPIRES_IN_IS_TOO_SMALL">; EXPIRES_IN_IS_TOO_LARGE: better_auth.RawError<"EXPIRES_IN_IS_TOO_LARGE">; INVALID_REMAINING: better_auth.RawError<"INVALID_REMAINING">; INVALID_PREFIX_LENGTH: better_auth.RawError<"INVALID_PREFIX_LENGTH">; INVALID_NAME_LENGTH: better_auth.RawError<"INVALID_NAME_LENGTH">; METADATA_DISABLED: better_auth.RawError<"METADATA_DISABLED">; RATE_LIMIT_EXCEEDED: better_auth.RawError<"RATE_LIMIT_EXCEEDED">; NO_VALUES_TO_UPDATE: better_auth.RawError<"NO_VALUES_TO_UPDATE">; KEY_DISABLED_EXPIRATION: better_auth.RawError<"KEY_DISABLED_EXPIRATION">; INVALID_API_KEY: better_auth.RawError<"INVALID_API_KEY">; INVALID_USER_ID_FROM_API_KEY: better_auth.RawError<"INVALID_USER_ID_FROM_API_KEY">; INVALID_REFERENCE_ID_FROM_API_KEY: better_auth.RawError<"INVALID_REFERENCE_ID_FROM_API_KEY">; INVALID_API_KEY_GETTER_RETURN_TYPE: better_auth.RawError<"INVALID_API_KEY_GETTER_RETURN_TYPE">; SERVER_ONLY_PROPERTY: better_auth.RawError<"SERVER_ONLY_PROPERTY">; FAILED_TO_UPDATE_API_KEY: better_auth.RawError<"FAILED_TO_UPDATE_API_KEY">; NAME_REQUIRED: better_auth.RawError<"NAME_REQUIRED">; ORGANIZATION_ID_REQUIRED: better_auth.RawError<"ORGANIZATION_ID_REQUIRED">; USER_NOT_MEMBER_OF_ORGANIZATION: better_auth.RawError<"USER_NOT_MEMBER_OF_ORGANIZATION">; INSUFFICIENT_API_KEY_PERMISSIONS: better_auth.RawError<"INSUFFICIENT_API_KEY_PERMISSIONS">; NO_DEFAULT_API_KEY_CONFIGURATION_FOUND: better_auth.RawError<"NO_DEFAULT_API_KEY_CONFIGURATION_FOUND">; ORGANIZATION_PLUGIN_REQUIRED: better_auth.RawError<"ORGANIZATION_PLUGIN_REQUIRED">; }; } | { id: "admin-client"; version: string; $InferServerPlugin: { id: "admin"; version: string; init(): { options: { databaseHooks: { user: { create: { before(user: { id: string; createdAt: Date; updatedAt: Date; email: string; emailVerified: boolean; name: string; image?: string | null | undefined; } & Record): Promise<{ data: { id: string; createdAt: Date; updatedAt: Date; email: string; emailVerified: boolean; name: string; image?: string | null | undefined; role: string; }; }>; }; }; session: { create: { before(session: { id: string; createdAt: Date; updatedAt: Date; userId: string; expiresAt: Date; token: string; ipAddress?: string | null | undefined; userAgent?: string | null | undefined; } & Record, ctx: better_auth.GenericEndpointContext | null): Promise; }; }; }; }; }; hooks: { after: { matcher(context: better_auth.HookEndpointContext): boolean; handler: (inputContext: better_auth.MiddlewareInputContext) => Promise; }[]; }; endpoints: { setRole: better_auth.StrictEndpoint<"/admin/set-role", { method: "POST"; body: zod.ZodObject<{ userId: zod.ZodCoercedString; role: zod.ZodUnion]>; }, zod_v4_core.$strip>; requireHeaders: true; use: ((inputContext: better_auth.MiddlewareInputContext) => Promise<{ session: { user: better_auth_plugins.UserWithRole; session: { id: string; createdAt: Date; updatedAt: Date; userId: string; expiresAt: Date; token: string; ipAddress?: string | null | undefined; userAgent?: string | null | undefined; }; }; }>)[]; metadata: { openapi: { operationId: string; summary: string; description: string; responses: { 200: { description: string; content: { "application/json": { schema: { type: "object"; properties: { user: { $ref: string; }; }; }; }; }; }; }; }; $Infer: { body: { userId: string; role: "admin" | "user" | ("admin" | "user")[]; }; }; }; }, { user: better_auth_plugins.UserWithRole; }>; getUser: better_auth.StrictEndpoint<"/admin/get-user", { method: "GET"; query: zod.ZodObject<{ id: zod.ZodString; }, zod_v4_core.$strip>; use: ((inputContext: better_auth.MiddlewareInputContext) => Promise<{ session: { user: better_auth_plugins.UserWithRole; session: { id: string; createdAt: Date; updatedAt: Date; userId: string; expiresAt: Date; token: string; ipAddress?: string | null | undefined; userAgent?: string | null | undefined; }; }; }>)[]; metadata: { openapi: { operationId: string; summary: string; description: string; responses: { 200: { description: string; content: { "application/json": { schema: { type: "object"; properties: { user: { $ref: string; }; }; }; }; }; }; }; }; }; }, better_auth_plugins.UserWithRole>; createUser: better_auth.StrictEndpoint<"/admin/create-user", { method: "POST"; body: zod.ZodObject<{ email: zod.ZodString; password: zod.ZodOptional; name: zod.ZodString; role: zod.ZodOptional]>>; data: zod.ZodOptional>; }, zod_v4_core.$strip>; metadata: { openapi: { operationId: string; summary: string; description: string; responses: { 200: { description: string; content: { "application/json": { schema: { type: "object"; properties: { user: { $ref: string; }; }; }; }; }; }; }; }; $Infer: { body: { email: string; password?: string | undefined; name: string; role?: "admin" | "user" | ("admin" | "user")[] | undefined; data?: Record | undefined; }; }; }; }, { user: better_auth_plugins.UserWithRole; }>; adminUpdateUser: better_auth.StrictEndpoint<"/admin/update-user", { method: "POST"; body: zod.ZodObject<{ userId: zod.ZodCoercedString; data: zod.ZodRecord; }, zod_v4_core.$strip>; use: ((inputContext: better_auth.MiddlewareInputContext) => Promise<{ session: { user: better_auth_plugins.UserWithRole; session: { id: string; createdAt: Date; updatedAt: Date; userId: string; expiresAt: Date; token: string; ipAddress?: string | null | undefined; userAgent?: string | null | undefined; }; }; }>)[]; metadata: { openapi: { operationId: string; summary: string; description: string; responses: { 200: { description: string; content: { "application/json": { schema: { type: "object"; properties: { user: { $ref: string; }; }; }; }; }; }; }; }; }; }, better_auth_plugins.UserWithRole>; listUsers: better_auth.StrictEndpoint<"/admin/list-users", { method: "GET"; use: ((inputContext: better_auth.MiddlewareInputContext) => Promise<{ session: { user: better_auth_plugins.UserWithRole; session: { id: string; createdAt: Date; updatedAt: Date; userId: string; expiresAt: Date; token: string; ipAddress?: string | null | undefined; userAgent?: string | null | undefined; }; }; }>)[]; query: zod.ZodObject<{ searchValue: zod.ZodOptional; searchField: zod.ZodOptional>; searchOperator: zod.ZodOptional>; limit: zod.ZodOptional>; offset: zod.ZodOptional>; sortBy: zod.ZodOptional; sortDirection: zod.ZodOptional>; filterField: zod.ZodOptional; filterValue: zod.ZodOptional, zod.ZodBoolean]>, zod.ZodArray]>, zod.ZodArray]>>; filterOperator: zod.ZodOptional>; }, zod_v4_core.$strip>; metadata: { openapi: { operationId: string; summary: string; description: string; responses: { 200: { description: string; content: { "application/json": { schema: { type: "object"; properties: { users: { type: string; items: { $ref: string; }; }; total: { type: string; }; limit: { type: string; }; offset: { type: string; }; }; required: string[]; }; }; }; }; }; }; }; }, { users: better_auth_plugins.UserWithRole[]; total: number; }>; listUserSessions: better_auth.StrictEndpoint<"/admin/list-user-sessions", { method: "POST"; use: ((inputContext: better_auth.MiddlewareInputContext) => Promise<{ session: { user: better_auth_plugins.UserWithRole; session: { id: string; createdAt: Date; updatedAt: Date; userId: string; expiresAt: Date; token: string; ipAddress?: string | null | undefined; userAgent?: string | null | undefined; }; }; }>)[]; body: zod.ZodObject<{ userId: zod.ZodCoercedString; }, zod_v4_core.$strip>; metadata: { openapi: { operationId: string; summary: string; description: string; responses: { 200: { description: string; content: { "application/json": { schema: { type: "object"; properties: { sessions: { type: string; items: { $ref: string; }; }; }; }; }; }; }; }; }; }; }, { sessions: better_auth_plugins.SessionWithImpersonatedBy[]; }>; unbanUser: better_auth.StrictEndpoint<"/admin/unban-user", { method: "POST"; body: zod.ZodObject<{ userId: zod.ZodCoercedString; }, zod_v4_core.$strip>; use: ((inputContext: better_auth.MiddlewareInputContext) => Promise<{ session: { user: better_auth_plugins.UserWithRole; session: { id: string; createdAt: Date; updatedAt: Date; userId: string; expiresAt: Date; token: string; ipAddress?: string | null | undefined; userAgent?: string | null | undefined; }; }; }>)[]; metadata: { openapi: { operationId: string; summary: string; description: string; responses: { 200: { description: string; content: { "application/json": { schema: { type: "object"; properties: { user: { $ref: string; }; }; }; }; }; }; }; }; }; }, { user: better_auth_plugins.UserWithRole; }>; banUser: better_auth.StrictEndpoint<"/admin/ban-user", { method: "POST"; body: zod.ZodObject<{ userId: zod.ZodCoercedString; banReason: zod.ZodOptional; banExpiresIn: zod.ZodOptional; }, zod_v4_core.$strip>; use: ((inputContext: better_auth.MiddlewareInputContext) => Promise<{ session: { user: better_auth_plugins.UserWithRole; session: { id: string; createdAt: Date; updatedAt: Date; userId: string; expiresAt: Date; token: string; ipAddress?: string | null | undefined; userAgent?: string | null | undefined; }; }; }>)[]; metadata: { openapi: { operationId: string; summary: string; description: string; responses: { 200: { description: string; content: { "application/json": { schema: { type: "object"; properties: { user: { $ref: string; }; }; }; }; }; }; }; }; }; }, { user: better_auth_plugins.UserWithRole; }>; impersonateUser: better_auth.StrictEndpoint<"/admin/impersonate-user", { method: "POST"; body: zod.ZodObject<{ userId: zod.ZodCoercedString; }, zod_v4_core.$strip>; use: ((inputContext: better_auth.MiddlewareInputContext) => Promise<{ session: { user: better_auth_plugins.UserWithRole; session: { id: string; createdAt: Date; updatedAt: Date; userId: string; expiresAt: Date; token: string; ipAddress?: string | null | undefined; userAgent?: string | null | undefined; }; }; }>)[]; metadata: { openapi: { operationId: string; summary: string; description: string; responses: { 200: { description: string; content: { "application/json": { schema: { type: "object"; properties: { session: { $ref: string; }; user: { $ref: string; }; }; }; }; }; }; }; }; }; }, { session: { id: string; createdAt: Date; updatedAt: Date; userId: string; expiresAt: Date; token: string; ipAddress?: string | null | undefined; userAgent?: string | null | undefined; }; user: better_auth_plugins.UserWithRole; }>; stopImpersonating: better_auth.StrictEndpoint<"/admin/stop-impersonating", { method: "POST"; requireHeaders: true; }, { session: { id: string; createdAt: Date; updatedAt: Date; userId: string; expiresAt: Date; token: string; ipAddress?: string | null | undefined; userAgent?: string | null | undefined; } & Record; user: { id: string; createdAt: Date; updatedAt: Date; email: string; emailVerified: boolean; name: string; image?: string | null | undefined; } & Record; }>; revokeUserSession: better_auth.StrictEndpoint<"/admin/revoke-user-session", { method: "POST"; body: zod.ZodObject<{ sessionToken: zod.ZodString; }, zod_v4_core.$strip>; use: ((inputContext: better_auth.MiddlewareInputContext) => Promise<{ session: { user: better_auth_plugins.UserWithRole; session: { id: string; createdAt: Date; updatedAt: Date; userId: string; expiresAt: Date; token: string; ipAddress?: string | null | undefined; userAgent?: string | null | undefined; }; }; }>)[]; metadata: { openapi: { operationId: string; summary: string; description: string; responses: { 200: { description: string; content: { "application/json": { schema: { type: "object"; properties: { success: { type: string; }; }; }; }; }; }; }; }; }; }, { success: boolean; }>; revokeUserSessions: better_auth.StrictEndpoint<"/admin/revoke-user-sessions", { method: "POST"; body: zod.ZodObject<{ userId: zod.ZodCoercedString; }, zod_v4_core.$strip>; use: ((inputContext: better_auth.MiddlewareInputContext) => Promise<{ session: { user: better_auth_plugins.UserWithRole; session: { id: string; createdAt: Date; updatedAt: Date; userId: string; expiresAt: Date; token: string; ipAddress?: string | null | undefined; userAgent?: string | null | undefined; }; }; }>)[]; metadata: { openapi: { operationId: string; summary: string; description: string; responses: { 200: { description: string; content: { "application/json": { schema: { type: "object"; properties: { success: { type: string; }; }; }; }; }; }; }; }; }; }, { success: boolean; }>; removeUser: better_auth.StrictEndpoint<"/admin/remove-user", { method: "POST"; body: zod.ZodObject<{ userId: zod.ZodCoercedString; }, zod_v4_core.$strip>; use: ((inputContext: better_auth.MiddlewareInputContext) => Promise<{ session: { user: better_auth_plugins.UserWithRole; session: { id: string; createdAt: Date; updatedAt: Date; userId: string; expiresAt: Date; token: string; ipAddress?: string | null | undefined; userAgent?: string | null | undefined; }; }; }>)[]; metadata: { openapi: { operationId: string; summary: string; description: string; responses: { 200: { description: string; content: { "application/json": { schema: { type: "object"; properties: { success: { type: string; }; }; }; }; }; }; }; }; }; }, { success: boolean; }>; setUserPassword: better_auth.StrictEndpoint<"/admin/set-user-password", { method: "POST"; body: zod.ZodObject<{ newPassword: zod.ZodString; userId: zod.ZodCoercedString; }, zod_v4_core.$strip>; use: ((inputContext: better_auth.MiddlewareInputContext) => Promise<{ session: { user: better_auth_plugins.UserWithRole; session: { id: string; createdAt: Date; updatedAt: Date; userId: string; expiresAt: Date; token: string; ipAddress?: string | null | undefined; userAgent?: string | null | undefined; }; }; }>)[]; metadata: { openapi: { operationId: string; summary: string; description: string; responses: { 200: { description: string; content: { "application/json": { schema: { type: "object"; properties: { status: { type: string; }; }; }; }; }; }; }; }; }; }, { status: boolean; }>; userHasPermission: better_auth.StrictEndpoint<"/admin/has-permission", { method: "POST"; body: zod.ZodIntersection>; role: zod.ZodOptional; }, zod_v4_core.$strip>, zod.ZodXor>; }, zod_v4_core.$strip>, zod.ZodObject<{ permissions: zod.ZodRecord>; }, zod_v4_core.$strip>]>>; metadata: { openapi: { description: string; requestBody: { content: { "application/json": { schema: { type: "object"; properties: { permissions: { type: string; description: string; }; }; required: string[]; }; }; }; }; responses: { "200": { description: string; content: { "application/json": { schema: { type: "object"; properties: { error: { type: string; }; success: { type: string; }; }; required: string[]; }; }; }; }; }; }; $Infer: { body: { permissions: { readonly user?: ("update" | "delete" | "create" | "list" | "set-role" | "ban" | "impersonate" | "impersonate-admins" | "set-password" | "set-email" | "get")[] | undefined; readonly session?: ("delete" | "list" | "revoke")[] | undefined; }; } & { userId?: string | undefined; role?: "admin" | "user" | undefined; }; }; }; }, { error: null; success: boolean; }>; }; $ERROR_CODES: { USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL: better_auth.RawError<"USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL">; FAILED_TO_CREATE_USER: better_auth.RawError<"FAILED_TO_CREATE_USER">; USER_ALREADY_EXISTS: better_auth.RawError<"USER_ALREADY_EXISTS">; YOU_CANNOT_BAN_YOURSELF: better_auth.RawError<"YOU_CANNOT_BAN_YOURSELF">; YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE">; YOU_ARE_NOT_ALLOWED_TO_CREATE_USERS: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_CREATE_USERS">; YOU_ARE_NOT_ALLOWED_TO_LIST_USERS: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_LIST_USERS">; YOU_ARE_NOT_ALLOWED_TO_LIST_USERS_SESSIONS: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_LIST_USERS_SESSIONS">; YOU_ARE_NOT_ALLOWED_TO_BAN_USERS: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_BAN_USERS">; YOU_ARE_NOT_ALLOWED_TO_IMPERSONATE_USERS: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_IMPERSONATE_USERS">; YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS">; YOU_ARE_NOT_ALLOWED_TO_DELETE_USERS: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_DELETE_USERS">; YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PASSWORD: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PASSWORD">; BANNED_USER: better_auth.RawError<"BANNED_USER">; YOU_ARE_NOT_ALLOWED_TO_GET_USER: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_GET_USER">; NO_DATA_TO_UPDATE: better_auth.RawError<"NO_DATA_TO_UPDATE">; YOU_ARE_NOT_ALLOWED_TO_UPDATE_USERS: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_UPDATE_USERS">; YOU_CANNOT_REMOVE_YOURSELF: better_auth.RawError<"YOU_CANNOT_REMOVE_YOURSELF">; YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE">; YOU_CANNOT_IMPERSONATE_ADMINS: better_auth.RawError<"YOU_CANNOT_IMPERSONATE_ADMINS">; INVALID_ROLE_TYPE: better_auth.RawError<"INVALID_ROLE_TYPE">; YOU_ARE_NOT_ALLOWED_TO_SET_USERS_EMAIL: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_SET_USERS_EMAIL">; PASSWORD_CANNOT_BE_UPDATED_VIA_UPDATE_USER: better_auth.RawError<"PASSWORD_CANNOT_BE_UPDATED_VIA_UPDATE_USER">; }; schema: { user: { fields: { role: { type: "string"; required: false; input: false; }; banned: { type: "boolean"; defaultValue: false; required: false; input: false; }; banReason: { type: "string"; required: false; input: false; }; banExpires: { type: "date"; required: false; input: false; }; }; }; session: { fields: { impersonatedBy: { type: "string"; required: false; input: false; }; }; }; }; options: NoInfer<{ ac: better_auth_plugins.AccessControl<{ readonly user: readonly ["create", "list", "set-role", "ban", "impersonate", "impersonate-admins", "delete", "set-password", "set-email", "get", "update"]; readonly session: readonly ["list", "revoke", "delete"]; }>; roles: { admin: better_auth_plugins.Role; user: better_auth_plugins.Role; }; }>; }; getActions: () => { admin: { checkRolePermission: (data: { permissions: { readonly user?: ("update" | "delete" | "create" | "list" | "set-role" | "ban" | "impersonate" | "impersonate-admins" | "set-password" | "set-email" | "get")[] | undefined; readonly session?: ("delete" | "list" | "revoke")[] | undefined; }; } & { role: R; }) => boolean; }; }; pathMethods: { "/admin/list-users": "GET"; "/admin/impersonate-user": "POST"; "/admin/stop-impersonating": "POST"; }; atomListeners: { matcher: (path: string) => path is "/admin/impersonate-user" | "/admin/stop-impersonating"; signal: "$sessionSignal"; }[]; $ERROR_CODES: { USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL: better_auth.RawError<"USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL">; FAILED_TO_CREATE_USER: better_auth.RawError<"FAILED_TO_CREATE_USER">; USER_ALREADY_EXISTS: better_auth.RawError<"USER_ALREADY_EXISTS">; YOU_CANNOT_BAN_YOURSELF: better_auth.RawError<"YOU_CANNOT_BAN_YOURSELF">; YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE">; YOU_ARE_NOT_ALLOWED_TO_CREATE_USERS: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_CREATE_USERS">; YOU_ARE_NOT_ALLOWED_TO_LIST_USERS: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_LIST_USERS">; YOU_ARE_NOT_ALLOWED_TO_LIST_USERS_SESSIONS: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_LIST_USERS_SESSIONS">; YOU_ARE_NOT_ALLOWED_TO_BAN_USERS: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_BAN_USERS">; YOU_ARE_NOT_ALLOWED_TO_IMPERSONATE_USERS: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_IMPERSONATE_USERS">; YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS">; YOU_ARE_NOT_ALLOWED_TO_DELETE_USERS: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_DELETE_USERS">; YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PASSWORD: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PASSWORD">; BANNED_USER: better_auth.RawError<"BANNED_USER">; YOU_ARE_NOT_ALLOWED_TO_GET_USER: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_GET_USER">; NO_DATA_TO_UPDATE: better_auth.RawError<"NO_DATA_TO_UPDATE">; YOU_ARE_NOT_ALLOWED_TO_UPDATE_USERS: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_UPDATE_USERS">; YOU_CANNOT_REMOVE_YOURSELF: better_auth.RawError<"YOU_CANNOT_REMOVE_YOURSELF">; YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE">; YOU_CANNOT_IMPERSONATE_ADMINS: better_auth.RawError<"YOU_CANNOT_IMPERSONATE_ADMINS">; INVALID_ROLE_TYPE: better_auth.RawError<"INVALID_ROLE_TYPE">; YOU_ARE_NOT_ALLOWED_TO_SET_USERS_EMAIL: better_auth.RawError<"YOU_ARE_NOT_ALLOWED_TO_SET_USERS_EMAIL">; PASSWORD_CANNOT_BE_UPDATED_VIA_UPDATE_USER: better_auth.RawError<"PASSWORD_CANNOT_BE_UPDATED_VIA_UPDATE_USER">; }; } | { id: "additional-fields-client"; version: string; $InferServerPlugin: { id: "additional-fields-client"; version: string; schema: { user: { fields: { lastActiveAt: { type: "date"; required: false; defaultValue: null; }; displayName: { type: "string"; input: true; required: false; defaultValue: null; }; title: { type: "string"; input: true; required: false; defaultValue: null; }; pronouns: { type: "string"; input: true; required: false; defaultValue: null; }; preferredLanguage: { type: "string"; input: true; required: true; defaultValue: string; }; }; }; session: { fields: {}; }; }; }; } | { id: "applications"; getActions: ($fetch: better_auth_client.BetterFetch) => { applications: { getApplicationAuthContext: (applicationId: string) => Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: ApplicationAuthContextResponse; error: null; }>; listCandidateOrganizations: (applicationId: string, options?: ListCandidateOrganizationsOptions) => Promise<{ data: ListCandidateOrganizationsResponse; error?: unknown; }>; startAuthorizationFlow: (applicationId: string, redirectUri: string, codeChallenge: string, organizationId: string) => Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: StartAuthorizationFlowResponse; error: null; }>; startDeviceAuthorizationFlow: (requesterApplicationId: string, targetApplicationId?: string) => Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: DeviceAuthorizationResponse; error: null; }>; getDeviceAuthorizationContext: (userCode: string) => Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: DeviceAuthorizationContextResponse; error: null; }>; approveDeviceAuthorizationFlow: (userCode: string, organizationId: string) => Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: DeviceAuthorizationActionResponse; error: null; }>; denyDeviceAuthorizationFlow: (userCode: string) => Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: DeviceAuthorizationActionResponse; error: null; }>; exchangeDeviceCodeForTokens: (deviceCode: string) => Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: CompleteAuthorizationFlowResponse; error: null; }>; exchangeClientCredentialsForToken: (credentials: ClientCredentialsGrant) => Promise<{ data: ClientCredentialsTokenResponse; error: null; } | { data: null; error: { message?: string | undefined; status: number; statusText: string; }; }>; completeAuthorizationFlow: (code: string, codeVerifier: string) => Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: CompleteAuthorizationFlowResponse; error: null; }>; refreshAccessToken: (refreshToken: string) => Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: CompleteAuthorizationFlowResponse; error: null; }>; whoAmI: (accessToken: string, options?: WhoAmIOptions) => Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: WhoAmIResponse; error: null; }>; switchOrganization: (organizationId: string, accessToken: string) => Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: CompleteAuthorizationFlowResponse; error: null; }>; logout: (refreshToken: string) => Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: void; error: null; }>; listApplicationRoles: () => Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: ApplicationRole[]; error: null; }>; }; }; } | { id: "session-assurance"; getActions: ($fetch: better_auth_client.BetterFetch) => { sessionAssurance: { getSessionAssurance: () => Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: unknown; error: null; }>; stepUpWithPassword: (body: { password: string; }) => Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: unknown; error: null; }>; sendOtp: () => Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: unknown; error: null; }>; verifyOtp: (body: { otp: string; }) => Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: unknown; error: null; }>; beginOAuthStepUp: (body: { provider: OAuthStepUpProvider; returnUrl?: string; }) => Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: unknown; error: null; }>; completeOAuthStepUp: (body: { stepUpToken: string; }) => Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: unknown; error: null; }>; }; }; } | { id: "login-methods"; getActions: ($fetch: better_auth_client.BetterFetch) => { loginMethods: { get: () => Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: LoginMethodsResponse; error: null; }>; }; }; } | { id: "email-otp"; version: string; $InferServerPlugin: ReturnType<(options: better_auth_plugins.EmailOTPOptions) => { id: "email-otp"; version: string; init(ctx: better_auth.AuthContext): { options: { emailVerification: { sendVerificationEmail(data: { user: better_auth.User; url: string; token: string; }, request: Request | undefined): Promise; }; }; } | undefined; endpoints: { sendVerificationOTP: better_auth.StrictEndpoint<"/email-otp/send-verification-otp", { method: "POST"; use: ((inputContext: better_auth.MiddlewareInputContext) => Promise)[]; body: zod.ZodObject<{ email: zod.ZodString; type: zod.ZodEnum<{ "sign-in": "sign-in"; "change-email": "change-email"; "email-verification": "email-verification"; "forget-password": "forget-password"; }>; }, zod_v4_core.$strip>; metadata: { openapi: { operationId: string; description: string; responses: { 200: { description: string; content: { "application/json": { schema: { type: "object"; properties: { success: { type: string; }; }; }; }; }; }; }; }; }; }, { success: boolean; }>; createVerificationOTP: better_auth.StrictEndpoint; }, zod_v4_core.$strip>; metadata: { openapi: { operationId: string; description: string; responses: { 200: { description: string; content: { "application/json": { schema: { type: "string"; }; }; }; }; }; }; }; }, string>; getVerificationOTP: better_auth.StrictEndpoint; }, zod_v4_core.$strip>; metadata: { openapi: { operationId: string; description: string; responses: { "200": { description: string; content: { "application/json": { schema: { type: "object"; properties: { otp: { type: string; nullable: boolean; description: string; }; }; required: string[]; }; }; }; }; }; }; }; }, { otp: null; } | { otp: string; }>; checkVerificationOTP: better_auth.StrictEndpoint<"/email-otp/check-verification-otp", { method: "POST"; body: zod.ZodObject<{ email: zod.ZodString; type: zod.ZodEnum<{ "sign-in": "sign-in"; "change-email": "change-email"; "email-verification": "email-verification"; "forget-password": "forget-password"; }>; otp: zod.ZodString; }, zod_v4_core.$strip>; metadata: { openapi: { operationId: string; description: string; responses: { 200: { description: string; content: { "application/json": { schema: { type: "object"; properties: { success: { type: string; }; }; }; }; }; }; }; }; }; }, { success: boolean; }>; verifyEmailOTP: better_auth.StrictEndpoint<"/email-otp/verify-email", { method: "POST"; body: zod.ZodObject<{ email: zod.ZodString; otp: zod.ZodString; }, zod_v4_core.$strip>; metadata: { openapi: { description: string; responses: { 200: { description: string; content: { "application/json": { schema: { type: "object"; properties: { status: { type: string; description: string; enum: boolean[]; }; token: { type: string; nullable: boolean; description: string; }; user: { $ref: string; }; }; required: string[]; }; }; }; }; }; }; }; }, { status: boolean; token: string; user: { id: string; createdAt: Date; updatedAt: Date; email: string; emailVerified: boolean; name: string; image?: string | null | undefined; } & Record; } | { status: boolean; token: null; user: { id: string; createdAt: Date; updatedAt: Date; email: string; emailVerified: boolean; name: string; image?: string | null | undefined; } & Record; }>; signInEmailOTP: better_auth.StrictEndpoint<"/sign-in/email-otp", { method: "POST"; body: zod.ZodIntersection; image: zod.ZodOptional; }, zod_v4_core.$strip>, zod.ZodRecord>; metadata: { openapi: { operationId: string; description: string; responses: { 200: { description: string; content: { "application/json": { schema: { type: "object"; properties: { token: { type: string; description: string; }; user: { $ref: string; }; }; required: string[]; }; }; }; }; }; }; }; }, { token: string; user: { id: string; createdAt: Date; updatedAt: Date; email: string; emailVerified: boolean; name: string; image?: string | null | undefined; }; }>; requestPasswordResetEmailOTP: better_auth.StrictEndpoint<"/email-otp/request-password-reset", { method: "POST"; body: zod.ZodObject<{ email: zod.ZodString; }, zod_v4_core.$strip>; metadata: { openapi: { operationId: string; description: string; responses: { 200: { description: string; content: { "application/json": { schema: { type: "object"; properties: { success: { type: string; description: string; }; }; }; }; }; }; }; }; }; }, { success: boolean; }>; forgetPasswordEmailOTP: better_auth.StrictEndpoint<"/forget-password/email-otp", { method: "POST"; body: zod.ZodObject<{ email: zod.ZodString; }, zod_v4_core.$strip>; metadata: { openapi: { operationId: string; description: string; responses: { 200: { description: string; content: { "application/json": { schema: { type: "object"; properties: { success: { type: string; description: string; }; }; }; }; }; }; }; }; }; }, { success: boolean; }>; resetPasswordEmailOTP: better_auth.StrictEndpoint<"/email-otp/reset-password", { method: "POST"; body: zod.ZodObject<{ email: zod.ZodString; otp: zod.ZodString; password: zod.ZodString; }, zod_v4_core.$strip>; metadata: { openapi: { operationId: string; description: string; responses: { 200: { description: string; content: { "application/json": { schema: { type: "object"; properties: { success: { type: string; }; }; }; }; }; }; }; }; }; }, { success: boolean; }>; requestEmailChangeEmailOTP: better_auth.StrictEndpoint<"/email-otp/request-email-change", { method: "POST"; body: zod.ZodObject<{ newEmail: zod.ZodString; otp: zod.ZodOptional; }, zod_v4_core.$strip>; use: ((inputContext: better_auth.MiddlewareInputContext) => Promise<{ session: { session: Record & { id: string; createdAt: Date; updatedAt: Date; userId: string; expiresAt: Date; token: string; ipAddress?: string | null | undefined; userAgent?: string | null | undefined; }; user: Record & { id: string; createdAt: Date; updatedAt: Date; email: string; emailVerified: boolean; name: string; image?: string | null | undefined; }; }; }>)[]; metadata: { openapi: { operationId: string; description: string; responses: { 200: { description: string; content: { "application/json": { schema: { type: "object"; properties: { success: { type: string; }; }; }; }; }; }; }; }; }; }, { success: boolean; }>; changeEmailEmailOTP: better_auth.StrictEndpoint<"/email-otp/change-email", { method: "POST"; body: zod.ZodObject<{ newEmail: zod.ZodString; otp: zod.ZodString; }, zod_v4_core.$strip>; use: ((inputContext: better_auth.MiddlewareInputContext) => Promise<{ session: { session: Record & { id: string; createdAt: Date; updatedAt: Date; userId: string; expiresAt: Date; token: string; ipAddress?: string | null | undefined; userAgent?: string | null | undefined; }; user: Record & { id: string; createdAt: Date; updatedAt: Date; email: string; emailVerified: boolean; name: string; image?: string | null | undefined; }; }; }>)[]; metadata: { openapi: { operationId: string; description: string; responses: { 200: { description: string; content: { "application/json": { schema: { type: "object"; properties: { success: { type: string; }; }; }; }; }; }; }; }; }; }, { success: boolean; }>; }; hooks: { after: { matcher(context: better_auth.HookEndpointContext): boolean; handler: (inputContext: better_auth.MiddlewareInputContext) => Promise; }[]; }; rateLimit: ({ pathMatcher(path: string): path is "/email-otp/send-verification-otp"; window: number; max: number; } | { pathMatcher(path: string): path is "/email-otp/check-verification-otp"; window: number; max: number; } | { pathMatcher(path: string): path is "/email-otp/verify-email"; window: number; max: number; } | { pathMatcher(path: string): path is "/sign-in/email-otp"; window: number; max: number; } | { pathMatcher(path: string): path is "/email-otp/request-password-reset"; window: number; max: number; } | { pathMatcher(path: string): path is "/email-otp/reset-password"; window: number; max: number; } | { pathMatcher(path: string): path is "/forget-password/email-otp"; window: number; max: number; } | { pathMatcher(path: string): path is "/email-otp/request-email-change"; window: number; max: number; } | { pathMatcher(path: string): path is "/email-otp/change-email"; window: number; max: number; })[]; options: better_auth_plugins.EmailOTPOptions; $ERROR_CODES: { OTP_EXPIRED: better_auth.RawError<"OTP_EXPIRED">; INVALID_OTP: better_auth.RawError<"INVALID_OTP">; TOO_MANY_ATTEMPTS: better_auth.RawError<"TOO_MANY_ATTEMPTS">; }; }>; atomListeners: { matcher: (path: string) => path is "/email-otp/verify-email" | "/sign-in/email-otp" | "/email-otp/request-email-change"; signal: "$sessionSignal"; }[]; $ERROR_CODES: { OTP_EXPIRED: better_auth.RawError<"OTP_EXPIRED">; INVALID_OTP: better_auth.RawError<"INVALID_OTP">; TOO_MANY_ATTEMPTS: better_auth.RawError<"TOO_MANY_ATTEMPTS">; }; })[]; fetchOptions: { credentials: "include"; headers: { 'X-User-Agent': string; }; throw: true; cache?: RequestCache | undefined; integrity?: string | undefined; keepalive?: boolean | undefined; method?: string | undefined; mode?: RequestMode | undefined; priority?: RequestPriority | undefined; redirect?: RequestRedirect | undefined; referrer?: string | undefined; referrerPolicy?: ReferrerPolicy | undefined; signal?: (AbortSignal | null) | undefined; window?: null | undefined; onRequest?: (>(context: better_auth_client.RequestContext) => Promise | better_auth_client.RequestContext | void) | undefined; onResponse?: ((context: better_auth_client.ResponseContext) => Promise | Response | better_auth_client.ResponseContext | void) | undefined; onSuccess?: ((context: better_auth_client.SuccessContext) => Promise | void) | undefined; onError?: ((context: better_auth_client.ErrorContext) => Promise | void) | undefined; onRetry?: ((response: better_auth_client.ResponseContext) => Promise | void) | undefined; hookOptions?: { cloneResponse?: boolean; } | undefined; timeout?: number | undefined; customFetchImpl?: better_auth_client.FetchEsque | undefined; plugins?: better_auth_client.BetterFetchPlugin[] | undefined; baseURL?: string | undefined; auth?: ({ type: "Bearer"; token: string | Promise | (() => string | Promise | undefined) | undefined; } | { type: "Basic"; username: string | (() => string | undefined) | undefined; password: string | (() => string | undefined) | undefined; } | { type: "Custom"; prefix: string | (() => string | undefined) | undefined; value: string | (() => string | undefined) | undefined; }) | undefined; body?: any; query?: any; params?: any; duplex?: "full" | "half" | undefined; jsonParser?: ((text: string) => Promise | any) | undefined; retry?: better_auth_client.RetryOptions | undefined; retryAttempt?: number | undefined; output?: (better_auth_client.StandardSchemaV1 | typeof Blob | typeof File) | undefined; errorSchema?: better_auth_client.StandardSchemaV1 | undefined; disableValidation?: boolean | undefined; }; }>; /** * The configured Better Auth client type with all plugins applied. * * @internal */ type APIClient = ReturnType; /** An authenticated user. */ type User = APIClient['$Infer']['Session']['user']; /** * A user session record. * * Breaking change in 1.12: this was previously the full `{ user, session }` * response object, even though runtime session state only ever held the * inner record. Use {@link SessionData} for the full response shape. */ type Session = APIClient['$Infer']['Session']['session']; /** A full session response containing the user and the session record. */ type SessionData = APIClient['$Infer']['Session']; /** An organization the user belongs to. */ type BaseOrganization = Strict; /** A team within an organization. */ type Team = Strict; /** A pending invitation to join an organization. */ type Invitation = Strict; /** A member of an organization with role information. */ type Member = Strict; /** * Custom settings that can be applied to an organization. */ type BillingMode = 'credits' | 'plan'; type OrganizationSettings = { /** Whether file storage is disabled for this organization. */ disableStorage?: boolean; /** Number of hours to retain data before automatic cleanup. */ dataRetentionHours?: number; /** How the organization is billed for usage. */ billing?: { mode: BillingMode; cvp?: number; limits?: { enabled: boolean; soft_usd?: number; hard_usd?: number; soft_credits?: number; hard_credits?: number; period: 'monthly'; notify_emails?: string[]; }; }; }; /** * An organization with optional custom settings. */ type ExtendedOrganization = BaseOrganization & { settings?: OrganizationSettings; }; /** * A member of a {@link FullOrganization}. */ type FullOrganizationMember = Member & { /** The member's role in the session's application. Only set for application sessions. */ applicationRole?: string | null; }; /** * A complete organization object including its members, invitations, and teams. */ type FullOrganization = ExtendedOrganization & { /** With an application session, only members with access to the application. */ members: FullOrganizationMember[]; invitations: Invitation[]; teams: Team[]; }; /** * An organization as returned by the "who am I" endpoint, where related * collections (`members`, `teams`, `invitations`) are optional and only * populated when explicitly requested via the `include` query parameter. */ type WhoAmIOrganization = Omit & { members?: Member[]; invitations?: Invitation[]; teams?: Team[]; }; /** * A record linking a user to a team. */ type TeamMember = { /** Unique identifier for this team membership. */ id: string; /** The team this membership belongs to. */ teamId: string; /** The user who is a member of the team. */ userId: string; /** When the user was added to the team. */ createdAt: Date; }; /** * Options accepted when listing users as a global admin. */ type ListAdminUsersOptions = { /** Maximum number of users to return. Defaults to 50. */ limit?: number; /** Number of users to skip. Defaults to 0. */ offset?: number; /** Column used to order the listing. Defaults to creation date. */ sortBy?: 'createdAt' | 'name'; /** Order direction. Defaults to descending. */ sortDirection?: 'asc' | 'desc'; /** Free-text search matched against user name, email, and ID. */ query?: string; /** * Number of organization previews to include per user (max 10). * When greater than 0, each row also includes the total organization count. * Defaults to 0. */ organizationsPreview?: number; /** * When true, invitation-only rows for people invited but not yet registered * are merged into the listing, grouped by email. Defaults to false. */ includeInvitations?: boolean; /** * Restricts the listing to users with an active membership in this * organization, and to invitations sent by it. Ignored for an organization * admin, whose listing is always pinned to their own organization. */ organizationId?: string; /** Restricts the listing to people with access to this application. Requires organizationId when listing users. */ applicationId?: string; }; /** * Organization preview returned alongside each admin user row. */ type AdminUserOrganization = { id: string; name: string; logo: string | null; createdAt: string; }; /** * Options accepted when listing all organizations as a global admin. */ type ListAdminOrganizationsOptions = { /** Maximum number of organizations to return. Defaults to 50. */ limit?: number; /** Number of organizations to skip. Defaults to 0. */ offset?: number; /** Column used to order the listing. Defaults to creation date. */ sortBy?: 'createdAt' | 'title'; /** Order direction. Defaults to descending. */ sortDirection?: 'asc' | 'desc'; /** Free-text search matched against organization name, slug, and ID. */ query?: string; /** * Number of member previews to include per organization (max 10). * When greater than 0, each row also includes the total member count. * Defaults to 0 (no members or member count returned). */ membersPreview?: number; /** * Number of application previews to include per organization (max 10). * When greater than 0, each row also includes the total application count. * Defaults to 0 (no applications or application count returned). */ applicationsPreview?: number; }; /** * Options accepted when listing applications as a global admin. */ type ListAdminApplicationsOptions = { /** Maximum number of applications to return. Defaults to 50. */ limit?: number; /** * Number of member previews to include per application (max 10). * When greater than 0, each row also includes the total member count. * Defaults to 0 (no members or member count returned). */ membersPreview?: number; /** Number of applications to skip. Defaults to 0. */ offset?: number; /** Column used to order the listing. Defaults to creation date. */ orderBy?: 'createdAt' | 'updatedAt' | 'name'; /** Order direction. Defaults to descending. */ orderDirection?: 'asc' | 'desc'; /** When provided, only applications enabled for this organization are returned. */ organizationId?: string; /** Free-text search matched against application name, description, and UUIDs. */ search?: string; }; /** * Options accepted when creating an application as a global admin. */ type CreateAdminApplicationOptions = { /** Display name of the application. */ name: string; /** Human-readable application description. */ description?: string; /** Logo or icon URL. */ imageUrl?: string | null; /** Allowed OAuth redirect URIs for this application. */ redirectUris: string[]; /** Application home URL. */ homeUrl?: string | null; /** Custom application authentication settings. */ config?: ApplicationConfig | null; /** Organization or global entitlements to create for this application. */ entitlements?: CreateAdminApplicationEntitlementOptions[]; }; /** * Options accepted when creating an organization or global entitlement for an application. */ type CreateAdminApplicationEntitlementOptions = { /** Organization ID for type `organization`; passing null creates an entitlement with type `global`. */ organizationId: string | null; }; /** * Options accepted when creating a client secret for an application. */ type CreateAdminApplicationSecretOptions = { /** Optional display name for the secret. */ name?: string; }; /** * Options accepted when disabling an application. */ type DisableAdminApplicationOptions = { /** Plain-text notice shown to users who try to sign in through the application. Blank or `null` clears it. */ deprecationNotice?: string | null; }; /** * Client secret metadata returned by application management endpoints. */ type AdminApplicationSecret = { id: string; applicationId: string; name: string | null; /** First characters of the secret, kept for later identification. */ start: string; createdAt: string; lastUsedAt: string | null; }; /** * Service-account identity backing client-credentials tokens for an application. */ type AdminApplicationIdentity = { id: string; email: string; }; /** * Newly-created client secret. The plaintext secret is returned only once. */ type CreatedAdminApplicationSecret = AdminApplicationSecret & { secret: string; serviceAccountUser: AdminApplicationIdentity; }; /** * Options accepted when fetching a single organization as a global admin. */ type GetAdminOrganizationOptions = { /** ID of the organization to fetch. */ organizationId: string; /** Column the listing adjacency is computed against. Defaults to creation date. */ sortBy?: 'createdAt' | 'title'; /** Order direction the listing adjacency is computed against. Defaults to descending. */ sortDirection?: 'asc' | 'desc'; /** * When true, the organization includes adjacent IDs in the listing * defined by the ordering options. */ includeAdjacent?: boolean; }; /** * Options accepted when listing members for a single organization as a global admin. */ type ListAdminOrganizationMembersOptions = { /** ID of the organization whose members should be listed. */ organizationId: string; /** Maximum number of members to return. Defaults to 50. */ limit?: number; /** Number of members to skip. Defaults to 0. */ offset?: number; /** Case-insensitive name/email match; also matches an exact user ID when a UUID. */ query?: string; /** Organization role filter, e.g. 'org:admin'. */ role?: string; /** Restricts the listing to members belonging to any of these teams. */ teamIds?: string[]; /** When true, pending invitation rows for the organization are merged into the listing. */ includeInvitations?: boolean; /** When true, each row includes the member's teams and accessible applications. */ includeAccess?: boolean; /** Column to sort by: the join date or the member name. Defaults to 'createdAt'. */ sortBy?: 'createdAt' | 'name'; /** Sort direction for the listing. Defaults to 'desc'. */ sortDirection?: 'asc' | 'desc'; /** Restricts the listing to people with access to this application. */ applicationId?: string; }; /** * Options accepted when listing teams for a single organization as a global admin. */ type ListAdminOrganizationTeamsOptions = { /** ID of the organization whose teams should be listed. */ organizationId: string; /** Maximum number of teams to return. Defaults to 50. */ limit?: number; /** Number of teams to skip. Defaults to 0. */ offset?: number; /** Free-text search matched against team name and ID. */ query?: string; /** Column used to order the listing. Defaults to creation date. */ sortBy?: 'createdAt' | 'name'; /** Order direction. Defaults to descending. */ sortDirection?: 'asc' | 'desc'; }; /** * Options accepted when creating a team for a single organization as a global admin. */ type CreateAdminOrganizationTeamOptions = { /** ID of the organization that should own the team. */ organizationId: string; /** Display name of the team. */ name: string; /** User IDs of organization members to add to the team. */ memberIds?: string[]; }; /** * Options accepted when updating an organization team as a global admin. */ type UpdateAdminOrganizationTeamOptions = { /** ID of the organization that owns the team. */ organizationId: string; /** ID of the team to update. */ teamId: string; /** New display name of the team. */ name: string; /** Complete replacement set of active organization member user IDs. */ memberIds?: string[]; }; /** * Options accepted when deleting an organization team as a global admin. */ type DeleteAdminOrganizationTeamOptions = { /** ID of the organization that owns the team. */ organizationId: string; /** ID of the team to delete. */ teamId: string; }; /** * Options accepted when updating an organization member's role as a global admin. */ type UpdateAdminMemberRoleOptions = { /** ID of the membership to update. */ memberId: string; /** New organization role for the membership. */ role: string; }; /** * Options accepted when removing an organization member as a global admin. */ type RemoveAdminMemberOptions = { /** ID of the membership to remove. */ memberId: string; }; /** * Options accepted when setting a user's effective application role as a global admin. */ type SetAdminUserApplicationRoleOptions = { /** ID of the user whose application role is being set. */ userId: string; /** Organization the entitlement belongs to. */ organizationId: string; /** Application the entitlement grants access to. */ applicationId: string; /** Non-null grants access with the role, null denies access (leave application). Ignored when clear is true. */ role?: string | null; /** When true, removes the user's override rule so broader organization rules apply again. */ clear?: boolean; }; /** * Options accepted when assigning or clearing a user's team as a global admin. */ type SetAdminUserTeamOptions = { /** ID of the user whose team membership is being set. */ userId: string; /** Organization the teams belong to. */ organizationId: string; /** Desired teams within the organization; an empty array clears the user's team memberships. */ teamIds: string[]; }; /** * Options accepted when setting a user's password as a global admin. */ type SetAdminUserPasswordOptions = { /** ID of the user whose password is being set. */ userId: string; /** New password. Replaces the current one, or creates a password login when the user has none. */ newPassword: string; }; /** * Team row returned by the admin organization team listing endpoint. */ type AdminOrganizationTeam = { id: string; name: string; }; /** * Organization membership row returned by the admin member mutation endpoints. */ type AdminMember = { id: string; organizationId: string; userId: string; role: string; createdAt: string; deletedAt: string | null; }; /** * Options accepted when creating an organization as a global admin. */ type CreateAdminOrganizationOptions = { /** Optional organization ID. Generated by the API when omitted. */ id?: string; /** Display name of the organization. */ name: string; /** URL-friendly identifier. Generated from the name when omitted. */ slug?: string; /** Logo URL. */ logo?: string; /** Opaque metadata stored with the organization. */ metadata?: string; /** Custom organization settings. */ settings?: OrganizationSettings; }; /** * Options accepted when updating an organization as a global admin. */ type UpdateAdminOrganizationOptions = { /** ID of the organization to update. */ organizationId: string; /** Display name of the organization. */ name?: string; /** URL-friendly identifier. */ slug?: string; /** Logo URL. */ logo?: string; /** Opaque metadata stored with the organization. */ metadata?: string; /** Custom organization settings. Replaces the stored settings object. */ settings?: OrganizationSettings; }; /** * Invitation attached to an invitation row in the admin user listing. */ type AdminUserInvitation = { id: string; organizationId: string; organizationName: string; organizationLogo: string | null; applicationId: string | null; role: string | null; teamIds: string[]; status: 'pending' | 'expired'; expiresAt: string; createdAt: string; }; /** * User row returned by the admin user listing endpoint. */ type AdminUser = { id: string; name: string; email: string; emailVerified: boolean; image: string | null; createdAt: string | Date; updatedAt: string | Date; role: string | null; banned: boolean | null; banReason: string | null; banExpires: string | Date | null; lastActiveAt?: string | Date | null; twoFactorEnabled?: boolean | null; /** Discriminates registered users from invitation-only rows. */ type: 'user' | 'invitation'; /** Aggregate invitation status. Present on invitation rows. */ invitationStatus?: 'pending' | 'expired'; /** Pending invitations grouped on this row. Present on invitation rows. */ invitations?: AdminUserInvitation[]; /** Total number of organizations the user belongs to. Present when requested via organizationsPreview. */ organizationCount?: number; /** Preview of the first organizations the user belongs to. Present when requested via organizationsPreview. */ organizations?: AdminUserOrganization[]; /** App role. Present when the listing is scoped to an application; null on invitation rows. */ applicationRole?: string | null; }; /** * Paginated admin user listing response. */ type ListAdminUsersResult = { users: AdminUser[]; total: number; limit: number; offset: number; }; /** * Member preview returned alongside each admin organization row. */ type AdminOrganizationMember = { id: string; name: string; email: string; image: string | null; }; /** * Team row attached to an organization member listing row. */ type AdminOrganizationMemberTeam = { id: string; name: string; }; /** * Application row attached to an organization member listing row. */ type AdminOrganizationMemberApplication = { id: string; name: string; imageUrl: string | null; }; /** * Row returned by the admin organization member listing endpoint. Members and * pending invitations share this shape, discriminated by type. */ type AdminOrganizationMemberRecord = { type: 'member' | 'invitation'; id: string; memberId: string | null; organizationId: string; name: string | null; email: string; image: string | null; role: string | null; lastActiveAt: string | null; createdAt: string; invitationId?: string; invitationStatus?: 'pending' | 'expired'; expiresAt?: string; teams?: AdminOrganizationMemberTeam[]; applications?: AdminOrganizationMemberApplication[]; /** App role. Present when the listing is scoped to an application; null on invitation rows. */ applicationRole?: string | null; }; /** * Paginated organization member listing response. */ type ListAdminOrganizationMembersResult = { members: AdminOrganizationMemberRecord[]; total: number; limit: number; offset: number; }; /** * Full team row returned by the admin organization team listing endpoint. */ type AdminOrganizationTeamRecord = { id: string; name: string; organizationId: string; createdAt: string; updatedAt: string; memberCount: number; }; /** * Paginated organization team listing response. */ type ListAdminOrganizationTeamsResult = { teams: AdminOrganizationTeamRecord[]; total: number; limit: number; offset: number; }; /** * Application row in an admin user access report. */ type AdminUserAccessApplication = { id: string; name: string; imageUrl: string | null; /** Effective role from entitlement rule evaluation. Null when the first matching rule denies access or no rule matches. */ role: string | null; /** User-facing name from the application role catalog. Null when no role matches. */ roleDisplayName: string | null; }; /** * Team row in an admin user access report. */ type AdminUserAccessTeam = { id: string; name: string; }; /** * Organization row in an admin user access report. */ type AdminUserAccessOrganization = { id: string; name: string; logo: string | null; memberId: string; role: string; teams: AdminUserAccessTeam[]; applications: AdminUserAccessApplication[]; }; /** * Access report returned by the admin user access endpoint. */ type AdminUserAccess = { organizations: AdminUserAccessOrganization[]; }; /** * Organization row embedded in an admin application entitlement. */ type AdminApplicationOrganization = { id: string; title: string; slug: string | null; avatarUrl: string | null; createdAt: string; metadata: string | null; settings: OrganizationSettings | null; }; /** * Entitlement returned alongside each admin application row. */ type AdminApplicationEntitlement = { id: string; /** Access scope. Defaults to `organization` when omitted; the API returns the resolved type. Type `global` applies across organizations. */ entitlementType?: 'organization' | 'global'; applicationId: string; /** Required for type `organization` and constrained to null for type `global`. */ organizationId: string | null; enabled: boolean; createdAt: string; updatedAt: string; createdBy: string; updatedBy: string; organization: AdminApplicationOrganization | null; }; /** * Entitlement record returned by entitlement mutation endpoints. */ type AdminApplicationEntitlementRecord = Omit; /** Application-scoped role definition used by entitlement rules. */ type AdminApplicationRole = { applicationId: string; name: string; displayName: string; description: string; /** Roles of the same application this role may grant, change, revoke and invite. */ manageableRoles: string[]; }; /** * Options accepted when creating an application role. Omitting `manageableRoles` * creates the role with none, and on update keeps the stored list. */ type CreateAdminApplicationRoleOptions = Omit & { manageableRoles?: string[]; }; /** Options accepted when updating an application role. */ type UpdateAdminApplicationRoleOptions = CreateAdminApplicationRoleOptions; /** Kind of matcher an entitlement rule applies. */ type AdminEntitlementRuleType = 'email_equals' | 'email_domain_equals' | 'organization_member' | 'user_id_equals' | 'organization_role_equals' | 'global'; /** * A single access rule on an entitlement. Rules are evaluated in `position` * order with the global catch-all always last, first match wins. A non-null `role` grants access with that role; a * null `role` denies access. */ type AdminEntitlementRule = { type: AdminEntitlementRuleType; value: string; role: string | null; position: number; }; /** An entitlement together with its ordered access rules. */ type AdminEntitlementWithRules = AdminApplicationEntitlementRecord & { rules: AdminEntitlementRule[]; }; /** Options accepted when enabling or disabling an entitlement. */ type UpdateAdminEntitlementOptions = { enabled: boolean; }; /** Options accepted when replacing all rules on an entitlement. */ type SetAdminEntitlementRulesOptions = { rules: AdminEntitlementRule[]; }; /** * Member preview returned alongside each admin application row. */ type AdminApplicationMember = { id: string; name: string; email: string; image: string | null; }; /** * Options accepted when listing the users with access to an application. */ type ListAdminApplicationMembersOptions = { /** ID of the application whose members should be listed. */ applicationId: string; /** Restricts the listing to users with access through this organization. */ organizationId?: string; /** Case-insensitive name or email match. */ query?: string; /** Maximum number of users to return. Defaults to 50. */ limit?: number; /** Number of users to skip. Defaults to 0. */ offset?: number; }; /** * Organization through which a user can access an application, with the role * the first matching entitlement rule grants them there. */ type AdminApplicationMemberOrganization = { id: string; name: string; role: string; /** User-facing name from the application role catalog. Null when the role is not in the catalog. */ roleDisplayName: string | null; }; /** * User row returned by the admin application member listing endpoint. */ type AdminApplicationMemberRecord = AdminApplicationMember & { organizations: AdminApplicationMemberOrganization[]; }; /** * Paginated application member listing response. */ type ListAdminApplicationMembersResult = { members: AdminApplicationMemberRecord[]; total: number; limit: number; offset: number; }; /** * Application row returned by the admin application listing endpoint. */ type AdminApplication = { id: string; name: string; description: string | null; imageUrl: string | null; redirectUris: string[]; homeUrl: string | null; config: ApplicationConfig | null; serviceAccountUserId: string | null; serviceAccountUser?: AdminApplicationIdentity | null; /** When the application was disabled, or `null` while it is enabled. A disabled application refuses every sign-in. */ disabledAt: string | null; /** ID of the admin who disabled the application, or `null`. */ disabledBy: string | null; /** Plain-text notice shown to users who try to sign in through the disabled application. */ deprecationNotice: string | null; createdBy: string; updatedBy: string; createdAt: string; updatedAt: string; entitlements: AdminApplicationEntitlement[]; /** Total number of users with application access. Present when requested via membersPreview. */ memberCount?: number; /** Preview of the first users with application access. Present when requested via membersPreview. */ members?: AdminApplicationMember[]; }; /** * Application record returned by create/update-style management endpoints. */ type AdminApplicationRecord = Omit; /** * Admin application listing response. */ type ListAdminApplicationsResult = AdminApplication[]; /** * Application preview returned alongside each admin organization row. */ type AdminOrganizationApplication = { id: string; name: string; imageUrl: string | null; createdAt: string; }; /** * Organization row returned by the admin organization listing endpoint. */ type AdminOrganization = { id: string; name: string; slug: string; logo: string | null; createdAt: string; metadata: string | null; settings: OrganizationSettings | null; /** Total number of active members. Present when requested via membersPreview. */ memberCount?: number; /** Preview of the first members. Present when requested via membersPreview. */ members?: AdminOrganizationMember[]; /** Total number of enabled applications. Present when requested via applicationsPreview. */ applicationCount?: number; /** Preview of the first enabled applications. Present when requested via applicationsPreview. */ applications?: AdminOrganizationApplication[]; /** * Adjacent organization IDs in the listing defined by the ordering options. * Present when requested via includeAdjacent. */ adjacent?: { previous: string | null; next: string | null; /** 1-based position in the listing. */ index: number; total: number; }; }; /** * Paginated admin organization listing response. */ type ListAdminOrganizationsResult = { organizations: AdminOrganization[]; total: number; limit: number; offset: number; }; /** * Minimal organization row returned by the admin organization summary endpoint. * Carries only the identity and branding the vault pages need to render a * workspace. */ type AdminOrganizationSummary = { id: string; name: string; logo: string | null; }; /** * Options accepted when fetching organization summaries as a global admin. */ type GetAdminOrganizationsSummaryOptions = { /** Workspace (organization) IDs to resolve to identity and branding (max 100). */ ids: string[]; }; /** * Options accepted when inviting several users to an organization as a global admin. */ type InviteAdminOrganizationUsersOptions = { organizationId: string; emails: string[]; role: string; /** Teams joined when each invitation is accepted. */ teamIds?: string[]; applicationId?: string; /** * When false, skips the invitation flow and adds each user as a member * immediately, creating the user account if it does not exist yet. * This mode is restricted to global administrators. * Defaults to true (send an invitation email). */ sendInvite?: boolean; /** * Initial password for accounts created by a force add (`sendInvite: * false`); rejected otherwise. 8–128 characters. Only applied to users * without a password yet — an existing credential is never overwritten. */ password?: string; }; /** * Per-email outcome of a batch organization invite. */ type InviteAdminOrganizationUsersResult = { results: { email: string; status: 'invited' | 'added' | 'error'; message?: string; }[]; }; /** * Service for global admin operations. * * All endpoints require the authenticated user to hold the global admin role. */ declare class AdminService { private client; private apiUrl; /** * Creates a new AdminService instance. * * @param client - The API client for making admin requests * @param apiUrl - The base URL of the authentication API, used to reach the * application routes that the Better Auth client cannot address */ constructor(client: APIClient, apiUrl: string); /** * Requests an application management route. * * These routes are served by the API itself rather than by the Better Auth * handler, so they sit outside the `/api/auth` base path. The request is * sent to an absolute URL resolved against the API root, which better-fetch * uses as-is instead of prefixing the client's base URL, so it still goes * through {@link APIClient.$fetch} and picks up every fetch option the * client was created with (hooks, default headers, custom fetch, cookies). * * @param path - Path relative to the API root, without a leading slash; `:name` segments are filled from `request.params` * @param request - Method, body, query, and path parameters * @returns The parsed JSON response */ private requestApplicationRoute; /** * Lists applications, optionally filtered by organization. * * @param options - Pagination, ordering, organization filter, and search options * @returns The application listing with entitlement details */ listApplications(options?: ListAdminApplicationsOptions): Promise; /** * Creates an application. * * @param options - Application name, URLs, logo, and authentication settings * @returns The created application */ createApplication(options: CreateAdminApplicationOptions): Promise; /** * Updates an application. * * @param applicationId - ID of the application to update * @param options - Application name, URLs, logo, and authentication settings * @returns The updated application */ updateApplication(applicationId: string, options: CreateAdminApplicationOptions): Promise; /** * Disables an application. Sign-ins, token exchanges, refreshes and * client-credentials exchanges through it fail with `application_disabled`, * which carries the deprecation notice. Disabling an already disabled * application replaces its notice. * * @param applicationId - ID of the application to disable * @param options - Optional deprecation notice * @returns The updated application */ disableApplication(applicationId: string, options?: DisableAdminApplicationOptions): Promise; /** * Enables a disabled application and clears its deprecation notice. * * @param applicationId - ID of the application to enable * @returns The updated application */ enableApplication(applicationId: string): Promise; /** Lists the role catalog for an application. */ listApplicationRoles(applicationId: string): Promise; /** Creates an application-scoped role definition. */ createApplicationRole(applicationId: string, options: CreateAdminApplicationRoleOptions): Promise; /** Updates an application-scoped role definition. */ updateApplicationRole(applicationId: string, currentName: string, options: UpdateAdminApplicationRoleOptions): Promise; /** Deletes an application-scoped role definition. */ deleteApplicationRole(applicationId: string, name: string): Promise; /** * Enables an organization for an application. * * @param applicationId - ID of the application to update * @param options - Organization entitlement payload * @returns The created entitlement */ createApplicationEntitlement(applicationId: string, options: CreateAdminApplicationEntitlementOptions): Promise; /** * Lists client secrets for an application. * * @param applicationId - ID of the application to inspect * @returns Secret metadata without plaintext values */ listApplicationSecrets(applicationId: string): Promise; /** * Creates a client secret for an application. * * @param applicationId - ID of the application to update * @param options - Optional secret display name * @returns The created secret, including the plaintext value shown only once */ createApplicationSecret(applicationId: string, options?: CreateAdminApplicationSecretOptions): Promise; /** * Deletes one client secret for an application. * * @param applicationId - ID of the application to update * @param secretId - ID of the secret to delete * @returns The deleted secret metadata */ deleteApplicationSecret(applicationId: string, secretId: string): Promise; /** * Retires an application's service-account identity. * * @param applicationId - ID of the application to update * @returns The updated application */ retireApplicationServiceAccount(applicationId: string): Promise; /** * Lists all organizations, optionally with member and application previews * and totals when a preview size is requested. * * @param options - Pagination, ordering, search, and preview options * @returns The paginated organization listing */ listOrganizations(options?: ListAdminOrganizationsOptions): Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: ListAdminOrganizationsResult; error: null; }>; /** * Lists users, optionally with organization previews and totals when a * preview size is requested. Global admins list across every organization * and may narrow to one with organizationId; an organization admin always * gets their own organization's users, without previews. * * @param options - Pagination, ordering, search, preview, and organization options * @returns The paginated user listing */ listUsers(options?: ListAdminUsersOptions): Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: ListAdminUsersResult; error: null; }>; /** * Fetches a single user by ID. * * @param userId - The ID of the user to fetch * @returns The user */ getUser(userId: string): Promise; /** * Fetches a single organization, optionally with adjacent IDs in * the listing defined by the ordering options. * * @param options - Organization ID and listing adjacency options * @returns The organization */ getOrganization(options: GetAdminOrganizationOptions): Promise<{ data: AdminOrganization; } | null>; /** * Fetches minimal identity and branding (id, name, logo) for several * organizations at once, for surfaces such as the vault pages that resolve * many workspace IDs to display names and logos in a single request. * * Unknown IDs are omitted from the result, so callers map the returned rows * by ID rather than by position. * * @param options - The workspace (organization) IDs to resolve * @returns The organization summaries for the IDs that exist */ getOrganizationsSummary(options: GetAdminOrganizationsSummaryOptions): Promise; /** * Fetches the per-organization access report for a single user: their * organizations with role, membership ID, and teams, plus each * organization's entitled applications with the user's effective role. * * @param userId - The ID of the user to fetch access for * @returns The user access report */ getUserAccess(userId: string): Promise<{ data: AdminUserAccess; } | null>; /** * Lists applications with their entitlements as a global admin. Unlike * {@link listApplications}, which goes through the session-only application * routes, this uses the admin endpoint and so also works with a bearer token. * * @param options - Pagination, ordering, organization filter, search, and member preview options * @returns The application listing with entitlement details */ listAdminApplications(options?: ListAdminApplicationsOptions): Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: ListAdminApplicationsResult; error: null; }>; /** * Lists the users with access to an application as a global admin, one row * per user with every organization that grants them access and the role it * grants. * * @param options - Application ID, organization filter, pagination, and search options * @returns The paginated application member listing */ listApplicationMembers(options: ListAdminApplicationMembersOptions): Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: ListAdminApplicationMembersResult; error: null; }>; /** * Lists active members for one organization as a global admin. * * @param options - Organization ID, pagination, and search options * @returns The paginated organization member listing */ listOrganizationMembers(options: ListAdminOrganizationMembersOptions): Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: ListAdminOrganizationMembersResult; error: null; }>; /** * Lists teams for one organization. Global admins may list any organization; * an organization admin only their own. * * @param options - Organization ID, pagination, search, and ordering options * @returns The paginated organization team listing */ listOrganizationTeams(options: ListAdminOrganizationTeamsOptions): Promise<{ data: null; error: { message?: string | undefined; status: number; statusText: string; }; } | { data: ListAdminOrganizationTeamsResult; error: null; }>; /** * Creates a team for one organization as a global admin. * * @param options - Organization ID, team name, and optional team members * @returns The created team */ createOrganizationTeam(options: CreateAdminOrganizationTeamOptions): Promise<{ data: AdminOrganizationTeamRecord; } | null>; /** * Updates a team for one organization. Global admins may update any * organization; an organization admin only their own. * * @param options - Organization ID, team ID, new name, and optional replacement member IDs * @returns The updated team */ updateOrganizationTeam(options: UpdateAdminOrganizationTeamOptions): Promise<{ data: AdminOrganizationTeamRecord; } | null>; /** * Deletes a team for one organization, detaching its members with it. * Global admins may delete from any organization; an organization admin * only from their own. * * @param options - Organization ID and team ID */ deleteOrganizationTeam(options: DeleteAdminOrganizationTeamOptions): Promise; /** * Fetches a single entitlement together with its ordered access rules. * * @param entitlementId - ID of the entitlement to fetch * @returns The entitlement and its rules */ getEntitlement(entitlementId: string): Promise; /** * Replaces all access rules on an entitlement in a single call. * * @param entitlementId - ID of the entitlement whose rules are replaced * @param options - The full set of rules to persist * @returns The entitlement with the saved rules */ setEntitlementRules(entitlementId: string, options: SetAdminEntitlementRulesOptions): Promise; /** * Enables or disables an entitlement. * * @param entitlementId - ID of the entitlement to update * @param options - The desired enabled state * @returns The updated entitlement */ updateEntitlement(entitlementId: string, options: UpdateAdminEntitlementOptions): Promise; /** * Deletes an entitlement and all of its access rules. * * @param entitlementId - ID of the entitlement to delete * @returns The deleted entitlement */ deleteEntitlement(entitlementId: string): Promise; /** * Creates an organization without adding the creator as a member. * * @param options - Organization name and optional slug, logo, metadata, and settings * @returns The created organization */ createOrganization(options: CreateAdminOrganizationOptions): Promise<{ data: AdminOrganization; } | null>; /** * Updates an organization's profile and settings. Global admins may update * any organization; an organization admin only their own, and only the * fields they own — the slug, metadata, and billing configuration stay * global admin territory. * * @param options - Organization ID and the fields to update * @returns The updated organization */ updateOrganization(options: UpdateAdminOrganizationOptions): Promise<{ data: AdminOrganization; } | null>; /** * Updates an organization member's role. * * @param options - Membership ID and the new role * @returns The updated membership */ updateMemberRole(options: UpdateAdminMemberRoleOptions): Promise<{ data: AdminMember; } | null>; /** * Removes an organization member. * * @param options - Membership ID to remove * @returns The removed membership */ removeMember(options: RemoveAdminMemberOptions): Promise<{ data: AdminMember; } | null>; /** * Sets a user's effective application role within an organization. A * non-null role grants access, a null role denies access (leave * application), and clear removes the user-specific override. * * @param options - User, organization, application, and the role or clear flag */ setUserApplicationRole(options: SetAdminUserApplicationRoleOptions): Promise; /** * Reconciles a user's team memberships within an organization to a given set. * * @param options - User, organization, and the desired teams (empty to clear) */ setUserTeam(options: SetAdminUserTeamOptions): Promise; /** * Bans a user from the auth system and invalidates all their sessions. * @param userId - The ID of the user to ban */ banUser(userId: string): Promise; /** * Lifts a user's ban. * @param userId - The ID of the user to unban */ unbanUser(userId: string): Promise; /** * Sets a user's password directly, without sending any email. Requires the * global admin role. * @param options - The user and their new password */ setUserPassword(options: SetAdminUserPasswordOptions): Promise; /** * Signs a user out everywhere by revoking all of their sessions. Requires * the global admin role. * @param userId - The ID of the user whose sessions are revoked */ revokeUserSessions(userId: string): Promise; /** * Permanently removes a user from the auth system. * @param userId - The ID of the user to remove */ removeUser(userId: string): Promise; /** * Cancels a pending invitation as a global admin. * @param invitationId - The ID of the invitation to cancel */ cancelInvite(invitationId: string): Promise; /** * Replaces a pending invitation with a new one that keeps its roles and * teams, and emails it, as a global admin. * @param invitationId - The ID of the invitation to resend */ resendInvite(invitationId: string): Promise; /** * Invites several users to an organization in one call, or — with * `sendInvite: false` — adds them as members immediately, creating user * accounts as needed. Failures are isolated per email in the results * payload. * * @param options - Organization, emails, role, and optional teams/application * @returns Per-email invite outcomes */ inviteOrganizationUsers(options: InviteAdminOrganizationUsersOptions): Promise<{ data: InviteAdminOrganizationUsersResult; } | null>; } /** * Optional related data that can be included when listing organizations. */ type ListOrganizationsOptions = { /** Additional organization data to include in the response. */ include?: readonly 'role'[]; }; /** * Organization list options that guarantee the current user's membership role. */ type ListOrganizationsWithRoleOptions = { include: readonly ['role', ...'role'[]]; }; /** * An organization with the current user's membership role. */ type OrganizationWithRole = ExtendedOrganization & { role: string; }; /** * Result of accepting an organization invitation. */ type AcceptInvitationResult = { /** The scoped application's ID, or `null` for a plain organization invitation. */ applicationId: string | null; /** The scoped application's display name, or `null` for a plain organization invitation. */ applicationName: string | null; /** Application home URL for application-scoped invitations, otherwise `null`. */ homeUrl: string | null; /** Configured post-acceptance URL for plain organization invitations. */ inviteAcceptedUrl: string | null; /** The accepted organization membership. This may be an existing membership. */ member: Member; }; /** * Fields that can be updated on an organization. */ type UpdateOrganizationPayload = Partial>; /** * Pagination options for listing organization members. */ type ListMembersOptions = { /** Maximum number of members to return. */ limit?: number; /** Number of members to skip for pagination. */ offset?: number; /** Member field used to order the page. */ sortBy?: 'createdAt'; /** Sort direction for the member page. */ sortDirection?: 'asc' | 'desc'; /** With an application session, also lists organization members without access to the application, marked hasAccess: false. Requires permission to grant access. */ includeWithoutAccess?: boolean; }; /** * Organization member as returned to an application session, with the member's * role in the application. */ type ApplicationScopedMember = Member & { /** The member's role in the application, or null without access. */ applicationRole?: string | null; /** Present when includeWithoutAccess was requested. */ hasAccess?: boolean; }; /** * Options for inviting a user to the active organization. * * When the SDK is authenticated with an application-scoped session, the invitation * is automatically scoped to that application. First-party callers receive a * plain organization invitation. */ type InviteUserToOrganizationOptions = { /** Email address of the user to invite. */ userEmail: string; /** Organization role to assign to the invited user. */ role: Role; /** Application role granted on acceptance. Required with an application-scoped session. */ applicationRole?: string; /** Optional team to add the user to upon acceptance. */ teamId?: string; /** Whether to resend the invitation if one already exists for this email. */ resend?: boolean; }; /** * Options for removing a user from the active organization. * * Provide either `memberId` or `userEmail`, but not both. */ type RemoveUserFromOrganizationOptions = { /** The member ID to remove. */ memberId: string; userEmail?: never; } | { /** The user's email address to remove. */ userEmail: string; memberId?: never; }; /** * Options for updating a member's role within the organization. * * With an application-scoped session, `role` is an application role and the * update grants or changes access to that application. The organization role * is left unchanged. */ type UpdateMemberRoleOptions = { /** The member ID whose role should be updated. */ memberId: string; /** The new role to assign: an organization role, or an application role in app mode. */ role: Role | (string & {}); }; /** * Payload for creating a new team. */ type CreateTeamPayload = Pick & { /** User IDs of organization members to add to the team as it is created. */ memberIds?: string[]; }; /** * Payload for updating an existing team. */ type UpdateTeamPayload = Pick; /** * Status of an invitation as seen by the pre-login invite flow. * * `email` and `requiresAccountSetup` are only present while the invitation is * still pending; other statuses return the status alone. */ type InvitationSignupStatus = { status: 'pending'; email: string; /** True when the invited user has no account yet and has never signed in. */ requiresAccountSetup: boolean; } | { status: 'accepted' | 'canceled' | 'rejected' | 'expired'; }; /** * Result of creating a password from an invitation. The user is signed in * as part of the call; the session cookie is set on the response. */ type InvitationPasswordSetupResult = { token: string; user: { id: string; email: string; name: string; }; }; /** * Service for managing organizations, members, invitations, and teams. * * Provides comprehensive multi-tenant organization management including: * - Organization CRUD operations * - Member management * - Invitation management * - Team management */ declare class OrganizationService { private client; /** * Creates a new OrganizationService instance. * * @param client - The API client for making organization requests */ constructor(client: APIClient); /** * Retrieves a single organization by ID with optional related data. * * @param id - The organization ID * @returns The organization with members, invitations, and teams */ getOrganization(id: string): Promise<{ members: { id: string; organizationId: string; role: "org:admin" | "org:member" | "org:reviewer"; createdAt: Date; userId: string; teamId?: string | undefined | undefined; user: { id: string; email: string; name: string; image?: string | undefined; }; }[]; invitations: { id: string; organizationId: string; email: string; role: "org:admin" | "org:member" | "org:reviewer"; status: better_auth_plugins.InvitationStatus; inviterId: string; expiresAt: Date; createdAt: Date; teamId?: string | undefined | undefined; }[]; teams: { id: string; name: string; organizationId: string; createdAt: Date; updatedAt?: Date | undefined; }[]; } & { id: string; name: string; slug: string; createdAt: Date; logo?: string | null | undefined | undefined; metadata?: any; }>; /** * Lists all organizations accessible to the current user. * * @param options - Optional related organization data to include * @returns An array of organizations */ listOrganizations(options: ListOrganizationsWithRoleOptions): Promise; listOrganizations(options?: ListOrganizationsOptions): Promise; /** * Sets the active organization for the current user session. * * @param id - The organization ID to set as active */ setActiveOrganization(id: string): Promise; /** * Updates an organization's details. * * @param payload - The organization fields to update (name, logo, settings) * @returns The updated organization */ updateOrganization(payload: UpdateOrganizationPayload): Promise; /** * Lists members of the active organization with optional pagination. * * @param options - Pagination options * @param options.limit - Maximum number of members to return * @param options.offset - Number of members to skip * @param options.includeWithoutAccess - With an application session, also list members without access to the application * @returns An array of organization members, with their application role when the session is an application session */ listMembers(options?: ListMembersOptions): Promise; /** * Gets the currently active organization member for the authenticated user. * * @returns The active member object */ getActiveMember(): Promise & { user: { id: string; name: string; email: string; image: string | undefined; }; }>>; /** * Invites a user to join the active organization. * * When the SDK runs with an application-scoped session, the server * automatically scopes the resulting invitation to that application. * * @param options - Invitation configuration * @param options.userEmail - Email address of the user to invite * @param options.role - Role to assign to the invited user * @param options.applicationRole - Application role granted on acceptance; required with an application-scoped session * @param options.teamId - Team ID to add the user to * @param options.resend - Whether to resend if invitation already exists * @returns The created invitation */ inviteUserToOrganization({ userEmail, role, applicationRole, teamId, resend }: InviteUserToOrganizationOptions): Promise>; /** * Cancels a pending organization invitation. * * @param id - The invitation ID to cancel */ cancelInvitation(id: string): Promise; /** * Accepts an organization invitation. * * @param id - The invitation ID to accept * @returns The accepted member, application context for app-scoped invitations, * and the configured post-acceptance URL for plain organization invitations. */ acceptInvitation(id: string): Promise; /** * Gets the pre-login signup status for an invitation. * * Public endpoint keyed by the invitation id from the emailed invite link. * While the invitation is pending, the result includes the invited email * and whether the invited user still needs to set up their account. * * @param id - The invitation ID from the invite link * @returns The invitation status with account-setup information */ getInvitationSignupStatus(id: string): Promise; /** * Creates a password for an invited user who has no account yet. * * Only available once per invitation, while the invitation is pending and * the invited user has never signed in. The user is signed in as part of * the call; the session cookie is set on the response. * * @param id - The invitation ID from the invite link * @param password - The password to create (minimum 8 characters) * @returns The session token and signed-in user */ setupInvitationPassword(id: string, password: string): Promise; /** * Removes a user from the active organization. * * With an application-scoped session, revokes the member's access to that * application and keeps the membership. * * @param options - Provide either `memberId` or `userEmail` to identify the user * @param options.memberId - Membership ID to remove * @param options.userEmail - Email address of the member to remove */ removeUserFromOrganization({ memberId, userEmail }: RemoveUserFromOrganizationOptions): Promise; /** * Updates the role of an organization member. * * With an application-scoped session, `role` is an application role: the * update grants or changes the member's access to that application and * keeps the organization role. * * @param options - Role update configuration * @param options.memberId - The member ID to update * @param options.role - The new role to assign */ updateMemberRole({ memberId, role }: UpdateMemberRoleOptions): Promise; /** * Creates a new team within the active organization. * * @param payload - Team configuration with a `name` field and optional `memberIds` * @returns The created team */ createTeam(payload: CreateTeamPayload): Promise<{ id: string; name: string; organizationId: string; createdAt: Date; updatedAt?: Date | undefined; }>; /** * Updates an existing team's details. * * @param id - The team ID to update * @param payload - Team fields to update (currently supports `name`) * @returns The updated team */ updateTeam(id: string, payload: UpdateTeamPayload): Promise<{ id: string; name: string; organizationId: string; createdAt: Date; updatedAt?: Date | undefined; }>; /** * Deletes a team from the active organization. * * @param id - The team ID to delete */ deleteTeam(id: string): Promise; /** * Lists all teams in the active organization. * * @returns An array of teams */ listTeams(): Promise<{ id: string; name: string; organizationId: string; createdAt: Date; updatedAt?: Date | undefined; }[]>; /** * Lists all members of a specific team. * * @param id - The team ID * @returns An array of team members */ listTeamMembers(id: string): Promise<{ id: string; teamId: string; userId: string; createdAt: Date; }[]>; /** * Adds a user to a team. * * @param teamId - The team ID * @param userId - The user ID to add * @returns The added team member */ addTeamMember(teamId: string, userId: string): Promise<{ id: string; teamId: string; userId: string; createdAt: Date; }>; /** * Removes a user from a team. * * @param teamId - The team ID * @param userId - The user ID to remove */ removeTeamMember(teamId: string, userId: string): Promise; } /** * Service for managing user authentication sessions. * * Provides methods for signing in with various providers (social, SSO, email/password), * signing out, and password reset functionality. */ declare class SessionService { private client; private apiUrl; /** * Creates a new SessionService instance. * * @param client - The API client for making authentication requests * @param apiUrl - The base URL of the authentication API */ constructor(client: APIClient, apiUrl: string); /** * Retrieves the current user session. * * @returns The current user session */ getSession(token?: string): Promise<{ user: better_auth.StripEmptyObjects<{ id: string; createdAt: Date; updatedAt: Date; email: string; emailVerified: boolean; name: string; image?: string | null | undefined; } & { twoFactorEnabled: boolean | null | undefined; } & {} & { banned: boolean | null | undefined; } & { role?: string | null | undefined; banReason?: string | null | undefined; banExpires?: Date | null | undefined; } & { preferredLanguage: string; } & { lastActiveAt?: Date | null | undefined; displayName?: string | null | undefined; title?: string | null | undefined; pronouns?: string | null | undefined; }>; session: better_auth.StripEmptyObjects<{ id: string; createdAt: Date; updatedAt: Date; userId: string; expiresAt: Date; token: string; ipAddress?: string | null | undefined; userAgent?: string | null | undefined; } & {} & { activeOrganizationId?: string | null | undefined; activeTeamId?: string | null | undefined; } & {} & { impersonatedBy?: string | null | undefined; } & {} & {}>; } | null>; /** * Retrieves a valid JWT token. * * @returns The JWT token */ getToken(): Promise<{ token: string; }>; /** * Lists the login methods enabled in the environment. Public; safe to call * before authentication to decide which sign-in options to render. * * @returns The enabled login methods */ getLoginMethods(): Promise<("sso" | "google" | "microsoft" | "password" | "otp")[]>; /** * Initiates social authentication flow with Google or Microsoft. * * @param options - Social sign-in configuration * @param options.provider - The social provider * @param options.callbackURL - URL to redirect to after successful authentication * @param options.errorCallbackURL - URL to redirect to on error * @param options.loginHint - Email to preselect at the provider * * @throws {InvalidSocialProvider} When the provider is not 'google' or 'microsoft' * @throws {InvalidCallbackURL} When callback URLs are malformed */ signInWithSocialProvider({ provider, callbackURL, errorCallbackURL, loginHint, }: SocialSignInOptions): Promise; /** * Initiates the Single Sign-On authentication flow. The provider resolved * from the email's domain determines whether SAML or OIDC is used. * * @param options - SSO sign-in configuration * @param options.email - User's email to determine the SSO provider * @param options.callbackURL - URL to redirect to after successful authentication * @param options.errorCallbackURL - URL to redirect to on error * * @throws {EmailRequired} When email is not provided * @throws {InvalidCallbackURL} When callback URLs are malformed */ signInWithSso({ email, callbackURL, errorCallbackURL, }: SignInWithSsoOptions): Promise; /** * Authenticates a user with email and password credentials. * * @param options - Email/password sign-in configuration * @param options.email - User's email address * @param options.password - User's password * @param options.callbackURL - URL to redirect to after successful authentication */ signInWithEmailAndPassword({ email, password, callbackURL, }: SignInWithEmailAndPasswordOptions): Promise; /** * Signs out the currently authenticated user. * * @param callback - Callback function to execute after signing out */ signOut(callback?: (() => void) | (() => Promise)): Promise; /** * Initiates a password reset request by sending a reset email. * * @param email - Email address of the user requesting password reset * @param callbackURL - URL where the user will be redirected to complete the reset */ requestPasswordReset(email: string, callbackURL: string): Promise; /** * Completes the password reset process with a reset token and new password. * * @param token - The password reset token from the email * @param password - The new password to set */ resetPassword(token: string, password: string): Promise; } /** * Service for managing API keys. * * Provides CRUD operations for API keys scoped to the authenticated * user or their active organization. */ declare class ApiKeyService { private client; /** * Creates a new ApiKeyService instance. * * @param client - The API client for making API key requests */ constructor(client: APIClient); /** * Creates a new API key. * * The returned object includes the secret `key` value, which is only * available at creation time and cannot be retrieved later. * * @param payload - The API key configuration * @returns The created API key including the secret key value */ createApiKey(payload: CreateApiKeyPayload): Promise; /** * Retrieves an API key by its ID. * * @param id - The API key ID * @returns The API key (without the secret key value) */ getApiKey(id: string): Promise; /** * Lists all API keys owned by the authenticated user. * * @returns An object containing the API keys array and pagination metadata */ listApiKeys(): Promise<{ apiKeys: ApiKeyWithoutSecret[]; total: number; limit: number | undefined; offset: number | undefined; }>; /** * Lists all API keys belonging to an organization. * * @param organizationId - Defaults to the active organization. Only global admins may select another organization. * @returns An array of API keys (without secret key values) */ listOrganizationApiKeys(organizationId?: string): Promise; /** * Updates an existing API key. * * @param payload - The fields to update * @returns The updated API key (without the secret key value) */ updateApiKey(payload: UpdateApiKeyPayload): Promise; /** * Permanently deletes an API key. * * @param id - The API key ID to delete */ deleteApiKey(id: string): Promise<{ success: boolean; }>; } /** * Options for requesting an email OTP. */ type SendVerificationOTPOptions = { /** * Application ID used to scope the OTP request to an application's * configured sign-in policy. */ applicationId: string; }; /** * Options for completing email OTP sign-in. */ type EmailOTPSignInOptions = { /** * Application ID used to scope the OTP sign-in to an application's * configured sign-in policy. */ applicationId: string; }; /** * Service for email OTP authentication operations. * * Provides helpers for sending one-time passcodes used by passwordless * sign-in flows. */ declare class EmailOTPService { private client; /** * Creates a new EmailOTPService instance. * * @param client - The API client for making email OTP requests */ constructor(client: APIClient); /** * Sends a sign-in verification OTP to an email address. * * @param email - Email address that should receive the OTP * @param options - Request configuration * @returns The underlying email OTP API response */ sendVerificationOTP(email: string, options: SendVerificationOTPOptions): Promise<{ success: boolean; }>; /** * Completes email OTP sign-in with a one-time passcode. * * @param email - Email address that received the OTP * @param otp - One-time passcode from the sign-in email * @param options - Request configuration * @returns The underlying email OTP sign-in API response */ signIn(email: string, otp: string, options: EmailOTPSignInOptions): Promise & { user: better_auth.StripEmptyObjects<{ id: string; createdAt: Date; updatedAt: Date; email: string; emailVerified: boolean; name: string; image?: string | null | undefined; } & { twoFactorEnabled: boolean | null | undefined; } & {} & { banned: boolean | null | undefined; } & { role?: string | null | undefined; banReason?: string | null | undefined; banExpires?: Date | null | undefined; } & { preferredLanguage: string; } & { lastActiveAt?: Date | null | undefined; displayName?: string | null | undefined; title?: string | null | undefined; pronouns?: string | null | undefined; }>; }>; } type UserProfile = Pick; type UpdateUserProfilePayload = Partial; declare class UserService { private readonly client; constructor(client: APIClient); changePassword(currentPassword: string, newPassword: string): Promise & { id: string; createdAt: Date; updatedAt: Date; email: string; emailVerified: boolean; name: string; image?: string | null | undefined; }; }, "user"> & { user: better_auth.StripEmptyObjects<{ id: string; createdAt: Date; updatedAt: Date; email: string; emailVerified: boolean; name: string; image?: string | null | undefined; } & { twoFactorEnabled: boolean | null | undefined; } & {} & { banned: boolean | null | undefined; } & { role?: string | null | undefined; banReason?: string | null | undefined; banExpires?: Date | null | undefined; } & { preferredLanguage: string; } & { lastActiveAt?: Date | null | undefined; displayName?: string | null | undefined; title?: string | null | undefined; pronouns?: string | null | undefined; }>; }>; updateProfile(profile: UpdateUserProfilePayload): Promise<{ status: boolean; }>; /** * Lists the authentication accounts (providers) linked to the current user. * Returns provider identifiers and timestamps only — never tokens. * * The underlying client is configured with `throw: true`, so it resolves to * the response data directly (the account array), not a `{ data }` envelope. */ listAccounts(): Promise<{ scopes: string[]; id: string; createdAt: Date; updatedAt: Date; userId: string; providerId: string; accountId: string; }[]>; /** * Begins linking a social provider to the current user. Resolves to * `{ url, redirect }`; the caller navigates to `url`. Requires an AAL2 * session (gated server-side). */ linkSocial(params: { provider: 'google' | 'microsoft'; callbackURL: string; }): Promise<{ url: string; redirect: boolean; }>; /** * Unlinks a provider from the current user. Requires an AAL2 session (gated * server-side). The server refuses to remove the user's last account. */ unlinkAccount(params: { providerId: string; accountId?: string; }): Promise<{ status: boolean; }>; } /** * Response from listing the members of a team in the active organization. */ type TeamMembersResponse = { /** The team's members. */ teamMembers: TeamMember[]; }; /** * Error thrown when an invalid social provider is specified. */ declare class InvalidSocialProvider extends BaseError { constructor(message: string); } /** * Error thrown when an invalid callback URL is provided. * * This error occurs when the callback URL or error callback URL * is malformed or not a valid URL. */ declare class InvalidCallbackURL extends BaseError { constructor(message: string); } /** * Error thrown when an email is required but not provided. */ declare class EmailRequired extends BaseError { constructor(message: string); } /** * Main authentication client for interacting with the Auth API. * * Provides access to session, organization, application, API key, and email OTP services. * * @example * ```typescript * // Initialize the client * const authClient = new AuthClient('https://auth.example.com') * * // Sign in with email and password * await authClient.session.signInWithEmailAndPassword({ * email: 'user@example.com', * password: 'password123' * }) * * // List organizations * const orgs = await authClient.organization.listOrganizations() * ``` */ declare class AuthClient { /** * Configured Better Auth client used by the public service wrappers. * * @internal */ private client; /** * Session management service for authentication operations */ session: SessionService; /** * Organization management service for multi-tenant operations */ organization: OrganizationService; /** * Application management service for application operations */ application: ApplicationService; /** * API key management service for API key operations */ apiKey: ApiKeyService; /** * Email OTP service for passwordless sign-in operations */ emailOtp: EmailOTPService; /** * Session assurance service for step-up operations */ sessionAssurance: SessionAssuranceService; /** * Magane the logged-in user's account and profile */ user: UserService; /** * Admin service for global admin operations */ admin: AdminService; /** * Creates a new AuthClient instance. * * @param apiUrl - The base URL of the authentication API * @param fetchOptions - Custom fetch options to include in all API requests */ constructor(apiUrl: string, fetchOptions?: BetterFetchOption); } /** Configuration for an in-memory application token cache. */ type ApplicationTokenStorageOptions = { /** Base URL of the Auth API. */ authApiUrl: string; /** Application identifier used for client-credentials exchanges. */ clientId: string; /** Application secret used for client-credentials exchanges. */ clientSecret: string; /** Full-jitter upper bound for the first retry delay. Defaults to 100 milliseconds. */ initialBackoffMs?: number; /** Maximum number of exchange attempts, including the initial request. Defaults to 3. */ maxAttempts?: number; /** Maximum number of organization tokens retained in memory. Defaults to 300. */ maxOrganizations?: number; }; /** Per-call retry overrides for {@link ApplicationTokenStorage.getToken}. */ type GetTokenOptions = { /** Full-jitter upper bound for the first retry delay. */ initialBackoffMs?: number; /** Maximum number of exchange attempts, including the initial request. */ maxAttempts?: number; }; /** * Caches organization-scoped application tokens in memory. * * Tokens are reissued one minute before expiry. Cache hits promote their * organization to the most-recently-used position, and insertions beyond the * configured limit evict the least recently used organization. Transient * exchange failures use full-jitter exponential backoff. */ declare class ApplicationTokenStorage { private readonly auth; private readonly clientId; private readonly clientSecret; private readonly initialBackoffMs; private readonly inFlight; private readonly maxAttempts; private readonly maxOrganizations; private readonly tokens; /** Creates an application token cache for one client-credentials identity. */ constructor({ authApiUrl, clientId, clientSecret, initialBackoffMs, maxAttempts, maxOrganizations, }: ApplicationTokenStorageOptions); /** Returns a fresh access token scoped to the requested organization. */ getToken(organizationId: string, { initialBackoffMs, maxAttempts, }?: GetTokenOptions): Promise; private exchangeTokenWithRetry; /** Performs the client-credentials exchange for one organization. */ protected exchangeToken(organizationId: string): Promise; /** Waits before the next exchange attempt. */ protected wait(delayMs: number): Promise; } type DecodedJWTPayload = Omit & { assurance?: JWTPayloadAssurance; }; /** * Validates a JWT token by checking its expiration and verifying its signature * against the JWKS endpoint. * * @param token - The JWT token string to validate * @param apiUrl - The base URL of the authentication API * @returns A promise that resolves to `true` if the token is valid, `false` otherwise * * @example * ```typescript * const token = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...' * const isValid = await validateToken(token, 'https://auth.example.com') * if (isValid) { * console.log('Token is valid') * } * ``` */ declare function validateToken(token: string, apiUrl: string): Promise; /** * Extracts and decodes the payload from a JWT token. * * **Warning:** This function does NOT validate the token's signature or check * if the token is valid. It only decodes the payload. Use `validateToken` if * you need to verify the token's authenticity. * * @param token - The JWT token string to extract the payload from * @returns The decoded payload as a key-value object * * @example * ```typescript * const token = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...' * const payload = extractTokenPayload(token) * console.log(payload.sub) // user ID * console.log(payload.exp) // expiration timestamp * ``` */ declare function extractTokenPayload(token: string): DecodedJWTPayload; export { AAL, AALBrand, AALs, ACR, ACRBrand, ACRs, AMR, AMRBrand, AMRs, ApiKeyMetadata, ApplicationConfig, ApplicationDisabledError, ApplicationError, ApplicationSessionAssuranceConfig, ApplicationSessionAssuranceError, ApplicationTokenStorage, AuthClient, AuthMethod, AuthMethodBrand, AuthMethods, AuthorizationFlowError, DEFAULT_APPLICATION_CONFIG, DEFAULT_JWT_ASSURANCE, DEFAULT_SESSION_ASSURANCE_CONFIG, DeviceAccessDeniedError, DeviceAuthorizationPendingError, DeviceAuthorizationSlowDownError, DeviceCodeExpiredError, DeviceTransientServerError, EmailOTPService, EmailRequired, InvalidCallbackURL, InvalidSocialProvider, JWTPayload, JWTPayloadAssurance, JWTPayloadUser, JWTPayloadWorkspace, LOGIN_METHODS, OAuthBeginStepUpResponse, OAuthCompleteStepUpResponse, OAuthStepUpProvider, RefreshTokenExpiredError, Roles, SENSITIVE_ACTION_ASSURANCE_POLICY, STEP_UP_MAX_AGE_SECONDS, SendOtpResponse, SessionAssurancePolicy, SessionAssuranceRequiredError, SessionAssuranceRequiredPayload, SessionAssuranceResponse, SessionAssuranceService, StepUpOption, UserNotLoggedInError, ac, assuranceFields, canStepUpWithAmr, createAPIClient, extractTokenPayload, getAalRank, invitationAdditionalFields, isAssuranceSufficientForPolicy, isSessionAssuranceSufficient, isTokenExpired, memberAdditionalFields, mergeStepUpAssurance, normalizeAmr, organizationAdditionalFields, parseApplicationDisabledPayload, parseSessionAssuranceRequiredPayload, rolesAccessControl, sessionAssurancePluginClient, userAdditionalFields, validateToken }; export type { APIClient, AcceptInvitationResult, AdminApplication, AdminApplicationEntitlement, AdminApplicationEntitlementRecord, AdminApplicationIdentity, AdminApplicationMember, AdminApplicationMemberOrganization, AdminApplicationMemberRecord, AdminApplicationOrganization, AdminApplicationRecord, AdminApplicationRole, AdminApplicationSecret, AdminEntitlementRule, AdminEntitlementRuleType, AdminEntitlementWithRules, AdminMember, AdminOrganization, AdminOrganizationApplication, AdminOrganizationMember, AdminOrganizationMemberApplication, AdminOrganizationMemberRecord, AdminOrganizationMemberTeam, AdminOrganizationSummary, AdminOrganizationTeam, AdminOrganizationTeamRecord, AdminUser, AdminUserAccess, AdminUserAccessApplication, AdminUserAccessOrganization, AdminUserAccessTeam, AdminUserInvitation, AdminUserOrganization, ApiKey, ApiKeyWithoutSecret, Application, ApplicationAuthContextResponse, ApplicationDeprecation, ApplicationDisabledPayload, ApplicationRole, ApplicationScopedMember, ApplicationTokenStorageOptions, AssuranceFields, BaseOrganization, BeginOAuthStepUpParams, BillingMode, ClientCredentialsGrant, ClientCredentialsTokenResponse, CompleteAuthorizationFlowResponse, CreateAdminApplicationEntitlementOptions, CreateAdminApplicationOptions, CreateAdminApplicationRoleOptions, CreateAdminApplicationSecretOptions, CreateAdminOrganizationOptions, CreateAdminOrganizationTeamOptions, CreateApiKeyPayload, CreateTeamPayload, CreatedAdminApplicationSecret, DecodedJWTPayload, DeleteAdminOrganizationTeamOptions, DeviceAuthorizationActionResponse, DeviceAuthorizationContextResponse, DeviceAuthorizationResponse, DeviceContextApplication, DisableAdminApplicationOptions, EmailOTPSignInOptions, FullOrganization, FullOrganizationMember, GetAdminOrganizationOptions, GetAdminOrganizationsSummaryOptions, GetTokenOptions, Invitation, InvitationPasswordSetupResult, InvitationSignupStatus, InviteAdminOrganizationUsersOptions, InviteAdminOrganizationUsersResult, InviteUserToOrganizationOptions, JWTPayloadData, ListAdminApplicationMembersOptions, ListAdminApplicationMembersResult, ListAdminApplicationsOptions, ListAdminApplicationsResult, ListAdminOrganizationMembersOptions, ListAdminOrganizationMembersResult, ListAdminOrganizationTeamsOptions, ListAdminOrganizationTeamsResult, ListAdminOrganizationsOptions, ListAdminOrganizationsResult, ListAdminUsersOptions, ListAdminUsersResult, ListCandidateOrganizationsInclude, ListCandidateOrganizationsOptions, ListCandidateOrganizationsResponse, ListMembersOptions, ListOrganizationsOptions, ListOrganizationsWithRoleOptions, LoginMethod, LoginMethodsResponse, Member, ExtendedOrganization as Organization, OrganizationSettings, OrganizationWithRole, RemoveAdminMemberOptions, RemoveUserFromOrganizationOptions, Role, SendVerificationOTPOptions, Session, SessionAssuranceActions, SessionData, SetAdminEntitlementRulesOptions, SetAdminUserApplicationRoleOptions, SetAdminUserPasswordOptions, SetAdminUserTeamOptions, SignInWithEmailAndPasswordOptions, SignInWithSsoOptions, SocialSignInOptions, StartAuthorizationFlowResponse, Strict, Team, TeamMember, TeamMembersResponse, UpdateAdminApplicationRoleOptions, UpdateAdminEntitlementOptions, UpdateAdminMemberRoleOptions, UpdateAdminOrganizationOptions, UpdateAdminOrganizationTeamOptions, UpdateApiKeyPayload, UpdateMemberRoleOptions, UpdateOrganizationPayload, UpdateTeamPayload, User, UserProfile, WhoAmIInclude, WhoAmIOptions, WhoAmIOrganization, WhoAmIResponse };