Documentation
¶
Overview ¶
Package domain holds the IAM domain model: aggregate roots and the command value-objects services pass to the aggregate ports.
Architecture (decided 2026-06-05):
- An aggregate root is the transactional consistency boundary. Each port method is ONE atomic business operation; the persistence adapter opens the transaction INSIDE the method — services never touch pgtx.
- API services (pkg/api) are pure orchestration: map oas -> domain, call one or more aggregate-port methods, map domain -> oas. They hold only interfaces (consumer-defined, next to each service).
- Cross-aggregate consistency is out of scope here (events/outbox come later); a single call mutates a single aggregate.
Fields are representative; they grow as operations are implemented.
Index ¶
- Constants
- Variables
- func FirstNonEmptyLocale(candidates ...string) string
- func MFAPolicyFactorName(dbFactorType string) string
- func NormalizeOrigin(raw string) string
- func NormalizeOrigins(in []string) []string
- func ValidateEmail(email string) error
- func ValidatePhone(phone string) error
- func WithRequestMeta(ctx context.Context, m RequestMeta) context.Context
- type APIKey
- type APIKeyCmd
- type Account
- type AccountAcceptConsentsCmd
- type AccountActivityCmd
- type AccountActivityEvent
- type AccountActivityPage
- type AccountConsent
- type AccountConsentAcceptance
- type AccountExportJob
- type AccountMergeConfirmCmd
- type AccountMergeStartCmd
- type AccountRenameSessionCmd
- type AccountRevokeSessionsCmd
- type AccountTrustSessionCmd
- type AdminAPIKeyCmd
- type AdminAPIKeySecret
- type AdminAPIKeyUpdateCmd
- type AdminAccessRequestDecisionCmd
- type AdminAccessRequestListCmd
- type AdminAccessRequestPage
- type AdminConfigDoc
- type AdminConfigGetCmd
- type AdminConfigUpdateCmd
- type AdminConnectionCmd
- type AdminDomainCmd
- type AdminDomainRegistration
- type AdminFeaturesUpdateCmd
- type AdminI18nUpdateCmd
- type AdminImpersonation
- type AdminJWKSRotateCmd
- type AdminProvider
- type AdminProviderCmd
- type AdminProviderDeleteCmd
- type AdminSecret
- type AdminServiceAccountSecretCmd
- type AdminServiceAccountUpdateCmd
- type AdminSigningKey
- type AdminTemplatePreview
- type AdminTemplatePreviewCmd
- type AdminTemplateSendTestCmd
- type AdminTemplateUpdateCmd
- type AdminTokenProfile
- type AdminTokenProfileCmd
- type AdminTokenProfilePreviewCmd
- type AdminUserAnonymizeCmd
- type AdminUserBanCmd
- type AdminUserImpersonateCmd
- type AdminUserPasswordCmd
- type AdminUserSessionsRevokeCmd
- type AdminUserUpdateCmd
- type AppClient
- type AppClientCmd
- type AuthConfigSpec
- type AuthRegistrationConfig
- type BuiltinEmailCopy
- type BuiltinEmailTemplate
- type Challenge
- type Connection
- type ConnectionCmd
- type ConsentConfigSpec
- type ConsentDocument
- type ConsentDocumentSpec
- type CoreAuthAccessRequest
- type CoreAuthAccessRequestCmd
- type CoreAuthCaptchaVerifyResult
- type CoreAuthEmailVerificationCallbackCmd
- type CoreAuthEmailVerificationCallbackResult
- type CoreAuthPasswordChangeCmd
- type CoreAuthPasswordCheckResult
- type CoreAuthPasswordForgotCmd
- type CoreAuthPasswordResetCmd
- type CoreAuthPasswordResult
- type CoreAuthPasswordVerifyResult
- type CoreAuthRevokeCmd
- type CoreAuthStepUpCmd
- type CoreAuthStepUpResult
- type CoreAuthTokenIntrospection
- type CoreAuthTokenVerification
- type CoreAuthVerifyConsumeCmd
- type CoreAuthVerifyStartCmd
- type Domain
- type Environment
- type EnvironmentCmd
- type Error
- type Event
- type Factor
- type FeaturesSpec
- type FederationConnectionConfig
- type FederationConnectionUpdateCmd
- type FederationOidcConfig
- type FederationSamlAcsCmd
- type FederationSamlConfig
- type FederationScimListQuery
- type FederationScimPatchCmd
- type FederationScimResource
- type FederationScimTokenCmd
- type FederationScimWriteCmd
- type FederationSsoCallbackCmd
- type FederationSsoRedirect
- type FederationSsoStartCmd
- type Flow
- type FlowAbandonCmd
- type FlowActiveChallenge
- type FlowCollected
- type FlowConsentRef
- type FlowContact
- type FlowCreateCmd
- type FlowError
- type FlowGetCmd
- type FlowKind
- type FlowResendCmd
- type FlowState
- type FlowStatus
- type FlowStep
- type FlowSubmitCmd
- type Grant
- type Identity
- type Interaction
- type Invite
- type InviteCreateCmd
- type InviteCreated
- type InviteListCmd
- type InviteRevokeCmd
- type MFAEmailEnrollCmd
- type MFAPolicySpec
- type MFARecoveryVerifyCmd
- type MFASmsEnrollCmd
- type MFATotpVerifyCmd
- type MFAWebAuthnEnrollOptionsCmd
- type MFAWebAuthnEnrollVerifyCmd
- type MachineIDAPIKeyPatchCmd
- type MachineIDSecret
- type MachineIDSecretCmd
- type MachineIDServiceAccountListCmd
- type MachineIDServiceAccountPage
- type MachineIDServiceAccountPatchCmd
- type OAuthProvider
- type OAuthSocialCallbackCmd
- type OAuthSocialCallbackResult
- type OAuthSocialExchangeCmd
- type OAuthSocialLinkCallbackCmd
- type OAuthSocialLinkStartCmd
- type OAuthSocialStartCmd
- type OIDCAuthorizeCmd
- type OIDCBackchannelLogoutCmd
- type OIDCConsentCmd
- type OIDCDeviceAuthorization
- type OIDCDeviceAuthorizationCmd
- type OIDCDeviceDecisionCmd
- type OIDCDevicePending
- type OIDCDeviceUserCode
- type OIDCIntrospectCmd
- type OIDCLogoutCmd
- type OIDCParCmd
- type OIDCParResult
- type OIDCRejectCmd
- type OIDCRevokeCmd
- type OIDCTokenCmd
- type OperatorAdminToken
- type OperatorAdminTokenCmd
- type OperatorConfigCmd
- type OperatorFeaturesCmd
- type OperatorProjectPatchCmd
- type PasswordPolicySpec
- type PlatformCsrfToken
- type Principal
- type PrincipalKind
- type ProfileUpdateCmd
- type Project
- type ProjectCmd
- type ProviderConfigSpec
- type PublicConfig
- type PublicEvent
- type RateLimitRuleSpec
- type RateLimitsSpec
- type RegisterCmd
- type RegistrationInfo
- type RequestMeta
- type ScimToken
- type ServiceAccount
- type ServiceAccountCmd
- type Session
- type SessionPolicySpec
- type SessionRevokedPayload
- type WebAuthnCeremonyData
- type WebAuthnCredential
- type WebAuthnRenameCredentialCmd
- type WebAuthnStoredCredential
- type Webhook
- type WebhookCreateCmd
- type WebhookDelivery
- type WebhookDeliveryListCmd
- type WebhookEventListCmd
- type WebhookEventPage
- type WebhookListCmd
- type WebhookUpdateCmd
Constants ¶
const ( FlowMethodPassword = "password" FlowMethodPhoneOTP = "phone_otp" FlowMethodMagicLink = "magic_link" FlowMethodPasskey = "passkey" FlowMethodOAuth = "oauth" FlowMethodEmail = "email" // recovery default channel )
Flow authentication methods (FlowCreateCmd.Method / Flow.Method).
const ( WebhookEventSessionRevoked = "session.revoked" WebhookEventUserBanned = "user.banned" WebhookEventUserDeleted = "user.deleted" WebhookEventEmailChanged = "email.changed" )
Variables ¶
var ( // 401 — authentication. ErrInvalidCredentials = newErr(http.StatusUnauthorized, "invalid_credentials", "Invalid credentials.") ErrInvalidToken = newErr(http.StatusUnauthorized, "invalid_token", "The token is invalid.") ErrTokenExpired = newErr(http.StatusUnauthorized, "token_expired", "The token has expired.") ErrTokenRevoked = newErr(http.StatusUnauthorized, "token_revoked", "The token has been revoked.") ErrSessionExpired = newErr(http.StatusUnauthorized, "session_expired", "The session has expired.") ErrSessionDeviceMismatch = newErr(http.StatusUnauthorized, "device_mismatch", "The session was used from a different device.") ErrMFAInvalid = newErr(http.StatusUnauthorized, "mfa_invalid", "Invalid MFA code.") ErrInvalidOTP = newErr(http.StatusUnauthorized, "invalid_otp", "Invalid one-time code.") ErrChallengeInvalid = newErr(http.StatusUnauthorized, "challenge_invalid", "Invalid challenge.") // 403 — permitted-but-blocked / gated. ErrForbidden = newErr(http.StatusForbidden, "forbidden", "Not permitted.") ErrAccountSuspended = newErr(http.StatusForbidden, "account_suspended", "Account suspended.") ErrAccountBanned = newErr(http.StatusForbidden, "account_banned", "Account banned.") ErrAccountLocked = newErr(http.StatusForbidden, "account_locked", "Account locked.") ErrEmailNotVerified = newErr(http.StatusForbidden, "email_not_verified", "Email not verified.") ErrPhoneNotVerified = newErr(http.StatusForbidden, "phone_not_verified", "Phone not verified.") ErrMFARequired = newErr(http.StatusForbidden, "mfa_required", "MFA is required.") ErrMFAFactorNotAllowed = newErr(http.StatusForbidden, "mfa_factor_not_allowed", "This MFA factor is not permitted by policy.") ErrStepUpRequired = newErr(http.StatusForbidden, "step_up_required", "Step-up authentication is required.") ErrRegistrationClosed = newErr(http.StatusForbidden, "registration_closed", "Registration is closed.") ErrInvitationRequired = newErr(http.StatusForbidden, "invitation_required", "An invitation is required.") ErrCaptchaRequired = newErr(http.StatusForbidden, "captcha_required", "Captcha is required.") ErrCaptchaInvalid = newErr(http.StatusForbidden, "captcha_invalid", "Invalid captcha.") ErrConsentRequired = newErr(http.StatusForbidden, "consent_required", "Consent is required.") ErrInvalidCsrf = newErr(http.StatusForbidden, "invalid_csrf", "Missing or invalid CSRF token.") // 404 — not found / not visible. ErrNotFound = newErr(http.StatusNotFound, "not_found", "Not found.") ErrUserNotFound = newErr(http.StatusNotFound, "user_not_found", "User not found.") ErrSessionNotFound = newErr(http.StatusNotFound, "session_not_found", "Session not found.") ErrProjectNotFound = newErr(http.StatusNotFound, "project_not_found", "Project not found.") ErrEnvironmentNotFound = newErr(http.StatusNotFound, "environment_not_found", "Environment not found.") ErrClientNotFound = newErr(http.StatusNotFound, "client_not_found", "App client not found.") ErrConnectionNotFound = newErr(http.StatusNotFound, "connection_not_found", "Connection not found.") ErrDomainNotFound = newErr(http.StatusNotFound, "domain_not_found", "Domain not found.") // 409 — conflict. ErrConflict = newErr(http.StatusConflict, "conflict", "Conflicting state.") ErrEmailExists = newErr(http.StatusConflict, "email_exists", "Email already in use.") ErrPhoneExists = newErr(http.StatusConflict, "phone_exists", "Phone already in use.") ErrIdentityExists = newErr(http.StatusConflict, "identity_exists", "Identity already linked.") ErrAlreadyLinked = newErr(http.StatusConflict, "already_linked", "Already linked.") ErrDomainTaken = newErr(http.StatusConflict, "domain_taken", "Domain already claimed.") // 410 — gone / single-use consumed. ErrChallengeExpired = newErr(http.StatusGone, "challenge_expired", "The challenge has expired.") ErrTokenUsed = newErr(http.StatusGone, "token_already_used", "The token has already been used.") ErrFlowNotFound = newErr(http.StatusGone, "flow_not_found", "Flow not found or expired.") ErrFlowExpired = newErr(http.StatusGone, "flow_expired", "The flow has expired.") // 422 — validation. ErrValidation = newErr(http.StatusUnprocessableEntity, "validation_failed", "Validation failed.") ErrWeakPassword = newErr(http.StatusUnprocessableEntity, "weak_password", "The password is too weak.") ErrPasswordReused = newErr(http.StatusUnprocessableEntity, "password_reused", "The password was used before.") // 400 — malformed. ErrBadRequest = newErr(http.StatusBadRequest, "bad_request", "Invalid request.") ErrUnsupportedGrant = newErr(http.StatusBadRequest, "unsupported_grant", "Unsupported grant type.") // 429 — throttled. ErrRateLimited = newErr(http.StatusTooManyRequests, "rate_limited", "Too many requests.") ErrFlowResendTooSoon = newErr(http.StatusTooManyRequests, "flow_resend_too_soon", "Please wait before resending.") // 501 — not implemented. ErrNotImplemented = newErr(http.StatusNotImplemented, "not_implemented", "Not implemented.") // 502/503/500 — downstream / server. ErrProviderError = newErr(http.StatusBadGateway, "provider_error", "Upstream provider error.") ErrSSOError = newErr(http.StatusBadGateway, "sso_error", "SSO error.") ErrSCIMError = newErr(http.StatusBadGateway, "scim_error", "SCIM error.") ErrInternal = newErr(http.StatusInternalServerError, "internal_error", "Internal error.") )
The complete catalogue of domain errors. Branch with errors.Is.
var BuiltinEmailTemplates = []BuiltinEmailTemplate{ { Key: "email_verification", Name: "Email verification", Locales: map[string]BuiltinEmailCopy{ "en": { Subject: "Verify your email", Text: "Use code {{.code}} to verify your email.{{with .link}}\nOr open this link: {{.}}{{end}}", HTML: `<p>Use code <strong>{{.code}}</strong> to verify your email.</p>{{with .link}}<p>Or open this link: <a href="{{.}}">{{.}}</a></p>{{end}}`, }, "ru": { Subject: "Подтвердите вашу почту", Text: "Введите код {{.code}}, чтобы подтвердить почту.{{with .link}}\nИли откройте ссылку: {{.}}{{end}}", HTML: `<p>Введите код <strong>{{.code}}</strong>, чтобы подтвердить почту.</p>{{with .link}}<p>Или откройте ссылку: <a href="{{.}}">{{.}}</a></p>{{end}}`, }, }, }, { Key: "otp", Name: "Sign-in code (OTP)", Locales: map[string]BuiltinEmailCopy{ "en": { Subject: "Your sign-in code", Text: "Your code is {{.code}}.", HTML: `<p>Your code is <strong>{{.code}}</strong>.</p>`, }, "ru": { Subject: "Код для входа", Text: "Ваш код: {{.code}}.", HTML: `<p>Ваш код: <strong>{{.code}}</strong>.</p>`, }, }, }, { Key: "magic_link", Name: "Magic link", Locales: map[string]BuiltinEmailCopy{ "en": { Subject: "Your sign-in link", Text: "Open this link to sign in: {{.link}}", HTML: `<p>Open this link to sign in: <a href="{{.link}}">{{.link}}</a></p>`, }, "ru": { Subject: "Ссылка для входа", Text: "Откройте ссылку, чтобы войти: {{.link}}", HTML: `<p>Откройте ссылку, чтобы войти: <a href="{{.link}}">{{.link}}</a></p>`, }, }, }, { Key: "email_change", Name: "Email change", Locales: map[string]BuiltinEmailCopy{ "en": { Subject: "Confirm your new email", Text: "Use code {{.code}} to confirm your new email.{{with .link}}\nOr open this link: {{.}}{{end}}", HTML: `<p>Use code <strong>{{.code}}</strong> to confirm your new email.</p>{{with .link}}<p>Or open this link: <a href="{{.}}">{{.}}</a></p>{{end}}`, }, "ru": { Subject: "Подтвердите новую почту", Text: "Введите код {{.code}}, чтобы подтвердить новую почту.{{with .link}}\nИли откройте ссылку: {{.}}{{end}}", HTML: `<p>Введите код <strong>{{.code}}</strong>, чтобы подтвердить новую почту.</p>{{with .link}}<p>Или откройте ссылку: <a href="{{.}}">{{.}}</a></p>{{end}}`, }, }, }, { Key: "password_reset", Name: "Password reset", Locales: map[string]BuiltinEmailCopy{ "en": { Subject: "Reset your password", Text: "Use code {{.code}} to reset your password.{{with .link}}\nOr open this link: {{.}}{{end}}", HTML: `<p>Use code <strong>{{.code}}</strong> to reset your password.</p>{{with .link}}<p>Or open this link: <a href="{{.}}">{{.}}</a></p>{{end}}`, }, "ru": { Subject: "Сброс пароля", Text: "Введите код {{.code}}, чтобы сбросить пароль.{{with .link}}\nИли откройте ссылку: {{.}}{{end}}", HTML: `<p>Введите код <strong>{{.code}}</strong>, чтобы сбросить пароль.</p>{{with .link}}<p>Или откройте ссылку: <a href="{{.}}">{{.}}</a></p>{{end}}`, }, }, }, { Key: "mfa_email", Name: "MFA code", Locales: map[string]BuiltinEmailCopy{ "en": { Subject: "Your MFA code", Text: "Your MFA code is {{.code}}.", HTML: `<p>Your MFA code is <strong>{{.code}}</strong>.</p>`, }, "ru": { Subject: "Код двухфакторной аутентификации", Text: "Ваш код подтверждения: {{.code}}.", HTML: `<p>Ваш код подтверждения: <strong>{{.code}}</strong>.</p>`, }, }, }, { Key: "flow_continue", Name: "Continue on another device", Locales: map[string]BuiltinEmailCopy{ "en": { Subject: "Continue where you left off", Text: "Use code {{.code}} to continue.{{with .continue_url}}\nOr open this link: {{.}}{{end}}", HTML: `<p>Use code <strong>{{.code}}</strong> to continue.</p>{{with .continue_url}}<p>Or open this link: <a href="{{.}}">{{.}}</a></p>{{end}}`, }, "ru": { Subject: "Продолжите с того же места", Text: "Введите код {{.code}}, чтобы продолжить.{{with .continue_url}}\nИли откройте ссылку: {{.}}{{end}}", HTML: `<p>Введите код <strong>{{.code}}</strong>, чтобы продолжить.</p>{{with .continue_url}}<p>Или откройте ссылку: <a href="{{.}}">{{.}}</a></p>{{end}}`, }, }, }, { Key: "invite", Name: "Invitation", Locales: map[string]BuiltinEmailCopy{ "en": { Subject: "You're invited", Text: "You've been invited. Accept your invitation: {{.invite_url}} (or use code {{.invite_token}})", HTML: `<p>You've been invited.</p>{{with .invite_url}}<p>Accept your invitation: <a href="{{.}}">{{.}}</a></p>{{end}}<p>Alternatively, use code <strong>{{.invite_token}}</strong>.</p>`, }, "ru": { Subject: "Вас пригласили", Text: "Вас пригласили. Примите приглашение: {{.invite_url}} (или используйте код {{.invite_token}})", HTML: `<p>Вас пригласили.</p>{{with .invite_url}}<p>Примите приглашение по ссылке: <a href="{{.}}">{{.}}</a></p>{{end}}<p>Или используйте код <strong>{{.invite_token}}</strong>.</p>`, }, }, }, }
BuiltinEmailTemplates is the canonical catalogue, keyed by the template ids the notification layer emits. Slice order is the admin display order. Keep the copy in sync with the renderer fallbacks.
var EmailProviderTypes = newStringSet("smtp")
EmailProviderTypes is the canonical set for iam_providers (kind=email) `type`. Only "smtp" is realized: the runtime sender skips every other type silently. To add a sender (ses/sendgrid/...): implement the sender, then add it here.
var FeatureKeys = newStringSet(
"password",
"otp",
"phone_login",
"magic_link",
"webauthn",
"oauth",
"mfa",
"guest",
"email_verification",
"phone_verification",
"email_change",
"phone_change",
"resumable_flows",
"impersonation",
"consent",
"access_requests",
"step_up",
)
FeatureKeys is the canonical namespace for the features doc (map[string]bool). Only keys backed by a working subsystem are listed. To add a feature: wire the toggle into the runtime, then add the key here.
var PasswordStrategies = newStringSet("password_first", "after_verify")
PasswordStrategies is the canonical set for auth.registration.password_strategy. Both are realized. To add a strategy: implement the flow branch, then add it here.
var RateLimitActions = newStringSet()
RateLimitActions is the canonical set for rate_limits rules `action`. The runtime limiter has NO concept of "action" today, so the set is EMPTY and any non-empty action is rejected. To support actions: implement action-aware limiting, then populate this set.
var RateLimitBy = newStringSet("ip")
RateLimitBy is the canonical set for rate_limits rules `by` (the counter subject). The runtime limiter keys exclusively by client IP, so "ip" is the only realized value. To add a dimension (user/session/...): implement keying in the limiter, then add it here.
var RateLimitEndpoints = newStringSet(
"/v1/auth/guest",
"/v1/auth/sign-in/password",
"/v1/auth/password/forgot",
"/v1/auth/password/reset",
"/v1/auth/password/verify",
"/v1/auth/email/verification/start",
"/v1/auth/email/verification/verify",
"/v1/auth/phone/verification/start",
"/v1/auth/phone/verification/verify",
"/v1/auth/otp/start",
"/v1/auth/otp/verify",
"/v1/auth/magic-link/start",
"/v1/auth/magic-link/verify",
"/v1/auth/mfa/challenge",
"/v1/auth/mfa/verify",
"/v1/auth/webauthn/login/options",
"/v1/auth/webauthn/login/verify",
"/v1/auth/webauthn/register/options",
"/v1/auth/webauthn/register/verify",
"/v1/challenges/captcha/verify",
"/v1/auth/sign-up",
"/v1/auth/token/refresh",
"/v1/auth/token/exchange",
"/v1/auth/oauth/exchange",
"/v1/auth/access-requests",
)
RateLimitEndpoints is the canonical set of endpoints the hardcoded limiter router actually classifies. A rule targeting any other path could never be enforced, so it is rejected. This MUST stay in sync with the switch lists in pkg/api/ratelimit.go (guest + sensitive + auth buckets). To add an endpoint: add it to the router classification, then add it here.
var RegistrationModes = newStringSet("open", "invite_only", "request_access", "closed")
RegistrationModes is the canonical set for auth.registration.mode. All four are enforced in the signup flow engine. To add a mode: implement the flow branch, then add it here.
var SMSProviderTypes = newStringSet("generic", "twilio", "aws_sns")
SMSProviderTypes is the canonical set for iam_providers (kind=sms) `type`. "generic" (HTTP webhook), "twilio", and "aws_sns" (AWS SNS / any SNS-compatible endpoint such as Yandex Cloud Notifications via a custom endpoint) are realized. The runtime sender skips every other type silently. To add a sender: implement the sender, then add it here.
var SupportedAuthMethods = newStringSet("email", "oauth", "passkey", "magic_link", "phone")
SupportedAuthMethods is the canonical set of values accepted in the auth doc `methods[]` array. Only methods implemented end-to-end are listed:
- email — password + email OTP/verification (flow engine + direct endpoints)
- oauth — social/OIDC via iam_providers rows (a methods entry is decorative)
- passkey — WebAuthn ceremony endpoints + iam_webauthn_credentials
- magic_link — /v1/auth/magic-link/{start,verify}
- phone — phone OTP login/signup over /v1/auth/otp/{start,verify} (channel=sms|whatsapp; resolves/creates by primary_phone)
`username` (as a first-class login method) is intentionally ABSENT: no route/handler/credential exists. To add a method: implement it end-to-end, then add it here.
var SupportedMFAFactors = newStringSet("totp", "sms", "email_otp", "webauthn", "backup_codes")
SupportedMFAFactors is the canonical set of values accepted in the mfa_policy doc `allowed_factors[]`. All five are implemented end-to-end. Note two policy values differ from the internal/DB names:
- email_otp maps to DB factor type "email"
- backup_codes maps to the iam_recovery_codes subsystem
To add a factor: implement enroll+verify end-to-end, then add it here.
var SupportedWebhookEvents = []string{ WebhookEventSessionRevoked, WebhookEventUserBanned, WebhookEventUserDeleted, WebhookEventEmailChanged, }
SupportedWebhookEvents is the deliberately small public event catalogue. Internal delivery events may contain credentials or one-time proofs and must never become subscribable merely because they pass through the same outbox.
Functions ¶
func FirstNonEmptyLocale ¶ added in v1.1.3
FirstNonEmptyLocale returns the first non-empty locale from candidates, or "en".
func MFAPolicyFactorName ¶ added in v1.3.0
MFAPolicyFactorName maps an internal/DB factor type to the value used in the mfa_policy `allowed_factors[]` doc (see SupportedMFAFactors). Two names differ from the DB representation:
- DB "email" -> policy "email_otp"
- the recovery-codes subsystem ("recovery"/"backup_codes") -> "backup_codes"
All other factors (totp/sms/webauthn) map 1:1.
func NormalizeOrigin ¶ added in v1.2.3
NormalizeOrigin validates and canonicalises a browser origin (scheme://host[:port]). It returns "" for anything that must NOT be allowed as a CORS origin: empty, "*", "null", non-http(s) schemes, missing host, any path/query/fragment/userinfo, or plain http on a non-loopback host. The result is lowercase scheme + host so comparisons are exact.
Rejecting "*"/"null" prevents credentialed wildcard and sandboxed-iframe (Origin: null) bypasses; requiring https off-localhost avoids registering insecure origins for credentialed CORS.
func NormalizeOrigins ¶ added in v1.2.3
NormalizeOrigins validates, canonicalises, and de-duplicates a list of origins, dropping invalid entries and capping the count.
func ValidateEmail ¶
ValidateEmail checks basic email format (contains @, has a domain part with a dot). This is NOT a full RFC 5322 check — it rejects obviously malformed addresses without false-positive-rejecting valid ones.
func ValidatePhone ¶
ValidatePhone checks that phone matches E.164 format (starts with +, 7-15 digits after the plus sign, no leading zero on the country code).
func WithRequestMeta ¶ added in v1.1.0
func WithRequestMeta(ctx context.Context, m RequestMeta) context.Context
WithRequestMeta returns a context carrying the request metadata.
Types ¶
type AccountAcceptConsentsCmd ¶
type AccountAcceptConsentsCmd struct {
AccountID string
Accept []AccountConsentAcceptance
}
AccountAcceptConsentsCmd accepts one or more consent documents.
type AccountActivityCmd ¶
AccountActivityCmd queries the account activity log.
type AccountActivityEvent ¶
AccountActivityEvent is a single audit/activity record on the account.
type AccountActivityPage ¶
type AccountActivityPage struct {
Events []AccountActivityEvent
NextCursor string
HasMore bool
}
AccountActivityPage is a cursor-paginated slice of activity events.
type AccountConsent ¶
type AccountConsent struct {
Key string
Version string
URL string
AcceptedAt time.Time
Locale string
}
AccountConsent is a recorded consent acceptance on the account.
type AccountConsentAcceptance ¶
AccountConsentAcceptance records acceptance of one consent document.
type AccountExportJob ¶
AccountExportJob describes a pending or finished data-export job.
type AccountMergeConfirmCmd ¶
AccountMergeConfirmCmd confirms a pending identity merge with a challenge code.
type AccountMergeStartCmd ¶
AccountMergeStartCmd begins linking/merging another identity into the account.
type AccountRenameSessionCmd ¶
AccountRenameSessionCmd sets a human-friendly device name on a session.
type AccountRevokeSessionsCmd ¶
type AccountRevokeSessionsCmd struct {
AccountID string
ExceptSessionID string // if set, this session is kept
ExceptCurrent bool
}
AccountRevokeSessionsCmd bulk-revokes sessions for the account.
type AccountTrustSessionCmd ¶
AccountTrustSessionCmd marks a session as trusted for a duration.
type AdminAPIKeyCmd ¶
AdminAPIKeyCmd creates a project API key.
type AdminAPIKeySecret ¶
AdminAPIKeySecret is an API key plus its one-time plaintext secret.
type AdminAPIKeyUpdateCmd ¶
type AdminAPIKeyUpdateCmd struct {
ProjectID string
KeyID string
Name string
Scopes []string
Disabled bool
}
AdminAPIKeyUpdateCmd updates an API key's name / scopes / state.
type AdminAccessRequestDecisionCmd ¶
type AdminAccessRequestDecisionCmd struct {
ProjectID string
Environment string
RequestID string
ActorID string
Reason string
}
AdminAccessRequestDecisionCmd approves or denies an access request.
type AdminAccessRequestListCmd ¶
type AdminAccessRequestListCmd struct {
ProjectID string
Environment string
Status string
Cursor string
}
AdminAccessRequestListCmd lists pending access requests.
type AdminAccessRequestPage ¶
type AdminAccessRequestPage struct {
Items []CoreAuthAccessRequest
NextCursor string
HasMore bool
}
AdminAccessRequestPage is a page of access requests.
type AdminConfigDoc ¶
AdminConfigDoc is an opaque, fully-typed configuration document carried between the API layer and the adapter as a map of raw JSON fields. Services never interpret it: the adapter validates/persists, the API layer round-trips it to/from the matching generated oas type. Used for auth / password-policy / session-policy / consent configuration objects.
type AdminConfigGetCmd ¶
AdminConfigGetCmd selects a configuration document for read.
type AdminConfigUpdateCmd ¶
type AdminConfigUpdateCmd struct {
ProjectID string
Environment string
Doc AdminConfigDoc
}
AdminConfigUpdateCmd carries a (partial or full) configuration document to apply. Doc is the wire object the admin sent, opaque to the service.
type AdminConnectionCmd ¶
type AdminConnectionCmd struct {
ProjectID string
Type string
Name string
Domains []string
ExternalRef string
}
AdminConnectionCmd creates an SSO connection.
type AdminDomainCmd ¶
AdminDomainCmd registers a verification domain.
type AdminDomainRegistration ¶
type AdminDomainRegistration struct {
Domain *Domain
VerificationRecordType string
VerificationRecordName string
VerificationRecordValue string
}
AdminDomainRegistration is a domain plus the DNS record proving ownership.
type AdminFeaturesUpdateCmd ¶
AdminFeaturesUpdateCmd toggles project feature flags.
type AdminI18nUpdateCmd ¶
type AdminI18nUpdateCmd struct {
ProjectID string
Environment string
Locale string
Messages map[string]jx.Raw
}
AdminI18nUpdateCmd replaces the i18n bundle for a locale.
type AdminImpersonation ¶
AdminImpersonation is the result of an impersonation request.
type AdminJWKSRotateCmd ¶
AdminJWKSRotateCmd rotates the signing key set, optionally activating the new key immediately.
type AdminProvider ¶
AdminProvider is a configured notification provider (email or SMS). Config is an opaque settings bag the adapter interprets.
type AdminProviderCmd ¶
type AdminProviderCmd struct {
ProjectID string
Environment string
ID string // empty on create
Type string
Config map[string]jx.Raw
Enabled bool
}
AdminProviderCmd creates or replaces a notification provider.
type AdminProviderDeleteCmd ¶
AdminProviderDeleteCmd removes a notification provider.
type AdminSecret ¶
AdminSecret is a freshly minted machine credential. The plaintext secret is returned exactly once.
type AdminServiceAccountSecretCmd ¶
type AdminServiceAccountSecretCmd struct {
ProjectID string
ServiceAccountID string
Name string
ExpiresAt time.Time
}
AdminServiceAccountSecretCmd issues a new secret for a service account.
type AdminServiceAccountUpdateCmd ¶
type AdminServiceAccountUpdateCmd struct {
ProjectID string
ServiceAccountID string
Scopes []string
Disabled bool
}
AdminServiceAccountUpdateCmd updates a service account's scopes / state.
type AdminSigningKey ¶
AdminSigningKey is a JWKS signing key in its administrative form.
type AdminTemplatePreview ¶
AdminTemplatePreview is a rendered email template.
type AdminTemplatePreviewCmd ¶
type AdminTemplatePreviewCmd struct {
ProjectID string
Environment string
TemplateID string
Locale string
Data map[string]jx.Raw
}
AdminTemplatePreviewCmd renders an email template with sample data.
type AdminTemplateSendTestCmd ¶
type AdminTemplateSendTestCmd struct {
ProjectID string
Environment string
TemplateID string
To string
Locale string
Data map[string]jx.Raw
}
AdminTemplateSendTestCmd sends a rendered template to a test address.
type AdminTemplateUpdateCmd ¶
type AdminTemplateUpdateCmd struct {
ProjectID string
Environment string
TemplateID string
Patch map[string]jx.Raw
}
AdminTemplateUpdateCmd patches an email template.
type AdminTokenProfile ¶
type AdminTokenProfile struct {
ID string
Name string
Audience string
AccessTTL int
RefreshTTL int
ClaimsTemplate map[string]jx.Raw
}
AdminTokenProfile is a token-shaping profile.
type AdminTokenProfileCmd ¶
type AdminTokenProfileCmd struct {
ProjectID string
Environment string
ID string // empty on create
Profile AdminConfigDoc
}
AdminTokenProfileCmd creates or replaces a token profile.
type AdminTokenProfilePreviewCmd ¶
type AdminTokenProfilePreviewCmd struct {
ProjectID string
Environment string
ProfileID string
UserID string
}
AdminTokenProfilePreviewCmd renders the claims a profile would produce for a user.
type AdminUserAnonymizeCmd ¶
type AdminUserAnonymizeCmd struct {
ProjectID string
Environment string
AccountID string
Reason string
}
AdminUserAnonymizeCmd anonymizes (GDPR erase) a user.
type AdminUserBanCmd ¶
type AdminUserBanCmd struct {
ProjectID string
Environment string
AccountID string
Reason string
Until time.Time
}
AdminUserBanCmd bans a user, optionally with a reason and an expiry.
type AdminUserImpersonateCmd ¶
type AdminUserImpersonateCmd struct {
ProjectID string
Environment string
AccountID string
ActorID string // the admin performing the impersonation
Reason string
DurationSeconds int
}
AdminUserImpersonateCmd mints a time-boxed impersonation link.
type AdminUserPasswordCmd ¶
type AdminUserPasswordCmd struct {
ProjectID string
Environment string
AccountID string
Password string
RevokeSessions bool
}
AdminUserPasswordCmd sets a user's password out-of-band.
type AdminUserSessionsRevokeCmd ¶
type AdminUserSessionsRevokeCmd struct {
ProjectID string
Environment string
AccountID string
ExceptSessionID string
Reason string
}
AdminUserSessionsRevokeCmd revokes a user's sessions, optionally keeping one.
type AdminUserUpdateCmd ¶
type AdminUserUpdateCmd struct {
ProjectID string
Environment string
AccountID string
Name string
Locale string
}
AdminUserUpdateCmd is a partial profile update applied by a project admin.
type AppClient ¶
type AppClient struct {
ID string
ProjectID string
Name string
Type string // spa | native | web | machine
Environment string
RedirectURIs []string
// AllowedOrigins are the browser origins (scheme://host[:port]) permitted to
// make cross-origin calls to IAM for this client. The CORS layer reflects
// ACAO for any origin in the union of all clients' AllowedOrigins.
AllowedOrigins []string
}
type AppClientCmd ¶
type AuthConfigSpec ¶ added in v1.3.0
type AuthConfigSpec struct {
Methods []string `json:"methods,omitempty"`
Registration *AuthRegistrationConfig `json:"registration,omitempty"`
AppBaseURL *string `json:"app_base_url,omitempty"`
DefaultLocale *string `json:"default_locale,omitempty"`
SupportedLocales []string `json:"supported_locales,omitempty"`
Locales []string `json:"locales,omitempty"`
}
AuthConfigSpec is the typed mirror of the iam_config key="auth" document. Field tags are the exact stored jsonb keys. `locales` and `supported_locales` both appear in the wild (oas writes supported_locales, platform_pg reads locales); both are accepted and reconciled in Validate.
func ParseAuthConfig ¶ added in v1.3.0
func ParseAuthConfig(raw []byte) (AuthConfigSpec, error)
ParseAuthConfig strictly decodes the auth doc, rejecting unknown top-level keys.
func (AuthConfigSpec) Validate ¶ added in v1.3.0
func (c AuthConfigSpec) Validate() error
Validate enforces the auth-doc rules fail-closed.
type AuthRegistrationConfig ¶ added in v1.3.0
type AuthRegistrationConfig struct {
Mode *string `json:"mode,omitempty"`
PasswordStrategy *string `json:"password_strategy,omitempty"`
}
AuthRegistrationConfig mirrors the nested `registration` object in the auth doc. Tags match coreauth_flows_pg.go / platform_pg.go / oas RegistrationConfig.
type BuiltinEmailCopy ¶ added in v1.1.3
BuiltinEmailCopy is the localized copy of a built-in email template.
type BuiltinEmailTemplate ¶ added in v1.1.3
type BuiltinEmailTemplate struct {
Key string
Name string
Locales map[string]BuiltinEmailCopy
}
BuiltinEmailTemplate is a system-provided email template: the default copy the notification renderer falls back to when a project has not customised the template for a given key/locale. The admin API lists, previews, and test-sends these so operators can see and exercise every template (and verify SMTP) before overriding any of them. Copy is keyed by locale; "en" is the canonical fallback and must always be present.
func BuiltinEmailTemplateByKey ¶ added in v1.1.3
func BuiltinEmailTemplateByKey(key string) *BuiltinEmailTemplate
BuiltinEmailTemplateByKey returns the catalogue entry for key, or nil when key is not a known built-in template.
func (*BuiltinEmailTemplate) Copy ¶ added in v1.1.3
func (t *BuiltinEmailTemplate) Copy(locale string) BuiltinEmailCopy
Copy returns the localized copy for locale, falling back to the base language (e.g. "ru-RU" -> "ru") and then to "en".
type Challenge ¶
type Challenge struct {
ID string
Type string
ExpiresAt time.Time
// Code and Token are transient delivery proofs returned only inside the
// current process so higher-level flows can build a single email containing
// both the manual code and the one-click proof link. They must never be
// serialized or exposed by API mappers.
Code string `json:"-"`
Token string `json:"-"`
// PublicKey carries WebAuthn / provisioning material when relevant.
PublicKey map[string]any
}
type Connection ¶
type Connection struct {
ID string
ProjectID string
Type string // saml | oidc
Name string
Status string
Domains []string
ExternalRef string
// Config carries the protocol-specific provider settings (SAML IdP metadata
// / certificate, OIDC issuer / client credentials). It is persisted whole in
// the connection's jsonb envelope; see FederationSamlConfig / FederationOidcConfig.
Config *FederationConnectionConfig `json:",omitempty"`
}
type ConnectionCmd ¶
func (ConnectionCmd) Validate ¶
func (c ConnectionCmd) Validate() error
Validate checks connection-create invariants.
type ConsentConfigSpec ¶ added in v1.3.0
type ConsentConfigSpec struct {
Documents []ConsentDocumentSpec `json:"documents,omitempty"`
}
ConsentConfigSpec mirrors the consent jsonb doc.
func ParseConsentConfig ¶ added in v1.3.0
func ParseConsentConfig(raw []byte) (ConsentConfigSpec, error)
ParseConsentConfig strictly decodes the consent doc.
func (ConsentConfigSpec) Validate ¶ added in v1.3.0
func (c ConsentConfigSpec) Validate() error
Validate enforces presentability and uniqueness rules fail-closed.
type ConsentDocument ¶
type ConsentDocumentSpec ¶ added in v1.3.0
type ConsentDocumentSpec struct {
Key string `json:"key"`
Version string `json:"version"`
Title *string `json:"title,omitempty"`
Body *string `json:"body,omitempty"`
Locale *string `json:"locale,omitempty"`
Required *bool `json:"required,omitempty"`
URL *string `json:"url,omitempty"`
}
ConsentDocumentSpec mirrors one consent document. Tags match the lowercase oas ConsentDocument / platform jsonb keys.
type CoreAuthAccessRequest ¶
type CoreAuthAccessRequest struct {
ID string
ProjectID string
Email string
Reason string
Status string
}
CoreAuthAccessRequest is a request for access to a project that gates self-service sign-up behind approval.
type CoreAuthAccessRequestCmd ¶
type CoreAuthAccessRequestCmd struct {
ProjectID string
Email string
Reason string
CaptchaToken string
}
CoreAuthAccessRequestCmd creates an access request.
type CoreAuthCaptchaVerifyResult ¶
CoreAuthCaptchaVerifyResult is the outcome of verifying a CAPTCHA token with the configured provider.
type CoreAuthEmailVerificationCallbackCmd ¶
CoreAuthEmailVerificationCallbackCmd consumes an opaque email-verification link token and resolves where to send the browser next.
type CoreAuthEmailVerificationCallbackResult ¶
CoreAuthEmailVerificationCallbackResult is the outcome of consuming an email verification link: the absolute redirect URL and an optional Set-Cookie value (e.g. a freshly issued session cookie) for the browser.
type CoreAuthPasswordChangeCmd ¶
type CoreAuthPasswordChangeCmd struct {
AccountID string
SessionID string
CurrentPassword string
NewPassword string
RevokeOtherSessions bool
}
CoreAuthPasswordChangeCmd changes the current account's password.
type CoreAuthPasswordCheckResult ¶
CoreAuthPasswordCheckResult is the outcome of a policy/strength check.
type CoreAuthPasswordForgotCmd ¶
type CoreAuthPasswordForgotCmd struct {
ProjectID string
Email string
RedirectTo string
Locale string
CaptchaToken string
}
CoreAuthPasswordForgotCmd begins a password-reset flow for an email.
type CoreAuthPasswordResetCmd ¶
type CoreAuthPasswordResetCmd struct {
ProjectID string
Token string
ChallengeID string
Code string
NewPassword string
}
CoreAuthPasswordResetCmd completes a password-reset flow with a fresh password. A reset is identified by ChallengeID plus Code, by ChallengeID plus Token, or by Token alone for standalone reset links.
type CoreAuthPasswordResult ¶ added in v1.1.0
type CoreAuthPasswordResult struct {
Account *Account
Session *Session
MFARequired bool
Factors []Factor
}
CoreAuthPasswordResult is the outcome of a password sign-in. When MFARequired is true the password (factor 1) verified but the account has an enrolled MFA factor, so no session is issued yet: the caller must complete a second factor. Session is non-nil only when MFARequired is false. Factors lists the account's active MFA factors so the client can choose which to use.
type CoreAuthPasswordVerifyResult ¶
CoreAuthPasswordVerifyResult is the outcome of re-asserting the current account's password (e.g. for a sudo/step-up gate).
type CoreAuthRevokeCmd ¶
CoreAuthRevokeCmd revokes a token or a whole session.
type CoreAuthStepUpCmd ¶
type CoreAuthStepUpCmd struct {
AccountID string
SessionID string
Purpose string
RequiredAAL int
MaxAgeSeconds int
HasMaxAge bool
}
CoreAuthStepUpCmd requests elevation of the current session to a higher AAL.
type CoreAuthStepUpResult ¶
CoreAuthStepUpResult is the outcome of a step-up request. When Satisfied is true the session already meets the bar; otherwise a Challenge gates it.
type CoreAuthTokenIntrospection ¶
CoreAuthTokenIntrospection is the result of introspecting a token.
type CoreAuthTokenVerification ¶
CoreAuthTokenVerification is the result of verifying a token.
type CoreAuthVerifyConsumeCmd ¶
type CoreAuthVerifyConsumeCmd struct {
ProjectID string
AccountID string // empty for unauthenticated consume
ChallengeID string
Code string
Token string
}
CoreAuthVerifyConsumeCmd consumes a verification/change challenge. A challenge is identified by ChallengeID plus Code, by ChallengeID plus Token, or by Token alone for standalone link callbacks.
type CoreAuthVerifyStartCmd ¶
type CoreAuthVerifyStartCmd struct {
ProjectID string
AccountID string // empty for unauthenticated start (public verification)
Contact string // the email or phone to verify; empty -> use the account's primary
RedirectTo string
Locale string
Channel string // sms | whatsapp (phone only)
SuppressEmail bool // flow engine sends a combined flow+proof email itself
}
CoreAuthVerifyStartCmd starts an email or phone verification/change flow. One challenge is minted and (for email/phone) a code or link is dispatched.
type Environment ¶
type EnvironmentCmd ¶
type Error ¶
Error is a domain error carrying the stable machine code, an HTTP status and a default human message. The persistence/service layers return these; the API layer (pkg/api NewError) renders them into the ErrorEnvelope. Equality is by Code, so errors.Is(err, ErrInvalidCredentials) matches any *Error with the same code, whether a sentinel or a freshly built one with details.
func (*Error) Is ¶
Is matches by Code so wrapped/rebuilt errors still compare equal to the sentinel of the same code.
func (*Error) WithDetails ¶
WithDetails returns a copy carrying structured context.
func (*Error) WithMessage ¶
WithMessage returns a copy with an overridden human message.
type Event ¶
type Event struct {
// ID is the unique event id (uuid). Consumers deduplicate on it because
// outbox delivery is at-least-once.
ID string `json:"id"`
// Version is the schema version of this event. Emitters default it to 1.
Version int `json:"version"`
// Type is the event name, "<aggregate>.<verb>" (e.g. "api_key.created").
Type string `json:"type"`
// ProjectID is the owning tenant; used as the outbox partition key so events
// for one project stay ordered.
ProjectID string `json:"project_id"`
// Environment is the project environment (live/…); empty when not applicable.
Environment string `json:"environment"`
// AggregateID is the id of the affected aggregate instance.
AggregateID string `json:"aggregate_id"`
// OccurredAt is when the event happened (UTC).
OccurredAt time.Time `json:"occurred_at"`
// Payload is the aggregate snapshot (or, for delivery events, the dispatch
// envelope). JSON-serialised into the outbox message body.
Payload any `json:"payload"`
}
Event is a domain event emitted transactionally through the outbox: the adapter that mutates an aggregate enqueues the event inside the same database transaction, so the event is durably recorded iff the mutation commits.
Payload carries a full snapshot of the affected aggregate (the subscriber is an in-infrastructure consumer that wants the state in-context, not a public API). Delivery events (auth.otp.started, auth.magiclink.started, …) carry the plaintext secret needed to dispatch the message — that plaintext lands in the outbox at rest and is the reason outbox payloads are an encryption target.
type Factor ¶
type Factor struct {
ID string
Type string // totp | sms | email | webauthn
Status string // pending | active
Hint string
// OTPAuthURL is the otpauth:// provisioning URL returned to the caller at
// TOTP enrollment time so it can be rendered as a QR code. It is transient
// provisioning material, not a stored credential (the shared secret lives
// in iam_factors.secret), so it is excluded from the persisted aggregate.
OTPAuthURL string `json:"-"`
}
type FeaturesSpec ¶ added in v1.3.0
FeaturesSpec mirrors the features jsonb doc (a flat map[string]bool).
func ParseFeatures ¶ added in v1.3.0
func ParseFeatures(raw []byte) (FeaturesSpec, error)
ParseFeatures decodes the features doc.
func (FeaturesSpec) Validate ¶ added in v1.3.0
func (c FeaturesSpec) Validate() error
Validate rejects any key outside the canonical FeatureKeys registry.
type FederationConnectionConfig ¶
type FederationConnectionConfig struct {
Saml *FederationSamlConfig `json:"saml,omitempty"`
Oidc *FederationOidcConfig `json:"oidc,omitempty"`
}
FederationConnectionConfig is the protocol-specific provider configuration of an SSO connection, persisted whole in the connection's jsonb envelope. Exactly one of Saml / Oidc is populated, matching Connection.Type.
type FederationConnectionUpdateCmd ¶
FederationConnectionUpdateCmd is a partial update of an SSO connection. The Patch map carries only the fields the caller supplied (decoded from the free-form JSON merge-patch body); the adapter applies them atomically.
type FederationOidcConfig ¶
type FederationOidcConfig struct {
Issuer string `json:"issuer,omitempty"`
AuthURL string `json:"auth_url,omitempty"`
TokenURL string `json:"token_url,omitempty"`
JWKSURL string `json:"jwks_url,omitempty"`
ClientID string `json:"client_id,omitempty"`
ClientSecret string `json:"client_secret,omitempty"`
RedirectURL string `json:"redirect_url,omitempty"`
Scopes []string `json:"scopes,omitempty"`
}
FederationOidcConfig carries the external OIDC provider settings used to drive the authorization-code leg and to verify the returned id_token.
type FederationSamlAcsCmd ¶
FederationSamlAcsCmd completes an inbound SAML assertion consumer leg. The adapter validates the assertion, links the account and returns the post-login redirect URL plus an optional session cookie.
type FederationSamlConfig ¶
type FederationSamlConfig struct {
// IDPMetadataXML is the IdP's SAML metadata document (entityID, SSO URL,
// signing certificate). When present it is the authoritative source.
IDPMetadataXML string `json:"idp_metadata_xml,omitempty"`
// IDPCertificatePEM is a fallback IdP signing certificate (PEM) used when no
// full metadata document is available.
IDPCertificatePEM string `json:"idp_certificate_pem,omitempty"`
// EntityID is the SP entity ID advertised to the IdP. Defaults to MetadataURL.
EntityID string `json:"entity_id,omitempty"`
// AcsURL is the SP Assertion Consumer Service URL (where the IdP POSTs the
// signed Response).
AcsURL string `json:"acs_url,omitempty"`
// MetadataURL is the SP metadata endpoint URL.
MetadataURL string `json:"metadata_url,omitempty"`
// SPCertificatePEM / SPPrivateKeyPEM is the SP's own signing keypair used to
// sign AuthnRequests and to advertise the SP signing certificate in metadata.
// Optional: when absent the SP runs without request signing.
SPCertificatePEM string `json:"sp_certificate_pem,omitempty"`
SPPrivateKeyPEM string `json:"sp_private_key_pem,omitempty"`
}
FederationSamlConfig carries the SAML Service Provider's view of an IdP: the IdP metadata XML (preferred) or a raw IdP signing certificate, plus the SP endpoint URLs used to build the AuthnRequest / ACS / metadata documents.
type FederationScimListQuery ¶
FederationScimListQuery is a paginated SCIM list request.
type FederationScimPatchCmd ¶
FederationScimPatchCmd applies a SCIM PATCH operation set to a resource.
type FederationScimResource ¶
FederationScimResource is an opaque SCIM resource (User or Group) carried as a free-form attribute map. pkg/api maps it to/from the generated wire maps; the adapter owns the SCIM schema semantics.
type FederationScimTokenCmd ¶
type FederationScimTokenCmd struct {
ProjectID string
ConnectionID string
Name string
ExpiresAt time.Time
}
FederationScimTokenCmd mints a new SCIM provisioning bearer token scoped to a single SSO connection.
type FederationScimWriteCmd ¶
type FederationScimWriteCmd struct {
ConnectionID string
ResourceID string // empty on create
Attributes map[string]any
}
FederationScimWriteCmd creates or replaces a SCIM resource on a connection.
type FederationSsoCallbackCmd ¶
FederationSsoCallbackCmd completes an inbound OIDC callback. The adapter exchanges the code, provisions/links the account and returns the post-login redirect URL plus an optional session cookie.
type FederationSsoRedirect ¶
type FederationSsoRedirect struct {
URL string
// Cookie carries the session cookies (access + refresh) to set in cookie
// mode; each entry is a full Set-Cookie header value.
Cookie []string
}
FederationSsoRedirect is a runtime SSO redirect result: the URL the caller's browser must be sent to, plus an optional Set-Cookie value.
type FederationSsoStartCmd ¶
type FederationSsoStartCmd struct {
ConnectionID string
RedirectTo string
State string
LoginHint string
}
FederationSsoStartCmd begins an outbound SSO authentication leg (OIDC authorization-code or SAML AuthnRequest). The adapter builds the provider redirect URL (with PKCE / RelayState baked in) and returns it; pkg/api just orchestrates the 302.
type Flow ¶ added in v1.1.0
type Flow struct {
ID string
ProjectID string
Environment string // runtime environment the flow operates in (test/live/…)
Kind FlowKind
Status FlowStatus
Step FlowStep
UserID string // set once the user is created / resolved
ExpiresAt time.Time // whole-flow TTL (30m)
CreatedAt time.Time
UpdatedAt time.Time
// Data fields (stored in the jsonb `data` column).
Locale string
RedirectTo string
Contact FlowContact
Collected FlowCollected
ActiveChallenge *FlowActiveChallenge
ConsentsRequired []FlowConsentRef
ConsentsAccepted []AccountConsentAcceptance
RegistrationMode string // open | request_access | invite_only | closed
PasswordStrategy string // password_first | after_verify
Error *FlowError
// Method is the active authentication method driving the flow
// (password | phone_otp | magic_link). Empty defaults to password for
// signin and email for recovery.
Method string
// AvailableMethods is the set of alternate methods the client may switch to
// mid-flow (surfaced as next_actions). Server-computed at create time.
AvailableMethods []string
}
Flow is the server-side resumable auth flow aggregate. Clients hold only the opaque FlowToken; all state lives here (§4 data model).
type FlowAbandonCmd ¶ added in v1.1.0
FlowAbandonCmd marks a live flow as aborted.
type FlowActiveChallenge ¶ added in v1.1.0
type FlowActiveChallenge struct {
ChallengeID string `json:"challenge_id"`
Channel string `json:"channel"` // email | sms | whatsapp | passkey | oauth
ExpiresAt time.Time `json:"expires_at"`
ResendAt time.Time `json:"resend_at"`
AttemptsLeft int `json:"attempts_left"`
// Code and Token are transient delivery proofs for flow emails. They are
// available only immediately after challenge issue/reissue and are never
// persisted in iam_flows.data.
Code string `json:"-"`
Token string `json:"-"`
// PublicKey carries WebAuthn PublicKeyCredentialRequestOptions for the
// passkey method (so the client can call navigator.credentials.get()).
PublicKey map[string]any `json:"public_key,omitempty"`
// RedirectURL is the provider authorization URL for the oauth method.
RedirectURL string `json:"redirect_url,omitempty"`
// Provider is the oauth provider id, carried so the callback step can
// complete the exchange. Internal only (not surfaced).
Provider string `json:"provider,omitempty"`
}
FlowActiveChallenge is the inline challenge metadata embedded in the flow's data jsonb. The authoritative challenge lives in iam_challenges; this carries only the display / gate fields.
type FlowCollected ¶ added in v1.1.0
type FlowCollected struct {
Name string `json:"name,omitempty"`
HasPassword bool `json:"has_password,omitempty"`
}
FlowCollected holds the non-secret credentials collected so far. Passwords are bcrypt-hashed at the point of consumption; only `has_password` is recorded here (§5 rule 5).
type FlowConsentRef ¶ added in v1.1.0
FlowConsentRef is a consent document reference embedded in the flow data.
type FlowContact ¶ added in v1.1.0
type FlowContact struct {
Email string `json:"email,omitempty"`
Phone string `json:"phone,omitempty"`
}
FlowContact holds the raw contact data (server-only; clients see only masked versions via FlowState).
type FlowCreateCmd ¶ added in v1.1.0
type FlowCreateCmd struct {
ProjectID string
Kind FlowKind
Email string
Password string
Name string
CaptchaToken string
// Method selects the authentication method for the flow
// (password | phone_otp | magic_link). Empty means the kind's default.
Method string
// Phone is the E.164 number for the phone_otp method.
Phone string
// Provider is the OAuth provider id for the oauth signin method.
Provider string
// RedirectTo optionally overrides the cross-device "continue" deep-link base
// for this flow. The notification layer only honours it when its origin
// (scheme+host) matches the project's configured app_base_url; otherwise it
// falls back to app_base_url.
RedirectTo string
// Locale is the requested language for flow emails (verification, continue).
// Empty lets the notification layer fall back to the account/project default.
Locale string
// InviteToken is the raw invitation token (inv_…) to redeem when the project
// registration mode is invite_only. Valid+pending+unexpired (and email-matched
// for email-bound invites) lets the signup proceed and marks the invite
// accepted in the same flow-create transaction.
InviteToken string
// Consents carries signup-time consent acceptances collected by the client
// before the identity proof. The flow records them only after verification.
Consents []AccountConsentAcceptance
}
FlowCreateCmd creates a new server-side resumable auth flow.
type FlowError ¶ added in v1.1.0
FlowError carries the last stable error code visible to the client (§8). The flow stays pending; the client branches on Code.
type FlowGetCmd ¶ added in v1.1.0
FlowGetCmd retrieves a live flow by its opaque token (project-scoped).
type FlowKind ¶ added in v1.1.0
type FlowKind string
FlowKind is the auth flow category, selecting the state machine.
type FlowResendCmd ¶ added in v1.1.0
FlowResendCmd re-issues the active challenge on a live flow.
type FlowState ¶ added in v1.1.0
type FlowState struct {
FlowToken string
Flow *Flow
Session *Session // non-nil only when status=completed
}
FlowState is the full view returned to the caller. It carries the plain-text token (returned from the engine exactly once per rotation, never persisted).
type FlowStatus ¶ added in v1.1.0
type FlowStatus string
FlowStatus is the top-level lifecycle state.
const ( FlowStatusPending FlowStatus = "pending" FlowStatusCompleted FlowStatus = "completed" FlowStatusExpired FlowStatus = "expired" FlowStatusAborted FlowStatus = "aborted" )
type FlowStep ¶ added in v1.1.0
type FlowStep string
FlowStep is the current step the client must action.
const ( FlowStepCollectCredentials FlowStep = "collect_credentials" FlowStepVerifyEmail FlowStep = "verify_email" FlowStepVerifyPhone FlowStep = "verify_phone" FlowStepSetPassword FlowStep = "set_password" FlowStepMFARequired FlowStep = "mfa_required" FlowStepStepUp FlowStep = "step_up" FlowStepAcceptConsents FlowStep = "accept_consents" FlowStepRequestAccess FlowStep = "request_access" FlowStepAwaitingApproval FlowStep = "awaiting_approval" FlowStepCompleted FlowStep = "completed" FlowStepBlocked FlowStep = "blocked" )
type FlowSubmitCmd ¶ added in v1.1.0
type FlowSubmitCmd struct {
ProjectID string
FlowToken string
Action string
Payload map[string]string
}
FlowSubmitCmd submits the current step, advancing the state machine.
type Interaction ¶
type Invite ¶ added in v1.2.0
type Invite struct {
ID string
ProjectID string
Email string // empty when the invite is not email-bound
Status string // pending | accepted | revoked
ExpiresAt time.Time
CreatedAt time.Time
}
Invite is a project invitation issued by an admin. The raw token is never stored; only sha256(token) lives in iam_invites.token_hash. The plain-text token is surfaced to the admin exactly once at creation.
type InviteCreateCmd ¶ added in v1.2.0
type InviteCreateCmd struct {
ProjectID string
Environment string
Email string // optional; empty → open invite, no email sent
ExpiresAt time.Time // zero → default TTL
RedirectTo string // optional base for the email link
}
InviteCreateCmd creates a new invitation. When Email is set the invite is email-bound (signup must use the same email) and a notification is sent. The raw token is returned in the InviteCreated result, never persisted.
type InviteCreated ¶ added in v1.2.0
InviteCreated is the create result carrying the one-time raw token.
type InviteListCmd ¶ added in v1.2.0
InviteListCmd lists invitations for a project.
type InviteRevokeCmd ¶ added in v1.2.0
InviteRevokeCmd revokes a pending invitation.
type MFAEmailEnrollCmd ¶
MFAEmailEnrollCmd enrolls an email factor and issues a delivery challenge.
type MFAPolicySpec ¶ added in v1.3.0
type MFAPolicySpec struct {
RequiredForAdmins *bool `json:"required_for_admins,omitempty"`
AllowedFactors []string `json:"allowed_factors,omitempty"`
RememberDevice *bool `json:"remember_device,omitempty"`
}
MFAPolicySpec mirrors the mfa_policy jsonb doc. Tags match oas MfaPolicy.
func ParseMFAPolicy ¶ added in v1.3.0
func ParseMFAPolicy(raw []byte) (MFAPolicySpec, error)
ParseMFAPolicy strictly decodes the mfa_policy doc.
func (MFAPolicySpec) FactorAllowed ¶ added in v1.3.0
func (c MFAPolicySpec) FactorAllowed(dbFactorType string) bool
FactorAllowed reports whether the given internal/DB factor type may be enrolled under this policy. An unset (nil) or empty AllowedFactors means the policy does not gate enrollment — every implemented factor is allowed (backward compatible: a project with no mfa_policy doc behaves as before).
func (MFAPolicySpec) Validate ¶ added in v1.3.0
func (c MFAPolicySpec) Validate() error
Validate enforces the factor enum, rejects duplicates, and blocks the "MFA required but no factors offered" lockout configuration.
type MFARecoveryVerifyCmd ¶
MFARecoveryVerifyCmd consumes a recovery code to complete an MFA flow.
type MFASmsEnrollCmd ¶
MFASmsEnrollCmd enrolls an SMS factor and issues a delivery challenge.
type MFATotpVerifyCmd ¶
MFATotpVerifyCmd activates a pending TOTP factor by verifying a code.
type MFAWebAuthnEnrollOptionsCmd ¶
MFAWebAuthnEnrollOptionsCmd requests creation options for a new WebAuthn factor enrollment.
type MFAWebAuthnEnrollVerifyCmd ¶
type MFAWebAuthnEnrollVerifyCmd struct {
AccountID string
ChallengeID string
Credential map[string]any
}
MFAWebAuthnEnrollVerifyCmd verifies the attestation produced by the authenticator and activates the WebAuthn factor.
type MachineIDAPIKeyPatchCmd ¶
type MachineIDAPIKeyPatchCmd struct {
ProjectID string
KeyID string
Name string
Scopes []string
Disabled *bool
}
MachineIDAPIKeyPatchCmd updates API-key metadata/scopes.
type MachineIDSecret ¶
MachineIDSecret is the result of creating a service-account client secret. ClientSecret is the plaintext value, returned exactly once at creation.
type MachineIDSecretCmd ¶
type MachineIDSecretCmd struct {
ProjectID string
ServiceAccountID string
Name string
ExpiresAt *time.Time
}
MachineIDSecretCmd mints a new client secret for a service account.
type MachineIDServiceAccountListCmd ¶
MachineIDServiceAccountListCmd queries service accounts in a project.
type MachineIDServiceAccountPage ¶
type MachineIDServiceAccountPage struct {
Items []*ServiceAccount
NextCursor string
HasMore bool
}
MachineIDServiceAccountPage is a cursor-paginated slice of service accounts.
type MachineIDServiceAccountPatchCmd ¶
type MachineIDServiceAccountPatchCmd struct {
ProjectID string
ServiceAccountID string
Scopes []string
Disabled *bool
}
MachineIDServiceAccountPatchCmd updates a service account's scopes/disabled state.
type OAuthProvider ¶
type OAuthSocialCallbackCmd ¶
type OAuthSocialCallbackCmd struct {
ProjectID string
Provider string
Code string
State string
Error string
CodeVerifier string // optional PKCE verifier paired with the StartLogin challenge
RedirectTo string // product URL to bounce the browser back to after minting
}
OAuthSocialCallbackCmd carries the provider callback query parameters back to the adapter, which validates state, exchanges the code, mints a session, and returns the product redirect URL (plus an optional Set-Cookie value in cookie mode).
type OAuthSocialCallbackResult ¶
type OAuthSocialCallbackResult struct {
RedirectURL string
// SetCookie carries the session cookies (access + refresh) to set in cookie
// mode; each entry is a full Set-Cookie header value.
SetCookie []string
}
OAuthSocialCallbackResult is the outcome of a social-login callback: the URL to redirect the browser to and, in cookie mode, the Set-Cookie header value.
type OAuthSocialExchangeCmd ¶
OAuthSocialExchangeCmd exchanges a one-time OAuth authorization code for a session. ProjectID scopes the exchange to the client's project; CodeVerifier carries the optional PKCE verifier.
type OAuthSocialLinkCallbackCmd ¶
type OAuthSocialLinkCallbackCmd struct {
AccountID string
ProjectID string
Provider string
Code string
State string
Error string
CodeVerifier string // optional PKCE verifier paired with the StartLink challenge
RedirectTo string // product URL to bounce the browser back to after linking
}
OAuthSocialLinkCallbackCmd carries the provider callback for an account-link flow; the adapter attaches the identity and returns the product redirect URL.
type OAuthSocialLinkStartCmd ¶
type OAuthSocialLinkStartCmd struct {
AccountID string
ProjectID string
Provider string
RedirectTo string
State string
}
OAuthSocialLinkStartCmd begins linking a provider identity to an already authenticated account. AccountID comes from the principal, never the request.
type OAuthSocialStartCmd ¶
type OAuthSocialStartCmd struct {
ProjectID string
Provider string
RedirectTo string
State string
CodeChallenge string
Prompt string
LoginHint string
}
OAuthSocialStartCmd begins a browser-driven social login: the adapter builds the provider authorize URL (carrying state/PKCE/prompt hints) and returns it for a 302 redirect. RedirectTo is the product URL the provider callback will ultimately bounce the user back to.
type OIDCAuthorizeCmd ¶
type OIDCAuthorizeCmd struct {
ClientID string
ResponseType string
RedirectURI string
Scope string
State string
CodeChallenge string
Nonce string
Prompt string
RequestURI string
}
OIDCAuthorizeCmd is the front-channel /oauth2/authorize request. It is a public operation: the client is identified by ClientID and the request is scoped to that client's project. The adapter validates the client, builds an interaction and returns the redirect URL the user-agent must follow (to the login/consent UI, or back to the client with code/error).
type OIDCBackchannelLogoutCmd ¶
type OIDCBackchannelLogoutCmd struct {
LogoutToken string
}
OIDCBackchannelLogoutCmd carries the back-channel logout token (RFC) the OP receives. It is public; the adapter validates the logout_token and terminates the referenced sessions.
type OIDCConsentCmd ¶
type OIDCConsentCmd struct {
InteractionID string
AccountID string
SessionID string
GrantedScopes []string
Remember bool
}
OIDCConsentCmd records the resource-owner's consent decision for an OIDC authorization interaction. AccountID and SessionID identify the authenticated caller (taken from the principal, never the body) and let the adapter verify the interaction belongs to this session before recording consent. Remember persists the grant so the client is not prompted again.
type OIDCDeviceAuthorization ¶
type OIDCDeviceAuthorization struct {
DeviceCode string
UserCode string
VerificationURI string
VerificationURIComplete string
ExpiresIn int
Interval int
}
OIDCDeviceAuthorization is the device authorization response (RFC 8628).
type OIDCDeviceAuthorizationCmd ¶
OIDCDeviceAuthorizationCmd is the /oauth2/device_authorization request (RFC 8628). It is client-authenticated.
type OIDCDeviceDecisionCmd ¶
type OIDCDeviceDecisionCmd struct {
ProjectID string
UserCode string
AccountID string
SessionID string
}
OIDCDeviceDecisionCmd records a logged-in user's approve/deny decision for a pending device authorization. AccountID/SessionID come from the principal.
type OIDCDevicePending ¶
type OIDCDevicePending struct {
ClientID string
ClientMap map[string]any
Scopes []string
ExpiresAt time.Time
}
OIDCDevicePending is the pending device authorization shown to the user at the verification UI before they approve or deny it.
type OIDCDeviceUserCode ¶
OIDCDeviceUserCode identifies a pending device authorization by its user-facing code, scoped to the project that owns the requesting client.
type OIDCIntrospectCmd ¶
type OIDCIntrospectCmd struct {
ProjectID string // request tenant (authenticated client), NOT the token
Env string
Token string
}
OIDCIntrospectCmd is the /oauth2/introspect request (RFC 7662). It is client-authenticated. The adapter returns the introspection response map, including the mandatory "active" flag.
type OIDCLogoutCmd ¶
OIDCLogoutCmd is the front-channel RP-initiated logout request (/oauth2/logout). It is public. The adapter terminates the session referenced by IDTokenHint and returns the post-logout redirect URL.
type OIDCParCmd ¶
type OIDCParCmd struct {
ResponseType string
ClientID string
RedirectURI string
Scope string
State string
CodeChallenge string
CodeChallengeMethod string
Nonce string
ResponseMode string
Prompt string
LoginHint string
Request string
ClientAssertionType string
ClientAssertion string
}
OIDCParCmd is a pushed authorization request (RFC 9126). It mirrors the authorization request parameters and is client-authenticated. The adapter stores the request and returns a request_uri reference plus its lifetime.
type OIDCParResult ¶
OIDCParResult is the result of a pushed authorization request: an opaque request_uri the client passes to /oauth2/authorize, and its lifetime in seconds.
type OIDCRejectCmd ¶
OIDCRejectCmd cancels an OIDC authorization interaction. It is a public operation (no authenticated caller): Error and ErrorDescription carry the OAuth2 error payload that is propagated back to the client via the redirect.
type OIDCRevokeCmd ¶
type OIDCRevokeCmd struct {
ProjectID string // request tenant (authenticated client), NOT the token
Env string
Token string
TokenTypeHint string
}
OIDCRevokeCmd is the /oauth2/revoke request (RFC 7009). It is client-authenticated. TokenTypeHint is optional.
type OIDCTokenCmd ¶
type OIDCTokenCmd struct {
ProjectID string // request tenant (authenticated client), NOT the token
Env string
GrantType string
Code string
RedirectURI string
CodeVerifier string
RefreshToken string
ClientID string
ClientSecret string
DeviceCode string
}
OIDCTokenCmd is the /oauth2/token request (RFC 6749 + extensions). It is a client-authenticated, public-facing endpoint: the client is identified by ClientID/ClientSecret in the body (or via HTTP basic auth at the adapter). The adapter dispatches on GrantType and returns the raw token response map.
type OperatorAdminToken ¶
type OperatorAdminToken struct {
ID string
ProjectID string
Name string
Scopes []string
CreatedAt time.Time
ExpiresAt time.Time
Revoked bool
}
OperatorAdminToken is a read model describing an admin token minted for a project, returned by the /mgmt admin-tokens listing.
type OperatorAdminTokenCmd ¶
type OperatorAdminTokenCmd struct {
ProjectID string
Name string
Scopes []string
ExpiresAt time.Time
}
OperatorAdminTokenCmd carries the operator request to mint a project-admin token. Empty ExpiresAt means the adapter applies its default TTL.
type OperatorConfigCmd ¶
OperatorConfigCmd carries a free-form declarative project configuration document for the config plan/apply operations. Config is intentionally schemaless at this layer; the adapter validates it.
type OperatorFeaturesCmd ¶
OperatorFeaturesCmd is the operator-scoped feature-flag patch for a project.
type OperatorProjectPatchCmd ¶
type OperatorProjectPatchCmd struct {
ProjectID string
Name string
Slug string
DefaultLocale string
}
OperatorProjectPatchCmd is the operator-scoped partial update of a project. Only the named scalar fields are mutable through /mgmt; empty strings are treated as "no change" by the adapter.
type PasswordPolicySpec ¶ added in v1.3.0
type PasswordPolicySpec struct {
MinLength *int `json:"min_length,omitempty"`
BreachedCheck *bool `json:"breached_check,omitempty"`
History *int `json:"history,omitempty"`
ZxcvbnMinScore *int `json:"zxcvbn_min_score,omitempty"`
}
PasswordPolicySpec mirrors the password_policy jsonb doc. Tags match coreauth_pg.go coreAuthPasswordPolicy and oas PasswordPolicy.
func ParsePasswordPolicy ¶ added in v1.3.0
func ParsePasswordPolicy(raw []byte) (PasswordPolicySpec, error)
ParsePasswordPolicy strictly decodes the password_policy doc.
func (PasswordPolicySpec) Validate ¶ added in v1.3.0
func (c PasswordPolicySpec) Validate() error
Validate enforces password-policy rules fail-closed. breached_check=true and history>0 are rejected because their engines are not implemented — we refuse to let admins enable a no-op security control.
type PlatformCsrfToken ¶
type PlatformCsrfToken struct {
Token string
}
PlatformCsrfToken is the result of issuing a CSRF token for a client.
type Principal ¶
type Principal struct {
Kind PrincipalKind
AccountID string // the user, for PrincipalUser
ProjectID string
Environment string
SessionID string
ClientID string
ConnectionID string // for PrincipalSCIM
Scopes []string
AAL int
}
Principal is the authenticated subject a SecurityHandler resolves from a credential and carries in the request context. Handlers read it instead of re-parsing tokens.
type PrincipalKind ¶
type PrincipalKind string
PrincipalKind is the kind of authenticated caller.
const ( PrincipalUser PrincipalKind = "user" // bearerAuth — end-user access token PrincipalAdmin PrincipalKind = "admin" // adminToken — project admin PrincipalOperator PrincipalKind = "operator" // masterKey PrincipalService PrincipalKind = "service" // serviceToken / API key PrincipalSCIM PrincipalKind = "scim" // scimToken PrincipalClient PrincipalKind = "client" // OAuth client (client_secret_basic) )
type ProfileUpdateCmd ¶
type ProfileUpdateCmd struct {
ProjectID string
AccountID string
Name string
AvatarURL string
Locale string
}
func (ProfileUpdateCmd) Validate ¶
func (c ProfileUpdateCmd) Validate() error
Validate checks profile-update invariants.
type ProjectCmd ¶
func (ProjectCmd) Validate ¶
func (c ProjectCmd) Validate() error
Validate checks project-create invariants.
type ProviderConfigSpec ¶ added in v1.3.0
ProviderConfigSpec validates an email/sms provider's type against the realized registry for the given kind. kind is "email" or "sms"; typ is the provider type string (e.g. "smtp"). Comparison is case-insensitive and the canonical form is lowercase.
func (ProviderConfigSpec) Validate ¶ added in v1.3.0
func (c ProviderConfigSpec) Validate() error
Validate rejects unsupported provider types fail-closed, checking the type against the realized registry for the given kind (email/sms).
type PublicConfig ¶
type PublicConfig struct {
ProjectName string
Methods []string
Providers []OAuthProvider
Locales []string
DefaultLocale string
ConsentDocuments []ConsentDocument
Registration *RegistrationInfo
}
type PublicEvent ¶ added in v1.4.0
type PublicEvent struct {
ID string `json:"id"`
Type string `json:"type"`
Version int `json:"version"`
OccurredAt time.Time `json:"occurred_at"`
ProjectID string `json:"project_id"`
Environment string `json:"environment"`
Data map[string]any `json:"data"`
}
PublicEvent is the versioned, credential-free body delivered to consumers.
type RateLimitRuleSpec ¶ added in v1.3.0
type RateLimitRuleSpec struct {
Endpoint *string `json:"endpoint,omitempty"`
Action *string `json:"action,omitempty"`
Limit *int `json:"limit,omitempty"`
WindowSeconds *int `json:"window_seconds,omitempty"`
By *string `json:"by,omitempty"`
}
RateLimitRuleSpec mirrors one element of rate_limits.rules[]. Tags match oas RateLimitRule.
type RateLimitsSpec ¶ added in v1.3.0
type RateLimitsSpec struct {
Rules []RateLimitRuleSpec `json:"rules,omitempty"`
}
RateLimitsSpec mirrors the rate_limits jsonb doc.
func ParseRateLimits ¶ added in v1.3.0
func ParseRateLimits(raw []byte) (RateLimitsSpec, error)
ParseRateLimits strictly decodes the rate_limits doc, rejecting unknown keys at both the top level and inside each rule.
func (RateLimitsSpec) Validate ¶ added in v1.3.0
func (c RateLimitsSpec) Validate() error
Validate enforces fail-closed rules: by must be "ip", endpoint must be a realized path, action must be empty (unsupported), limit/window positive.
type RegisterCmd ¶
type RegisterCmd struct {
ProjectID string
Environment string
Email string
Phone string
Password string
Name string
Locale string
Consents []AccountConsentAcceptance
// SkipConsentGate bypasses the up-front consent.required enforcement in
// Register. The resumable signup flow sets this because it enforces consent
// at its own accept_consents step (after identity proof), not at user
// creation. The non-flow POST /v1/auth/sign-up path leaves it false.
SkipConsentGate bool
}
func (RegisterCmd) Validate ¶
func (c RegisterCmd) Validate() error
Validate checks sign-up invariants: an identifier is required.
type RegistrationInfo ¶ added in v1.2.0
type RegistrationInfo struct {
Mode string // open | invite_only | request_access | closed
PasswordStrategy string // password_first | after_verify
}
RegistrationInfo is the public view of a project's signup policy, so the app can pre-block /register and show/hide the password field.
type RequestMeta ¶ added in v1.1.0
RequestMeta is the per-request device/network context captured by transport middleware and read by the session-minting path so sessions carry the originating device (for self-managed-session UIs and theft detection).
func RequestMetaFromContext ¶ added in v1.1.0
func RequestMetaFromContext(ctx context.Context) RequestMeta
RequestMetaFromContext returns the request metadata, or the zero value when none was set (non-HTTP callers, internal mints).
type ScimToken ¶
type ScimToken struct {
ID string
ProjectID string
ConnectionID string
Name string
ExpiresAt time.Time
}
ScimToken is a provisioning credential bound to an SSO connection. The secret is returned only at creation time and is never persisted in clear.
type ServiceAccount ¶
type ServiceAccountCmd ¶
type Session ¶
type Session struct {
ID string
AccountID string
ProjectID string
ClientID string
AMR []string
AAL int
AccessToken string
RefreshToken string
ExpiresIn int
CreatedAt time.Time
// Device / management metadata (stored in the iam_sessions data envelope;
// snake-cased so it round-trips with the rename/trust paths). Powers
// self-managed-session UIs.
DeviceName string `json:"device_name,omitempty"`
IP string `json:"ip,omitempty"`
UserAgent string `json:"user_agent,omitempty"`
Fingerprint string `json:"fingerprint,omitempty"`
Trusted bool `json:"trusted,omitempty"`
LastActiveAt time.Time `json:"last_active_at,omitempty"`
// Current is a transient view flag (this session == the caller's) — never
// persisted.
Current bool `json:"-"`
}
type SessionPolicySpec ¶ added in v1.3.0
type SessionPolicySpec struct {
AccessTTL *int `json:"access_ttl,omitempty"`
RefreshTTL *int `json:"refresh_ttl,omitempty"`
IdleTimeout *int `json:"idle_timeout,omitempty"`
AbsoluteTimeout *int `json:"absolute_timeout,omitempty"`
ReuseDetection *bool `json:"reuse_detection,omitempty"`
}
SessionPolicySpec mirrors the session_policy jsonb doc. Tags match oas SessionPolicy. All TTLs are seconds.
func ParseSessionPolicy ¶ added in v1.3.0
func ParseSessionPolicy(raw []byte) (SessionPolicySpec, error)
ParseSessionPolicy strictly decodes the session_policy doc.
func (SessionPolicySpec) Validate ¶ added in v1.3.0
func (c SessionPolicySpec) Validate() error
Validate enforces positivity, sane upper bounds, and cross-field ordering.
type SessionRevokedPayload ¶ added in v1.5.0
type SessionRevokedPayload struct {
SessionID string `json:"session_id"`
UserID string `json:"user_id"`
ProjectID string `json:"project_id"`
}
SessionRevokedPayload is the stable public payload for session.revoked. SessionID is the exact session identifier placed in the JWT sid claim.
type WebAuthnCeremonyData ¶
type WebAuthnCeremonyData struct {
PublicKey map[string]any `json:"publicKey,omitempty"`
Session []byte `json:"session,omitempty"`
AccountID string `json:"accountId,omitempty"`
}
WebAuthnCeremonyData is the persisted state of an in-flight WebAuthn ceremony. It is marshalled into the iam_challenges `data` jsonb column. PublicKey holds the publicKey credential options surfaced to the browser (also mirrored on the returned Challenge), while Session is the opaque marshalled go-webauthn SessionData (challenge bytes, RP id, allowed credentials, user verification) the library requires to verify the matching Finish* response. AccountID scopes a registration ceremony to its owner.
type WebAuthnCredential ¶
type WebAuthnRenameCredentialCmd ¶
WebAuthnRenameCredentialCmd renames a stored passkey/WebAuthn credential. The AccountID scopes the operation to the caller, preventing cross-account access.
type WebAuthnStoredCredential ¶
type WebAuthnStoredCredential struct {
Credential WebAuthnCredential `json:"credential"`
Library []byte `json:"library,omitempty"`
}
WebAuthnStoredCredential is the persisted form of a registered passkey. The public, display-facing fields live on Credential; Library is the opaque marshalled go-webauthn Credential (id, COSE public key, sign count, AAGUID, flags, attestation) the library needs to verify subsequent assertions. It is marshalled into the iam_webauthn_credentials `data` jsonb column.
type Webhook ¶ added in v1.4.0
type Webhook struct {
ID string `json:"id"`
ProjectID string `json:"project_id"`
Environment string `json:"environment"`
URL string `json:"url"`
Events []string `json:"events"`
Description string `json:"description,omitempty"`
Enabled bool `json:"enabled"`
SigningSecret string `json:"-"`
PreviousSigningSecret string `json:"-"`
PreviousSecretValidUntil time.Time `json:"-"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type WebhookCreateCmd ¶ added in v1.4.0
type WebhookDelivery ¶ added in v1.4.0
type WebhookDelivery struct {
ID string `json:"id"`
ProjectID string `json:"project_id"`
Environment string `json:"environment"`
WebhookID string `json:"webhook_id"`
EventID string `json:"event_id"`
EventType string `json:"event_type"`
Status string `json:"status"`
AttemptCount int `json:"attempt_count"`
NextAttemptAt *time.Time `json:"next_attempt_at,omitempty"`
LastAttemptAt *time.Time `json:"last_attempt_at,omitempty"`
DeliveredAt *time.Time `json:"delivered_at,omitempty"`
ResponseStatus *int `json:"response_status,omitempty"`
ResponseBody string `json:"response_body,omitempty"`
LastError string `json:"last_error,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type WebhookDeliveryListCmd ¶ added in v1.4.0
type WebhookEventListCmd ¶ added in v1.4.0
type WebhookEventPage ¶ added in v1.4.0
type WebhookEventPage struct {
Data []PublicEvent
NextCursor string
HasMore bool
}