engine

package
v0.149.0 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2026 License: MIT Imports: 77 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Migrate

func Migrate(ctx context.Context, pool *pgxpool.Pool, cfg config.Config, opts config.MigrateOptions) error

Migrate applies AuthKit's PostgreSQL migrations to cfg.Schema, and River's unless cfg.River.HostOwned; see authkit.Migrate.

func ParseBootstrapManifestYAML added in v0.148.0

func ParseBootstrapManifestYAML(raw []byte) (iam.BootstrapManifest, error)

ParseBootstrapManifestYAML parses and structurally validates a manifest, with no catalog or environment: each root_role must be a root role (`root:admin`), and ApplyBootstrapManifest checks it against the catalog. An unknown key is logged as a warning, with its path, and ignored.

Types

type Authenticator

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

Authenticator authenticates requests against this deployment: its API keys, the tokens it issues (verified statelessly against its live key source) and the tokens its stored remote applications issue (federation), for a set of audiences. The engine's own serves AuthKit's routes and the Client; NewAuthenticator builds one for a host resource server.

func (*Authenticator) CheckIssuerKeys

func (a *Authenticator) CheckIssuerKeys(ctx context.Context) error

CheckIssuerKeys is the no-I/O health probe of the applications' JWKS keys.

func (*Authenticator) IssuerKeyStatuses

func (a *Authenticator) IssuerKeyStatuses() []verify.IssuerKeyStatus

IssuerKeyStatuses reports the applications' JWKS key state and age.

func (*Authenticator) Verify

func (a *Authenticator) Verify(ctx context.Context, token string) (verify.Claims, error)

Verify is VerifyRequest for a token detached from any request, so a sender-bound delegated token fails with verify.ErrSenderProofRequired.

func (*Authenticator) VerifyRequest

func (a *Authenticator) VerifyRequest(r *http.Request) (verify.Claims, error)

VerifyRequest authenticates r: an API key is resolved and never tried as a JWT; a JWT is this deployment's or a stored application's.

func (*Authenticator) VerifyServiceJWT

func (a *Authenticator) VerifyServiceJWT(ctx context.Context, token string, opts ...verify.ServiceJWTVerifyOption) (iam.ServiceJWTClaims, error)

VerifyServiceJWT verifies a service JWT (verify.Verifier.VerifyServiceJWT) of this deployment or of a stored application.

type Engine

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

Engine owns local business logic and resources behind Client.

func New

func New(ctx context.Context, cfg config.Config, deps config.Deps) (_ *Engine, err error)

New builds the engine: it normalizes cfg once (config.Normalize), resolves keys, then builds the store, River, the permission groups and the request authenticator. ctx bounds the boot-time database work.

func (*Engine) AddMFAEnrollmentExemptRoutes

func (s *Engine) AddMFAEnrollmentExemptRoutes(paths []string)

