domain

package
v1.7.0 Latest Latest
Warning

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

Go to latest
Published: Sep 17, 2026 License: MIT Imports: 11 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package 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

View Source
const (
	ApplyActionCreate    = "create"
	ApplyActionUpdate    = "update"
	ApplyActionDelete    = "delete"
	ApplyActionUnchanged = "unchanged"
)

Actions a desired-state apply reports per object. They describe what the apply did, or — under dry-run — what it would do.

View Source
const (
	PublicMetadataMaxEntries     = 100
	PublicMetadataMaxValueLength = 4096
)

PublicMetadataMaxEntries / PublicMetadataMaxValueLength bound the document: it is served on every unauthenticated bootstrap call, so its size is not the operator's to grow without limit.

View Source
const (
	ConfigDocAuth           = "auth"
	ConfigDocPasswordPolicy = "password_policy"
	ConfigDocSessionPolicy  = "session_policy"
	ConfigDocMFAPolicy      = "mfa_policy"
	ConfigDocRateLimits     = "rate_limits"
)

Names of the project-config documents, identical to the iam_config `key` column and to the keys of the bulk config object.

View Source
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).

View Source
const (
	OIDCStageLogin   = "login"
	OIDCStageConsent = "consent"
)

Stages of an authorization interaction, as reported to the hosted UI.

View Source
const (
	WebhookEventSessionRevoked    = "session.revoked"
	WebhookEventUserBanned        = "user.banned"
	WebhookEventUserDeleted       = "user.deleted"
	WebhookEventDeletionScheduled = "user.deletion_scheduled"
	WebhookEventDeletionCancelled = "user.deletion_cancelled"
	WebhookEventEmailChanged      = "email.changed"
)

Variables

View Source
var (
	// 401 — authentication.
	ErrInvalidCredentials    = newErr(http.StatusUnauthorized, "invalid_credentials", "Invalid credentials.")
	ErrUnauthorized          = newErr(http.StatusUnauthorized, "unauthorized", "Authentication required.")
	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.")
	// RFC 6749 §4.1.2.1: when the client is unknown/disabled or the redirect_uri
	// is not one the client registered, the authorization server MUST NOT
	// redirect the user-agent — the target cannot be trusted — and reports the
	// error directly instead.
	// RFC 6749 §5.2 invalid_grant: the presented authorization grant is invalid,
	// expired, revoked, or does not match the request it was issued for — which
	// is also how a failed PKCE verification is reported.
	ErrInvalidGrant = newErr(http.StatusBadRequest, "invalid_grant", "The authorization grant is invalid.")
	// RFC 9126 §4 invalid_request_uri: the pushed request is unknown, expired or
	// already redeemed. It cannot be reported on a redirect, because without the
	// pushed request there is no validated redirect_uri to report it on.
	ErrInvalidRequestURI  = newErr(http.StatusBadRequest, "invalid_request_uri", "The request_uri is unknown or expired.")
	ErrInvalidClient      = newErr(http.StatusBadRequest, "invalid_client", "Unknown or disabled OAuth client.")
	ErrInvalidRedirectURI = newErr(http.StatusBadRequest, "invalid_redirect_uri",
		"The redirect_uri is not registered for this client.")

	// 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.")
	ErrServiceUnavailable = newErr(http.StatusServiceUnavailable, "service_unavailable", "Service unavailable.")
	ErrInternal           = newErr(http.StatusInternalServerError, "internal_error", "Internal error.")
)

The complete catalog of domain errors. Branch with errors.Is.

