auth

package
v0.0.5-rc1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 4, 2026 License: Apache-2.0 Imports: 67 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package auth implements the Supabase Auth (gotrue) compatible surface mounted at /auth/v1 (project.md §2.2, §2.3).

The wire contract — request/response JSON, HTTP statuses, error bodies, JWT claims and refresh-token semantics — follows github.com/supabase/auth master. Compatibility beats internal elegance here: json tags, field order and error strings are deliberately copied. Deviations are called out in comments.

The package deliberately does NOT use huma: the /auth/v1 surface must match upstream byte-for-byte, and its OpenAPI contract is upstream's openapi.yaml.

Index

Constants

View Source
const (
	// DefaultSiteURL is used when neither DILION_AUTH_SITE_URL nor
	// GOTRUE_SITE_URL is set. Upstream requires SITE_URL; Dilion defaults it so
	// the zero-config developer path works.
	DefaultSiteURL = "http://localhost:5173"

	// DefaultJWTExp mirrors GOTRUE_JWT_EXP (seconds).
	DefaultJWTExp = 3600

	// DefaultOTPLength mirrors GOTRUE_MAILER_OTP_LENGTH / GOTRUE_SMS_OTP_LENGTH.
	DefaultOTPLength = 6

	// DefaultSMSTemplate is upstream's fallback GOTRUE_SMS_TEMPLATE.
	DefaultSMSTemplate = "Your code is {{ .Code }}"

	// DefaultMailerURLPath is the URL path every emailed action link is built
	// on top of (GOTRUE_MAILER_URLPATHS_*).
	//
	// DEVIATION: upstream's default is "/verify" because its API owns the root
	// of its host. Dilion mounts the compatible surface under /auth/v1, so the
	// default carries that prefix; the env overrides still work.
	DefaultMailerURLPath = "/auth/v1/verify"

	// DefaultCaptchaTimeout mirrors upstream's captcha verifier default: the
	// HTTP timeout of one hcaptcha/turnstile siteverify call.
	DefaultCaptchaTimeout = 10 * time.Second

	// DefaultRefreshTokenReuseInterval mirrors
	// GOTRUE_SECURITY_REFRESH_TOKEN_REUSE_INTERVAL (seconds). Upstream ships 0;
	// Dilion defaults to 10s because every supported client (gotrue-js and the
	// Supabase CLI) can issue concurrent refreshes.
	DefaultRefreshTokenReuseInterval = 10

	// DefaultDeletionReauthWindow is SecurityConfig.DeletionReauthWindow's
	// default.
	DefaultDeletionReauthWindow = 10 * time.Minute
)

Defaults that are referenced from more than one place.

View Source
const (
	ErrorCodeUnexpectedFailure = "unexpected_failure"
	ErrorCodeValidationFailed  = "validation_failed"
	ErrorCodeBadJSON           = "bad_json"
	ErrorCodeBadJWT            = "bad_jwt"
	ErrorCodeNotAdmin          = "not_admin"
	ErrorCodeNoAuthorization   = "no_authorization"
	ErrorCodeEmailExists       = "email_exists"
	ErrorCodePhoneExists       = "phone_exists"
	ErrorCodeUserNotFound      = "user_not_found"
	ErrorCodeUserAlreadyExists = "user_already_exists"
	ErrorCodeUserBanned        = "user_banned"
	ErrorCodeSessionNotFound   = "session_not_found"
	// ErrorCodeOAuthClientToken: an OAuth application's token on a route only
	// the user's own sign-in may use (Dilion extension).
	ErrorCodeOAuthClientToken        = "oauth_client_token_not_allowed"
	ErrorCodeSessionExpired          = "session_expired"
	ErrorCodeRefreshTokenNotFound    = "refresh_token_not_found"
	ErrorCodeRefreshTokenAlreadyUsed = "refresh_token_already_used"
	ErrorCodeSignupDisabled          = "signup_disabled"
	ErrorCodeInvalidCredentials      = "invalid_credentials"
	ErrorCodeSamePassword            = "same_password"
	ErrorCodeWeakPassword            = "weak_password"
	ErrorCodeConflict                = "conflict"
	ErrorCodeEmailNotConfirmed       = "email_not_confirmed"

	// ErrorCodeOverRequestRateLimit is the 429 of every rate-limited endpoint.
	ErrorCodeOverRequestRateLimit = "over_request_rate_limit"
	// ErrorCodeRequestTimeout is upstream's 504 when a request exceeds
	// GOTRUE_API_MAX_REQUEST_DURATION.
	ErrorCodeRequestTimeout = "request_timeout"
	// ErrorCodeAnonymousProviderDisabled is POST /signup without email/phone
	// while anonymous sign-ins are off.
	ErrorCodeAnonymousProviderDisabled = "anonymous_provider_disabled"
	// ErrorCodeEmailProviderDisabled is a password/email flow while the email
	// provider is disabled.
	ErrorCodeEmailProviderDisabled = "email_provider_disabled"
	// ErrorCodePhoneProviderDisabled is a phone flow while the phone provider is
	// disabled.
	ErrorCodePhoneProviderDisabled = "phone_provider_disabled"

	// ErrorCodeOTPExpired is /verify's answer for a token that is unknown,
	// already consumed, or past Mailer.OTPExp. The three cases deliberately
	// share one code and one message so /verify is not an oracle for which
	// links exist.
	ErrorCodeOTPExpired = "otp_expired"
	// ErrorCodeOTPDisabled is POST /otp with create_user=false for an address
	// that has no account.
	ErrorCodeOTPDisabled = "otp_disabled"
	// ErrorCodeOverEmailSendRateLimit is the 429 of the mail-sending endpoints.
	ErrorCodeOverEmailSendRateLimit = "over_email_send_rate_limit"
	// ErrorCodePhoneNotConfirmed is a phone flow on an unverified number.
	ErrorCodePhoneNotConfirmed = "phone_not_confirmed"
	// ErrorCodeUserSSOManaged is an attempt to change the email, phone or
	// password of an account whose identity is owned by an SSO provider.
	ErrorCodeUserSSOManaged = "user_sso_managed"

	// ErrorCodeReauthenticationNeeded is PUT /user with a new password while
	// Security.UpdatePasswordRequireReauth is on and no nonce was supplied.
	ErrorCodeReauthenticationNeeded = "reauthentication_needed"
	// ErrorCodeReauthenticationNotValid is a nonce that is wrong or expired.
	ErrorCodeReauthenticationNotValid = "reauthentication_not_valid"

	// ErrorCodeFlowStateNotFound is an auth code that never existed, was already
	// redeemed, or belongs to a flow with no user.
	ErrorCodeFlowStateNotFound = "flow_state_not_found"
	// ErrorCodeFlowStateExpired is an auth code older than FlowStateExpiry.
	ErrorCodeFlowStateExpired = "flow_state_expired"
	// ErrorCodeBadCodeVerifier is a code_verifier that does not hash to the
	// challenge the flow was created with.
	ErrorCodeBadCodeVerifier = "bad_code_verifier"
)

Error codes mirror github.com/supabase/auth/internal/api/apierrors/errorcode.go verbatim. Only the wave-1 subset is declared; add upstream names as features land.

View Source
const (
	// ErrorCodeBadOAuthState is a `state` that is not a UUID, names no flow
	// state, or names one that has expired.
	ErrorCodeBadOAuthState = "bad_oauth_state"
	// ErrorCodeBadOAuthCallback is a callback without `state` or without `code`.
	ErrorCodeBadOAuthCallback = "bad_oauth_callback"
	// ErrorCodeOAuthProviderNotSupported is a provider Dilion has no
	// implementation for.
	ErrorCodeOAuthProviderNotSupported = "oauth_provider_not_supported"
	// ErrorCodeProviderDisabled is a provider that exists but is switched off.
	ErrorCodeProviderDisabled = "provider_disabled"
	// ErrorCodeProviderEmailNeedsVerification is a sign-in whose provider email
	// is unverified while the project requires confirmed addresses.
	ErrorCodeProviderEmailNeedsVerification = "provider_email_needs_verification"
	// ErrorCodeFlowStateAlreadyUsed is a callback for a flow that already
	// produced an auth code.
	ErrorCodeFlowStateAlreadyUsed = "flow_state_already_used"
	// ErrorCodeIdentityAlreadyExists is a manual link of an identity that is
	// already attached to a user.
	ErrorCodeIdentityAlreadyExists = "identity_already_exists"
	// ErrorCodeIdentityNotFound is DELETE /user/identities/{id} for an identity
	// that is not the caller's.
	ErrorCodeIdentityNotFound = "identity_not_found"
	// ErrorCodeSingleIdentityNotDeletable is an attempt to unlink the last
	// identity of a user.
	ErrorCodeSingleIdentityNotDeletable = "single_identity_not_deletable"
	// ErrorCodeEmailConflictIdentityNotDeletable is an unlink that would promote
	// an email another account already owns.
	ErrorCodeEmailConflictIdentityNotDeletable = "email_conflict_identity_not_deletable"
	// ErrorCodeManualLinkingDisabled is /user/identities/authorize while
	// GOTRUE_SECURITY_MANUAL_LINKING_ENABLED is false.
	ErrorCodeManualLinkingDisabled = "manual_linking_disabled"
	// ErrorCodeUnexpectedAudience is a token whose `aud` is not the request's.
	ErrorCodeUnexpectedAudience = "unexpected_audience"
)
View Source
const (
	HookNameSendSMS              = "send-sms"
	HookNameSendEmail            = "send-email"
	HookNameCustomAccessToken    = "customize-access-token"
	HookNameMFAVerification      = "mfa-verification"
	HookNamePasswordVerification = "password-verification"
	HookNameBeforeUserCreated    = "before-user-created"
	HookNameAfterUserCreated     = "after-user-created"
)

Hook names. The strings are upstream's v0hooks.Name values and travel in the `metadata.name` field of every payload.

View Source
const (
	DefaultMFAHookRejectionMessage      = "Further MFA verification attempts will be rejected."
	DefaultPasswordHookRejectionMessage = "Further password verification attempts will be rejected."
)

Default rejection messages upstream substitutes when a hook rejects without supplying one (v0hooks.Default*HookRejectionMessage).

View Source
const (
	// ErrorCodeHookTimeout is the 422 when a webhook does not answer within the
	// per-call timeout (upstream ErrorCodeHookTimeout).
	ErrorCodeHookTimeout = "hook_timeout"
	// ErrorCodeHookTimeoutAfterRetry is the 422 after every retry timed out.
	ErrorCodeHookTimeoutAfterRetry = "hook_timeout_after_retry"
	// ErrorCodeHookPayloadOverSizeLimit is the 422 when a webhook response body
	// exceeds the read limit.
	ErrorCodeHookPayloadOverSizeLimit = "hook_payload_over_size_limit"
	// ErrorCodeHookPayloadInvalidContentType is the 400 when a webhook answers
	// 200/202 without an application/json Content-Type.
	ErrorCodeHookPayloadInvalidContentType = "hook_payload_invalid_content_type"
)

Hook error codes. Upstream declares these in apierrors/errorcode.go; they live here because errors.go is shared and this file owns the external-hook surface.

View Source
const (
	// ErrorCodeHookNotFound is the 404 for an unknown {name}.
	ErrorCodeHookNotFound = "hook_not_found"
	// ErrorCodeHookLocked is the 403 for a hook the operator pinned.
	ErrorCodeHookLocked = "hook_locked"
)
View Source
const (
	FactorTypeTOTP     = "totp"
	FactorTypePhone    = "phone"
	FactorTypeWebAuthn = "webauthn"
)

Factor types, matching the auth.factor_type enum (upstream models.TOTP etc.).

View Source
const (
	FactorStateUnverified = "unverified"
	FactorStateVerified   = "verified"
)

Factor states, matching the auth.factor_status enum (upstream models.FactorState.String()).

View Source
const (
	AAL1 = "aal1"
	AAL2 = "aal2"
	AAL3 = "aal3"
)

Authenticator assurance levels (upstream models.AuthenticatorAssuranceLevel).

View Source
const (
	AMRMethodOAuth        = "oauth"
	AMRMethodPassword     = "password"
	AMRMethodOTP          = "otp"
	AMRMethodTOTP         = "totp"
	AMRMethodMFAPhone     = "mfa/phone"
	AMRMethodMFAWebAuthn  = "mfa/webauthn"
	AMRMethodRecovery     = "recovery"
	AMRMethodInvite       = "invite"
	AMRMethodMagicLink    = "magiclink"
	AMRMethodEmailSignup  = "email/signup"
	AMRMethodEmailChange  = "email_change"
	AMRMethodTokenRefresh = "token_refresh"
	AMRMethodAnonymous    = "anonymous"
	AMRMethodSSOSAML      = "sso/saml"
)

AMR authentication methods. These strings are the wire contract: they are stored verbatim in auth.mfa_amr_claims.authentication_method and echoed in the JWT `amr` claim, and they are copied from upstream models.AuthenticationMethod.String().

View Source
const (
	ErrorCodeTooManyEnrolledMFAFactors = "too_many_enrolled_mfa_factors"
	ErrorCodeMFAFactorNameConflict     = "mfa_factor_name_conflict"
	ErrorCodeMFAFactorNotFound         = "mfa_factor_not_found"
	ErrorCodeMFAIPAddressMismatch      = "mfa_ip_address_mismatch"
	ErrorCodeMFAChallengeExpired       = "mfa_challenge_expired"
	ErrorCodeMFAVerificationFailed     = "mfa_verification_failed"
	ErrorCodeMFAVerificationRejected   = "mfa_verification_rejected"
	ErrorCodeInsufficientAAL           = "insufficient_aal"
	ErrorCodeMFAVerifiedFactorExists   = "mfa_verified_factor_exists"

	ErrorCodeMFATOTPEnrollDisabled     = "mfa_totp_enroll_not_enabled"
	ErrorCodeMFATOTPVerifyDisabled     = "mfa_totp_verify_not_enabled"
	ErrorCodeMFAPhoneEnrollDisabled    = "mfa_phone_enroll_not_enabled"
	ErrorCodeMFAPhoneVerifyDisabled    = "mfa_phone_verify_not_enabled"
	ErrorCodeMFAWebAuthnEnrollDisabled = "mfa_webauthn_enroll_not_enabled"
	ErrorCodeMFAWebAuthnVerifyDisabled = "mfa_webauthn_verify_not_enabled"
)

MFA error codes, copied verbatim from upstream internal/api/apierrors/errorcode.go. They live here (not in errors.go) so the MFA feature owns its own vocabulary.

View Source
const (
	// LimiterToken is POST /token?grant_type=refresh_token
	// (GOTRUE_RATE_LIMIT_TOKEN_REFRESH).
	LimiterToken = "token"
	// LimiterTokenPassword is POST /token?grant_type=password. Upstream shares
	// the refresh limit; Dilion applies the (much stricter) OTP limit, because a
	// password grant is a credential-guessing surface and a refresh is not.
	LimiterTokenPassword = "token_password"
	// LimiterSignup is POST /signup (GOTRUE_RATE_LIMIT_OTP, as upstream).
	LimiterSignup = "signup"
	// LimiterAnonymous is POST /signup without email or phone
	// (GOTRUE_RATE_LIMIT_ANONYMOUS_USERS, per HOUR).
	LimiterAnonymous = "anonymous"
	// LimiterVerify is /verify (GOTRUE_RATE_LIMIT_VERIFY).
	LimiterVerify = "verify"
	// LimiterOTP is POST /otp (GOTRUE_RATE_LIMIT_EMAIL_SENT).
	LimiterOTP = "otp"
	// LimiterMagicLink is POST /magiclink (GOTRUE_RATE_LIMIT_EMAIL_SENT).
	LimiterMagicLink = "magiclink"
	// LimiterRecover is POST /recover (GOTRUE_RATE_LIMIT_EMAIL_SENT).
	LimiterRecover = "recover"
	// LimiterResend is POST /resend (GOTRUE_RATE_LIMIT_EMAIL_SENT).
	LimiterResend = "resend"
	// LimiterSMS is the SMS-sending endpoints (GOTRUE_RATE_LIMIT_SMS_SENT).
	LimiterSMS = "sms"
	// LimiterUser is PUT /user (GOTRUE_RATE_LIMIT_OTP, as upstream).
	LimiterUser = "user"
	// LimiterSSO is POST /sso (GOTRUE_RATE_LIMIT_SSO).
	LimiterSSO = "sso"
	// LimiterWeb3 is POST /token?grant_type=web3 (GOTRUE_RATE_LIMIT_WEB3).
	LimiterWeb3 = "web3"
	// LimiterPasskey is the passkey endpoints (GOTRUE_RATE_LIMIT_PASSKEY).
	LimiterPasskey = "passkey"
)