AddMFAEnrollmentExemptRoutes registers the anchored paths (mount prefix and route path) of the 2FA enrollment routes, matched exactly: the only paths a 2FA-enrollment-only token, or a user a Required policy has yet to enroll, may reach. A host route replacing one (HTTPConfig.Exclude) keeps the exemption; one that merely ends in the same path does not (ak#324).

func (*Engine) ApplyBootstrapManifest

func (s *Engine) ApplyBootstrapManifest(ctx context.Context, manifest iam.BootstrapManifest, opts iam.BootstrapOptions, options ...ops.Option) (iam.BootstrapResult, error)

ApplyBootstrapManifest applies seed data and its StartupOnly receipt in one authority transaction, as a host operation. It never adopts an account through a username, an alias or an unverified contact, and never changes an existing account's identity or marks its contacts verified (see iam.BootstrapManifestUser). Role changes run the credential sweep.

func (*Engine) Ban

func (s *Engine) Ban(ctx context.Context, a iam.Actor, userID string, b iam.Ban, opts ...ops.Option) error

Ban bans an account under ACCT(root:users:ban) and revokes its sessions, device keys and every credential it issued, in one transaction. Nobody bans themselves, and the last usable owner of a group cannot be banned.

func (*Engine) BeginDeviceKeyEnrollment

func (s *Engine) BeginDeviceKeyEnrollment(ctx context.Context, email, publicKey, label string) (authflow.DeviceKeyChallenge, error)

BeginDeviceKeyEnrollment sends an email proof and records the proposed key.

func (*Engine) BeginDeviceKeyLogin

func (s *Engine) BeginDeviceKeyLogin(ctx context.Context, deviceKeyID string) (authflow.DeviceKeyChallenge, error)

BeginDeviceKeyLogin returns an indistinguishable challenge for active, revoked, and unknown ids.

func (*Engine) BeginPasskeyLogin

func (s *Engine) BeginPasskeyLogin(ctx context.Context) (*protocol.CredentialAssertion, error)

BeginPasskeyLogin always issues a discoverable assertion with an empty allowCredentials list (AK2-PK-002): scoping it to a known identifier would leak account existence and credential ids to an unauthenticated caller. The asserted credential's user handle resolves the user at finish.

func (*Engine) BeginPasskeyRegistration

func (s *Engine) BeginPasskeyRegistration(ctx context.Context, userID string) (*protocol.CredentialCreation, error)

BeginPasskeyRegistration starts adding a passkey to an already identified user. The same ceremony finishes as either FinishPasskeyRegistration (add) or FinishPasskeyReplacement (replace all).

func (*Engine) BeginTwoFactorEnrollment

func (s *Engine) BeginTwoFactorEnrollment(ctx context.Context, userID string, enrollmentToken bool, sessionID string) (authflow.TwoFactorEnrollmentScope, error)

BeginTwoFactorEnrollment decides the enrollment scope for a caller. An enrollment-only token (issued at login when a factor is mandatory) may fill the FIRST factor only, and only while no session or factor exists — ErrTwoFAFactorExists otherwise. A full session may add further factors.

func (*Engine) Can

func (s *Engine) Can(ctx context.Context, a iam.Actor, ref iam.GroupRef, perm iam.Perm) (bool, error)

Can reports whether a covers perm in the group ref addresses, live: a dead actor, an unknown group or an actor bound to another group is false, and an actor whose bound session was revoked is ErrSessionRevoked. The system is always true. An unregistered perm is ErrUnknownPermission.

func (*Engine) ChangePassword

func (s *Engine) ChangePassword(ctx context.Context, userID, current, new string, keepSessionID *string) error

ChangePassword verifies the current password, replaces it, invalidates recovery grants and revokes other sessions atomically. keepSessionID may preserve one.

func (*Engine) CheckIssuerKeys

func (s *Engine) CheckIssuerKeys(ctx context.Context) error

CheckIssuerKeys is the no-I/O health probe of the remote applications' JWKS keys (verify.Verifier.CheckIssuerKeys).

func (*Engine) CheckPendingRegistrationConflict

func (s *Engine) 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 (*Engine) CheckPhoneRegistrationConflict

func (s *Engine) 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 (*Engine) CheckRecentSignIn

func (s *Engine) CheckRecentSignIn(ctx context.Context, cl verify.Claims) error

CheckRecentSignIn is the sensitive-action gate, for AuthKit's own credential routes and verify.Sensitive alike: CheckSession, then a sign-in of the user's own token within authflow.SensitiveActionFreshAuthWindow, with a second factor when the account has one (checked live, so a token minted before enrollment cannot hide it). A stale sign-in is StepUpRequired; a delegated token, which carries no sign-in of its own, is forbidden.

func (*Engine) CheckSession

func (s *Engine) CheckSession(ctx context.Context, cl verify.Claims) error

CheckSession is the session check (#412) for verified claims: the refresh session or device key the token was minted from is still active and its account usable. A user's token names one, and so does a delegated token this deployment minted from a sign-in (#412 binds it to its minting session). A token that names none, such as one the host minted, is refused too, since nothing proves it still stands. Every refusal is ErrSessionRevoked; any other credential (an API key, an application's, a 2FA-enrollment token) is forbidden. Permission checks run the same query through the actor's session binding.

func (*Engine) CheckUserPassword

func (s *Engine) CheckUserPassword(ctx context.Context, userID, pass string) error

CheckUserPassword is the error-returning form of VerifyUserPassword: nil on success, ErrPasswordResetRequired when the stored hash is flagged iam.HashLegacyResetRequired (no plaintext can verify; the user must reset), and a generic unauthorized error otherwise. Callers that need to route reset-required users (step-up, change-password) should use this form.

func (*Engine) CheckUsername

func (s *Engine) CheckUsername(ctx context.Context, name string) error

CheckUsername reports whether a new account could take name: the username policy, then any claim on it (a canonical name, a live alias, a purged account's reservation, a pending registration), then NameAdmission. A claim answers ErrUsernameInUse and nothing about its owner.

func (*Engine) ClaimDPoPProof

func (s *Engine) ClaimDPoPProof(ctx context.Context, key string, ttl time.Duration) (bool, error)

ClaimDPoPProof implements dpop.ReplayGuard using the configured shared ephemeral store. Replay keys have a fixed length and expire within 121s.

func (*Engine) Close

func (s *Engine) Close()

Close releases AuthKit-owned resources, including its schema-bound pool. Injected dependencies, including the host pool, stores and keys, stay host-owned.

func (*Engine) CompleteExternalLogin

func (s *Engine) CompleteExternalLogin(ctx context.Context, in authflow.ExternalLoginInput) (authflow.LoginOutcome, error)

CompleteExternalLogin resolves the identity to a user and signs it in. Resolution errors: ErrProviderAlreadyLinked, ErrProviderChangeRequiresUnlink, ErrAccountExistsLinkRequired, ErrRegistrationDisabled, ErrProviderLinkFailed, ErrUserCreationFailed. Session and MFA errors come from the shared login workflow.

func (*Engine) CompleteLoginChallenge

func (s *Engine) CompleteLoginChallenge(ctx context.Context, in authflow.LoginChallengeInput) (authflow.LoginOutcome, error)

CompleteLoginChallenge gives one current first-factor grant one successful second-factor completion and commits its session while holding the account lock.

func (*Engine) Config

func (s *Engine) Config() config.Config

Config is the normalized configuration the engine runs with.

func (*Engine) ConfirmAccountRecovery

func (s *Engine) ConfirmAccountRecovery(ctx context.Context, token string) error

func (*Engine) ConfirmPasswordReset

func (s *Engine) ConfirmPasswordReset(ctx context.Context, token, newPassword string) (string, error)

ConfirmPasswordReset verifies token and sets a new password.

func (*Engine) ConfirmVerification

func (s *Engine) ConfirmVerification(ctx context.Context, in authflow.VerificationInput) (authflow.LoginOutcome, error)

ConfirmVerification is the shared registration/contact-verification workflow. Verification that authenticates a user returns the same MFA/session outcome as password and provider login; a contact mutation returns contact_changed.

func (*Engine) ConsumeOIDCResult added in v0.149.0

func (s *Engine) ConsumeOIDCResult(ctx context.Context, code string) (json.RawMessage, bool, error)

ConsumeOIDCResult trades a one-time code for its result, once.

func (*Engine) ConsumeOIDCState

func (s *Engine) ConsumeOIDCState(ctx context.Context, state string) (oidcstate.StateData, bool, error)

ConsumeOIDCState claims a pending browser login once; concurrent callbacks cannot both win it.

func (*Engine) ContinueRefreshMFA

func (s *Engine) ContinueRefreshMFA(ctx context.Context, userID, sessionID string) (authflow.LoginOutcome, error)

ContinueRefreshMFA is called only after validating the refresh credential. An old session must repeat a first factor before sensitive factor enrollment.

func (*Engine) CreateAPIKey

func (s *Engine) CreateAPIKey(ctx context.Context, a iam.Actor, ref iam.GroupRef, k iam.NewAPIKey, opts ...ops.Option) (iam.APIKeyCreated, error)

CreateAPIKey issues a key holding role in ref: CAP(<p>:credentials:manage) plus COVER(role). Only a user or the system issues credentials. The token is returned once.

func (*Engine) CreateGroup

func (s *Engine) CreateGroup(ctx context.Context, ng iam.NewGroup, opts ...ops.Option) (iam.Group, error)

CreateGroup creates a group of a declared persona. ng.Owner, when set, must be a live account; it is seeded with the owner role. With ng.ID, creating an existing live group of the same persona returns it unchanged; a deleted group or another persona under that id is iam.ErrGroupConflict.

func (*Engine) CreateInvitation

func (s *Engine) CreateInvitation(ctx context.Context, a iam.Actor, ref iam.GroupRef, n iam.NewInvitation, opts ...ops.Option) (iam.InvitationCreated, error)

CreateInvitation creates an invite link (n.Email empty), or emails an invitation to n.Email. A link, and an email invitation carrying a role, need CAP(<p>:members:manage) plus COVER(role) in ref; a plain email invitation (no role) is issued in the root group and needs CAP(root:users:invite). Only a user or the system issues credentials. The code is returned once. ops.InTx applies to links only: an email is sent at once.

func (*Engine) CreateUser

func (s *Engine) CreateUser(ctx context.Context, n iam.NewUser, opts ...ops.Option) (iam.User, error)

CreateUser creates a native account: a host operation.

func (*Engine) DelegationAuthorizer

func (s *Engine) DelegationAuthorizer() iam.DelegationAuthorizer

DelegationAuthorizer returns the host-injected delegated-token authorizer (#277), nil when none was wired.

func (*Engine) DeleteGroup

func (s *Engine) DeleteGroup(ctx context.Context, ref iam.GroupRef, opts ...ops.Option) error

DeleteGroup soft-deletes a group: it stops resolving and granting, while its rows stay until PurgeGroup. Deleting a deleted group is a no-op; the root group cannot be deleted.

func (*Engine) DeletePasskey

func (s *Engine) DeletePasskey(ctx context.Context, userID, id string) error

DeletePasskey deletes the account's passkey id; a deleted one stays deleted, and ErrPasskeyNotFound when the account never held it.

func (*Engine) DeletePendingPhoneRegistrationByPhone

func (s *Engine) DeletePendingPhoneRegistrationByPhone(ctx context.Context, phone string) error

DeletePendingPhoneRegistrationByPhone removes a pending phone registration for the given phone, if one exists. No-op when none exists.

func (*Engine) DeletePendingRegistrationByEmail

func (s *Engine) DeletePendingRegistrationByEmail(ctx context.Context, email string) error

DeletePendingRegistrationByEmail removes a pending email registration for the given email, if one exists. No-op when none exists.

func (*Engine) DeleteRemoteApplication

func (s *Engine) DeleteRemoteApplication(ctx context.Context, actor iam.Actor, ref iam.GroupRef, id string, opts ...ops.Option) error

DeleteRemoteApplication deletes the application id that group ref controls; an id unknown in the group is iam.ErrRemoteApplicationNotFound. Any actor but the system needs the same authority as re-keying it, and never deletes a system-registered application.

func (*Engine) DeleteUsers

func (s *Engine) DeleteUsers(ctx context.Context, a iam.Actor, ids []string, opts ...ops.Option) ([]iam.OpResult, error)

DeleteUsers soft-deletes accounts under ACCT(root:users:delete), starting the fixed recovery window; an account may delete itself, and only then can signing in undo it. Sessions, device keys and every credential the account issued are revoked. A repeat call keeps the original window. Per-item results; the error is a whole-call failure.

func (*Engine) DeviceKeys

func (s *Engine) DeviceKeys(ctx context.Context, userID string) ([]iam.DeviceKey, error)

DeviceKeys returns the account's device keys in enrollment order, revoked ones included. ErrDeviceKeysDisabled without Config.DeviceKeys.Enabled.

func (*Engine) Disable2FA added in v0.149.0

func (s *Engine) Disable2FA(ctx context.Context, userID string) error

Disable2FA removes every second factor of the account, and the roles that require MFA it held.

func (*Engine) Disable2FAFactor added in v0.149.0

func (s *Engine) Disable2FAFactor(ctx context.Context, userID, factorID string) error

Disable2FAFactor removes one second factor; the last one disables MFA as Disable2FA does, and a removed default passes to another factor. A factor the account does not hold is not_found.

func (*Engine) EffectivePermissions

func (s *Engine) EffectivePermissions(ctx context.Context, a iam.Actor, refs []iam.GroupRef) (map[string][]iam.Perm, error)

EffectivePermissions returns a's effective grant patterns per group id, for clients that gate UI on permission strings (glob-matching with iam.Perm.Matches). Globs are returned verbatim; a ceiling narrows them. Unknown and deleted groups and groups granting nothing are absent; a dead actor has none, and one whose bound session was revoked is ErrSessionRevoked. The system gets each persona's owner grant. A user's grants on many groups are read in one query.

func (*Engine) EmailAvailable added in v0.149.0

func (s *Engine) EmailAvailable() bool

EmailAvailable reports whether email flows are offered: Deps.Email is set and its latest health check, if any, passed.

func (*Engine) EmailHealth added in v0.149.0

func (s *Engine) EmailHealth() (time.Time, error)

EmailHealth is the latest Deps.Email health verdict and when that check started; a zero time means no check has run.

func (*Engine) EnrollTwoFactor

EnrollTwoFactor runs the enrollment decision tree. Input problems: ErrInvalidTwoFAMethod, ErrPhoneNumberRequired, ErrPhoneNumberMustBeE164, ErrInvalidCode, ErrCodeExpired, ErrTwoFAFactorExists; engine failures carry a stage prefix wrapping ErrSMSUnavailable / ErrTwoFASetupCodeSendFailed (with the delivery sentinel) / ErrTwoFAEnableFailed.

func (*Engine) EnsureUserRole

func (s *Engine) EnsureUserRole(ctx context.Context, ref iam.GroupRef, u iam.UserRef, role iam.Role, opts ...ops.Option) (iam.User, error)

EnsureUserRole makes the account u names hold role in ref, under the system, and is idempotent on every boot. ops.InTx runs it in the host's transaction.

u is an id, an email or a phone; a username proves nothing and is refused. With no account for the contact, one is created without credentials and with the contact unverified: only a proof of that contact can ever sign in, and that proof verifies it. An existing account is used when u is its id or the contact is verified on it; one that already holds role, the group's owner role, or a role covering role is left as it is (a re-run, including on the unverified account an earlier call created). Any other account is refused with ErrContactNotVerified: a pre-registered account is never adopted, and nothing here marks a contact verified.

func (*Engine) ExchangeRefreshToken

func (s *Engine) ExchangeRefreshToken(ctx context.Context, refreshToken string, ua string, ip net.IP) (userID string, session authflow.IssuedSession, err error)

ExchangeRefreshToken rotates a refresh token: the session's user, and its new access and refresh tokens.

func (*Engine) FinishDeviceKeyEnrollment

func (s *Engine) FinishDeviceKeyEnrollment(ctx context.Context, enrollmentID, code, signature, secondFactor string) (authflow.DeviceKeyAuthResult, error)

FinishDeviceKeyEnrollment consumes both proofs, enrolls the key, and mints no refresh session. An existing account with a usable second factor must also present one independent of the emailed code (secondFactor: a TOTP or SMS code, or a backup code) — email possession alone never enrolls a standing credential on an MFA-protected account (#293, P1). A revoked key, or one bound to another account, is refused before any second factor is asked for, and a backup code is spent only by the enrollment that commits (R4).

func (*Engine) FinishDeviceKeyLogin

func (s *Engine) FinishDeviceKeyLogin(ctx context.Context, challengeID, signature string) (authflow.DeviceKeyAuthResult, error)

FinishDeviceKeyLogin atomically consumes a challenge and issues only a short access token.

func (*Engine) FinishPasskeyLogin

func (s *Engine) FinishPasskeyLogin(ctx context.Context, response []byte, userAgent string, ip net.IP) (authflow.LoginOutcome, error)

FinishPasskeyLogin composes the verification primitive with the browser session issuance; it is the only passkey path that mints a session.

func (*Engine) FinishPasskeyRegistration

func (s *Engine) FinishPasskeyRegistration(ctx context.Context, userID string, response []byte) (iam.Passkey, error)

func (*Engine) GenerateSIWSChallenge

func (s *Engine) GenerateSIWSChallenge(ctx context.Context, domain, address, username string) (siws.SignInInput, error)

GenerateSIWSChallenge creates a new SIWS challenge for the given address. The challenge must be verified within 15 minutes.

func (*Engine) Get2FASettings

func (s *Engine) Get2FASettings(ctx context.Context, userID string) (*authflow.TwoFactorSettings, error)

Get2FASettings retrieves a user's 2FA settings

func (*Engine) GetPendingPhoneRegistrationByPhone

func (s *Engine) GetPendingPhoneRegistrationByPhone(ctx context.Context, phone string) (*authflow.PendingRegistration, error)

GetPendingPhoneRegistrationByPhone looks up a pending phone registration by phone number. (PendingRegistration.Email carries the phone for phone registrations, preserving prior behavior.)

func (*Engine) GetPendingRegistrationByEmail

func (s *Engine) GetPendingRegistrationByEmail(ctx context.Context, email string) (*authflow.PendingRegistration, error)

GetPendingRegistrationByEmail looks up a pending registration by email.

func (*Engine) GetProviderLinkByIssuer

func (s *Engine) GetProviderLinkByIssuer(ctx context.Context, issuer, subject string) (string, *string, error)

Issuer-based provider link helpers (preferred)

func (*Engine) GetRemoteApplication

func (s *Engine) GetRemoteApplication(ctx context.Context, issuer string) (*iam.RemoteApplication, error)

GetRemoteApplication returns a remote_application by OIDC issuer URL.

func (*Engine) Group

func (s *Engine) Group(ctx context.Context, ref iam.GroupRef) (iam.Group, error)

Group reads one group, a soft-deleted one included, with DeletedAt set. Absence is ErrGroupNotFound.

func (*Engine) GroupRoles

func (s *Engine) GroupRoles(ctx context.Context, ref iam.GroupRef, subjects []iam.Subject) (map[iam.Subject]iam.Role, error)

GroupRoles returns the direct role of each subject that holds one in the group, for at most iam.MaxBatch subjects. Roles no longer defined (catalog or custom) confer nothing and are omitted.

func (*Engine) Groups

func (s *Engine) Groups(ctx context.Context, ids []string) (map[string]iam.Group, error)

Groups reads many groups by id in one query, soft-deleted ones included. Unknown ids are absent. At most iam.MaxBatch distinct ids.

func (*Engine) HasPassword

func (s *Engine) HasPassword(ctx context.Context, userID string) (bool, error)

HasPassword reports whether the user has a local password set.

func (s *Engine) HasProviderLink(ctx context.Context, userID, issuer, providerSlug string) (bool, error)

HasProviderLink reports whether userID holds a link to subject-issuer under providerSlug — the step-up gate's "is this the user's own provider" check.

func (*Engine) HasUsableMFA

func (s *Engine) HasUsableMFA(ctx context.Context, userID string) (bool, error)

HasUsableMFA reports whether the account has 2FA enabled with a factor.

func (s *Engine) ImportSolanaLinks(ctx context.Context, rows []iam.ImportSolanaLink, opts ...ops.Option) (iam.ImportSolanaLinksResult, error)

ImportSolanaLinks imports legacy wallet claims as a host operation, one outcome per row. It never verifies a wallet: only a successful SIWS proof promotes an imported claim.

func (*Engine) ImportUsers

func (s *Engine) ImportUsers(ctx context.Context, rows []iam.ImportUser, opts iam.ImportOptions, options ...ops.Option) (iam.ImportResult, error)

ImportUsers bulk-imports accounts (target: 500k+ rows) as a host operation. Rows are validated in Go, then each chunk runs in one transaction: find the accounts its rows name, insert the rest with one multi-row INSERT, store their password hashes, and merge where asked. A row sharing an identifier with an earlier row of the batch is that row's account. A row whose identifiers name two accounts is rejected. Matching is never proof: only an id, or a contact verified on the account, binds a row for a merge.

func (*Engine) IssuerKeyStatuses

func (s *Engine) IssuerKeyStatuses() []verify.IssuerKeyStatus

IssuerKeyStatuses reports the remote applications' JWKS key state.

func (*Engine) JWKS

func (s *Engine) JWKS() keys.JWKS

JWKS publishes the CURRENT public keys, read from the KeySource on every call, so a rotation shows on the very next request (#238).

func (*Engine) KnownPermission

func (s *Engine) KnownPermission(perm iam.Perm) bool

KnownPermission reports whether perm is registered in a persona catalog.

func (*Engine) LinkProvider

func (s *Engine) LinkProvider(ctx context.Context, userID string, l iam.ProviderLink, opts ...ops.Option) error

LinkProvider links an external identity to a live account as a login method, as a host operation. Browser flows use ExternalLoginInput.Link, whose initiating session is checked at commit.

func (*Engine) LinkSolanaWallet

func (s *Engine) LinkSolanaWallet(ctx context.Context, userID string, output siws.SignInOutput) (authflow.SolanaLinkedAccount, error)

LinkSolanaWallet links the Solana wallet a SIWS output proves to an existing account and returns the account's linked wallet.

func (*Engine) ListAPIKeys

func (s *Engine) ListAPIKeys(ctx context.Context, ref iam.GroupRef, p iam.PageRequest) (iam.ListPage[iam.APIKey], error)

ListAPIKeys lists the group's keys, newest first, including revoked and expired ones (terminal keys are purged after 90 days). Never the secret.

func (*Engine) ListEnabledRemoteApplications

func (s *Engine) ListEnabledRemoteApplications(ctx context.Context) ([]iam.RemoteApplication, error)

ListEnabledRemoteApplications returns only the enabled remote_applications: the verification-facing snapshot a Verifier trusts issuers from.

func (*Engine) ListGroupMembers

func (s *Engine) ListGroupMembers(ctx context.Context, ref iam.GroupRef, q iam.MemberQuery) (iam.ListPage[iam.GroupMember], error)

ListGroupMembers lists the subjects holding a role in a live group, ordered by subject kind, then id.

func (*Engine) ListGroups

func (s *Engine) ListGroups(ctx context.Context, q iam.GroupQuery) (iam.ListPage[iam.Group], error)

ListGroups lists groups oldest first. The root group is never listed. q.Ownerless keeps live groups with no owner that counts toward the last-owner rule (requireRemainingOwner).

func (*Engine) ListInvitations

func (s *Engine) ListInvitations(ctx context.Context, ref iam.GroupRef, p iam.PageRequest) (iam.ListPage[iam.Invitation], error)

ListInvitations lists the group's invitations, links and email invitations, newest first, active or not; never a code. Root's include the plain email invitations.

func (*Engine) ListMemberships

func (s *Engine) ListMemberships(ctx context.Context, subject iam.Subject, p iam.PageRequest) (iam.ListPage[iam.Membership], error)

ListMemberships lists the live groups a subject holds a role in, ordered by persona, then id.

func (*Engine) ListPasskeys

func (s *Engine) ListPasskeys(ctx context.Context, userID string) ([]iam.Passkey, error)

func (*Engine) ListRemoteApplications

func (s *Engine) ListRemoteApplications(ctx context.Context, ref iam.GroupRef, page iam.PageRequest) (iam.ListPage[iam.RemoteApplication], error)

ListRemoteApplications lists the applications group ref controls, newest first, with their roles.

func (*Engine) ListSessionEvents

func (s *Engine) ListSessionEvents(ctx context.Context, userID string, q iam.SessionEventQuery) (iam.ListPage[iam.SessionEvent], error)

SessionEvents pages an account's session history, newest first.

func (*Engine) ListUsers

func (s *Engine) ListUsers(ctx context.Context, q iam.UserQuery) (iam.ListPage[iam.UserEntry], error)

ListUsers is the user directory: search, status, root-role and entitlement filters, keyset-paged. NULL sort values come last in either direction. Each entry carries its root role and, with q.WithEntitlements, its entitlements; q.Total counts every match.

func (*Engine) LogSessionFailed

func (s *Engine) LogSessionFailed(ctx context.Context, userID string, sessionID string, reason *string, ip *string, ua *string)

LogSessionFailed records a failed session event for a user (best-effort).

func (*Engine) MarkSessionAuthenticated

func (s *Engine) MarkSessionAuthenticated(ctx context.Context, userID, sessionID string) error

func (*Engine) MarkSessionAuthenticatedWithMethods

func (s *Engine) MarkSessionAuthenticatedWithMethods(ctx context.Context, userID, sessionID string, authMethods []string) error

MarkSessionAuthenticatedWithMethods refreshes the session's sensitive-action auth window and records how the user re-proved identity.

func (*Engine) MintAccessToken

func (s *Engine) MintAccessToken(ctx context.Context, userID string, o iam.AccessTokenOptions, opts ...ops.Option) (iam.Token, error)

MintAccessToken mints an access token for a live account outside any login flow; a host operation. Reserved claims in o.Claims are dropped; o.SessionID becomes sid.

func (*Engine) MintDelegatedAccessToken

func (s *Engine) MintDelegatedAccessToken(ctx context.Context, actor iam.Actor, d iam.DelegatedAccess, opts ...ops.Option) (iam.Token, error)

MintDelegatedAccessToken signs a delegated access token as this deployment. A user actor mints for itself only, and every AuthKit-namespace permission in the grant must be held live on the root group (checkDelegatedGrant); the system may mint for any subject; machine actors may not mint. A user actor bound to a session (verify.ActorFromClaims) mints only while that session stands, and the token carries it (sid or device_key_id), so revoking the session cuts the delegated token off at every AuthKit permission check.

func (*Engine) MintServiceJWT

func (s *Engine) MintServiceJWT(ctx context.Context, opts iam.ServiceJWT, options ...ops.Option) (iam.Token, iam.ServiceJWTClaims, error)

MintServiceJWT signs a short-lived service JWT with this deployment's key. It stamps token_use=service and grants nothing AuthKit enforces.

func (*Engine) MintSessionAccessToken

func (s *Engine) MintSessionAccessToken(ctx context.Context, userID, sessionID string) (string, time.Time, error)

MintSessionAccessToken re-mints the access token of the caller's own session (step-up and provider-link responses).

func (*Engine) NewAuthenticator

func (s *Engine) NewAuthenticator(audiences []string, opts ...verify.VerifierOption) (*Authenticator, error)

NewAuthenticator builds an authenticator for a host resource server in this process: this deployment's API keys and tokens and its remote applications' tokens, for audiences. DPoP proofs are spent in this deployment's replay store and checked against the issuer's origin unless opts say otherwise (verify.WithPublicURL). It applies no 2FA policy.

func (*Engine) PasskeysEnabled

func (s *Engine) PasskeysEnabled() bool

PasskeysEnabled reports whether passkey (WebAuthn) support is configured. Passkeys require a Relying Party ID (PasskeyConfig.RPID); without it every WebAuthn ceremony fails closed (the origin must match the RPID). The HTTP transport uses this to skip mounting the /passkeys/* routes entirely rather than exposing endpoints that can only error.

func (*Engine) PasswordLogin

PasswordLogin runs the whole password-login decision tree. It returns an error only when the engine itself failed (a send, the challenge store, the session insert — each prefixed with its stage and, for sends, the delivery sentinel); every policy result is a LoginOutcome.

func (*Engine) PasswordlessLogin

func (*Engine) PatchUserMetadata

func (s *Engine) PatchUserMetadata(ctx context.Context, a iam.Actor, userID string, patch map[string]any, opts ...ops.Option) error

PatchUserMetadata applies patch to the account's application-owned metadata as an RFC 7396 JSON Merge Patch under ACCT(root:users:manage): objects merge recursively, a nil value deletes its key, and any other value (arrays included) replaces the one it names. Keys AuthKit owns are refused.

func (*Engine) Permission

func (s *Engine) Permission(text string) (iam.Perm, error)

Permission resolves a registered concrete permission.

func (*Engine) PermissionGroupSchema

func (s *Engine) PermissionGroupSchema() *rbac.Schema

PermissionGroupSchema returns the compiled Config.Roles.

func (*Engine) Persona

func (s *Engine) Persona(name string) (iam.Persona, error)

Persona resolves a persona name declared in Config.Roles (root always is).

func (*Engine) ProviderSlugs

func (s *Engine) ProviderSlugs(ctx context.Context, userID string) ([]string, error)

ProviderSlugs returns the distinct provider slugs linked to userID.

func (*Engine) PublicKeysByKID

func (s *Engine) PublicKeysByKID() map[string]crypto.PublicKey

PublicKeysByKID returns the CURRENT public keys indexed by key ID, read fresh from the KeySource on every call (#238).

func (*Engine) PublicNativeUserRegistrationEnabled

func (s *Engine) PublicNativeUserRegistrationEnabled() bool

PublicNativeUserRegistrationEnabled reports whether public native-user self-registration / auto-registration is allowed.

func (*Engine) PublicUsers

func (s *Engine) PublicUsers(ctx context.Context, ids []string) (map[string]iam.PublicUser, error)

PublicUsers returns what others may see of ids. A deleted account is a tombstone; a banned one is returned normally (a ban is an access decision, not a visibility one); unknown ids are absent.

func (*Engine) PurgeGroup

func (s *Engine) PurgeGroup(ctx context.Context, ref iam.GroupRef, opts ...ops.Option) error

PurgeGroup permanently deletes a group, live or soft-deleted, with every role, key and link in it. Purging an unknown group is a no-op.

func (*Engine) PurgeUsers

func (s *Engine) PurgeUsers(ctx context.Context, ids []string, opts ...ops.Option) ([]iam.OpResult, error)

PurgeUsers closes the recovery window of accounts now, soft-deleting live ones first: a host operation. The account row goes once the host deletion callbacks complete, exactly as at the end of the window.

func (*Engine) PutOIDCResult added in v0.149.0

func (s *Engine) PutOIDCResult(ctx context.Context, code string, result json.RawMessage) error

PutOIDCResult keeps a browser OIDC result for its one-time code; the key is the code's hash, so the store never holds a usable code.

func (*Engine) PutOIDCState

func (s *Engine) PutOIDCState(ctx context.Context, state string, data oidcstate.StateData) error

PutOIDCState records a pending browser login for the provider callback.

func (*Engine) RecordFailedDeviceKeyEnrollment

func (s *Engine) RecordFailedDeviceKeyEnrollment(ctx context.Context, enrollmentID string)

RecordFailedDeviceKeyEnrollment bounds online guessing without consuming a valid ceremony on one typo.

func (*Engine) RedeemInvitation

func (s *Engine) RedeemInvitation(ctx context.Context, a iam.Actor, code string) (authflow.InviteRedemption, error)

RedeemInvitation redeems code for the signed-in user a: a link must be live (not revoked, expired or used) and its issuer live, and the redeemer live. The role is assigned in the same transaction and the link consumed. Idempotent: a redeemer already holding the role succeeds without using it. code may also be a role-carrying account invitation (an add by email): only the account that has verified the invited address accepts it.

func (*Engine) RegenerateBackupCodes

func (s *Engine) RegenerateBackupCodes(ctx context.Context, userID string) ([]string, error)

RegenerateBackupCodes generates new backup codes for a user (invalidating old ones). Returns the plaintext codes (caller must show these to user ONCE).

func (*Engine) Register

Register runs the registration decision tree. Input problems come back as the validation errors (ValidationErrorCode) and the sentinels ErrInvalidIdentifier / ErrEmailInUse / ErrPhoneInUse / ErrUsernameInUse / ErrRegistrationDisabled / ErrEmailUnavailable / ErrSMSUnavailable; engine failures carry a stage prefix and, for sends, the delivery sentinel.

func (*Engine) RegistrationVerificationEnabled

func (s *Engine) RegistrationVerificationEnabled() bool

func (*Engine) RelabelDeviceKey added in v0.149.0

func (s *Engine) RelabelDeviceKey(ctx context.Context, userID, id, label string) (iam.DeviceKey, error)

RelabelDeviceKey sets the label of the account's live key id (empty clears it); not_found when the account holds no such live key.

func (*Engine) RemoteApplication

func (s *Engine) RemoteApplication(ctx context.Context, ref iam.AppRef) (iam.RemoteApplication, error)

RemoteApplication is the management read of an application, by id or by issuer, disabled or in a retired group included, with its role and the permissions it confers now.

func (*Engine) RemoveGroupMember

func (s *Engine) RemoveGroupMember(ctx context.Context, a iam.Actor, ref iam.GroupRef, subject iam.Subject, opts ...ops.Option) error

RemoveGroupMember strips subject's role in ref: CAP by subject kind, COVER of the role it holds (none for a removed role), then the last-owner check. A non-member is a no-op, as is a subject holding another role than ops.IfRole names.

func (*Engine) RemovePhone added in v0.149.0

func (s *Engine) RemovePhone(ctx context.Context, a iam.Actor, userID string) error

RemovePhone clears the account's phone number under ACCT(root:users:manage), the account's own included. It is refused (ErrCannotRemoveLastContact) unless a proven email remains, so the account keeps an address to sign in and recover with, and an MFA holder keeps a proven contact. An account without a phone is unchanged.

func (*Engine) RenamePasskey

func (s *Engine) RenamePasskey(ctx context.Context, userID, id, label string) error

RenamePasskey sets the label of the account's live passkey id (empty clears it); ErrPasskeyNotFound when the account holds no such passkey.

func (*Engine) RequestEmailChange

func (s *Engine) RequestEmailChange(ctx context.Context, userID, newEmail string) error

RequestEmailChange initiates an email change by sending a verification code to the new email. The current email is NOT changed until the user confirms it (ConfirmVerification). The old address is not notified by AuthKit (only a security log line); a host that wants that notification sends it itself.

func (*Engine) RequestEmailVerification

func (s *Engine) RequestEmailVerification(ctx context.Context, email string, ttl time.Duration) error

RequestEmailVerification sends a verification code to an account or pending registration whose address is unproven. An unknown or already verified address gets the same nil, so the answer reveals neither.

func (*Engine) RequestPasswordReset

func (s *Engine) 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 (*Engine) RequestPhoneChange

func (s *Engine) RequestPhoneChange(ctx context.Context, userID, newPhone string) error

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 (*Engine) RequestPhonePasswordReset

func (s *Engine) 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 (*Engine) RequestPhoneVerification

func (s *Engine) RequestPhoneVerification(ctx context.Context, phone string, ttl time.Duration) error

RequestPhoneVerification is RequestEmailVerification for a phone number.

func (*Engine) Require2FAForStepUpMethod

func (s *Engine) Require2FAForStepUpMethod(ctx context.Context, userID, sessionID, method string) (destination, selectedMethod string, factor authflow.TwoFactorFactor, err error)

func (*Engine) RequireProvenContact

func (s *Engine) RequireProvenContact(ctx context.Context, userID string) error

RequireProvenContact is the pre-flight form of the login-method gate.

func (*Engine) ResendLoginChallenge

func (s *Engine) ResendLoginChallenge(ctx context.Context, userID, nonce, factorID string) (*authflow.TwoFactorChallenge, error)

ResendLoginChallenge changes the selected independent factor while retaining the first-factor proof and its original expiry.

func (*Engine) ResetAccountMFA

func (s *Engine) ResetAccountMFA(ctx context.Context, userID string, opts ...ops.Option) error

ResetAccountMFA is the system's recovery for an account that lost its second factors (a lost passkey answers passkey_required): it deletes the account's passkeys, 2FA factors and backup codes, revokes its device keys and its sessions on every account issuer, and tells its address. Roles stay: when one needs MFA, or 2FA is Required, the next sign-in enrolls a factor: a host operation.

func (*Engine) ResolveAPIKey

func (s *Engine) ResolveAPIKey(ctx context.Context, token string) (iam.APIKeyPrincipal, error)

ResolveAPIKey authenticates a presented token: the key must exist with a matching secret, be neither revoked nor expired, belong to a live group, and have a live creator (a banned, deleted or reserved creator's keys are refused even before any sweep revokes them). Permissions are the role's now. It is verify's API-key resolver.

func (*Engine) ResolveUsername

func (s *Engine) ResolveUsername(ctx context.Context, name string) (iam.NameResolution, error)

ResolveUsername resolves a current username or live alias of a live account.

func (*Engine) RestoreUsers

func (s *Engine) RestoreUsers(ctx context.Context, a iam.Actor, ids []string, opts ...ops.Option) ([]iam.OpResult, error)

RestoreUsers restores soft-deleted accounts within their recovery window under ACCT(root:users:delete), re-checked against every group role the account resumes. Old sessions, device keys and credentials stay revoked.

func (*Engine) RevokeAPIKey

func (s *Engine) RevokeAPIKey(ctx context.Context, a iam.Actor, ref iam.GroupRef, id string, opts ...ops.Option) error

RevokeAPIKey revokes the group's key id. It needs the authority to issue the key's role: CAP(<p>:credentials:manage) plus COVER(role). A revoked key is a no-op; an id unknown in the group is iam.ErrAPIKeyNotFound.

func (*Engine) RevokeAccountSessions

func (s *Engine) RevokeAccountSessions(ctx context.Context, a iam.Actor, userID string, opts ...ops.Option) (iam.AccountSessionRevocation, error)

RevokeAccountSessions revokes the account's refresh sessions on every account issuer and all its device keys, under ACCT(root:users:manage); an account may revoke its own. Issued access tokens expire on their TTL.

func (*Engine) RevokeDeviceKey

func (s *Engine) RevokeDeviceKey(ctx context.Context, userID, currentID, targetID string) error

RevokeDeviceKey revokes the account's key targetID; a revoked key stays revoked, and a key the account does not hold is not_found. currentID is the key behind the caller's token ("" for a browser session): it is checked live in the same transaction, so a revoked machine cannot use the rest of its access token to revoke a replacement.

func (*Engine) RevokeInvitation

func (s *Engine) RevokeInvitation(ctx context.Context, a iam.Actor, ref iam.GroupRef, id string, opts ...ops.Option) error

RevokeInvitation revokes the group's invitation id. It needs the authority to issue it: CAP(<p>:members:manage) plus COVER of its role, or CAP(root:users:invite) for a plain email invitation. A revoked or redeemed invitation is a no-op; an id unknown in the group is iam.ErrInvitationNotFound.

func (*Engine) RevokeIssuerSessions

func (s *Engine) RevokeIssuerSessions(ctx context.Context, userID string, keepSessionID *string) error

RevokeIssuerSessions revokes the user's refresh sessions on this issuer only, optionally keeping one: a user's own "sign out my other sessions" here.

func (*Engine) RevokeOtherDeviceKeys

func (s *Engine) RevokeOtherDeviceKeys(ctx context.Context, userID, currentID string) error

RevokeOtherDeviceKeys atomically revokes every key except the live key that minted the caller's email-proven token.

func (*Engine) RevokeSession

func (s *Engine) RevokeSession(ctx context.Context, a iam.Actor, userID, sessionID string, opts ...ops.Option) error

RevokeSession revokes one refresh session of the account on this issuer, under ACCT(root:users:manage); an account may revoke its own. An unknown or already revoked session is a no-op.

func (*Engine) RevokeSessionByIDForUser

func (s *Engine) RevokeSessionByIDForUser(ctx context.Context, userID, sessionID string) error

RevokeSessionByIDForUser revokes a session by id ensuring it belongs to the user; an unknown or revoked session is left as it is.

func (*Engine) RiverJobs

func (s *Engine) RiverJobs() riverhelpers.Contribution

RiverJobs contributes AuthKit maintenance to one host-owned fleet. It does not construct or start a client. Compose once, before serving requests, and close the library if composition fails. The host controls Start and Stop.

func (*Engine) Role

func (s *Engine) Role(text string) (iam.Role, error)

Role resolves role text `<persona>:<name>`: a declared role or a persona's owner role, else iam.ErrRoleNotAssignable (iam.ErrUnknownGroupPersona for an undeclared persona).

func (*Engine) RolePermissions added in v0.148.0

func (s *Engine) RolePermissions(role iam.Role) ([]iam.Perm, error)

RolePermissions returns role's grants in the catalog, includes flattened: permissions and patterns, in declaration order.

func (*Engine) SMSAvailable

func (s *Engine) SMSAvailable() bool

SMSAvailable is EmailAvailable for Deps.SMS and phone flows.

func (*Engine) SMSHealth

func (s *Engine) SMSHealth() (time.Time, error)

SMSHealth is EmailHealth for Deps.SMS.

func (*Engine) SendWelcome

func (s *Engine) SendWelcome(ctx context.Context, userID string)

SendWelcome sends the welcome email when Deps.Email is set.

func (*Engine) SessionFreshness

func (s *Engine) SessionFreshness(ctx context.Context, userID, sessionID string, now time.Time) (authflow.SessionFreshness, error)

func (*Engine) Sessions

func (s *Engine) Sessions(ctx context.Context, userID string) ([]iam.Session, error)

Sessions lists the account's live refresh sessions on this issuer.

func (*Engine) SetDefault2FAFactor added in v0.149.0

func (s *Engine) SetDefault2FAFactor(ctx context.Context, userID, factorID string) (authflow.TwoFactorFactor, error)

SetDefault2FAFactor makes the account's factor factorID its default and returns it; not_found when the account holds no such factor.

func (*Engine) SetGroupRole

func (s *Engine) SetGroupRole(ctx context.Context, a iam.Actor, ref iam.GroupRef, subject iam.Subject, role iam.Role, opts ...ops.Option) (iam.GroupMember, error)

SetGroupRole makes subject hold role in ref, replacing the role it holds: CAP by subject kind, COVER(role), and when replacing, COVER(old) (none for a removed role) and the last-owner check. An application subject must be controlled by the group. Holding role already changes nothing.

func (*Engine) SetPasswordAfterFreshAuth

func (s *Engine) SetPasswordAfterFreshAuth(ctx context.Context, userID, new string, keepSessionID *string) error

SetPasswordAfterFreshAuth performs the same mutation for a host-authorized fresh authentication, without requiring the previous password.

func (*Engine) Start

func (s *Engine) Start(ctx context.Context) error

Start starts AuthKit-owned maintenance after privileged initialization. It performs no migrations. In host mode it checks registration only: the host starts its shared client after composing every library's worker registry. A client without PostgreSQL (for example verify-only tests) has no jobs.

func (*Engine) StepUpRequired

func (s *Engine) StepUpRequired(ctx context.Context, userID string) error

StepUpRequired is the step_up_required error for userID, carrying how the account can step up: its methods, the window, and its second factors (with mfa_required, since a password never clears the gate for such an account).

func (*Engine) TwoFactorEnabled

func (s *Engine) TwoFactorEnabled() bool

TwoFactorEnabled reports whether any 2FA flow is usable (Mode != Disabled).

func (*Engine) TwoFactorMethods added in v0.148.0

func (s *Engine) TwoFactorMethods() []iam.TwoFactorMethod

TwoFactorMethods are the second factors a user can enroll now, in stable order: enabled by TwoFactor.Mode and Methods, with their dependency present (Deps.Email and Deps.SMS while healthy, the TOTP key). Empty when 2FA is disabled.

func (*Engine) Unban

func (s *Engine) Unban(ctx context.Context, a iam.Actor, userID string, opts ...ops.Option) error

Unban lifts a ban under ACCT(root:users:ban). Lifting a ban restores the account's authority, so it needs the same coverage as imposing one; nobody lifts their own ban.

func (*Engine) UnlinkProviderUnlessLast

func (s *Engine) UnlinkProviderUnlessLast(ctx context.Context, userID, provider string) (bool, error)

UnlinkProviderUnlessLast atomically removes the provider link only if the user retains a login method afterward (a password, or another provider). Returns (false, nil) when removal would strip the last login method. The check and the delete run in one transaction, and UserProviderCountForUpdate locks the user's provider rows so two concurrent unlinks of different providers cannot both pass the "not last" check and leave the user with zero login methods.

func (*Engine) UpdateUser

func (s *Engine) UpdateUser(ctx context.Context, a iam.Actor, userID string, u iam.UserUpdate, opts ...ops.Option) (iam.User, error)

UpdateUser changes an account under ACCT(root:users:manage). An account may change its own Username, AvatarURL and PreferredLanguage (the rename policy applies to itself, not to staff renaming it); Password, PasswordHash and the verified flags are system-only (staff send a reset to the proven address instead). Setting a verified flag is the proof transition: on an account with no proven contact it first retires every pre-proof credential. A contact change never leaves an account with a second factor or MFA-required roles without a proven contact, since the next proof would retire its MFA, and never moves its email factor, which stays bound to the address it was proven for. Nothing is sent to the new address.

func (*Engine) UpsertRemoteApplication

func (s *Engine) UpsertRemoteApplication(ctx context.Context, actor iam.Actor, ref iam.GroupRef, in iam.RemoteApplication, opts ...ops.Option) (iam.RemoteApplication, error)

UpsertRemoteApplication registers the application app.Issuer in the group ref, or updates it there. The system may set Mode and TrustRoot (new applications default to manual); a user registers at trust root user. Machine actors cannot register.

func (*Engine) User

func (s *Engine) User(ctx context.Context, ref iam.UserRef, opts ...ops.Option) (iam.User, error)

User returns one account. Soft-deleted accounts are excluded unless opts include ops.IncludeDeleted(); a miss is iam.ErrUserNotFound.

func (*Engine) UserEntry

func (s *Engine) UserEntry(ctx context.Context, userID string) (iam.UserEntry, error)

UserEntry is one account, deleted ones included, as the user directory lists it, entitlements included.

func (*Engine) UserMetadata

func (s *Engine) UserMetadata(ctx context.Context, userID string) (map[string]any, error)

UserMetadata returns the account's application-owned metadata.

func (*Engine) UserNamingState

func (s *Engine) UserNamingState(ctx context.Context, id string) (naming.State, error)

func (*Engine) UserProfile

func (s *Engine) UserProfile(ctx context.Context, in authflow.ProfileInput) (authflow.UserProfile, error)

UserProfile builds the caller's profile. Errors: the user row is missing (stage "load_user"), or a store failure (stage "load_password", "load_providers").

func (*Engine) UserSecurity added in v0.149.0

func (s *Engine) UserSecurity(ctx context.Context, in authflow.ProfileInput) (authflow.UserSecurity, error)

UserSecurity builds the caller's security view: the presented token's freshness, the step-up methods and the MFA state, from one 2FA-settings read.

func (*Engine) Users

func (s *Engine) Users(ctx context.Context, ids []string) (map[string]iam.User, error)

Users returns the accounts among ids, deleted ones included; unknown ids are absent. It is privileged: it carries contact details.

func (*Engine) ValidatePassword

func (s *Engine) ValidatePassword(value string, identifiers ...string) error

ValidatePassword applies the configured password policy. identifiers are the account's username and email address when known. Length failures carry min_length/max_length; requirement failures carry the missing classes.

func (*Engine) ValidateUsername

func (s *Engine) ValidateUsername(username string) error

ValidateUsername applies the configured username rule.

func (*Engine) ValidateUsernameForRegistration

func (s *Engine) ValidateUsernameForRegistration(ctx context.Context, username string) (string, error)

func (*Engine) Verify

func (s *Engine) Verify(ctx context.Context, token string) (verify.Claims, error)

Verify is VerifyRequest for a token detached from any request.

func (*Engine) Verify2FAStepUpMethodCode

func (s *Engine) Verify2FAStepUpMethodCode(ctx context.Context, userID, sessionID, method, code string) (bool, error)

func (*Engine) VerifyBackupCode

func (s *Engine) VerifyBackupCode(ctx context.Context, userID, backupCode string) (bool, error)

VerifyBackupCode verifies a 2FA backup code for account recovery. On success, removes the used backup code from the user's backup codes.

func (*Engine) VerifyPendingPassword

func (s *Engine) VerifyPendingPassword(ctx context.Context, email, pass string) bool

VerifyPendingPassword checks if the provided password matches the pending registration's hash. Returns true if password is correct, false otherwise.

func (*Engine) VerifyPendingPhonePassword

func (s *Engine) VerifyPendingPhonePassword(ctx context.Context, phone, pass string) bool

VerifyPendingPhonePassword checks if the provided password matches the pending phone registration's hash. Returns true if password is correct, false otherwise.

func (*Engine) VerifyRequest

func (s *Engine) VerifyRequest(r *http.Request) (verify.Claims, error)

VerifyRequest authenticates the engine's own requests (verify.Authenticator).

func (*Engine) VerifySIWSAndLogin

func (s *Engine) VerifySIWSAndLogin(ctx context.Context, output siws.SignInOutput, extra map[string]any) (authflow.LoginOutcome, error)

VerifySIWSAndLogin verifies a SIWS signature and logs in or creates a user. It shares the normal MFA/recovery/session tail with other first factors.

func (*Engine) VerifyServiceJWT

func (s *Engine) VerifyServiceJWT(ctx context.Context, token string, opts ...verify.ServiceJWTVerifyOption) (iam.ServiceJWTClaims, error)

VerifyServiceJWT verifies a service JWT this deployment or one of its remote applications issued.

type SolanaSNSResolver

type SolanaSNSResolver interface {
	ResolvePrimaryName(ctx context.Context, address string) (string, error)
}

SolanaSNSResolver mirrors authkit.SolanaSNSResolver.

Source Files

Jump to

Keyboard shortcuts

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