View Source
var BuiltinEmailTemplates = []BuiltinEmailTemplate{
	{Key: "account_deletion", Name: "Account deletion", Locales: map[string]BuiltinEmailCopy{
		"en": {Subject: "Account deletion", Text: "{{.summary}}\n{{if .link}}Manage your account: {{.link}}{{end}}"},
		"ru": {Subject: "Удаление аккаунта", Text: "{{.summary}}\n{{if .link}}Управление аккаунтом: {{.link}}{{end}}"},
	}},
	{
		Key:  "security_status",
		Name: "Account protection status",
		Locales: map[string]BuiltinEmailCopy{
			"en": {
				Subject: "Account protection status",
				Text:    "Account security status: {{.summary}}. If you did not request this, contact support.",
			},
			"ru": {
				Subject: "Защита аккаунта",
				Text: "Состояние безопасности аккаунта: {{.summary}}. Если вы не отправляли это" +
					"т запрос, свяжитесь с поддержкой.",
			},
		},
	},
	{
		Key:  "security_alert",
		Name: "Account security alert",
		Locales: map[string]BuiltinEmailCopy{
			"en": {
				Subject: "Account security activity",
				Text: "An account security event was recorded: {{.summary}}\nReview activity: {{" +
					".link}}\nOpening this link does not change your account.",
				HTML: `<p>Account security activity: {{.summary}}</p>
<p><a href="{{.link}}">Review activity</a></p>
<p>Opening this link does not change your account.</p>`,
			},
			"ru": {
				Subject: "Безопасность аккаунта",
				Text: "Зафиксировано событие безопасности: {{.summary}}\nПроверить активность: {" +
					"{.link}}\nОткрытие ссылки не изменяет аккаунт.",
				HTML: `<p>Событие безопасности: {{.summary}}</p>
<p><a href="{{.link}}">Проверить активность</a></p>
<p>Открытие ссылки не изменяет аккаунт.</p>`,
			},
		},
	},
	{
		Key:  "security_code",
		Name: "Security verification code",
		Locales: map[string]BuiltinEmailCopy{
			"en": {
				Subject: "Confirm your security request",
				Text:    "Your verification code is {{.code}}. It expires in 10 minutes. Do not share it.",
			},
			"ru": {
				Subject: "Подтвердите запрос безопасности",
				Text:    "Код подтверждения: {{.code}}. Действует 10 минут. Никому не сообщайте его.",
			},
		},
	},
	{
		Key:  "security_recovery",
		Name: "Account recovery status",
		Locales: map[string]BuiltinEmailCopy{
			"en": {
				Subject: "Your account recovery request",
				Text:    "Recovery status: {{.summary}}\nContinue: {{.link}}\nThis link does not sign you in.",
			},
			"ru": {
				Subject: "Восстановление аккаунта",
				Text: "Статус обращения: {{.summary}}\nПродолжить: {{.link}}\nЭта ссылка не выпол" +
					"няет вход в аккаунт.",
			},
		},
	},
	{
		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>`,
			},
		},
	},
	{
		Key:  "access_request_approved",
		Name: "Access request approved",
		Locales: map[string]BuiltinEmailCopy{
			"en": {
				Subject: "Your access request was approved",
				Text: "Good news — your access request was approved." +
					"{{with .link}}\nAccept your access and finish signing up: {{.}}{{end}}" +
					"{{with .invite_token}}\nAlternatively, use code {{.}} during sign-up.{{end}}",
				HTML: `<p>Good news — your access request was approved.</p>
{{with .link}}<p><a href="{{.}}">Accept your access and finish signing up</a></p>{{end}}
{{with .invite_token}}<p>Alternatively, use code <strong>{{.}}</strong> during sign-up.</p>{{end}}`,
			},
			"ru": {
				Subject: "Ваша заявка на доступ одобрена",
				Text: "Хорошая новость — ваша заявка на доступ одобрена." +
					"{{with .link}}\nПримите приглашение и завершите регистрацию: {{.}}{{end}}" +
					"{{with .invite_token}}\nИли используйте код {{.}} при регистрации.{{end}}",
				HTML: `<p>Хорошая новость — ваша заявка на доступ одобрена.</p>
{{with .link}}<p><a href="{{.}}">Примите приглашение и завершите регистрацию</a></p>{{end}}
{{with .invite_token}}<p>Или используйте код <strong>{{.}}</strong> при регистрации.</p>{{end}}`,
			},
		},
	},
	{
		Key:  "access_request_denied",
		Name: "Access request declined",
		Locales: map[string]BuiltinEmailCopy{
			"en": {
				Subject: "Your access request was declined",
				Text:    "Your access request was declined.{{with .reason}}\nReason: {{.}}{{end}}",
				HTML: `<p>Your access request was declined.</p>
{{with .reason}}<p>Reason: {{.}}</p>{{end}}`,
			},
			"ru": {
				Subject: "Ваша заявка на доступ отклонена",
				Text:    "Ваша заявка на доступ отклонена.{{with .reason}}\nПричина: {{.}}{{end}}",
				HTML: `<p>Ваша заявка на доступ отклонена.</p>
{{with .reason}}<p>Причина: {{.}}</p>{{end}}`,
			},
		},
	},
}

BuiltinEmailTemplates is the canonical catalog, 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.

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
var RiskActions = newStringSet("require_step_up", "block", "notify", "allow")

RiskActions is the canonical set of outcomes a rule may ask for.

View Source
var RiskSignals = newStringSet("new_device", "new_ip", "recent_failures")

RiskSignals is the canonical set of conditions a risk rule may fire on.

It is a closed set rather than an expression language on purpose. A free-form condition needs a parser, an evaluator and a way to tell an administrator why their expression did nothing — and until all three exist, every rule written is a control that silently never fires. A named signal either evaluates or is rejected at write time.

To add one: implement its detection in the evaluator, then add it here.

  • new_device — no earlier session of this user carried this device fingerprint. Requires the client to send a device fingerprint; without one the signal never fires rather than firing on everyone.
  • new_ip — no earlier session of this user came from this address.
  • recent_failures — the password was wrong at least once since the last successful sign-in.
View Source
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.

View Source
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.

View Source
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.

SupportedWebhookEvents is the deliberately small public event catalog. 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 ClockOffset added in v1.6.0

func ClockOffset(ctx context.Context) time.Duration

ClockOffset is how far ahead this request's clock runs. Zero for every request that did not come from a test-mode environment, which is all of them in live.

func ConfigDocuments added in v1.6.0

func ConfigDocuments() []string

ConfigDocuments returns the ordered set of documents the bulk get/apply surface covers. Order is fixed so a change set reads the same way every time.

func FirstNonEmptyLocale added in v1.1.3

func FirstNonEmptyLocale(candidates ...string) string

FirstNonEmptyLocale returns the first non-empty locale from candidates, or "en".

func MFAPolicyFactorName added in v1.3.0

func MFAPolicyFactorName(dbFactorType string) string

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

func NormalizeOrigin(raw string) string

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

func NormalizeOrigins(in []string) []string

NormalizeOrigins validates, canonicalises, and de-duplicates a list of origins, dropping invalid entries and capping the count.

func NormalizeRoles added in v1.6.0

func NormalizeRoles(roles []string) ([]string, error)

NormalizeRoles validates a desired-state role list and returns it sorted and de-duplicated, so the same set always produces the same `groups` claim.

func Now added in v1.6.0

func Now(ctx context.Context) time.Time

Now is the current time as this request sees it.

func ValidateAbsoluteHTTPURL added in v1.6.0

func ValidateAbsoluteHTTPURL(field, s string) error

ValidateAbsoluteHTTPURL ensures s is an absolute http(s) URL. It is the single absolute-URL validator in the codebase: config docs (app_base_url, consent document URLs) and the service-level public base URL all go through it.

func ValidateConfigDocument added in v1.6.0

func ValidateConfigDocument(name string, raw []byte) error

ValidateConfigDocument runs the strict parse+validate for one document by name. It is the same code path each single-document endpoint uses, so a bulk apply cannot be a way around the per-document rules (including unknown-key rejection). An unknown document name is itself a validation failure.

func ValidateEmail

func ValidateEmail(email string) error

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

func ValidatePhone(phone string) error

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 ValidateSessionPolicyClaims added in v1.6.5

func ValidateSessionPolicyClaims(claims []string) error

ValidateSessionPolicyClaims rejects unknown access_token_claims values.

func WithClockOffset added in v1.6.0

func WithClockOffset(ctx context.Context, offset time.Duration) context.Context

WithClockOffset returns a context whose current time runs `offset` ahead.

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 APIKey

type APIKey struct {
	ID        string
	ProjectID string
	Name      string
	Scopes    []string
	Prefix    string
	Disabled  bool
}

type APIKeyCmd

type APIKeyCmd struct {
	ProjectID string
	Name      string
	Scopes    []string
}

type Account

type Account struct {
	Deletion      *AccountDeletion `json:"deletion,omitempty"`
	ID            string
	ProjectID     string
	Kind          string // human | guest | system
	Status        string // active | suspended | banned | deactivated
	PrimaryEmail  string
	EmailVerified bool
	PrimaryPhone  string
	PhoneVerified bool
	Name          string
	Locale        string
	// InviteCap is the per-user member-invite cap override (nil = the project
	// member_invites default applies; 0 = the right is revoked). Lives in the
	// account envelope under the lowercase tag.
	InviteCap *int `json:"invite_cap,omitempty"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

type AccountAcceptConsentsCmd

type AccountAcceptConsentsCmd struct {
	AccountID string
	Accept    []AccountConsentAcceptance
}

AccountAcceptConsentsCmd accepts one or more consent documents.

type AccountActivityCmd

type AccountActivityCmd struct {
	AccountID string
	Type      string
	Cursor    string
	Limit     int
}

AccountActivityCmd queries the account activity log.

type AccountActivityEvent

type AccountActivityEvent struct {
	ID     string
	Type   string
	IP     string
	Device string
	At     time.Time
}

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

type AccountConsentAcceptance struct {
	Key     string `json:"key"`
	Version string `json:"version"`
}

AccountConsentAcceptance records acceptance of one consent document.

type AccountDeletion added in v1.7.0

type AccountDeletion struct {
	OK          bool       `json:"ok"`
	RequestID   string     `json:"request_id,omitempty"`
	Status      string     `json:"status"`
	RequestedAt *time.Time `json:"requested_at,omitempty"`
	DeleteAt    *time.Time `json:"delete_at,omitempty"`
	CancelledAt *time.Time `json:"cancelled_at,omitempty"`
	GraceDays   int        `json:"grace_days"`
}

AccountDeletion is independent of Account.Status: pending accounts stay active.

type AccountDeletionEvent added in v1.7.0

type AccountDeletionEvent struct {
	ActorID   string    `json:"actor_id,omitempty"`
	Reason    string    `json:"reason,omitempty"`
	Type      string    `json:"type"`
	At        time.Time `json:"at"`
	RequestID string    `json:"request_id"`
}

type AccountDeletionHistory added in v1.7.0

type AccountDeletionHistory struct {
	Deletion AccountDeletion        `json:"deletion"`
	Events   []AccountDeletionEvent `json:"events"`
}

type AccountDeletionInput added in v1.7.0

type AccountDeletionInput struct {
	Password   string `json:"password,omitempty"`
	ProofToken string `json:"proof_token,omitempty"`
	Reason     string `json:"reason,omitempty"`
}

type AccountDeletionPolicy added in v1.7.0

type AccountDeletionPolicy struct {
	GraceDays int `json:"grace_days"`
}

type AccountExportJob

type AccountExportJob struct {
	JobID       string
	Status      string
	DownloadURL string
}

AccountExportJob describes a pending or finished data-export job.

type AccountMergeConfirmCmd

type AccountMergeConfirmCmd struct {
	AccountID   string
	ChallengeID string
	Code        string
}

AccountMergeConfirmCmd confirms a pending identity merge with a challenge code.

type AccountMergeStartCmd

type AccountMergeStartCmd struct {
	AccountID        string
	TargetIdentifier string
}

AccountMergeStartCmd begins linking/merging another identity into the account.

type AccountRenameSessionCmd

type AccountRenameSessionCmd struct {
	AccountID  string
	SessionID  string
	DeviceName string
}

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

type AccountTrustSessionCmd struct {
	AccountID       string
	SessionID       string
	DurationSeconds int
}

AccountTrustSessionCmd marks a session as trusted for a duration.

type AdminAPIKeyCmd

type AdminAPIKeyCmd struct {
	ProjectID string
	Name      string
	Scopes    []string
	ExpiresAt time.Time
}

AdminAPIKeyCmd creates a project API key.

type AdminAPIKeySecret

type AdminAPIKeySecret struct {
	Key    *APIKey
	Secret string
}

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 AdminAccountDeletionCancelInput added in v1.7.0

type AdminAccountDeletionCancelInput struct {
	RequestID string `json:"request_id"`
	Reason    string `json:"reason"`
}

type AdminAppClientChange added in v1.6.0

type AdminAppClientChange struct {
	ID     string
	Action string
	Before *AppClient
	After  *AppClient
}

AdminAppClientChange is what an apply did, or would do, to one app client. Before is nil for a create, After is nil for a delete.

type AdminAppClientDesired added in v1.6.0

type AdminAppClientDesired struct {
	ID                     string
	Name                   string
	Type                   string
	RedirectURIs           []string
	AllowedOrigins         []string
	Disabled               bool
	PostLogoutRedirectURIs []string
	BackchannelLogoutURI   string
	Scopes                 []string
	JWKS                   string
	JWKSURI                string
	TokenProfileID         string
}

AdminAppClientDesired is one entry of a desired-state client list. An ID that already exists is updated in place; an unknown or empty ID is created (a supplied ID is honored so an external applicator can name its clients deterministically instead of discovering server-generated ids).

type AdminAppsApplyCmd added in v1.6.0

type AdminAppsApplyCmd struct {
	ProjectID   string
	Environment string
	Clients     []AdminAppClientDesired
	// Prune deletes clients that exist but are absent from Clients. Off by
	// default so a partial list cannot destroy clients it does not know about.
	Prune bool
	// DryRun computes the change set and writes nothing.
	DryRun bool
}

AdminAppsApplyCmd reconciles a project environment's app clients against a desired-state list.

type AdminAppsApplyResult added in v1.6.0

type AdminAppsApplyResult struct {
	DryRun  bool
	Prune   bool
	Changes []AdminAppClientChange
}

AdminAppsApplyResult is the outcome of a desired-state client apply.

type AdminBlock added in v1.6.0

type AdminBlock struct {
	ID        string
	Type      string
	Value     string
	Reason    string
	ExpiresAt time.Time
}

AdminBlock is a manual rate-limit block on a subject (ip / email / phone / asn). A request whose subject matches an unexpired block is refused.

type AdminConfigApplyCmd added in v1.6.0

type AdminConfigApplyCmd struct {
	ProjectID   string
	Environment string
	Docs        AdminConfigBundle
	// DryRun computes the change set and writes nothing (the `plan` half).
	DryRun bool
}

AdminConfigApplyCmd applies a whole bundle of configuration documents in one transaction. Documents absent from Docs are left untouched — a partial bundle must not silently reset the documents it does not mention.

type AdminConfigApplyResult added in v1.6.0

type AdminConfigApplyResult struct {
	DryRun  bool
	Changes []AdminConfigDocChange
	Config  AdminConfigBundle
}

AdminConfigApplyResult is the outcome of a bulk config apply: the per-document change set plus the resulting (or would-be) state of every document.

type AdminConfigBundle added in v1.6.0

type AdminConfigBundle map[string]AdminConfigDoc

AdminConfigBundle is every project-config document in one value, keyed by document name (domain.ConfigDoc*). A missing key means "not present in this request"; an empty doc means "the document is unset".

type AdminConfigDoc

type AdminConfigDoc = map[string]jx.Raw

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 AdminConfigDocChange added in v1.6.0

type AdminConfigDocChange struct {
	Document string
	Action   string
	Before   AdminConfigDoc
	After    AdminConfigDoc
}

AdminConfigDocChange is what an apply did, or would do, to one document. Before is nil when the document did not exist.

type AdminConfigGetCmd

type AdminConfigGetCmd struct {
	ProjectID   string
	Environment string
}

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

type AdminDomainCmd struct {
	ProjectID    string
	Domain       string
	ConnectionID string
}

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

type AdminFeaturesUpdateCmd struct {
	ProjectID   string
	Environment string
	Features    map[string]bool
}

AdminFeaturesUpdateCmd toggles project feature flags.

type AdminHook added in v1.6.0

type AdminHook struct {
	ID            string
	Type          string
	URL           string
	TimeoutMs     int
	Enabled       bool
	FailOpen      bool
	SigningSecret string
}

AdminHook is a blocking auth hook: a signed HTTP callback invoked at an auth decision point (before_sign_in / before_token_issue / before_user_create). A non-2xx reply denies the action unless FailOpen is set. SigningSecret is returned only once, on create.

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

type AdminImpersonation struct {
	URL       string
	ExpiresAt time.Time
}

AdminImpersonation is the result of an impersonation request.

type AdminJWKSRotateCmd

type AdminJWKSRotateCmd struct {
	ProjectID   string
	Environment string
	Activate    bool
}

AdminJWKSRotateCmd rotates the signing key set, optionally activating the new key immediately.

type AdminJob added in v1.6.0

type AdminJob struct {
	ID     string
	Type   string
	Status string
	// Progress and Result mirror the job's data envelope.
	Progress int
	Result   map[string]any
	Error    string
}

AdminJob is an async background job (bulk import, audit/data export) an admin enqueues and polls.

type AdminOAuthProvider added in v1.6.0

type AdminOAuthProvider struct {
	ID           string
	Provider     string
	ClientID     string
	ClientSecret string
	Scopes       []string
	Enabled      bool
}

AdminOAuthProvider is a configured OAuth social login provider (google, github, …). ClientSecret is write-only: it is accepted on create/update but never returned on read (empty).

type AdminProvider

type AdminProvider struct {
	ID      string
	Type    string
	Config  map[string]jx.Raw
	Enabled bool
}

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

type AdminProviderDeleteCmd struct {
	ProjectID   string
	Environment string
	ID          string
}

AdminProviderDeleteCmd removes a notification provider.

type AdminRiskRule added in v1.6.0

type AdminRiskRule struct {
	ID   string
	Name string
	// Signal names the condition the rule fires on, from RiskSignals. Condition
	// is its released spelling and is accepted as an alias on the way in, so a
	// rule written against the older shape keeps working.
	Signal    string
	Condition string
	Action    string
	Enabled   bool
}

AdminRiskRule is a declarative risk rule an admin defines. Condition is a free-form expression evaluated by the risk engine; Action is what to do when it matches (require_step_up / block / notify / allow).

func (AdminRiskRule) EffectiveSignal added in v1.6.0

func (r AdminRiskRule) EffectiveSignal() string

EffectiveSignal is the signal this rule fires on, preferring the current field and falling back to the released one.

func (AdminRiskRule) Validate added in v1.6.0

func (r AdminRiskRule) Validate() error

Validate rejects a rule that could never fire: an unknown signal or an unknown action. Storing one would be a control an administrator believes is in place and is not.

type AdminSecret

type AdminSecret struct {
	SecretID     string
	ClientID     string
	ClientSecret string
}

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

type AdminSigningKey struct {
	Kid       string
	Alg       string
	Use       string
	Status    string
	CreatedAt time.Time
}

AdminSigningKey is a JWKS signing key in its administrative form.

type AdminTemplatePreview

type AdminTemplatePreview struct {
	Subject string
	HTML    string
	Text    string
}

AdminTemplatePreview is a rendered email template.

type AdminTemplatePreviewCmd

type AdminTemplatePreviewCmd struct {
	ProjectID    string
	Environment  string
	TemplateID   string
	Locale       string
	Data         map[string]jx.Raw
	DraftSubject string
	DraftText    string
	DraftHTML    string
}

AdminTemplatePreviewCmd renders an email template with sample data. The Draft* fields render an unsaved editor body instead of the stored template (live preview); empty draft fields fall back to the stored part.

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 AdminUserRolesCmd added in v1.6.0

type AdminUserRolesCmd struct {
	ProjectID   string
	Environment string
	UserID      string
}

AdminUserRolesCmd addresses one user's role assignments inside a project environment.

type AdminUserRolesSetCmd added in v1.6.0

type AdminUserRolesSetCmd struct {
	ProjectID   string
	Environment string
	UserID      string
	Roles       []string
}

AdminUserRolesSetCmd replaces a user's roles with exactly Roles. Assignments are a desired-state list: whatever is not in it is removed.

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
	// InviteCap patches the per-user member-invite cap override. InviteCapSet
	// distinguishes "absent" (keep) from "explicit null" (clear the override).
	InviteCap    *int
	InviteCapSet bool
}

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
	// Disabled turns the client off without deleting it: the authorization
	// endpoint refuses it exactly like an unknown client_id, so an integration
	// can be suspended and restored without re-issuing its registration.
	Disabled bool
	// PostLogoutRedirectURIs are the targets an RP-initiated logout may send the
	// browser to. Matched exactly, like RedirectURIs: honoring an unregistered
	// value would make logout an open redirect.
	PostLogoutRedirectURIs []string
	// BackchannelLogoutURI receives a signed logout_token when a session this
	// client holds a grant on ends (OpenID Connect Back-Channel Logout 1.0).
	// Empty means the client is not notified.
	BackchannelLogoutURI string
	// Scopes the client may request. Empty means no restriction — a project that
	// has not thought about it is not silently narrowed.
	Scopes []string
	// JWKS / JWKSURI are the public keys the CLIENT signs with: private_key_jwt
	// assertions and request objects are verified against them. Inline JWKS wins
	// when both are set — it needs no network and cannot be made unavailable by
	// the client's own infrastructure.
	JWKS    string
	JWKSURI string
	// RegistrationTokenHash is the sha256 of the client's registration access
	// token (RFC 7592). Only the digest is kept: the token itself is shown once,
	// at registration.
	RegistrationTokenHash string
	// TokenEndpointAuthMethod records how the client authenticates, as registered.
	TokenEndpointAuthMethod string
	// TokenProfileID binds the client to a token profile: what `aud` its tokens
	// carry, how long they live, and a fixed set of extra claims. Empty means the
	// project's defaults.
	TokenProfileID string
}