Limiter names. Feature files rate-limit their routes with a.limit(<name>) — see Register. Names are stable; the limits behind them come from Config.

View Source
const (
	// OAuthServerAuthorizationTTL is how long a pending authorization request
	// stays redeemable — upstream's GOTRUE_OAUTH_SERVER_AUTHORIZATION_TTL.
	//
	// DEVIATION: 3 minutes, not upstream's 10m default. It is the default of
	// auth.oauth_authorizations.expires_at in migration 0116, and a consent
	// screen that takes longer than three minutes is a re-authorization, not a
	// slow click.
	OAuthServerAuthorizationTTL = 3 * time.Minute

	// OAuthServerDefaultScope is the scope assumed when the authorization
	// request omits one (upstream GOTRUE_OAUTH_SERVER_DEFAULT_SCOPE, "email").
	OAuthServerDefaultScope = ScopeEmail

	// OAuthServerAuthorizationPath is the SiteURL-relative path of the hosted
	// consent page /oauth/authorize redirects the browser to
	// (upstream GOTRUE_OAUTH_SERVER_AUTHORIZATION_PATH).
	//
	// DEVIATION: upstream has NO default — an unconfigured deployment redirects
	// the caller back with error=server_error. Dilion defaults to
	// "/oauth/consent" so the flow is usable out of the box.
	OAuthServerAuthorizationPath = "/oauth/consent"

	// OAuthServerAllowDynamicRegistration gates POST /oauth/clients/register
	// (upstream GOTRUE_OAUTH_SERVER_ALLOW_DYNAMIC_REGISTRATION, default false).
	//
	// DEVIATION: Dilion allows DCR whenever the OAuth server is enabled,
	// because Config has no separate knob to turn it on with. The endpoint is
	// rate limited per IP (LimiterOAuthClientRegister). Deployments that must
	// not accept anonymous client registrations should keep the OAuth server
	// off until conf.go grows the flag.
	OAuthServerAllowDynamicRegistration = true

	// LimiterOAuthClientRegister guards POST /oauth/clients/register
	// (upstream GOTRUE_RATE_LIMIT_OAUTH_DYNAMIC_CLIENT_REGISTER).
	LimiterOAuthClientRegister = "oauth_client_register"
)
View Source
const (
	ScopeOpenID        = "openid"
	ScopeEmail         = "email"
	ScopeProfile       = "profile"
	ScopePhone         = "phone"
	ScopeOfflineAccess = "offline_access"
)

OAuth/OIDC scope constants (upstream models/oauth_scope.go).

View Source
const (
	OAuthClientTypePublic       = "public"
	OAuthClientTypeConfidential = "confidential"
)

Client types (auth.oauth_client_type).

View Source
const (
	TokenEndpointAuthMethodNone              = "none"
	TokenEndpointAuthMethodClientSecretBasic = "client_secret_basic"
	TokenEndpointAuthMethodClientSecretPost  = "client_secret_post"
)

Token endpoint authentication methods (auth.oauth_clients.token_endpoint_auth_method).

View Source
const (
	OAuthRegistrationDynamic = "dynamic"
	OAuthRegistrationManual  = "manual"
)

Registration types (auth.oauth_registration_type).

View Source
const (
	OAuthAuthorizationPending  = "pending"
	OAuthAuthorizationApproved = "approved"
	OAuthAuthorizationDenied   = "denied"
	OAuthAuthorizationExpired  = "expired"
)

Authorization statuses (auth.oauth_authorization_status).

View Source
const (
	GrantTypeAuthorizationCode = "authorization_code"
	GrantTypeRefreshToken      = "refresh_token"
)

OAuth 2.1 grant types accepted by POST /oauth/token.

View Source
const (
	// ErrorCodeOAuthClientNotFound is an unknown or soft-deleted client.
	ErrorCodeOAuthClientNotFound = "oauth_client_not_found"
	// ErrorCodeOAuthAuthorizationNotFound is an unknown, expired or foreign
	// authorization request.
	ErrorCodeOAuthAuthorizationNotFound = "oauth_authorization_not_found"
	// ErrorCodeOAuthConsentNotFound is DELETE /user/oauth/grants for a client
	// the user never consented to.
	ErrorCodeOAuthConsentNotFound = "oauth_consent_not_found"
	// ErrorCodeOAuthDynamicClientRegistrationDisabled is POST
	// /oauth/clients/register while dynamic registration is off.
	ErrorCodeOAuthDynamicClientRegistrationDisabled = "oauth_dynamic_client_registration_disabled"
	// ErrorCodeFeatureDisabled is the 404 every route of a disabled feature
	// answers with (upstream requireOAuthServerEnabled).
	ErrorCodeFeatureDisabled = "feature_disabled"
)
View Source
const (
	// ErrorCodePasskeyDisabled is every /passkeys route while
	// Config.Passkeys.Enabled is false. Upstream answers 404 (not 422) — see
	// requirePasskeyEnabled.
	ErrorCodePasskeyDisabled = "passkey_disabled"
	// ErrorCodeTooManyPasskeys is a registration that would exceed
	// maxPasskeysPerUser (422).
	ErrorCodeTooManyPasskeys = "too_many_passkeys"

	// ErrorCodeWebAuthnCredentialNotFound is a credential the server does not
	// know (or does not know for this user).
	ErrorCodeWebAuthnCredentialNotFound = "webauthn_credential_not_found"
	// ErrorCodeWebAuthnChallengeNotFound is a challenge_id that never existed,
	// was already consumed, or belongs to a different ceremony/user.
	ErrorCodeWebAuthnChallengeNotFound = "webauthn_challenge_not_found"
	// ErrorCodeWebAuthnChallengeExpired is a challenge past its expires_at.
	ErrorCodeWebAuthnChallengeExpired = "webauthn_challenge_expired"
	// ErrorCodeWebAuthnVerificationFailed is a malformed or cryptographically
	// invalid attestation/assertion — wrong origin, wrong RP ID, bad signature.
	ErrorCodeWebAuthnVerificationFailed = "webauthn_verification_failed"
	// ErrorCodeWebAuthnCredentialExists is a credential_id that is already
	// registered (the unique index on webauthn_credentials.credential_id).
	ErrorCodeWebAuthnCredentialExists = "webauthn_credential_exists"
)

Passkey and WebAuthn error codes, copied verbatim from upstream internal/api/apierrors/errorcode.go. They live here (not in errors.go) so the passkey feature owns its own vocabulary, the way mfa_models.go owns the MFA codes.

View Source
const (
	// DefaultAppleIssuer / OtherAppleIssuer are upstream's two Apple issuers.
	DefaultAppleIssuer = "https://appleid.apple.com"
	OtherAppleIssuer   = "https://account.apple.com"
)
View Source
const (
	// ErrorCodeOverSMSSendRateLimit is the 429 of the SMS-sending endpoints
	// (the per-USER SMS.MaxFrequency throttle; the per-IP LimiterSMS bucket
	// answers with over_request_rate_limit).
	ErrorCodeOverSMSSendRateLimit = "over_sms_send_rate_limit"
	// ErrorCodeSMSSendFailed is upstream's 422 when the SMS provider rejects
	// the message.
	ErrorCodeSMSSendFailed = "sms_send_failed"
)

Error codes upstream declares in apierrors/errorcode.go. They live here rather than in errors.go because errors.go is shared and this wave owns the phone surface.

View Source
const (
	// ErrorCodeSAMLProviderDisabled is any /sso route while
	// GOTRUE_SAML_ENABLED is false (404 upstream, not 403).
	ErrorCodeSAMLProviderDisabled = "saml_provider_disabled"
	// ErrorCodeSAMLRelayStateNotFound is a RelayState UUID that names no row.
	ErrorCodeSAMLRelayStateNotFound = "saml_relay_state_not_found"
	// ErrorCodeSAMLRelayStateExpired is a RelayState older than
	// DefaultSAMLRelayStateValidityPeriod.
	ErrorCodeSAMLRelayStateExpired = "saml_relay_state_expired"
	// ErrorCodeSAMLIdPNotFound is an assertion from an EntityID no provider
	// has been registered for.
	ErrorCodeSAMLIdPNotFound = "saml_idp_not_found"
	// ErrorCodeSAMLAssertionNoUserID is an assertion without a persistent
	// subject identifier.
	ErrorCodeSAMLAssertionNoUserID = "saml_assertion_no_user_id"
	// ErrorCodeSAMLAssertionNoEmail is an assertion that carries no email
	// address, neither mapped nor guessed.
	ErrorCodeSAMLAssertionNoEmail = "saml_assertion_no_email"
	// ErrorCodeSSOProviderNotFound is POST /sso (or an admin route) naming an
	// SSO provider that does not exist.
	ErrorCodeSSOProviderNotFound = "sso_provider_not_found"
	// ErrorCodeSSOProviderDisabled is a provider whose `disabled` column is
	// true. Upstream answers 404, deliberately: a disabled provider must look
	// exactly like an absent one to an unauthenticated caller.
	ErrorCodeSSOProviderDisabled = "sso_provider_disabled"
	// ErrorCodeSAMLMetadataFetchFailed is a non-200 answer from metadata_url.
	ErrorCodeSAMLMetadataFetchFailed = "saml_metadata_fetch_failed"
	// ErrorCodeSAMLIdPAlreadyExists is a create whose metadata EntityID is
	// already registered.
	ErrorCodeSAMLIdPAlreadyExists = "saml_idp_already_exists"
	// ErrorCodeSSODomainAlreadyExists is a domain already assigned to another
	// provider.
	ErrorCodeSSODomainAlreadyExists = "sso_domain_already_exists"
	// ErrorCodeSAMLEntityIDMismatch is a metadata update that would change the
	// provider's EntityID.
	ErrorCodeSAMLEntityIDMismatch = "saml_entity_id_mismatch"
)
View Source
const (
	// RoleAuthenticated is the role claim of a signed-in end user.
	RoleAuthenticated = "authenticated"
	// RoleAnon is the role claim of the unauthenticated/public token.
	RoleAnon = "anon"
	// RoleServiceRole is the role claim that admits the /admin/* endpoints
	// unconditionally.
	RoleServiceRole = "service_role"

	// ActorTypeUser is the ports.Actor.Type of a regular user access token
	// acting through management-plane RBAC (mirrors iam.ActorTypeUser).
	ActorTypeUser = "user"
	// ActorTypeServiceRole is the ports.Actor.Type recorded for a service_role
	// JWT acting on /admin/* (mirrors iam.ActorTypeServiceRole).
	ActorTypeServiceRole = "service_role"
	// PermUsersAdmin is the RBAC permission that admits a user access token to
	// /admin/* (mirrors iam.PermUsersAdmin, seeded by migration 0303).
	PermUsersAdmin = "users.admin"
	// PermAuthSettingsManage (owner only, migration 0306) additionally gates
	// the instance's auth configuration: hooks, custom and SSO providers and
	// OAuth server clients (mirrors iam.PermAuthSettingsManage).
	PermAuthSettingsManage = "auth.settings.manage"
	// PermAuditRead additionally gates /admin/audit (mirrors iam.PermAuditRead).
	PermAuditRead = "audit.read"

	// AudienceAuthenticated is gotrue's default `aud`.
	AudienceAuthenticated = "authenticated"

	// DefaultAccessTokenTTL matches gotrue's default JWT_EXP (3600s).
	DefaultAccessTokenTTL = time.Hour

	// AlgES256 is the asymmetric signing algorithm Dilion uses. Upstream also
	// supports RS256/RS512/EdDSA; Dilion deliberately ships ES256 only — one
	// curve, small keys, small tokens (project decision, not upstream parity).
	AlgES256 = "ES256"
	// AlgHS256 is the legacy symmetric algorithm (GOTRUE_JWT_SECRET).
	AlgHS256 = "HS256"

	// IssuerPathSuffix is appended to SiteURL to build the default OIDC issuer
	// when GOTRUE_JWT_ISSUER / DILION_AUTH_JWT_ISSUER is not set. Upstream
	// defaults the issuer to API_EXTERNAL_URL + "/auth/v1"; Dilion has no
	// separate external-API URL, so SiteURL takes that role.
	IssuerPathSuffix = "/auth/v1"
)
View Source
const AMRMethodPasskey = "passkey"

AMRMethodPasskey is the authentication_method a passkey sign-in writes into auth.mfa_amr_claims, and therefore the entry that shows up in the JWT `amr` array. It is upstream models.PasskeyLogin.String() == "passkey".

It is deliberately NOT an aal2 method (see amrClaim.isAAL2Claim in mfa_models.go): a passkey is a sign-in method here, not a second factor, so a passkey session starts at aal1 exactly like a password session and is raised to aal2 only by verifying an MFA factor against it. That is upstream's behaviour too — PasskeyLogin is absent from AMRClaim.IsAAL2Claim.

View Source
const BcryptCost = 10

BcryptCost is the bcrypt work factor used for `auth.users.encrypted_password`. gotrue's default is 10; keeping the same cost means password hashes are interchangeable with an upstream Supabase deployment in both directions.

View Source
const (
	// DefaultSAMLRelayStateValidityPeriod mirrors
	// GOTRUE_SAML_RELAY_STATE_VALIDITY_PERIOD (upstream default 2 minutes,
	// set in conf.SAMLConfiguration.parseCertificateDer): the window in which
	// an IdP must post its assertion back after /sso started the flow.
	DefaultSAMLRelayStateValidityPeriod = 2 * time.Minute
)

Config.SAML only carries {Enabled, PrivateKey} (conf.go, which this feature must not extend), so the remaining upstream knobs are compiled in at their upstream default. Each one is an operator-visible value; if they ever need to become configurable, they belong on conf.SAMLConfiguration next to Enabled/PrivateKey, spelled GOTRUE_SAML_*.

View Source
const DuplicateEmailMessage = "A user with this email address has already been registered"

DuplicateEmailMessage is upstream's DuplicateEmailMsg.

View Source
const EnvPrefix = "DILION_AUTH_"

EnvPrefix is the preferred prefix of every Dilion auth environment variable.

View Source
const ErrorCodeCaptchaFailed = "captcha_failed"

ErrorCodeCaptchaFailed is upstream apierrors.ErrorCodeCaptchaFailed: the 400 returned when no captcha token was supplied or the provider rejected it.

It is declared here rather than in errors.go because that file is shared by every feature; the constant belongs to the feature that raises it.

View Source
const ErrorCodeCustomProviderNotFound = "custom_oauth_provider_not_found"

ErrorCodeCustomProviderNotFound is returned for an unknown {id}.

View Source
const HookRejection = "reject"

HookRejection is the `decision` value an MFA / password verification hook returns to abort the attempt (upstream v0hooks.HookRejection).

View Source
const InvalidLoginMessage = "Invalid login credentials"

InvalidLoginMessage is upstream's constant message for a failed password grant. It is deliberately identical for "no such user" and "wrong password" so the endpoint does not become a user-enumeration oracle.

View Source
const IssuerGoogle = "https://accounts.google.com"

IssuerGoogle is upstream's provider.IssuerGoogle.

View Source
const (

	// IssuerKakao is upstream's provider.IssuerKakao.
	IssuerKakao = "https://kauth.kakao.com"
)
View Source
const IssuerLinkedin = "https://www.linkedin.com/oauth"

IssuerLinkedin is upstream's provider.IssuerLinkedin.

View Source
const IssuerSlack = "https://slack.com"

IssuerSlack is upstream's provider.IssuerSlack.

View Source
const LegacyEnvPrefix = "GOTRUE_"

LegacyEnvPrefix is the upstream prefix accepted as a fallback so an existing gotrue environment keeps working during a migration.

View Source
const MaxPasswordLength = 72

MaxPasswordLength is upstream api.MaxPasswordLength: bcrypt ignores input past 72 bytes, so accepting a longer password would make distinct passwords equivalent.

View Source
const MinPasswordLength = 6

MinPasswordLength mirrors gotrue's default GOTRUE_PASSWORD_MIN_LENGTH.

View Source
const ProviderAnonymous = "anonymous"

ProviderAnonymous is the app_metadata provider of an anonymous user (upstream api.AnonymousProvider).

