Documentation
¶
Index ¶
- Constants
- Variables
- func FormatServiceToken(prefix, keyID, secret string) string
- func HasServiceTokenPrefix(prefix, token string) bool
- func IsDevEnvironment(environment string) bool
- func IsReservedPermission(name string) bool
- func IsServiceTokenGrantableReservedPermission(name string) bool
- func NormalizeEmail(email string) string
- func NormalizePhone(phone string) string
- func OwnerSlugFromUsername(username string) string
- func ParseServiceToken(prefix, token string) (keyID, secret string, ok bool)
- func ServiceTokenMarker(prefix string) string
- func UsernameOwnerNamespaceError(lookup *OwnerNamespaceLookup, allowedUserID string) string
- func ValidateEmail(email string) error
- func ValidatePassword(value string) error
- func ValidatePhone(phone string) error
- func ValidateUsername(username string) error
- func ValidationErrorCode(err error) string
- func WithSessionRevokeReason(ctx context.Context, reason SessionRevokeReason) context.Context
- type AdminListUsersResult
- type AdminUser
- type AuthEventLogReader
- type AuthEventLogger
- type AuthSessionEvent
- type Config
- type DefaultRole
- type DelegatedUser
- type EmailSender
- type EntitlementsProvider
- type EphemeralMode
- type EphemeralStore
- type FileTenantManifestTokenStore
- type ImportUserInput
- type Keyset
- type Options
- func (o Options) AutoCreatePersonalTenantsEnabled() bool
- func (o Options) PublicNativeUserRegistrationEnabled() bool
- func (o Options) PublicTenantRegistrationEnabled() bool
- func (o Options) RegistrationVerificationEnabled() bool
- func (o Options) RegistrationVerificationPolicy() RegistrationVerificationPolicy
- func (o Options) RegistrationVerificationRequired() bool
- type OwnerNamespaceLookup
- type OwnerNamespaceLookupStatus
- type OwnerNamespaceLookupTenant
- type OwnerNamespaceLookupUser
- type OwnerNamespaceState
- type PendingRegistration
- type PermissionDef
- type RegistrationMode
- type RegistrationVerificationPolicy
- type ResolvedServiceToken
- type ResourceScopeAuthorizationRequest
- type ResourceScopeAuthorizer
- type SMSSender
- type Service
- func (s *Service) AcceptTenantInvite(ctx context.Context, inviteID, userID string) error
- func (s *Service) AddMember(ctx context.Context, tenantSlug, userID string) error
- func (s *Service) AdminDeleteUser(ctx context.Context, id string) error
- func (s *Service) AdminGetUser(ctx context.Context, id string) (*AdminUser, error)
- func (s *Service) AdminListUserSessions(ctx context.Context, userID string) ([]Session, error)
- func (s *Service) AdminListUsers(ctx context.Context, page, pageSize int, filter, search string, ...) (*AdminListUsersResult, error)
- func (s *Service) AdminRevokeUserSessions(ctx context.Context, userID string) error
- func (s *Service) AdminSetPassword(ctx context.Context, userID, new string) error
- func (s *Service) AssignRole(ctx context.Context, tenantSlug, userID, role string) error
- func (s *Service) AssignRoleBySlug(ctx context.Context, userID, slug string) error
- func (s *Service) AuthorizeServiceTokenResources(ctx context.Context, req ResourceScopeAuthorizationRequest) error
- func (s *Service) BanUser(ctx context.Context, userID string, reason *string, until *time.Time, ...) error
- func (s *Service) BeginPasswordReset(ctx context.Context, token string, sessionTTL time.Duration) (string, error)
- func (s *Service) Catalog() []PermissionDef
- func (s *Service) ChangePassword(ctx context.Context, userID, current, new string, keepSessionID *string) error
- func (s *Service) CheckPendingRegistrationConflict(ctx context.Context, email, username string) (bool, bool, error)
- func (s *Service) CheckPhoneRegistrationConflict(ctx context.Context, phone, username string) (bool, bool, error)
- func (s *Service) ClaimOrgNamespace(ctx context.Context, slug, ownerUserID string) (tenantID string, created bool, err error)
- func (s *Service) ClaimUserNamespace(ctx context.Context, slug string) (userID, tenantID string, created bool, err error)
- func (s *Service) CleanupExpiredAuthState(ctx context.Context) error
- func (s *Service) Clear2FAChallenge(ctx context.Context, userID string) error
- func (s *Service) ConfirmEmailChange(ctx context.Context, userID, code string) error
- func (s *Service) ConfirmEmailVerification(ctx context.Context, token string) (userID string, err error)
- func (s *Service) ConfirmPasswordReset(ctx context.Context, token, newPassword string) (string, error)
- func (s *Service) ConfirmPasswordResetWithSession(ctx context.Context, resetSession, newPassword string) (string, error)
- func (s *Service) ConfirmPendingPhoneRegistration(ctx context.Context, phone, code string) (userID string, err error)
- func (s *Service) ConfirmPendingPhoneRegistrationByToken(ctx context.Context, token string) (string, error)
- func (s *Service) ConfirmPendingRegistration(ctx context.Context, token string) (userID string, err error)
- func (s *Service) ConfirmPhoneChange(ctx context.Context, userID, phone, code string) error
- func (s *Service) ConfirmPhoneVerification(ctx context.Context, phone, code string) error
- func (s *Service) ConfirmPhoneVerificationByToken(ctx context.Context, token string) error
- func (s *Service) ConfirmPhoneVerificationByTokenUserID(ctx context.Context, token string) (string, error)
- func (s *Service) ConfirmPhoneVerificationUserID(ctx context.Context, phone, code string) (string, error)
- func (s *Service) CountProviderLinks(ctx context.Context, userID string) int
- func (s *Service) Create2FAChallenge(ctx context.Context, userID string) (string, error)
- func (s *Service) CreatePendingPhoneRegistration(ctx context.Context, phone, username, passwordHash string) (string, error)
- func (s *Service) CreatePendingRegistration(ctx context.Context, email, username, passwordHash string, ttl time.Duration) (string, error)
- func (s *Service) CreateTenant(ctx context.Context, slug string) (*Tenant, error)
- func (s *Service) CreateTenantInvite(ctx context.Context, tenantSlug, userID, invitedBy, role string, ...) (*TenantInvite, error)
- func (s *Service) CreateUser(ctx context.Context, email, username string) (*User, error)
- func (s *Service) DeclineTenantInvite(ctx context.Context, inviteID, userID string) error
- func (s *Service) DefineRole(ctx context.Context, tenantSlug, role string) error
- func (s *Service) DeleteRole(ctx context.Context, tenantSlug, role string) error
- func (s *Service) DeleteTenantIssuer(ctx context.Context, issuer string) error
- func (s *Service) DeriveUsername(email string) string
- func (s *Service) DeriveUsernameForOAuth(ctx context.Context, provider, preferred, email, displayName string) string
- func (s *Service) Disable2FA(ctx context.Context, userID string) error
- func (s *Service) EffectivePermissions(ctx context.Context, tenantSlug, userID string) ([]string, error)
- func (s *Service) EffectiveRolePermissions(ctx context.Context, tenantSlug, role string) ([]string, error)
- func (s *Service) Enable2FA(ctx context.Context, userID, method string, phoneNumber *string) ([]string, error)
- func (s *Service) EntitlementsProvider() EntitlementsProvider
- func (s *Service) EphemeralMode() EphemeralMode
- func (s *Service) ExchangeRefreshToken(ctx context.Context, refreshToken string, ua string, ip net.IP) (idToken string, expiresAt time.Time, newRefresh string, err error)
- func (s *Service) ExchangeRefreshTokenWithTenant(ctx context.Context, refreshToken string, ua string, ip net.IP, tenant string) (idToken string, expiresAt time.Time, newRefresh string, err error)
- func (s *Service) GenerateAvailableUsername(ctx context.Context, base string) string
- func (s *Service) GenerateSIWSChallenge(ctx context.Context, cache siws.ChallengeCache, ...) (siws.SignInInput, error)
- func (s *Service) Get2FASettings(ctx context.Context, userID string) (*TwoFactorSettings, error)
- func (s *Service) GetDiscordUsername(ctx context.Context, userID string) (string, error)
- func (s *Service) GetEmailByUserID(ctx context.Context, id string) (string, error)
- func (s *Service) GetOrgMetadata(ctx context.Context, tenantID string) (map[string]any, error)
- func (s *Service) GetOrgNamespaceState(ctx context.Context, tenantID string) (OwnerNamespaceState, error)
- func (s *Service) GetOwnerNamespaceStateBySlug(ctx context.Context, slug string) (OwnerNamespaceState, error)
- func (s *Service) GetPendingEmailChange(ctx context.Context, userID string) (string, error)
- func (s *Service) GetPendingPhoneRegistrationByPhone(ctx context.Context, phone string) (*PendingRegistration, error)
- func (s *Service) GetPendingRegistrationByEmail(ctx context.Context, email string) (*PendingRegistration, error)
- func (s *Service) GetPersonalOrgForUser(ctx context.Context, userID string) (*Tenant, error)
- func (s *Service) GetProviderLink(ctx context.Context, providerSlug, subject string) (string, *string, error)
- func (s *Service) GetProviderLinkByIssuer(ctx context.Context, issuer, subject string) (string, *string, error)
- func (s *Service) GetProviderUsername(ctx context.Context, userID, provider string) (string, error)
- func (s *Service) GetRolePermissions(ctx context.Context, tenantSlug, role string) ([]string, error)
- func (s *Service) GetSolanaAddress(ctx context.Context, userID string) (string, error)
- func (s *Service) GetTenantIssuer(ctx context.Context, issuer string) (*TenantIssuer, error)
- func (s *Service) GetUserByEmail(ctx context.Context, email string) (*User, error)
- func (s *Service) GetUserByPhone(ctx context.Context, phone string) (*User, error)
- func (s *Service) GetUserBySolanaAddress(ctx context.Context, address string) (*User, error)
- func (s *Service) GetUserByUsername(ctx context.Context, username string) (*User, error)
- func (s *Service) GetUserMetadata(ctx context.Context, userID string) (map[string]any, error)
- func (s *Service) HardDeleteUser(ctx context.Context, userID string) error
- func (s *Service) HasEmailSender() bool
- func (s *Service) HasPassword(ctx context.Context, userID string) bool
- func (s *Service) HasPermission(ctx context.Context, tenantSlug, userID, perm string) (bool, error)
- func (s *Service) HasSMSSender() bool
- func (s *Service) HostDeleteUser(ctx context.Context, id string, soft bool) error
- func (s *Service) ImportUser(ctx context.Context, input ImportUserInput) (*User, error)
- func (s *Service) IsOrgReserved(ctx context.Context, tenantID string) (bool, error)
- func (s *Service) IsTenantMember(ctx context.Context, tenantSlug, userID string) (bool, error)
- func (s *Service) IsUserAllowed(ctx context.Context, userID string) (bool, error)
- func (s *Service) IsUserReserved(ctx context.Context, userID string) (bool, error)
- func (s *Service) IssueAccessToken(ctx context.Context, userID, email string, extra map[string]any) (token string, expiresAt time.Time, err error)
- func (s *Service) IssueRefreshSession(ctx context.Context, userID, userAgent string, ip net.IP) (sessionID, refreshToken string, expiresAt *time.Time, err error)
- func (s *Service) IssueServiceToken(ctx context.Context, userID, email, tenantSlug string, extra map[string]any) (token string, expiresAt time.Time, err error)
- func (s *Service) JWKS() jwtkit.JWKS
- func (s *Service) Keyfunc() func(token *jwt.Token) (any, error)
- func (s *Service) LinkProvider(ctx context.Context, userID, provider, subject string, email *string) error
- func (s *Service) LinkProviderByIssuer(ctx context.Context, userID, issuer, providerSlug, subject string, ...) error
- func (s *Service) LinkSolanaWallet(ctx context.Context, cache siws.ChallengeCache, userID string, ...) error
- func (s *Service) ListEntitlements(ctx context.Context, userID string) []string
- func (s *Service) ListEntitlementsDetailed(ctx context.Context, userID string) []entpg.Entitlement
- func (s *Service) ListOrgAliases(ctx context.Context, tenantID string) ([]string, error)
- func (s *Service) ListOrgDefinedRoles(ctx context.Context, tenantSlug string) ([]string, error)
- func (s *Service) ListOrgMembers(ctx context.Context, tenantSlug string) ([]string, error)
- func (s *Service) ListRoleSlugsByUser(ctx context.Context, userID string) []string
- func (s *Service) ListServiceTokens(ctx context.Context, tenantSlug string) ([]ServiceToken, error)
- func (s *Service) ListTenantInvites(ctx context.Context, tenantSlug, status string) ([]TenantInvite, error)
- func (s *Service) ListTenantIssuers(ctx context.Context, activeOnly bool) ([]TenantIssuer, error)
- func (s *Service) ListTenantMembershipsForUser(ctx context.Context, userID string) ([]string, error)
- func (s *Service) ListUserInvites(ctx context.Context, userID, status string) ([]TenantInvite, error)
- func (s *Service) ListUserSessions(ctx context.Context, userID string) ([]Session, error)
- func (s *Service) ListUserSlugAliases(ctx context.Context, userID string) ([]string, error)
- func (s *Service) ListUserTenantMembershipsAndRoles(ctx context.Context, userID string) ([]TenantMembership, error)
- func (s *Service) ListUsersDeletedBefore(ctx context.Context, cutoff time.Time, limit int) ([]string, error)
- func (s *Service) LogPasswordChanged(ctx context.Context, userID string, sessionID string, ip *string, ua *string)
- func (s *Service) LogPasswordRecovery(ctx context.Context, userID string, method, sessionID string, ip *string, ...)
- func (s *Service) LogSessionCreated(ctx context.Context, userID string, method string, sessionID string, ...)
- func (s *Service) LogSessionFailed(ctx context.Context, userID string, sessionID string, reason *string, ...)
- func (s *Service) LookupOwnerNamespace(ctx context.Context, slug string) (*OwnerNamespaceLookup, error)
- func (s *Service) MarkSessionAuthenticated(ctx context.Context, userID, sessionID string) error
- func (s *Service) MintServiceToken(ctx context.Context, tenantSlug, name string, permissions []string, ...) (ServiceToken, string, error)
- func (s *Service) MintServiceTokenWithOptions(ctx context.Context, tenantSlug string, opts ServiceTokenMintOptions) (ServiceToken, string, error)
- func (s *Service) Options() Options
- func (s *Service) ParkOrgNamespace(ctx context.Context, slug string) (tenantID string, created bool, err error)
- func (s *Service) ParkUserNamespace(ctx context.Context, slug string) (userID, tenantID string, created bool, err error)
- func (s *Service) PasswordLogin(ctx context.Context, email, pass string, extra map[string]any) (string, time.Time, error)
- func (s *Service) PasswordLoginByUserID(ctx context.Context, userID, pass string, extra map[string]any) (string, time.Time, error)
- func (s *Service) PatchOrgMetadata(ctx context.Context, tenantID string, patch map[string]any) error
- func (s *Service) PatchUserMetadata(ctx context.Context, userID string, patch map[string]any) error
- func (s *Service) Postgres() *pgxpool.Pool
- func (s *Service) PromoteParkedOrgToRegistered(ctx context.Context, slug, ownerUserID string) (tenantID string, err error)
- func (s *Service) PromoteReservedNameToRegistered(ctx context.Context, slug, ownerUserID string) (tenantID string, created bool, err error)
- func (s *Service) PublicKeysByKID() map[string]crypto.PublicKey
- func (s *Service) ReadMemberRoles(ctx context.Context, tenantSlug, userID string) ([]string, error)
- func (s *Service) ReconcileTenantManifest(ctx context.Context, manifest TenantManifest, store TenantManifestTokenStore) (TenantManifestResult, error)
- func (s *Service) RegenerateBackupCodes(ctx context.Context, userID string) ([]string, error)
- func (s *Service) RemoveMember(ctx context.Context, tenantSlug, userID string) error
- func (s *Service) RemoveRoleBySlug(ctx context.Context, userID, slug string) error
- func (s *Service) RenameTenantSlug(ctx context.Context, tenantID, newSlug, actorUserID string) error
- func (s *Service) RenameTenantSlugForce(ctx context.Context, tenantID, newSlug, actorUserID string) error
- func (s *Service) RequestEmailChange(ctx context.Context, userID, newEmail string) error
- func (s *Service) RequestEmailVerification(ctx context.Context, email string, ttl time.Duration) error
- func (s *Service) RequestPasswordReset(ctx context.Context, email string, ttl time.Duration, ip *string, ua *string) error
- func (s *Service) RequestPhoneChange(ctx context.Context, userID, newPhone string) error
- func (s *Service) RequestPhonePasswordReset(ctx context.Context, phone string, ttl time.Duration, ip *string, ua *string) error
- func (s *Service) RequestPhoneVerification(ctx context.Context, phone string, ttl time.Duration) error
- func (s *Service) Require2FAForLogin(ctx context.Context, userID string) (string, error)
- func (s *Service) RequireFreshSession(ctx context.Context, userID, sessionID string, now time.Time) (SessionFreshness, error)
- func (s *Service) ResendEmailChangeCode(ctx context.Context, userID string) error
- func (s *Service) ResendPhoneChangeCode(ctx context.Context, userID, phone string) error
- func (s *Service) ReserveAccount(ctx context.Context, slug string) (userID, tenantID string, reserved bool, err error)
- func (s *Service) ResolveServiceToken(ctx context.Context, keyID, secret string) (tenantSlug string, permissions []string, err error)
- func (s *Service) ResolveServiceTokenWithResources(ctx context.Context, keyID, secret string) (ResolvedServiceToken, error)
- func (s *Service) ResolveSessionByRefresh(ctx context.Context, refreshToken string) (string, error)
- func (s *Service) ResolveTenantBySlug(ctx context.Context, slug string) (*Tenant, error)
- func (s *Service) ResolveUserBySlug(ctx context.Context, slug string) (userID string, username string, err error)
- func (s *Service) RestoreUser(ctx context.Context, id string) error
- func (s *Service) RestrictOwnerNamespaceSlugs(ctx context.Context, slugs []string) (restricted []string, alreadyRestricted []string, err error)
- func (s *Service) RevokeAllSessions(ctx context.Context, userID string, keepSessionID *string) error
- func (s *Service) RevokeServiceToken(ctx context.Context, tenantSlug, tokenID string) (bool, error)
- func (s *Service) RevokeSessionByID(ctx context.Context, sessionID string) error
- func (s *Service) RevokeSessionByIDForUser(ctx context.Context, userID, sessionID string) error
- func (s *Service) RevokeTenantInvite(ctx context.Context, tenantSlug, inviteID string) error
- func (s *Service) SendPhone2FASetupCode(ctx context.Context, userID, phone, code string) error
- func (s *Service) SendPhoneVerificationToUser(ctx context.Context, phone, userID string, ttl time.Duration) error
- func (s *Service) SendWelcome(ctx context.Context, userID string)
- func (s *Service) SessionFreshness(ctx context.Context, userID, sessionID string, now time.Time) (SessionFreshness, error)
- func (s *Service) SetEmailVerified(ctx context.Context, id string, v bool) error
- func (s *Service) SetOrgNamespaceState(ctx context.Context, tenantID string, state OwnerNamespaceState) error
- func (s *Service) SetPasswordAfterFreshAuth(ctx context.Context, userID, new string, keepSessionID *string) error
- func (s *Service) SetProviderUsername(ctx context.Context, userID, provider, subject, username string) error
- func (s *Service) SetRolePermissions(ctx context.Context, tenantSlug, role string, perms []string) error
- func (s *Service) SoftDeleteUser(ctx context.Context, id string) error
- func (s *Service) TimeUntilOrgRenameAvailable(ctx context.Context, tenantID string, now time.Time) (int64, error)
- func (s *Service) TimeUntilUsernameRenameAvailable(ctx context.Context, userID string, now time.Time) (int64, error)
- func (s *Service) TouchDelegatedUser(ctx context.Context, tenantSlug, issuer, subject string) (*DelegatedUser, error)
- func (s *Service) UnassignRole(ctx context.Context, tenantSlug, userID, role string) error
- func (s *Service) UnbanUser(ctx context.Context, userID string) error
- func (s *Service) UnlinkProvider(ctx context.Context, userID, provider string) error
- func (s *Service) UnrestrictOwnerNamespaceSlugs(ctx context.Context, slugs []string) (unrestricted []string, notRestricted []string, err error)
- func (s *Service) UpdateBiography(ctx context.Context, id string, bio *string) error
- func (s *Service) UpdateEmail(ctx context.Context, id, email string) error
- func (s *Service) UpdateImportedUser(ctx context.Context, userID string, input ImportUserInput) (*User, error)
- func (s *Service) UpdateUsername(ctx context.Context, id, username string) error
- func (s *Service) UpdateUsernameForce(ctx context.Context, id, username string) error
- func (s *Service) UpsertPasswordHash(ctx context.Context, userID, hash, algo string, params []byte) error
- func (s *Service) UpsertRoleBySlug(ctx context.Context, name, slug string, description *string) error
- func (s *Service) UpsertTenantIssuer(ctx context.Context, in TenantIssuer) (*TenantIssuer, error)
- func (s *Service) ValidateGrant(ctx context.Context, tenantSlug, actorUserID string, tokens []string, ...) (unknown, offending []string, err error)
- func (s *Service) ValidateUsernameForRegistration(ctx context.Context, username string) (string, error)
- func (s *Service) ValidateUsernameForUser(ctx context.Context, username, userID string) (slug, excludeOrgID string, err error)
- func (s *Service) ValidateVerificationConfiguration() error
- func (s *Service) Verify2FAChallenge(ctx context.Context, userID, challenge string) (bool, error)
- func (s *Service) Verify2FACode(ctx context.Context, userID, code string) (bool, error)
- func (s *Service) VerifyBackupCode(ctx context.Context, userID, backupCode string) (bool, error)
- func (s *Service) VerifyPendingPassword(ctx context.Context, email, pass string) bool
- func (s *Service) VerifyPhone2FASetupCode(ctx context.Context, userID, phone, code string) (bool, error)
- func (s *Service) VerifySIWSAndLogin(ctx context.Context, cache siws.ChallengeCache, output siws.SignInOutput, ...) (accessToken string, expiresAt time.Time, refreshToken, userID string, ...)
- func (s *Service) VerifyUserPassword(ctx context.Context, userID, pass string) bool
- func (s *Service) WithAuthLogger(l AuthEventLogger) *Service
- func (s *Service) WithEmailSender(sender EmailSender) *Service
- func (s *Service) WithEntitlements(p EntitlementsProvider) *Service
- func (s *Service) WithEphemeralStore(store EphemeralStore, mode EphemeralMode) *Service
- func (s *Service) WithPostgres(pool *pgxpool.Pool) *Service
- func (s *Service) WithSMSSender(sender SMSSender) *Service
- type ServiceToken
- type ServiceTokenMintOptions
- type ServiceTokenResource
- type Session
- type SessionEventType
- type SessionFreshness
- type SessionRevokeReason
- type Tenant
- type TenantInvite
- type TenantIssuer
- type TenantManifest
- type TenantManifestIssuer
- type TenantManifestResult
- type TenantManifestRole
- type TenantManifestServiceToken
- type TenantManifestServiceTokenOutput
- type TenantManifestTenant
- type TenantManifestTokenStore
- type TenantMembership
- type TwoFactorSettings
- type User
- type ValidationError
- type VerificationMessage
Constants ¶
const ( ErrCodeUsernameTooShort = "username_too_short" ErrCodeUsernameTooLong = "username_too_long" ErrCodeUsernameMustStartWithLetter = "username_must_start_with_letter" ErrCodeUsernameCannotContainAt = "username_cannot_contain_at" ErrCodeUsernameCannotStartWithPlus = "username_cannot_start_with_plus" ErrCodeUsernameInvalidCharacters = "username_invalid_characters" ErrCodeOwnerSlugTaken = "owner_slug_taken" ErrCodeUsernameNotAllowed = "username_not_allowed" ErrCodeRenameRateLimited = "rename_rate_limited" ErrCodeInvalidEmail = "invalid_email" ErrCodeInvalidPhoneNumber = "invalid_phone_number" ErrCodePasswordTooShort = "password_too_short" )
const ( // PermWildcard in a role's permission set means "all catalog permissions". PermWildcard = "*" // authkit base tenant-management permissions. They gate authkit's own // tenant-management endpoints via the permission system. PermTenantRolesManage = "tenant:roles:manage" // create/modify/delete roles + set role permissions PermTenantMembersManage = "tenant:members:manage" // add/remove members + grant/remove their roles PermTenantTokensManage = "tenant:service_tokens:manage" // mint/revoke service tokens PermTenantRead = "tenant:read" // view members/roles/tokens )
const SensitiveActionFreshAuthWindow = 30 * time.Minute
const SolanaProviderSlug = "solana"
SolanaProviderSlug is the provider slug used for Solana wallets.
Variables ¶
var ( // ErrUserBanned indicates the account is blocked from authenticating. ErrUserBanned = errors.New("user_banned") // ErrUserNotFound indicates a user does not exist (or is not visible). ErrUserNotFound = errors.New("user_not_found") // ErrEmailAlreadyVerified indicates an email verification request targeted an already-verified email. ErrEmailAlreadyVerified = errors.New("email_already_verified") // ErrPhoneAlreadyVerified indicates a phone verification request targeted an already-verified phone. ErrPhoneAlreadyVerified = errors.New("phone_already_verified") // ErrPendingRegistrationNotFound indicates a registration resend request did not match a pending registration. ErrPendingRegistrationNotFound = errors.New("pending_registration_not_found") // ErrRegistrationDisabled indicates a public user-creation path was attempted // while native-user registration is bootstrap-only. Existing-user // authentication is unaffected; only NEW account creation through // public/auto-registration is blocked. ErrRegistrationDisabled = errors.New("registration_disabled") // ErrTenantManagementDisabled indicates a public tenant onboarding/management path // was attempted while tenant registration is bootstrap-only. Embedded // bootstrap/admin core APIs remain available. ErrTenantManagementDisabled = errors.New("tenant_management_disabled") )
var ( ErrEmailDeliveryFailed = errors.New("email_delivery_failed") ErrSMSDeliveryFailed = errors.New("sms_delivery_failed") )
var ( ErrOwnerSlugTaken = errors.New("owner_slug_taken") ErrPersonalTenantLocked = errors.New("personal_tenant_locked") ErrInviteNotFound = errors.New("tenant_invite_not_found") ErrInviteNotPending = errors.New("tenant_invite_not_pending") ErrInviteNotForUser = errors.New("tenant_invite_not_for_user") ErrInviteExpired = errors.New("tenant_invite_expired") ErrPersonalOrgNotFound = errors.New("personal_tenant_not_found") )
var ( ErrOwnerNamespaceNotFound = errors.New("owner_namespace_not_found") ErrInvalidOwnerNamespaceState = errors.New("invalid_owner_namespace_state") ErrInvalidOwnerNamespaceTransition = errors.New("invalid_owner_namespace_transition") ErrOwnerMembershipRequired = errors.New("owner_membership_required") ErrOwnerNamespaceAlreadyClaimed = errors.New("owner_namespace_already_claimed") ErrOwnerNamespaceBatchEmpty = errors.New("owner_namespace_batch_empty") )
var ( ErrReservedAccountNotFound = errors.New("reserved_account_not_found") ErrReservedAccountClaimed = errors.New("reserved_account_claimed") )
var ( // ErrTenantIssuerNotFound indicates no tenant-tenant issuer matched. ErrTenantIssuerNotFound = errors.New("tenant_issuer_not_found") // ErrInvalidTenantIssuer indicates a malformed registration payload. ErrInvalidTenantIssuer = errors.New("invalid_tenant_issuer") )
var ( ErrTenantNotFound = errors.New("tenant_not_found") ErrNotTenantMember = errors.New("not_tenant_member") ErrInvalidTenantSlug = errors.New("invalid_tenant_slug") ErrInvalidTenantRole = errors.New("invalid_tenant_role") ErrProtectedTenantRole = errors.New("protected_tenant_role") ErrLastTenantOwner = errors.New("cannot_remove_last_owner") ErrPersonalTenantOwner = errors.New("cannot_remove_personal_tenant_owner") // ErrRenameRateLimited is returned when a rename attempt happens // within renameCooldown of the previous rename for the same row. // Admin override paths (RenameTenantSlugForce / RenameUsernameForce) // bypass the check. ErrRenameRateLimited = errors.New("rename_rate_limited") )
var ( // ErrInvalidAccessToken indicates a service token that does not exist, has a bad // secret, or whose owning tenant is gone. Deliberately indistinguishable from // a malformed token so callers learn nothing from the error. ErrInvalidAccessToken = errors.New("invalid_token") // ErrAccessTokenRevoked indicates the service token was explicitly revoked. ErrAccessTokenRevoked = errors.New("token_revoked") // ErrAccessTokenExpired indicates the service token is past its expires_at. ErrAccessTokenExpired = errors.New("token_expired") )
var ErrCannotRemoveLastAdminRole = errors.New("cannot_remove_last_admin_role")
var ErrInvalidDelegatedUser = errors.New("invalid_delegated_user")
var ErrInvalidTenantManifest = errors.New("invalid_tenant_manifest")
var ErrReauthenticationRequired = errors.New("reauth_required")
var ErrReservedRoleSlug = errors.New("reserved_role_slug")
var ErrUnknownPermission = errors.New("unknown_permission")
ErrUnknownPermission indicates a permission not present in the catalog.
var ErrUserRoleNotFound = errors.New("user_role_not_found")
Functions ¶
func FormatServiceToken ¶ added in v0.12.4
FormatServiceToken assembles the full presented token: <marker><key_id>_<secret>.
func HasServiceTokenPrefix ¶ added in v0.12.4
HasServiceTokenPrefix reports whether token carries the service-token marker for prefix. Used by middleware to route to the service-token path before attempting JWT verification.
func IsDevEnvironment ¶
IsDevEnvironment reports whether a host-provided environment string is non-production.
func IsReservedPermission ¶ added in v0.11.3
IsReservedPermission reports whether name is in authkit's reserved base namespace (an app catalog may not redefine these; service tokens may not hold them unless service token-grantable, see IsServiceTokenGrantableReservedPermission).
func IsServiceTokenGrantableReservedPermission ¶ added in v0.12.4
IsServiceTokenGrantableReservedPermission reports whether a reserved `tenant:` permission may be granted to a service token. Returns false for non-reserved names.
func NormalizeEmail ¶ added in v0.8.6
func NormalizePhone ¶ added in v0.8.6
func OwnerSlugFromUsername ¶ added in v0.8.6
func ParseServiceToken ¶ added in v0.12.4
ParseServiceToken splits a presented token into its key_id and secret. key_id and secret are base62 (no underscores), so the first "_" after the marker is the unambiguous delimiter. ok is false if the token lacks the marker or either part is empty.
func ServiceTokenMarker ¶ added in v0.12.4
ServiceTokenMarker returns the leading marker that identifies a service token for the given application prefix: "<prefix>_st_" when prefix is non-empty, else "st_".
func UsernameOwnerNamespaceError ¶ added in v0.8.6
func UsernameOwnerNamespaceError(lookup *OwnerNamespaceLookup, allowedUserID string) string
func ValidateEmail ¶ added in v0.8.6
func ValidatePassword ¶ added in v0.8.6
func ValidatePhone ¶ added in v0.8.6
func ValidateUsername ¶ added in v0.8.6
func ValidationErrorCode ¶ added in v0.8.6
ValidationErrorCode returns a stable validation code from err when possible.
func WithSessionRevokeReason ¶
func WithSessionRevokeReason(ctx context.Context, reason SessionRevokeReason) context.Context
WithSessionRevokeReason annotates ctx so revoke paths can emit a structured reason to the auth logger.
Types ¶
type AdminListUsersResult ¶
type AdminListUsersResult struct {
Users []AdminUser `json:"users"`
Total int64 `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
AdminListUsersResult contains paginated user list with total count
type AdminUser ¶
type AdminUser struct {
ID string `json:"id"`
Email *string `json:"email"` // Nullable for phone-only users
PhoneNumber *string `json:"phone_number"`
Username *string `json:"username"`
DiscordUsername *string `json:"discord_username"`
EmailVerified bool `json:"email_verified"`
PhoneVerified bool `json:"phone_verified"`
BannedAt *time.Time `json:"banned_at,omitempty"`
BannedUntil *time.Time `json:"banned_until,omitempty"`
BanReason *string `json:"ban_reason,omitempty"`
BannedBy *string `json:"banned_by,omitempty"`
DeletedAt *time.Time `json:"deleted_at"`
Biography *string `json:"biography"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
LastLogin *time.Time `json:"last_login"`
Roles []string `json:"roles"`
Entitlements []string `json:"entitlements"`
}
Admin listing/get/delete
type AuthEventLogReader ¶ added in v0.4.2
type AuthEventLogReader interface {
// ListSessionEvents returns session events matching any of the given event types.
// If userID is empty, returns events for all users.
ListSessionEvents(ctx context.Context, userID string, eventTypes ...SessionEventType) ([]AuthSessionEvent, error)
}
AuthEventLogReader allows listing session events filtered by event types and optional userID.
type AuthEventLogger ¶
type AuthEventLogger interface {
LogSessionEvent(ctx context.Context, e AuthSessionEvent) error
}
type AuthSessionEvent ¶
type AuthSessionEvent struct {
OccurredAt time.Time
Issuer string
UserID string
SessionID string
Event SessionEventType
Method *string
Reason *string
IPAddr *string
UserAgent *string
}
AuthSessionEvent is a best-effort, append-only session lifecycle record intended for external sinks.
ClickHouse schema expectation (see migrations/clickhouse): - issuer, user_id, session_id, event are required - method is typically set for SessionEventCreated - reason is typically set for SessionEventRevoked
type Config ¶
type Config struct {
Issuer string
IssuedAudiences []string // JWT audiences - tokens issued will contain ALL of these audiences
ExpectedAudiences []string
AccessTokenDuration time.Duration
RefreshTokenDuration time.Duration
// Session limits
SessionMaxPerUser int // 0 = unlimited, default 3 if unset by service; eviction is always evict-oldest
// Optional: if set, used for building absolute URLs (e.g., password reset/verify links).
// If empty and Issuer is a well-formed URL, NewFromConfig defaults BaseURL to Issuer.
BaseURL string
// FrontendCallbackPath is the host-owned frontend route that receives full-page
// OIDC login results. Empty defaults to "/login/callback".
FrontendCallbackPath string
// RegistrationVerification controls registration verification behavior.
// Valid values: "none", "optional", "required".
// Empty defaults to "none".
RegistrationVerification RegistrationVerificationPolicy
// AutoCreatePersonalTenants creates a personal tenant for each native user at
// signup. Direct host opt-in (authkit issue 60): tenants are always a supported
// primitive, so this is no longer gated on a global tenant mode. Empty/false
// means native users can exist without tenant rows; hosts that want
// personal/team workspaces opt in.
AutoCreatePersonalTenants bool
// NativeUserRegistrationMode controls public native-user self-registration.
// Empty defaults to "open". Non-open modes disable every public user
// creation path while leaving embedded admin/bootstrap core APIs available.
NativeUserRegistrationMode RegistrationMode
// TenantRegistrationMode controls public tenant onboarding/management.
// Empty defaults to "open". Non-open modes disable public tenant mutation
// routes while leaving manifest/admin/bootstrap core APIs available.
TenantRegistrationMode RegistrationMode
// Environment is a host-provided runtime mode string used for dev/prod behavior checks.
// Expected values include "prod"/"production" for production, anything else is treated as non-prod.
Environment string
// SolanaNetwork is a host-provided Solana chain selector ("mainnet", "testnet", "devnet").
// If empty, AuthKit derives a default from Environment.
SolanaNetwork string
// Keys can be nil - if nil, authkit auto-discovers keys with this priority:
// 1. Environment variables (ACTIVE_KEY_ID, ACTIVE_PRIVATE_KEY_PEM, PUBLIC_KEYS)
// 2. Filesystem /vault/auth/keys.json (External Secrets Operator in K8s)
// 3. Auto-generated keys in .runtime/authkit/ (development fallback)
Keys jwtkit.KeySource
// Providers – identity providers by name ("google", "apple", "github", "discord").
// Only client id/secret are required; standard scopes are derived from defaults.
Providers map[string]oidckit.RPConfig
// ProviderDescriptors define OAuth2/OIDC providers using config-first
// descriptors. These augment/override built-in Providers entries and are
// the preferred path for adding custom providers.
ProviderDescriptors map[string]authprovider.Provider
// ServiceTokenPrefix is the issuing application's BRAND prefix for Tenant
// Service Tokens (service tokens). It is a single value per deployment (NOT per-tenant)
// and a free brand choice by the host app — e.g. tensorhub sets "cozy" so
// every service token it mints is `cozy_st_<key_id>_<secret>`. The `_st_` type
// segment is fixed and not configurable. Empty -> bare `st_`. Must be
// lowercase alphanumeric, 1-16 chars. A unique app prefix lets leak
// scanners and push-protection partners identify the issuer at a glance.
ServiceTokenPrefix string
// ServiceTokenMaxTTL caps how far in the future a minted service token may expire.
// 0 (default) means no cap (tokens may be non-expiring). When set, a
// requested expiry beyond now+MaxTTL — including a null/no-expiry request —
// is capped to now+MaxTTL at mint time.
ServiceTokenMaxTTL time.Duration
// ResourceScopeAuthorizer optionally authorizes host-defined service token resource
// scopes during HTTP minting. AuthKit validates only shape/length and stores
// resource Kind/ID pairs opaquely; the embedding host owns semantic
// no-escalation such as "may this caller mint openrails.tenant_subject=cozy-art".
ResourceScopeAuthorizer ResourceScopeAuthorizer
// PermissionCatalog is the embedding application's set of valid permission
// strings (e.g. tensorhub's `endpoint:revise`, `repo:create`). authkit merges
// this with its own base permissions (the reserved `tenant:` namespace) to form
// the catalog it validates role/service token grants against. Permissions are opaque to
// authkit — it never interprets their meaning. Names must not collide with
// the reserved `tenant:` base permissions.
PermissionCatalog []PermissionDef
// DefaultRoles are role templates seeded into every tenant at creation, in
// addition to the built-in `owner` role (which is always seeded with `*`).
// e.g. tensorhub declares `admin` = {"*", "!tenant:roles:manage",
// "!tenant:members:manage"} (everything an owner has except role + membership
// management). Permission tokens: a concrete permission, `*` (all), or
// `!perm` (exclude).
DefaultRoles []DefaultRole
}
Config mirrors the simplicity of go-pkgz/auth: provide issuer, durations, and keys.
type DefaultRole ¶ added in v0.11.3
DefaultRole is a role template seeded into every tenant at creation: a role name and its permission set (tokens may include `*` and `!perm` exclusions).
type DelegatedUser ¶ added in v0.12.4
type DelegatedUser struct {
ID string
TenantSlug string
Issuer string
Subject string
CreatedAt time.Time
LastSeenAt time.Time
}
DelegatedUser is the minimal local record for an external OIDC subject that was accepted under a tenant issuer. AuthKit deliberately stores only the stable OIDC identity tuple plus first/last-seen timestamps.
type EmailSender ¶
type EmailSender interface {
SendVerification(ctx context.Context, email, username string, msg VerificationMessage) error
SendPasswordResetLink(ctx context.Context, email, username, token string) error
SendLoginCode(ctx context.Context, email, username, code string) error
SendWelcome(ctx context.Context, email, username string) error
}
EmailSender sends verification/login/reset emails.
type EntitlementsProvider ¶
type EntitlementsProvider interface {
ListEntitlements(ctx context.Context, userID string) ([]entpg.Entitlement, error)
}
EntitlementsProvider returns application entitlements for a user (e.g., billing tiers).
type EphemeralMode ¶
type EphemeralMode string
const ( EphemeralMemory EphemeralMode = "memory" EphemeralRedis EphemeralMode = "redis" )
type EphemeralStore ¶
type EphemeralStore interface {
Get(ctx context.Context, key string) ([]byte, bool, error)
Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
Del(ctx context.Context, key string) error
}
EphemeralStore is a minimal key-value interface used for short-lived auth state. Implementations should honor TTL on Set and treat missing keys as (found=false, err=nil).
type FileTenantManifestTokenStore ¶ added in v0.12.4
type FileTenantManifestTokenStore struct{}
FileTenantManifestTokenStore writes tokens to local files. It intentionally refuses Vault outputs; production deployments can provide a Vault-backed TenantManifestTokenStore with narrower deploy-time credentials.
func (FileTenantManifestTokenStore) ReadTenantManifestToken ¶ added in v0.12.4
func (FileTenantManifestTokenStore) ReadTenantManifestToken(_ context.Context, out TenantManifestServiceTokenOutput) (string, error)
func (FileTenantManifestTokenStore) WriteTenantManifestToken ¶ added in v0.12.4
func (FileTenantManifestTokenStore) WriteTenantManifestToken(_ context.Context, out TenantManifestServiceTokenOutput, token string) error
type ImportUserInput ¶ added in v0.9.0
type Options ¶
type Options struct {
Issuer string
IssuedAudiences []string // JWT audiences - tokens issued will contain ALL of these audiences
ExpectedAudiences []string
AccessTokenDuration time.Duration
RefreshTokenDuration time.Duration
SessionMaxPerUser int
// Optional link building (paths are fixed: /reset and /verify)
BaseURL string
// FrontendCallbackPath is the host-owned frontend route that receives full-page OIDC login results.
FrontendCallbackPath string
// RegistrationVerification controls whether registration verification is disabled,
// non-blocking, or required.
RegistrationVerification RegistrationVerificationPolicy
// AutoCreatePersonalTenants creates a personal tenant for each native user at
// signup (direct opt-in; authkit issue 60). False keeps native users
// tenant-free by default.
AutoCreatePersonalTenants bool
// NativeUserRegistrationMode controls public native-user self-registration.
NativeUserRegistrationMode RegistrationMode
// TenantRegistrationMode controls public tenant onboarding/management.
TenantRegistrationMode RegistrationMode
// Environment is host-provided runtime mode used for dev/prod behavior checks.
Environment string
// SolanaNetwork is host-provided chain selector for SIWS flows.
SolanaNetwork string
// ServiceTokenPrefix is the issuing application's brand prefix for Tenant
// Service Tokens (validated lowercase-alnum, 1-16 chars; empty -> bare st_).
ServiceTokenPrefix string
// ServiceTokenMaxTTL caps a minted service token's expiry (0 = no cap).
ServiceTokenMaxTTL time.Duration
// ResourceScopeAuthorizer optionally authorizes host-defined service token resource
// scopes during HTTP minting. Nil means AuthKit stores valid scopes
// opaquely for callers who may manage service tokens for the tenant.
ResourceScopeAuthorizer ResourceScopeAuthorizer
// PermissionCatalog is the app's permission vocabulary (merged with authkit's
// base `tenant:` permissions). DefaultRoles are role templates seeded per tenant.
PermissionCatalog []PermissionDef
DefaultRoles []DefaultRole
}
Options configures issued tokens and identifiers.
func (Options) AutoCreatePersonalTenantsEnabled ¶ added in v0.12.4
func (Options) PublicNativeUserRegistrationEnabled ¶ added in v0.12.4
PublicNativeUserRegistrationEnabled reports whether public native-user self-registration / auto-registration is allowed.
func (Options) PublicTenantRegistrationEnabled ¶ added in v0.12.4
PublicTenantRegistrationEnabled reports whether public tenant onboarding / management HTTP routes are allowed.
func (Options) RegistrationVerificationEnabled ¶ added in v0.5.0
func (Options) RegistrationVerificationPolicy ¶ added in v0.5.0
func (o Options) RegistrationVerificationPolicy() RegistrationVerificationPolicy
func (Options) RegistrationVerificationRequired ¶ added in v0.5.0
type OwnerNamespaceLookup ¶ added in v0.8.0
type OwnerNamespaceLookup struct {
RequestedSlug string
CanonicalSlug string
Status OwnerNamespaceLookupStatus
Claimable bool
Exists bool
EntityKind string
Renamed bool
HoldUntil *time.Time
User *OwnerNamespaceLookupUser
Tenant *OwnerNamespaceLookupTenant
}
type OwnerNamespaceLookupStatus ¶ added in v0.8.0
type OwnerNamespaceLookupStatus string
const ( OwnerNamespaceStatusRegisteredUser OwnerNamespaceLookupStatus = "registered_user" OwnerNamespaceStatusRegisteredTenant OwnerNamespaceLookupStatus = "registered_tenant" OwnerNamespaceStatusParkedUser OwnerNamespaceLookupStatus = "parked_user" OwnerNamespaceStatusParkedTenant OwnerNamespaceLookupStatus = "parked_tenant" OwnerNamespaceStatusRestrictedName OwnerNamespaceLookupStatus = "restricted_name" OwnerNamespaceStatusRenamedUser OwnerNamespaceLookupStatus = "renamed_user" OwnerNamespaceStatusRenamedTenant OwnerNamespaceLookupStatus = "renamed_tenant" OwnerNamespaceStatusHeldByDeletedUser OwnerNamespaceLookupStatus = "held_by_deleted_user" OwnerNamespaceStatusHeldByDeletedTenant OwnerNamespaceLookupStatus = "held_by_deleted_tenant" OwnerNamespaceStatusHeldByRecentUserRename OwnerNamespaceLookupStatus = "held_by_recent_user_rename" OwnerNamespaceStatusHeldByRecentOrgRename OwnerNamespaceLookupStatus = "held_by_recent_tenant_rename" OwnerNamespaceStatusUnregistered OwnerNamespaceLookupStatus = "unregistered" )
type OwnerNamespaceLookupTenant ¶ added in v0.12.4
type OwnerNamespaceLookupTenant struct {
ID string
Slug string
IsPersonal bool
OwnerUserID string
State OwnerNamespaceState
}
type OwnerNamespaceLookupUser ¶ added in v0.8.0
type OwnerNamespaceState ¶ added in v0.5.3
type OwnerNamespaceState string
const ( OwnerNamespaceStateRestrictedName OwnerNamespaceState = "restricted_name" OwnerNamespaceStateParkedTenant OwnerNamespaceState = "parked_tenant" OwnerNamespaceStateRegistered OwnerNamespaceState = "registered_tenant" )
type PendingRegistration ¶
PendingRegistration represents an unverified registration
type PermissionDef ¶ added in v0.11.3
type PermissionDef struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
}
PermissionDef is one entry in the permission catalog: an opaque permission string plus a human-readable description (surfaced to admin UIs).
func BasePermissions ¶ added in v0.11.3
func BasePermissions() []PermissionDef
BasePermissions are the tenant-management permissions authkit defines for every embedding app (reserved `tenant:` namespace).
type RegistrationMode ¶ added in v0.12.4
type RegistrationMode string
const ( RegistrationModeOpen RegistrationMode = "open" RegistrationModeInviteOnly RegistrationMode = "invite_only" RegistrationModeAdminOnly RegistrationMode = "admin_only" RegistrationModeAdminBootstrapOnly RegistrationMode = "admin_bootstrap_only" RegistrationModeManifestOnly RegistrationMode = "manifest_only" RegistrationModeClosed RegistrationMode = "closed" )
type RegistrationVerificationPolicy ¶ added in v0.5.0
type RegistrationVerificationPolicy string
const ( RegistrationVerificationNone RegistrationVerificationPolicy = "none" RegistrationVerificationOptional RegistrationVerificationPolicy = "optional" RegistrationVerificationRequired RegistrationVerificationPolicy = "required" )
type ResolvedServiceToken ¶ added in v0.12.4
type ResolvedServiceToken struct {
TokenID string
KeyID string
TenantSlug string
Permissions []string
Resources []ServiceTokenResource
}
ResolvedServiceToken is the resource-aware service token resolution result.
type ResourceScopeAuthorizationRequest ¶ added in v0.12.4
type ResourceScopeAuthorizationRequest struct {
TenantSlug string
ActorUserID string
Permissions []string
Resources []ServiceTokenResource
ActorGlobalAdmin bool
}
ResourceScopeAuthorizationRequest is passed to a host callback when the HTTP service token mint route receives resource scopes. AuthKit has already validated shape and permission no-escalation before this hook runs.
type ResourceScopeAuthorizer ¶ added in v0.12.4
type ResourceScopeAuthorizer func(ctx context.Context, req ResourceScopeAuthorizationRequest) error
ResourceScopeAuthorizer is an optional host callback for service token resource-scope no-escalation. Return an error to deny minting. AuthKit treats resource kinds and IDs as opaque and never interprets their semantics itself.
type SMSSender ¶
type SMSSender interface {
SendVerification(ctx context.Context, phone string, msg VerificationMessage) error
SendPasswordResetLink(ctx context.Context, phone, token string) error
SendLoginCode(ctx context.Context, phone, code string) error
}
SMSSender sends verification/login/reset SMS messages.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service is the core auth service used by HTTP adapters.
func NewFromConfig ¶
NewFromConfig creates a Service from high-level Config + Stores. If Keys is nil, auto-discovers keys from environment variables, filesystem, or generates development keys.
func NewService ¶
func (*Service) AcceptTenantInvite ¶ added in v0.12.4
func (*Service) AdminDeleteUser ¶
func (*Service) AdminGetUser ¶
func (*Service) AdminListUserSessions ¶
Helper exposed for admin endpoints
func (*Service) AdminListUsers ¶
func (*Service) AdminRevokeUserSessions ¶
func (*Service) AdminSetPassword ¶
AdminSetPassword force-sets a user's password (admin only, no current password required)
func (*Service) AssignRole ¶ added in v0.4.4
func (*Service) AssignRoleBySlug ¶
Exported wrappers for admin endpoints
func (*Service) AuthorizeServiceTokenResources ¶ added in v0.12.4
func (s *Service) AuthorizeServiceTokenResources(ctx context.Context, req ResourceScopeAuthorizationRequest) error
func (*Service) BanUser ¶
func (s *Service) BanUser(ctx context.Context, userID string, reason *string, until *time.Time, bannedBy string) error
BanUser disables a user account and stores ban metadata.
func (*Service) BeginPasswordReset ¶ added in v0.5.0
func (s *Service) BeginPasswordReset(ctx context.Context, token string, sessionTTL time.Duration) (string, error)
BeginPasswordReset validates and consumes a password reset token, then issues a short-lived one-time reset session for browser handoff.
func (*Service) Catalog ¶ added in v0.11.3
func (s *Service) Catalog() []PermissionDef
Catalog returns the full permission catalog: authkit base permissions plus the app-declared catalog (deduped, base wins on collision).
func (*Service) ChangePassword ¶
func (s *Service) ChangePassword(ctx context.Context, userID, current, new string, keepSessionID *string) error
ChangePassword sets or changes a user's password. If the user already has a password, current must verify; otherwise current is ignored. Always Argon2id-hashes the new password and upserts it, then revokes all other sessions for the user; caller may keep one active session via keepSessionID.
func (*Service) CheckPendingRegistrationConflict ¶
func (s *Service) CheckPendingRegistrationConflict(ctx context.Context, email, username string) (bool, bool, error)
CheckPendingRegistrationConflict checks if email or username exists in users or pending registration cache. Returns (emailTaken, usernameTaken, error)
func (*Service) CheckPhoneRegistrationConflict ¶
func (s *Service) CheckPhoneRegistrationConflict(ctx context.Context, phone, username string) (bool, bool, error)
CheckPhoneRegistrationConflict checks if phone or username exists in users OR pending tables. Returns (phoneTaken, usernameTaken, error)
func (*Service) ClaimOrgNamespace ¶ added in v0.5.3
func (s *Service) ClaimOrgNamespace(ctx context.Context, slug, ownerUserID string) (tenantID string, created bool, err error)
ClaimOrgNamespace claims tenant ownership for a specific existing user.
Rules:
- parked_tenant -> registered_tenant + owner membership assignment
- already-registered tenants return ErrOwnerNamespaceAlreadyClaimed
- restricted_name (or missing namespace) creates the tenant if needed, then claims it
- owner user must exist and not be soft-deleted
func (*Service) ClaimUserNamespace ¶ added in v0.6.0
func (s *Service) ClaimUserNamespace(ctx context.Context, slug string) (userID, tenantID string, created bool, err error)
ClaimUserNamespace ensures a slug resolves to a non-reserved user namespace.
Behavior:
- If no same-slug user exists, creates one (and a personal tenant) and marks it claimed.
- Clears user reserved metadata and any restricted-name marker for the slug.
- Forces the user's personal tenant namespace state to registered_tenant when present.
- If a same-slug non-personal tenant exists, returns ErrInvalidOwnerNamespaceTransition.
func (*Service) CleanupExpiredAuthState ¶ added in v0.9.0
CleanupExpiredAuthState removes expired transient AuthKit state.
func (*Service) Clear2FAChallenge ¶
Clear2FAChallenge removes the stored challenge after successful 2FA verification.
func (*Service) ConfirmEmailChange ¶
ConfirmEmailChange verifies the code and updates the user's email address. This is called when the user enters the verification code sent to their new email.
func (*Service) ConfirmEmailVerification ¶
func (s *Service) ConfirmEmailVerification(ctx context.Context, token string) (userID string, err error)
ConfirmEmailVerification verifies a token and marks email_verified = true. Returns the userID of the verified user.
func (*Service) ConfirmPasswordReset ¶
func (s *Service) ConfirmPasswordReset(ctx context.Context, token, newPassword string) (string, error)
ConfirmPasswordReset verifies token and sets a new password.
func (*Service) ConfirmPasswordResetWithSession ¶ added in v0.5.0
func (s *Service) ConfirmPasswordResetWithSession(ctx context.Context, resetSession, newPassword string) (string, error)
ConfirmPasswordResetWithSession consumes a reset session and sets the new password.
func (*Service) ConfirmPendingPhoneRegistration ¶
func (s *Service) ConfirmPendingPhoneRegistration(ctx context.Context, phone, code string) (userID string, err error)
ConfirmPendingPhoneRegistration verifies code and creates the actual user account. Implements "first to verify wins" - whoever verifies first gets the username/phone.
func (*Service) ConfirmPendingPhoneRegistrationByToken ¶ added in v0.5.0
func (s *Service) ConfirmPendingPhoneRegistrationByToken(ctx context.Context, token string) (string, error)
ConfirmPendingPhoneRegistrationByToken verifies a pending phone registration using either a manual code or a high-entropy link token.
func (*Service) ConfirmPendingRegistration ¶
func (s *Service) ConfirmPendingRegistration(ctx context.Context, token string) (userID string, err error)
ConfirmPendingRegistration verifies token and creates the actual user account. This implements "first to verify wins" - whoever verifies first gets the username/email.
func (*Service) ConfirmPhoneChange ¶
ConfirmPhoneChange verifies the code and updates the user's phone number. This is called when the user enters the verification code sent to their new phone.
func (*Service) ConfirmPhoneVerification ¶
ConfirmPhoneVerification verifies a token and marks phone_verified = true.
func (*Service) ConfirmPhoneVerificationByToken ¶ added in v0.5.0
ConfirmPhoneVerificationByToken verifies phone ownership using a one-click token.
func (*Service) ConfirmPhoneVerificationByTokenUserID ¶ added in v0.8.1
func (s *Service) ConfirmPhoneVerificationByTokenUserID(ctx context.Context, token string) (string, error)
ConfirmPhoneVerificationByTokenUserID verifies phone ownership using a one-click token and returns the user ID.
func (*Service) ConfirmPhoneVerificationUserID ¶ added in v0.8.1
func (s *Service) ConfirmPhoneVerificationUserID(ctx context.Context, phone, code string) (string, error)
ConfirmPhoneVerificationUserID verifies a token, marks phone_verified = true, and returns the user ID.
func (*Service) CountProviderLinks ¶
Public wrappers
func (*Service) Create2FAChallenge ¶
Create2FAChallenge creates a short-lived challenge to prove password verification before 2FA.
func (*Service) CreatePendingPhoneRegistration ¶
func (s *Service) CreatePendingPhoneRegistration(ctx context.Context, phone, username, passwordHash string) (string, error)
CreatePendingPhoneRegistration creates a pending phone registration and sends SMS verification code. Returns 6-digit code for verification. Code expires in 10 minutes (shorter than email).
func (*Service) CreatePendingRegistration ¶
func (s *Service) CreatePendingRegistration(ctx context.Context, email, username, passwordHash string, ttl time.Duration) (string, error)
CreatePendingRegistration creates a pending registration and sends verification email. Returns token for verification. Allows duplicate pending registrations (last one wins).
func (*Service) CreateTenant ¶ added in v0.12.4
func (*Service) CreateTenantInvite ¶ added in v0.12.4
func (*Service) CreateUser ¶
func (*Service) DeclineTenantInvite ¶ added in v0.12.4
func (*Service) DefineRole ¶ added in v0.4.4
func (*Service) DeleteRole ¶ added in v0.4.4
func (*Service) DeleteTenantIssuer ¶ added in v0.12.4
DeleteTenantIssuer removes a tenant issuer registration by OIDC issuer URL.
func (*Service) DeriveUsername ¶
func (*Service) DeriveUsernameForOAuth ¶
func (s *Service) DeriveUsernameForOAuth(ctx context.Context, provider, preferred, email, displayName string) string
DeriveUsernameForOAuth prefers provider-preferred usernames; falls back to email local part or display name.
func (*Service) Disable2FA ¶
Disable2FA disables two-factor authentication for a user
func (*Service) EffectivePermissions ¶ added in v0.11.3
func (s *Service) EffectivePermissions(ctx context.Context, tenantSlug, userID string) ([]string, error)
EffectivePermissions returns the union of permissions across all of the user's roles in the tenant, expanded against the catalog. This is the single source of truth for "what can this principal do" (the embedding app calls it at request time for enforcement — do NOT bake into the JWT).
func (*Service) EffectiveRolePermissions ¶ added in v0.11.3
func (s *Service) EffectiveRolePermissions(ctx context.Context, tenantSlug, role string) ([]string, error)
EffectiveRolePermissions returns a single role's permissions expanded against the catalog (`*` => all, `!p` => exclude). Used to enforce no-escalation when assigning a role to a member (the assigner must hold everything the role grants).
func (*Service) Enable2FA ¶
func (s *Service) Enable2FA(ctx context.Context, userID, method string, phoneNumber *string) ([]string, error)
Enable2FA enables two-factor authentication for a user and generates backup codes. Returns the plaintext backup codes (caller must show these to user ONCE).
func (*Service) EntitlementsProvider ¶
func (s *Service) EntitlementsProvider() EntitlementsProvider
func (*Service) EphemeralMode ¶
func (s *Service) EphemeralMode() EphemeralMode
func (*Service) ExchangeRefreshToken ¶
func (s *Service) ExchangeRefreshToken(ctx context.Context, refreshToken string, ua string, ip net.IP) (idToken string, expiresAt time.Time, newRefresh string, err error)
ExchangeRefreshToken rotates a refresh token and returns a new ID token + refresh token.
func (*Service) ExchangeRefreshTokenWithTenant ¶ added in v0.12.4
func (s *Service) ExchangeRefreshTokenWithTenant(ctx context.Context, refreshToken string, ua string, ip net.IP, tenant string) (idToken string, expiresAt time.Time, newRefresh string, err error)
ExchangeRefreshTokenWithTenant rotates a refresh token and returns a new service token + refresh token. If tenant is provided and tenant_mode=multi, it mints an tenant-scoped service token (tenant + roles for that tenant).
func (*Service) GenerateAvailableUsername ¶
GenerateAvailableUsername tries base, then minimal numeric suffixes, then a short fallback.
func (*Service) GenerateSIWSChallenge ¶
func (s *Service) GenerateSIWSChallenge(ctx context.Context, cache siws.ChallengeCache, domain, address, username string) (siws.SignInInput, error)
GenerateSIWSChallenge creates a new SIWS challenge for the given address. The challenge is stored in the cache and must be verified within 15 minutes.
func (*Service) Get2FASettings ¶
Get2FASettings retrieves a user's 2FA settings
func (*Service) GetDiscordUsername ¶
Convenience: Discord username
func (*Service) GetEmailByUserID ¶
func (*Service) GetOrgMetadata ¶ added in v0.4.8
func (*Service) GetOrgNamespaceState ¶ added in v0.5.3
func (*Service) GetOwnerNamespaceStateBySlug ¶ added in v0.5.3
func (*Service) GetPendingEmailChange ¶
GetPendingEmailChange retrieves the pending email change for a user, if any.
func (*Service) GetPendingPhoneRegistrationByPhone ¶
func (s *Service) GetPendingPhoneRegistrationByPhone(ctx context.Context, phone string) (*PendingRegistration, error)
GetPendingPhoneRegistrationByPhone looks up a pending phone registration by phone number.
func (*Service) GetPendingRegistrationByEmail ¶
func (s *Service) GetPendingRegistrationByEmail(ctx context.Context, email string) (*PendingRegistration, error)
GetPendingRegistrationByEmail looks up a pending registration by email.
func (*Service) GetPersonalOrgForUser ¶ added in v0.4.6
func (*Service) GetProviderLink ¶
func (s *Service) GetProviderLink(ctx context.Context, providerSlug, subject string) (string, *string, error)
Additional public helpers used by OIDC flow
func (*Service) GetProviderLinkByIssuer ¶
func (s *Service) GetProviderLinkByIssuer(ctx context.Context, issuer, subject string) (string, *string, error)
Issuer-based provider link helpers (preferred)
func (*Service) GetProviderUsername ¶
func (*Service) GetRolePermissions ¶ added in v0.11.3
func (s *Service) GetRolePermissions(ctx context.Context, tenantSlug, role string) ([]string, error)
GetRolePermissions returns a role's RAW permission tokens (may include `*` and `!p` exclusions).
func (*Service) GetSolanaAddress ¶
GetSolanaAddress retrieves the Solana wallet address linked to a user, if any.
func (*Service) GetTenantIssuer ¶ added in v0.12.4
GetTenantIssuer returns a tenant issuer by OIDC issuer URL.
func (*Service) GetUserByEmail ¶
func (*Service) GetUserByPhone ¶
GetUserByPhone looks up a user by phone number.
func (*Service) GetUserBySolanaAddress ¶
GetUserBySolanaAddress looks up a user by their Solana wallet address.
func (*Service) GetUserByUsername ¶
func (*Service) GetUserMetadata ¶ added in v0.4.8
func (*Service) HardDeleteUser ¶
HardDeleteUser permanently deletes the user row and dependent AuthKit rows via ON DELETE CASCADE.
func (*Service) HasEmailSender ¶
HasEmailSender returns true if an email sender is configured.
func (*Service) HasPassword ¶
func (*Service) HasPermission ¶ added in v0.11.3
HasPermission reports whether the user holds perm in the tenant.
func (*Service) HasSMSSender ¶
HasSMSSender returns true if an SMS sender is configured.
func (*Service) HostDeleteUser ¶
HostDeleteUser performs deletion on behalf of the host application. If soft is true, it performs a soft delete (see SoftDeleteUser). If false, it hard-deletes the user and all dependent rows via ON DELETE CASCADE.
func (*Service) ImportUser ¶ added in v0.9.0
func (*Service) IsOrgReserved ¶ added in v0.4.8
func (*Service) IsTenantMember ¶ added in v0.12.4
func (*Service) IsUserAllowed ¶
func (*Service) IsUserReserved ¶ added in v0.5.3
func (*Service) IssueAccessToken ¶
func (s *Service) IssueAccessToken(ctx context.Context, userID, email string, extra map[string]any) (token string, expiresAt time.Time, err error)
IssueAccessToken builds and signs an access token (JWT) for the given user. Includes core registered claims plus: - roles (snapshot, tenant_mode=single only) - entitlements (snapshot) - email, username, discord_username (if available) Extra claims in `extra` are merged into the token body (e.g., sid).
func (*Service) IssueRefreshSession ¶
func (s *Service) IssueRefreshSession(ctx context.Context, userID, userAgent string, ip net.IP) (sessionID, refreshToken string, expiresAt *time.Time, err error)
IssueRefreshSession creates a session row and returns a new refresh token string.
func (*Service) IssueServiceToken ¶ added in v0.12.4
func (s *Service) IssueServiceToken(ctx context.Context, userID, email, tenantSlug string, extra map[string]any) (token string, expiresAt time.Time, err error)
IssueServiceToken builds and signs a tenant-scoped service token (JWT) for the given user. Valid whenever the user is a member of the tenant (issue 60: tenants are always supported; no global mode gate). The token includes: - tenant (canonical slug) - roles (snapshot for that tenant)
func (*Service) Keyfunc ¶
Keyfunc looks up a public key by KID, falling back to the active key if missing.
func (*Service) LinkProvider ¶
func (*Service) LinkProviderByIssuer ¶
func (*Service) LinkSolanaWallet ¶
func (s *Service) LinkSolanaWallet(ctx context.Context, cache siws.ChallengeCache, userID string, output siws.SignInOutput) error
LinkSolanaWallet links a Solana wallet to an existing user account.
func (*Service) ListEntitlements ¶
ListEntitlements returns current entitlements for a user (fresh from provider).
func (*Service) ListEntitlementsDetailed ¶
ListEntitlementsDetailed returns detailed entitlements (name + metadata).
func (*Service) ListOrgAliases ¶ added in v0.4.6
ListOrgAliases returns every historical slug this tenant has held (excluding the current one). Source: `tenant_renames.from_slug` (issue #58). Distinct values.
func (*Service) ListOrgDefinedRoles ¶ added in v0.4.4
func (*Service) ListOrgMembers ¶ added in v0.4.4
func (*Service) ListRoleSlugsByUser ¶
Public helpers for HTTP adapters
func (*Service) ListServiceTokens ¶ added in v0.12.4
ListServiceTokens returns metadata for every service token of the tenant (including revoked/expired ones, so an admin can see and clean them up). The secret is never returned.
func (*Service) ListTenantInvites ¶ added in v0.12.4
func (*Service) ListTenantIssuers ¶ added in v0.12.4
ListTenantIssuers returns registered tenant issuers. When activeOnly is true, only enabled rows are returned.
func (*Service) ListTenantMembershipsForUser ¶ added in v0.12.4
func (*Service) ListUserInvites ¶ added in v0.4.6
func (*Service) ListUserSessions ¶
ListUserSessions lists active sessions for a user and issuer.
func (*Service) ListUserSlugAliases ¶ added in v0.4.6
ListUserSlugAliases returns every historical username this user has held (excluding the current one). Source: `user_renames.from_slug` (issue #58). Distinct values; order by usage timeline.
func (*Service) ListUserTenantMembershipsAndRoles ¶ added in v0.12.4
func (*Service) ListUsersDeletedBefore ¶
func (s *Service) ListUsersDeletedBefore(ctx context.Context, cutoff time.Time, limit int) ([]string, error)
ListUsersDeletedBefore returns user IDs for users soft-deleted before the cutoff. It is intended for retention/purge workflows in the host application.
func (*Service) LogPasswordChanged ¶ added in v0.4.2
func (s *Service) LogPasswordChanged(ctx context.Context, userID string, sessionID string, ip *string, ua *string)
LogPasswordChanged records a password change event for a user (best-effort).
func (*Service) LogPasswordRecovery ¶ added in v0.4.2
func (*Service) LogSessionCreated ¶
func (s *Service) LogSessionCreated(ctx context.Context, userID string, method string, sessionID string, ip *string, ua *string)
LogSessionCreated records a session creation event via the configured AuthEventLogger (best-effort).
func (*Service) LogSessionFailed ¶ added in v0.4.2
func (*Service) LookupOwnerNamespace ¶ added in v0.8.0
func (s *Service) LookupOwnerNamespace(ctx context.Context, slug string) (*OwnerNamespaceLookup, error)
LookupOwnerNamespace returns one canonical availability/routing view for an owner slug. It intentionally uses the same sources as both owner resolution and owner-slug availability so callers can distinguish "not registered" from "not resolvable but still held".
func (*Service) MarkSessionAuthenticated ¶ added in v0.8.3
func (*Service) MintServiceToken ¶ added in v0.12.4
func (s *Service) MintServiceToken(ctx context.Context, tenantSlug, name string, permissions []string, createdBy string, expiresAt *time.Time) (ServiceToken, string, error)
MintServiceToken inserts a new service token for the tenant and returns its metadata plus the full plaintext token (shown ONCE). permissions must already be authorized by the caller (the grant decision lives in the HTTP handler / host hook). expiresAt is optional (nil = no expiry) and is capped to ServiceTokenMaxTTL when set.
func (*Service) MintServiceTokenWithOptions ¶ added in v0.12.4
func (s *Service) MintServiceTokenWithOptions(ctx context.Context, tenantSlug string, opts ServiceTokenMintOptions) (ServiceToken, string, error)
MintServiceTokenWithOptions inserts a new service token using the resource-aware mint contract. Permissions and resources must already be authorized by the caller.
func (*Service) Options ¶
Options exposes immutable configuration for callers that need to validate claims.
func (*Service) ParkOrgNamespace ¶ added in v0.6.1
func (s *Service) ParkOrgNamespace(ctx context.Context, slug string) (tenantID string, created bool, err error)
ParkOrgNamespace parks `slug` as a parked_tenant. Works whether or not the slug is currently in owner_reserved_names — any caller-supplied slug is parkable, even bootstrap-reserved names like 'root' or 'admin'. If a reserved-name row exists it's deleted as part of the transaction. Internal-library API only — not exposed publicly.
func (*Service) ParkUserNamespace ¶ added in v0.6.0
func (s *Service) ParkUserNamespace(ctx context.Context, slug string) (userID, tenantID string, created bool, err error)
ParkUserNamespace ensures a slug is represented as a parked user namespace.
Behavior:
- If no same-slug user exists, creates a placeholder user (and personal tenant), then parks it.
- If a same-slug non-personal tenant exists, returns ErrInvalidOwnerNamespaceTransition.
- Requires the slug to be valid and available for user ownership semantics.
func (*Service) PasswordLogin ¶
func (s *Service) PasswordLogin(ctx context.Context, email, pass string, extra map[string]any) (string, time.Time, error)
PasswordLogin verifies credentials and issues an ID token.
func (*Service) PasswordLoginByUserID ¶
func (s *Service) PasswordLoginByUserID(ctx context.Context, userID, pass string, extra map[string]any) (string, time.Time, error)
PasswordLoginByUserID verifies credentials for a specific user ID and issues an ID token. This supports login flows where the identifier is a phone number or username and email may be NULL.
func (*Service) PatchOrgMetadata ¶ added in v0.4.8
func (*Service) PatchUserMetadata ¶ added in v0.4.8
func (*Service) PromoteParkedOrgToRegistered ¶ added in v0.5.3
func (*Service) PromoteReservedNameToRegistered ¶ added in v0.5.3
func (s *Service) PromoteReservedNameToRegistered(ctx context.Context, slug, ownerUserID string) (tenantID string, created bool, err error)
PromoteReservedNameToRegistered supports direct handoff in one operation:
restricted_name -> parked_tenant -> registered_tenant
It is idempotent for already-registered tenants and optionally ensures owner membership.
func (*Service) PublicKeysByKID ¶ added in v0.6.0
PublicKeysByKID returns the public keys indexed by key ID.
func (*Service) ReadMemberRoles ¶ added in v0.4.4
func (*Service) ReconcileTenantManifest ¶ added in v0.12.4
func (s *Service) ReconcileTenantManifest(ctx context.Context, manifest TenantManifest, store TenantManifestTokenStore) (TenantManifestResult, error)
ReconcileTenantManifest idempotently applies tenants, issuers, roles, and service-token outputs. It serializes reconciliation with a Postgres advisory lock so multiple replicas do not mint duplicate bootstrap tokens.
func (*Service) RegenerateBackupCodes ¶
RegenerateBackupCodes generates new backup codes for a user (invalidating old ones). Returns the plaintext codes (caller must show these to user ONCE).
func (*Service) RemoveMember ¶ added in v0.4.4
func (*Service) RemoveRoleBySlug ¶
func (*Service) RenameTenantSlug ¶ added in v0.12.4
func (s *Service) RenameTenantSlug(ctx context.Context, tenantID, newSlug, actorUserID string) error
RenameTenantSlug renames a non-personal tenant. Subject to the 72h `renameCooldown`. Personal tenants are renamed implicitly by the user- rename flow (see service.go) and reject this entrypoint with `ErrPersonalTenantLocked`.
`actorUserID` is recorded on the rename audit row. Pass empty string when the caller doesn't have an authenticated user (e.g. internal admin tooling without an actor); the column is nullable.
func (*Service) RenameTenantSlugForce ¶ added in v0.12.4
func (s *Service) RenameTenantSlugForce(ctx context.Context, tenantID, newSlug, actorUserID string) error
RenameTenantSlugForce is the admin-override variant that skips the 72h cooldown check. Otherwise identical to RenameTenantSlug. Caller is responsible for gating this behind admin scope upstream.
func (*Service) RequestEmailChange ¶
RequestEmailChange initiates an email change by sending a verification code to the new email. The current email is NOT changed until the user confirms via ConfirmEmailChange. Also sends a notification to the old email for security.
func (*Service) RequestEmailVerification ¶
func (s *Service) RequestEmailVerification(ctx context.Context, email string, ttl time.Duration) error
RequestEmailVerification creates a verification code and dispatches an email.
func (*Service) RequestPasswordReset ¶
func (s *Service) RequestPasswordReset(ctx context.Context, email string, ttl time.Duration, ip *string, ua *string) error
RequestPasswordReset creates a password reset token and dispatches a reset link via email. Returns nil for unknown emails to prevent user enumeration (202-like behavior).
func (*Service) RequestPhoneChange ¶
RequestPhoneChange initiates a phone number change by sending a verification code to the new phone. The current phone is NOT changed until the user confirms via ConfirmPhoneChange.
func (*Service) RequestPhonePasswordReset ¶
func (s *Service) RequestPhonePasswordReset(ctx context.Context, phone string, ttl time.Duration, ip *string, ua *string) error
RequestPhonePasswordReset creates a password reset token and sends a reset link via SMS. Always returns nil for unknown phone numbers to prevent user enumeration (202-like behavior).
func (*Service) RequestPhoneVerification ¶
func (s *Service) RequestPhoneVerification(ctx context.Context, phone string, ttl time.Duration) error
RequestPhoneVerification looks up the user by phone number and sends a verification code. This mirrors the RequestEmailVerification pattern - caller only needs to provide the phone number.
func (*Service) Require2FAForLogin ¶
Require2FAForLogin sends a 2FA code to the user's configured method. Returns the destination (email/phone) where the code was sent. This should be called after successful password verification.
func (*Service) RequireFreshSession ¶ added in v0.8.3
func (*Service) ResendEmailChangeCode ¶
ResendEmailChangeCode resends the verification code for a pending email change.
func (*Service) ResendPhoneChangeCode ¶
ResendPhoneChangeCode resends the verification code for a pending phone change.
func (*Service) ReserveAccount ¶ added in v0.4.8
func (s *Service) ReserveAccount(ctx context.Context, slug string) (userID, tenantID string, reserved bool, err error)
ReserveAccount reserves a namespace slug without requiring a same-slug login user. For legacy placeholder rows, it still enforces non-loginable reserved invariants.
func (*Service) ResolveServiceToken ¶ added in v0.12.4
func (s *Service) ResolveServiceToken(ctx context.Context, keyID, secret string) (tenantSlug string, permissions []string, err error)
ResolveServiceToken validates a presented service token (key_id + secret) and returns the owning tenant's current slug and the token's frozen permissions. It performs an indexed lookup by key_id, a constant-time secret compare, and revoked / expired / tenant-deleted checks, then best-effort async-touches last_used_at.
func (*Service) ResolveServiceTokenWithResources ¶ added in v0.12.4
func (s *Service) ResolveServiceTokenWithResources(ctx context.Context, keyID, secret string) (ResolvedServiceToken, error)
ResolveServiceTokenWithResources validates a presented service token and returns the full resource-aware result. Existing tokens with no resources return an empty Resources slice and remain tenant-wide for hosts that use the compatibility resolver.
func (*Service) ResolveSessionByRefresh ¶
ResolveSessionByRefresh finds the session id for a presented refresh token, if valid and active.
func (*Service) ResolveTenantBySlug ¶ added in v0.12.4
ResolveTenantBySlug resolves an tenant by current slug or alias. Returns ErrTenantNotFound when no tenant matches.
func (*Service) ResolveUserBySlug ¶ added in v0.4.6
func (*Service) RestoreUser ¶
RestoreUser clears deleted_at and re-enables the account.
func (*Service) RestrictOwnerNamespaceSlugs ¶ added in v0.5.3
func (s *Service) RestrictOwnerNamespaceSlugs(ctx context.Context, slugs []string) (restricted []string, alreadyRestricted []string, err error)
RestrictOwnerNamespaceSlugs adds slugs to the restricted-name blocklist. It is an admin operation separate from park/claim tenant lifecycle transitions.
func (*Service) RevokeAllSessions ¶
func (*Service) RevokeServiceToken ¶ added in v0.12.4
RevokeServiceToken marks the service token revoked. It is scoped to the tenant so a token cannot be revoked from a different tenant. Returns false if no matching, not-already-revoked token exists.
func (*Service) RevokeSessionByID ¶
func (*Service) RevokeSessionByIDForUser ¶
RevokeSessionByIDForUser revokes a session by id ensuring it belongs to the user.
func (*Service) RevokeTenantInvite ¶ added in v0.12.4
func (*Service) SendPhone2FASetupCode ¶
SendPhone2FASetupCode generates and sends a 6-digit code for 2FA setup to the user's phone.
func (*Service) SendPhoneVerificationToUser ¶
func (s *Service) SendPhoneVerificationToUser(ctx context.Context, phone, userID string, ttl time.Duration) error
SendPhoneVerificationToUser creates a verification code and sends it via SMS to a known user. Use RequestPhoneVerification if you only have a phone number and need to look up the user. Always returns nil for security.
func (*Service) SendWelcome ¶
SendWelcome triggers the welcome email if an EmailSender is configured.
func (*Service) SessionFreshness ¶ added in v0.8.3
func (*Service) SetEmailVerified ¶
func (*Service) SetOrgNamespaceState ¶ added in v0.5.3
func (*Service) SetPasswordAfterFreshAuth ¶ added in v0.8.3
func (*Service) SetProviderUsername ¶
func (*Service) SetRolePermissions ¶ added in v0.11.3
func (s *Service) SetRolePermissions(ctx context.Context, tenantSlug, role string, perms []string) error
SetRolePermissions replaces a role's permission set (idempotent). The role must already exist (created via DefineRole). Tokens are stored as-is (opaque); callers should validate via ValidateGrant first for no-escalation.
func (*Service) SoftDeleteUser ¶
SoftDeleteUser marks the user deleted and sets deleted_at without dropping rows. Also revokes all refresh sessions for this issuer.
func (*Service) TimeUntilOrgRenameAvailable ¶ added in v0.9.4
func (*Service) TimeUntilUsernameRenameAvailable ¶ added in v0.8.6
func (*Service) TouchDelegatedUser ¶ added in v0.12.4
func (s *Service) TouchDelegatedUser(ctx context.Context, tenantSlug, issuer, subject string) (*DelegatedUser, error)
TouchDelegatedUser records that tenantSlug accepted issuer+subject. The row is idempotent and updates last_seen_at on repeat use.
func (*Service) UnassignRole ¶ added in v0.4.4
func (*Service) UnlinkProvider ¶
func (*Service) UnrestrictOwnerNamespaceSlugs ¶ added in v0.5.3
func (s *Service) UnrestrictOwnerNamespaceSlugs(ctx context.Context, slugs []string) (unrestricted []string, notRestricted []string, err error)
UnrestrictOwnerNamespaceSlugs removes slugs from the restricted-name blocklist.
func (*Service) UpdateBiography ¶
func (*Service) UpdateEmail ¶
func (*Service) UpdateImportedUser ¶ added in v0.9.0
func (*Service) UpdateUsername ¶
func (*Service) UpdateUsernameForce ¶ added in v0.7.0
UpdateUsernameForce is the admin override that skips the 72h cooldown check. Otherwise identical to UpdateUsername. Caller is responsible for gating this behind admin scope upstream.
func (*Service) UpsertPasswordHash ¶
func (*Service) UpsertRoleBySlug ¶ added in v0.9.0
func (*Service) UpsertTenantIssuer ¶ added in v0.12.4
func (s *Service) UpsertTenantIssuer(ctx context.Context, in TenantIssuer) (*TenantIssuer, error)
UpsertTenantIssuer registers or updates a tenant-owned OIDC issuer.
func (*Service) ValidateGrant ¶ added in v0.11.3
func (s *Service) ValidateGrant(ctx context.Context, tenantSlug, actorUserID string, tokens []string, actorAll bool) (unknown, offending []string, err error)
ValidateGrant checks a set of permission tokens an actor wants to assign to a role: every concrete permission must be in the catalog (else returned in unknown) AND within the actor's effective permissions (else returned in offending); `*` requires the actor to effectively hold the whole catalog; `!p` exclusions only subtract and are always allowed. `actorAll` short-circuits the no-escalation check for an actor known to hold everything (e.g. a platform global admin). Returns (unknown, offending).
func (*Service) ValidateUsernameForRegistration ¶ added in v0.8.6
func (*Service) ValidateUsernameForUser ¶ added in v0.8.6
func (*Service) ValidateVerificationConfiguration ¶ added in v0.5.0
ValidateVerificationConfiguration ensures registration verification policy can be satisfied by currently configured delivery senders.
func (*Service) Verify2FAChallenge ¶
Verify2FAChallenge verifies the challenge created during the password step.
func (*Service) Verify2FACode ¶
Verify2FACode verifies a 2FA code entered by the user during login. Returns true if code is valid, false otherwise.
func (*Service) VerifyBackupCode ¶
VerifyBackupCode verifies a 2FA backup code for account recovery. On success, removes the used backup code from the user's backup codes.
func (*Service) VerifyPendingPassword ¶
VerifyPendingPassword checks if the provided password matches the pending registration's hash. Returns true if password is correct, false otherwise.
func (*Service) VerifyPhone2FASetupCode ¶
func (s *Service) VerifyPhone2FASetupCode(ctx context.Context, userID, phone, code string) (bool, error)
VerifyPhone2FASetupCode checks the code for 2FA phone setup.
func (*Service) VerifySIWSAndLogin ¶
func (s *Service) VerifySIWSAndLogin(ctx context.Context, cache siws.ChallengeCache, output siws.SignInOutput, extra map[string]any) (accessToken string, expiresAt time.Time, refreshToken, userID string, created bool, err error)
VerifySIWSAndLogin verifies a SIWS signature and logs in or creates a user. Returns service token, expiry, refresh token, user ID, and whether a new user was created.
func (*Service) VerifyUserPassword ¶ added in v0.5.1
VerifyUserPassword checks a user's password without issuing tokens or updating last-login. Returns true if the password is correct, false otherwise.
func (*Service) WithAuthLogger ¶
func (s *Service) WithAuthLogger(l AuthEventLogger) *Service
WithAuthLogger sets the authentication event logger (e.g., ClickHouse sink).
func (*Service) WithEmailSender ¶
func (s *Service) WithEmailSender(sender EmailSender) *Service
WithEmailSender sets the email sender dependency.
func (*Service) WithEntitlements ¶
func (s *Service) WithEntitlements(p EntitlementsProvider) *Service
WithEntitlements sets the entitlements provider.
func (*Service) WithEphemeralStore ¶
func (s *Service) WithEphemeralStore(store EphemeralStore, mode EphemeralMode) *Service
func (*Service) WithPostgres ¶
WithPostgres attaches a pgx pool to the service.
func (*Service) WithSMSSender ¶
WithSMSSender sets the SMS sender dependency.
type ServiceToken ¶ added in v0.12.4
type ServiceToken struct {
ID string
KeyID string
Name string
Permissions []string
Resources []ServiceTokenResource
CreatedBy string
CreatedAt time.Time
LastUsedAt *time.Time
ExpiresAt *time.Time
RevokedAt *time.Time
}
ServiceToken is the non-secret metadata view of a service token. The secret is never stored or returned after creation.
type ServiceTokenMintOptions ¶ added in v0.12.4
type ServiceTokenMintOptions struct {
Name string
Permissions []string
Resources []ServiceTokenResource
CreatedBy string
ExpiresAt *time.Time
}
ServiceTokenMintOptions is the resource-aware service token mint request. The token format remains unchanged; resources are stored beside the opaque credential.
type ServiceTokenResource ¶ added in v0.12.4
ServiceTokenResource is one opaque, host-defined resource scope carried by a service token. AuthKit stores and returns the exact Kind/ID pair but does not interpret it. Hosts own resource semantics, including any wildcard-looking IDs such as "*".
type Session ¶
type Session struct {
ID string
FamilyID string
CreatedAt time.Time
LastAuthenticatedAt *time.Time
LastUsedAt time.Time
ExpiresAt *time.Time
RevokedAt *time.Time
UserAgent *string
IPAddr *string
}
Session represents a sanitized session view (no tokens).
type SessionEventType ¶
type SessionEventType string
SessionEventType identifies a session lifecycle event.
const ( SessionEventCreated SessionEventType = "session_created" SessionEventRevoked SessionEventType = "session_revoked" SessionEventPasswordChange SessionEventType = "password_changed" SessionEventPasswordRecovery SessionEventType = "password_recovery" SessionEventFailed SessionEventType = "session_failed" )
type SessionFreshness ¶ added in v0.8.3
type SessionRevokeReason ¶
type SessionRevokeReason string
SessionRevokeReason identifies why a session (or set of sessions) was revoked.
const ( SessionRevokeReasonUnknown SessionRevokeReason = "" SessionRevokeReasonLogout SessionRevokeReason = "logout" SessionRevokeReasonUserRevoke SessionRevokeReason = "user_revoke" SessionRevokeReasonUserRevokeAll SessionRevokeReason = "user_revoke_all" SessionRevokeReasonAdminRevoke SessionRevokeReason = "admin_revoke" SessionRevokeReasonAdminRevokeAll SessionRevokeReason = "admin_revoke_all" SessionRevokeReasonPasswordChange SessionRevokeReason = "password_change" SessionRevokeReasonAdminSetPassword SessionRevokeReason = "admin_set_password" SessionRevokeReasonUserDisabled SessionRevokeReason = "user_disabled" SessionRevokeReasonBanned SessionRevokeReason = "banned" SessionRevokeReasonSoftDeleted SessionRevokeReason = "soft_deleted" SessionRevokeReasonEvicted SessionRevokeReason = "evicted" SessionRevokeReasonRefreshReuseDetected SessionRevokeReason = "refresh_reuse_detected" )
type TenantInvite ¶ added in v0.12.4
type TenantInvite struct {
ID string `json:"id"`
Tenant string `json:"tenant"`
UserID string `json:"user_id"`
InvitedBy string `json:"invited_by"`
Role string `json:"role"`
Status string `json:"status"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
ActedAt *time.Time `json:"acted_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
type TenantIssuer ¶ added in v0.12.4
type TenantIssuer struct {
ID string
TenantSlug string
Issuer string // OIDC iss
JWKSURI string // OIDC jwks_uri
Audiences []string
Enabled bool
CreatedAt time.Time
UpdatedAt time.Time
}
TenantIssuer is a registered tenant-owned issuer. A tenant brings its own users that authenticate via the tenant's issuer; this record is the resource server side's trusted OIDC issuer registration.
type TenantManifest ¶ added in v0.12.4
type TenantManifest struct {
Tenants []TenantManifestTenant `json:"tenants" yaml:"tenants"`
}
TenantManifest is the DevOps source of truth for closed-registration AuthKit deployments. It declares tenants plus their trusted OIDC issuers, roles, and optional server-to-server service tokens.
func ParseTenantManifestYAML ¶ added in v0.12.4
func ParseTenantManifestYAML(raw []byte) (TenantManifest, error)
ParseTenantManifestYAML parses a tenant manifest and rejects unknown fields.
func ParseTenantManifestYAMLFile ¶ added in v0.12.4
func ParseTenantManifestYAMLFile(path string) (TenantManifest, error)
type TenantManifestIssuer ¶ added in v0.12.4
type TenantManifestResult ¶ added in v0.12.4
type TenantManifestRole ¶ added in v0.12.4
type TenantManifestServiceToken ¶ added in v0.12.4
type TenantManifestServiceToken struct {
Name string `json:"name" yaml:"name"`
Permissions []string `json:"permissions" yaml:"permissions"`
Resources []ServiceTokenResource `json:"resources" yaml:"resources"`
ExpiresAt *time.Time `json:"expires_at" yaml:"expires_at"`
Output TenantManifestServiceTokenOutput `json:"output" yaml:"output"`
}
type TenantManifestServiceTokenOutput ¶ added in v0.12.4
type TenantManifestServiceTokenOutput struct {
File string `json:"file" yaml:"file"`
VaultMount string `json:"vault_mount" yaml:"vault_mount"`
VaultPath string `json:"vault_path" yaml:"vault_path"`
VaultField string `json:"vault_field" yaml:"vault_field"`
}
TenantManifestServiceTokenOutput names where a freshly minted token should be written. AuthKit ships a file-backed implementation; Vault/Kubernetes/etc. can implement TenantManifestTokenStore with the same output struct.
type TenantManifestTenant ¶ added in v0.12.4
type TenantManifestTenant struct {
Slug string `json:"slug" yaml:"slug"`
Issuers []TenantManifestIssuer `json:"issuers" yaml:"issuers"`
Roles []TenantManifestRole `json:"roles" yaml:"roles"`
ServiceTokens []TenantManifestServiceToken `json:"service_tokens" yaml:"service_tokens"`
}
type TenantManifestTokenStore ¶ added in v0.12.4
type TenantManifestTokenStore interface {
ReadTenantManifestToken(ctx context.Context, out TenantManifestServiceTokenOutput) (string, error)
WriteTenantManifestToken(ctx context.Context, out TenantManifestServiceTokenOutput, token string) error
}
TenantManifestTokenStore preserves existing non-empty outputs and writes newly minted service-token values. The store owns the output backend.
type TenantMembership ¶ added in v0.12.4
TenantMembership is a user's membership with optional roles.
type TwoFactorSettings ¶
type TwoFactorSettings struct {
UserID string
Enabled bool
Method string // "email" or "sms"
PhoneNumber *string
BackupCodes []string // Hashed backup codes
CreatedAt time.Time
UpdatedAt time.Time
}
TwoFactorSettings represents a user's 2FA configuration
type User ¶
type User struct {
ID string
Email *string // Nullable - phone-only users have NULL email
PhoneNumber *string
Username *string
DiscordUsername *string
EmailVerified bool
PhoneVerified bool
BannedAt *time.Time
BannedUntil *time.Time
BanReason *string
BannedBy *string
DeletedAt *time.Time
Biography *string
CreatedAt time.Time
UpdatedAt time.Time
LastLogin *time.Time
}
type ValidationError ¶ added in v0.8.6
ValidationError is the stable identity-policy error returned by AuthKit validation helpers. Code is intended to be exposed directly in route responses as {"error":"code"}.
func (*ValidationError) Error ¶ added in v0.8.6
func (e *ValidationError) Error() string
type VerificationMessage ¶ added in v0.5.0
type VerificationMessage struct {
// Fixed-length numeric code for manual entry (optional).
Code string
// High-entropy token for one-click verification link flow (optional).
LinkToken string
}
func (VerificationMessage) Validate ¶ added in v0.5.0
func (m VerificationMessage) Validate() error
Source Files
¶
- audit.go
- audit_context.go
- cleanup.go
- config.go
- delegated_users.go
- ephemeral.go
- ephemeral_data.go
- identity_validation.go
- owner_namespace_lookup.go
- rename_policy.go
- service.go
- service_owner_namespace.go
- service_owner_namespace_state.go
- service_reserved_accounts.go
- service_sessions.go
- service_solana.go
- service_tenant_invites.go
- service_tenant_issuers.go
- service_tenants.go
- service_tokens.go
- tenant_manifest.go
- tenant_role_permissions.go
- user_purge.go
- username.go
- uuid.go