type AppClientCmd

type AppClientCmd struct {
	ProjectID              string
	Environment            string
	Name                   string
	Type                   string
	RedirectURIs           []string
	AllowedOrigins         []string
	Disabled               bool
	PostLogoutRedirectURIs []string
	BackchannelLogoutURI   string
	Scopes                 []string
	JWKS                   string
	JWKSURI                string
	TokenProfileID         string
}

type AuditExportCmd added in v1.6.0

type AuditExportCmd struct {
	ProjectID string
	From      time.Time
	To        time.Time
	Format    string
}

AuditExportCmd requests an audit-log export job over an optional time window.

type AuditLogEntry added in v1.6.0

type AuditLogEntry struct {
	ID       string
	Type     string
	ActorID  string
	TargetID string
	At       time.Time
	Data     map[string]jx.Raw
}

AuditLogEntry is one recorded privileged action (an admin/operator/service principal mutating a tenant's data).

type AuditLogListCmd added in v1.6.0

type AuditLogListCmd struct {
	ProjectID string
	ActorID   string
	TargetID  string
	Type      string
	Cursor    string
	Limit     int
}

AuditLogListCmd filters and paginates the audit log. Empty filter fields are ignored. Cursor is an opaque keyset token from a prior page.

type AuthConfigSpec added in v1.3.0

type AuthConfigSpec struct {
	Methods          []string                 `json:"methods,omitempty"`
	Registration     *AuthRegistrationConfig  `json:"registration,omitempty"`
	MemberInvites    *AuthMemberInvitesConfig `json:"member_invites,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 AuthMemberInvitesConfig added in v1.6.3

type AuthMemberInvitesConfig struct {
	Enabled    *bool `json:"enabled,omitempty"`
	DefaultCap *int  `json:"default_cap,omitempty"`
}

AuthMemberInvitesConfig mirrors the nested `member_invites` object in the auth doc: the project-wide default for user-driven invitations. Enabled gates the right entirely; DefaultCap bounds one user's simultaneously active invitations (pending-unexpired + accepted). Per-user invite_cap overrides in the user envelope win; 0 there revokes the right.

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

type BuiltinEmailCopy struct {
	Subject string
	Text    string
	HTML    string
}

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 customized 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 catalog entry for key, or nil when key is not a known built-in template.

func (*BuiltinEmailTemplate) Copy added in v1.1.3

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

type ConnectionCmd struct {
	ProjectID string
	Type      string
	Name      string
	Domains   []string
}

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 ConsentDocument struct {
	Key      string
	Version  string
	Title    string
	Body     string
	Locale   string
	Required bool
	URL      string
}

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
	Locale    string
}

CoreAuthAccessRequest is a request for access to a project that gates self-service sign-up behind approval. Locale is the requester's preferred language (from submission), reused for the decision emails.

type CoreAuthAccessRequestCmd

type CoreAuthAccessRequestCmd struct {
	ProjectID    string
	Email        string
	Reason       string
	Locale       string
	CaptchaToken string
}

CoreAuthAccessRequestCmd creates an access request.

type CoreAuthCaptchaVerifyResult

type CoreAuthCaptchaVerifyResult struct {
	Valid bool
	Score float64
}

CoreAuthCaptchaVerifyResult is the outcome of verifying a CAPTCHA token with the configured provider.

type CoreAuthEmailVerificationCallbackCmd

type CoreAuthEmailVerificationCallbackCmd struct {
	Token      string
	RedirectTo string
}

CoreAuthEmailVerificationCallbackCmd consumes an opaque email-verification link token and resolves where to send the browser next.

type CoreAuthEmailVerificationCallbackResult

type CoreAuthEmailVerificationCallbackResult struct {
	RedirectURL string
	SetCookie   string
}

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

type CoreAuthPasswordCheckResult struct {
	Valid      bool
	Score      int
	Violations []string
}

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
	// PriorFailures is how many consecutive wrong passwords preceded this
	// success. The counter is reset by the success itself, so it is carried out
	// here for risk evaluation, which is the only thing that still cares.
	PriorFailures int
}

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

type CoreAuthPasswordVerifyResult struct {
	OK  bool
	AAL int
	AMR []string
}

CoreAuthPasswordVerifyResult is the outcome of re-asserting the current account's password (e.g. for a sudo/step-up gate).

type CoreAuthRevokeCmd

type CoreAuthRevokeCmd struct {
	Token     string
	SessionID string
	Reason    string
}

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

type CoreAuthStepUpResult struct {
	Satisfied bool
	Challenge *Challenge
}

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

type CoreAuthTokenIntrospection struct {
	Active bool
	Claims map[string]any
}

CoreAuthTokenIntrospection is the result of introspecting a token.

type CoreAuthTokenVerification

type CoreAuthTokenVerification struct {
	Valid  bool
	Claims map[string]any
	Error  string
}

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 Domain

type Domain struct {
	ID           string
	ProjectID    string
	Domain       string
	Status       string // pending | verified
	ConnectionID string
}

type Environment

type Environment struct {
	ProjectID string
	Name      string // live | test | staging
	Issuer    string
	CreatedAt time.Time
}

type EnvironmentCmd

type EnvironmentCmd struct {
	ProjectID string
	Name      string
}

type Error

type Error struct {
	Code    string
	Message string
	Status  int
	Details map[string]any
}

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) Error

func (e *Error) Error() string

func (*Error) Is

func (e *Error) Is(target error) bool

Is matches by Code so wrapped/rebuilt errors still compare equal to the sentinel of the same code.

func (*Error) WithDetails

func (e *Error) WithDetails(d map[string]any) *Error

WithDetails returns a copy carrying structured context.

func (*Error) WithMessage

func (e *Error) WithMessage(msg string) *Error

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-serialized 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

type FeaturesSpec map[string]bool

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

type FederationConnectionUpdateCmd struct {
	ProjectID string
	ID        string
	Patch     map[string]any
}

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"`
	// DiscoveryURL is where the provider publishes its metadata. When set it is
	// fetched at configuration time to fill AuthURL/TokenURL/JWKSURL; when unset
	// the well-known path under Issuer is used instead.
	DiscoveryURL string   `json:"discovery_url,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

type FederationSamlAcsCmd struct {
	ConnectionID string
	SAMLResponse string
	RelayState   string
}

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"`
	// IDPMetadataURL is where the IdP publishes that document. It is fetched once,
	// at configuration time, into IDPMetadataXML — an IdP's availability does not
	// belong in the path of every sign-in.
	IDPMetadataURL string `json:"idp_metadata_url,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

type FederationScimListQuery struct {
	ConnectionID string
	Filter       string
	StartIndex   int
	Count        int
}

FederationScimListQuery is a paginated SCIM list request.

type FederationScimPatchCmd

type FederationScimPatchCmd struct {
	ConnectionID string
	ResourceID   string
	Patch        map[string]any
}

FederationScimPatchCmd applies a SCIM PATCH operation set to a resource.

type FederationScimResource

type FederationScimResource struct {
	Attributes map[string]any
}

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

type FederationSsoCallbackCmd struct {
	ConnectionID string
	Code         string
	State        string
}

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
	// CookieMode records that a browser is driving this flow. When it completes,
	// the minted session is handed back as HttpOnly cookies instead of being left
	// in the response body for the page to hold — which is what makes a browser
	// session (and therefore SSO across relying parties) possible at all. It is
	// declared once at create time and survives resume, because the single
	// round-trip case completes before any cookie could have been sent back.
	CookieMode bool
}

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

type FlowAbandonCmd struct {
	ProjectID string
	FlowToken string
}

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

type FlowConsentRef struct {
	Key     string `json:"key"`
	Version string `json:"version"`
}

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 honors 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
	// CookieMode asks for the completed session to be returned as HttpOnly
	// cookies rather than in the response body. Browsers set it; programmatic
	// clients leave it false and keep receiving tokens they can store themselves.
	CookieMode bool
}

FlowCreateCmd creates a new server-side resumable auth flow.

type FlowError added in v1.1.0

type FlowError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

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

type FlowGetCmd struct {
	ProjectID string
	FlowToken string
}

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.

const (
	FlowKindSignup      FlowKind = "signup"
	FlowKindSignin      FlowKind = "signin"
	FlowKindRecovery    FlowKind = "recovery"
	FlowKindEmailChange FlowKind = "email_change"
)

type FlowResendCmd added in v1.1.0

type FlowResendCmd struct {
	ProjectID string
	FlowToken string
}

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 Grant

type Grant struct {
	ID        string
	AccountID string
	ClientID  string
	Scopes    []string
	GrantedAt time.Time
}

type Identity

type Identity struct {
	ID                string
	Type              string // password | oauth | saml | oidc | passkey
	Provider          string
	ProviderAccountID string
	Email             string
}

type Interaction

type Interaction struct {
	ID          string
	ClientID    string
	Scopes      []string
	RedirectURI string
	Nonce       string
	SessionID   string
	// CodeChallenge / CodeChallengeMethod are the PKCE parameters of the
	// authorization request (RFC 7636). They travel from the authorization
	// request onto the authorization code, where the token endpoint checks the
	// verifier against them.
	CodeChallenge       string `json:"code_challenge,omitempty"`
	CodeChallengeMethod string `json:"code_challenge_method,omitempty"`
	// State is the client's opaque value from the authorization request. RFC
	// 6749 §4.1.2 requires it back, unmodified, on the authorization response;
	// relying parties use it as their CSRF defense and reject a callback without
	// it, so it has to survive the interaction.
	State string `json:"state,omitempty"`
	// Prompt is the request's prompt parameter, so the UI knows whether it must
	// force re-authentication or the consent screen rather than offering to
	// continue as the signed-in user.
	Prompt string `json:"prompt,omitempty"`
	// ResponseMode selects how the response is returned (query or fragment).
	ResponseMode string `json:"response_mode,omitempty"`
}

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
	// CreatedBy is the inviting user's account id for member invitations;
	// empty for admin/system invites (panel, approvals, integrations).
	CreatedBy string
	// CreatedByEmail is the resolved inviter address (admin listings only).
	CreatedByEmail string
}

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.

func (Invite) WithCreatorEmail added in v1.6.4

func (i Invite) WithCreatorEmail(email string) Invite

WithCreatorEmail is the admin-listing enrichment: the inviter's account id resolved to their email (best-effort — the account may be gone).

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
	// CreatedBy marks a member (user-driven) invitation: the invite occupies
	// one of that user's invite-cap slots. Empty = admin/system invite (the
	// admin API, access-request approvals, the telegram bot), uncapped.
	CreatedBy string
}

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

type InviteCreated struct {
	Invite
	Token string
}

InviteCreated is the create result carrying the one-time raw token.

type InviteListCmd added in v1.2.0

type InviteListCmd struct {
	ProjectID   string
	Environment string
}

InviteListCmd lists invitations for a project.

type InviteQuota added in v1.6.3

type InviteQuota struct {
	Cap  int
	Used int
	Left int
}

InviteQuota is a user's member-invitation budget: Cap is the effective limit (user override or project default), Used the occupied slots (pending-unexpired + accepted), Left the creatable count.

type InviteRevokeCmd added in v1.2.0

type InviteRevokeCmd struct {
	ProjectID   string
	Environment string
	InviteID    string
}

InviteRevokeCmd revokes a pending invitation.

type MFAEmailEnrollCmd

type MFAEmailEnrollCmd struct {
	AccountID string
	Email     string
}

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

type MFARecoveryVerifyCmd struct {
	ProjectID string
	AccountID string
	FlowToken string
	Code      string
}

MFARecoveryVerifyCmd consumes a recovery code to complete an MFA flow.

type MFASmsEnrollCmd

type MFASmsEnrollCmd struct {
	AccountID string
	Phone     string
}

MFASmsEnrollCmd enrolls an SMS factor and issues a delivery challenge.

type MFATotpVerifyCmd

type MFATotpVerifyCmd struct {
	AccountID string
	FactorID  string
	Code      string
}

MFATotpVerifyCmd activates a pending TOTP factor by verifying a code.

type MFAWebAuthnEnrollOptionsCmd

type MFAWebAuthnEnrollOptionsCmd struct {
	AccountID string
	Name      string
}

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

type MachineIDSecret struct {
	SecretID     string
	ClientID     string
	ClientSecret string
}

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

type MachineIDServiceAccountListCmd struct {
	ProjectID string
	Cursor    string
	Limit     int
}

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 OAuthProvider struct {
	ID     string
	Name   string
	Scopes []string
}

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

type OAuthSocialExchangeCmd struct {
	ProjectID    string
	Code         string
	CodeVerifier string
}

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 / CodeChallengeMethod carry PKCE (RFC 7636). The challenge is
	// bound to the issued authorization code and the token endpoint refuses the
	// exchange without the matching verifier.
	CodeChallenge       string
	CodeChallengeMethod string
	Nonce               string
	Prompt              string
	// MaxAge bounds how old the relied-upon authentication may be, in seconds.
	// Negative means the client did not ask.
	MaxAge int
	// ResponseMode selects how the response is returned: query (default) or
	// fragment.
	ResponseMode string
	RequestURI   string
	// Request is a signed request object (RFC 9101) carrying the whole
	// authorization request as a JWT the client signed.
	Request 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 OIDCAuthorizeResult added in v1.6.0

type OIDCAuthorizeResult struct {
	RedirectTo string
	FormPost   *OIDCFormPost
}

OIDCAuthorizeResult is how an authorization request is answered: either the user-agent is redirected somewhere (the interaction UI, or the client's redirect_uri carrying the response), or the response is form-posted back. Exactly one of the two is set.

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 OIDCClientRegisterCmd added in v1.6.0

type OIDCClientRegisterCmd struct {
	ProjectID    string
	Environment  string
	Registration OIDCClientRegistration
}

OIDCClientRegisterCmd registers a client inside a project environment.

type OIDCClientRegistration added in v1.6.0

type OIDCClientRegistration struct {
	ClientID                string
	ClientName              string
	RedirectURIs            []string
	ApplicationType         string
	TokenEndpointAuthMethod string
	GrantTypes              []string
	ResponseTypes           []string
	Scope                   []string
	JWKS                    string
	JWKSURI                 string
	PostLogoutRedirectURIs  []string
	BackchannelLogoutURI    string
	// IssuedAt is when the client was registered.
	IssuedAt time.Time
	// ClientSecret and RegistrationAccessToken are returned once, at
	// registration; afterwards only their digests are kept.
	ClientSecret            string
	RegistrationAccessToken string
	RegistrationClientURI   string
}

OIDCClientRegistration is a client's metadata in the shape RFC 7591 defines. It is deliberately its own type rather than AppClient: the registration API is a public contract with standard field names, and letting the storage type drive it would leak our naming into somebody else's client library.

type OIDCClientUpdateCmd added in v1.6.0

type OIDCClientUpdateCmd struct {
	ClientID     string
	ProjectID    string
	Registration OIDCClientRegistration
}

OIDCClientUpdateCmd replaces a registered client's metadata. RFC 7592 makes this a replacement, not a patch: a field left out is cleared.

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

type OIDCDeviceAuthorizationCmd struct {
	ClientID string
	Scope    string
}

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

type OIDCDeviceUserCode struct {
	ProjectID string
	UserCode  string
}

OIDCDeviceUserCode identifies a pending device authorization by its user-facing code, scoped to the project that owns the requesting client.

type OIDCFormPost added in v1.6.0

type OIDCFormPost struct {
	// Action is the client's registered redirect_uri, the form's target.
	Action string
	// Fields are the response parameters, posted as form fields.
	Fields map[string]string
}

OIDCFormPost is an authorization response delivered as an auto-submitting HTML form (OAuth 2.0 Form Post Response Mode) instead of a redirect. The response parameters travel in a POST body, so they never appear in the browser's address bar, its history, or the Referer header of the page the client renders next.

type OIDCInteractionContext added in v1.6.0

type OIDCInteractionContext struct {
	Interaction Interaction
	// ProjectID / Environment are the tenant the interaction belongs to. The
	// page needs them for the X-Client-Id it sends on the CSRF and interaction
	// calls.
	ProjectID   string
	Environment string
	// ClientName is the application's display name, ClientType its kind
	// (spa/native/web/machine).
	ClientName string
	ClientType string
	// DefaultLocale / SupportedLocales come from the project's auth config, so
	// the hosted pages speak the project's language rather than the browser's.
	DefaultLocale    string
	SupportedLocales []string
	// ExpiresAt is when the interaction stops being resumable.
	ExpiresAt time.Time
	// Stage tells the UI what is still missing: OIDCStageLogin while nobody has
	// claimed the interaction, OIDCStageConsent once a user has signed in.
	Stage string
}

OIDCInteractionContext is everything the hosted login/consent UI needs to render an interaction: which application is asking, what it is asking for, and which project's language the page should speak. The interaction id alone is a handle — the UI cannot show "Sign in to <app>" without this.

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

type OIDCLogoutCmd struct {
	IDTokenHint           string
	PostLogoutRedirectURI string
	State                 string
}

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 OIDCLogoutResult added in v1.6.0

type OIDCLogoutResult struct {
	RedirectURL         string
	ClearSessionCookies bool
}

OIDCLogoutResult is the outcome of an RP-initiated logout: where to send the browser, and whether its session cookies should be cleared on the way.

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
}

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

type OIDCParResult struct {
	RequestURI string
	ExpiresIn  int
}

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

type OIDCRejectCmd struct {
	InteractionID    string
	Error            string
	ErrorDescription string
}

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
	// ClientAssertionType / ClientAssertion carry private_key_jwt client
	// authentication (RFC 7523 §3): the client signs a short-lived JWT with a key
	// only it holds instead of presenting a shared secret.
	ClientAssertionType string
	ClientAssertion     string
	// AuthenticatedClientID is the client the TRANSPORT already authenticated —
	// client_secret_basic (RFC 6749 §2.3.1), the method most OAuth clients use by
	// default. It is empty when the client sent its credentials in the form body
	// (client_secret_post) instead, in which case ClientSecret carries them.
	AuthenticatedClientID string
	// Scope narrows a client_credentials request. It can only ever ask for less
	// than the caller already holds.
	Scope 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

type OperatorConfigCmd struct {
	ProjectID string
	Config    map[string]any
}

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

type OperatorFeaturesCmd struct {
	ProjectID string
	Features  map[string]bool
}

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 {
	CredentialID string // stable administrative credential identifier for audit
	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 Project

type Project struct {
	ID               string
	Name             string
	Slug             string
	DefaultLocale    string
	SupportedLocales []string
	Environments     []string
	CreatedAt        time.Time
}

type ProjectCmd

type ProjectCmd struct {
	Name          string
	Slug          string
	DefaultLocale string
}

func (ProjectCmd) Validate

func (c ProjectCmd) Validate() error

Validate checks project-create invariants.

type ProviderConfigSpec added in v1.3.0

type ProviderConfigSpec struct {
	Kind string // "email" | "sms"
	Type string
}

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
	// Metadata is the project's public_metadata doc: free-form string flags an
	// admin publishes for their own client apps to read before login. See
	// PublicMetadataSpec.
	Metadata map[string]string
}

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 PublicMetadataSpec added in v1.6.0

type PublicMetadataSpec map[string]string

PublicMetadataSpec mirrors the public_metadata jsonb doc: a flat map[string]string. Deliberately unstructured — unlike `features`, there is no closed registry of keys, because the values are a client's own product flags, not a toggle for a subsystem IAM implements.

func ParsePublicMetadata added in v1.6.0

func ParsePublicMetadata(raw []byte) (PublicMetadataSpec, error)

ParsePublicMetadata strictly decodes the public_metadata doc.

func (PublicMetadataSpec) Validate added in v1.6.0

func (c PublicMetadataSpec) Validate() error

Validate bounds the document's size. There is no key registry to check against: the whole point is that a client can publish whatever key it wants without IAM knowing what it means.

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

type RequestMeta struct {
	IP            string
	UserAgent     string
	Fingerprint   string
	DeviceName    string
	DeviceToken   string
	SecurityProof string
}

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 SecurityCase added in v1.7.0

type SecurityCase struct {
	ID            string                `json:"id"`
	AccountID     string                `json:"account_id,omitempty"`
	Status        string                `json:"status"`
	ContactMasked string                `json:"contact_masked"`
	CreatedAt     time.Time             `json:"created_at"`
	UpdatedAt     time.Time             `json:"updated_at"`
	Messages      []SecurityCaseMessage `json:"messages"`
}

type SecurityCaseDecision added in v1.7.0

type SecurityCaseDecision struct {
	Action   string `json:"action"`
	Message  string `json:"message"`
	Evidence string `json:"evidence"`
}

type SecurityCaseMessage added in v1.7.0

type SecurityCaseMessage struct {
	At      time.Time `json:"at"`
	Author  string    `json:"author"`
	Message string    `json:"message"`
}

type SecurityDelivery added in v1.7.0

type SecurityDelivery struct {
	ID              string    `json:"id"`
	IncidentID      string    `json:"incident_id,omitempty"`
	CaseID          string    `json:"case_id,omitempty"`
	Channel         string    `json:"channel"`
	RecipientMasked string    `json:"recipient_masked"`
	Status          string    `json:"status"`
	Attempts        int       `json:"attempts"`
	LastError       string    `json:"last_error,omitempty"`
	CreatedAt       time.Time `json:"created_at"`
	UpdatedAt       time.Time `json:"updated_at"`
}

type SecurityDevice added in v1.7.0

type SecurityDevice struct {
	ID           string     `json:"id"`
	Name         string     `json:"name"`
	FirstSeenAt  time.Time  `json:"first_seen_at"`
	LastSeenAt   time.Time  `json:"last_seen_at"`
	TrustedUntil *time.Time `json:"trusted_until,omitempty"`
	Revoked      bool       `json:"revoked"`
	Current      bool       `json:"current"`
	SessionIDs   []string   `json:"session_ids"`
}

type SecurityDeviceRegistration added in v1.7.0

type SecurityDeviceRegistration struct {
	Device      SecurityDevice `json:"device"`
	DeviceToken string         `json:"device_token"`
}

type SecurityEvent added in v1.7.0

type SecurityEvent struct {
	ID        string    `json:"id"`
	Type      string    `json:"type"`
	At        time.Time `json:"at"`
	Outcome   string    `json:"outcome"`
	SessionID string    `json:"session_id,omitempty"`
	DeviceID  string    `json:"device_id,omitempty"`
	IP        string    `json:"ip,omitempty"`
	UserAgent string    `json:"user_agent,omitempty"`
}

type SecurityFlowInput added in v1.7.0

type SecurityFlowInput struct {
	ExchangeKey       string         `json:"exchange_key,omitempty"`
	RequestID         string         `json:"request_id,omitempty"`
	DeviceID          string         `json:"device_id,omitempty"`
	Credential        map[string]any `json:"credential,omitempty"`
	Action            string         `json:"action,omitempty"`
	IncidentID        string         `json:"incident_id,omitempty"`
	SessionID         string         `json:"session_id,omitempty"`
	ContinuationToken string         `json:"continuation_token,omitempty"`
	Identifier        string         `json:"identifier,omitempty"`
	Contact           string         `json:"contact,omitempty"`
	Code              string         `json:"code,omitempty"`
	Password          string         `json:"password,omitempty"`
	NewPassword       string         `json:"new_password,omitempty"`
	FactorID          string         `json:"factor_id,omitempty"`
	Message           string         `json:"message,omitempty"`
	AllSessions       bool           `json:"all_sessions"`
	Version           int            `json:"version"`
}

type SecurityFlowState added in v1.7.0

type SecurityFlowState struct {
	Deletion          *AccountDeletion      `json:"deletion,omitempty"`
	Sessions          []SecuritySession     `json:"sessions,omitempty"`
	Challenge         map[string]any        `json:"challenge,omitempty"`
	FlowToken         string                `json:"flow_token,omitempty"`
	Kind              string                `json:"kind"`
	Status            string                `json:"status"`
	Step              string                `json:"step"`
	Version           int                   `json:"version"`
	NextActions       []string              `json:"next_actions"`
	ExpiresAt         time.Time             `json:"expires_at"`
	Incident          *SecurityIncident     `json:"incident,omitempty"`
	Case              *SecurityCase         `json:"case,omitempty"`
	ContactMasked     string                `json:"contact_masked,omitempty"`
	AttemptsLeft      int                   `json:"attempts_left"`
	ResendAt          *time.Time            `json:"resend_at,omitempty"`
	Factors           []SecurityProofFactor `json:"factors,omitempty"`
	AllSessions       bool                  `json:"all_sessions"`
	RevokedSessionIDs []string              `json:"revoked_session_ids"`
	Outcome           string                `json:"outcome,omitempty"`
	ErrorCode         string                `json:"error_code,omitempty"`
}

SecurityFlowState carries only the restricted flow capability, never a session.

type SecurityIncident added in v1.7.0

type SecurityIncident struct {
	ID                string          `json:"id"`
	AccountID         string          `json:"account_id"`
	Status            string          `json:"status"`
	Severity          string          `json:"severity"`
	Reasons           []string        `json:"reasons"`
	Events            []SecurityEvent `json:"events"`
	SessionID         string          `json:"session_id,omitempty"`
	DeviceID          string          `json:"device_id,omitempty"`
	CreatedAt         time.Time       `json:"created_at"`
	UpdatedAt         time.Time       `json:"updated_at"`
	PolicyVersion     int             `json:"policy_version"`
	RevokedSessionIDs []string        `json:"revoked_session_ids"`
	Resolution        string          `json:"resolution,omitempty"`
}

type SecurityPolicy added in v1.7.0

type SecurityPolicy struct {
	Version                     int               `json:"version"`
	Mode                        string            `json:"mode"`
	ContinueURL                 string            `json:"continue_url"`
	ClientURLs                  map[string]string `json:"client_urls"`
	Notify                      bool              `json:"notify"`
	RequireNewDeviceProof       bool              `json:"require_new_device_proof"`
	FlowTTLSeconds              int               `json:"flow_ttl_seconds"`
	TrustTTLSeconds             int               `json:"trust_ttl_seconds"`
	RetentionDays               int               `json:"retention_days"`
	FailureThreshold            int               `json:"failure_threshold"`
	FailureWindowSeconds        int               `json:"failure_window_seconds"`
	NotificationCooldownSeconds int               `json:"notification_cooldown_seconds"`
}

type SecurityProofFactor added in v1.7.0

type SecurityProofFactor struct {
	ID   string `json:"id"`
	Type string `json:"type"`
	Hint string `json:"hint"`
}

type SecurityScope added in v1.7.0

type SecurityScope struct {
	ProjectID   string
	Environment string
	AccountID   string
	SessionID   string
	ActorID     string
}

SecurityScope is supplied by the transport, never by a request body.

type SecuritySession added in v1.7.0

type SecuritySession struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

type ServiceAccount

type ServiceAccount struct {
	ID        string
	ProjectID string
	Name      string
	Scopes    []string
	Disabled  bool
}

type ServiceAccountCmd

type ServiceAccountCmd struct {
	ProjectID string
	Name      string
	Scopes    []string
}

type Session

type Session struct {
	ID           string
	AccountID    string
	ProjectID    string
	ClientID     string
	AMR          []string
	AAL          int
	AccessToken  string
	RefreshToken string
	// ExpiresIn / RefreshExpiresIn are the access and refresh lifetimes in
	// seconds, as resolved from the project's session_policy. Cookie-mode
	// callers use them for the session cookies' Max-Age, so the browser session
	// lives exactly as long as the policy says — not as long as a constant
	// compiled into the transport layer.
	ExpiresIn        int
	RefreshExpiresIn 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"`
	// AccessTokenClaims opts the project's core-auth access tokens into extra
	// claims. Known value: "roles" (the user's IAM role assignments, resolved
	// server-side at signing time).
	AccessTokenClaims []string `json:"access_token_claims,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 marshaled 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 marshaled 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 WebAuthnCredential struct {
	ID         string
	Name       string
	CreatedAt  time.Time
	LastUsedAt time.Time
}

type WebAuthnRenameCredentialCmd

type WebAuthnRenameCredentialCmd struct {
	AccountID    string
	CredentialID string
	Name         string
}

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 marshaled go-webauthn Credential (id, COSE public key, sign count, AAGUID, flags, attestation) the library needs to verify subsequent assertions. It is marshaled 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 WebhookCreateCmd struct {
	ProjectID      string
	Environment    string
	URL            string
	Events         []string
	Description    string
	Enabled        bool
	IdempotencyKey string
}

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 WebhookDeliveryListCmd struct {
	ProjectID   string
	Environment string
	WebhookID   string
	Status      string
	Limit       int
}

type WebhookEventListCmd added in v1.4.0

type WebhookEventListCmd struct {
	ProjectID   string
	Environment string
	Type        string
	UserID      string
	Cursor      string
	Limit       int
}

type WebhookEventPage added in v1.4.0

type WebhookEventPage struct {
	Data       []PublicEvent
	NextCursor string
	HasMore    bool
}

type WebhookListCmd added in v1.4.0

type WebhookListCmd struct {
	ProjectID   string
	Environment string
	Cursor      string
	Limit       int
}

type WebhookUpdateCmd added in v1.4.0

type WebhookUpdateCmd struct {
	ProjectID   string
	Environment string
	ID          string
	URL         *string
	Events      *[]string
	Description *string
	Enabled     *bool
}

Jump to

Keyboard shortcuts

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