View Source
const ProviderEmail = "email"

ProviderEmail is the identity provider used for email/password accounts.

View Source
const ProviderPhone = "phone"

ProviderPhone is the identity provider used for phone/SMS accounts (upstream api.PhoneProvider).

View Source
const SAMLProviderType = "saml"

SAMLProviderType is the only `type` POST /admin/sso/providers accepts (upstream api.SAMLProvider).

View Source
const SAMLSubjectIDAttributeName = "urn:oasis:names:tc:SAML:attribute:subject-id"

SAMLSubjectIDAttributeName is the OASIS subject-id attribute, the preferred persistent identifier of a SAML 2.0 subject.

View Source
const Version = "0.1.0"

Version is reported by GET /health.

Variables

View Source
var ErrPasswordTooLong = errors.New("auth: password exceeds 72 bytes")

ErrPasswordTooLong is returned when a password exceeds bcrypt's 72-byte input limit (bytes beyond it are silently ignored by the algorithm, so accepting them would make distinct passwords equivalent).

View Source
var ErrSessionNotFound = errors.New("auth: session not found")

ErrSessionNotFound is LookupSessionAssurance's answer for a session that does not exist, has ended, or belongs to another user.

View Source
var ExternalProviders = []string{
	"apple", "azure", "bitbucket", "discord", "facebook", "snapchat", "figma",
	"fly", "github", "gitlab", "google", "keycloak", "kakao", "linkedin",
	"linkedin_oidc", "notion", "spotify", "slack", "slack_oidc", "workos",
	"twitch", "twitter", "email", "phone", "zoom",
}

ExternalProviders is the fixed set of provider keys reported by GET /settings. The order is the order of upstream's api.ProviderSettings struct; the strings are its json tags. `anonymous_users` is reported from Config.AnonymousUsersEnabled, not from this map.

Functions

func ComparePassword

func ComparePassword(hash, password string) error

ComparePassword reports whether password matches the stored bcrypt hash. It returns a non-nil error on mismatch (bcrypt.ErrMismatchedHashAndPassword).

func HashPassword

func HashPassword(password string) (string, error)

HashPassword returns a bcrypt hash suitable for auth.users.encrypted_password.

Types

type AccessTokenResponse

type AccessTokenResponse struct {
	Token        string `json:"access_token"`
	TokenType    string `json:"token_type"` // always "bearer"
	ExpiresIn    int    `json:"expires_in"`
	ExpiresAt    int64  `json:"expires_at"`
	RefreshToken string `json:"refresh_token"`
	User         *User  `json:"user"`
	// Provider tokens ride the PKCE exchange after an external OAuth flow
	// (upstream parity); empty otherwise.
	ProviderToken        string `json:"provider_token,omitempty"`
	ProviderRefreshToken string `json:"provider_refresh_token,omitempty"`

	// WeakPassword is upstream's sign-in advisory (tokens.AccessTokenResponse
	// .WeakPassword, set in api.ResourceOwnerPasswordGrant): the presented
	// credential DID authenticate, but it no longer satisfies the currently
	// configured strength rules. Upstream accepts the login and reports the
	// reasons here so a client can prompt for a password change; it does not
	// reject. Populated ONLY by the password grant — see passwordGrant.
	//
	// Deviation from upstream, catalogued as `token-weak-password-field` in
	// test/parity/deviations.yaml: upstream types this field `interface{}` and
	// assigns a typed nil pointer to it on every successful grant, which
	// defeats `omitempty` and puts a literal `"weak_password": null` in the
	// body. Dilion types it concretely, so a strong password simply omits the
	// key. Populated, the two are identical: {"message":…,"reasons":[…]}.
	WeakPassword *WeakPasswordError `json:"weak_password,omitempty"`

	// IDToken mirrors upstream tokens.AccessTokenResponse.IDToken
	// (`json:"id_token,omitempty"`, internal/tokens/service.go).
	//
	// It is ALWAYS EMPTY on this envelope, and that is upstream parity, not an
	// omission. Upstream declares one AccessTokenResponse type and shares it
	// between the session envelope and the OAuth-server token endpoint, but the
	// only assignment to the field in the whole tree is
	// internal/api/oauthserver/handlers.go:461, in handleAuthorizationCodeGrant
	// when the `openid` scope was granted — and that handler does not even
	// serialize the struct: it re-projects the four OAuth fields plus id_token
	// into a map before sending (handlers.go:470-482). No session-issuing path
	// — password, refresh_token, pkce, id_token, web3, external callback, MFA
	// verify, signup, verify — ever sets it, so `omitempty` keeps the key out
	// of every session body upstream serves.
	//
	// Dilion's OAuth-server token endpoint carries its own id_token on its own
	// response type (oauthserver_token.go OAuthTokenResponse.IDToken), which is
	// the structural equivalent of upstream's map. The field is mirrored here
	// so the two AccessTokenResponse shapes match field-for-field; populating
	// it from a session grant would be a divergence, not a fix.
	IDToken string `json:"id_token,omitempty"`
}

AccessTokenResponse is gotrue's session envelope, returned by /token and by /signup when confirmation is disabled.

type AdminAuditLogEntry

type AdminAuditLogEntry struct {
	ID        uuid.UUID      `json:"id"`
	Payload   map[string]any `json:"payload"`
	CreatedAt time.Time      `json:"created_at"`
	IPAddress string         `json:"ip_address"`
}

AdminAuditLogEntry is upstream's models.AuditLogEntry on the wire: the field names, order and types are the compatibility contract.

type AdminListUsersResponse

type AdminListUsersResponse struct {
	Users []*User `json:"users"`
	Aud   string  `json:"aud"`
}

AdminListUsersResponse is the GET /admin/users body. `aud` is deprecated upstream but still emitted.

type AdminUpdateFactorParams

type AdminUpdateFactorParams struct {
	FriendlyName string `json:"friendly_name"`
	Phone        string `json:"phone"`
}

AdminUpdateFactorParams is the PUT /admin/users/{user_id}/factors/{factor_id} body (upstream adminUserUpdateFactorParams).

type AdminUserDeleteParams

type AdminUserDeleteParams struct {
	ShouldSoftDelete bool `json:"should_soft_delete"`
}

AdminUserDeleteParams is the optional DELETE /admin/users/{user_id} body.

type AdminUserParams

type AdminUserParams struct {
	ID           string         `json:"id"`
	Aud          string         `json:"aud"`
	Role         string         `json:"role"`
	Email        string         `json:"email"`
	Phone        string         `json:"phone"`
	Password     *string        `json:"password"`
	EmailConfirm bool           `json:"email_confirm"`
	PhoneConfirm bool           `json:"phone_confirm"`
	UserMetaData map[string]any `json:"user_metadata"`
	AppMetaData  map[string]any `json:"app_metadata"`
	BanDuration  string         `json:"ban_duration"`
}

AdminUserParams is the POST/PUT /admin/users body (wave-1 subset).

type AfterUserCreatedInput

type AfterUserCreatedInput struct {
	Metadata *hookMetadata `json:"metadata"`
	User     *User         `json:"user"`
}

AfterUserCreatedInput is upstream v0hooks.AfterUserCreatedInput.

type AfterUserCreatedOutput

type AfterUserCreatedOutput struct{}

AfterUserCreatedOutput is upstream v0hooks.AfterUserCreatedOutput (empty).

type AuthorizationDetailsResponse

type AuthorizationDetailsResponse struct {
	AuthorizationID string                `json:"authorization_id"`
	RedirectURI     string                `json:"redirect_uri,omitempty"`
	Client          ClientDetailsResponse `json:"client,omitempty"`
	User            UserDetailsResponse   `json:"user,omitempty"`
	Scope           string                `json:"scope,omitempty"`
}

AuthorizationDetailsResponse is the GET /oauth/authorizations/{id} body.

type AuthorizeParams

type AuthorizeParams struct {
	ClientID     string `json:"client_id"`
	RedirectURI  string `json:"redirect_uri"`
	ResponseType string `json:"response_type"`
	Scope        string `json:"scope"`
	State        string `json:"state"`

	// Resource is the RFC 8707 resource indicator.
	Resource            string `json:"resource"`
	CodeChallenge       string `json:"code_challenge"`
	CodeChallengeMethod string `json:"code_challenge_method"`
	// Nonce is the OIDC nonce, replayed into the id_token.
	Nonce string `json:"nonce"`
}

AuthorizeParams are the /oauth/authorize request parameters (upstream oauthserver.AuthorizeParams).

type BeforeUserCreatedInput

type BeforeUserCreatedInput struct {
	Metadata *hookMetadata `json:"metadata"`
	User     *User         `json:"user"`
}

BeforeUserCreatedInput is upstream v0hooks.BeforeUserCreatedInput.

type BeforeUserCreatedOutput

type BeforeUserCreatedOutput struct{}

BeforeUserCreatedOutput is upstream v0hooks.BeforeUserCreatedOutput (empty; a rejection travels as the `error` object, not as a field here).

type CORSConfig

type CORSConfig struct {
	// AllowedHeaders mirrors GOTRUE_CORS_ALLOWED_HEADERS: EXTRA headers, added
	// to the built-in list (see corsAllowedHeaders in middleware.go).
	AllowedHeaders []string `json:"allowed_headers"`
}

CORSConfig mirrors upstream conf.CORSConfiguration.

type CaptchaConfig

type CaptchaConfig struct {
	// Enabled mirrors GOTRUE_SECURITY_CAPTCHA_ENABLED.
	Enabled bool `json:"enabled"`
	// Provider mirrors GOTRUE_SECURITY_CAPTCHA_PROVIDER: hcaptcha | turnstile.
	Provider string `json:"provider"`
	// Secret mirrors GOTRUE_SECURITY_CAPTCHA_SECRET.
	Secret string `json:"-"`
	// Timeout mirrors upstream conf.CaptchaConfiguration.Timeout
	// (GOTRUE_SECURITY_CAPTCHA_TIMEOUT, default 10s): the HTTP timeout of one
	// siteverify call.
	Timeout time.Duration `json:"-"`
	// VerifyURL has NO upstream equivalent: it overrides the provider's
	// siteverify endpoint. It exists so tests (and an operator fronting the
	// provider with a proxy) can point verification somewhere else; empty means
	// the provider's real endpoint.
	VerifyURL string `json:"-"`
}

CaptchaConfig mirrors upstream conf.CaptchaConfiguration. Enforced by captcha.go: Enabled gates the check, Provider selects the siteverify endpoint and Secret/Timeout/VerifyURL parameterise the call.

type ChallengeFactorParams

type ChallengeFactorParams struct {
	Channel string `json:"channel"`
}

ChallengeFactorParams is the POST /factors/{id}/challenge body.

type ChallengeFactorResponse

type ChallengeFactorResponse struct {
	ID        string `json:"id"`
	Type      string `json:"type"`
	ExpiresAt int64  `json:"expires_at,omitempty"`
	// WebAuthn carries the go-webauthn credential options for a webauthn factor
	// challenge (upstream ChallengeFactorResponse.WebAuthn). It is absent for
	// TOTP and phone.
	WebAuthn *WebAuthnChallengeData `json:"webauthn,omitempty"`
}

ChallengeFactorResponse is the POST /factors/{id}/challenge body.

type ClientDetailsResponse

type ClientDetailsResponse struct {
	ID      string `json:"id"`
	Name    string `json:"name,omitempty"`
	URI     string `json:"uri,omitempty"`
	LogoURI string `json:"logo_uri,omitempty"`
}

ClientDetailsResponse is the client block of the consent screen payload.

type Config

type Config struct {
	Opaque OpaqueConfig `json:"opaque"`
	// SiteURL mirrors GOTRUE_SITE_URL: the default redirect target and an
	// always-allowed redirect destination. Defaults to DefaultSiteURL.
	SiteURL string `json:"site_url"`
	// URIAllowList mirrors GOTRUE_URI_ALLOW_LIST: a comma-separated list of glob
	// patterns of additional allowed redirect URLs. See IsRedirectAllowed.
	URIAllowList []string `json:"uri_allow_list"`
	// DisableSignup mirrors GOTRUE_DISABLE_SIGNUP.
	DisableSignup bool `json:"disable_signup"`

	JWT      JWTConfig      `json:"jwt"`
	Mailer   MailerConfig   `json:"mailer"`
	SMS      SMSConfig      `json:"sms"`
	Sessions SessionsConfig `json:"sessions"`
	Security SecurityConfig `json:"security"`
	Password PasswordConfig `json:"password"`

	// RateLimits mirrors GOTRUE_RATE_LIMIT_*.
	RateLimits RateLimitConfig `json:"rate_limits"`

	// External mirrors GOTRUE_EXTERNAL_*, keyed by the provider names in
	// ExternalProviders. Every key of ExternalProviders is always present.
	External map[string]ProviderConfig `json:"external"`
	// FlowStateExpiry mirrors GOTRUE_EXTERNAL_FLOW_STATE_EXPIRY_DURATION
	// (default 5m). Enforced: pkce.go and external_callback.go reject an
	// auth code older than this with 422 flow_state_expired, and cleanup.go
	// sweeps the expired rows.
	FlowStateExpiry time.Duration `json:"flow_state_expiry"`

	MFA         MFAConfig         `json:"mfa"`
	Hooks       HooksConfig       `json:"hooks"`
	Passkeys    PasskeyConfig     `json:"passkeys"`
	SAML        SAMLConfig        `json:"saml"`
	OAuthServer OAuthServerConfig `json:"oauth_server"`
	CORS        CORSConfig        `json:"cors"`

	// CleanupEnabled mirrors GOTRUE_DB_CLEANUP_ENABLED (Dilion default TRUE;
	// upstream defaults to false because it piggybacks cleanup on requests).
	CleanupEnabled bool `json:"cleanup_enabled"`
	// CleanupInterval has no upstream equivalent (upstream runs cleanup from a
	// request middleware); Dilion runs a worker, default every 5m.
	CleanupInterval time.Duration `json:"cleanup_interval"`
	// APIMaxRequestDuration mirrors GOTRUE_API_MAX_REQUEST_DURATION (default 10s).
	APIMaxRequestDuration time.Duration `json:"api_max_request_duration"`
	// AnonymousUsersEnabled mirrors GOTRUE_EXTERNAL_ANONYMOUS_USERS_ENABLED
	// (default false): POST /signup with neither email nor phone.
	AnonymousUsersEnabled bool `json:"anonymous_users_enabled"`
	// contains filtered or unexported fields
}

Config is the whole /auth/v1 configuration. Construct it with LoadConfig (env) or DefaultConfig (defaults only) — never as a bare literal, or the compiled redirect allow-list will be empty.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns the configuration used when the embedder supplies none: upstream defaults, with the Dilion deviations documented on each field.

func LoadConfig

func LoadConfig() (*Config, error)

LoadConfig builds the configuration from the environment on top of DefaultConfig. Every parse or validation failure is returned as an error: a mis-typed auth configuration must be fatal at boot, never silently ignored.

func (*Config) IsRedirectAllowed

func (c *Config) IsRedirectAllowed(redirectURL string) bool

IsRedirectAllowed reports whether redirectURL may be used as a redirect target. It reproduces upstream utilities.IsRedirectURLValid exactly:

  • the empty string is never allowed;
  • a URL with the same scheme+host as SiteURL is allowed; the PORT must match too, except for loopback hosts (RFC 8252 §7.3 native apps);
  • a host in decimal-integer form (http://2130706433/) is never allowed;
  • any other IP literal is allowed only if it is a loopback address;
  • an http(s) URL whose hostname contains unusual characters is rejected;
  • otherwise the URL — WITHOUT its #fragment — must match one URIAllowList glob, where `.` and `/` are separators: `*` does not cross them, `**` does.

func (*Config) RedirectURLOrSiteURL

func (c *Config) RedirectURLOrSiteURL(candidates ...string) string

RedirectURLOrSiteURL is upstream's utilities.GetReferrer decision: the caller supplied redirect_to when it is allowed, otherwise the referrer when it is allowed, otherwise SiteURL. Feature agents building email links call this.

func (*Config) Validate

func (c *Config) Validate() error

Validate normalizes and checks the configuration, and compiles the redirect allow-list. It is called by LoadConfig and by newAPI, so an embedder-supplied Config is always usable.

type ConsentRequest

type ConsentRequest struct {
	Action OAuthConsentAction `json:"action"`
}

ConsentRequest is the POST .../consent body.

type ConsentResponse

type ConsentResponse struct {
	RedirectURL string `json:"redirect_url,omitempty"`
}

ConsentResponse is what the consent UI receives: the URL it must send the browser back to. Upstream returns it from both the consent POST and the auto-approve branch of the authorization GET.

type CreateSSOProviderParams

type CreateSSOProviderParams struct {
	Type string `json:"type"`

	MetadataURL      string               `json:"metadata_url"`
	MetadataXML      string               `json:"metadata_xml"`
	Domains          []string             `json:"domains"`
	AttributeMapping SAMLAttributeMapping `json:"attribute_mapping"`
	NameIDFormat     string               `json:"name_id_format"`

	ResourceID *string `json:"resource_id,omitempty"`
	Disabled   *bool   `json:"disabled,omitempty"`
}

CreateSSOProviderParams is the POST and PUT /admin/sso/providers body (upstream api.CreateSSOProviderParams).

type CustomAccessTokenInput

type CustomAccessTokenInput struct {
	Metadata             *hookMetadata  `json:"metadata"`
	UserID               string         `json:"user_id"`
	Claims               map[string]any `json:"claims"`
	AuthenticationMethod string         `json:"authentication_method"`
}

CustomAccessTokenInput is upstream v0hooks.CustomAccessTokenInput. Claims is the full claim view of the token about to be signed (a superset of the JWT registered claims plus gotrue's email/phone/app_metadata/... members), exactly what upstream's AccessTokenClaims marshals to.

type CustomAccessTokenOutput

type CustomAccessTokenOutput struct {
	Claims map[string]any `json:"claims"`
}

CustomAccessTokenOutput is upstream v0hooks.CustomAccessTokenOutput. The returned Claims map becomes the token's claims. Upstream fails when the field is missing; UnmarshalJSON reproduces that so a hook that returns `{}` is a hard error rather than a silently empty token.

func (*CustomAccessTokenOutput) UnmarshalJSON

func (o *CustomAccessTokenOutput) UnmarshalJSON(b []byte) error

UnmarshalJSON mirrors upstream's CustomAccessTokenOutput.UnmarshalJSON: a response missing the `claims` field is an internal error.

type CustomOAuthProviderParams

type CustomOAuthProviderParams struct {
	ProviderType          string         `json:"provider_type"`
	Identifier            string         `json:"identifier"`
	Name                  string         `json:"name"`
	ClientID              string         `json:"client_id"`
	ClientSecret          string         `json:"client_secret"`
	AcceptableClientIDs   []string       `json:"acceptable_client_ids"`
	Scopes                []string       `json:"scopes"`
	PKCEEnabled           *bool          `json:"pkce_enabled"`
	AttributeMapping      map[string]any `json:"attribute_mapping"`
	AuthorizationParams   map[string]any `json:"authorization_params"`
	CustomClaimsAllowlist []string       `json:"custom_claims_allowlist"`
	Enabled               *bool          `json:"enabled"`
	EmailOptional         *bool          `json:"email_optional"`

	// OIDC
	Issuer         string `json:"issuer"`
	DiscoveryURL   string `json:"discovery_url"`
	SkipNonceCheck *bool  `json:"skip_nonce_check"`

	// OAuth2
	AuthorizationURL string `json:"authorization_url"`
	TokenURL         string `json:"token_url"`
	UserinfoURL      string `json:"userinfo_url"`
	JwksURI          string `json:"jwks_uri"`
}

CustomOAuthProviderParams is the POST/PUT body. Pointer fields distinguish an absent key (keep the default / existing value) from an explicit zero value.

type Deps

type Deps struct {
	// Pool is the fixed database of a single-instance deployment.
	Pool *pgxpool.Pool
	// Pools resolves the database per request and takes precedence over Pool.
	// Multi-instance deployments set it to instances.Registry.Pool.
	Pools PoolFunc
	// Tokens is the fixed token service of a single-instance deployment.
	Tokens *TokenService
	// TokensFor resolves the token service per request and takes precedence
	// over Tokens. Multi-instance deployments set it to
	// instances.Registry.Tokens, so every instance signs and verifies with
	// its own key material.
	TokensFor TokenFunc
	Mailer    ports.Mailer
	Hooks     *hooks.Registry

	// Config is the /auth/v1 configuration (conf.go). It is optional: when nil
	// DefaultConfig() is used, which keeps every embedder that predates the
	// configuration surface working unchanged. Handlers must treat it as
	// read-only — it is shared by every request.
	Config *Config

	// Authz is optional. When set, /admin/* additionally accepts a regular user
	// access token (role=authenticated) that holds the `users.admin` permission
	// (project.md §2.11). When nil the surface stays service_role-only, which is
	// the historical behaviour embedders may rely on.
	Authz ports.Authorizer

	// Providers defines external OIDC providers in code (ports.ProviderSource).
	// Optional; when set it is consulted before the built-in providers and
	// auth.custom_oauth_providers.
	Providers ports.ProviderSource

	// OAuthClients decides the OAuth 2.1 server's clients in code
	// (ports.OAuthClientResolver). Optional; when set it is consulted before
	// auth.oauth_clients.
	OAuthClients ports.OAuthClientResolver

	// TrustedProxies are the proxies whose X-Forwarded-For is believed
	// (netguard.ClientIP); the zero value trusts none, so the peer address is
	// the client.
	TrustedProxies netguard.Networks

	// OutboundNetworks are the private networks that calls to URLs instance
	// admins configure (hooks, custom and SSO providers) may reach; nil
	// means none. Code-defined providers are not guarded.
	OutboundNetworks *netguard.Networks

	// AdminMFADisabled lets a user token administer without an aal2 session
	// (dilion.WithoutAdminMFA). Development only.
	AdminMFADisabled bool

	// Settings sets each instance's site URL and redirect allow list
	// (ports.AuthSettingsSource). Optional; without it every instance uses
	// Config's.
	Settings ports.AuthSettingsSource

	// Audit is optional. When set, the /admin/users surface records an access
	// event per request (안전성 확보조치 기준 제8조 접속기록, project.md §5). When nil
	// nothing is recorded — embedders that mount this package standalone keep
	// working. Auditing here is deliberately FAIL-OPEN: an audit sink is an
	// observability dependency, so a sink failure is logged at WARN and the
	// request still succeeds (see emitAudit).
	Audit ports.AuditSink

	// Logger is optional; slog.Default() is used when nil.
	Logger *slog.Logger
	// Clock is optional; ports.SystemClock is used when nil.
	Clock ports.Clock
}

Deps are the collaborators injected by the embedder. One of Pool / Pools and Tokens are required; Mailer, Hooks and Logger are optional and default to no-ops.

type EmailContentConfig

type EmailContentConfig struct {
	Invite           string `json:"invite"`
	Confirmation     string `json:"confirmation"`
	Recovery         string `json:"recovery"`
	EmailChange      string `json:"email_change"`
	MagicLink        string `json:"magic_link"`
	Reauthentication string `json:"reauthentication"`
}

EmailContentConfig mirrors upstream conf.EmailContentConfiguration; used for both Subjects (GOTRUE_MAILER_SUBJECTS_*) and URLPaths (GOTRUE_MAILER_URLPATHS_*).

type EmailData

type EmailData struct {
	Token           string `json:"token"`
	TokenHash       string `json:"token_hash"`
	RedirectTo      string `json:"redirect_to"`
	EmailActionType string `json:"email_action_type"`
	SiteURL         string `json:"site_url"`
	TokenNew        string `json:"token_new"`
	TokenHashNew    string `json:"token_hash_new"`
	OldEmail        string `json:"old_email,omitempty"`
	OldPhone        string `json:"old_phone,omitempty"`
	Provider        string `json:"provider,omitempty"`
	FactorType      string `json:"factor_type,omitempty"`
}

EmailData is upstream mailer.EmailData: everything a send_email hook needs to render and deliver the message itself. Field order and tags are upstream's.

type EnrollFactorParams

type EnrollFactorParams struct {
	FriendlyName string `json:"friendly_name"`
	FactorType   string `json:"factor_type"`
	Issuer       string `json:"issuer"`
	Phone        string `json:"phone"`
}

EnrollFactorParams is the POST /factors body.

type EnrollFactorResponse

type EnrollFactorResponse struct {
	ID           string      `json:"id"`
	Type         string      `json:"type"`
	FriendlyName string      `json:"friendly_name"`
	TOTP         *TOTPObject `json:"totp,omitempty"`
	Phone        string      `json:"phone,omitempty"`
}

EnrollFactorResponse is the POST /factors body.

type Factor

type Factor struct {
	ID               string     `json:"id"`
	CreatedAt        time.Time  `json:"created_at"`
	UpdatedAt        time.Time  `json:"updated_at"`
	Status           string     `json:"status"`
	FriendlyName     string     `json:"friendly_name,omitempty"`
	FactorType       string     `json:"factor_type"`
	Phone            string     `json:"phone"`
	LastChallengedAt *time.Time `json:"last_challenged_at"`

	// WebAuthnAAGUID is auth.mfa_factors.web_authn_aaguid: the model identifier
	// the authenticator reported when the webauthn factor was registered
	// (upstream models.Factor.WebAuthnAAGUID, written by SaveWebAuthnCredential
	// — see updateFactorWebAuthnCredential). Upstream types it *uuid.UUID with
	// `omitempty`, which for a pointer means "absent when nil"; a *string
	// serialises identically. Always nil on a totp/phone factor, and on a
	// webauthn factor whose authenticator declined to identify its model (the
	// all-zero AAGUID is stored as NULL — see formatUUIDBytes).
	WebAuthnAAGUID *string `json:"web_authn_aaguid,omitempty"`

	// LastWebAuthnChallengeData is auth.mfa_factors.last_webauthn_challenge_data
	// (upstream models.Factor.LastWebAuthnChallengeData, migration
	// 20250925093508_add_last_webauthn_challenge_data). Upstream writes it on
	// EVERY webauthn verify — registration and assertion alike — and, having no
	// `json:"-"`, returns it from every endpoint that serialises a factor. See
	// updateFactorLastWebAuthnChallenge.
	LastWebAuthnChallengeData *LastWebAuthnChallengeData `json:"last_webauthn_challenge_data,omitempty"`

	// DB-only. The TOTP secret NEVER leaves the server after enrolment.
	UserID string `json:"-"`
	Secret string `json:"-"`
}

Factor is the auth.mfa_factors row as gotrue serialises it. FIELD ORDER and json tags follow upstream models.Factor; the columns Dilion does not implement (WebAuthn credential blobs) are simply absent.

func (*Factor) IsUnverified

func (f *Factor) IsUnverified() bool

func (*Factor) IsVerified

func (f *Factor) IsVerified() bool

IsVerified / IsUnverified mirror upstream's helpers.

type GenerateLinkParams

type GenerateLinkParams struct {
	Type       string         `json:"type"`
	Email      string         `json:"email"`
	NewEmail   string         `json:"new_email"`
	Password   string         `json:"password"`
	Data       map[string]any `json:"data"`
	RedirectTo string         `json:"redirect_to"`
}

GenerateLinkParams is the POST /admin/generate_link body (upstream api.GenerateLinkParams).

type GenerateLinkResponse

type GenerateLinkResponse struct {
	User
	ActionLink       string `json:"action_link"`
	EmailOtp         string `json:"email_otp"`
	HashedToken      string `json:"hashed_token"`
	VerificationType string `json:"verification_type"`
	RedirectTo       string `json:"redirect_to"`
}

GenerateLinkResponse is upstream's GenerateLinkResponse: the user object FLATTENED (User is embedded, not nested) plus the link material.

type HTTPError

type HTTPError struct {
	HTTPStatus int    `json:"code"`                 // do not rename the JSON tags!
	ErrorCode  string `json:"error_code,omitempty"` // do not rename the JSON tags!
	Message    string `json:"msg"`                  // do not rename the JSON tags!
	// contains filtered or unexported fields
}

HTTPError is the gotrue error body. The JSON tags are part of the compatibility contract — do not rename them.

{"code": 400, "error_code": "validation_failed", "msg": "..."}

func (*HTTPError) Error

func (e *HTTPError) Error() string

func (*HTTPError) MarshalJSON

func (e *HTTPError) MarshalJSON() ([]byte, error)

MarshalJSON renders the gotrue error body, plus upstream's `weak_password` payload when the error carries a *WeakPasswordError cause.

Field order and tags are unchanged for every other error:

{"code":400,"error_code":"validation_failed","msg":"..."}

func (*HTTPError) Unwrap

func (e *HTTPError) Unwrap() error

type HealthCheckResponse

type HealthCheckResponse struct {
	Version     string `json:"version"`
	Name        string `json:"name"`
	Description string `json:"description"`
}

HealthCheckResponse is the GET /health body.

type HookEndpointConfig

type HookEndpointConfig struct {
	// Enabled mirrors GOTRUE_HOOK_<NAME>_ENABLED (default false).
	Enabled bool `json:"enabled"`
	// URI mirrors GOTRUE_HOOK_<NAME>_URI (http(s):// or pg-functions://...).
	URI string `json:"uri"`
	// Secrets mirrors GOTRUE_HOOK_<NAME>_SECRETS (v1,whsec_... — HMAC signing).
	// Several secrets, for rotation, are separated by "|" as upstream does: a
	// secret itself contains a comma. HTTP driver only.
	Secrets []string `json:"-"`
	// Locked (DILION_AUTH_HOOK_<NAME>_LOCKED, Dilion extension) keeps this
	// setting in force for every instance: /admin/hooks cannot replace or
	// disable it, and any instance setting already stored is ignored.
	Locked bool `json:"locked"`
	// contains filtered or unexported fields
}

HookEndpointConfig configures one Supabase-compatible auth hook. A hook is an external extension point invoked at a fixed lifecycle moment; the URI scheme selects the driver: https?:// -> HTTP webhook (HMAC-signed with Secrets), pg-functions://<db>/<schema>.<func> -> a Postgres function called in-tx. Both drivers are implemented (hooks_http.go, hooks_pg.go) and dispatched from hooks_ext.go; Enabled/URI/Secrets are all consumed there.

This is the server-wide setting. An instance admin can replace it for their own instance through /admin/hooks (hooks_instance.go) unless Locked is set.

type HookSettingParams added in v0.0.5

type HookSettingParams struct {
	Enabled *bool     `json:"enabled"`
	URI     string    `json:"uri"`
	Secrets *[]string `json:"secrets"`
}

HookSettingParams is the PUT body. secrets absent keeps the ones stored; present (even empty) replaces them.

type HooksConfig

type HooksConfig struct {
	// CustomAccessToken mirrors GOTRUE_HOOK_CUSTOM_ACCESS_TOKEN_* — rewrites the
	// access-token claims before signing (in addition to the in-process
	// ports.TokenClaims hook).
	CustomAccessToken HookEndpointConfig `json:"custom_access_token"`
	// SendEmail mirrors GOTRUE_HOOK_SEND_EMAIL_* — overrides email delivery.
	SendEmail HookEndpointConfig `json:"send_email"`
	// SendSMS mirrors GOTRUE_HOOK_SEND_SMS_* — overrides SMS delivery.
	SendSMS HookEndpointConfig `json:"send_sms"`
	// BeforeUserCreated mirrors GOTRUE_HOOK_BEFORE_USER_CREATED_* — may reject a
	// signup before the row is written.
	BeforeUserCreated HookEndpointConfig `json:"before_user_created"`
	// AfterUserCreated mirrors GOTRUE_HOOK_AFTER_USER_CREATED_* — observes a new
	// user post-commit.
	AfterUserCreated HookEndpointConfig `json:"after_user_created"`
	// MFAVerificationAttempt mirrors GOTRUE_HOOK_MFA_VERIFICATION_ATTEMPT_* —
	// may reject an MFA challenge verification.
	MFAVerificationAttempt HookEndpointConfig `json:"mfa_verification_attempt"`
	// PasswordVerificationAttempt mirrors
	// GOTRUE_HOOK_PASSWORD_VERIFICATION_ATTEMPT_* — observes/limits a password
	// check.
	PasswordVerificationAttempt HookEndpointConfig `json:"password_verification_attempt"`
}

HooksConfig mirrors upstream conf.HookConfiguration. Each field is one hook point Supabase exposes to external code, and all seven are enforced: CustomAccessToken in auth.go, the other six in hooks_ext.go.

type IDTokenClaims

type IDTokenClaims struct {
	jwt.RegisteredClaims
	Nonce               string `json:"nonce,omitempty"`
	AuthTime            int64  `json:"auth_time"`
	Email               string `json:"email,omitempty"`
	EmailVerified       bool   `json:"email_verified"`
	PhoneNumber         string `json:"phone_number,omitempty"`
	PhoneNumberVerified bool   `json:"phone_number_verified"`
	Name                string `json:"name,omitempty"`
	Picture             string `json:"picture,omitempty"`
	UpdatedAt           int64  `json:"updated_at,omitempty"`
	PreferredUsername   string `json:"preferred_username,omitempty"`
	ClientID            string `json:"client_id,omitempty"`
}

IDTokenClaims are the OIDC ID Token claims (upstream tokens.IDTokenClaims). `email_verified` and `phone_number_verified` are NOT omitempty: OIDC requires them whenever their scope was granted, including when they are false.

type IDTokenGrantParams

type IDTokenGrantParams struct {
	IDToken      string `json:"id_token"`
	AccessToken  string `json:"access_token"`
	Nonce        string `json:"nonce"`
	Provider     string `json:"provider"`
	ClientID     string `json:"client_id"`
	Issuer       string `json:"issuer"`
	LinkIdentity bool   `json:"link_identity"`
}

IDTokenGrantParams is the POST /token?grant_type=id_token body (upstream api.IdTokenGrantParams).

type Identity

type Identity struct {
	ID           string     `json:"identity_id"`
	ProviderID   string     `json:"id"`
	UserID       string     `json:"user_id"`
	IdentityData JSONMap    `json:"identity_data,omitempty"`
	Provider     string     `json:"provider"`
	LastSignInAt *time.Time `json:"last_sign_in_at,omitempty"`
	CreatedAt    time.Time  `json:"created_at"`
	UpdatedAt    time.Time  `json:"updated_at"`
	Email        string     `json:"email,omitempty"`
}

Identity is gotrue's models.Identity. Note the deliberately crossed json tags: the DB primary key `id` is exposed as `identity_id`, and `provider_id` as `id` — required for compatibility with gotrue-js's Identity type.

type InviteParams

type InviteParams struct {
	Email      string         `json:"email"`
	Data       map[string]any `json:"data"`
	RedirectTo string         `json:"redirect_to"`
}

InviteParams is the POST /invite body (upstream api.InviteParams).

type JSONMap

type JSONMap map[string]any

JSONMap mirrors gotrue's models.JSONMap (raw_app_meta_data / raw_user_meta_data).

type JWK

type JWK struct {
	KeyType   string   `json:"kty"`
	KeyID     string   `json:"kid"`
	Algorithm string   `json:"alg"`
	Use       string   `json:"use"`
	KeyOps    []string `json:"key_ops"`

	// EC (ES256) members.
	Curve string `json:"crv,omitempty"`
	X     string `json:"x,omitempty"`
	Y     string `json:"y,omitempty"`
	D     string `json:"d,omitempty"`

	// RSA / oct members, decoded so a foreign key set round-trips.
	N string `json:"n,omitempty"`
	E string `json:"e,omitempty"`
	K string `json:"k,omitempty"`

	// Raw is the key exactly as it appeared in GOTRUE_JWT_KEYS.
	Raw json.RawMessage `json:"-"`
}

JWK is one JSON Web Key of GOTRUE_JWT_KEYS. Only the fields Dilion needs to route a key are decoded; Raw keeps the original JSON so the signing implementation can parse it with whatever library it wants without losing members (`aws:kms:arn`, `x5c`, ...).

func (JWK) CanSign

func (k JWK) CanSign() bool

CanSign reports whether key_ops contains "sign" (upstream's signing-key rule).

type JWKSet

type JWKSet struct {
	Keys  map[string]JWK
	Order []string
}

JWKSet is the parsed GOTRUE_JWT_KEYS: a JSON ARRAY of private JWKs, indexed here by `kid`. Order preserves the array order so /.well-known/jwks.json can be emitted deterministically.

func ParseJWKSet added in v0.0.4

func ParseJWKSet(raw string) (JWKSet, error)

parseJWKSet decodes GOTRUE_JWT_KEYS: a JSON array of private JWKs. ParseJWKSet decodes the GOTRUE_JWT_KEYS / ports.JWTKeys.Keys form: a JSON array of private JWKs, each with a unique kid.

func (JWKSet) JSON added in v0.0.4

func (s JWKSet) JSON() json.RawMessage

JSON renders the set back into the GOTRUE_JWT_KEYS wire form — a JSON array of the keys exactly as they were configured, in order — which is the shape ports.JWTKeys.Keys carries per instance. nil for an empty set.

func (JWKSet) Len

func (s JWKSet) Len() int

Len reports how many keys were configured.

func (JWKSet) SigningKey

func (s JWKSet) SigningKey() (JWK, bool)

SigningKey returns the single private key whose key_ops contains "sign" — upstream's active `kid`. Absent when no key set is configured (HS256 mode).

type JWTConfig

type JWTConfig struct {
	// Exp mirrors GOTRUE_JWT_EXP: access-token lifetime in seconds (default 3600).
	Exp int `json:"exp"`
	// Aud mirrors GOTRUE_JWT_AUD (default "authenticated").
	Aud string `json:"aud"`
	// AdminRoles mirrors GOTRUE_JWT_ADMIN_ROLES; roles admitted to /admin/*
	// unconditionally (default ["service_role", "supabase_admin"]).
	AdminRoles []string `json:"admin_roles"`
	// Issuer mirrors GOTRUE_JWT_ISSUER; empty means no `iss` claim. When set
	// it is minted into every token AND required by Verify (a token with a
	// different or missing `iss` is rejected). Multi-instance deployments
	// supply it per instance through ports.JWTKeys.
	Issuer string `json:"issuer"`
	// KeyID mirrors GOTRUE_JWT_KEY_ID. Advisory: the active key is the one whose
	// key_ops contains "sign" (see JWKSet.SigningKey).
	KeyID string `json:"key_id"`
	// Keys mirrors GOTRUE_JWT_KEYS — a JSON array of PRIVATE JWKs. Dilion signs
	// with ES256 (NOT RS256) when a key set is configured.
	//
	// FIELDS + PARSING ONLY here: asymmetric signing itself is implemented by
	// the JWT/ES256 feature work, which reads this field.
	Keys JWKSet `json:"-"`
	// Secret mirrors GOTRUE_JWT_SECRET: the legacy HS256 shared secret. It stays
	// a valid VERIFY key even after ES256 signing is enabled, so tokens issued
	// before a key rotation keep working.
	Secret string `json:"-"`
}

JWTConfig mirrors upstream conf.JWTConfiguration.

func (JWTConfig) ExpDuration

func (j JWTConfig) ExpDuration() time.Duration

ExpDuration returns Exp as a duration.

type JwksResponse

type JwksResponse struct {
	Keys []PublicJWK `json:"keys"`
}

JwksResponse is the GET /.well-known/jwks.json body (upstream api.JwksResponse).

type LastWebAuthnChallengeData

type LastWebAuthnChallengeData struct {
	// Challenge is the challenge row as it stood when the ceremony was
	// validated, BEFORE it was consumed.
	Challenge MFAChallengeRecord `json:"challenge"`
	// Type is the ceremony: "create" (registration) or "request" (assertion).
	Type string `json:"type"`
	// CredentialResponse is the PARSED authenticator response, exactly as
	// upstream stores it: go-webauthn's ParsedCredentialCreationData /
	// ParsedCredentialAssertionData marshalled to JSON — not the raw body the
	// client posted.
	CredentialResponse json.RawMessage `json:"credential_response"`
}

LastWebAuthnChallengeData is the jsonb document stored on auth.mfa_factors.last_webauthn_challenge_data, copied field-for-field from upstream models.LastWebAuthnChallengeData:

Challenge          Challenge       `json:"challenge"`
Type               string          `json:"type"`
CredentialResponse json.RawMessage `json:"credential_response"`

It is a forensic record of the last WebAuthn ceremony the factor completed — upstream's column comment calls it "the latest WebAuthn challenge data including attestation/assertion for customer verification". Nothing in the request path ever reads it back; it exists to be served.

type MFAChallengeRecord

type MFAChallengeRecord struct {
	ID                  string          `json:"challenge_id"`
	FactorID            string          `json:"factor_id"`
	CreatedAt           time.Time       `json:"created_at"`
	VerifiedAt          *time.Time      `json:"verified_at,omitempty"`
	IPAddress           string          `json:"ip_address"`
	WebAuthnSessionData json.RawMessage `json:"web_authn_session_data,omitempty"`
}

MFAChallengeRecord is the JSON projection of an auth.mfa_challenges row, mirroring upstream models.Challenge's json tags (note `challenge_id`, not `id`). It exists only as the `challenge` member of LastWebAuthnChallengeData.

Upstream's Challenge additionally carries `factor` and `otp_code`, both `omitempty`: `factor` is nil unless the row was eager-loaded (it is not on this path) and `otp_code` is empty on a webauthn challenge, so both are absent from upstream's stored document too. Omitting the fields here yields byte-identical JSON.

type MFAConfig

type MFAConfig struct {
	// TOTP mirrors GOTRUE_MFA_TOTP_*.
	TOTP MFATOTPConfig `json:"totp"`
	// Phone mirrors GOTRUE_MFA_PHONE_* (SMS-delivered MFA factor). Default off.
	Phone MFAFactorTypeConfig `json:"phone"`
	// WebAuthn mirrors GOTRUE_MFA_WEB_AUTHN_* (WebAuthn as a second factor,
	// distinct from first-class Passkeys). Default off.
	WebAuthn MFAFactorTypeConfig `json:"web_authn"`
	// MaxEnrolledFactors mirrors GOTRUE_MFA_MAX_ENROLLED_FACTORS (default 10).
	MaxEnrolledFactors int `json:"max_enrolled_factors"`
	// PhoneOTPLength / PhoneOTPExp mirror the MFA phone challenge OTP shape
	// (default 6 / 300s).
	PhoneOTPLength int           `json:"phone_otp_length"`
	PhoneOTPExp    time.Duration `json:"phone_otp_exp"`
}

MFAConfig mirrors upstream conf.MFAConfiguration. Every field is enforced: the per-type gates and MaxEnrolledFactors in factors.go, the OTP shape in factors_phone.go.

type MFAFactorTypeConfig

type MFAFactorTypeConfig struct {
	// EnrollEnabled mirrors GOTRUE_MFA_<TYPE>_ENROLL_ENABLED (default false).
	EnrollEnabled bool `json:"enroll_enabled"`
	// VerifyEnabled mirrors GOTRUE_MFA_<TYPE>_VERIFY_ENABLED (default false).
	VerifyEnabled bool `json:"verify_enabled"`
}

MFAFactorTypeConfig mirrors upstream's per-factor enroll/verify toggle (conf.MFAFactorTypeConfiguration), used by the phone and webauthn factors.

type MFATOTPConfig

type MFATOTPConfig struct {
	// EnrollEnabled mirrors GOTRUE_MFA_TOTP_ENROLL_ENABLED (default true).
	EnrollEnabled bool `json:"enroll_enabled"`
	// VerifyEnabled mirrors GOTRUE_MFA_TOTP_VERIFY_ENABLED (default true).
	VerifyEnabled bool `json:"verify_enabled"`
}

MFATOTPConfig mirrors upstream conf.TOTPFactorTypeConfiguration. Enforced by factors.go (enroll and verify gates for the TOTP factor).

type MFAVerificationAttemptInput

type MFAVerificationAttemptInput struct {
	Metadata   *hookMetadata `json:"metadata"`
	UserID     string        `json:"user_id"`
	FactorID   string        `json:"factor_id"`
	FactorType string        `json:"factor_type"`
	Valid      bool          `json:"valid"`
}

MFAVerificationAttemptInput is upstream v0hooks.MFAVerificationAttemptInput.

type MFAVerificationAttemptOutput

type MFAVerificationAttemptOutput struct {
	Decision string `json:"decision"`
	Message  string `json:"message"`
}

MFAVerificationAttemptOutput is upstream v0hooks.MFAVerificationAttemptOutput.

type MagicLinkParams

type MagicLinkParams struct {
	Email               string         `json:"email"`
	Data                map[string]any `json:"data"`
	CodeChallengeMethod string         `json:"code_challenge_method"`
	CodeChallenge       string         `json:"code_challenge"`
	RedirectTo          string         `json:"redirect_to"`
}

MagicLinkParams is the POST /magiclink body (upstream api.MagicLinkParams).

type MailerConfig

type MailerConfig struct {
	// Autoconfirm mirrors GOTRUE_MAILER_AUTOCONFIRM (default false, as
	// upstream): a new address is confirmed by the link mailed to it.
	Autoconfirm bool `json:"autoconfirm"`
	// SecureEmailChangeEnabled mirrors
	// GOTRUE_MAILER_SECURE_EMAIL_CHANGE_ENABLED (default true): an email change
	// must be confirmed from BOTH the old and the new address.
	SecureEmailChangeEnabled bool `json:"secure_email_change_enabled"`
	// OTPExp mirrors GOTRUE_MAILER_OTP_EXP, in seconds.
	//
	// DILION DEFAULT: 3600 (upstream defaults to 86400). A one-hour email OTP is
	// the tighter, and for 개인정보보호법 purposes the defensible, default.
	OTPExp int `json:"otp_exp"`
	// OTPLength mirrors GOTRUE_MAILER_OTP_LENGTH (default 6, clamped to 6..10).
	OTPLength int `json:"otp_length"`
	// Subjects mirrors GOTRUE_MAILER_SUBJECTS_*.
	Subjects EmailContentConfig `json:"subjects"`
	// URLPaths mirrors GOTRUE_MAILER_URLPATHS_* (defaults: "/verify").
	URLPaths EmailContentConfig `json:"url_paths"`
	// ExternalHosts mirrors GOTRUE_MAILER_EXTERNAL_HOSTS: extra Host values the
	// API answers on, used to build absolute links in emails.
	ExternalHosts []string `json:"external_hosts"`
	// MaxFrequency is the minimum interval between two mails of the SAME type
	// to the SAME user (upstream's validateSentWithinFrequencyLimit). Default
	// 1m, upstream's default too.
	//
	// UPSTREAM NAMING: gotrue houses this knob under its SMTP section
	// (GOTRUE_SMTP_MAX_FREQUENCY) because upstream owns the SMTP client;
	// Dilion delegates delivery to ports.Mailer and has no SMTP section, so the
	// knob lives on the mailer instead. BOTH env names are read:
	// DILION_AUTH_MAILER_MAX_FREQUENCY / GOTRUE_MAILER_MAX_FREQUENCY take
	// precedence, GOTRUE_SMTP_MAX_FREQUENCY (upstream's spelling) is the
	// fallback.
	//
	// A value <= 0 is replaced by the 1m default in Validate(); to switch the
	// suppression OFF entirely, set a negative-free tiny value (e.g. 1ns).
	MaxFrequency time.Duration `json:"max_frequency"`
}

MailerConfig mirrors upstream conf.MailerConfiguration.

func (MailerConfig) OTPExpDuration

func (m MailerConfig) OTPExpDuration() time.Duration

OTPExpDuration returns OTPExp as a duration.

type Mount

type Mount struct {
	// contains filtered or unexported fields
}

Mount is the handle to one mounted /auth/v1 surface. It exposes the parts of the package that live outside the request path.

func Register

func Register(r chi.Router, d Deps) *Mount

Register mounts the gotrue-compatible routes on r. The caller is responsible for mounting r at /auth/v1.

Middleware order matches upstream's (internal/api/api.go NewAPIWithVersion): CORS outermost, then client-IP resolution, then the request timeout. Rate limiting is per route (a.limit / a.limitCheck), as upstream does it.

Routes are mounted in two phases: the core surface below, then every feature registered with registerFeature, in name order.

The returned Mount carries the background work of this mount; embedders that only need the HTTP surface can ignore it.

func (*Mount) Config

func (m *Mount) Config() *Config

Config returns the configuration this mount was built with.

func (*Mount) RunCleanup

func (m *Mount) RunCleanup(ctx context.Context)

RunCleanup runs the periodic deletion of expired auth rows until ctx is cancelled (cleanup.go). It is a no-op when Config.CleanupEnabled is false, and it operates on the database of the instance selected on ctx (ports.ContextWithInstance), so a multi-instance deployment starts one worker per instance.

func (*Mount) WithOpaqueSessionKey

func (m *Mount) WithOpaqueSessionKey(ctx context.Context, bearer, keyID string, fn func([]byte) error) error

WithOpaqueSessionKey is the server-side integration point, NOT an HTTP key export endpoint. It verifies the bearer, live session and MFA on each use. fn must not retain the byte slice; it is cleared before this call returns. Keys expire after 15 minutes; refresh does not resurrect/extend OPAQUE keys.

type OAuthClientListResponse

type OAuthClientListResponse struct {
	Clients []OAuthClientResponse `json:"clients,omitempty"`
}

OAuthClientListResponse is the GET /admin/oauth/clients body.

type OAuthClientRegisterParams

type OAuthClientRegisterParams struct {
	// RedirectURIs is required: at least one, at most ten.
	RedirectURIs []string `json:"redirect_uris"`

	// ClientType may be given explicitly or inferred from
	// TokenEndpointAuthMethod (see determineClientType).
	ClientType              string `json:"client_type,omitempty"`
	TokenEndpointAuthMethod string `json:"token_endpoint_auth_method,omitempty"`

	GrantTypes []string `json:"grant_types,omitempty"`
	ClientName string   `json:"client_name,omitempty"`
	ClientURI  string   `json:"client_uri,omitempty"`
	LogoURI    string   `json:"logo_uri,omitempty"`
	// contains filtered or unexported fields
}

OAuthClientRegisterParams is the POST /admin/oauth/clients and POST /oauth/clients/register body (upstream OAuthServerClientRegisterParams).

type OAuthClientResponse

type OAuthClientResponse struct {
	ClientID     string `json:"client_id"`
	ClientSecret string `json:"client_secret,omitempty"` // only returned on registration
	ClientType   string `json:"client_type"`

	RedirectURIs            []string `json:"redirect_uris,omitempty"`
	TokenEndpointAuthMethod string   `json:"token_endpoint_auth_method,omitempty"`
	GrantTypes              []string `json:"grant_types,omitempty"`
	ResponseTypes           []string `json:"response_types,omitempty"`
	ClientName              string   `json:"client_name,omitempty"`
	ClientURI               string   `json:"client_uri,omitempty"`
	LogoURI                 string   `json:"logo_uri,omitempty"`

	RegistrationType string    `json:"registration_type,omitempty"`
	CreatedAt        time.Time `json:"created_at,omitempty"`
	UpdatedAt        time.Time `json:"updated_at,omitempty"`
}

OAuthClientResponse is the admin/DCR client body (upstream oauthserver.OAuthServerClientResponse). Field order and json tags are copied.

type OAuthClientUpdateParams

type OAuthClientUpdateParams struct {
	RedirectURIs            *[]string `json:"redirect_uris,omitempty"`
	GrantTypes              *[]string `json:"grant_types,omitempty"`
	ClientName              *string   `json:"client_name,omitempty"`
	ClientURI               *string   `json:"client_uri,omitempty"`
	LogoURI                 *string   `json:"logo_uri,omitempty"`
	TokenEndpointAuthMethod *string   `json:"token_endpoint_auth_method,omitempty"`
}

OAuthClientUpdateParams is the PUT /admin/oauth/clients/{client_id} body. Every field is a pointer: only the ones present in the JSON are written.

type OAuthConsentAction

type OAuthConsentAction string

OAuthConsentAction is the decision the consent page reports.

const (
	OAuthConsentActionApprove OAuthConsentAction = "approve"
	OAuthConsentActionDeny    OAuthConsentAction = "deny"
)

type OAuthError

type OAuthError struct {
	Err         string `json:"error"`
	Description string `json:"error_description,omitempty"`
	// contains filtered or unexported fields
}

OAuthError is the RFC 6749 error body of POST /oauth/token. It is DELIBERATELY NOT the gotrue {code,error_code,msg} envelope: an OAuth client library parses `error` / `error_description`, and upstream answers this endpoint the same way (apierrors.OAuthError, always with HTTP 400).

func (*OAuthError) Error

func (e *OAuthError) Error() string

func (*OAuthError) Unwrap

func (e *OAuthError) Unwrap() error

type OAuthServerConfig

type OAuthServerConfig struct {
	// Enabled mirrors GOTRUE_OAUTH_SERVER_ENABLED.
	Enabled bool `json:"enabled"`
}

OAuthServerConfig mirrors upstream conf.OAuthServerConfiguration. Enforced by oauthserver.go, which 404s every /oauth route while Enabled is false.

type OAuthTokenParams

type OAuthTokenParams struct {
	GrantType    string `json:"grant_type"`
	Code         string `json:"code"`
	RefreshToken string `json:"refresh_token"`
	RedirectURI  string `json:"redirect_uri"`
	ClientID     string `json:"client_id"`
	ClientSecret string `json:"client_secret"`
	CodeVerifier string `json:"code_verifier"`
	Resource     string `json:"resource"`
}

OAuthTokenParams is the POST /oauth/token body, accepted as JSON or as application/x-www-form-urlencoded (upstream OAuthTokenParams).

type OAuthTokenResponse

type OAuthTokenResponse struct {
	AccessToken  string `json:"access_token"`
	TokenType    string `json:"token_type"`
	ExpiresIn    int    `json:"expires_in"`
	RefreshToken string `json:"refresh_token"`
	IDToken      string `json:"id_token,omitempty"`
}

OAuthTokenResponse is the RFC 6749 §5.1 success body. Note what is NOT here: the user object and `expires_at` of the gotrue session envelope. An OAuth client learns about the user from the id_token or /oauth/userinfo.

type OpaqueConfig

type OpaqueConfig struct {
	Enabled   bool   `json:"enabled"`
	MasterKey string `json:"-"`
}

LoadConfig enables OpaqueConfig by default when a master key is configured, unless OPAQUE_ENABLED explicitly disables it. Programmatic configs use Enabled as supplied. The 32-byte base64url master key must be stable, external to PostgreSQL, and identical on every replica. Never log it.

type OpenIDConfigurationResponse

type OpenIDConfigurationResponse struct {
	// Core Discovery Fields (Required by both OIDC and OAuth 2.0)
	Issuer                string `json:"issuer"`
	AuthorizationEndpoint string `json:"authorization_endpoint"`
	TokenEndpoint         string `json:"token_endpoint"`
	JWKSURL               string `json:"jwks_uri"`
	UserInfoEndpoint      string `json:"userinfo_endpoint,omitempty"` // OIDC-specific
	RegistrationEndpoint  string `json:"registration_endpoint,omitempty"`

	// Supported Parameters
	ScopesSupported                   []string `json:"scopes_supported,omitempty"`
	ResponseTypesSupported            []string `json:"response_types_supported"`
	ResponseModesSupported            []string `json:"response_modes_supported,omitempty"`
	GrantTypesSupported               []string `json:"grant_types_supported"`
	SubjectTypesSupported             []string `json:"subject_types_supported"`               // OIDC-specific
	IDTokenSigningAlgValuesSupported  []string `json:"id_token_signing_alg_values_supported"` // OIDC-specific
	TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported"`
	ClaimsSupported                   []string `json:"claims_supported,omitempty"`       // OIDC-specific
	CodeChallengeMethodsSupported     []string `json:"code_challenge_methods_supported"` // OAuth 2.1/PKCE
}

OpenIDConfigurationResponse is the OIDC Discovery / RFC 8414 metadata document. Field names, json tags and field order are copied from upstream api.OpenIDConfigurationResponse — OIDC Discovery extends RFC 8414, so one structure serves both /.well-known/openid-configuration and (once Dilion grows an OAuth server) /.well-known/oauth-authorization-server.

type OtpParams

type OtpParams struct {
	Email      string         `json:"email"`
	Phone      string         `json:"phone"`
	CreateUser bool           `json:"create_user"`
	Data       map[string]any `json:"data"`
	Channel    string         `json:"channel"`

	CodeChallengeMethod string `json:"code_challenge_method"`
	CodeChallenge       string `json:"code_challenge"`

	// RedirectTo is not an upstream body field (upstream reads redirect_to from
	// the query string / Referer); it is accepted here as well because several
	// client libraries send it in the body.
	RedirectTo string `json:"redirect_to"`
}

OtpParams is the POST /otp body (upstream api.OtpParams).

type PKCEGrantParams

type PKCEGrantParams struct {
	AuthCode     string `json:"auth_code"`
	CodeVerifier string `json:"code_verifier"`
}

PKCEGrantParams is the POST /token?grant_type=pkce body.

type PasskeyAuthenticationOptionsResponse

type PasskeyAuthenticationOptionsResponse struct {
	ChallengeID string                                      `json:"challenge_id"`
	Options     *protocol.PublicKeyCredentialRequestOptions `json:"options"`
	ExpiresAt   int64                                       `json:"expires_at"`
}

PasskeyAuthenticationOptionsResponse is the POST /passkeys/authentication/options body (upstream api.PasskeyAuthenticationOptionsResponse). `options` is handed straight to navigator.credentials.get().

type PasskeyAuthenticationVerifyParams

type PasskeyAuthenticationVerifyParams struct {
	ChallengeID string          `json:"challenge_id"`
	Credential  json.RawMessage `json:"credential"`
}

PasskeyAuthenticationVerifyParams is the POST /passkeys/authentication/verify body.

type PasskeyConfig

type PasskeyConfig struct {
	// Enabled mirrors GOTRUE_PASSKEY_ENABLED; reported by GET /settings.
	Enabled bool `json:"enabled"`
	// RPID mirrors GOTRUE_WEBAUTHN_RP_ID.
	RPID string `json:"rp_id"`
	// RPOrigins mirrors GOTRUE_WEBAUTHN_RP_ORIGINS.
	RPOrigins []string `json:"rp_origins"`
}

PasskeyConfig mirrors upstream conf.PasskeyConfiguration + conf.WebAuthnConfiguration. Enforced by passkeys.go: Enabled gates the /passkeys routes (and is reported by GET /settings), RPID/RPOrigins configure the relying party for both passkeys and the WebAuthn MFA factor.

type PasskeyListItem

type PasskeyListItem struct {
	ID           string     `json:"id"`
	FriendlyName string     `json:"friendly_name,omitempty"`
	CreatedAt    time.Time  `json:"created_at"`
	LastUsedAt   *time.Time `json:"last_used_at,omitempty"`
}

PasskeyListItem is one entry of GET /passkeys and the body of a successful PATCH (upstream api.PasskeyListItem). The credential id, the public key and the sign counter are deliberately absent — a client has no use for them and they are the parts worth not echoing.

type PasskeyMetadataResponse

type PasskeyMetadataResponse struct {
	ID           string    `json:"id"`
	FriendlyName string    `json:"friendly_name,omitempty"`
	CreatedAt    time.Time `json:"created_at"`
}

PasskeyMetadataResponse is the body of a successful passkey creation.

type PasskeyRegistrationOptionsResponse

type PasskeyRegistrationOptionsResponse struct {
	ChallengeID string                                       `json:"challenge_id"`
	Options     *protocol.PublicKeyCredentialCreationOptions `json:"options"`
	ExpiresAt   int64                                        `json:"expires_at"`
}

PasskeyRegistrationOptionsResponse is the POST /passkeys/registration/options body (upstream api.PasskeyRegistrationOptionsResponse). `options` is the raw PublicKeyCredentialCreationOptions the browser hands to navigator.credentials.create().

type PasskeyRegistrationVerifyParams

type PasskeyRegistrationVerifyParams struct {
	ChallengeID string          `json:"challenge_id"`
	Credential  json.RawMessage `json:"credential"`
}

PasskeyRegistrationVerifyParams is the POST /passkeys/registration/verify body.

type PasskeyUpdateParams

type PasskeyUpdateParams struct {
	FriendlyName string `json:"friendly_name"`
}

PasskeyUpdateParams is the PATCH /passkeys/{passkey_id} body.

type PasswordConfig

type PasswordConfig struct {
	// MinLength mirrors GOTRUE_PASSWORD_MIN_LENGTH (default 6).
	MinLength int `json:"min_length"`
	// RequiredCharacters mirrors GOTRUE_PASSWORD_REQUIRED_CHARACTERS: a
	// COLON-SEPARATED list of character-class sets, each of which the password
	// must draw at least one character from. A literal colon is escaped `\:`.
	//
	//	abcdefghijklmnopqrstuvwxyz:ABCDEFGHIJKLMNOPQRSTUVWXYZ:0123456789
	RequiredCharacters []string `json:"required_characters"`
}

PasswordConfig mirrors upstream conf.PasswordConfiguration.

type PasswordGrantParams

type PasswordGrantParams struct {
	Email    string `json:"email"`
	Phone    string `json:"phone"`
	Password string `json:"password"`
}

PasswordGrantParams is the POST /token?grant_type=password body.

type PasswordVerificationAttemptInput

type PasswordVerificationAttemptInput struct {
	Metadata *hookMetadata `json:"metadata"`
	UserID   string        `json:"user_id"`
	Valid    bool          `json:"valid"`
}

PasswordVerificationAttemptInput is upstream v0hooks.PasswordVerificationAttemptInput.

type PasswordVerificationAttemptOutput

type PasswordVerificationAttemptOutput struct {
	Decision         string `json:"decision"`
	Message          string `json:"message"`
	ShouldLogoutUser bool   `json:"should_logout_user"`
}

PasswordVerificationAttemptOutput is upstream v0hooks.PasswordVerificationAttemptOutput.

type PoolFunc

type PoolFunc func(context.Context) (*pgxpool.Pool, error)

PoolFunc resolves the database pool for a request. In a multi-instance deployment it returns the database of the instance selected on the context (ports.ContextWithInstance, internal/instances); the single-instance default always answers with the one configured pool. It is structurally identical to instances.PoolFunc — declared here so this package keeps its narrow imports.

func StaticPool

func StaticPool(pool *pgxpool.Pool) PoolFunc

StaticPool is the single-instance PoolFunc over one fixed pool.

type ProviderConfig

type ProviderConfig struct {
	// Enabled mirrors GOTRUE_EXTERNAL_<PROVIDER>_ENABLED.
	Enabled bool `json:"enabled"`
	// ClientID mirrors GOTRUE_EXTERNAL_<PROVIDER>_CLIENT_ID. It is a LIST
	// upstream (comma separated in the env) because Apple/Azure accept several
	// audiences; the first entry is the primary client id.
	ClientID []string `json:"client_id"`
	// Secret mirrors GOTRUE_EXTERNAL_<PROVIDER>_SECRET.
	Secret string `json:"-"`
	// RedirectURI mirrors GOTRUE_EXTERNAL_<PROVIDER>_REDIRECT_URI.
	RedirectURI string `json:"redirect_uri"`
	// URL mirrors GOTRUE_EXTERNAL_<PROVIDER>_URL (self-hosted GitLab/Keycloak).
	URL string `json:"url"`
	// SkipNonceCheck mirrors GOTRUE_EXTERNAL_<PROVIDER>_SKIP_NONCE_CHECK.
	SkipNonceCheck bool `json:"skip_nonce_check"`
}

ProviderConfig is one external identity provider (upstream conf.OAuthProviderConfiguration). Env prefix: GOTRUE_EXTERNAL_<PROVIDER>_*.

type ProviderSettings

type ProviderSettings struct {
	AnonymousUsers bool `json:"anonymous_users"`
	Apple          bool `json:"apple"`
	Azure          bool `json:"azure"`
	Bitbucket      bool `json:"bitbucket"`
	Discord        bool `json:"discord"`
	Facebook       bool `json:"facebook"`
	Snapchat       bool `json:"snapchat"`
	Figma          bool `json:"figma"`
	Fly            bool `json:"fly"`
	GitHub         bool `json:"github"`
	GitLab         bool `json:"gitlab"`
	Google         bool `json:"google"`
	Keycloak       bool `json:"keycloak"`
	Kakao          bool `json:"kakao"`
	Linkedin       bool `json:"linkedin"`
	LinkedinOIDC   bool `json:"linkedin_oidc"`
	Notion         bool `json:"notion"`
	Spotify        bool `json:"spotify"`
	Slack          bool `json:"slack"`
	SlackOIDC      bool `json:"slack_oidc"`
	WorkOS         bool `json:"workos"`
	Twitch         bool `json:"twitch"`
	Twitter        bool `json:"twitter"`
	Email          bool `json:"email"`
	Phone          bool `json:"phone"`
	Zoom           bool `json:"zoom"`
}

ProviderSettings is the `external` object of GET /settings. Field order and json tags are copied from upstream api.ProviderSettings — supabase-js reads these keys by name, so none of them may be renamed or dropped.

type PublicJWK

type PublicJWK struct {
	KeyID     string   `json:"kid"`
	KeyType   string   `json:"kty"`
	Curve     string   `json:"crv"`
	X         string   `json:"x"`
	Y         string   `json:"y"`
	Algorithm string   `json:"alg"`
	Use       string   `json:"use"`
	KeyOps    []string `json:"key_ops"`
}

PublicJWK is one key of GET /.well-known/jwks.json. Only PUBLIC members are ever declared here — the private scalar `d` has no field on purpose, so no code path can leak it, and the HS256 secret is never represented at all.

type RateLimitConfig

type RateLimitConfig struct {
	// EmailSent mirrors GOTRUE_RATE_LIMIT_EMAIL_SENT (default 30 / 5m).
	EmailSent float64 `json:"email_sent"`
	// SMSSent mirrors GOTRUE_RATE_LIMIT_SMS_SENT (default 30 / 5m).
	SMSSent float64 `json:"sms_sent"`
	// Verify mirrors GOTRUE_RATE_LIMIT_VERIFY (default 30 / 5m).
	Verify float64 `json:"verify"`
	// TokenRefresh mirrors GOTRUE_RATE_LIMIT_TOKEN_REFRESH (default 150 / 5m).
	TokenRefresh float64 `json:"token_refresh"`
	// SSO mirrors GOTRUE_RATE_LIMIT_SSO (default 30 / 5m).
	SSO float64 `json:"sso"`
	// AnonymousUsers mirrors GOTRUE_RATE_LIMIT_ANONYMOUS_USERS (default 30).
	// Upstream measures this one PER HOUR, and Dilion does the same.
	AnonymousUsers float64 `json:"anonymous_users"`
	// OTP mirrors GOTRUE_RATE_LIMIT_OTP (default 30 / 5m). Upstream applies it
	// to /otp, /magiclink, /recover, /resend, /signup and PUT /user.
	OTP float64 `json:"otp"`
	// Web3 mirrors GOTRUE_RATE_LIMIT_WEB3 (default 30 / 5m). FIELD ONLY, and
	// the only one left in this file: middleware.go does build the LimiterWeb3
	// bucket from it, but no route applies that limiter, because Dilion
	// implements no `web3` grant yet. It starts limiting the moment
	// registerGrant("web3", LimiterWeb3, ...) exists.
	Web3 float64 `json:"web3"`
	// Passkey mirrors GOTRUE_RATE_LIMIT_PASSKEY (default 30 / 5m). Enforced:
	// middleware.go builds the LimiterPasskey bucket and passkeys.go applies it
	// to the passkey registration/authentication routes.
	Passkey float64 `json:"passkey"`
}

RateLimitConfig mirrors upstream's GOTRUE_RATE_LIMIT_* knobs. Unless noted, the number is "requests per 5 minutes per client IP" (upstream's window) and the burst is 30.

type RecoverParams

type RecoverParams struct {
	Email               string `json:"email"`
	CodeChallenge       string `json:"code_challenge"`
	CodeChallengeMethod string `json:"code_challenge_method"`
	RedirectTo          string `json:"redirect_to"`
}

RecoverParams is the POST /recover body (upstream api.RecoverParams).

type RefreshTokenGrantParams

type RefreshTokenGrantParams struct {
	RefreshToken string `json:"refresh_token"`
}

RefreshTokenGrantParams is the POST /token?grant_type=refresh_token body.

type ResendConfirmationParams

type ResendConfirmationParams struct {
	Type                string `json:"type"`
	Email               string `json:"email"`
	Phone               string `json:"phone"`
	CodeChallenge       string `json:"code_challenge"`
	CodeChallengeMethod string `json:"code_challenge_method"`
	RedirectTo          string `json:"redirect_to"`
}

ResendConfirmationParams is the POST /resend body (upstream api.ResendConfirmationParams).

type SAMLAttribute

type SAMLAttribute struct {
	// Name is the primary SAML attribute Name (or FriendlyName) to read.
	Name string `json:"name,omitempty"`
	// Names are further attribute names, tried in order after Name.
	Names []string `json:"names,omitempty"`
	// Default is used when none of the names produced a value.
	Default any `json:"default,omitempty"`
	// Array collects EVERY value of the first matching attribute instead of
	// just the first one.
	Array bool `json:"array,omitempty"`
}

SAMLAttribute is one entry of a provider's attribute_mapping (upstream models.SAMLAttribute).

type SAMLAttributeMapping

type SAMLAttributeMapping struct {
	Keys map[string]SAMLAttribute `json:"keys,omitempty"`
}

SAMLAttributeMapping maps claim keys to SAML attributes (upstream models.SAMLAttributeMapping).

func (*SAMLAttributeMapping) Equal

Equal is upstream's SAMLAttributeMapping.Equal, used by the admin update to decide whether the mapping actually changed.

type SAMLConfig

type SAMLConfig struct {
	// Enabled mirrors GOTRUE_SAML_ENABLED; reported by GET /settings.
	Enabled bool `json:"enabled"`
	// PrivateKey mirrors GOTRUE_SAML_PRIVATE_KEY (base64 DER RSA key).
	PrivateKey string `json:"-"`
}

SAMLConfig mirrors upstream conf.SAMLConfiguration. Enforced: Enabled gates the /sso routes (sso.go) and is reported by GET /settings; PrivateKey is the SP key material parsed in saml_sp.go.

type SAMLProvider

type SAMLProvider struct {
	ID            string `json:"-"`
	SSOProviderID string `json:"-"`

	EntityID    string  `json:"entity_id"`
	MetadataXML string  `json:"metadata_xml,omitempty"`
	MetadataURL *string `json:"metadata_url,omitempty"`

	AttributeMapping SAMLAttributeMapping `json:"attribute_mapping,omitempty"`

	NameIDFormat *string `json:"name_id_format,omitempty"`

	CreatedAt time.Time `json:"-"`
	UpdatedAt time.Time `json:"-"`
}

SAMLProvider is one auth.saml_providers row (upstream models.SAMLProvider).

type SMS

type SMS struct {
	OTP     string `json:"otp,omitempty"`
	SMSType string `json:"sms_type,omitempty"`
	Phone   string `json:"phone,omitempty"`
}

SMS is upstream v0hooks.SMS: the OTP payload handed to a send_sms hook.

type SMSConfig

type SMSConfig struct {
	// Autoconfirm mirrors GOTRUE_SMS_AUTOCONFIRM.
	Autoconfirm bool `json:"autoconfirm"`
	// OTPExp mirrors GOTRUE_SMS_OTP_EXP, in seconds (upstream default 60).
	OTPExp int `json:"otp_exp"`
	// OTPLength mirrors GOTRUE_SMS_OTP_LENGTH (default 6, clamped to 6..10).
	OTPLength int `json:"otp_length"`
	// Provider mirrors GOTRUE_SMS_PROVIDER; reported verbatim by GET /settings.
	// "twilio" selects the built-in Twilio REST sender (sms_twilio.go). Any
	// other non-empty value is reported to clients but has no built-in
	// transport — supply one through Sender.
	Provider string `json:"provider"`
	// MaxFrequency mirrors GOTRUE_SMS_MAX_FREQUENCY (default 1m).
	MaxFrequency time.Duration `json:"max_frequency"`

	// Template mirrors GOTRUE_SMS_TEMPLATE: the text/template rendered into the
	// message body, with `{{ .Code }}` bound to the OTP. Empty means upstream's
	// default, "Your code is {{ .Code }}".
	Template string `json:"template"`

	// Twilio mirrors GOTRUE_SMS_TWILIO_*.
	Twilio TwilioConfig `json:"twilio"`

	// Sender is the injected SMS transport (ports.SMSSender). When non-nil it
	// takes precedence over Provider, so an embedder can deliver SMS through
	// its own carrier without touching this configuration further.
	//
	// DILION-ONLY. Upstream has no equivalent because it owns its providers;
	// Dilion's SMS surface is a port. It is deliberately NOT read from the
	// environment and never serialized.
	//
	// NOTE: auth.Deps has no SMS field yet, so this is currently the ONLY way
	// to inject a sender into a mount. See the gap note in smsflow.go.
	Sender ports.SMSSender `json:"-"`
}

SMSConfig mirrors upstream conf.SmsProviderConfiguration. It is consumed by the phone/SMS lifecycle (smsflow.go, sms_twilio.go).

func (SMSConfig) OTPExpDuration

func (s SMSConfig) OTPExpDuration() time.Duration

OTPExpDuration returns SMS.OTPExp as a duration.

func (SMSConfig) SMSTemplateOrDefault

func (s SMSConfig) SMSTemplateOrDefault() string

SMSTemplateOrDefault returns the configured message template, falling back to upstream's default when none is set.

type SSODomain

type SSODomain struct {
	ID            string `json:"-"`
	SSOProviderID string `json:"-"`

	Domain string `json:"domain"`

	CreatedAt time.Time `json:"-"`
	UpdatedAt time.Time `json:"-"`
}

SSODomain is one auth.sso_domains row (upstream models.SSODomain).

type SSOProvider

type SSOProvider struct {
	ID           string       `json:"id"`
	ResourceID   *string      `json:"resource_id,omitempty"`
	Disabled     *bool        `json:"disabled"`
	SAMLProvider SAMLProvider `json:"saml,omitempty"`
	SSODomains   []SSODomain  `json:"domains"`

	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

SSOProvider is one auth.sso_providers row plus its SAML connection and the email domains routed to it (upstream models.SSOProvider).

func (*SSOProvider) IsEnabled

func (p *SSOProvider) IsEnabled() bool

IsEnabled is upstream's SSOProvider.IsEnabled: NULL means enabled, so a row written before the `disabled` column existed keeps working.

type SecurityConfig

type SecurityConfig struct {
	// RefreshTokenRotationEnabled mirrors
	// GOTRUE_SECURITY_REFRESH_TOKEN_ROTATION_ENABLED (default true): a refresh
	// revokes the presented token and issues its child.
	RefreshTokenRotationEnabled bool `json:"refresh_token_rotation_enabled"`
	// RefreshTokenReuseInterval mirrors
	// GOTRUE_SECURITY_REFRESH_TOKEN_REUSE_INTERVAL, in SECONDS (Dilion default
	// 10, upstream 0): a revoked token presented within this many seconds of its
	// revocation is tolerated and answered with the session's current token
	// instead of being treated as abuse.
	RefreshTokenReuseInterval int `json:"refresh_token_reuse_interval"`
	// UpdatePasswordRequireReauth mirrors
	// GOTRUE_SECURITY_UPDATE_PASSWORD_REQUIRE_REAUTHENTICATION. Enforced by
	// user.go requireReauthentication: PUT /user changing the password needs a
	// nonce from POST /reauthenticate, else 400 reauthentication_needed.
	UpdatePasswordRequireReauth bool `json:"update_password_require_reauthentication"`
	// ManualLinkingEnabled mirrors GOTRUE_SECURITY_MANUAL_LINKING_ENABLED
	// (default false). Enforced by identity.go: while off, GET
	// /user/identities/authorize answers 404 manual_linking_disabled.
	ManualLinkingEnabled bool `json:"manual_linking_enabled"`
	// Captcha mirrors GOTRUE_SECURITY_CAPTCHA_*.
	Captcha CaptchaConfig `json:"captcha"`
	// HIBPEnabled mirrors GOTRUE_PASSWORD_HIBP_ENABLED (upstream nests it under
	// Password; it is a security control, so it lives here): password strength
	// checks additionally query the HaveIBeenPwned range API (hibp.go).
	HIBPEnabled bool `json:"hibp_enabled"`
	// HIBPFailClosed mirrors GOTRUE_PASSWORD_HIBP_FAIL_CLOSED (default false):
	// when HaveIBeenPwned cannot be reached, false ACCEPTS the password (fail
	// open, with a WARN log — upstream's default) and true rejects the request
	// with a 500.
	HIBPFailClosed bool `json:"hibp_fail_closed"`
	// HIBPBaseURL has no upstream equivalent (upstream's hibp client hardcodes
	// the host): the base of the k-anonymity range API, without a trailing
	// slash. It exists so tests and air-gapped deployments can point the check
	// at their own mirror. Empty means api.pwnedpasswords.com.
	HIBPBaseURL string `json:"-"`
	// DeletionReauthWindow (DILION_AUTH_SECURITY_DELETION_REAUTH_WINDOW, Dilion
	// extension, default 10m) is how recent a user's sign-in must be for them to
	// request their own account deletion (POST /privacy/v1/me/requests with
	// type DELETION). Older than this, the request answers 403
	// reauthentication_needed and the user signs in again. 0 turns the check
	// off.
	DeletionReauthWindow time.Duration `json:"deletion_reauth_window"`
}

SecurityConfig mirrors upstream conf.SecurityConfiguration.

func (SecurityConfig) ReuseIntervalDuration

func (s SecurityConfig) ReuseIntervalDuration() time.Duration

ReuseIntervalDuration returns RefreshTokenReuseInterval as a duration.

type SendEmailInput

type SendEmailInput struct {
	Metadata  *hookMetadata `json:"metadata"`
	User      *User         `json:"user"`
	EmailData EmailData     `json:"email_data"`
}

SendEmailInput is upstream v0hooks.SendEmailInput.

type SendEmailOutput

type SendEmailOutput struct{}

SendEmailOutput is upstream v0hooks.SendEmailOutput (empty — success is the absence of an error object in the body).

type SendSMSInput

type SendSMSInput struct {
	Metadata *hookMetadata `json:"metadata"`
	User     *User         `json:"user,omitempty"`
	SMS      SMS           `json:"sms,omitempty"`
}

SendSMSInput is upstream v0hooks.SendSMSInput.

type SendSMSOutput

type SendSMSOutput struct{}

SendSMSOutput is upstream v0hooks.SendSMSOutput (empty).

type SessionAssurance added in v0.0.5

type SessionAssurance struct {
	// AAL is aal2 once the session verified an MFA factor, else aal1.
	AAL string
	// AuthenticatedAt is the newest authentication recorded for the session:
	// its sign-in, or a later MFA verification. A refresh does not renew it.
	AuthenticatedAt time.Time
	// MFAEnabled reports whether the user has a verified factor, and so could
	// reach aal2.
	MFAEnabled bool
	// OAuthClient reports that the session belongs to an OAuth application
	// the user authorized, not to the user's own sign-in.
	OAuthClient bool
	// Active is false for a banned or deleted user.
	Active bool
}

SessionAssurance is what one session proves about the person using it, read from the database for code outside this package (the privacy API's self-service surface). The access token carries the same facts as its aal and amr claims, but a TokenClaims or custom_access_token hook can rewrite those, so a decision that matters reads them here.

func LookupSessionAssurance added in v0.0.5

func LookupSessionAssurance(ctx context.Context, pool *pgxpool.Pool, userID, sessionID string) (SessionAssurance, error)

LookupSessionAssurance reads the assurance of userID's session sessionID.

type SessionsConfig

type SessionsConfig struct {
	// Timebox mirrors GOTRUE_SESSIONS_TIMEBOX: absolute session lifetime measured
	// from sessions.created_at. Zero disables the check.
	Timebox time.Duration `json:"timebox"`
	// InactivityTimeout mirrors GOTRUE_SESSIONS_INACTIVITY_TIMEOUT: maximum age of
	// sessions.refreshed_at. Zero disables the check.
	InactivityTimeout time.Duration `json:"inactivity_timeout"`
	// SinglePerUser mirrors GOTRUE_SESSIONS_SINGLE_PER_USER (default false).
	// Enforced by grant.go checkSinglePerUser, on the refresh_token grant —
	// which is where upstream enforces it too (internal/tokens/service.go, the
	// only reader of the flag in supabase/auth). It does NOT restrict session
	// CREATION: a second sign-in still mints a second session, and the older
	// one is rejected the next time it tries to refresh, once the newer one has
	// refreshed at least once. Nothing is deleted or revoked.
	SinglePerUser bool `json:"single_per_user"`
}

SessionsConfig mirrors upstream conf.SessionsConfiguration.

type Settings

type Settings struct {
	ExternalProviders            ProviderSettings `json:"external"`
	DisableSignup                bool             `json:"disable_signup"`
	MailerAutoconfirm            bool             `json:"mailer_autoconfirm"`
	PhoneAutoconfirm             bool             `json:"phone_autoconfirm"`
	SmsProvider                  string           `json:"sms_provider"`
	SAMLEnabled                  bool             `json:"saml_enabled"`
	SAMLPrivateKeyNextConfigured bool             `json:"saml_private_key_next_configured"`
	PasskeysEnabled              bool             `json:"passkeys_enabled"`
}

Settings is the GET /settings body (upstream api.Settings).

type SignupParams

type SignupParams struct {
	Email    string         `json:"email"`
	Phone    string         `json:"phone"`
	Password string         `json:"password"`
	Data     map[string]any `json:"data"`
	Channel  string         `json:"channel"` // "sms" (default) or "whatsapp"

	// CodeChallenge / CodeChallengeMethod turn the signup into a PKCE flow
	// (pkce.go): a flow_state row is created alongside the user and the mailed
	// confirmation token is prefixed "pkce_", so following the link redirects
	// to `?code=<auth_code>` instead of dropping tokens in the URL fragment.
	CodeChallenge       string `json:"code_challenge"`
	CodeChallengeMethod string `json:"code_challenge_method"`
}

SignupParams is the POST /signup body (wave-1 subset of upstream's).

type SingleSignOnParams

type SingleSignOnParams struct {
	ProviderID          string `json:"provider_id"`
	Domain              string `json:"domain"`
	RedirectTo          string `json:"redirect_to"`
	SkipHTTPRedirect    *bool  `json:"skip_http_redirect"`
	CodeChallenge       string `json:"code_challenge"`
	CodeChallengeMethod string `json:"code_challenge_method"`
}

SingleSignOnParams is the POST /sso body (upstream api.SingleSignOnParams).

type SingleSignOnResponse

type SingleSignOnResponse struct {
	URL string `json:"url"`
}

SingleSignOnResponse is the skip_http_redirect body (upstream api.SingleSignOnResponse).

type TOTPObject

type TOTPObject struct {
	QRCode string `json:"qr_code,omitempty"`
	Secret string `json:"secret,omitempty"`
	URI    string `json:"uri,omitempty"`
}

TOTPObject is the `totp` member of an enrolment response.

type TokenFunc added in v0.0.4

type TokenFunc func(context.Context) (*TokenService, error)

TokenFunc resolves the token service of the instance selected on ctx. It is the token-side twin of PoolFunc: multi-instance deployments hand in instances.Registry.Tokens, single-instance ones StaticTokens.

func StaticTokens added in v0.0.4

func StaticTokens(ts *TokenService) TokenFunc

StaticTokens is the TokenFunc of a single-instance mount. A nil service is allowed (read-only test mounts); tokensFor then reports it as an error.

type TokenService

type TokenService struct {
	// contains filtered or unexported fields
}

TokenService signs and verifies gotrue-compatible access tokens.

Signing

When Config.JWT.Keys contains an ES256 key whose key_ops include "sign" (upstream's GOTRUE_JWT_KEYS contract), tokens are signed ES256 and carry that key's `kid` in the JOSE header. Otherwise the service falls back to HS256 with Config.JWT.Secret — the zero-configuration developer path, where only DILION_JWT_SECRET is set.

Verifying

Verification accepts BOTH: an ES256 token is checked against the public part of the configured key set (selected by `kid`, or tried against every key when the header carries none), and an HS256 token against the legacy secret. That is what makes a rotation from HS256 to ES256 non-breaking: tokens issued before the switch keep verifying until they expire. WithValidMethods is restricted to exactly the algorithms the configuration can actually verify, so `alg: none` and key-confusion attacks are rejected.

Key rotation runbook

Config.JWT.Keys is an ordered set; exactly one member carries key_ops ["sign"] (enforced by Config.Validate). To rotate:

  1. Mint a new key (`go run ./cmd/genkey`) and append it to DILION_AUTH_JWT_KEYS with key_ops ["verify"]. Deploy. The new key is now published in JWKS and accepted by every replica, but nothing signs with it yet.
  2. Once every replica runs step 1, flip the new key to key_ops ["sign"] and the old key to ["verify"]. Deploy. New tokens carry the new `kid`; tokens signed by the old key still verify.
  3. After the old tokens have expired (Config.JWT.Exp, plus your refresh window), drop the old key from the environment. Deploy.

Retiring the legacy HS256 secret is the same dance: keep JWT_SECRET set while old tokens are alive, then unset it.

It implements both ports.TokenSigner and ports.TokenVerifier; internal/api consumes it through those interfaces.

func NewTokenService

func NewTokenService(cfg *Config) (*TokenService, error)

NewTokenService builds the token service from the /auth/v1 configuration: ES256 when cfg.JWT.Keys holds a signing key, HS256 with cfg.JWT.Secret otherwise. A nil cfg means DefaultConfig().

It fails when the key set is present but unusable (non-EC curve, malformed coordinates, signing key without a private scalar). A configuration with neither an ES256 key nor a secret is accepted here — Sign and Verify then report the missing key — because tests and read-only mounts legitimately construct one.

func NewTokenServiceHS

func NewTokenServiceHS(secret []byte) *TokenService

NewTokenServiceHS is the symmetric-only constructor: HS256 with the given secret and every other setting at its default. It is the compatibility shortcut for embedders and tests that predate the key-set configuration.

func NewTokenServiceWithKeys added in v0.0.4

func NewTokenServiceWithKeys(cfg *Config, keys ports.JWTKeys) (*TokenService, error)

NewTokenServiceWithKeys builds the token service of ONE instance: cfg supplies the deployment-wide settings (TTL, audience) and keys the instance's own key set, secret and issuer (ports.InstanceResolver.JWT). This is what binds a token to its instance — two instances with different key material cannot verify each other's tokens, whoever does the verifying.

func (*TokenService) Algorithm

func (s *TokenService) Algorithm() string

Algorithm reports the algorithm this service signs with: ES256 when a key set is configured, HS256 otherwise, and "" when it cannot sign at all.

func (*TokenService) Issuer added in v0.0.4

func (s *TokenService) Issuer() string

Issuer is the `iss` claim this service mints and requires; empty when no issuer is configured (then no `iss` is minted or checked).

func (*TokenService) KeyID

func (s *TokenService) KeyID() string

KeyID reports the `kid` of the active signing key, empty in HS256 mode.

func (*TokenService) PublicJWKS

func (s *TokenService) PublicJWKS() []PublicJWK

PublicJWKS returns the public half of every configured EC key, in configuration order — exactly what /.well-known/jwks.json publishes. It never contains a private scalar and never the HS256 secret.

func (*TokenService) Sign

func (s *TokenService) Sign(_ context.Context, c ports.Claims) (string, error)

Sign issues a JWT. Claims.Extra is merged in first so custom claims (typically produced by the ports.TokenClaims hook) land in the token, then the canonical claims are written on top — Extra can never override them.

The `iss` claim is emitted only when Config.JWT.Issuer is configured, which is upstream's GOTRUE_JWT_ISSUER semantics as documented on JWTConfig. The OIDC discovery document falls back to SiteURL + /auth/v1 when it is unset, so a deployment that wants a verifiable issuer must set it explicitly.

func (*TokenService) TTL

func (s *TokenService) TTL() time.Duration

TTL reports the access-token lifetime, i.e. the `expires_in` of a session.

func (*TokenService) Verify

func (s *TokenService) Verify(_ context.Context, token string) (*ports.Claims, error)

Verify parses and validates an access token. Only the algorithms this configuration can actually verify are accepted (`alg: none` and asymmetric/symmetric key confusion are rejected): ES256 against the configured key set, HS256 against the legacy secret. An ES256 token naming a `kid` is checked against that key alone; without a `kid` every configured key is tried, which is what keeps a rotation working for tokens minted before the new key existed. When an issuer is configured the token must carry exactly that `iss`. Every non-canonical claim is returned in Claims.Extra.

func (*TokenService) WithClock

func (s *TokenService) WithClock(clk ports.Clock) *TokenService

WithClock returns a copy using an injectable clock (tests).

func (*TokenService) WithTTL

func (s *TokenService) WithTTL(ttl time.Duration) *TokenService

WithTTL returns a copy using a different access-token lifetime. Zero or negative durations fall back to DefaultAccessTokenTTL.

type TwilioConfig

type TwilioConfig struct {
	// AccountSID mirrors GOTRUE_SMS_TWILIO_ACCOUNT_SID. It is both the HTTP
	// basic-auth username and a path segment of the Messages endpoint.
	AccountSID string `json:"account_sid"`
	// AuthToken mirrors GOTRUE_SMS_TWILIO_AUTH_TOKEN (basic-auth password).
	AuthToken string `json:"-"`
	// MessageServiceSID mirrors GOTRUE_SMS_TWILIO_MESSAGE_SERVICE_SID: the
	// `From` of the message (a Messaging Service SID or a sending number).
	MessageServiceSID string `json:"message_service_sid"`
	// ContentSID mirrors GOTRUE_SMS_TWILIO_CONTENT_SID: the WhatsApp
	// authentication template. When set, the OTP is passed as ContentVariables
	// instead of a rendered Body.
	ContentSID string `json:"content_sid"`

	// APIBase overrides https://api.twilio.com.
	//
	// DILION-ONLY (GOTRUE_SMS_TWILIO_API_BASE / DILION_AUTH_SMS_TWILIO_API_BASE):
	// upstream hard-codes the host, which leaves the provider untestable
	// without network access. Point it at an httptest server in tests, or at a
	// regional Twilio edge in production.
	APIBase string `json:"api_base"`
}

TwilioConfig mirrors upstream conf.TwilioProviderConfiguration (GOTRUE_SMS_TWILIO_*).

type UnenrollFactorResponse

type UnenrollFactorResponse struct {
	ID string `json:"id"`
}

UnenrollFactorResponse is the DELETE /factors/{id} body.

type User

type User struct {
	ID string `json:"id"`

	Aud       string `json:"aud"`
	Role      string `json:"role"`
	Email     string `json:"email"`
	IsSSOUser bool   `json:"-"`

	EncryptedPassword *string    `json:"-"`
	EmailConfirmedAt  *time.Time `json:"email_confirmed_at,omitempty"`
	InvitedAt         *time.Time `json:"invited_at,omitempty"`

	Phone            string     `json:"phone"`
	PhoneConfirmedAt *time.Time `json:"phone_confirmed_at,omitempty"`

	ConfirmationSentAt *time.Time `json:"confirmation_sent_at,omitempty"`

	// ConfirmedAt is a generated column (least(email_confirmed_at, phone_confirmed_at));
	// kept for backward compatibility with older clients.
	ConfirmedAt *time.Time `json:"confirmed_at,omitempty"`

	RecoverySentAt *time.Time `json:"recovery_sent_at,omitempty"`

	EmailChange       string     `json:"new_email,omitempty"`
	EmailChangeSentAt *time.Time `json:"email_change_sent_at,omitempty"`

	PhoneChange       string     `json:"new_phone,omitempty"`
	PhoneChangeSentAt *time.Time `json:"phone_change_sent_at,omitempty"`

	ReauthenticationSentAt *time.Time `json:"reauthentication_sent_at,omitempty"`

	LastSignInAt *time.Time `json:"last_sign_in_at,omitempty"`

	AppMetaData  JSONMap `json:"app_metadata"`
	UserMetaData JSONMap `json:"user_metadata"`

	// Factors is populated by loadFactors (mfa_models.go) on user-facing reads;
	// omitted from the body, exactly as upstream does for users without factors.
	Factors    []any      `json:"factors,omitempty"`
	Identities []Identity `json:"identities"`

	CreatedAt   time.Time  `json:"created_at"`
	UpdatedAt   time.Time  `json:"updated_at"`
	BannedUntil *time.Time `json:"banned_until,omitempty"`
	DeletedAt   *time.Time `json:"deleted_at,omitempty"`
	IsAnonymous bool       `json:"is_anonymous"`
}

User is the gotrue user representation. Field ORDER and json tags (including `omitempty`) are copied from github.com/supabase/auth/internal/models.User so the serialized body is byte-comparable with upstream.

Fields tagged `json:"-"` are DB-only and never leave the server.

func (*User) IsBanned

func (u *User) IsBanned(now time.Time) bool

IsBanned reports whether banned_until is in the future.

type UserDetailsResponse

type UserDetailsResponse struct {
	ID    string `json:"id,omitempty"`
	Email string `json:"email,omitempty"`
}

UserDetailsResponse is the user block of the consent screen payload.

type UserOAuthGrantResponse

type UserOAuthGrantResponse struct {
	Client    ClientDetailsResponse `json:"client"`
	Scopes    []string              `json:"scopes"`
	GrantedAt time.Time             `json:"granted_at"`
}

UserOAuthGrantResponse is one entry of GET /user/oauth/grants.

type UserUpdateParams

type UserUpdateParams struct {
	Email    *string        `json:"email"`
	Phone    *string        `json:"phone"`
	Password *string        `json:"password"`
	Nonce    string         `json:"nonce"`
	Data     map[string]any `json:"data"`
	// AppMetaData is accepted upstream but only honoured for admin callers; a
	// self-service user may not escalate their own app_metadata.
	AppMetaData map[string]any `json:"app_metadata"`
	Channel     string         `json:"channel"`

	// CodeChallenge / CodeChallengeMethod make the email-change confirmation a
	// PKCE flow (pkce.go), exactly as they do on /signup and /otp.
	CodeChallenge       string `json:"code_challenge"`
	CodeChallengeMethod string `json:"code_challenge_method"`

	// RedirectTo is where /verify sends the browser after the change is
	// confirmed. Validated against Config.URIAllowList like every other
	// redirect.
	RedirectTo string `json:"redirect_to"`
}

UserUpdateParams is the PUT /user body.

type VerifyFactorParams

type VerifyFactorParams struct {
	ChallengeID string `json:"challenge_id"`
	Code        string `json:"code"`
	// WebAuthn carries the authenticator's response for a webauthn factor verify
	// (upstream VerifyFactorParams.WebAuthn). `credential` is the raw
	// CredentialCreationResponse ("create") or CredentialAssertionResponse
	// ("request"); the ceremony is inferred from the factor's status, so the
	// client-supplied type is advisory.
	WebAuthn *WebAuthnVerifyData `json:"webauthn"`
}

VerifyFactorParams is the POST /factors/{id}/verify body.

type VerifyParams

type VerifyParams struct {
	Type       string `json:"type"`
	Token      string `json:"token"`
	TokenHash  string `json:"token_hash"`
	Email      string `json:"email"`
	Phone      string `json:"phone"`
	RedirectTo string `json:"redirect_to"`
}

VerifyParams is the /verify request (upstream api.VerifyParams).

type WeakPasswordError

type WeakPasswordError struct {
	Message string   `json:"message,omitempty"`
	Reasons []string `json:"reasons,omitempty"`
}

WeakPasswordError is upstream api.WeakPasswordError: a password that does not meet the configured policy, with the machine-readable REASONS a client shows next to its password field.

The reasons are upstream's exact strings:

"length"     shorter than Password.MinLength
"characters" misses one of Password.RequiredCharacters' sets
"pwned"      found in the HaveIBeenPwned corpus

It is never returned to a handler on its own: weakPasswordError wraps it in the HTTPError envelope, whose MarshalJSON renders it as upstream's `weak_password` payload.

func (*WeakPasswordError) Error

func (e *WeakPasswordError) Error() string

type WebAuthnChallengeData

type WebAuthnChallengeData struct {
	Type              string `json:"type"`
	CredentialOptions any    `json:"credential_options"`
}

WebAuthnChallengeData is the `webauthn` member of a webauthn factor challenge (upstream api.WebAuthnChallengeData). Type is "create" for an unverified factor (BeginRegistration) and "request" for a verified one (BeginLogin); CredentialOptions is the raw PublicKeyCredential(Creation|Request)Options the browser hands to navigator.credentials.

type WebAuthnVerifyData

type WebAuthnVerifyData struct {
	Type       string          `json:"type"`
	Credential json.RawMessage `json:"credential"`
}

WebAuthnVerifyData is the `webauthn` member of a webauthn factor verify.

Directories

Path Synopsis
Package upstreamspec holds Go types generated from the OpenAPI document that github.com/supabase/auth (GoTrue) publishes for its own REST API.
Package upstreamspec holds Go types generated from the OpenAPI document that github.com/supabase/auth (GoTrue) publishes for its own REST API.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL