core

package
v0.0.0-...-728c4da Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: AGPL-3.0 Imports: 106 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

Index

Constants

View Source
const (
	// ServerAssetVisibilityHeader positively marks legacy flat NATS objects that
	// may be served by the unauthenticated public server-asset route. New public
	// objects use PublicServerAssetObjectPrefix instead.
	ServerAssetVisibilityHeader       = "Chatto-Asset-Visibility"
	ServerAssetVisibilityPublic       = "public"
	ServerAssetVisibilityNUIDHeader   = "Chatto-Asset-Public-NUID"
	ServerAssetVisibilityDigestHeader = "Chatto-Asset-Public-Digest"

	// PublicServerAssetObjectPrefix is the explicit SERVER_ASSETS namespace for
	// newly written unauthenticated public assets. Historical public objects use
	// flat asset-ID keys and remain available through the legacy classifier.
	PublicServerAssetObjectPrefix = "public/"
)
View Source
const (
	// MessageEditWindow is the duration after posting during which an author can
	// edit their own message without message.manage. Effective message.manage
	// permits edits at any time.
	MessageEditWindow = 3 * time.Hour

	// MaxMessageBodyLength is the maximum length of a message body in bytes.
	MaxMessageBodyLength = 10000

	// MaxReactionsPerUserPerMessage is the maximum number of distinct emoji
	// reactions one user may add to one canonical message.
	MaxReactionsPerUserPerMessage = 20

	// MaxDisplayNameLength is the maximum length of a user's display name in characters.
	MaxDisplayNameLength = 32

	// MaxDescriptionLength is the maximum length of space/room descriptions in bytes.
	MaxDescriptionLength = 2000

	// MaxSpaceNameLength is the maximum length of a space name in bytes.
	MaxSpaceNameLength = 42

	// MaxLoginLength is the maximum length of a user login in characters.
	MaxLoginLength = config.LoginLengthCeiling

	// MinLoginLength is the minimum length of a user login in characters.
	MinLoginLength = 2

	// LoginChangeCooldown is the minimum duration between login changes.
	LoginChangeCooldown = 30 * 24 * time.Hour

	// MinPasswordLength is the minimum length of a password in bytes.
	MinPasswordLength = 8

	// MaxPasswordLength is the maximum length of a password in bytes.
	// Go bcrypt rejects passwords longer than 72 bytes. Never truncate passwords.
	MaxPasswordLength = 72

	// MaxServerNameLength is the maximum length of a runtime-editable server name in bytes.
	MaxServerNameLength = 80

	// MaxServerDescriptionLength is the maximum length of a server description in bytes.
	MaxServerDescriptionLength = 500

	// MaxServerMOTDLength is the maximum length of a server message of the day in bytes.
	MaxServerMOTDLength = 1000

	// MaxServerWelcomeMessageLength is the maximum length of a server welcome message in bytes.
	MaxServerWelcomeMessageLength = 10000

	// MaxServerBlockedUsernamesLength is the maximum length of the blocked-username list in bytes.
	MaxServerBlockedUsernamesLength = 10000

	// MaxRoleDisplayNameLength is the maximum length of a role display name in bytes.
	MaxRoleDisplayNameLength = 80

	// MaxRoleDescriptionLength is the maximum length of a role description in bytes.
	MaxRoleDescriptionLength = 500

	// MaxRoomGroupNameLength is the maximum length of a room group display name in bytes.
	MaxRoomGroupNameLength = 80

	// MaxRoomGroupDescriptionLength is the maximum length of a room group description in bytes.
	MaxRoomGroupDescriptionLength = 500

	// MaxSidebarLinkLabelLength is the maximum length of a sidebar link label in bytes.
	MaxSidebarLinkLabelLength = 80

	// MaxSidebarLinkURLLength is the maximum length of a sidebar link URL in bytes.
	MaxSidebarLinkURLLength = 2048

	// MaxPushEndpointLength is the maximum length of a Push API endpoint URL in bytes.
	MaxPushEndpointLength = 4096
	// MaxPushClientHostLength bounds the URL host stored with a browser subscription.
	MaxPushClientHostLength = 255

	// MaxPushKeyLength is the maximum length of a Push API p256dh public key in bytes.
	MaxPushKeyLength = 256

	// MaxPushAuthLength is the maximum length of a Push API auth secret in bytes.
	MaxPushAuthLength = 128
	// MaxPushCleanupTokenLength bounds the random capability attached to one save.
	MaxPushCleanupTokenLength = 128
	// MinPushCleanupTokenLength preserves at least 128 bits for hexadecimal tokens.
	MinPushCleanupTokenLength = 32

	// MaxPushUserAgentLength is the maximum length of a stored push user-agent string in bytes.
	MaxPushUserAgentLength = 512

	// MaxLinkPreviewURLLength is the maximum length of a client-provided link preview URL in bytes.
	MaxLinkPreviewURLLength = 2048

	// MaxLinkPreviewTitleLength is the maximum length of a client-provided link preview title in bytes.
	MaxLinkPreviewTitleLength = 300

	// MaxLinkPreviewDescriptionLength is the maximum length of a client-provided link preview description in bytes.
	MaxLinkPreviewDescriptionLength = 1000

	// MaxLinkPreviewSiteNameLength is the maximum length of a client-provided link preview site name in bytes.
	MaxLinkPreviewSiteNameLength = 200

	// MaxLinkPreviewEmbedTypeLength is the maximum length of a client-provided link preview embed type in bytes.
	MaxLinkPreviewEmbedTypeLength = 64

	// MaxLinkPreviewEmbedIDLength is the maximum length of a client-provided link preview embed ID in bytes.
	MaxLinkPreviewEmbedIDLength = 256

	// MaxLinkPreviewImageAssetIDLength is the maximum length of a client-provided link preview image asset ID in bytes.
	MaxLinkPreviewImageAssetIDLength = 15

	// MaxMessageAttachmentAssetIDs is the maximum number of attachment asset IDs accepted for one message.
	MaxMessageAttachmentAssetIDs = 10

	// MaxMessageAttachmentAssetIDLength is the maximum length of a message attachment asset ID in bytes.
	MaxMessageAttachmentAssetIDLength = 15

	// MaxAttachmentDescriptionLength is the maximum number of Unicode
	// characters in one attachment description.
	MaxAttachmentDescriptionLength = 1000
)

Input validation limits. Note: These limits are enforced using len() which counts bytes, not Unicode characters. This is intentional for consistent storage cost control - a 10KB message costs the same regardless of whether it contains ASCII or multi-byte UTF-8 characters.

View Source
const (
	DefaultEventLogPageSize   = 50
	MaxEventLogPageSize       = 200
	FilteredEventLogScanLimit = 5000
)
View Source
const (
	ExternalIdentityFlowTTL = 15 * time.Minute

	ExternalIdentityFlowKindCreate = "create"
	ExternalIdentityFlowKindLink   = "link"
)
View Source
const (

	// JobTypeMedia is the job type of media processing. Standalone media
	// processes run its consumer.
	JobTypeMedia = "media"
	// JobSucceededRetention is how long succeeded jobs stay.
	JobSucceededRetention = 3 * 24 * time.Hour
)

Persisted job queue resource contract (ADR-123). The JOBS stream holds the facts of each job on jobs.{type}.{id}.{fact}.

View Source
const (
	MentionHandleAll  = "all"
	MentionHandleHere = "here"
)
View Source
const (
	// MaxNeighbors bounds the public directory and its API payloads.
	MaxNeighbors = 100
	// MaxNeighborOriginLength bounds each stored canonical origin.
	MaxNeighborOriginLength = 2048
)
View Source
const (
	// PasswordResetTokenTTL is the duration a password reset token is valid.
	PasswordResetTokenTTL = 1 * time.Hour

	// PasswordResetRequestThrottleTTL is the minimum interval between delivered
	// password-reset links for one account.
	PasswordResetRequestThrottleTTL = 5 * time.Minute
)
View Source
const (
	// RoleOwner has all permissions and is the highest authority. Must be
	// explicitly assigned. Config-designated owners (matched against
	// `owners.emails` in chatto.toml) get this role materialized at boot
	// and on email verification.
	RoleOwner = "owner"

	// RoleAdmin has administrative permissions. Must be explicitly assigned.
	RoleAdmin = "admin"

	// RoleModerator has moderation permissions. Must be explicitly assigned.
	RoleModerator = "moderator"

	// RoleEveryone is implicit for all authenticated users. It has no role
	// assignment facts; permission facts on this role apply to every
	// authenticated viewer.
	RoleEveryone = "everyone"
)

Built-in role names (system-defined, cannot be deleted).

Phase 5 of #330 collapsed the dual-layer instance/space RBAC into a single server-shaped layer. The legacy `instance-` prefix is gone — the unified owner/admin/moderator roles cover what the two parallel layers used to.

View Source
const (
	PresenceStatusOffline      = "OFFLINE"
	PresenceStatusOnline       = "ONLINE"
	PresenceStatusAway         = "AWAY"
	PresenceStatusDoNotDisturb = "DO_NOT_DISTURB"
)

Presence status constants used by public API and storage mappings.

View Source
const (
	// PresenceTTL is the TTL for presence entries in the KV bucket.
	// If a client disconnects without explicit cleanup, entries expire after this duration.
	PresenceTTL = 60 * time.Second

	// PresenceRefreshInterval is how often clients refresh their presence.
	// Should be less than PresenceTTL to ensure entries don't expire while connected.
	PresenceRefreshInterval = 30 * time.Second
)

Presence configuration constants

View Source
const (

	// MaxPushSubscriptionsPerUser is the maximum number of active browser
	// subscriptions that one account can fan push delivery out to.
	MaxPushSubscriptionsPerUser = pushendpoint.MaxSubscriptionsPerUser

	// PushSubscriptionLifetime is how long a subscription stays deliverable
	// after its most recent save. Clients save their subscriptions again while
	// the device is in use, so only devices that stop using Chatto expire.
	PushSubscriptionLifetime = 180 * 24 * time.Hour
)
View Source
const (
	// Position numbering: higher sorts before lower.
	//   everyone   = 0     (always; the implicit role every user holds)
	//   custom     = 1..99 (operator-defined roles slot in here)
	//   moderator  = 100
	//   admin      = 900
	//   owner      = 1000
	//
	// Wide gaps between system roles leave room for new system roles in the
	// future and let custom roles be positioned without renumbering existing
	// ones.
	PositionEveryone    int32 = 0
	PositionCustomFirst int32 = 1
	PositionModerator   int32 = 100
	PositionAdmin       int32 = 900
	PositionOwner       int32 = 1000
)

Position constants for role display/order and legacy event compatibility.

View Source
const (
	RoomNameMinLength        = 1
	RoomNameMaxLength        = 30
	RoomDescriptionMaxLength = 500
	// MaxRoomSlowModeSeconds is the longest supported per-user posting interval.
	MaxRoomSlowModeSeconds = 6 * 60 * 60
)

Room name validation constants

View Source
const (
	MaxCustomStatusEmojiLength = 16
	MaxCustomStatusTextLength  = 100
	// MaxBioLength bounds a user's public bio in Unicode characters.
	MaxBioLength = 1000
)
View Source
const AccountDeletionTokenTTL = 15 * time.Minute

AccountDeletionTokenTTL is how long an account deletion token is valid.

View Source
const AnnouncementsRoomName = "announcements"

AnnouncementsRoomName is the canonical name for the seeded announcement-only room whose creation-time permission facts differ from ordinary rooms.

View Source
const AssetAccessTicketTTL = 24 * time.Hour

AssetAccessTicketTTL keeps direct browser/standalone-client asset URLs useful across long-lived room views and deferred media playback, without turning copied URLs into indefinite bearer links.

View Source
const AssetProcessingConsumerName = "chatto-asset-processing-v1"

AssetProcessingConsumerName is the durable EVT consumer of the media job source. The name is a persisted resource contract (ADR-069).

View Source
const AttachmentDerivativeCacheResource = "attachment-stable-v2"

AttachmentDerivativeCacheResource versions the current attachment image encoding profile independently from the stable public URL shape.

View Source
const AttachmentSignResource = "attachment"

AttachmentSignResource binds legacy signed attachment transforms and remains a cache-cleanup namespace for derivatives written before stable asset paths.

View Source
const CallMediaPublisherTokenTTL = time.Minute

CallMediaPublisherTokenTTL only needs to cover starting the native helper's LiveKit connection. An established connection remains valid after expiry.

View Source
const ConfigSubjectServer = "server"
View Source
const DefaultAssetUploadChunkSize = 10 * 1024 * 1024

DefaultAssetUploadChunkSize is the maximum chunk size in bytes for new upload sessions. Larger chunks reduce acknowledgement waits on high-latency connections. Transports must allow this payload plus request metadata. Existing sessions retain the limit stored when they were created.

View Source
const DefaultBlockedUsernames = "root\nadmin\nsuperuser\nop\noperator\nsupport"

DefaultBlockedUsernames is the default list of blocked usernames for new servers (used when no config has been written yet).

View Source
const DefaultDescription = "Come join our community!"

DefaultDescription is the fallback server description used when no admin-configured description is set. Surfaced via OG meta tags and the ServerDiscoveryService.GetServer discovery endpoint.

View Source
const DeletedUserDisplayName = "Deleted User"
View Source
const FallbackContentType = "application/octet-stream"

FallbackContentType is the media type for attachment bytes with a missing or unparseable declared content type.

View Source
const FreshAuthWindow = 30 * time.Minute
View Source
const InvitationNoteMaxLength = 250

InvitationNoteMaxLength is the maximum number of Unicode code points in a creation note.

View Source
const LegacyDMRoomSpaceID = "DM"

LegacyDMRoomSpaceID is the wire-frozen space_id value that older event payloads and a few compatibility APIs still use to mean "DM room".

View Source
const LegacyServerSpaceID = "server"

LegacyServerSpaceID is the wire-frozen space_id value used by channel-room payloads and compatibility APIs after the Space tier was retired.

View Source
const (

	// LinkPreviewTokenTTL keeps composer tokens useful across retries and
	// mention-confirmation flows without making cached preview selection durable.
	LinkPreviewTokenTTL = 30 * time.Minute
)
View Source
const MaxDMParticipants = 10

MaxDMParticipants bounds lookup of stored DMs from older servers. New DMs allow at most two distinct participants; use channels for groups.

View Source
const MaxHistoricalAvatarBytes = 5 << 20

MaxHistoricalAvatarBytes bounds one avatar image, not the archive.

View Source
const MaxHistoricalMessages = 32

MaxHistoricalMessages bounds message bodies and work in one atomic request.

View Source
const MaxHistoricalReactionChanges = 128

MaxHistoricalReactionChanges bounds one atomic historical reaction write.

View Source
const MaxRoomBanReasonLength = 1000
View Source
const MaxRoomNoticeLength = 4000

MaxRoomNoticeLength bounds notice Markdown in Unicode code points.

View Source
const MessageIdempotencyWindow = 30 * time.Minute

MessageIdempotencyWindow is the fixed lifetime of an accepted send key. Callers must stop retrying within this period after their first attempt; an expired key can reserve another message identity.

View Source
const (

	// MyEventsHeartbeatInterval controls the synthetic heartbeat cadence used by
	// StreamMyEvents and advertised by the realtime WebSocket protocol.
	MyEventsHeartbeatInterval = 15 * time.Second
)
View Source
const ObjectIdAny = "any"

ObjectIdAny identifies a server-scope decision in permission explanations.

View Source
const ParticipantPublisherKindGameShare = "game_share"

ParticipantPublisherKindGameShare identifies a native companion connection that contributes game media to another participant.

View Source
const (
	// PendingOAuthAuthorizeTTL bounds an OAuth browser flow that has not yet
	// reached approval, denial, or an already-consented callback.
	PendingOAuthAuthorizeTTL = 15 * time.Minute
)
View Source
const PrivilegedModeWindow = 15 * time.Minute

PrivilegedModeWindow is the fixed lifetime of one explicit activation. Ordinary use does not extend the deadline.

View Source
const (
	// RegistrationCompletionTokenTTL is the duration a code-exchanged completion token is valid.
	RegistrationCompletionTokenTTL = 15 * time.Minute
)
View Source
const S3AssetRedirectTTL = 5 * time.Minute

S3AssetRedirectTTL bounds direct object-store redirects for heavy original asset responses. Chatto authorizes the request first, then hands browsers a short-lived S3 URL only for cases where proxying the bytes would be costly.

View Source
const SeedDefaultRoomGroupName = "Lobby"

SeedDefaultRoomGroupName is the operator-facing name given to the auto-created seed room group on first boot. Not system-protected — operators can rename, reorder, or delete it like any other.

View Source
const ServerAssetSignResource = "server"

ServerAssetSignResource is the first resource component fed to the signed-URL signer for server asset transform URLs and the cache prefix for transformed server assets (avatars, logos, banners, and similar public server-scoped images).

View Source
const SystemActorID = "system"

SystemActorID is used for internal/bootstrap operations that bypass permission checks. SECURITY: This value cannot be forged by external users because user IDs are always generated with a "U" prefix (via NewUserID), e.g., "U1234567890abcd". The string "system" can never match a valid user ID.

View Source
const VoiceCallTokenTTL = 5 * time.Minute

VoiceCallTokenTTL gives browser clients enough time for E2EE worker setup, permission prompts, and a signaling retry without making leaked join tokens long-lived.

Variables

View Source
var (
	ErrAssetLifecycleSkipped = errors.New("asset lifecycle event skipped")
	ErrAssetCommitUnknown    = errors.New("asset event commit status unknown")
)
View Source
var (
	// ErrAuthCodeNotFound is returned when an authorization code doesn't exist or has expired.
	ErrAuthCodeNotFound = errors.New("authorization code not found")

	// ErrAuthCodeInvalidVerifier is returned when the PKCE code_verifier doesn't match the stored code_challenge.
	ErrAuthCodeInvalidVerifier = errors.New("invalid code verifier")

	// ErrAuthCodeRedirectMismatch is returned when the redirect_uri doesn't match the one used during authorization.
	ErrAuthCodeRedirectMismatch = errors.New("redirect URI mismatch")

	// ErrAuthCodeClientMismatch is returned when client_id doesn't match the one used during authorization.
	ErrAuthCodeClientMismatch = errors.New("client ID mismatch")

	// ErrAuthCodeInvalidMethod is returned when the code_challenge_method is not S256.
	ErrAuthCodeInvalidMethod = errors.New("unsupported code challenge method: only S256 is supported")
)
View Source
var (
	// ErrMessageIdempotencyConflict means a caller reused a live send key with
	// a different room or request. The new request has not been applied.
	ErrMessageIdempotencyConflict = errors.New("message send key was reused with different arguments")
	// ErrNotFound is returned when a requested resource does not exist.
	ErrNotFound = errors.New("not found")

	// ErrNotAuthenticated is returned when an operation requires authentication
	// but no valid user context is available.
	ErrNotAuthenticated = errors.New("authentication required")

	// ErrPermissionDenied is returned when a user lacks the required permission
	// to perform an operation.
	ErrPermissionDenied = errors.New("permission denied")

	// ErrInvalidArgument is returned when a caller provides invalid request
	// input. Wrap this with an InvalidArgumentError when the caller should see a
	// specific validation message.
	ErrInvalidArgument = errors.New("invalid argument")

	// ErrPasswordAlreadySet is returned when trying to add an initial password
	// to an account that already has a password credential.
	ErrPasswordAlreadySet = errors.New("password is already set")

	// ErrCurrentPasswordRequired is returned when changing an existing password
	// without proving knowledge of the current password.
	ErrCurrentPasswordRequired = errors.New("current password is required")

	// ErrCurrentPasswordInvalid is returned when the supplied current password
	// does not match the authenticated user's password.
	ErrCurrentPasswordInvalid = errors.New("current password is invalid")

	// ErrAdminCannotSetOwnPassword is returned when a user attempts to use the
	// admin password-reset path for their own account.
	ErrAdminCannotSetOwnPassword = errors.New("cannot set your own password through admin user management")

	// ErrNotSpaceMember is returned when a user attempts to access a space
	// they are not a member of.
	ErrNotSpaceMember = errors.New("not a member of this space")

	// ErrNotRoomMember is returned when a user attempts to access a room
	// they are not a member of.
	ErrNotRoomMember = errors.New("not a member of this room")

	// ErrCallParticipantLimit means a new admission would exceed the server quota.
	ErrCallParticipantLimit = errors.New("This server has reached its call participant limit. Try again later.")

	// ErrCallParticipationRequired is returned when an operation requires the
	// user to be a participant in the active call generation.
	ErrCallParticipationRequired = errors.New("active call participation required")

	// ErrRoleNotFound is returned when attempting to access a role that doesn't exist.
	ErrRoleNotFound = errors.New("role not found")

	// ErrImplicitRole is returned when attempting to assign or revoke an implicit role
	// (like member or verified) which cannot be explicitly managed.
	ErrImplicitRole = errors.New("implicit role cannot be explicitly assigned or revoked")

	// ErrCannotDeleteSystemRole is returned when attempting to delete a system role
	// (owner, moderator, everyone, etc.) which are protected.
	ErrCannotDeleteSystemRole = errors.New("cannot delete system role")

	// ErrInvalidRoleName is returned when a role name doesn't match the required format
	// (lowercase letters, numbers, and dashes; must start with a letter; 1-32 chars).
	ErrInvalidRoleName = errors.New("invalid role name: must be lowercase letters, numbers, and dashes, starting with a letter, 1-32 chars")

	// ErrRoleAlreadyExists is returned when attempting to create a role that already exists.
	ErrRoleAlreadyExists = errors.New("role already exists")

	// ErrInvalidPermission is returned when an unrecognized permission value is used.
	ErrInvalidPermission = errors.New("invalid permission")

	// ErrNotMessageAuthor is returned when a user attempts to edit/delete a message
	// they did not author.
	ErrNotMessageAuthor = errors.New("not the message author")

	// ErrMessageNotFound is returned when a message body doesn't exist (already deleted).
	ErrMessageNotFound = errors.New("message not found")

	// ErrMessageBodyCorrupt is returned when a persisted message body envelope is
	// malformed or cannot be authenticated. Callers may render the affected
	// message as unavailable, but should not treat dependency or request errors
	// as this sentinel.
	ErrMessageBodyCorrupt = errors.New("message body corrupt")

	// ErrMessageAttachmentNotFound is returned when a message does not contain
	// the requested attachment.
	ErrMessageAttachmentNotFound = errors.New("message attachment not found")

	// ErrAssetNotAttachable is returned when a message references an asset that
	// is unavailable, belongs to another uploader, or is already attached to a
	// message.
	ErrAssetNotAttachable = errors.New("asset is not available to attach")

	// ErrMessageLinkPreviewNotFound is returned when a message does not contain
	// the requested link preview.
	ErrMessageLinkPreviewNotFound = errors.New("message link preview not found")

	// ErrEditWindowExpired is returned when attempting to edit a message
	// after the edit window has closed.
	ErrEditWindowExpired = errors.New("edit window has expired")

	// ErrMessageTooLong is returned when a message body exceeds the maximum length.
	ErrMessageTooLong = errors.New("message body exceeds maximum length")

	// ErrSlowModeActive is returned when a user attempts to post before the
	// room's per-user posting interval has elapsed.
	ErrSlowModeActive = errors.New("slow mode is active")

	// ErrRoomThreadingPolicy is returned when thread creation or message
	// placement conflicts with the channel's current threading mode.
	ErrRoomThreadingPolicy = errors.New("message conflicts with the room threading policy")

	// ErrDisplayNameTooLong is returned when a display name exceeds the maximum length.
	ErrDisplayNameTooLong = errors.New("display name exceeds maximum length")

	// ErrDisplayNameInvalidCharacter is returned when a display name contains
	// controls, line breaks, unsupported format characters, or no visible content.
	ErrDisplayNameInvalidCharacter = errors.New("display name contains invalid characters")

	// ErrDescriptionTooLong is returned when a description exceeds the maximum length.
	ErrDescriptionTooLong = errors.New("description exceeds maximum length")

	// ErrSpaceNameTooLong is returned when a space name exceeds the maximum length.
	ErrSpaceNameTooLong = errors.New("space name exceeds maximum length")

	// ErrAdminCannotLeaveSpace is returned when a space admin tries to leave the space.
	// Admins must transfer or remove their admin role before leaving.
	ErrAdminCannotLeaveSpace = errors.New("space admin cannot leave: transfer or remove admin role first")

	// ErrCannotLeaveDMConversation is returned when a user tries to leave a DM room.
	// DM conversations are permanent and cannot be left.
	ErrCannotLeaveDMConversation = errors.New("cannot leave DM conversations")

	// ErrCannotLeaveUniversalRoom is returned when a user tries to leave a
	// universal channel room. Universal rooms grant effective membership through
	// server policy; users can mute them instead.
	ErrCannotLeaveUniversalRoom = errors.New("cannot leave universal rooms")

	// ErrCannotRemoveDMRoomMember is returned when a moderator tries to remove
	// someone from a DM room. DM membership is the privacy boundary and
	// cannot be moderated like a channel room.
	ErrCannotRemoveDMRoomMember = errors.New("cannot remove users from DM conversations")

	// ErrLoginTooShort is returned when a login is shorter than MinLoginLength.
	ErrLoginTooShort = errors.New("username must be at least 2 characters")

	// ErrLoginTooLong is returned when a login exceeds the configured maximum.
	ErrLoginTooLong = errors.New("username is too long")

	// ErrLoginInvalidCharacter is returned when a login contains characters
	// outside the allowed set (letters, digits, periods, underscores, hyphens).
	ErrLoginInvalidCharacter = errors.New("username can only contain letters, numbers, periods, underscores, and hyphens")

	// ErrHumanAccountRequired is returned when a human-only operation targets a bot.
	ErrHumanAccountRequired = errors.New("operation requires a human account")
	// ErrPrivilegedModeUnavailable means the current user has no
	// protected role to activate.
	ErrPrivilegedModeUnavailable = errors.New("privileged mode is not available")

	// ErrBotOwnerPermissionCeiling is returned when a requested bot grant would
	// exceed its owner's current effective permission.
	ErrBotOwnerPermissionCeiling = errors.New("bot permission exceeds its owner's current permission")

	// ErrLoginChangeCooldown is returned when a user tries to change their login
	// before the cooldown period has elapsed.
	ErrLoginChangeCooldown = errors.New("you can only change your username once every 30 days")

	// ErrInvalidEvent is returned when an event publish helper receives an invalid
	// event payload (e.g. nil pointer or missing protobuf oneof payload).
	ErrInvalidEvent = errors.New("invalid event")

	// ErrLimitExceeded is returned when an operation would exceed an instance-wide
	// resource limit configured via [limits] (e.g. max_users).
	ErrLimitExceeded = errors.New("instance limit reached")

	// ErrReactionLimitExceeded is returned when a user already has the maximum
	// number of distinct emoji reactions on one canonical message.
	ErrReactionLimitExceeded = errors.New("reaction limit reached")

	// ErrServerNotBootstrapped is returned by API-layer helpers that need
	// the deployment's primary space ID before its bootstrap has run.
	ErrServerNotBootstrapped = errors.New("instance not bootstrapped")

	// ErrRoomArchived is returned when an operation is rejected because the
	// room is archived. Archived rooms are read-only: no posting, editing,
	// reactions, or joining.
	ErrRoomArchived = errors.New("room is archived")

	// ErrPasswordTooShort is returned when a password is shorter than MinPasswordLength.
	ErrPasswordTooShort = fmt.Errorf("password must be at least %d bytes long", MinPasswordLength)

	// ErrPasswordTooLong is returned when a password exceeds MaxPasswordLength.
	ErrPasswordTooLong = fmt.Errorf("password cannot exceed %d bytes", MaxPasswordLength)
)

Sentinel errors for common error conditions in ChattoCore.

View Source
var (
	ErrExternalIdentityFlowNotFound  = errors.New("external identity flow not found")
	ErrExternalIdentityFlowExpired   = errors.New("external identity flow expired")
	ErrExternalIdentityFlowWrongKind = errors.New("external identity flow has the wrong kind")
	ErrExternalIdentityFlowUserBound = errors.New("external identity flow is bound to a different user")
	ErrExternalIdentityNotFound      = errors.New("external identity is not linked to this account")
	ErrExternalIdentityLastMethod    = errors.New("cannot disconnect the last sign-in method")
)
View Source
var (
	// ErrFreshAuthReverificationMismatch reports a provider identity that is
	// not linked to the account that started the re-verification, or a
	// callback in a browser that no longer holds a session of that account.
	ErrFreshAuthReverificationMismatch = errors.New("re-verified identity does not match the current account")
	// ErrFreshAuthReverificationStale reports a provider sign-in that did not
	// happen during this re-verification, so it does not prove presence.
	ErrFreshAuthReverificationStale = errors.New("provider did not authenticate the user again")
)
View Source
var (
	// ErrJobNotRetryable means this job is active, successful, or expired, or
	// changed after the caller read it.
	ErrJobNotRetryable = errors.New("job cannot be retried")
	// ErrJobNotDeletable means this job is not failed, or changed after the
	// caller read it.
	ErrJobNotDeletable = errors.New("job cannot be deleted")
)
View Source
var (
	// ErrNeighborNotFound means that the requested Neighbor does not exist.
	ErrNeighborNotFound = errors.New("Neighbor not found")
	// ErrNeighborAlreadyExists means that the canonical origin is advertised.
	ErrNeighborAlreadyExists = errors.New("Neighbor origin already exists")
	// ErrNeighborMatchesServerOrigin means that the configured origin identifies
	// this server and cannot be advertised as a Neighbor.
	ErrNeighborMatchesServerOrigin = errors.New("Neighbor origin identifies this server")
	// ErrNeighborRevisionChanged prevents a stale update or delete.
	ErrNeighborRevisionChanged = errors.New("Neighbor was changed by another request")
	// ErrNeighborLimitReached means that the directory is full.
	ErrNeighborLimitReached = errors.New("Neighbor limit reached")
)
View Source
var (
	// ErrPasswordResetTokenNotFound is returned when the reset token doesn't exist.
	ErrPasswordResetTokenNotFound = errors.New("password reset token not found")

	// ErrPasswordResetTokenExpired is returned when the reset token has expired.
	ErrPasswordResetTokenExpired = errors.New("password reset token has expired")

	// ErrPasswordResetRequestThrottled is returned when an account already had
	// a password-reset link prepared within the throttle window.
	ErrPasswordResetRequestThrottled = errors.New("password reset request throttled")
)
View Source
var (
	// ErrPushSubscriptionLimitReached is returned when a new endpoint would
	// exceed the account's active Web Push subscription limit.
	ErrPushSubscriptionLimitReached = errors.New("push subscription limit reached")

	// ErrPushTestNotificationRateLimited is returned when an account requests
	// another test notification inside the shared throttle window.
	ErrPushTestNotificationRateLimited = errors.New("push test notification rate limited")
)
View Source
var (
	// ErrRealtimeCursorInvalid means the cursor is malformed, references a
	// different EVT incarnation, or points beyond the current stream.
	ErrRealtimeCursorInvalid = errors.New("invalid realtime cursor")
	// ErrRealtimeCursorExpired means the cursor is older than its public
	// lifetime or precedes retained EVT history.
	ErrRealtimeCursorExpired = errors.New("realtime cursor expired")
)
View Source
var (
	// ErrRegistrationCodeNotFound is returned when the registration code record doesn't exist.
	ErrRegistrationCodeNotFound = errors.New("registration code not found")

	// ErrRegistrationCodeExpired is returned when the registration code has expired.
	ErrRegistrationCodeExpired = errors.New("registration code has expired")

	// ErrRegistrationCodeInvalid is returned when a submitted registration code is wrong.
	ErrRegistrationCodeInvalid = errors.New("invalid registration code")

	// ErrRegistrationCodeExhausted is returned when too many invalid attempts were made.
	ErrRegistrationCodeExhausted = errors.New("registration code exhausted")

	// ErrRegistrationCodeLimitExceeded is returned when too many codes are active for an email.
	ErrRegistrationCodeLimitExceeded = errors.New("too many active registration codes")

	// ErrRegistrationTokenNotFound is returned when the completion token doesn't exist.
	ErrRegistrationTokenNotFound = errors.New("registration completion token not found")

	// ErrRegistrationTokenExpired is returned when the completion token has expired.
	ErrRegistrationTokenExpired = errors.New("registration completion token has expired")
)
View Source
var (
	// ErrRefreshTokenNotFound is returned for malformed, expired, revoked, or
	// otherwise unusable refresh credentials.
	ErrRefreshTokenNotFound = errors.New("refresh token not found")
	// ErrRefreshTokenReused is returned after a stale refresh credential is
	// presented under a different rotation request and the session is revoked.
	ErrRefreshTokenReused = errors.New("refresh token reuse detected")
	// ErrRefreshRequestIDInvalid is returned when rotation has no bounded opaque
	// idempotency key.
	ErrRefreshRequestIDInvalid = errors.New("refresh request ID is invalid")
	// ErrRefreshTokenClientMismatch prevents a public client from redeeming a
	// refresh credential issued to another client.
	ErrRefreshTokenClientMismatch = errors.New("refresh token client mismatch")
)
View Source
var (
	ErrRoomGroupNotFound        = errors.New("room group not found")
	ErrRoomGroupHasRooms        = errors.New("room group has rooms; move them out before deleting")
	ErrRoomGroupNameEmpty       = errors.New("room group name must not be empty")
	ErrRoomGroupOrderMismatch   = errors.New("room group order must be a permutation of existing groups")
	ErrRoomMoveSourceChanged    = errors.New("room move source group changed")
	ErrSidebarLinkNotFound      = errors.New("sidebar link not found")
	ErrSidebarLinkSourceChanged = errors.New("sidebar link source group changed")
	ErrSidebarLinkLabelEmpty    = errors.New("sidebar link label must not be empty")
	ErrSidebarLinkURLInvalid    = errors.New("sidebar link URL must be an absolute http(s) URL or server-local path")
	ErrSidebarItemNotFound      = errors.New("sidebar item not found")
	ErrSidebarItemPlacement     = errors.New("sidebar item placement target is not in the destination group")
)

Errors specific to room-group operations.

View Source
var (
	// ErrTokenNotFound is returned when the verification code doesn't exist or has expired.
	ErrTokenNotFound = errors.New("verification code not found or expired")

	// ErrTokenExpired is returned when the verification code has expired.
	ErrTokenExpired = errors.New("verification code has expired")

	// ErrEmailVerificationCodeInvalid is returned when a submitted email verification code is wrong.
	ErrEmailVerificationCodeInvalid = errors.New("invalid email verification code")

	// ErrEmailVerificationCodeExhausted is returned when too many invalid attempts were made.
	ErrEmailVerificationCodeExhausted = errors.New("email verification code exhausted")

	// ErrEmailVerificationCodeLimitExceeded is returned when too many codes are active for an email verification challenge.
	ErrEmailVerificationCodeLimitExceeded = errors.New("too many active email verification codes")

	// ErrEmailAlreadyVerified is returned when trying to verify an email that's already verified by another user.
	ErrEmailAlreadyVerified = errors.New("email address is already verified by another account")
)
View Source
var DefaultGlobalRooms = []DefaultGlobalRoom{
	{Name: AnnouncementsRoomName, Description: "Announcements and news", Universal: true},
	{Name: "general", Description: "General discussion"},
}

DefaultGlobalRooms is the list of channel rooms seeded on a fresh deployment. Each lands in the seed "Lobby" group. Normal rooms inherit the server-tier everyone defaults; the "announcements" room is universal and adds a room-tier everyone/message.post denial and message.post grants for admins and owners.

View Source
var (
	// ErrAuthTokenNotFound is returned when a bearer auth token doesn't exist or has expired.
	ErrAuthTokenNotFound = errors.New("auth token not found")
)
View Source
var ErrAuthenticationRevoked = errors.New("authentication revoked")
View Source
var ErrBioTooLong = fmt.Errorf("bio is too long")
View Source
var (
	// ErrCannotReorderSystemRole is returned when attempting to reorder a system role.
	ErrCannotReorderSystemRole = errors.New("cannot reorder system roles")
)

RBAC-engine-specific validation errors. Errors common with the rest of core (ErrInvalidRoleName, ErrRoleNotFound, ErrRoleAlreadyExists, ErrPermissionDenied, ErrCannotDeleteSystemRole, ErrInvalidPermission) live in core/errors.go and core/rbac.go.

View Source
var (
	// ErrCannotRevokeSelfAdmin is returned when an admin tries to remove their own admin role.
	ErrCannotRevokeSelfAdmin = errors.New("cannot revoke your own admin role")
)
View Source
var ErrConfigConflict = errors.New("config was modified by another request")

ErrConfigConflict is returned when a config update fails due to concurrent modification. The OCC scope is the EVT event publish; ErrConfigConflict surfaces when retries on the publish path exhaust without success. Callers can retry the whole UpdateServerConfigFunc call.

View Source
var (
	// ErrCookieSessionNotFound is returned when a cookie session does not exist,
	// has expired, is malformed, or does not belong to the supplied user.
	ErrCookieSessionNotFound = errors.New("cookie session not found")
)
View Source
var ErrCustomStatusEmojiInvalid = fmt.Errorf("custom status emoji must be a single supported emoji")
View Source
var ErrCustomStatusEmojiRequired = fmt.Errorf("custom status emoji is required")
View Source
var ErrCustomStatusEmojiTooLong = fmt.Errorf("custom status emoji is too long")
View Source
var ErrCustomStatusExpiryInPast = fmt.Errorf("custom status expiry must be in the future")
View Source
var ErrCustomStatusTextRequired = fmt.Errorf("custom status text is required")
View Source
var ErrCustomStatusTextTooLong = fmt.Errorf("custom status text is too long")
View Source
var (
	// ErrExternalIdentityAlreadyClaimed is returned when an external identity is already linked to a different user.
	ErrExternalIdentityAlreadyClaimed = errors.New("external identity is already linked to another account")
)
View Source
var ErrExternalIdentityUnlinkDisabled = errors.New("disconnecting this sign-in provider is disabled")

ErrExternalIdentityUnlinkDisabled reports an operator restriction on self-service.

View Source
var ErrFreshAuthRequired = errors.New("fresh authentication is required")
View Source
var (
	ErrInvitationInvalid = errors.New("invitation is invalid")
)
View Source
var ErrLoginAlreadyTaken = fmt.Errorf("login name is already taken")

ErrLoginAlreadyTaken is returned when the login name is already taken.

View Source
var ErrNotificationAlertSuppressed = errors.New("notification alert suppressed")

ErrNotificationAlertSuppressed tells the durable worker that a last-moment transport check intentionally suppressed delivery and should be terminal.

View Source
var (
	ErrOAuthClientBlocked = errors.New("OAuth client is blocked")
)
View Source
var ErrPendingOAuthAuthorizeNotFound = errors.New("pending OAuth authorization request not found")
View Source
var ErrProviderUsernameUnavailable = errors.New("provider username cannot be assigned; contact the server operator")

ErrProviderUsernameUnavailable identifies a provider configuration or naming conflict that prevents managed account creation.

View Source
var ErrRoomNameExists = errors.New("a room with this name already exists on this server")

ErrRoomNameExists is returned when a room with an equivalent normalized, case-folded name already exists.

View Source
var ErrSetupRequired = errors.New("complete first-run setup before creating accounts")

ErrSetupRequired blocks public registration until the initial owner exists.

View Source
var ErrSetupUnavailable = errors.New("first-run setup is not available")

ErrSetupUnavailable means the first-run setup command is disabled or closed.

View Source
var ErrUnsupportedNotificationSignal = errors.New("unsupported notification signal")

ErrUnsupportedNotificationSignal preserves work for a newer signal shape until a binary that understands it can safely process it.

View Source
var ErrUsernameBlocked = fmt.Errorf("this username is not available")

ErrUsernameBlocked is returned when the login name is in the blocked list.

View Source
var ErrUsernameManaged = errors.New("username is managed by a sign-in provider")

ErrUsernameManaged reports that a linked provider controls username editing.

View Source
var ReservedGroupNames = []string{
	"here",
	"all",
}

ReservedGroupNames lists names that cannot be used for custom groups. These are reserved for built-in mention groups (e.g. @here, @all).

Functions

func AttachmentFromAsset

func AttachmentFromAsset(asset *evtv1.AssetRecord) *evtv1.Attachment

AttachmentFromAsset converts the Asset model into the message-facing Attachment view used by API response mapping and asset URL helpers.

func AttachmentNeedsVideoProcessing

func AttachmentNeedsVideoProcessing(attachment *evtv1.Attachment, animatedGIF bool) bool

AttachmentNeedsVideoProcessing returns whether an attachment should enter the video processing pipeline. Static GIFs stay image-only; callers that inspect the upload bytes can set animatedGIF for GIF-to-MP4 conversion.

func AuditRequestMetadataFromContext

func AuditRequestMetadataFromContext(ctx context.Context) *evtv1.AuditRequestMetadata

AuditRequestMetadataFromContext returns a copy of request audit metadata from ctx, if present. Missing metadata is normal for non-HTTP callers.

func CanonicalContentType

func CanonicalContentType(declared string) (string, bool)

CanonicalContentType parses a declared content type and returns it with a lowercase media type and canonically formatted parameters. It returns FallbackContentType and false for a missing or unparseable value.

Uploads store only canonical values, and attachment responses send only canonical values. Browsers must never receive a malformed type that Go and the browser could interpret differently, such as "text/html,".

func DMRoomID

func DMRoomID(participantIDs []string) string

DMRoomID generates a deterministic room ID from participant IDs. The same set of participants always produces the same room ID, regardless of order. This enables find-or-create semantics without database queries.

func DeletedUserReference

func DeletedUserReference(userID string) *readmodel.User

func DeprecatedAssetFromAsset

func DeprecatedAssetFromAsset(asset *evtv1.AssetRecord) *evtv1.DeprecatedAsset

func EffectiveRoomThreadingMode

func EffectiveRoomThreadingMode(room *readmodel.Room) evtv1.RoomThreadingMode

EffectiveRoomThreadingMode normalizes persisted room data. Historical channel events predate the field and therefore resolve UNSPECIFIED to ENABLED. DMs always use ENABLED. Unknown future channel values fail closed to DISABLED.

func EffectiveThreadSlowModeSeconds

func EffectiveThreadSlowModeSeconds(room *readmodel.Room) uint32

EffectiveThreadSlowModeSeconds preserves the interval of legacy room facts. New configuration facts store an explicit thread interval, including zero.

func EncryptionKeysConfig

func EncryptionKeysConfig(replicas int) jetstream.KeyValueConfig

EncryptionKeysConfig is the ENCRYPTION_KEYS bucket configuration. The server and `chatto keys import` must create the bucket identically. The bucket is excluded from backups for security.

func EventMessageEdited

func EventMessageEdited(event EventEnvelope) *evtv1.MessageEditedEvent

func EventMessagePosted

func EventMessagePosted(event EventEnvelope) *evtv1.MessagePostedEvent

func EventMessageRetracted

func EventMessageRetracted(event EventEnvelope) *evtv1.MessageRetractedEvent

func EventSessionTerminated

func EventSessionTerminated(event EventEnvelope) *pubsubv1.SessionTerminatedEvent

func EventUserTyping

func EventUserTyping(event EventEnvelope) *realtimev1.UserTypingEvent

func ExtractMentionUsernames

func ExtractMentionUsernames(body string) []string

ExtractMentionUsernames extracts all unique @username mentions from a message body. Returns a slice of usernames (without the @ prefix) in the order they appear. Duplicate mentions are deduplicated. Mentions inside Markdown code spans, code blocks, blockquotes, links, and URLs are ignored.

The bundled frontend renders mentions with the same rules (see apps/frontend/src/lib/markdownMentions.ts), so a message notifies exactly the handles that it shows as mentions. The shared cases in testdata/mentions/extraction.json test both implementations.

func GenerateCodeChallenge

func GenerateCodeChallenge(verifier string) string

GenerateCodeChallenge computes the S256 code challenge for a given verifier. This is a convenience for tests; clients compute this themselves.

func HasVisibleContent

func HasVisibleContent(s string) bool

HasVisibleContent returns true if the string contains at least one visible character. A visible character is one that is not whitespace, not a format character (Cf), and not a control character (Cc).

This is used to validate message content, rejecting messages that contain only invisible Unicode characters like zero-width spaces (U+200B), zero-width joiners (U+200C, U+200D), soft hyphens (U+00AD), word joiners (U+2060), etc.

func HistoricalEmojiName

func HistoricalEmojiName(unicode string) (string, error)

HistoricalEmojiName selects a stable bundled shortcode without changing the Unicode sequence. Unknown sequences fail preflight rather than lose a reaction.

func HistoricalReactionName

func HistoricalReactionName(input string) (string, error)

HistoricalReactionName preserves valid reaction names and converts supported Unicode emoji from existing archives with the historical selection rule.

func ImageCacheKey

func ImageCacheKey(spaceID, attachmentID string, width, height int, fit string) string

ImageCacheKey generates a cache key for a resized image. Format: {spaceId}.{attachmentId}.{paramsHash} Uses NATS subject notation (dots as separators).

func IsCallMediaPublisher

func IsCallMediaPublisher(metadata string) bool

IsCallMediaPublisher reports whether metadata belongs to a native companion publisher rather than a Chatto call participant.

func IsNoSuchKeyError

func IsNoSuchKeyError(err error) bool

IsNoSuchKeyError reports whether err came from S3 returning a definitive "object does not exist" response (404 / NoSuchKey). All other errors — network failures, timeouts, auth errors, misconfigured endpoint — return false so callers can distinguish "we know it's gone" from "we can't tell".

func IsRBACEvent

func IsRBACEvent(event *evtv1.Event) bool

IsRBACEvent reports whether event changes roles or permission resolution. The public realtime protocol uses this to invalidate authorization-dependent client state without exposing the internal RBAC payload.

func IsReservedGroupName

func IsReservedGroupName(name string) bool

IsReservedGroupName reports whether the given name is reserved and cannot be used as a custom group name.

func IsSystemRole

func IsSystemRole(name string) bool

IsSystemRole returns true if the role name is a system role that cannot be deleted. Custom roles must avoid these names.

func IsUserSubject

func IsUserSubject(subject string) bool

IsUserSubject reports whether an RBAC subject is a user ID. User IDs start with the U prefix. Other subject values identify roles.

func IsValidReactionName

func IsValidReactionName(name string) bool

IsValidReactionName accepts 1–128 ASCII letters, digits, underscores, plus signs, or hyphens. Names are case-sensitive and need not be in the bundled catalogue. Slack-style skin-tone suffixes are accepted only for complete sequences in the shared catalogue. Validation preserves stored identity.

func IsValidRoomThreadingMode

func IsValidRoomThreadingMode(mode evtv1.RoomThreadingMode) bool

IsValidRoomThreadingMode reports whether mode is an explicit channel-room policy. UNSPECIFIED is reserved for omitted historical data and DMs.

func IsValidUnicodeEmoji

func IsValidUnicodeEmoji(emoji string) bool

IsValidUnicodeEmoji reports whether emoji is one complete emoji from the bundled gemoji and Unicode skin-tone datasets. This includes flags and family sequences, while rejecting arbitrary text and multiple adjacent emoji.

func IsVirtualMentionHandle

func IsVirtualMentionHandle(handle string) bool

IsVirtualMentionHandle reports whether a handle is owned by Chatto rather than by a user or role. Handles are matched case-insensitively.

func IsVisibleRoomTimelineEntry

func IsVisibleRoomTimelineEntry(event *evtv1.Event) bool

IsVisibleRoomTimelineEntry reports whether an event should surface in the public room timeline.

func JobsConsumerConfig

func JobsConsumerConfig(q *jobqueue.Queue, kind string) jetstream.ConsumerConfig

JobsConsumerConfig is the application-owned configuration of the JOBS consumer of one job type. A job that waits for a retry holds an unacknowledged delivery, so pending acknowledgements have no limit; the worker pool bounds running jobs.

The acknowledgement wait is how long a job waits after a worker crash. It is two minutes, but one minute for notification alerts: an alert expires two minutes after its source, so a longer wait would always lose the alert.

func JobsConsumerName

func JobsConsumerName(kind string) string

JobsConsumerName returns the durable JOBS consumer of one job type. Each type has its own consumer and worker pool, so one type cannot delay another.

func LegacySpaceIDForRoomKind

func LegacySpaceIDForRoomKind(kind RoomKind) string

LegacySpaceIDForRoomKind returns the wire-format-frozen `space_id` value for a room kind. Use this only when filling legacy payload fields or calling APIs whose storage keys still include `space_id`.

func LiveKitRoomName

func LiveKitRoomName(serverID string, kind RoomKind, roomID string, callID ...string) string

LiveKitRoomName constructs a deterministic LiveKit room name from a room kind and room ID while preserving the legacy space token in LiveKit's wire name. When serverID is non-empty, the room name is prefixed with "{serverID}." so the webhook bridge can route events to the correct Chatto server in shared deployments. Authorization: Caller must verify room membership before calling.

func LoginDisplayName

func LoginDisplayName(login string) string

LoginDisplayName returns a default display name that fits the display-name limit. Valid logins contain only ASCII characters.

func MediaJobHandler

func MediaJobHandler(logger *log.Logger, process func(ctx context.Context, assetID, messageID string) error) jobqueue.Handler

MediaJobHandler decodes a media job and runs process for its asset. Server replicas and standalone media processes share it. The queue stores only a failure category, so the handler logs the cause of each failed attempt.

func MessageAuthorID

func MessageAuthorID(event *evtv1.Event) string

MessageAuthorID returns the displayed author of a message, or the event actor for other facts. Historical imports retain the operator in the event envelope for audit.

func ModelKeys

func ModelKeys() []string

ModelKeys returns the stable metric keys in the core model inventory.

func NewAccountDeletionToken

func NewAccountDeletionToken() string

NewAccountDeletionToken generates a new account deletion confirmation token with "AD" prefix.

func NewAssetID

func NewAssetID() string

NewAssetID generates a new asset ID with "A" prefix.

func NewAuthCode

func NewAuthCode() string

NewAuthCode generates a new OAuth authorization code with "cht_AC" prefix.

func NewAuthToken

func NewAuthToken() string

NewAuthToken generates a new bearer auth token with "cht_AT" prefix. The "cht_" prefix makes tokens recognizable in logs and password managers.

func NewBotAPIKey

func NewBotAPIKey(botUserID string) (string, error)

NewBotAPIKey creates the sole show-once API key for a bot. The stable bot ID in the prefix lets authentication select one aggregate without maintaining a separate mutable lookup index; the random secret remains unpersisted.

func NewBotAPIKeyID

func NewBotAPIKeyID() string

NewBotAPIKeyID generates a stable opaque API-key credential ID.

func NewBotIncomingWebhookCredentialForID

func NewBotIncomingWebhookCredentialForID(botUserID, webhookID string) (string, error)

NewBotIncomingWebhookCredentialForID creates a show-once action credential that identifies one bot and one of its incoming webhooks.

func NewBotIncomingWebhookID

func NewBotIncomingWebhookID() string

NewBotIncomingWebhookID generates a stable opaque webhook credential ID.

func NewBotOutboundWebhookID

func NewBotOutboundWebhookID() string

NewBotOutboundWebhookID generates a stable opaque outbound endpoint ID.

func NewCallID

func NewCallID() string

NewCallID generates a new voice call session ID with "C" prefix.

func NewCallMediaPublisherID

func NewCallMediaPublisherID() string

NewCallMediaPublisherID generates an opaque LiveKit companion-publisher ID with a distinct prefix so it can never collide with a user identity.

func NewEventID

func NewEventID() string

NewEventID generates a new event ID with "E" prefix.

func NewExternalIdentityCreateToken

func NewExternalIdentityCreateToken() string

NewExternalIdentityCreateToken generates a pending external-identity account creation token.

func NewExternalIdentityLinkStartToken

func NewExternalIdentityLinkStartToken() string

NewExternalIdentityLinkStartToken generates a provider-link browser handoff token.

func NewExternalIdentityLinkToken

func NewExternalIdentityLinkToken() string

NewExternalIdentityLinkToken generates a pending external-identity account linking token.

func NewInvitationID

func NewInvitationID() string

NewInvitationID generates a new invitation ID with "I" prefix.

func NewJobQueue

func NewJobQueue(js jetstream.JetStream, stream jetstream.Stream, failedRetention time.Duration, logger *log.Logger, onFailed func(context.Context, jobqueue.Job)) (*jobqueue.Queue, error)

NewJobQueue binds Chatto's job queue contract to the JOBS stream. failedRetention is core.job_failed_retention: zero keeps failed jobs until an operator retries or deletes them. Every process that runs jobs must use the same value. onFailed may be nil.

func NewLinkPreviewToken

func NewLinkPreviewToken() string

NewLinkPreviewToken generates a composer link-preview token with "cht_LP" prefix.

func NewNeighborID

func NewNeighborID() string

NewNeighborID generates a stable opaque Neighbor resource ID.

func NewPasswordResetToken

func NewPasswordResetToken() string

NewPasswordResetToken generates a new password reset token with "PR" prefix.

func NewPendingOAuthAuthorizeToken

func NewPendingOAuthAuthorizeToken() string

NewPendingOAuthAuthorizeToken generates an opaque browser-flow handle.

func NewRegistrationToken

func NewRegistrationToken() string

NewRegistrationToken generates a new registration completion token with "RG" prefix.

func NewRoomGroupID

func NewRoomGroupID() string

NewRoomGroupID generates a new room-group ID with "G" prefix.

func NewRoomID

func NewRoomID() string

NewRoomID generates a new room ID with "R" prefix.

func NewSidebarLinkID

func NewSidebarLinkID() string

NewSidebarLinkID generates a new sidebar-link ID with "L" prefix.

func NewUserID

func NewUserID() string

NewUserID generates a new user ID with "U" prefix.

func NewVerificationCode

func NewVerificationCode() (string, error)

NewVerificationCode generates a six-digit numeric code for email verification.

func NormalizeDisplayName

func NormalizeDisplayName(name string) string

NormalizeDisplayName trims surrounding whitespace. Use ValidateDisplayName after normalizing.

func NormalizeProviderUsername

func NormalizeProviderUsername(username string) string

NormalizeProviderUsername preserves the provider's name apart from surrounding whitespace and case. It never substitutes an email address or display name.

func NotificationAlertDeadline

func NotificationAlertDeadline(occurrence *notificationv1.NotificationOccurrence) time.Time

func NotificationAlertPending

func NotificationAlertPending(occurrence *notificationv1.NotificationOccurrence) bool

NotificationAlertPending reports whether an occurrence still has unresolved interruptive delivery work.

func NotificationOccurrenceHasUnsupportedSignal

func NotificationOccurrenceHasUnsupportedSignal(occurrence *notificationv1.NotificationOccurrence) bool

func NotificationOccurrenceMessageReference

func NotificationOccurrenceMessageReference(occurrence *notificationv1.NotificationOccurrence) *notificationv1.NotificationMessageReference

NotificationOccurrenceMessageReference returns the exact message target for a signal understood by this server version.

func NotificationOccurrenceRoomID

func NotificationOccurrenceRoomID(occurrence *notificationv1.NotificationOccurrence) string

NotificationOccurrenceRoomID returns the room destination for either message activity or an invitation, without inventing a message target.

func OAuthConsentKey

func OAuthConsentKey(clientID, redirectOrigin string) string

OAuthConsentKey returns the stable client identity used for consent. Legacy origin-only flows retain their origin key until the 0.5 transport cutover.

func OAuthConsentOrigin

func OAuthConsentOrigin(redirectOrigin string) string

func OAuthScopedConsentKey

func OAuthScopedConsentKey(clientID, redirectOrigin, resource string, scopes []string) string

OAuthScopedConsentKey returns the stable identity for an exact delegated grant. Empty resource and scope values retain the legacy client key.

func ParseLiveKitRoomIdentity

func ParseLiveKitRoomIdentity(lkRoomName string) (legacySpaceID, roomID, callID string)

ParseLiveKitRoomIdentity extracts the legacy space token, room ID, and optional Chatto call ID from a LiveKit room name. New room names append "@{callId}" so LiveKit room_finished events can be tied to one Chatto call session; names without a suffix are accepted for compatibility with older active LiveKit rooms.

func ParseLiveKitRoomServerID

func ParseLiveKitRoomServerID(lkRoomName string) string

ParseLiveKitRoomServerID extracts just the server ID prefix from a LiveKit room name. Returns empty string if no prefix is present (unprefixed format).

func ParseParticipantMetadata

func ParseParticipantMetadata(metadata string) participantMetadata

ParseParticipantMetadata parses JSON metadata from a LiveKit participant. Returns zero-value struct if metadata is empty or invalid.

func PermissionAppliesAtScope

func PermissionAppliesAtScope(perm Permission, scope PermissionScope) bool

PermissionAppliesAtScope checks if a permission can be configured at a given scope.

func PresentableDisplayName

func PresentableDisplayName(displayName, login string) string

PresentableDisplayName returns the display name that read paths show for a stored name. If a name stored under earlier rules is empty, too long, or invalid now, the login is shown instead. Old names cannot bypass rules that apply to new edits.

func ProtoKindForRoomKind

func ProtoKindForRoomKind(kind RoomKind) evtv1.RoomKind

ProtoKindForRoomKind maps the Go-side RoomKind string to the proto enum stored on Room.kind.

func ProviderCanReverify

func ProviderCanReverify(provider config.AuthProviderConfig, identities []ExternalIdentity) bool

ProviderCanReverify reports whether provider can confirm a recent sign-in of the user with identities. Only OpenID Connect can force a new provider sign-in (prompt=login, max_age=0) and prove it with auth_time. Other provider types can pass an existing provider session through silently.

func PublicServerAssetObjectKey

func PublicServerAssetObjectKey(assetID string) string

PublicServerAssetObjectKey returns the NATS object key for a new public server asset while keeping its logical asset ID stable.

func S3KeyAttachment

func S3KeyAttachment(attachmentID string) string

S3KeyAttachment returns the S3 key for an attachment uploaded after ADR-030 Phase 4. Format: attachments/{attachmentId}. Pre-Phase-4 attachments live at `spaces/{server|DM}/attachments/{id}`; that key shape is no longer constructed by Go code — the canonical key for every attachment comes from `Attachment.Storage.S3.Key` on the proto.

func S3KeyServerAsset

func S3KeyServerAsset(assetID string) string

S3KeyServerAsset returns the S3 key for a server asset (avatar, logo, banner, link preview image). Format: instance/{assetId} This matches the NATS key format so HTTP handlers can probe both backends with the same key.

func ServerAssetDeliveryKey

func ServerAssetDeliveryKey(asset *evtv1.AssetRecord) string

ServerAssetDeliveryKey returns the storage-aware key used in public server asset URLs. New NATS assets carry their explicit public/ object key, while S3 and historical records continue to use their logical asset ID.

func UserIDOfPublicProfileEvent

func UserIDOfPublicProfileEvent(event *evtv1.Event) string

UserIDOfPublicProfileEvent returns the user whose public resource changed. It intentionally accepts historical granular profile facts and the current user-scoped avatar fact so all of them map to one public hydration hint.

func ValidateDisplayName

func ValidateDisplayName(name string) error

ValidateDisplayName accepts single-line Unicode presentation text. A name must contain a letter, number, punctuation mark, or symbol, not just combining marks or whitespace. Joiners and emoji tags are the only permitted format characters. Block mosaic glyphs (see isDisplayNameMosaicGlyph) are rejected. Callers trim the name and check its length in Unicode code points separately. An empty name is permitted here for creation paths that default to the login; profile update paths reject empty names before they call this function.

func ValidateLogin

func ValidateLogin(login string, maxLength int) error

ValidateLogin validates a login/username for allowed characters and length. Allowed: ASCII letters, digits, periods, underscores, hyphens. Must start with a letter or digit and must not end with a period. Length: MinLoginLength to maxLength characters.

func ValidatePassword

func ValidatePassword(password string) error

ValidatePassword validates that a password meets length requirements. Length is measured in UTF-8 bytes, not Unicode characters. The upper bound matches the maximum input length accepted by Go bcrypt.

func ValidatePermission

func ValidatePermission(perm Permission) error

ValidatePermission checks if a permission value is valid.

func ValidatePermissionString

func ValidatePermissionString(perm string) error

ValidatePermissionString checks if a string is a valid permission.

func ValidateRoleName

func ValidateRoleName(name string) error

ValidateRoleName checks if a role name is valid. Valid names: lowercase letters / digits / dashes, starting with a letter, 1-32 characters, no leading or trailing dash.

func ValidateRoomDescription

func ValidateRoomDescription(description string) error

ValidateRoomDescription validates a room description and returns an error if invalid.

func ValidateRoomName

func ValidateRoomName(name string) error

ValidateRoomName validates a room name and returns an error if invalid. Room names accept visible Unicode text but reject controls and line-breaking separators that would disrupt user-interface layout.

func WithAuditRequestMetadata

func WithAuditRequestMetadata(ctx context.Context, metadata *evtv1.AuditRequestMetadata) context.Context

WithAuditRequestMetadata attaches security-safe request metadata to ctx for auth workflow audit events. The metadata is copied so callers can reuse their input struct without mutating future event payloads.

func WithDEKRequestCache

func WithDEKRequestCache(ctx context.Context) context.Context

WithDEKRequestCache returns a child context that caches unwrapped DEKs for one request or batch operation. The cache is intentionally not process-wide: once a DEK record has been physically shredded from the shared store, later requests fail closed instead of using a stale in-memory key.

func WithStrictAuthGenerationCheck

func WithStrictAuthGenerationCheck(ctx context.Context) context.Context

WithStrictAuthGenerationCheck returns a context in which every auth generation check is strict, also in the first pass of request validation. The periodic credential validation of a realtime connection uses it, so a connection on a replica that is behind cannot stay open for one timer interval plus one window (ADR-127 section 5).

Types

type AccountDeletionToken

type AccountDeletionToken struct {
	UserID    string    `json:"user_id"`
	CreatedAt time.Time `json:"created_at"`
}

AccountDeletionToken represents a token used to confirm account deletion.

type AccountInfo

type AccountInfo struct {
	Memory        uint64
	MemoryUsed    uint64
	Storage       uint64
	StorageUsed   uint64
	Streams       int
	StreamsUsed   int
	Consumers     int
	ConsumersUsed int
}

AccountInfo contains JetStream account limits and usage.

type AdminCreateUserRequest

type AdminCreateUserRequest struct {
	Login         string
	DisplayName   string
	Password      string
	VerifiedEmail string
	RoleNames     []string
}

AdminCreateUserRequest describes one operator-created user.

type AdminDiagnostics

type AdminDiagnostics struct {
	Connection           *ConnectionInfo
	Account              *AccountInfo
	Stats                *ServerStats
	JetStream            *JetStreamStats
	Projections          []ProjectionAdminState
	ProjectionsAvailable bool
	AssetCleanup         AssetCleanupAdminStatus
	DurableWorkers       []DurableWorkerAdminStatus
	LiveKit              LiveKitAdminStatus
}

type AdminMember

type AdminMember struct {
	ID          string
	Login       string
	DisplayName string
	// Bio is the user's public biography. Empty means unset.
	Bio string
	// SharedTimezone is public only while the user enables time-zone sharing.
	SharedTimezone              string
	AvatarURL                   string
	Roles                       []string
	CreatedAt                   *timestamppb.Timestamp
	Deleted                     bool
	Deactivated                 bool
	ViewerCanChangeDeactivation bool
	IsBot                       bool
	// BotOwnerUserID identifies the human owner of a bot.
	BotOwnerUserID   string
	HasVerifiedEmail bool
	VerifiedEmails   []string
	// PrimaryVerifiedEmail is empty when no primary address is visible.
	PrimaryVerifiedEmail   string
	ViewerCanDeleteAccount bool
	LastLoginChange        *time.Time
	CustomStatus           *evtv1.CustomUserStatus
}

type AdminMemberDetails

type AdminMemberDetails struct {
	Member                         *AdminMember
	Roles                          []AdminMemberRoleSummary
	AvailablePermissions           []Permission
	ViewerCanAssignRoles           bool
	ViewerCanManageRoles           bool
	ViewerCanManageUserPermissions bool
	AssignableRoleNames            []string
	RevocableRoleNames             []string
}

type AdminMemberIDPage

type AdminMemberIDPage struct {
	UserIDs    []string
	TotalCount int
	HasMore    bool
}

AdminMemberIDPage selects members without hydrating administrative fields.

type AdminMemberList

type AdminMemberList struct {
	Users      []AdminMember
	Roles      []AdminMemberRoleSummary
	TotalCount int
	HasMore    bool
}

type AdminMemberListInput

type AdminMemberListInput struct {
	Search string
	Limit  int
	Offset int
}

type AdminMemberRoleSummary

type AdminMemberRoleSummary struct {
	Name               string
	DisplayName        string
	Description        string
	IsSystem           bool
	Position           int32
	Pingable           bool
	RequiresShieldMode bool
}

type AdminRoleInput

type AdminRoleInput struct {
	RequiresShieldMode bool
	Name               string
	DisplayName        string
	Description        string
	Pingable           *bool
}

type AdminRoleUpdateInput

type AdminRoleUpdateInput struct {
	RequiresShieldMode *bool
	Name               string
	DisplayName        *string
	Description        *string
	Pingable           *bool
}

type AdminRoomGroupManagementDetails

type AdminRoomGroupManagementDetails struct {
	Group                *readmodel.RoomGroup
	CanManageGroup       bool
	CanManagePermissions bool
}

type AdminRoomManagementDetails

type AdminRoomManagementDetails struct {
	Room                 *readmodel.Room
	CanManageRoom        bool
	CanManagePermissions bool
}

type AdminUpdateOperatorUserRequest

type AdminUpdateOperatorUserRequest struct {
	UserID      string
	Login       *string
	DisplayName *string
}

AdminUpdateOperatorUserRequest describes one operator profile update.

type AdminUserList

type AdminUserList struct {
	Users      []*AdminUserView
	TotalCount int
	HasMore    bool
}

AdminUserList is a paginated operator user listing.

type AdminUserView

type AdminUserView struct {
	User           *readmodel.User
	RoleNames      []string
	VerifiedEmails []VerifiedEmail
}

AdminUserView is the core representation returned by operator user administration workflows.

type AssetCleanupAdminStatus

type AssetCleanupAdminStatus struct {
	Health               AssetCleanupHealth
	PendingCount         int
	OldestPendingAt      time.Time
	PassInProgress       bool
	LastPassAt           time.Time
	LastSuccessfulPassAt time.Time
	UpdatedAt            time.Time
	LastPassFailed       bool
	LastInspectedSeq     uint64
	LatestDeletionSeq    uint64
}

type AssetCleanupHealth

type AssetCleanupHealth int
const (
	AssetCleanupHealthInactive AssetCleanupHealth = iota
	AssetCleanupHealthInitializing
	AssetCleanupHealthHealthy
	AssetCleanupHealthRetrying
	AssetCleanupHealthStalled
	AssetCleanupHealthUnavailable
)

type AssetModel

type AssetModel struct {
	*ChattoCore
	// contains filtered or unexported fields
}

AssetModel owns durable asset lifecycle facts and invariants.

MediaModel owns bytes, URLs, transforms, and caches. AssetModel owns the event-sourced asset aggregate: creation facts, processing transitions, tombstones, derivative cleanup ordering, and projection read-your-writes.

func NewAssetModel

func NewAssetModel(core *ChattoCore, assets events.ProjectionHandle[*AssetProjection]) *AssetModel

func (*AssetModel) AdminCleanupStatus

func (s *AssetModel) AdminCleanupStatus(ctx context.Context) (AssetCleanupAdminStatus, error)

AdminCleanupStatus derives shared queue health directly from JetStream. Pending work is the deletions that the source consumer has not handed to the job queue, plus the cleanup jobs that have not finished, including jobs that wait for a retry. Pass-oriented fields are retained for API compatibility but remain unknown for continuously delivered durable work.

func (*AssetModel) AssetCreation

func (s *AssetModel) AssetCreation(assetID string) (*evtv1.AssetCreatedEvent, bool)

func (*AssetModel) AssetDeleted

func (s *AssetModel) AssetDeleted(assetID string) bool

func (*AssetModel) AssetMessageOwner

func (s *AssetModel) AssetMessageOwner(assetID string) (roomID, messageEventID string, ok bool)

func (*AssetModel) AssetRoomID

func (s *AssetModel) AssetRoomID(assetID string) (string, bool)

func (*AssetModel) AssetState

func (s *AssetModel) AssetState(assetID string) AssetState

func (*AssetModel) AssetSubtreeIDs

func (s *AssetModel) AssetSubtreeIDs(assetID string) []string

func (*AssetModel) DeleteAsset

func (s *AssetModel) DeleteAsset(ctx context.Context, actorID, assetID string) error

DeleteAsset appends an AssetDeletedEvent for a projected asset.

func (*AssetModel) DeleteMessageOwnedAssetsForUser

func (s *AssetModel) DeleteMessageOwnedAssetsForUser(ctx context.Context, actorID, userID string) int

DeleteMessageOwnedAssetsForUser removes every currently projected message-owned asset for userID, including derivative children such as video thumbnails and variants. AssetDeletedEvent is appended before the backing bytes are removed so serving paths stop resolving the asset even if storage cleanup is slow or partially fails.

func (*AssetModel) DeleteVideoDerivativesForAttachment

func (s *AssetModel) DeleteVideoDerivativesForAttachment(ctx context.Context, actorID string, attachmentID string)

DeleteVideoDerivativesForAttachment deletes generated thumbnail/variant binaries for a processed video attachment and emits AssetDeletedEvent for each derivative. The durable processing manifest remains in EVT for audit/replay; deletion makes future signed URLs resolve to 404.

func (*AssetModel) IsPublicLinkPreviewAsset

func (s *AssetModel) IsPublicLinkPreviewAsset(assetID string) bool

func (*AssetModel) MessageAssetOwners

func (s *AssetModel) MessageAssetOwners() []MessageAssetRef

func (*AssetModel) MessageAssetsByAuthor

func (s *AssetModel) MessageAssetsByAuthor(userID string) []MessageAssetRef

func (*AssetModel) MessageOwnsAsset

func (s *AssetModel) MessageOwnsAsset(ctx context.Context, roomID, messageEventID, assetID string) (bool, error)

MessageOwnsAsset waits for the complete asset aggregate and verifies the durable attachment before a message path touches derivatives or backing storage.

func (*AssetModel) MessageTombstoned

func (s *AssetModel) MessageTombstoned(eventID string) bool

func (*AssetModel) PendingExpiredAssets

func (s *AssetModel) PendingExpiredAssets(now time.Time) []*evtv1.AssetCreatedEvent

func (*AssetModel) PublishAssetProcessing

func (s *AssetModel) PublishAssetProcessing(ctx context.Context, roomID string, event *evtv1.Event) error

PublishAssetProcessing appends a durable asset-processing event to EVT. Refuses events with an empty ActorId; every asset lifecycle event must be attributable to a user or SystemActorID.

func (*AssetModel) RecordAssetDeleted

func (s *AssetModel) RecordAssetDeleted(ctx context.Context, actorID string, roomID, assetID string) error

RecordAssetDeleted appends a durable AssetDeletedEvent in the asset aggregate.

func (*AssetModel) RecordAssetProcessed

func (s *AssetModel) RecordAssetProcessed(ctx context.Context, actorID string, roomID, messageEventID, attachmentID string, durationMs int64, width, height int32, thumbnail *evtv1.Attachment, variants []*runtimestatev1.VideoVariant) error

RecordAssetProcessed builds and publishes a durable processed-video manifest for an original video attachment. If the terminal manifest is skipped because another terminal/deleted state already won, it makes a bounded best-effort attempt to tombstone and storage-clean the unused output.

func (*AssetModel) RecordAssetProcessedWithHLS

func (s *AssetModel) RecordAssetProcessedWithHLS(ctx context.Context, actorID string, roomID, messageEventID, attachmentID string, durationMs int64, width, height int32, thumbnail *evtv1.Attachment, variants []*runtimestatev1.VideoVariant, hls *evtv1.AssetProcessedHLS) error

RecordAssetProcessedWithHLS publishes a terminal video manifest containing the compatibility MP4 renditions and, when generated, one HLS generation.

func (*AssetModel) RecordAssetProcessingFailed

func (s *AssetModel) RecordAssetProcessingFailed(ctx context.Context, actorID string, roomID, messageEventID, attachmentID string, failureCode evtv1.AssetProcessingFailureCode) error

RecordAssetProcessingFailed builds and publishes a durable failed video-processing outcome.

func (*AssetModel) RecordAssetProcessingStarted

func (s *AssetModel) RecordAssetProcessingStarted(ctx context.Context, actorID string, roomID, messageEventID, assetID string) error

RecordAssetProcessingStarted appends a durable AssetProcessingStartedEvent.

func (*AssetModel) RecordDerivativeAsset

func (s *AssetModel) RecordDerivativeAsset(ctx context.Context, parentAssetID string, derivativeRole evtv1.AssetDerivativeRole, roomID string, attachment *evtv1.Attachment) error

RecordDerivativeAsset writes the AssetCreatedEvent for a worker-generated derivative such as a thumbnail or transcoded variant.

func (*AssetModel) RecordExpiredPendingAssetDeleted

func (s *AssetModel) RecordExpiredPendingAssetDeleted(ctx context.Context, roomID, assetID string, now time.Time) (bool, error)

RecordExpiredPendingAssetDeleted atomically rechecks that an expired upload remains unattached before tombstoning it.

func (*AssetModel) RecordMessageAssetDeleted

func (s *AssetModel) RecordMessageAssetDeleted(ctx context.Context, actorID, roomID, messageEventID, assetID string) (bool, error)

RecordMessageAssetDeleted appends a tombstone only while the durable asset attachment still names the supplied room and message.

func (*AssetModel) RecordUploadedAsset

func (s *AssetModel) RecordUploadedAsset(ctx context.Context, actorID, roomID string, attachment *evtv1.Attachment) error

RecordUploadedAsset writes the AssetCreatedEvent for a user-uploaded binary.

func (*AssetModel) RecordUploadedPendingAttachmentAsset

func (s *AssetModel) RecordUploadedPendingAttachmentAsset(ctx context.Context, actorID, roomID string, attachment *evtv1.Attachment, sha256 string, pendingExpiresAt time.Time, needsVideoProcessing bool) error

RecordUploadedPendingAttachmentAsset writes the AssetCreatedEvent for an attachment produced by the public chunked upload flow. The pending expiry is a cleanup hint until a message attaches the asset.

func (*AssetModel) RecoverUnmanifestedVideoAttachments

func (s *AssetModel) RecoverUnmanifestedVideoAttachments(ctx context.Context)

RecoverUnmanifestedVideoAttachments backfills durable queue markers for message attachments committed by versions that scheduled processing only after the message append. New message writes commit the marker atomically.

func (*AssetModel) Run

func (s *AssetModel) Run(ctx context.Context) error

Run hands asset deletion facts to the shared job queue, which performs the recoverable physical cleanup.

func (*AssetModel) ScheduleVideoProcessingForMessageAttachment

func (s *AssetModel) ScheduleVideoProcessingForMessageAttachment(ctx context.Context, actorID string, roomID, messageEventID string, attachment *evtv1.Attachment) error

ScheduleVideoProcessingForMessageAttachment durably enqueues processing for a message-owned video asset. Runtime-unit workers consume the resulting AssetProcessingStartedEvent from a shared JetStream consumer.

func (*AssetModel) UnmanifestedVideoAttachments

func (s *AssetModel) UnmanifestedVideoAttachments() []VideoProcessingRequest

func (*AssetModel) VideoAttachmentManifest

func (s *AssetModel) VideoAttachmentManifest(assetID string) (*VideoAttachmentManifest, bool)

type AssetProcessingRuntime

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

AssetProcessingRuntime is the deliberately small core boundary needed by asset-processing workers. It opens existing asset/EVT resources, owns one AssetProjection, and exposes media and asset lifecycle operations without starting ChattoCore or its boot-time mutations.

func NewAssetProcessingRuntime

func NewAssetProcessingRuntime(
	ctx context.Context,
	nc *nats.Conn,
	js jetstream.JetStream,
	cfg config.CoreConfig,
	logger *log.Logger,
) (*AssetProcessingRuntime, error)

NewAssetProcessingRuntime opens the resources used by a worker. The main app owns resource creation; standalone workers therefore expect EVT and SERVER_ASSETS to exist already. Generated media bypasses user upload limits.

func (*AssetProcessingRuntime) AssetState

func (r *AssetProcessingRuntime) AssetState(assetID string) AssetState

AssetState returns the worker's projected lifecycle view.

func (*AssetProcessingRuntime) Core

Core returns the narrow ChattoCore facade used by the existing media processor. Only asset/media methods are initialized on this instance.

func (*AssetProcessingRuntime) Run

Run maintains the worker's private AssetProjection until shutdown.

func (*AssetProcessingRuntime) WaitForStartup

func (r *AssetProcessingRuntime) WaitForStartup(ctx context.Context) error

WaitForStartup waits until historical EVT replay has completed.

type AssetProjection

type AssetProjection struct {
	events.MemoryProjection
	// contains filtered or unexported fields
}

AssetProjection owns durable asset lifecycle and message-ownership state. New lifecycle writes live under evt.asset.{assetId}.*, including the exclusive message attachment. Message bodies remain a first-reference fallback for histories written before attachment events existed. The projection also consumes legacy evt.room.*.asset_* lanes so beta histories replay.

func NewAssetProjection

func NewAssetProjection() *AssetProjection

func (*AssetProjection) Apply

func (p *AssetProjection) Apply(event *evtv1.Event, seq uint64) error

func (*AssetProjection) AssetCreation

func (p *AssetProjection) AssetCreation(assetID string) (*evtv1.AssetCreatedEvent, bool)

func (*AssetProjection) AssetDeleted

func (p *AssetProjection) AssetDeleted(assetID string) bool

func (*AssetProjection) AssetMessageOwner

func (p *AssetProjection) AssetMessageOwner(assetID string) (roomID, messageEventID string, ok bool)

AssetMessageOwner returns the room and message to which assetID was first attached in durable message history. Ownership survives asset deletion so a deletion event can still be routed to the timeline row whose attachment changed.

func (*AssetProjection) AssetRoomID

func (p *AssetProjection) AssetRoomID(assetID string) (string, bool)

func (*AssetProjection) AssetState

func (p *AssetProjection) AssetState(assetID string) AssetState

func (*AssetProjection) AssetSubtreeIDs

func (p *AssetProjection) AssetSubtreeIDs(assetID string) []string

func (*AssetProjection) CompleteStartupReplay

func (p *AssetProjection) CompleteStartupReplay()

func (*AssetProjection) IsPublicLinkPreviewAsset

func (p *AssetProjection) IsPublicLinkPreviewAsset(assetID string) bool

IsPublicLinkPreviewAsset reports whether durable message history references assetID as a server-fetched public link-preview image.

func (*AssetProjection) MessageAssetOwners

func (p *AssetProjection) MessageAssetOwners() []MessageAssetRef

MessageAssetOwners returns every projected message-to-asset relationship.

func (*AssetProjection) MessageAssetsByAuthor

func (p *AssetProjection) MessageAssetsByAuthor(userID string) []MessageAssetRef

MessageAssetsByAuthor returns message-owned assets attributed to userID.

func (*AssetProjection) PendingExpiredAssets

func (p *AssetProjection) PendingExpiredAssets(now time.Time) []*evtv1.AssetCreatedEvent

func (*AssetProjection) ReplaySubjects

func (p *AssetProjection) ReplaySubjects() []string

ReplaySubjects uses one stream-wide physical filter for the projection's canonical, legacy, and message-body lanes. Projector filters unrelated subjects before decoding them.

func (*AssetProjection) Restore

func (p *AssetProjection) Restore(data []byte) error

func (*AssetProjection) Snapshot

func (p *AssetProjection) Snapshot() ([]byte, error)

func (*AssetProjection) SnapshotContractID

func (*AssetProjection) SnapshotContractID() string

func (*AssetProjection) Subjects

func (p *AssetProjection) Subjects() []string

func (*AssetProjection) VideoAttachmentManifest

func (p *AssetProjection) VideoAttachmentManifest(assetID string) (*VideoAttachmentManifest, bool)

type AssetState

type AssetState struct {
	// Creation is the current declaration, or nil after deletion.
	Creation *evtv1.AssetCreatedEvent
	// RoomID remains available for a projected tombstone.
	RoomID string
	// VideoManifest is the current processing state, if processing started.
	VideoManifest *VideoAttachmentManifest
	// Deleted reports whether the latest lifecycle fact is a tombstone.
	Deleted bool
	// PublicLinkPreview reports a positive durable public-preview reference.
	PublicLinkPreview bool
}

AssetState is one detached, generation-consistent view of projected asset lifecycle state. Callers cannot observe a declaration from one projection generation and room or processing state from another.

type AssetUploadCancelInput

type AssetUploadCancelInput struct {
	ActorID string
	// Operator selects a private upload session and requires SystemActorID.
	Operator bool
	UploadID string
}

type AssetUploadChunkInput

type AssetUploadChunkInput struct {
	ActorID string
	// Operator selects a private upload session and requires SystemActorID.
	Operator    bool
	UploadID    string
	Offset      int64
	Content     []byte
	ChunkSHA256 string
}

type AssetUploadCompleteInput

type AssetUploadCompleteInput struct {
	ActorID string
	// Operator selects a private upload session and requires SystemActorID.
	Operator bool
	UploadID string
}

type AssetUploadCreateInput

type AssetUploadCreateInput struct {
	// ActorID is the authenticated user for a public upload or the mapped asset
	// owner for an operator upload. The operator fact uses SystemActorID.
	ActorID string
	// Operator is set only by the private Operator API handler.
	Operator bool
	// Historical permits archived channels only on the private operator path.
	Historical  bool
	RoomID      string
	Filename    string
	ContentType string
	Size        int64
	SHA256      string
}

type AssetUploadModel

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

func (*AssetUploadModel) CancelUpload

func (*AssetUploadModel) CleanupExpired

func (m *AssetUploadModel) CleanupExpired(ctx context.Context) error

func (*AssetUploadModel) CompleteUpload

func (*AssetUploadModel) CreateUpload

func (*AssetUploadModel) GetUpload

func (m *AssetUploadModel) GetUpload(ctx context.Context, actorID, uploadID string) (*AssetUploadSession, error)

func (*AssetUploadModel) RunCleanup

func (m *AssetUploadModel) RunCleanup(ctx context.Context) error

func (*AssetUploadModel) UploadChunk

type AssetUploadSession

type AssetUploadSession struct {
	UploadID string `json:"upload_id"`
	// ActorID owns the asset, including when the upload was started by an operator.
	ActorID string `json:"actor_id"`
	// Operator prevents public upload calls from using this session.
	Operator bool `json:"operator,omitempty"`
	// Historical is fixed at creation and never grants access to a public caller.
	Historical      bool              `json:"historical,omitempty"`
	RoomID          string            `json:"room_id"`
	Filename        string            `json:"filename"`
	ContentType     string            `json:"content_type"`
	Size            int64             `json:"size"`
	SHA256          string            `json:"sha256"`
	Status          AssetUploadStatus `json:"status"`
	CommittedOffset int64             `json:"committed_offset"`
	MaxChunkSize    int32             `json:"max_chunk_size"`
	ExpiresAt       time.Time         `json:"expires_at"`
	AssetID         string            `json:"asset_id,omitempty"`
	ChunkKeys       []string          `json:"chunk_keys,omitempty"`
}

type AssetUploadStatus

type AssetUploadStatus string
const (
	AssetUploadStatusOpen      AssetUploadStatus = "open"
	AssetUploadStatusCompleted AssetUploadStatus = "completed"
	AssetUploadStatusCancelled AssetUploadStatus = "cancelled"
)

type AttachmentBinaryStatus

type AttachmentBinaryStatus int

AttachmentBinaryStatus is the tri-state result of probing an attachment's underlying binary. Use this when the absence-vs-can't-tell distinction matters — most importantly, when deciding whether to emit a durable "source missing" terminal event.

const (
	// AttachmentBinaryPresent means storage definitively returned the object.
	AttachmentBinaryPresent AttachmentBinaryStatus = iota
	// AttachmentBinaryMissing means storage definitively said "not there"
	// (S3 NoSuchKey / 404, NATS ObjectStore ErrObjectNotFound). Safe to
	// treat as a permanent terminal state.
	AttachmentBinaryMissing
	// AttachmentBinaryUnknown means the probe failed for a reason that
	// isn't "not found" — auth, network, missing client config, etc. The
	// binary might still exist; callers must NOT publish missing-source
	// events on this status, only skip / retry later.
	AttachmentBinaryUnknown
)

type AttachmentInfo

type AttachmentInfo struct {
	Size        int64
	ContentType string
	Filename    string
	RoomID      string
}

AttachmentInfo contains metadata about an attachment. This is a backend-agnostic wrapper around storage-specific info.

type AuthCodeData

type AuthCodeData struct {
	UserID              string    `json:"user_id"`
	ClientID            string    `json:"client_id,omitempty"`
	Resource            string    `json:"resource,omitempty"`
	Scopes              []string  `json:"scopes,omitempty"`
	RedirectURI         string    `json:"redirect_uri"`
	CodeChallenge       string    `json:"code_challenge"`
	CodeChallengeMethod string    `json:"code_challenge_method"`
	CreatedAt           time.Time `json:"created_at"`
	AuthGeneration      uint64    `json:"auth_generation,omitempty"`
}

AuthCodeData is the JSON value stored in RUNTIME_STATE for authorization codes.

type AuthGenerationCheckMetrics

type AuthGenerationCheckMetrics struct {
	// Fast is the number of checks that the fast check accepted.
	Fast uint64
	// Strict is the number of strict checks, by reason label: "path",
	// "window", "gate", and "mismatch".
	Strict map[string]uint64
}

AuthGenerationCheckMetrics counts auth generation checks in this process. The counters contain no user data.

type AuthTokenData

type AuthTokenData struct {
	UserID             string                      `json:"user_id"`
	ClientID           string                      `json:"client_id,omitempty"`
	Resource           string                      `json:"resource,omitempty"`
	Scopes             []string                    `json:"scopes,omitempty"`
	Kind               AuthTokenKind               `json:"kind,omitempty"`
	Presentation       AuthTokenPresentation       `json:"presentation,omitempty"`
	Source             string                      `json:"source,omitempty"`
	Request            *evtv1.AuditRequestMetadata `json:"request,omitempty"`
	CreatedAt          time.Time                   `json:"created_at"`
	ExpiresAt          time.Time                   `json:"expires_at,omitzero"`
	AuthGeneration     uint64                      `json:"auth_generation,omitempty"`
	RenewableSessionID string                      `json:"renewable_session_id,omitempty"`
	AccessGeneration   uint64                      `json:"access_generation,omitempty"`
	FreshAuthAt        time.Time                   `json:"fresh_auth_at,omitzero"`
	FreshAuthMethod    string                      `json:"fresh_auth_method,omitempty"`
	FreshAuthSource    string                      `json:"fresh_auth_source,omitempty"`
	// A separate storage field keeps older replicas from treating a partial
	// selection as permission to activate every role.
	PrivilegedModeExpiresAt time.Time `json:"selected_roles_expire_at,omitzero"`
	PrivilegedRoles         []string  `json:"privileged_roles,omitempty"`
}

AuthTokenData is the JSON value stored in RUNTIME_STATE under session.{hmac}. New bearer tokens and same-origin cookie session handles share this record shape so validators can reject a credential presented through the wrong transport. The name is kept for compatibility with the existing auth-token service API.

type AuthTokenKind

type AuthTokenKind string

AuthTokenKind identifies the security class of an opaque runtime credential.

const (
	AuthTokenKindFirstPartySession AuthTokenKind = "first_party_session"
	AuthTokenKindOAuthAccessToken  AuthTokenKind = "oauth_access_token"
)

type AuthTokenPresentation

type AuthTokenPresentation string

AuthTokenPresentation identifies how an opaque runtime token is intended to be presented by clients.

const (
	AuthTokenPresentationBearer AuthTokenPresentation = "bearer"
	// AuthTokenPresentationResourceBearer identifies access credentials that
	// are bound to an OAuth resource and scope set. General bearer validators
	// must reject this presentation instead of ignoring the grant boundary.
	AuthTokenPresentationResourceBearer AuthTokenPresentation = "resource_bearer"
	AuthTokenPresentationCookie         AuthTokenPresentation = "cookie"
)

type AuthorizationModel

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

AuthorizationModel owns shared permission decisions, effective room membership, authenticated operation guards and stable-input checks. It uses the same content-view transaction as the domain models; it does not create another projection or authorization cache.

Effective membership belongs here, not in RoomMembershipModel, because a universal channel derives it from join authority. Domain models depend on this model; this model depends on no domain operation model.

func (*AuthorizationModel) CanAccessRoomMessages

func (a *AuthorizationModel) CanAccessRoomMessages(ctx context.Context, userID string, kind RoomKind, roomID string) (bool, error)

CanAccessRoomMessages reports whether a channel-room account has at least one configured read mode. A positive interaction result does not imply that any specific thread relationship exists.

func (*AuthorizationModel) CanAdminAuditView

func (a *AuthorizationModel) CanAdminAuditView(ctx context.Context, userID string) (bool, error)

CanAdminAuditView checks if a user can view the audit log (event log) page in admin. The event-log inspection view in /manage/server/event-log is the first concrete use; future log exports / search endpoints gate on the same permission.

func (*AuthorizationModel) CanAdminSystemView

func (a *AuthorizationModel) CanAdminSystemView(ctx context.Context, userID string) (bool, error)

CanAdminSystemView checks if a user can view system projection diagnostics in admin. The diagnostics endpoint exposes low-level system state and is owner-only, so this mirrors GetAdminDiagnostics instead of any grantable RBAC permission.

func (*AuthorizationModel) CanAdminUsersView

func (a *AuthorizationModel) CanAdminUsersView(ctx context.Context, userID string) (bool, error)

CanAdminUsersView checks if a user can view the users page in admin.

func (*AuthorizationModel) CanAssignRoles

func (a *AuthorizationModel) CanAssignRoles(ctx context.Context, userID string) (bool, error)

CanAssignRoles checks if a user can assign/revoke roles to/from users. Backed by the canonical role.assign permission. Subsumes the previous CanAdminUsersManage (which was a duplicate "edit role assignments").

func (*AuthorizationModel) CanAttachFiles

func (a *AuthorizationModel) CanAttachFiles(ctx context.Context, userID string, kind RoomKind, roomID string) (bool, error)

CanAttachFiles checks if a user can attach files to messages in a specific room.

func (*AuthorizationModel) CanCreateBots

func (a *AuthorizationModel) CanCreateBots(ctx context.Context, userID string) (bool, error)

CanCreateBots checks whether a human user may create an owned bot account.

func (*AuthorizationModel) CanCreateRoom

func (a *AuthorizationModel) CanCreateRoom(ctx context.Context, userID string, kind RoomKind, groupID string) (bool, error)

CanCreateRoom checks if a user can create new rooms. When groupID is non-empty, the check is scoped to that room group (a role granted room.create at server scope can create in any group; a role granted only at a group's scope can create only in that group). DM rooms are creation-locked at this layer because room.create does not apply at the DM scope. DMs are created through FindOrCreateDM.

func (*AuthorizationModel) CanDeleteUser

func (a *AuthorizationModel) CanDeleteUser(ctx context.Context, actorID, targetUserID string) (bool, error)

CanDeleteUser checks if an actor can delete a specific user account. Returns true if:

  • A human actor is deleting their own account and has user.delete-self, OR
  • The actor has user.delete-any (the admin power).

func (*AuthorizationModel) CanEchoMessage

func (a *AuthorizationModel) CanEchoMessage(ctx context.Context, userID string, kind RoomKind, roomID string) (bool, error)

CanEchoMessage checks if a user can echo thread replies to the room timeline.

func (*AuthorizationModel) CanJoinRoom

func (a *AuthorizationModel) CanJoinRoom(ctx context.Context, userID string, kind RoomKind) (bool, error)

CanJoinRoom checks if a user can join existing rooms at the server tier (no specific room context). Used as a top-level "is the join action available at all" check. For per-room decisions — including "is this user implicitly a member of this global room" — use CanJoinRoomAt, which evaluates room, group, and server decisions.

DM-sensitive: DMs grant join implicitly to participants.

func (*AuthorizationModel) CanJoinRoomAt

func (a *AuthorizationModel) CanJoinRoomAt(ctx context.Context, userID string, kind RoomKind, roomID string) (bool, error)

CanJoinRoomAt checks if a user can join a specific room. Uses room-scope permission resolution (room override > group override > server default). This is the gate for global-room implicit membership: a global room's members are exactly the users for whom this returns true. Active room bans deny joins even when RBAC would otherwise allow them.

func (*AuthorizationModel) CanManageAnyRoom

func (a *AuthorizationModel) CanManageAnyRoom(ctx context.Context, userID string) (bool, error)

CanManageAnyRoom checks if a user can update or delete any room. "Any" room as opposed to a specific room — for per-room checks, use the room-level resolver via PermissionResolver.HasRoomPermission.

func (*AuthorizationModel) CanManageBots

func (a *AuthorizationModel) CanManageBots(ctx context.Context, userID string) (bool, error)

CanManageBots checks whether a human user may manage every bot account.

func (*AuthorizationModel) CanManageOthersMessage

func (a *AuthorizationModel) CanManageOthersMessage(ctx context.Context, userID string, kind RoomKind, roomID string) (bool, error)

CanManageOthersMessage checks if a user has effective message.manage in a specific room. This permission allows edits and deletions of other users' messages. It also lets an author edit their own message after the edit window closes.

func (*AuthorizationModel) CanManageRoles

func (a *AuthorizationModel) CanManageRoles(ctx context.Context, userID string) (bool, error)

CanManageRoles checks if a user can create, edit, delete, and reorder roles and their permissions. Subsumes the previous CanAdminRolesManage / CanSpaceRolesManage pair (which were duplicates).

func (*AuthorizationModel) CanManageRoomGroup

func (a *AuthorizationModel) CanManageRoomGroup(ctx context.Context, userID, groupID string) (bool, error)

CanManageRoomGroup checks whether a user can manage room/sidebar layout facts owned by a specific room group. Server-scope room.manage still applies through the group permission resolver; role.manage is intentionally not a substitute for this group-scoped capability.

func (*AuthorizationModel) CanManageServer

func (a *AuthorizationModel) CanManageServer(ctx context.Context, userID string) (bool, error)

CanManageServer checks if a user can update server settings (name, description, logo).

func (*AuthorizationModel) CanManageUserAccounts

func (a *AuthorizationModel) CanManageUserAccounts(ctx context.Context, userID string) (bool, error)

CanManageUserAccounts checks if a user can perform cross-user account lifecycle and recovery operations.

func (*AuthorizationModel) CanManageUserPermissions

func (a *AuthorizationModel) CanManageUserPermissions(ctx context.Context, userID string) (bool, error)

CanManageUserPermissions checks if a user can edit direct per-user permission overrides.

func (*AuthorizationModel) CanPostInThread

func (a *AuthorizationModel) CanPostInThread(ctx context.Context, userID string, kind RoomKind, roomID string) (bool, error)

CanPostInThread checks room-level authority to reply in any readable thread. It includes message.post but not relationship-scoped posting. For a specific target, use CanReplyInThread, which also checks access and room policy.

func (*AuthorizationModel) CanPostMessage

func (a *AuthorizationModel) CanPostMessage(ctx context.Context, userID string, kind RoomKind, roomID string) (bool, error)

CanPostMessage checks if a user can post new root messages in a specific room. Uses the permission scope chain for the specified room kind.

func (*AuthorizationModel) CanReactToMessage

func (a *AuthorizationModel) CanReactToMessage(ctx context.Context, userID string, kind RoomKind, roomID string) (bool, error)

CanReactToMessage checks if a user can add/remove reactions in a specific room.

func (*AuthorizationModel) CanReadMessage

func (a *AuthorizationModel) CanReadMessage(ctx context.Context, userID string, kind RoomKind, roomID, messageEventID string) (bool, error)

CanReadMessage reports whether the account can read one channel-room message. Roots, replies, and channel echoes use their canonical thread root. Callers must enforce current room membership separately.

func (*AuthorizationModel) CanReadMessageEvent

func (a *AuthorizationModel) CanReadMessageEvent(ctx context.Context, userID string, kind RoomKind, roomID string, event *evtv1.Event) (bool, error)

CanReadMessageEvent reports whether the account can receive one durable message-derived fact. Callers must enforce current room membership.

func (*AuthorizationModel) CanReadMessageInteractions

func (a *AuthorizationModel) CanReadMessageInteractions(ctx context.Context, userID string, kind RoomKind, roomID string) (bool, error)

CanReadMessageInteractions checks the RBAC gate for interaction-scoped reads. It does not test a specific thread relationship. Callers must enforce current room membership separately.

func (*AuthorizationModel) CanReadMessages

func (a *AuthorizationModel) CanReadMessages(ctx context.Context, userID string, kind RoomKind, roomID string) (bool, error)

CanReadMessages checks the permission part of message-content access in a specific room. Callers must enforce room membership for both room kinds.

func (*AuthorizationModel) CanReadThreadMessages

func (a *AuthorizationModel) CanReadThreadMessages(ctx context.Context, userID string, kind RoomKind, roomID, threadRootEventID string) (bool, error)

CanReadThreadMessages reports whether the account can read one complete thread. Callers must enforce current room membership separately.

func (*AuthorizationModel) CanReplyInThread

func (a *AuthorizationModel) CanReplyInThread(ctx context.Context, userID string, kind RoomKind, roomID, threadRootEventID string) (bool, error)

CanReplyInThread checks current membership, room policy, read access, and posting authority for one canonical thread root. Interaction posting needs an existing relationship; broad read access alone cannot create one.

func (*AuthorizationModel) CanSeeRoom

func (a *AuthorizationModel) CanSeeRoom(ctx context.Context, userID string, kind RoomKind, roomID string) (bool, error)

CanSeeRoom checks if a user can see a specific room in the directory or any other surface that enumerates rooms (e.g. the group "Join all" affordance). A user can see a room iff they are already a member OR `room.list` resolves to allow at the room (room → group → server walk).

`room.list` is distinct from `room.join`: a restricted room can be visible in the directory (request-access flow) without being directly joinable. Pair with `CanJoinRoomAt` to decide whether to show a "Join" button vs a "Restricted" indicator.

DM-sensitive: for KindDM this returns false. DM rooms aren't surfaced through the channel room-list API; they use their own listing path.

func (*AuthorizationModel) CanStartDM

func (a *AuthorizationModel) CanStartDM(ctx context.Context, userID string) (bool, error)

CanStartDM checks if a human user can start DM conversations. Bot accounts can never start or fetch DMs through the creation operation, regardless of their permissions. The direct-message-scoped message.post decision controls creation and inherits the server decision when no DM override exists.

func (*AuthorizationModel) HasAnyAdminPermission

func (a *AuthorizationModel) HasAnyAdminPermission(ctx context.Context, userID string) (bool, error)

HasAnyAdminPermission checks if a user has any admin-level permission. Used to determine whether the server admin link should be visible.

func (*AuthorizationModel) HasServerPermission

func (a *AuthorizationModel) HasServerPermission(ctx context.Context, userID string, perm Permission) (bool, error)

HasServerPermission checks a server-only permission (no room context).

func (*AuthorizationModel) IsServerAdmin

func (a *AuthorizationModel) IsServerAdmin(ctx context.Context, userID string) (bool, error)

IsServerAdmin checks if a user has the admin role via RBAC. Does NOT check config fallback (owners.emails) - caller should check that separately.

func (*AuthorizationModel) IsServerOwner

func (a *AuthorizationModel) IsServerOwner(ctx context.Context, userID string) (bool, error)

IsServerOwner checks whether a user has the durable owner role. Configured owners.emails entries are materialized into that role at boot and by the durable notification-effects worker after email verification, so live and event-time authorization cannot diverge.

func (*AuthorizationModel) ResolveUserPermission

func (a *AuthorizationModel) ResolveUserPermission(ctx context.Context, userID string, kind RoomKind, roomID string, perm Permission) (DecisionKind, error)

ResolveUserPermission returns the walker's decision (allow / deny / none) for a user-permission pair. Single source of truth for both the bool authorizer and the inspector. Pass roomID="" with KindDM to resolve the singleton direct-message scope before the server scope.

func (*AuthorizationModel) RoomMembershipExists

func (a *AuthorizationModel) RoomMembershipExists(ctx context.Context, kind RoomKind, userID, roomID string) (bool, error)

RoomMembershipExists reports whether userID is an effective member of roomID. Explicit memberships are the durable state. A universal channel also grants effective membership to every server member who can currently join it; this membership is derived at read time.

type BatchMessageAttachmentsInput

type BatchMessageAttachmentsInput struct {
	ActorID  string
	RoomID   string
	EventIDs []string
}

BatchMessageAttachmentsInput is the authorized current-message attachment batch request.

type BatchMessagesReadResult

type BatchMessagesReadResult struct {
	Kind   RoomKind
	Events []*evtv1.Event
}

type BatchRoomAssetsInput

type BatchRoomAssetsInput struct {
	ActorID  string
	RoomID   string
	AssetIDs []string
}

BatchRoomAssetsInput is the authorized room-scoped asset batch read request.

type BearerSessionCredentials

type BearerSessionCredentials struct {
	AccessToken          string
	RefreshToken         string
	AccessTokenExpiresAt time.Time
	// SessionExpiresAt is the end of the current renewable-session window.
	SessionExpiresAt time.Time
	// Scopes is a detached copy of the exact OAuth grant for these credentials.
	// First-party sessions have no OAuth scopes.
	Scopes []string
}

BearerSessionCredentials is the show-once credential pair returned to a human client. Raw values are never persisted.

type Bot

type Bot struct {
	User             *readmodel.User
	OwnerUserID      string
	APIKey           string
	APIKeyID         string
	APIKeyCreatedAt  time.Time
	APIKeys          []BotAPIKey
	IncomingWebhooks []BotIncomingWebhook
}

Bot is the management view of a bot account. Raw credentials are populated only by the command that issues them and must never be logged or persisted.

type BotAPIKey

type BotAPIKey struct {
	ID            string
	Name          string
	CreatedAt     time.Time
	LastUsedAt    time.Time
	LastUsedState BotCredentialLastUsedState
	// contains filtered or unexported fields
}

BotAPIKey is safe management metadata for one active credential.

type BotAPIKeyCredential

type BotAPIKeyCredential struct {
	ID              string
	Name            string
	Verifier        []byte
	CreatedAt       time.Time
	RollbackVisible bool
}

BotAPIKeyCredential is one projected verifier and its safe lifecycle metadata.

type BotAPIKeyIssue

type BotAPIKeyIssue struct {
	Bot        *Bot
	KeyID      string
	Credential string
}

BotAPIKeyIssue contains the show-once secret returned by an issuance command. Credential must never be logged or persisted.

type BotCredentialLastUsedState

type BotCredentialLastUsedState uint8

BotCredentialLastUsedState identifies whether optional credential-use telemetry was loaded and whether it has a value.

const (
	BotCredentialLastUsedUnspecified BotCredentialLastUsedState = iota
	BotCredentialLastUsedNoUseRecorded
	BotCredentialLastUsedRecorded
	BotCredentialLastUsedUnavailable
)

type BotIncomingWebhook

type BotIncomingWebhook struct {
	ID            string
	Name          string
	CreatedAt     time.Time
	LastUsedAt    time.Time
	LastUsedState BotCredentialLastUsedState
}

BotIncomingWebhook is safe management metadata for one active credential.

type BotIncomingWebhookCredential

type BotIncomingWebhookCredential struct {
	ID        string
	Name      string
	Verifier  []byte
	CreatedAt time.Time
}

BotIncomingWebhookCredential is one projected verifier and its safe lifecycle metadata.

type BotIncomingWebhookIssue

type BotIncomingWebhookIssue struct {
	Bot        *Bot
	WebhookID  string
	Credential string
}

BotIncomingWebhookIssue contains the show-once secret returned by a create command. Credential must never be logged or persisted.

type BotOutboundWebhook

type BotOutboundWebhook struct {
	ID               string
	Name             string // Human label, encrypted alongside endpoint credentials.
	CreatedAt        time.Time
	URL              string // Saved destination; can include tool credentials and must not be logged.
	Enabled          bool   // Accepts new messages; resume does not recover earlier work.
	HasAuthorization bool
	Latest           *logv1.Entry // Latest retained failure; absence is not proof of delivery.
}

BotOutboundWebhook exposes the saved destination only to bot managers. Authorization credentials and signing secrets remain write-only.

type BotOutboundWebhookPatch

type BotOutboundWebhookPatch struct {
	Enabled       *bool
	URL           *string
	Authorization *string
}

BotOutboundWebhookPatch preserves omitted fields. Empty Authorization removes it. Name and signing secret cannot be changed through a patch.

type BotWebhookFailurePage

type BotWebhookFailurePage struct {
	Entries    []*logv1.Entry
	NextCursor string
}

BotWebhookFailurePage contains complete retained records in recording order. NextCursor is confidential and bound to the requesting viewer and endpoint.

type CallAccessMaterial

type CallAccessMaterial struct {
	CallID  string
	E2EEKey string
}

CallAccessMaterial binds the identity and encryption key for one projected call generation. Callers must keep these values together when issuing access.

type CallModel

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

func NewCallModel

func NewCallModel(
	publisher *evtstream.Publisher,
	callState events.ProjectionHandle[*CallStateProjection],
	callKeys kms.CallKeyStore,
	livekit liveKitParticipantLister,
	reconcileLease *lease.Lease,
	memoryCacheKV jetstream.KeyValue,
	logger *log.Logger,
) *CallModel

func (*CallModel) AppendJoined

func (s *CallModel) AppendJoined(ctx context.Context, roomID, userID string, source evtv1.CallParticipantEventSource) error

func (*CallModel) AppendJoinedForCall

func (s *CallModel) AppendJoinedForCall(ctx context.Context, roomID, userID, expectedCallID string, source evtv1.CallParticipantEventSource) error

func (*CallModel) AppendLeft

func (s *CallModel) AppendLeft(ctx context.Context, roomID, userID string, source evtv1.CallParticipantEventSource) error

func (*CallModel) AppendLeftForCall

func (s *CallModel) AppendLeftForCall(ctx context.Context, roomID, userID, expectedCallID string, source evtv1.CallParticipantEventSource) error

func (*CallModel) GetAccessMaterial

func (s *CallModel) GetAccessMaterial(ctx context.Context, roomID string) (CallAccessMaterial, error)

func (*CallModel) GetE2EEKey

func (s *CallModel) GetE2EEKey(ctx context.Context, roomID string) (string, error)

func (*CallModel) GetParticipantAccessMaterial

func (s *CallModel) GetParticipantAccessMaterial(ctx context.Context, roomID, userID string) (CallAccessMaterial, error)

GetParticipantAccessMaterial resolves access for the active call only when userID participates in that same generation before and after the key read.

func (*CallModel) ReconcileRoomParticipants

func (s *CallModel) ReconcileRoomParticipants(ctx context.Context, roomID string, observedUserIDs []string) error

func (*CallModel) ReconcileWithLiveKit

func (s *CallModel) ReconcileWithLiveKit(ctx context.Context) error

func (*CallModel) RemoveLiveKitParticipant

func (s *CallModel) RemoveLiveKitParticipant(ctx context.Context, kind RoomKind, roomID, callID, userID string) error

func (*CallModel) Run

func (s *CallModel) Run(ctx context.Context) error

type CallParticipant

type CallParticipant struct {
	UserID   string
	CallID   string
	JoinedAt int64
	Source   evtv1.CallParticipantEventSource
}

CallParticipant represents a user currently in a voice call.

type CallPermissions

type CallPermissions struct {
	Start       bool
	Join        bool
	Voice       bool
	Camera      bool
	ScreenShare bool
}

CallPermissions separates call admission from each media source. Membership is checked separately. Start never implies Join or a publishing permission.

func (CallPermissions) PublishSources

func (p CallPermissions) PublishSources() []livekit.TrackSource

PublishSources maps logical permissions to the browser participant's sources. Native publishers use a separate grant: their microphone source carries captured application audio and requires ScreenShare instead of Voice.

type CallRoomSnapshot

type CallRoomSnapshot struct {
	Participants []CallParticipant
	Call         CallSession
	Seq          uint64
}

type CallSession

type CallSession struct {
	CallID     string
	E2EEKeyRef string
	StartedAt  int64
	Source     evtv1.CallParticipantEventSource
}

type CallStateProjection

type CallStateProjection struct {
	events.MemoryProjection
	// contains filtered or unexported fields
}

CallStateProjection derives the active-call snapshot from durable room facts. It deliberately keeps only process-local projection state; LiveKit reconciliation appends more facts instead of mutating the projection directly.

func NewCallStateProjection

func NewCallStateProjection() *CallStateProjection

func (*CallStateProjection) ActiveCall

func (p *CallStateProjection) ActiveCall(roomID string) (CallSession, bool)

func (*CallStateProjection) ActiveRoomIDs

func (p *CallStateProjection) ActiveRoomIDs() []string

func (*CallStateProjection) Apply

func (p *CallStateProjection) Apply(event *evtv1.Event, seq uint64) error

func (*CallStateProjection) Participants

func (p *CallStateProjection) Participants(roomID string) []CallParticipant

func (*CallStateProjection) Restore

func (p *CallStateProjection) Restore(data []byte) error

func (*CallStateProjection) RoomSnapshot

func (p *CallStateProjection) RoomSnapshot(roomID string) CallRoomSnapshot

func (*CallStateProjection) Snapshot

func (p *CallStateProjection) Snapshot() ([]byte, error)

func (*CallStateProjection) SnapshotContractID

func (*CallStateProjection) SnapshotContractID() string

func (*CallStateProjection) Subjects

func (p *CallStateProjection) Subjects() []string

type ChattoCore

type ChattoCore struct {

	// VideoUploadsEnabled makes message commits enqueue durable processing work
	// for accepted video-shaped attachments. Worker placement is configured
	// independently; the main process does not hand work to a local callback.
	VideoUploadsEnabled bool

	// OnPushTestRequested sends a test notification to a user's push subscriptions.
	OnPushTestRequested func(ctx context.Context, userID string) error

	// PresenceHub is the compatibility handle for PresenceModel's per-process
	// fanout hub. Started by (*ChattoCore).Run through PresenceModel.
	PresenceHub *PresenceHub

	// EventPublisher writes to the EVT event-sourcing stream
	// (ADR-033/034). Exposed for use by the migrate subcommand and
	// future aggregate cutovers; domain code accesses it through
	// higher-level helpers as aggregates migrate.
	EventPublisher *evtstream.Publisher
	// contains filtered or unexported fields
}

ChattoCore is the central hub for all Chatto operations. It provides a unified API for spaces, users, rooms, and messages, managing current JetStream resources internally.

func NewChattoCore

func NewChattoCore(ctx context.Context, nc *nats.Conn, cfg config.CoreConfig) (*ChattoCore, error)

NewChattoCore creates and initializes a new ChattoCore instance. This should be called once at application startup.

func (*ChattoCore) ATProtoSigningKey

func (c *ChattoCore) ATProtoSigningKey(ctx context.Context, origin string) (*atcrypto.PrivateKeyP256, error)

ATProtoSigningKey opens the signing key shared by all providers and replicas for a canonical HTTPS origin. Only an absent record permits generation.

func (*ChattoCore) AddMember

func (c *ChattoCore) AddMember(ctx context.Context, actorID string, kind RoomKind, roomID, targetUserID string) (*readmodel.RoomMembership, error)

AddMember delegates to the owning RoomMembershipModel.

func (*ChattoCore) AddVerifiedEmailDirect

func (c *ChattoCore) AddVerifiedEmailDirect(ctx context.Context, userID, email string) error

AddVerifiedEmailDirect adds an email as verified without requiring token verification. Used for OAuth flows where the email is already verified by the provider.

func (*ChattoCore) AddVerifiedEmailDirectAs

func (c *ChattoCore) AddVerifiedEmailDirectAs(ctx context.Context, actorID, userID, email string) error

AddVerifiedEmailDirectAs adds an email as verified with explicit actor attribution. Operator/admin flows should pass SystemActorID.

func (*ChattoCore) AdminAddUserVerifiedEmailAs

func (c *ChattoCore) AdminAddUserVerifiedEmailAs(ctx context.Context, actorID, userID, email string) (*AdminUserView, error)

AdminAddUserVerifiedEmailAs adds an already-verified email with an explicit actor.

func (*ChattoCore) AdminAssignServerRole

func (c *ChattoCore) AdminAssignServerRole(ctx context.Context, actorID, targetUserID, roleName string) error

func (*ChattoCore) AdminAssignUserRole

func (c *ChattoCore) AdminAssignUserRole(ctx context.Context, userID, roleName string) (*AdminUserView, error)

AdminAssignUserRole assigns a role to an existing user.

func (*ChattoCore) AdminClearLoginChangeCooldown

func (c *ChattoCore) AdminClearLoginChangeCooldown(ctx context.Context, actorID, targetUserID string) error

AdminClearLoginChangeCooldown clears a human account's login cooldown. The actor needs user.manage-accounts, including when targeting their own account.

func (*ChattoCore) AdminClearUserLoginChangeCooldown

func (c *ChattoCore) AdminClearUserLoginChangeCooldown(ctx context.Context, userID string) error

AdminClearUserLoginChangeCooldown clears a user's self-service login-change cooldown as the system actor.

func (*ChattoCore) AdminCreateServerRole

func (c *ChattoCore) AdminCreateServerRole(ctx context.Context, actorID string, input AdminRoleInput) (*RoleWithPermissions, error)

func (*ChattoCore) AdminCreateUserAs

func (c *ChattoCore) AdminCreateUserAs(ctx context.Context, actorID string, req AdminCreateUserRequest) (*AdminUserView, error)

AdminCreateUserAs creates a user with an explicit actor and applies optional email and role state with compensation if a post-create step fails.

func (*ChattoCore) AdminDeleteServerRole

func (c *ChattoCore) AdminDeleteServerRole(ctx context.Context, actorID, roleName string) error

func (*ChattoCore) AdminDeleteUserAs

func (c *ChattoCore) AdminDeleteUserAs(ctx context.Context, actorID, userID string) error

AdminDeleteUserAs permanently deletes a user with an explicit actor.

func (*ChattoCore) AdminGetUser

func (c *ChattoCore) AdminGetUser(ctx context.Context, userID string) (*AdminUserView, error)

AdminGetUser returns a hydrated operator view for one user ID.

func (*ChattoCore) AdminListServerRoles

func (c *ChattoCore) AdminListServerRoles(ctx context.Context, actorID string) (*RoleCatalog, error)

AdminListServerRoles adds aggregate counts only for managers and assigners. Ordinary public role catalog reads retain their lightweight response.

func (*ChattoCore) AdminListUsers

func (c *ChattoCore) AdminListUsers(ctx context.Context, search string, limit, offset int) (*AdminUserList, error)

AdminListUsers returns users with their admin-facing role and verified-email data hydrated.

func (*ChattoCore) AdminReorderServerRoles

func (c *ChattoCore) AdminReorderServerRoles(ctx context.Context, actorID string, roleNames []string) ([]RoleWithPermissions, error)

func (*ChattoCore) AdminRevokeServerRole

func (c *ChattoCore) AdminRevokeServerRole(ctx context.Context, actorID, targetUserID, roleName string) error

func (*ChattoCore) AdminRevokeUserRole

func (c *ChattoCore) AdminRevokeUserRole(ctx context.Context, userID, roleName string) (*AdminUserView, error)

AdminRevokeUserRole revokes a role from an existing user.

func (*ChattoCore) AdminSetUserPasswordAs

func (c *ChattoCore) AdminSetUserPasswordAs(ctx context.Context, actorID, userID, password string) (*AdminUserView, error)

AdminSetUserPasswordAs sets a user's password with an explicit actor.

func (*ChattoCore) AdminSetUserPasswordAuthorized

func (c *ChattoCore) AdminSetUserPasswordAuthorized(ctx context.Context, actorID, targetUserID, password string) error

AdminSetUserPasswordAuthorized sets a password for the target account without requiring the old password. Changing another account requires the same admin-management gate used by admin identity changes.

func (*ChattoCore) AdminUpdateOperatorUser

func (c *ChattoCore) AdminUpdateOperatorUser(ctx context.Context, req AdminUpdateOperatorUserRequest) (*AdminUserView, error)

AdminUpdateOperatorUser updates operator-managed profile fields and returns the hydrated user view.

func (*ChattoCore) AdminUpdateServerRole

func (c *ChattoCore) AdminUpdateServerRole(ctx context.Context, actorID string, input AdminRoleUpdateInput) (*RoleWithPermissions, error)

func (*ChattoCore) AdminUpdateUserLogin

func (c *ChattoCore) AdminUpdateUserLogin(ctx context.Context, userID, newLogin string) (*readmodel.User, error)

AdminUpdateUserLogin changes a user's login/username, bypassing the cooldown check and not advancing the cooldown timestamp. The user retains whatever rename allowance they had prior to the admin edit. Authorization: Caller must verify admin privileges.

func (*ChattoCore) AdminUpdateUserProfile

func (c *ChattoCore) AdminUpdateUserProfile(ctx context.Context, userID string, login, displayName, bio *string) (*readmodel.User, error)

AdminUpdateUserProfile updates a user's login, display name, and/or bio as a single admin-authored mutation. When multiple fields are changed, their durable events are appended atomically in one batch.

func (*ChattoCore) AdmitPushTestNotification

func (c *ChattoCore) AdmitPushTestNotification(ctx context.Context, userID string) error

AdmitPushTestNotification reserves the per-account test-notification window in shared runtime state so concurrent replicas enforce one limit.

func (*ChattoCore) AllProjectorsStarted

func (c *ChattoCore) AllProjectorsStarted() bool

AllProjectorsStarted reports whether every registered projector has entered its Run body. Test helpers (and any sequenced startup code) use this to wait for projector consumers to come online before issuing reads that depend on a populated projection — the background goroutines launched by Run aren't guaranteed to have been scheduled the instant `go core.Run(ctx)` returns.

func (*ChattoCore) AllServerPermissions

func (c *ChattoCore) AllServerPermissions() []Permission

AllServerPermissions returns all defined server permissions. Exposed as a method for consistency with other core APIs.

func (*ChattoCore) ArchiveRoom

func (c *ChattoCore) ArchiveRoom(ctx context.Context, actorID string, kind RoomKind, roomID string) (*readmodel.Room, error)

ArchiveRoom sets a room's archived flag. Archived rooms are hidden from sidebars and Browse Rooms; existing memberships are preserved. Authorization: Caller must verify CanManageAnyRoom before calling.

ADR-035 phase 6: event-only.

func (*ChattoCore) AssetEventTimelineTarget

func (c *ChattoCore) AssetEventTimelineTarget(event *evtv1.Event) (roomID, messageEventID string, ok bool)

AssetEventTimelineTarget resolves the current room timeline row affected by a durable asset lifecycle event. Processing events carry their owning message directly. Deletions recover ownership from the asset projection's durable message-to-asset index, including a processed derivative referenced by an original message asset's manifest.

func (*ChattoCore) AssetMessageTarget

func (c *ChattoCore) AssetMessageTarget(assetID string) (roomID, messageEventID string, ok bool)

AssetMessageTarget resolves the durable message that owns an original or processed derivative asset.

func (*ChattoCore) AssetUploads

func (c *ChattoCore) AssetUploads() *AssetUploadModel

func (*ChattoCore) AssetsConfig

func (c *ChattoCore) AssetsConfig() assets.Config

AssetsConfig returns the assets configuration as an assets.Config.

func (*ChattoCore) AssignAdminRole

func (c *ChattoCore) AssignAdminRole(ctx context.Context, userID string) error

AssignAdminRole assigns the admin role to a user.

func (*ChattoCore) AssignConfiguredOwnerRole

func (c *ChattoCore) AssignConfiguredOwnerRole(ctx context.Context, userID string) error

AssignConfiguredOwnerRole assigns the owner role because owners.emails in the server configuration names a verified email of the user. The event records that reason.

func (*ChattoCore) AssignOwnerRole

func (c *ChattoCore) AssignOwnerRole(ctx context.Context, userID string) error

AssignOwnerRole assigns the owner role to a user.

func (*ChattoCore) AssignServerRole

func (c *ChattoCore) AssignServerRole(ctx context.Context, actorID, userID, roleName string) error

AssignServerRole assigns any role to a user. The role must exist (system or custom). The everyone role cannot be assigned (it's implicit). The model enforces that non-owner actors cannot assign authority they do not possess; API boundaries additionally require role.assign.

func (*ChattoCore) AssignServerRoleToExistingUser

func (c *ChattoCore) AssignServerRoleToExistingUser(ctx context.Context, actorID, userID, roleName string) error

AssignServerRoleToExistingUser assigns any role to an existing user. Unlike AssignServerRole, it validates target-user existence inside the append OCC loop so operator APIs cannot report NotFound after persisting a role fact for a user that was already deleted.

func (*ChattoCore) AuthGenerationCheckMetrics

func (c *ChattoCore) AuthGenerationCheckMetrics() AuthGenerationCheckMetrics

AuthGenerationCheckMetrics returns the auth generation check counters of this process.

func (*ChattoCore) AuthorizeCall

func (c *ChattoCore) AuthorizeCall(ctx context.Context, actorID, roomID string, starting bool) (CallPermissions, error)

AuthorizeCall checks current membership and permissions at stable authority inputs. A start additionally needs call.start. Credential issuance must use the returned permissions, and must separately validate the call generation.

func (*ChattoCore) BatchGetAdminMembers

func (c *ChattoCore) BatchGetAdminMembers(ctx context.Context, actorID string, userIDs []string) (*AdminMemberList, error)

func (*ChattoCore) BatchGetRoomAssets

func (c *ChattoCore) BatchGetRoomAssets(ctx context.Context, input BatchRoomAssetsInput) ([]*evtv1.Attachment, error)

BatchGetRoomAssets returns room-scoped assets for a room the actor may read to. Missing, deleted, and wrong-room asset IDs are omitted.

func (*ChattoCore) BatchMessageAttachments

func (c *ChattoCore) BatchMessageAttachments(ctx context.Context, input BatchMessageAttachmentsInput) ([]*MessageAttachmentSet, error)

BatchMessageAttachments returns current attachments for visible messages in a room the actor may read. Missing, retracted, hidden, wrong-room, and non-message event IDs are omitted.

func (*ChattoCore) CallTokenAccess

func (c *ChattoCore) CallTokenAccess(ctx context.Context, actorID, roomID string) (CallPermissions, CallAccessMaterial, error)

CallTokenAccess authorizes primary media access and resolves the key for the active generation. A capped server first records the participant's place.

func (*ChattoCore) CanAccessRoomMessages

func (c *ChattoCore) CanAccessRoomMessages(ctx context.Context, userID string, kind RoomKind, roomID string) (bool, error)

CanAccessRoomMessages delegates to shared authorization policy.

func (*ChattoCore) CanAdminAuditView

func (c *ChattoCore) CanAdminAuditView(ctx context.Context, userID string) (bool, error)

CanAdminAuditView delegates to shared authorization policy.

func (*ChattoCore) CanAdminSystemView

func (c *ChattoCore) CanAdminSystemView(ctx context.Context, userID string) (bool, error)

CanAdminSystemView delegates to shared authorization policy.

func (*ChattoCore) CanAdminUsersView

func (c *ChattoCore) CanAdminUsersView(ctx context.Context, userID string) (bool, error)

CanAdminUsersView delegates to shared authorization policy.

func (*ChattoCore) CanAssignRole

func (c *ChattoCore) CanAssignRole(ctx context.Context, actorID, roleName string) (bool, error)

CanAssignRole reports whether an actor with role.assign may grant a specific role without granting authority they do not currently possess.

func (*ChattoCore) CanAssignRoles

func (c *ChattoCore) CanAssignRoles(ctx context.Context, userID string) (bool, error)

CanAssignRoles delegates to shared authorization policy.

func (*ChattoCore) CanAttachFiles

func (c *ChattoCore) CanAttachFiles(ctx context.Context, userID string, kind RoomKind, roomID string) (bool, error)

CanAttachFiles delegates to shared authorization policy.

func (*ChattoCore) CanChangeUserDeactivation

func (c *ChattoCore) CanChangeUserDeactivation(ctx context.Context, actorID, userID string) (bool, error)

CanChangeUserDeactivation supplies the same policy for commands and admin UI. Human accounts can be managed, but self-deactivation and owner lockout are prohibited. Bot lifecycle remains owned by bot management.

func (*ChattoCore) CanCreateBots

func (c *ChattoCore) CanCreateBots(ctx context.Context, userID string) (bool, error)

CanCreateBots delegates to shared authorization policy.

func (*ChattoCore) CanCreateRoom

func (c *ChattoCore) CanCreateRoom(ctx context.Context, userID string, kind RoomKind, groupID string) (bool, error)

CanCreateRoom delegates to shared authorization policy.

func (*ChattoCore) CanDeleteUser

func (c *ChattoCore) CanDeleteUser(ctx context.Context, actorID, targetUserID string) (bool, error)

CanDeleteUser delegates to shared authorization policy.

func (*ChattoCore) CanEchoMessage

func (c *ChattoCore) CanEchoMessage(ctx context.Context, userID string, kind RoomKind, roomID string) (bool, error)

CanEchoMessage delegates to shared authorization policy.

func (*ChattoCore) CanManageAnyRoom

func (c *ChattoCore) CanManageAnyRoom(ctx context.Context, userID string) (bool, error)

CanManageAnyRoom delegates to shared authorization policy.

func (*ChattoCore) CanManageBots

func (c *ChattoCore) CanManageBots(ctx context.Context, userID string) (bool, error)

CanManageBots delegates to shared authorization policy.

func (*ChattoCore) CanManageOthersMessage

func (c *ChattoCore) CanManageOthersMessage(ctx context.Context, userID string, kind RoomKind, roomID string) (bool, error)

CanManageOthersMessage delegates to shared authorization policy.

func (*ChattoCore) CanManageRoles

func (c *ChattoCore) CanManageRoles(ctx context.Context, userID string) (bool, error)

CanManageRoles delegates to shared authorization policy.

func (*ChattoCore) CanManageRoomGroup

func (c *ChattoCore) CanManageRoomGroup(ctx context.Context, userID, groupID string) (bool, error)

CanManageRoomGroup delegates to shared authorization policy.

func (*ChattoCore) CanManageServer

func (c *ChattoCore) CanManageServer(ctx context.Context, userID string) (bool, error)

CanManageServer delegates to shared authorization policy.

func (*ChattoCore) CanManageUserAccounts

func (c *ChattoCore) CanManageUserAccounts(ctx context.Context, userID string) (bool, error)

CanManageUserAccounts delegates to shared authorization policy.

func (*ChattoCore) CanManageUserPermissions

func (c *ChattoCore) CanManageUserPermissions(ctx context.Context, userID string) (bool, error)

CanManageUserPermissions delegates to shared authorization policy.

func (*ChattoCore) CanPostInThread

func (c *ChattoCore) CanPostInThread(ctx context.Context, userID string, kind RoomKind, roomID string) (bool, error)

CanPostInThread delegates to shared authorization policy.

func (*ChattoCore) CanPostMessage

func (c *ChattoCore) CanPostMessage(ctx context.Context, userID string, kind RoomKind, roomID string) (bool, error)

CanPostMessage delegates to shared authorization policy.

func (*ChattoCore) CanReactToMessage

func (c *ChattoCore) CanReactToMessage(ctx context.Context, userID string, kind RoomKind, roomID string) (bool, error)

CanReactToMessage delegates to shared authorization policy.

func (*ChattoCore) CanReadMessage

func (c *ChattoCore) CanReadMessage(ctx context.Context, userID string, kind RoomKind, roomID, messageEventID string) (bool, error)

CanReadMessage delegates to shared authorization policy.

func (*ChattoCore) CanReadMessageEvent

func (c *ChattoCore) CanReadMessageEvent(ctx context.Context, userID string, kind RoomKind, roomID string, event *evtv1.Event) (bool, error)

CanReadMessageEvent delegates to shared authorization policy.

func (*ChattoCore) CanReadMessageInteractions

func (c *ChattoCore) CanReadMessageInteractions(ctx context.Context, userID string, kind RoomKind, roomID string) (bool, error)

CanReadMessageInteractions delegates to shared authorization policy.

func (*ChattoCore) CanReadMessages

func (c *ChattoCore) CanReadMessages(ctx context.Context, userID string, kind RoomKind, roomID string) (bool, error)

CanReadMessages delegates to shared authorization policy.

func (*ChattoCore) CanReadRoomAsset

func (c *ChattoCore) CanReadRoomAsset(ctx context.Context, actorID string, kind RoomKind, roomID, assetID string) (bool, error)

CanReadRoomAsset reports whether an account can read one room asset. Pending assets without a durable message owner do not qualify for interaction-scoped reads. Callers must enforce current room membership.

func (*ChattoCore) CanReadThreadMessages

func (c *ChattoCore) CanReadThreadMessages(ctx context.Context, userID string, kind RoomKind, roomID, threadRootEventID string) (bool, error)

CanReadThreadMessages delegates to shared authorization policy.

func (*ChattoCore) CanReplyInThread

func (c *ChattoCore) CanReplyInThread(ctx context.Context, userID string, kind RoomKind, roomID, threadRootEventID string) (bool, error)

CanReplyInThread delegates to shared authorization policy.

func (*ChattoCore) CanRevokeRole

func (c *ChattoCore) CanRevokeRole(ctx context.Context, actorID, roleName string) (bool, error)

CanRevokeRole reports whether an actor with role.assign may revoke a specific role. Explicit denials are included because removing a restriction can restore authority to the target user.

func (*ChattoCore) CanRevokeRoleFromUser

func (c *ChattoCore) CanRevokeRoleFromUser(ctx context.Context, actorID, targetUserID, roleName string) (bool, error)

CanRevokeRoleFromUser reports whether a role revocation is available for a concrete target. It includes target-specific safety rules that the generic role-authority comparison cannot express.

func (*ChattoCore) CanSeeRoom

func (c *ChattoCore) CanSeeRoom(ctx context.Context, userID string, kind RoomKind, roomID string) (bool, error)

CanSeeRoom delegates to shared authorization policy.

func (*ChattoCore) CanStartDM

func (c *ChattoCore) CanStartDM(ctx context.Context, userID string) (bool, error)

CanStartDM delegates to shared authorization policy.

func (*ChattoCore) CancelEmailVerificationCode

func (c *ChattoCore) CancelEmailVerificationCode(ctx context.Context, userID, email, code string) error

CancelEmailVerificationCode removes an email-verification OTP that was created but not delivered, so failed email sends do not consume throttle slots.

func (*ChattoCore) CancelPasswordResetToken

func (c *ChattoCore) CancelPasswordResetToken(ctx context.Context, token string) error

CancelPasswordResetToken removes an undelivered reset token and releases its request throttle reservation. A newer request reservation is never removed.

func (*ChattoCore) CancelRegistrationCode

func (c *ChattoCore) CancelRegistrationCode(ctx context.Context, email, code string) error

CancelRegistrationCode removes a registration OTP that was created but not delivered, so failed email sends do not consume resend throttle slots.

func (*ChattoCore) CanonicalReactionMessageEventID

func (c *ChattoCore) CanonicalReactionMessageEventID(roomID, messageEventID string) string

CanonicalReactionMessageEventID returns the original thread reply event ID when messageEventID identifies a channel echo. Unknown IDs are returned unchanged so legacy callers get the same behavior as direct projection reads.

func (*ChattoCore) CaptureUserContentSnapshot

func (c *ChattoCore) CaptureUserContentSnapshot(userID string) *UserContentSnapshot

CaptureUserContentSnapshot copies one user's projected state without resolving encryption keys. Callers can use it inside a content-view read barrier because it performs bounded in-memory work only.

func (*ChattoCore) ChannelEchoEventID

func (c *ChattoCore) ChannelEchoEventID(messageEventID string) (string, bool)

ChannelEchoEventID returns the visible room-timeline echo for an original thread reply. The boolean is false when the reply is not currently echoed.

func (*ChattoCore) CleanupAsset

func (c *ChattoCore) CleanupAsset(ctx context.Context, asset *evtv1.DeprecatedAsset)

CleanupAsset deletes an asset from the server object store. Used to clean up orphaned assets when subsequent operations fail.

func (*ChattoCore) CleanupUserState

func (c *ChattoCore) CleanupUserState(ctx context.Context, userID string, kind RoomKind) error

CleanupUserState removes a user's per-kind room memberships. It is idempotent and safe to call for kinds the user never used.

Post-#330 there's no separate "space membership" record to delete — every authenticated user is implicitly a server member.

func (*ChattoCore) ClearGroupPermissionState

func (c *ChattoCore) ClearGroupPermissionState(ctx context.Context, actorID, groupID, roleName string, perm Permission) error

ClearGroupPermissionState removes both allow and deny for a role on a set.

func (*ChattoCore) ClearLoginChangeCooldown

func (c *ChattoCore) ClearLoginChangeCooldown(ctx context.Context, userID string) error

ClearLoginChangeCooldown removes the cooldown timestamp for a user, allowing them to immediately change their login again. Idempotent — clearing an already-clear cooldown is a no-op. Authorization: Caller must verify admin privileges.

func (*ChattoCore) ClearLoginChangeCooldownAs

func (c *ChattoCore) ClearLoginChangeCooldownAs(ctx context.Context, actorID, userID string) error

ClearLoginChangeCooldownAs removes the cooldown timestamp with explicit actor attribution. Authorization must be checked by the caller.

func (*ChattoCore) ClearRoomPermissionState

func (c *ChattoCore) ClearRoomPermissionState(ctx context.Context, actorID, roomID, roleName string, perm Permission) error

ClearRoomPermissionState removes both grant and denial for a permission at room level.

func (*ChattoCore) ClearServerPermissionState

func (c *ChattoCore) ClearServerPermissionState(ctx context.Context, actorID, roleName string, perm Permission) error

ClearServerPermissionState clears both grant and denial for a permission.

func (*ChattoCore) ClearUserAvatar

func (c *ChattoCore) ClearUserAvatar(ctx context.Context, actorID, targetUserID string) (*readmodel.User, error)

ClearUserAvatar removes the target user's avatar after applying the same authorization policy as UpdateUserAvatar. The operation is idempotent.

func (*ChattoCore) ClearUserCustomStatus

func (c *ChattoCore) ClearUserCustomStatus(ctx context.Context, userID string) (*readmodel.User, error)

ClearUserCustomStatus removes a user's durable custom status. It is idempotent and still records a clear event for explicit user action history.

func (*ChattoCore) ClearUserPermissionState

func (c *ChattoCore) ClearUserPermissionState(ctx context.Context, actorID, userID string, perm Permission) error

ClearUserPermissionState clears both the grant and denial for a user-level permission at server scope.

func (*ChattoCore) ClearUserRoomPermissionState

func (c *ChattoCore) ClearUserRoomPermissionState(ctx context.Context, actorID, roomID, userID string, perm Permission) error

ClearUserRoomPermissionState clears both the grant and denial for a user-level permission for a specific room.

func (*ChattoCore) CompleteBootstrappedSetup

func (c *ChattoCore) CompleteBootstrappedSetup(ctx context.Context) error

CompleteBootstrappedSetup records completion for trusted operator-created accounts. It runs after development bootstrap, before the HTTP listener starts.

func (*ChattoCore) CompleteFreshAuthReverification

func (c *ChattoCore) CompleteFreshAuthReverification(ctx context.Context, userID string, startedAt time.Time, issuer, subject string, authTime time.Time, cookieHandle string) error

CompleteFreshAuthReverification marks cookieHandle fresh after a provider verified issuer and subject with a sign-in at authTime. userID and startedAt come from the start of the re-verification in the same browser. The identity and the cookie session must both belong to userID, and authTime must not be earlier than startedAt. It never creates a session.

func (c *ChattoCore) CompleteLegacyOIDCIdentityLink(ctx context.Context, userID, providerID, issuer, subject string) error

CompleteLegacyOIDCIdentityLink records metadata for an existing hash-only link after the caller verifies the OIDC issuer and subject. It never creates a missing link or overwrites a complete one. The user OCC check prevents a concurrent unlink from being undone; a successful write waits for projections. Repeat calls are idempotent.

func (*ChattoCore) CompleteServerSetup

func (c *ChattoCore) CompleteServerSetup(ctx context.Context, input ServerSetupInput) error

CompleteServerSetup creates the owner, settings, and completion fact in one atomic EVT batch. All eligibility checks run again inside whole-EVT OCC. A lost response must be recovered through discovery and normal login, never by reopening setup. Required projections catch up before success is returned.

func (*ChattoCore) ConfigModel

func (c *ChattoCore) ConfigModel() *ConfigModel

ConfigModel returns the runtime configuration model.

func (*ChattoCore) ConfigureLiveKitCalls

func (c *ChattoCore) ConfigureLiveKitCalls(cfg config.LiveKitConfig) error

ConfigureLiveKitCalls applies admission and reconciliation settings before Run.

func (*ChattoCore) ConfigureLiveKitDiagnostics

func (c *ChattoCore) ConfigureLiveKitDiagnostics(cfg config.LiveKitConfig, publicURL string)

ConfigureLiveKitDiagnostics sets the LiveKit configuration and public server URL that owner diagnostics report and check. Call it once during startup.

func (c *ChattoCore) ConfirmPendingExternalIdentityLink(ctx context.Context, flow *PendingExternalIdentityFlow) (ExternalIdentity, error)

func (*ChattoCore) ConsumePendingExternalIdentityLinkStart

func (c *ChattoCore) ConsumePendingExternalIdentityLinkStart(ctx context.Context, token string) (*PendingExternalIdentityLinkStart, error)

func (*ChattoCore) ConsumePendingOAuthAuthorize

func (c *ChattoCore) ConsumePendingOAuthAuthorize(ctx context.Context, token string) (PendingOAuthAuthorize, error)

ConsumePendingOAuthAuthorize atomically claims and removes a pending browser flow so concurrent approval, denial, or completion requests cannot reuse it.

func (*ChattoCore) CookieSessionUser

func (c *ChattoCore) CookieSessionUser(ctx context.Context, cookieHandle string) (string, error)

CookieSessionUser returns the user of a valid first-party cookie session.

func (*ChattoCore) CountUserLimitAccounts

func (c *ChattoCore) CountUserLimitAccounts(ctx context.Context) (int, error)

CountUserLimitAccounts returns every account consuming the instance user limit: humans with a verified sign-in factor plus all active bot accounts.

func (*ChattoCore) CountUsers

func (c *ChattoCore) CountUsers(ctx context.Context) (int, error)

ListUsers retrieves all users from the user projection. CountUsers returns the total number of users on the server.

func (*ChattoCore) CountVerifiedAccounts

func (c *ChattoCore) CountVerifiedAccounts(ctx context.Context) (int, error)

CountVerifiedAccounts returns the number of distinct users with at least one verified sign-in factor: a verified email or linked external identity.

func (*ChattoCore) CreateAccountDeletionToken

func (c *ChattoCore) CreateAccountDeletionToken(ctx context.Context, userID string) (string, error)

CreateAccountDeletionToken generates a confirmation token for account deletion. The token is stored in RUNTIME_STATE and must be provided to DeleteUser within the TTL. Issuance enforces the human-account check and the caller's user.delete-self permission, so revoking that permission disables self-service deletion: no valid confirmation token can be issued or redeemed without it.

func (*ChattoCore) CreateAuthCode

func (c *ChattoCore) CreateAuthCode(ctx context.Context, userID, redirectURI, codeChallenge, codeChallengeMethod string) (string, error)

CreateAuthCode generates a new OAuth authorization code for the given user. The code is stored in RUNTIME_STATE with a "grant." key prefix and a 5-minute per-key TTL. The code is single-use — it must be exchanged via ExchangeAuthCode and is deleted on successful exchange.

func (*ChattoCore) CreateAuthCodeForClientGeneration

func (c *ChattoCore) CreateAuthCodeForClientGeneration(ctx context.Context, userID, clientID, redirectURI, codeChallenge, codeChallengeMethod string, authGeneration uint64) (string, error)

CreateAuthCodeForClientGeneration creates an OAuth authorization code bound to the validated public client and authenticated account generation.

func (*ChattoCore) CreateAuthCodeForClientGrantGeneration

func (c *ChattoCore) CreateAuthCodeForClientGrantGeneration(ctx context.Context, userID, clientID, resource string, scopes []string, redirectURI, codeChallenge, codeChallengeMethod string, authGeneration uint64) (string, error)

CreateAuthCodeForClientGrantGeneration creates an authorization code bound to the validated client, resource, scopes, and account generation.

func (*ChattoCore) CreateAuthCodeForGeneration

func (c *ChattoCore) CreateAuthCodeForGeneration(ctx context.Context, userID, redirectURI, codeChallenge, codeChallengeMethod string, authGeneration uint64) (string, error)

CreateAuthCodeForGeneration creates an OAuth authorization code for an already-authenticated session that proved authGeneration.

func (*ChattoCore) CreateAuthToken

func (c *ChattoCore) CreateAuthToken(ctx context.Context, userID string) (string, error)

CreateAuthToken creates a new opaque bearer token for the given user. The token is stored in RUNTIME_STATE and can be used for API authentication. Token expiry is handled by NATS KV TTL.

func (*ChattoCore) CreateAuthTokenWithSource

func (c *ChattoCore) CreateAuthTokenWithSource(ctx context.Context, userID, source string) (string, error)

CreateAuthTokenWithSource creates a new opaque bearer token and records the security-safe issuance fact in EVT. The raw token remains only in the return value and the HMAC-derived RUNTIME_STATE key.

func (*ChattoCore) CreateAuthTokenWithSourceGeneration

func (c *ChattoCore) CreateAuthTokenWithSourceGeneration(ctx context.Context, userID, source string, authGeneration uint64) (string, error)

CreateAuthTokenWithSourceGeneration creates a bearer token for an authentication that proved credentials against authGeneration.

func (*ChattoCore) CreateBearerSessionWithSource

func (c *ChattoCore) CreateBearerSessionWithSource(ctx context.Context, userID, source string) (BearerSessionCredentials, error)

CreateBearerSessionWithSource creates a renewable first-party bearer session.

func (*ChattoCore) CreateBearerSessionWithSourceGeneration

func (c *ChattoCore) CreateBearerSessionWithSourceGeneration(ctx context.Context, userID, source string, authGeneration uint64) (BearerSessionCredentials, error)

CreateBearerSessionWithSourceGeneration creates a renewable first-party bearer session for credentials proven against authGeneration.

func (*ChattoCore) CreateBot

func (c *ChattoCore) CreateBot(ctx context.Context, actorID, login, displayName string) (*Bot, error)

CreateBot creates a passwordless bot for the human caller or a bot caller's human owner, and returns its raw key once.

func (*ChattoCore) CreateBotAPIKey

func (c *ChattoCore) CreateBotAPIKey(ctx context.Context, actorID, botID, name string) (*BotAPIKeyIssue, error)

CreateBotAPIKey creates one named show-once credential. The raw credential is returned once and is never persisted.

func (*ChattoCore) CreateBotIncomingWebhook

func (c *ChattoCore) CreateBotIncomingWebhook(ctx context.Context, actorID, botID, name string) (*BotIncomingWebhookIssue, error)

CreateBotIncomingWebhook creates one named action-limited credential. The raw credential is returned once and is never persisted.

func (*ChattoCore) CreateBotOutboundWebhook

func (c *ChattoCore) CreateBotOutboundWebhook(ctx context.Context, actorID, botID, name, rawURL, authorization string, enabled bool) (*BotOutboundWebhook, string, error)

CreateBotOutboundWebhook creates an independent endpoint and returns its signing secret once. Paused endpoints count toward the limit.

func (*ChattoCore) CreateBotWithAPIKeyName

func (c *ChattoCore) CreateBotWithAPIKeyName(ctx context.Context, actorID, login, displayName, apiKeyName string) (*Bot, error)

CreateBotWithAPIKeyName creates a bot and names its initial show-once API key. A bot caller's human owner owns the new bot; creation grants no permissions.

func (*ChattoCore) CreateCookieSession

func (c *ChattoCore) CreateCookieSession(ctx context.Context, userID, source string) (string, *runtimestatev1.CookieSession, error)

CreateCookieSession creates a first-party runtime credential for same-origin cookie presentation and returns the opaque handle that should be stored in the signed browser cookie.

func (*ChattoCore) CreateCookieSessionForGeneration

func (c *ChattoCore) CreateCookieSessionForGeneration(ctx context.Context, userID, source string, authGeneration uint64) (string, *runtimestatev1.CookieSession, error)

CreateCookieSessionForGeneration creates a first-party cookie-presentation runtime credential for an authentication that proved credentials against authGeneration.

func (*ChattoCore) CreateCookieSessionValue

func (c *ChattoCore) CreateCookieSessionValue(ctx context.Context, sessionID string, value []byte, now time.Time) error

CreateCookieSessionValue commits a new opaque cookie session with physical retention through the record's authoritative expiry.

func (*ChattoCore) CreateDefaultRoles

func (c *ChattoCore) CreateDefaultRoles(ctx context.Context) error

CreateDefaultRoles appends the system roles and their default permissions to the RBAC aggregate. It is idempotent at the projection level.

func (*ChattoCore) CreateEmailVerificationCode

func (c *ChattoCore) CreateEmailVerificationCode(ctx context.Context, userID, email string) (string, error)

CreateEmailVerificationCode creates a short-lived verification code for an email. The returned raw code is intended to be sent by email and is never stored.

func (*ChattoCore) CreateHistoricalOperatorRoom

func (c *ChattoCore) CreateHistoricalOperatorRoom(ctx context.Context, key, group, name, description string) (*readmodel.Room, error)

CreateHistoricalOperatorRoom creates one channel, independently of archives.

func (*ChattoCore) CreateHistoricalOperatorUser

func (c *ChattoCore) CreateHistoricalOperatorUser(ctx context.Context, key, login, display, email string) (*readmodel.User, error)

CreateHistoricalOperatorUser creates one active human account with permanent retry protection. Email ownership remains enforced by ordinary account creation.

func (*ChattoCore) CreateInvitationCode

func (c *ChattoCore) CreateInvitationCode(ctx context.Context, actorID string, note string) (InvitationState, error)

CreateInvitationCode grants admission for exactly one new account for seven days. The server sets expiry for all callers. The note is optional.

func (*ChattoCore) CreateLinkPreviewToken

func (c *ChattoCore) CreateLinkPreviewToken(ctx context.Context, url string) (string, error)

CreateLinkPreviewToken stores a short-lived opaque reference to a cached server-fetched preview URL.

func (*ChattoCore) CreateNeighbor

func (c *ChattoCore) CreateNeighbor(ctx context.Context, actorID, rawOrigin string) (Neighbor, error)

CreateNeighbor adds one canonical server origin to the public directory.

func (*ChattoCore) CreateOAuthAccessTokenForClient

func (c *ChattoCore) CreateOAuthAccessTokenForClient(ctx context.Context, userID, clientID string, authGeneration uint64) (string, error)

CreateOAuthAccessTokenForClient creates a bearer token bound to the public OAuth client that completed the authorization-code flow.

func (*ChattoCore) CreateOAuthBearerSessionForClient

func (c *ChattoCore) CreateOAuthBearerSessionForClient(ctx context.Context, userID, clientID string, authGeneration uint64) (BearerSessionCredentials, error)

CreateOAuthBearerSessionForClient creates a renewable delegated bearer session bound to the public OAuth client that completed authorization.

func (*ChattoCore) CreateOAuthBearerSessionForClientGrant

func (c *ChattoCore) CreateOAuthBearerSessionForClientGrant(ctx context.Context, userID, clientID, resource string, scopes []string, authGeneration uint64) (BearerSessionCredentials, error)

CreateOAuthBearerSessionForClientGrant creates a delegated bearer session bound to one OAuth resource and its normalized scope set.

func (*ChattoCore) CreateOAuthClientAuthorizationCode

func (c *ChattoCore) CreateOAuthClientAuthorizationCode(ctx context.Context, authorization OAuthClientAuthorization, redirectURI, codeChallenge, codeChallengeMethod string, authGeneration uint64) (string, error)

CreateOAuthClientAuthorizationCode creates an authorization code before it records the successful client authorization. If the durable record cannot be committed, the undisclosed code is removed so callers cannot complete an authorization that is absent from the administrator inventory.

func (*ChattoCore) CreateOAuthClientAuthorizationCodeForGrant

func (c *ChattoCore) CreateOAuthClientAuthorizationCodeForGrant(ctx context.Context, authorization OAuthClientAuthorization, resource string, scopes []string, redirectURI, codeChallenge, codeChallengeMethod string, authGeneration uint64) (string, error)

CreateOAuthClientAuthorizationCodeForGrant creates a code bound to one delegated resource and normalized scope set before it records authorization.

func (*ChattoCore) CreatePasswordResetToken

func (c *ChattoCore) CreatePasswordResetToken(ctx context.Context, email string) (string, error)

CreatePasswordResetToken creates a new password reset token for a verified email. If the email is not found or not verified, returns ("", nil) to prevent email enumeration. Only verified emails can trigger password reset.

func (*ChattoCore) CreatePendingExternalIdentityCreateFlow

func (c *ChattoCore) CreatePendingExternalIdentityCreateFlow(ctx context.Context, flow PendingExternalIdentityFlow) (string, error)

func (*ChattoCore) CreatePendingExternalIdentityLinkFlow

func (c *ChattoCore) CreatePendingExternalIdentityLinkFlow(ctx context.Context, flow PendingExternalIdentityFlow, userID string) (string, error)

func (*ChattoCore) CreatePendingExternalIdentityLinkStart

func (c *ChattoCore) CreatePendingExternalIdentityLinkStart(ctx context.Context, providerID, redirectPath, userID string) (string, error)

func (*ChattoCore) CreatePendingOAuthAuthorize

func (c *ChattoCore) CreatePendingOAuthAuthorize(ctx context.Context, pending PendingOAuthAuthorize) (string, error)

CreatePendingOAuthAuthorize stores a validated browser authorization flow and returns the opaque handle that may be placed in the signed session cookie.

func (*ChattoCore) CreateRegistrationCode

func (c *ChattoCore) CreateRegistrationCode(ctx context.Context, email string) (string, error)

CreateRegistrationCode creates a short-lived registration code for an email. It returns the raw six-digit code so the caller can send it by email. The code itself is never stored; only an HMAC-derived lookup key is kept in RUNTIME_STATE.

func (*ChattoCore) CreateRegistrationCodeForInvitation

func (c *ChattoCore) CreateRegistrationCodeForInvitation(ctx context.Context, email, invitationID string) (string, error)

CreateRegistrationCodeForInvitation binds the email-verification flow to a previously validated invitation without storing the raw capability.

func (*ChattoCore) CreateRegistrationCompletionToken

func (c *ChattoCore) CreateRegistrationCompletionToken(ctx context.Context, email string) (string, error)

CreateRegistrationCompletionToken creates a high-entropy token after the email code has been verified. This token is used by /auth/register/complete and is not sent by email.

func (*ChattoCore) CreateRegistrationToken

func (c *ChattoCore) CreateRegistrationToken(ctx context.Context, email string) (string, error)

CreateRegistrationToken is kept as a test/back-compat helper for callers that need to bypass email delivery and code entry.

func (*ChattoCore) CreateRoom

func (c *ChattoCore) CreateRoom(ctx context.Context, actorID string, kind RoomKind, groupID, name, description string, opts ...CreateRoomOption) (*readmodel.Room, error)

CreateRoom creates a new room. Authorization: Caller must verify CanCreateRoom before calling.

groupID identifies the RoomGroup the room belongs to. DM rooms pass empty. For channel rooms an empty groupID auto-routes to the first group in the layout (seed "Lobby" group on fresh deployments) — see ADR-031.

ADR-035 phase 6: event-only. Name uniqueness is enforced via JetStream wildcard OCC against `evt.room.>` — the room service reads a catalog snapshot containing both the name owner and the applied evt.room.> sequence, then publishes RoomCreatedEvent, any selected channel room-group membership fact, and any channel-room default permission facts as one atomic batch with that seq as the expected-last for the filter. Concurrent room mutations from any process (this one or another replica) advance the filter's seq and cause our publish to fail; we re-check uniqueness from the (now-caught-up) projection and retry.

func (*ChattoCore) CreateSelfServiceUser

func (c *ChattoCore) CreateSelfServiceUser(ctx context.Context, actorID, login, displayName, password, email, invitationID string) (*readmodel.User, error)

CreateSelfServiceUser completes self-service email registration with an already-verified address under the current admission policy. An empty invitation is allowed only when registration is open. Invitation redemption and account creation commit atomically when required.

func (*ChattoCore) CreateServerRole

func (c *ChattoCore) CreateServerRole(ctx context.Context, actorID, name, displayName, description string, pingableValue ...bool) (*RoleWithPermissions, error)

CreateServerRole creates a new custom role. Role names must be lowercase letters only (e.g., "editor", "moderator"). System role names (owner, admin, moderator, everyone) are reserved.

func (*ChattoCore) CreateUser

func (c *ChattoCore) CreateUser(ctx context.Context, actorID string, login, displayName, password string) (*readmodel.User, error)

CreateUser creates a new user. Uses the mentionables projection plus stream-wide OCC to prevent user/role handle collisions across replicas. Password is optional - pass empty string for OAuth-only users.

func (*ChattoCore) CreateUserForExternalIdentity

func (c *ChattoCore) CreateUserForExternalIdentity(ctx context.Context, login, displayName string, flow *PendingExternalIdentityFlow) (*readmodel.User, error)

func (*ChattoCore) CreateVerifiedUser

func (c *ChattoCore) CreateVerifiedUser(ctx context.Context, actorID, login, displayName, password, email string) (*readmodel.User, error)

CreateVerifiedUser atomically creates a user with an already-verified email.

This trusted entry point bypasses registration admission. Self-service email registration must use CreateSelfServiceUser, even when registration is open.

func (*ChattoCore) CurrentAuthGeneration

func (c *ChattoCore) CurrentAuthGeneration(ctx context.Context, userID string) (uint64, error)

CurrentAuthGeneration returns the current auth generation of the user with a strict auth generation check: it waits until the User Auth projection of this replica has applied the newest generation-relevant event of the user on the EVT stream leader. It returns ErrAuthenticationRevoked when the user is unknown, deleted, or deactivated. An acceptance starts the auth generation check window of the user on this replica (ADR-127).

func (*ChattoCore) CurrentMessageBodyVersion

func (c *ChattoCore) CurrentMessageBodyVersion(eventID string) MessageBodyVersion

CurrentMessageBodyVersion returns the body version of a message from the room timeline and content-key projections. It does no I/O. Read it before GetFullMessageBody to find out later whether a body read is still current.

func (*ChattoCore) DeleteAllUserPushSubscriptions

func (c *ChattoCore) DeleteAllUserPushSubscriptions(ctx context.Context, userID string) (int, error)

DeleteAllUserPushSubscriptions removes all push subscriptions for a user. Used when a user account is deleted. Authorization: Internal use only - called from user deletion flow.

func (*ChattoCore) DeleteAttachmentFromMessage

func (c *ChattoCore) DeleteAttachmentFromMessage(ctx context.Context, actorID string, kind RoomKind, roomID, eventID, attachmentID string) error

DeleteAttachmentFromMessage deletes a single attachment from a message. Only the message author can delete their attachments. Emits a MessageEditedEvent with the attachment removed; also deletes the file from the asset store best-effort.

func (*ChattoCore) DeleteAttachmentFromStorage

func (c *ChattoCore) DeleteAttachmentFromStorage(ctx context.Context, attachment *evtv1.Attachment) error

func (*ChattoCore) DeleteBot

func (c *ChattoCore) DeleteBot(ctx context.Context, actorID, botID string) (bool, error)

DeleteBot permanently deletes a managed bot. Repeated calls are idempotent.

func (*ChattoCore) DeleteCookieSessionValue

func (c *ChattoCore) DeleteCookieSessionValue(ctx context.Context, sessionID string, revision uint64) error

DeleteCookieSessionValue removes a cookie session only if it still has the revision loaded by the request. This is intended for conditional cleanup; explicit logout uses RevokeCookieSession so it fences every earlier writer.

func (*ChattoCore) DeleteJob

func (c *ChattoCore) DeleteJob(ctx context.Context, actorID, id, expectedVersion string) error

DeleteJob removes a failed job. Its work is abandoned. OCC on the facts of the job makes a concurrent retry and a delete exclusive.

func (*ChattoCore) DeleteLinkPreviewFromMessage

func (c *ChattoCore) DeleteLinkPreviewFromMessage(ctx context.Context, actorID string, kind RoomKind, roomID, eventID, previewURL string) error

DeleteLinkPreviewFromMessage removes a link preview from a message. Only the message author can delete link previews from their messages.

func (*ChattoCore) DeleteManagedServerBanner

func (c *ChattoCore) DeleteManagedServerBanner(ctx context.Context, actorID string) error
func (c *ChattoCore) DeleteManagedServerLogo(ctx context.Context, actorID string) error

func (*ChattoCore) DeleteMessage

func (c *ChattoCore) DeleteMessage(ctx context.Context, actorID string, kind RoomKind, roomID, eventID string, opts ...DeleteMessageOption) error

DeleteMessage retracts a message. For ordinary messages and original thread replies, the retraction removes visible content and attachments for GDPR compliance while preserving the event in the stream for audit. For echoes, the same durable MessageRetractedEvent hides only the echo artifact from the room timeline; the original thread reply remains readable. Authorization: Caller must verify the actor is the message author OR CanManageOthersMessage before calling.

func (*ChattoCore) DeleteNeighbor

func (c *ChattoCore) DeleteNeighbor(ctx context.Context, actorID, neighborID, revision string) error

DeleteNeighbor removes one Neighbor if its revision is current.

func (*ChattoCore) DeletePendingExternalIdentityFlow

func (c *ChattoCore) DeletePendingExternalIdentityFlow(ctx context.Context, token string) error

func (*ChattoCore) DeletePushSubscription

func (c *ChattoCore) DeletePushSubscription(ctx context.Context, userID, endpoint string) error

DeletePushSubscription removes a push subscription by endpoint. Authorization: Caller must verify userID matches authenticated user.

func (*ChattoCore) DeletePushSubscriptionByCapability

func (c *ChattoCore) DeletePushSubscriptionByCapability(ctx context.Context, endpoint, auth, cleanupToken string) error

DeletePushSubscriptionByCapability removes only the exact current endpoint owner whose browser Push API auth secret and per-save token match. It is safe to call without an account session after a cancelled registration settles: later saves fail the token/revision checks even when they reuse the same browser subscription credentials.

func (*ChattoCore) DeleteRegistrationToken

func (c *ChattoCore) DeleteRegistrationToken(ctx context.Context, token string) error

DeleteRegistrationToken removes a completion token after successful account creation.

func (*ChattoCore) DeleteServerBanner

func (c *ChattoCore) DeleteServerBanner(ctx context.Context, actorID string) error

DeleteServerBanner clears the server's banner. No-op when no banner is set.

func (c *ChattoCore) DeleteServerLogo(ctx context.Context, actorID string) error

DeleteServerLogo clears the server's logo and requests cleanup of its stored image. No-op when no logo is set.

func (*ChattoCore) DeleteServerRole

func (c *ChattoCore) DeleteServerRole(ctx context.Context, actorID, name string) error

DeleteServerRole deletes a custom role and all its associated data. This includes: the role definition, all permission grants, and all user assignments. System roles (owner, admin, moderator, everyone) cannot be deleted.

func (*ChattoCore) DeleteUser

func (c *ChattoCore) DeleteUser(ctx context.Context, actorID, userID string) error

DeleteUser permanently deletes a user account and all associated data. This performs GDPR-compliant deletion including removal of message bodies. Authorization: Caller must verify CanDeleteUser(actorID, userID) before calling.

func (*ChattoCore) DeleteUserAvatar

func (c *ChattoCore) DeleteUserAvatar(ctx context.Context, userID string) error

DeleteUserAvatar removes a user's avatar from storage (NATS or S3). Returns nil if the user has no avatar set.

func (*ChattoCore) DeleteUserEncryptionKeyAs

func (c *ChattoCore) DeleteUserEncryptionKeyAs(ctx context.Context, actorID, userID string) error

func (*ChattoCore) DenyGroupPermission

func (c *ChattoCore) DenyGroupPermission(ctx context.Context, actorID, groupID, roleName string, perm Permission) error

DenyGroupPermission writes a group-scope deny for a role on a specific room group.

func (*ChattoCore) DenyRoomPermission

func (c *ChattoCore) DenyRoomPermission(ctx context.Context, actorID, roomID, roleName string, perm Permission) error

DenyRoomPermission denies a permission for a role at a specific room.

func (*ChattoCore) DenyServerPermission

func (c *ChattoCore) DenyServerPermission(ctx context.Context, actorID, roleName string, perm Permission) error

DenyServerPermission denies a permission at a role's server-level default.

func (*ChattoCore) DenyUserPermission

func (c *ChattoCore) DenyUserPermission(ctx context.Context, actorID, userID string, perm Permission) error

DenyUserPermission denies a permission directly to a user at server scope.

func (*ChattoCore) DenyUserRoomPermission

func (c *ChattoCore) DenyUserRoomPermission(ctx context.Context, actorID, roomID, userID string, perm Permission) error

DenyUserRoomPermission denies a permission directly to a user for a specific room.

func (*ChattoCore) DiscardPendingOAuthAuthorize

func (c *ChattoCore) DiscardPendingOAuthAuthorize(ctx context.Context, token string) error

DiscardPendingOAuthAuthorize removes an abandoned or superseded browser flow.

func (*ChattoCore) DisconnectExternalIdentityAs

func (c *ChattoCore) DisconnectExternalIdentityAs(ctx context.Context, actorID, userID, subjectHash string, policy ExternalIdentitySignInPolicy) error

DisconnectExternalIdentityAs removes a link with explicit actor attribution. It refuses removal when no method enabled by policy would remain. The check runs inside user OCC, so concurrent removals cannot remove both last methods. Existing sessions remain valid. A missing link returns ErrExternalIdentityNotFound.

func (*ChattoCore) EditMessage

func (c *ChattoCore) EditMessage(ctx context.Context, actorID string, kind RoomKind, roomID, eventID, newBody string, opts ...EditMessageOption) error

EditMessage edits a message body. Updates the body content and sets updated_at. Publishes a MessageEditedEvent to notify connected clients in real-time. Business rule: Authors can edit their own messages within MessageEditWindow (3 hours). Effective message.manage bypasses the window and also permits editing other authors' messages.

Authorization: Caller must verify the actor is the author OR CanManageOthersMessage before calling.

func (*ChattoCore) EventLogEventTypes

func (c *ChattoCore) EventLogEventTypes(ctx context.Context, userID string) ([]string, error)

func (*ChattoCore) EventStreamForDebug

func (c *ChattoCore) EventStreamForDebug(_ context.Context) (jetstream.Stream, error)

EventStreamForDebug returns the EVT stream. Intended for the `chatto evt list` command and similar low-level operator tooling that reads raw stream messages. Domain code goes through EventPublisher / Projector instead.

func (*ChattoCore) ExchangeAuthCode

func (c *ChattoCore) ExchangeAuthCode(ctx context.Context, code, codeVerifier, redirectURI string) (string, string, error)

ExchangeAuthCode validates an authorization code and PKCE code_verifier, deletes the code (single-use enforcement), and returns a new bearer token.

Validation checks:

  1. Code exists and hasn't expired (NATS TTL)
  2. redirect_uri matches the one used during authorization
  3. SHA256(code_verifier) == code_challenge (PKCE S256)

func (*ChattoCore) ExchangeAuthCodeForClient

func (c *ChattoCore) ExchangeAuthCodeForClient(ctx context.Context, code, codeVerifier, redirectURI, clientID string) (string, string, error)

ExchangeAuthCodeForClient exchanges a single-use authorization code and requires both its exact redirect URI and client identifier to match.

func (*ChattoCore) ExchangeAuthCodeForClientResourceSession

func (c *ChattoCore) ExchangeAuthCodeForClientResourceSession(ctx context.Context, code, codeVerifier, redirectURI, clientID, resource string) (BearerSessionCredentials, string, error)

ExchangeAuthCodeForClientResourceSession exchanges a code and requires its exact OAuth resource identifier to match the token request.

func (*ChattoCore) ExchangeAuthCodeForClientSession

func (c *ChattoCore) ExchangeAuthCodeForClientSession(ctx context.Context, code, codeVerifier, redirectURI, clientID string) (BearerSessionCredentials, string, error)

ExchangeAuthCodeForClientSession exchanges a single-use authorization code for a renewable bearer session and requires its exact redirect URI, client identifier, and PKCE proof to match.

func (*ChattoCore) ExplainPermissions

func (c *ChattoCore) ExplainPermissions(ctx context.Context, actorID, targetUserID, roomID string) ([]PermissionExplanation, error)

func (*ChattoCore) ExplainPermissionsAtScope

func (c *ChattoCore) ExplainPermissionsAtScope(ctx context.Context, actorID, targetUserID string, target PermissionTargetScope) ([]PermissionExplanation, error)

ExplainPermissionsAtScope returns permission explanations for a server, direct-message, or channel-room target.

func (*ChattoCore) ExternalIdentitiesForUser

func (c *ChattoCore) ExternalIdentitiesForUser(ctx context.Context, userID string) ([]ExternalIdentity, error)

ExternalIdentitiesForUser returns detached identity links for an existing human account, ordered by provider ID and hash. It catches up both user and authentication projections. The raw issuer and subject require an account- owner or operator response boundary; they must not be logged.

func (*ChattoCore) FetchRemoteImage

func (c *ChattoCore) FetchRemoteImage(ctx context.Context, rawURL string) ([]byte, error)

FetchRemoteImage downloads the raw bytes of a remote image with the SSRF-safe client and the default size limit. It returns an error that wraps remoteimage.ErrRejected when the remote host does not supply an acceptable response. Errors do not contain the URL; callers must not log it.

After a failure, every replica skips the source for remoteImageFailureTTL, so a broken or slow host does not cause a remote request for each client request.

func (*ChattoCore) FindOrCreateDM

func (c *ChattoCore) FindOrCreateDM(ctx context.Context, creatorID string, participantIDs []string) (*readmodel.Room, bool, error)

FindOrCreateDM finds an existing DM conversation or creates a new one. The caller (creatorID) is automatically included in the participant list. Returns the room and a boolean indicating whether it was newly created.

For existing DMs, the caller must already be a participant. For new DMs, all participants are automatically joined to the room.

func (*ChattoCore) FindRoomByID

func (c *ChattoCore) FindRoomByID(ctx context.Context, room_id string) (*readmodel.Room, error)

FindRoomByID resolves a room from its ID alone (no kind probe). Returns ErrNotFound if the room isn't in the catalog.

Live events carry only a room ID (no kind discriminator on the wire), so resolvers and consumers downstream of those events use this to recover both the room and the kind context (via KindOfRoom on the result).

func (*ChattoCore) FindRoomKind

func (c *ChattoCore) FindRoomKind(ctx context.Context, room_id string) (RoomKind, error)

FindRoomKind is a thin wrapper around FindRoomByID for callers that only need the kind. The room load is paid either way; the wrapper is just there for ergonomics.

func (*ChattoCore) FollowThread

func (c *ChattoCore) FollowThread(ctx context.Context, kind RoomKind, userID, roomID, threadRootEventID string) error

FollowThread marks a user as following a thread so they receive reply notifications. Stores durable follow state in EVT. Idempotent. Publishes a ThreadViewerStateChangedEvent for multi-tab sync when state changes.

func (*ChattoCore) FollowThreadIfNeverSet

func (c *ChattoCore) FollowThreadIfNeverSet(ctx context.Context, kind RoomKind, userID, roomID, threadRootEventID string, source evtv1.ThreadFollowSource) (bool, error)

FollowThreadIfNeverSet follows a thread only when the user has no prior follow state. Explicit unfollows and existing follows are left untouched.

func (*ChattoCore) FollowThreadWithSource

func (c *ChattoCore) FollowThreadWithSource(ctx context.Context, kind RoomKind, userID, roomID, threadRootEventID string, source evtv1.ThreadFollowSource) error

func (*ChattoCore) GetAccountInfo

func (c *ChattoCore) GetAccountInfo(ctx context.Context) (*AccountInfo, error)

GetAccountInfo retrieves JetStream account information.

func (*ChattoCore) GetActiveCall

func (c *ChattoCore) GetActiveCall(roomID string) (CallSession, bool, error)

GetActiveCall returns the current projected call session for a room. Authorization: Caller must verify room visibility before calling.

func (*ChattoCore) GetActiveCallRoomIDs

func (c *ChattoCore) GetActiveCallRoomIDs(context.Context) ([]string, error)

GetActiveCallRoomIDs returns every room ID that has an active voice call. Reads from the call-state projection, not MEMORY_CACHE. Authorization: Caller must filter the result to rooms visible to the actor.

func (*ChattoCore) GetAdminDiagnostics

func (c *ChattoCore) GetAdminDiagnostics(ctx context.Context, actorID string) (*AdminDiagnostics, error)

func (*ChattoCore) GetAdminMemberDetails

func (c *ChattoCore) GetAdminMemberDetails(ctx context.Context, actorID, targetUserID string) (*AdminMemberDetails, error)

func (*ChattoCore) GetAssetCount

func (c *ChattoCore) GetAssetCount(ctx context.Context) (int, error)

GetAssetCount returns the number of assets (attachments) on the server.

func (*ChattoCore) GetAssetState

func (c *ChattoCore) GetAssetState(assetID string) AssetState

GetAssetState returns one detached, generation-consistent view of an asset's declaration, room scope, processing manifest, and deletion state. A missing model or projection returns the zero state so authorization callers fail closed during incomplete initialization.

func (*ChattoCore) GetAttachmentReader

func (c *ChattoCore) GetAttachmentReader(ctx context.Context, attachment *evtv1.Attachment) (io.Reader, *AttachmentInfo, error)

func (*ChattoCore) GetBot

func (c *ChattoCore) GetBot(ctx context.Context, actorID, botID string) (*Bot, error)

GetBot returns one bot visible to the caller without optional credential-use telemetry. Response assembly can hydrate that state later.

func (*ChattoCore) GetBotOutboundWebhook

func (c *ChattoCore) GetBotOutboundWebhook(ctx context.Context, actorID, botID, webhookID string) (*BotOutboundWebhook, error)

GetBotOutboundWebhook reads one endpoint within a managed bot's collection.

func (*ChattoCore) GetCachedResize

func (c *ChattoCore) GetCachedResize(ctx context.Context, key string) ([]byte, error)

func (*ChattoCore) GetCallParticipants

func (c *ChattoCore) GetCallParticipants(roomID string) ([]CallParticipant, error)

GetCallParticipants returns the participants currently in a voice call. Returns an empty slice if no call is active. Authorization: Caller must verify room membership before calling.

func (*ChattoCore) GetCallSnapshot

func (c *ChattoCore) GetCallSnapshot(roomID string) (CallRoomSnapshot, error)

GetCallSnapshot returns one generation-consistent projected call snapshot. Authorization: Caller must verify room visibility before calling.

func (*ChattoCore) GetConnectionInfo

func (c *ChattoCore) GetConnectionInfo() *ConnectionInfo

GetConnectionInfo retrieves NATS connection information.

func (*ChattoCore) GetDMRolePermissions

func (c *ChattoCore) GetDMRolePermissions(ctx context.Context, roleName string) (grants []Permission, denials []Permission, err error)

GetDMRolePermissions returns the direct-message-scope grants and denials for a role.

func (*ChattoCore) GetEffectiveNotificationModeForSignal

func (c *ChattoCore) GetEffectiveNotificationModeForSignal(userID, roomID string, signal *notificationv1.NotificationSignal) evtv1.NotificationDeliveryMode

GetEffectiveNotificationModeForSignal resolves room, current room-group, server, and product-default policy for the rich signal variant.

func (*ChattoCore) GetEventLogEntry

func (c *ChattoCore) GetEventLogEntry(ctx context.Context, userID, sequence string) (*EventLogEntry, error)

func (*ChattoCore) GetEventSequence

func (c *ChattoCore) GetEventSequence(ctx context.Context, kind RoomKind, roomID, eventID string) (uint64, error)

GetEventSequence returns the stream sequence number for an event by its envelope id, or 0 if not found.

func (*ChattoCore) GetFullMessageBody

func (c *ChattoCore) GetFullMessageBody(ctx context.Context, eventID string) (*DecryptedMessageBody, error)

GetFullMessageBody returns the decrypted message body for a message event, folding any subsequent edit or retract events to produce the current body. Returns nil if the message has been retracted or doesn't exist, or if the author's encryption key has been crypto-shredded.

func (*ChattoCore) GetGroupRolePermissions

func (c *ChattoCore) GetGroupRolePermissions(ctx context.Context, groupID, roleName string) (grants []Permission, denials []Permission, err error)

GetGroupRolePermissions returns the set-scope grants and denials for a role in a specific room group (ADR-031).

func (*ChattoCore) GetInvitation

func (c *ChattoCore) GetInvitation(ctx context.Context, actorID, id string) (InvitationState, error)

GetInvitation returns a visible code. Inaccessible and unknown IDs both return ErrNotFound.

func (*ChattoCore) GetJetStreamStats

func (c *ChattoCore) GetJetStreamStats(ctx context.Context) (*JetStreamStats, error)

GetJetStreamStats lists current JetStream streams and consumers.

func (*ChattoCore) GetJob

func (c *ChattoCore) GetJob(ctx context.Context, actorID, id string) (jobqueue.Job, error)

GetJob requires the same management permission as list and retry.

func (*ChattoCore) GetLastLoginChange

func (c *ChattoCore) GetLastLoginChange(ctx context.Context, userID string) (time.Time, error)

GetLastLoginChange returns when the user last changed their login. Returns zero time if the user has never changed their login.

func (*ChattoCore) GetLinkPreview

func (c *ChattoCore) GetLinkPreview(ctx context.Context, url string) (*evtv1.LinkPreview, error)

GetLinkPreview fetches link preview metadata for a URL. Results are cached server-side. Returns nil if the URL cannot be previewed.

func (*ChattoCore) GetManagedNeighbor

func (c *ChattoCore) GetManagedNeighbor(ctx context.Context, actorID, neighborID string) (Neighbor, error)

GetManagedNeighbor returns one Neighbor to an authorized administrator.

func (*ChattoCore) GetManagedServerConfig

func (c *ChattoCore) GetManagedServerConfig(ctx context.Context, actorID string) (*configv1.ServerConfig, error)

func (*ChattoCore) GetMessageBody

func (c *ChattoCore) GetMessageBody(ctx context.Context, eventID string) (string, error)

GetMessageBody is a thin wrapper returning just the plaintext body text. Same semantics as GetFullMessageBody: retracted or crypto- shredded messages return empty string.

func (*ChattoCore) GetOAuthClient

func (c *ChattoCore) GetOAuthClient(ctx context.Context, actorID, clientID string) (OAuthClientState, error)

func (*ChattoCore) GetPendingExternalIdentityCreateFlow

func (c *ChattoCore) GetPendingExternalIdentityCreateFlow(ctx context.Context, token string) (*PendingExternalIdentityFlow, error)

func (*ChattoCore) GetPendingExternalIdentityFlow

func (c *ChattoCore) GetPendingExternalIdentityFlow(ctx context.Context, token string) (*PendingExternalIdentityFlow, error)

func (*ChattoCore) GetPendingExternalIdentityLinkFlow

func (c *ChattoCore) GetPendingExternalIdentityLinkFlow(ctx context.Context, token, userID string) (*PendingExternalIdentityFlow, error)

func (*ChattoCore) GetPendingOAuthAuthorize

func (c *ChattoCore) GetPendingOAuthAuthorize(ctx context.Context, token string) (PendingOAuthAuthorize, error)

GetPendingOAuthAuthorize reads a pending browser flow without consuming it.

func (*ChattoCore) GetPresencePreference

func (c *ChattoCore) GetPresencePreference(ctx context.Context, userID string) (*apiv1.PresencePreference, error)

GetPresencePreference returns the private saved choice. Callers must enforce self-only authorization. Missing choices are left absent for safe migration.

func (*ChattoCore) GetPublicServerAsset

func (c *ChattoCore) GetPublicServerAsset(ctx context.Context, location *PublicServerAssetLocation) (io.Reader, *ServerAssetInfo, error)

GetPublicServerAsset opens only the exact object previously classified by ResolvePublicServerAsset. It never probes a fallback backend or key.

func (*ChattoCore) GetReactions

func (c *ChattoCore) GetReactions(ctx context.Context, messageEventID string) ([]ReactionSummary, error)

GetReactions returns all reactions for a message, aggregated by emoji shortcode name. Returns a slice of ReactionSummary, each containing the shortcode name and list of user IDs. Results are ordered by the time each emoji was first added (earliest first).

func (*ChattoCore) GetReactionsBatch

func (c *ChattoCore) GetReactionsBatch(ctx context.Context, eventIDs []string) (map[string][]ReactionSummary, error)

GetReactionsBatch returns reactions for multiple messages in a single pass. Returns a map from messageEventID to sorted ReactionSummary slices.

func (*ChattoCore) GetRegistrationToken

func (c *ChattoCore) GetRegistrationToken(ctx context.Context, token string) (*RegistrationToken, error)

GetRegistrationToken retrieves and validates a registration completion token. Returns the token data including the email address.

func (*ChattoCore) GetRolePermissionDMTierMatrix

func (c *ChattoCore) GetRolePermissionDMTierMatrix(ctx context.Context, actorID string) (*TierRoles, error)

GetRolePermissionDMTierMatrix returns the role matrix for the singleton direct-message scope.

func (*ChattoCore) GetRolePermissionMatrix

func (c *ChattoCore) GetRolePermissionMatrix(ctx context.Context, actorID, roleName string) (*RolePermissionMatrix, error)

func (*ChattoCore) GetRolePermissionMatrixIncludingDM

func (c *ChattoCore) GetRolePermissionMatrixIncludingDM(ctx context.Context, actorID, roleName string, includeDM bool) (*RolePermissionMatrix, error)

GetRolePermissionMatrixIncludingDM returns the complete matrix, optionally including DMs.

func (*ChattoCore) GetRolePermissionMatrixPage

func (c *ChattoCore) GetRolePermissionMatrixPage(ctx context.Context, actorID, roleName string, includeDM bool, query PermissionScopeQuery) (*RolePermissionMatrix, error)

GetRolePermissionMatrixPage authorizes and evaluates the selected scopes.

func (*ChattoCore) GetRolePermissionTierMatrix

func (c *ChattoCore) GetRolePermissionTierMatrix(ctx context.Context, actorID, roomID, groupID string) (*TierRoles, error)

func (*ChattoCore) GetRoleUsers

func (c *ChattoCore) GetRoleUsers(ctx context.Context, roleName string) ([]string, error)

GetRoleUsers returns all user IDs explicitly assigned to a role. The implicit `everyone` role returns []; all authenticated users carry it.

func (*ChattoCore) GetRoom

func (c *ChattoCore) GetRoom(ctx context.Context, kind RoomKind, room_id string) (*readmodel.Room, error)

GetRoom retrieves a room by id.

Reads come from RoomModel's room catalog and group-layout state for the group_id field. Returns ErrNotFound (wrapped) if the room isn't projected OR if its kind doesn't match the requested kind — keeping the "the wrong kind is not found" semantic so callers don't accidentally read a DM via a channel-kind probe.

func (*ChattoCore) GetRoomAsset

func (c *ChattoCore) GetRoomAsset(ctx context.Context, input RoomAssetInput) (*evtv1.Attachment, error)

GetRoomAsset returns one room-scoped asset for a room the actor may read. Missing, deleted, and wrong-room asset IDs return ErrNotFound.

func (*ChattoCore) GetRoomAttachments

func (c *ChattoCore) GetRoomAttachments(ctx context.Context, kind RoomKind, roomID string, limit int, offset int) (*RoomAttachmentsResult, error)

GetRoomAttachments returns current message-owned attachments in newest message order. It includes root messages and thread replies, reads the room timeline projection's current attachment-message index, and preserves attachment order within each message.

Authorization: caller must verify room membership and applicable applicable message-read authority before calling.

func (*ChattoCore) GetRoomEventByEventID

func (c *ChattoCore) GetRoomEventByEventID(ctx context.Context, kind RoomKind, roomID, eventID string) (*evtv1.Event, error)

GetRoomEventByEventID returns a room event by its envelope id, or nil if not found. Supports posted messages, including thread replies and channel echoes, plus visible lifecycle/meta events.

Authorization: caller must verify room membership before calling.

func (*ChattoCore) GetRoomEvents

func (c *ChattoCore) GetRoomEvents(ctx context.Context, kind RoomKind, room_id string, limit int, beforeSeq *uint64) (*RoomEventsResult, error)

GetRoomEvents returns up to `limit` most recent room timeline entries in oldest-first order (chronological — matches the legacy SERVER_EVENTS-backed shape). If `beforeSeq` is non-nil, only entries with stream sequence strictly less than `*beforeSeq` are returned.

Reads from the in-memory RoomTimelineProjection (ADR-033 / #597). The projection stores the room-visible event log; folded facts such as thread replies, edits, retractions, reactions, and asset processing are handled by sibling projections or derived indexes.

Authorization: caller must verify room membership before calling. The `kind` parameter is retained on the signature for API stability with the legacy SERVER_EVENTS-backed implementation; the projection is kind-agnostic (the room aggregate's subject is evt.room.{R}.{eventType} — kind is a property of the room, not the event).

func (*ChattoCore) GetRoomEventsAfter

func (c *ChattoCore) GetRoomEventsAfter(ctx context.Context, kind RoomKind, roomID string, afterSeq uint64, limit int) (*RoomEventsResult, error)

GetRoomEventsAfter returns up to `limit` events with stream sequence strictly greater than afterSeq, oldest-first (i.e. forward pagination order).

Authorization: caller must verify room membership before calling.

func (*ChattoCore) GetRoomEventsAround

func (c *ChattoCore) GetRoomEventsAround(ctx context.Context, kind RoomKind, roomID, eventID string, limit int) (*RoomEventsAroundResult, error)

GetRoomEventsAround returns a window of events centered on a target event ID. The result includes `limit/2` events before and after the target, with the target at TargetIndex.

Authorization: caller must verify room membership before calling.

func (*ChattoCore) GetRoomGroup

func (c *ChattoCore) GetRoomGroup(ctx context.Context, groupID string) (*readmodel.RoomGroup, error)

GetRoomGroup delegates to the owning RoomLayoutModel.

func (*ChattoCore) GetRoomLastEvent

func (c *ChattoCore) GetRoomLastEvent(ctx context.Context, kind RoomKind, roomID string) (eventID string, ts time.Time, exists bool, err error)

GetRoomLastEvent returns the last root message's event ID and proto-level `created_at` timestamp for a room. Excludes thread replies — only root messages affect room-level unread tracking. exists is false if the room has no ordinary root messages. Historical imports do not advance this marker.

Uses the proto's `created_at` rather than JetStream's stored time so the value stays correct after #354 phase 4d (which re-publishes messages with fresh JetStream timestamps but leaves the proto payloads intact).

func (*ChattoCore) GetRoomMembersList

func (c *ChattoCore) GetRoomMembersList(ctx context.Context, kind RoomKind, room_id string) ([]*readmodel.RoomMembership, error)

GetRoomMembersList delegates to the owning RoomMembershipModel.

func (*ChattoCore) GetRoomRolePermissions

func (c *ChattoCore) GetRoomRolePermissions(ctx context.Context, roomID, roleName string) (grants []Permission, denials []Permission, err error)

GetRoomRolePermissions returns the per-room override grants and denials for a role in a specific room. Reads ADR-031's room_allow / room_deny key families.

func (*ChattoCore) GetServerAssetFromAnyBackend

func (c *ChattoCore) GetServerAssetFromAnyBackend(ctx context.Context, assetID string) (io.Reader, *ServerAssetInfo, error)

GetServerAssetFromAnyBackend retrieves a server asset by probing both NATS and S3 backends. It tries the canonical SERVER_ASSETS NATS object store first, then S3. Returns a reader for the asset content and metadata. The caller is responsible for closing the reader if it implements io.Closer.

func (*ChattoCore) GetServerBanner

func (c *ChattoCore) GetServerBanner(ctx context.Context) (*evtv1.AssetRecord, error)

GetServerBanner returns the asset reference for the server's current banner, or (nil, nil) if no banner is set.

func (*ChattoCore) GetServerBannerURL

func (c *ChattoCore) GetServerBannerURL(ctx context.Context, width, height *int, fit string) (string, error)

GetServerBannerURL returns the server-relative URL for the server's banner, optionally transformed to the given dimensions. Returns empty string when no banner is set.

func (c *ChattoCore) GetServerLogo(ctx context.Context) (*evtv1.AssetRecord, error)

GetServerLogo returns the asset reference for the server's current logo, or (nil, nil) if no logo is set.

func (*ChattoCore) GetServerLogoURL

func (c *ChattoCore) GetServerLogoURL(ctx context.Context, width, height *int, fit string) (string, error)

GetServerLogoURL returns the server-relative URL for the server's logo, optionally transformed to the given dimensions. Returns empty string when no logo is set.

func (*ChattoCore) GetServerMembers

func (c *ChattoCore) GetServerMembers(ctx context.Context, search string, limit, offset int) ([]ServerMemberWithRoles, int, error)

GetServerMembers retrieves server members with optional search and pagination. Search matches against login and displayName (case-insensitive partial match). Returns members, total count (matching search), and error.

Post-#330 every authenticated user is implicitly a server member, so this iterates the full user list rather than space-membership records.

func (*ChattoCore) GetServerRole

func (c *ChattoCore) GetServerRole(ctx context.Context, name string) (*RoleWithPermissions, error)

GetServerRole returns a single role by name. Note: Admin roles are NOT special-cased - permissions are read from the RBAC projection.

func (*ChattoCore) GetServerRoleDetails

func (c *ChattoCore) GetServerRoleDetails(ctx context.Context, actorID, roleName string) (*RoleDetails, error)

func (*ChattoCore) GetServerRolePermissionDenials

func (c *ChattoCore) GetServerRolePermissionDenials(ctx context.Context, roleName string) ([]Permission, error)

GetServerRolePermissionDenials returns all permissions denied by an role. Note: Admin roles are NOT special-cased - they can have denials like any other role.

func (*ChattoCore) GetServerRolePermissions

func (c *ChattoCore) GetServerRolePermissions(ctx context.Context, roleName string) ([]Permission, error)

GetServerRolePermissions returns all permissions granted to an role. Note: Admin roles are NOT special-cased - permissions are materialized in the RBAC projection.

func (*ChattoCore) GetServerSecurityConfig

func (c *ChattoCore) GetServerSecurityConfig(ctx context.Context, actorID string) ([]string, error)

func (*ChattoCore) GetStableAttachmentAssetURL

func (c *ChattoCore) GetStableAttachmentAssetURL(assetID, userID string) StableAssetURL

func (*ChattoCore) GetStableHLSMasterPlaylistAssetURL

func (c *ChattoCore) GetStableHLSMasterPlaylistAssetURL(assetID, userID string) StableAssetURL

func (*ChattoCore) GetStableTransformedAttachmentAssetURL

func (c *ChattoCore) GetStableTransformedAttachmentAssetURL(assetID, userID string, width, height int, fit string) StableAssetURL

func (*ChattoCore) GetStats

func (c *ChattoCore) GetStats(ctx context.Context) (*ServerStats, error)

GetStats returns deployment-level counts: registered users, channel rooms, DM rooms. Per-space breakdowns went away with the Space tier (ADR-030).

func (*ChattoCore) GetThreadEvents

func (c *ChattoCore) GetThreadEvents(ctx context.Context, kind RoomKind, room_id string, threadRootEventId string) ([]*evtv1.Event, error)

GetThreadEvents returns the root message followed by every reply (in stream-arrival order) for the given thread root.

Source: RoomTimelineProjection for the root, ThreadProjection for the replies. The ThreadProjection holds replies plus edit/retract events targeting them — currently we surface only MessagePostedEvent replies here so legacy callers see the same shape as the SERVER_EVENTS-backed implementation. Edits / retracts are folded onto the original through current-body EVT hydration at resolve time.

Authorization: caller must verify room membership before calling.

func (*ChattoCore) GetThreadLastOpened

func (c *ChattoCore) GetThreadLastOpened(ctx context.Context, kind RoomKind, userID, roomID, threadRootEventID string) (time.Time, error)

GetThreadLastOpened retrieves the timestamp of the latest thread message the user has seen. Returns zero time if the thread has never been opened.

New RUNTIME_STATE markers store the seen message event ID. Values migrated from SERVER_RUNTIME may still be the legacy 8-byte UnixNano timestamp; those are decoded here so existing read state survives the rollout.

func (*ChattoCore) GetThreadMetadata

func (c *ChattoCore) GetThreadMetadata(rootEventID string) *ThreadMetadata

GetThreadMetadata returns existence, reply count, last reply timestamp, and participants for a thread root message. Derived from Threads and Room Timeline. Root event IDs are globally unique, so no room scope is needed. The result is never nil; Exists is false for an unknown root.

func (*ChattoCore) GetThreadReplyEvents

func (c *ChattoCore) GetThreadReplyEvents(ctx context.Context, kind RoomKind, roomID, threadRootEventID string, limit int, beforeSeq *uint64, afterSeq *uint64) (*RoomEventsResult, error)

GetThreadReplyEvents returns a paginated page of message-posted replies for a thread root. The root event itself is not included. Results are chronological and use the same stream-sequence cursor convention as room events.

Authorization: caller must verify room membership before calling.

func (*ChattoCore) GetThreadReplyEventsAround

func (c *ChattoCore) GetThreadReplyEventsAround(ctx context.Context, kind RoomKind, roomID, threadRootEventID, anchorEventID string, limit int) (*RoomEventsResult, error)

GetThreadReplyEventsAround returns a chronological page of replies centered on anchorEventID. The root event itself is not included.

Authorization: caller must verify room membership before calling.

func (*ChattoCore) GetTransformedServerAssetURL

func (c *ChattoCore) GetTransformedServerAssetURL(key string, width, height int, fit string) string

func (*ChattoCore) GetUser

func (c *ChattoCore) GetUser(ctx context.Context, userID string) (*readmodel.User, error)

GetUser retrieves a user from the user projection.

func (*ChattoCore) GetUserAvatar

func (c *ChattoCore) GetUserAvatar(ctx context.Context, userID string) (*evtv1.AssetRecord, error)

GetUserAvatar retrieves a user's avatar asset reference from the user projection. Returns nil if the user has no avatar set.

func (*ChattoCore) GetUserAvatarURL

func (c *ChattoCore) GetUserAvatarURL(ctx context.Context, userID string, width, height *int, fit string) (string, error)

GetUserAvatarURL returns the server-relative URL for a user's avatar. If width and height are provided (non-nil), returns a URL to a resized version. Returns empty string if no avatar is set.

func (*ChattoCore) GetUserByExternalIdentity

func (c *ChattoCore) GetUserByExternalIdentity(ctx context.Context, issuer, subject string) (*readmodel.User, error)

GetUserByExternalIdentity looks up a user by provider issuer namespace and subject.

func (*ChattoCore) GetUserByExternalIdentityForAuthentication

func (c *ChattoCore) GetUserByExternalIdentityForAuthentication(ctx context.Context, issuer, subject string) (*readmodel.User, uint64, error)

GetUserByExternalIdentityForAuthentication returns the mapped user and the authentication generation that was current in the same projection snapshot as the identity mapping. Credential issuance must use that generation.

func (*ChattoCore) GetUserByLogin

func (c *ChattoCore) GetUserByLogin(ctx context.Context, login string) (*readmodel.User, error)

GetUserByLogin retrieves a user by their login name using the login index.

func (*ChattoCore) GetUserByVerifiedEmail

func (c *ChattoCore) GetUserByVerifiedEmail(ctx context.Context, email string) (*readmodel.User, error)

GetUserByVerifiedEmail looks up a user by their verified email address. Returns the user if found, or an error if not found.

func (*ChattoCore) GetUserEffectiveSpacePermissions

func (c *ChattoCore) GetUserEffectiveSpacePermissions(ctx context.Context, kind RoomKind, userID string) ([]Permission, error)

GetUserEffectiveSpacePermissions returns all permissions the user effectively has for a room kind. Delegates to PermissionResolver.HasSpacePermission for each space-scoped permission, ensuring consistent resolution logic (DM rooms additionally have their boundary deny-list applied).

func (*ChattoCore) GetUserExplicitDMOverride

func (c *ChattoCore) GetUserExplicitDMOverride(ctx context.Context, userID string, perm Permission) (DecisionKind, error)

GetUserExplicitDMOverride returns the user's explicit direct-message-scope allow or deny, or DecisionNone when no override exists.

func (*ChattoCore) GetUserExplicitGroupOverride

func (c *ChattoCore) GetUserExplicitGroupOverride(ctx context.Context, groupID, userID string, perm Permission) (DecisionKind, error)

GetUserExplicitGroupOverride returns the user's explicit user-level allow/deny at the given room group's scope, or DecisionNone.

func (*ChattoCore) GetUserExplicitRoomOverride

func (c *ChattoCore) GetUserExplicitRoomOverride(ctx context.Context, roomID, userID string, perm Permission) (DecisionKind, error)

GetUserExplicitRoomOverride returns the user's explicit user-level allow/deny at the given room's scope, or DecisionNone.

func (*ChattoCore) GetUserExplicitServerOverride

func (c *ChattoCore) GetUserExplicitServerOverride(ctx context.Context, userID string, perm Permission) (DecisionKind, error)

GetUserExplicitServerOverride returns the user's explicit user-level allow/deny at server scope for the given permission, or DecisionNone when there's no user-level override.

func (*ChattoCore) GetUserPermissionMatrix

func (c *ChattoCore) GetUserPermissionMatrix(ctx context.Context, actorID, userID string) (*UserPermissionMatrix, error)

func (*ChattoCore) GetUserPermissionMatrixIncludingDM

func (c *ChattoCore) GetUserPermissionMatrixIncludingDM(ctx context.Context, actorID, userID string, includeDM bool) (*UserPermissionMatrix, error)

GetUserPermissionMatrixIncludingDM returns the complete matrix, optionally including DMs.

func (*ChattoCore) GetUserPermissionMatrixPage

func (c *ChattoCore) GetUserPermissionMatrixPage(ctx context.Context, actorID, userID string, includeDM bool, query PermissionScopeQuery) (*UserPermissionMatrix, error)

GetUserPermissionMatrixPage authorizes and evaluates the selected scopes.

func (*ChattoCore) GetUserPresence

func (c *ChattoCore) GetUserPresence(ctx context.Context, userID string) (string, error)

GetUserPresence retrieves a user's current presence status. Returns "OFFLINE" if the user has no presence entry (never connected or TTL expired).

func (*ChattoCore) GetUserPresences

func (c *ChattoCore) GetUserPresences(ctx context.Context, userIDs []string) (map[string]string, error)

GetUserPresences returns watcher-backed presence for bulk read hydration. Singular reads use the KV bucket directly; their liveness read can come from any replica.

func (*ChattoCore) GetUserPushSubscriptions

func (c *ChattoCore) GetUserPushSubscriptions(ctx context.Context, userID string) ([]*runtimestatev1.PushSubscription, error)

GetUserPushSubscriptions returns the user's current push subscriptions: records that are not expired and that own their endpoint at their exact revision. It also removes every expired record it finds, so push delivery and registration prune subscriptions of devices that stopped using Chatto. Authorization: Caller must verify userID matches authenticated user.

func (*ChattoCore) GetUserReference

func (c *ChattoCore) GetUserReference(ctx context.Context, userID string) (*readmodel.User, error)

GetUserReference retrieves a public user reference. Deleted or crypto-shredded users are returned as tombstones; unknown users still return ErrNotFound.

func (*ChattoCore) GetUserReferences

func (c *ChattoCore) GetUserReferences(ctx context.Context, userIDs []string) ([]*readmodel.User, error)

GetUserReferences returns public user references in request order. A deleted account has an explicit tombstone; an unknown or not-yet-projected ID is nil.

func (*ChattoCore) GetUserRoleAssignments

func (c *ChattoCore) GetUserRoleAssignments(ctx context.Context, actorID, targetUserID string) (*UserRoleAssignments, error)

GetUserRoleAssignments checks role.assign independently of admin.view-users. Each call reads current state; commands must still recheck their own policy.

func (*ChattoCore) GetUserRoles

func (c *ChattoCore) GetUserRoles(ctx context.Context, userID string) ([]string, error)

GetUserRoles returns the explicit role assignments for a user. The implicit `everyone` role is omitted — callers that need it can prepend it themselves based on the relevant scope (e.g. space membership).

func (*ChattoCore) GetUserServerPermissions

func (c *ChattoCore) GetUserServerPermissions(ctx context.Context, userID string) ([]Permission, error)

GetUserServerPermissions returns all server permissions the user has, using the unified resolver.

func (*ChattoCore) GetUserSettings

func (c *ChattoCore) GetUserSettings(_ context.Context, userID string) (*evtv1.ServerUserPreferences, error)

GetUserSettings retrieves a user's settings from the config projection. Returns nil, nil if no settings have been saved yet (the user hasn't configured any). Authorization: Caller must verify access before calling this helper.

func (*ChattoCore) GetVerifiedEmails

func (c *ChattoCore) GetVerifiedEmails(ctx context.Context, userID string) ([]VerifiedEmail, error)

GetVerifiedEmails returns all verified emails for a user from the user projection.

func (*ChattoCore) GetVoiceCallAccessMaterial

func (c *ChattoCore) GetVoiceCallAccessMaterial(ctx context.Context, roomID string) (CallAccessMaterial, error)

GetVoiceCallAccessMaterial returns generation-consistent access data for issuing a call token. Authorization: Caller must verify room membership before calling.

func (*ChattoCore) GetVoiceCallE2EEKey

func (c *ChattoCore) GetVoiceCallE2EEKey(ctx context.Context, roomID string) (string, error)

func (*ChattoCore) GetVoiceCallPublisherAccessMaterial

func (c *ChattoCore) GetVoiceCallPublisherAccessMaterial(ctx context.Context, roomID, userID string) (CallAccessMaterial, error)

GetVoiceCallPublisherAccessMaterial returns generation-consistent access data only when userID participates in that same active call generation. Authorization: Caller must verify room membership before calling.

func (*ChattoCore) GrantGroupPermission

func (c *ChattoCore) GrantGroupPermission(ctx context.Context, actorID, groupID, roleName string, perm Permission) error

GrantGroupPermission writes a group-scope grant for a role on a specific room group.

func (*ChattoCore) GrantOAuthClientConsent

func (c *ChattoCore) GrantOAuthClientConsent(ctx context.Context, userID, clientID, clientName, clientURI, redirectOrigin string) error

func (*ChattoCore) GrantOAuthClientScopedConsent

func (c *ChattoCore) GrantOAuthClientScopedConsent(ctx context.Context, userID, clientID, clientName, clientURI, redirectOrigin, resource string, scopes []string) error

GrantOAuthClientScopedConsent records the exact resource and normalized scope set approved by the user.

func (*ChattoCore) GrantOAuthConsent

func (c *ChattoCore) GrantOAuthConsent(ctx context.Context, userID, redirectOrigin string) error

func (*ChattoCore) GrantRoomPermission

func (c *ChattoCore) GrantRoomPermission(ctx context.Context, actorID, roomID, roleName string, perm Permission) error

GrantRoomPermission grants a permission to a role for a specific room.

func (*ChattoCore) GrantServerPermission

func (c *ChattoCore) GrantServerPermission(ctx context.Context, actorID, roleName string, perm Permission) error

GrantServerPermission grants a permission to a role's server-level default.

func (*ChattoCore) GrantUserGroupPermission

func (c *ChattoCore) GrantUserGroupPermission(ctx context.Context, actorID, groupID, userID string, perm Permission) error

GrantUserGroupPermission grants a permission directly to a user at a room group's scope.

func (*ChattoCore) GrantUserPermission

func (c *ChattoCore) GrantUserPermission(ctx context.Context, actorID, userID string, perm Permission) error

GrantUserPermission grants a permission directly to a user at server scope.

func (*ChattoCore) GrantUserRoomPermission

func (c *ChattoCore) GrantUserRoomPermission(ctx context.Context, actorID, roomID, userID string, perm Permission) error

GrantUserRoomPermission grants a permission directly to a user for a specific room.

func (*ChattoCore) HandleCallParticipantJoined

func (c *ChattoCore) HandleCallParticipantJoined(ctx context.Context, roomID, userID string, callID ...string) error

HandleCallParticipantJoined appends a durable LiveKit-observed join fact. Called by the webhook handler when LiveKit reports a participant joined.

func (*ChattoCore) HandleCallParticipantLeft

func (c *ChattoCore) HandleCallParticipantLeft(ctx context.Context, roomID, userID string, callID ...string) error

HandleCallParticipantLeft appends a durable LiveKit-observed leave fact. Called by the webhook handler when LiveKit reports a participant left.

func (*ChattoCore) HandleCallRoomFinished

func (c *ChattoCore) HandleCallRoomFinished(ctx context.Context, roomID string, callID ...string) error

HandleCallRoomFinished appends LiveKit-observed leave facts for any remaining projected participants in the room. Called by the webhook handler when LiveKit reports a room has finished (closed).

func (*ChattoCore) HasAnyAdminPermission

func (c *ChattoCore) HasAnyAdminPermission(ctx context.Context, userID string) (bool, error)

HasAnyAdminPermission delegates to shared authorization policy.

func (*ChattoCore) HasOAuthClientConsent

func (c *ChattoCore) HasOAuthClientConsent(ctx context.Context, userID, clientID, redirectOrigin string) (bool, error)

func (*ChattoCore) HasOAuthClientScopedConsent

func (c *ChattoCore) HasOAuthClientScopedConsent(ctx context.Context, userID, clientID, redirectOrigin, resource string, scopes []string) (bool, error)

HasOAuthClientScopedConsent reports whether the user approved the exact resource and normalized scope set for this client.

func (*ChattoCore) HasOAuthConsent

func (c *ChattoCore) HasOAuthConsent(ctx context.Context, userID, redirectOrigin string) (bool, error)

func (*ChattoCore) HasPassword

func (c *ChattoCore) HasPassword(ctx context.Context, userID string) (bool, error)

func (*ChattoCore) HasServerPermission

func (c *ChattoCore) HasServerPermission(ctx context.Context, userID string, perm Permission) (bool, error)

HasServerPermission checks if a user has a specific server permission. This delegates to the unified PermissionResolver which implements hierarchical resolution.

Note: Config-based admin check (owners.emails) should be done separately by the caller before calling this function.

func (*ChattoCore) HasUnread

func (c *ChattoCore) HasUnread(ctx context.Context, kind RoomKind, userID, roomID string) (bool, error)

HasUnread reports whether a room has active Badge attention for a user. Thread Badge attention rolls up into the parent room. The result is independent of the user's last-read cursor and false when the user cannot see the room.

func (*ChattoCore) HasUnreadFollowedThreads

func (c *ChattoCore) HasUnreadFollowedThreads(ctx context.Context, userID string, spaceIDs []string) (bool, error)

HasUnreadFollowedThreads reports whether any followed thread has unread replies without materializing the public result.

func (*ChattoCore) HasUserPermissionDeniedViaRoles

func (c *ChattoCore) HasUserPermissionDeniedViaRoles(ctx context.Context, userID string, perm Permission) (bool, error)

HasUserPermissionDeniedViaRoles is the sibling to HasUserPermissionViaRoles that reports whether the resolver's first decision is an explicit deny. "No decision" returns false here — only an explicit deny does.

func (*ChattoCore) HasUserPermissionViaRoles

func (c *ChattoCore) HasUserPermissionViaRoles(ctx context.Context, userID string, perm Permission) (bool, error)

HasUserPermissionViaRoles is a bool wrapper around ResolveUserPermission for server-scope checks. Kept as a thin convenience for the inspector and tests; new code should call ResolveUserPermission directly when it cares about the deny-vs-none distinction.

func (*ChattoCore) HasVerifiedEmail

func (c *ChattoCore) HasVerifiedEmail(ctx context.Context, userID string) (bool, error)

HasVerifiedEmail checks if a user has at least one verified email.

func (*ChattoCore) HydrateBotCredentialUsage

func (c *ChattoCore) HydrateBotCredentialUsage(ctx context.Context, bot *Bot)

HydrateBotCredentialUsage adds optional last-use telemetry to request-local bot metadata. Callers must defer this read until after filtering and pagination, and credential-issuing paths must not call it.

func (*ChattoCore) HydrateLinkPreviewImageAsset

func (c *ChattoCore) HydrateLinkPreviewImageAsset(ctx context.Context, preview *evtv1.LinkPreview) error

HydrateLinkPreviewImageAsset ensures a posted LinkPreview carries the server-issued AssetRecord for its preview image. Clients only send image_asset_id for compatibility; the backend rehydrates the storage pointer from the server-side preview cache or by probing known backends.

func (*ChattoCore) HydrateMessagePost

func (c *ChattoCore) HydrateMessagePost(ctx context.Context, event *evtv1.Event) (*evtv1.MessagePostedEvent, error)

func (*ChattoCore) HydrateUserContentSnapshot

func (c *ChattoCore) HydrateUserContentSnapshot(ctx context.Context, snapshot *UserContentSnapshot) (*HydratedUserContent, bool, error)

HydrateUserContentSnapshot resolves encrypted PII after the content-view read barrier is released. The returned state still represents the captured content generation.

func (*ChattoCore) IdentityUnlinkDisabled

func (c *ChattoCore) IdentityUnlinkDisabled(identity ExternalIdentity) bool

IdentityUnlinkDisabled reports the configured self-service restriction. It does not check whether another usable sign-in method remains.

func (*ChattoCore) ImportHistoricalMessage

func (c *ChattoCore) ImportHistoricalMessage(ctx context.Context, input HistoricalMessageInput) (result *evtv1.Event, resultErr error)

ImportHistoricalMessage appends a source-time message without user posting policy or live posting effects. EVT records the system actor, while the message fact and encrypted body retain the mapped historical author.

func (*ChattoCore) ImportHistoricalMessageChange

func (c *ChattoCore) ImportHistoricalMessageChange(ctx context.Context, in HistoricalMessageChange) error

ImportHistoricalMessageChange preserves source-time mutations without live effects. Each operation and its permanent retry receipt commit atomically.

func (*ChattoCore) ImportHistoricalMessages

func (c *ChattoCore) ImportHistoricalMessages(ctx context.Context, operations []HistoricalMessageOperation) ([]*evtv1.Event, error)

ImportHistoricalMessages commits new file-free messages and reactions in one room atomically, with individual permanent receipts. Results follow input order. Retrying subsets or using individual RPCs preserves the same identities. All validation precedes encryption. Key provisioning can survive a failed attempt, but message facts, thread declarations, reactions, and receipts commit together. No archive state or source-platform references are stored here.

func (*ChattoCore) ImportHistoricalReaction

func (c *ChattoCore) ImportHistoricalReaction(ctx context.Context, input HistoricalReactionInput) (bool, error)

ImportHistoricalReaction records a mapped reactor as a system operation. It bypasses membership and interactive count limits, but requires an existing user and message (including a tombstone), join, or leave event in an active channel. Room OCC makes concurrent repeats idempotent. Names outside the bundled emoji catalogue are preserved. The event time is the import time, not an invented source time.

func (*ChattoCore) ImportHistoricalReactionChanges

func (c *ChattoCore) ImportHistoricalReactionChanges(ctx context.Context, changes []HistoricalMessageChange) error

ImportHistoricalReactionChanges commits new reaction operations in order in one room, atomically with their individual receipts. Exact retries (including retries through ImportHistoricalMessageChange) do not repeat transitions. Previously committed operations are skipped. No new operation commits if validation fails. An uncertain commit can be resolved with the same keys.

func (*ChattoCore) ImportHistoricalRoomChange

func (c *ChattoCore) ImportHistoricalRoomChange(ctx context.Context, in HistoricalRoomChange) error

ImportHistoricalRoomChange applies a single historical room transition. Room name claims use the complete room boundary; no archive state is kept here.

func (*ChattoCore) ImportHistoricalRoomEvent

func (c *ChattoCore) ImportHistoricalRoomEvent(ctx context.Context, in HistoricalRoomChange) (string, error)

ImportHistoricalRoomEvent returns the committed event ID, including on retries. Receipts written before event IDs were retained return an empty ID; their transitions are never repeated merely to supply a reaction target.

func (*ChattoCore) ImportHistoricalUser

func (c *ChattoCore) ImportHistoricalUser(ctx context.Context, key string, input HistoricalUserInput) (*readmodel.User, error)

ImportHistoricalUser creates an account and its initial status in one batch. It never issues credentials or changes the status of an existing account.

func (*ChattoCore) ImportHistoricalUserAvatar

func (c *ChattoCore) ImportHistoricalUserAvatar(ctx context.Context, key, userID string, image []byte) error

ImportHistoricalUserAvatar fills an absent avatar with permanent retry protection. Existing avatars win, including changes concurrent with import. A skipped assignment also commits a receipt, so a retry after a later clear cannot restore the imported avatar.

func (*ChattoCore) ImportUserAvatarFromURL

func (c *ChattoCore) ImportUserAvatarFromURL(ctx context.Context, userID, avatarURL string) error

ImportUserAvatarFromURL fetches a remote provider avatar and stores it as a Chatto-managed user avatar asset. Errors do not contain the URL, which can identify the account; callers log them.

func (*ChattoCore) InvitationCode

func (c *ChattoCore) InvitationCode(id string) string

InvitationCode reconstructs a single-use registration capability. The raw code is never persisted. Spaces, hyphens, and letter case are presentation.

func (*ChattoCore) InvitationRequired

func (c *ChattoCore) InvitationRequired() bool

InvitationRequired is a UI/early-validation hint. Final admission is checked under account creation's stream-wide OCC. Unknown values fail closed.

func (*ChattoCore) IsEmailClaimed

func (c *ChattoCore) IsEmailClaimed(ctx context.Context, email string) (bool, error)

IsEmailClaimed checks if an email address is already verified by any user. Used to prevent registration with an email that's already in use.

func (*ChattoCore) IsFollowingThread

func (c *ChattoCore) IsFollowingThread(ctx context.Context, kind RoomKind, userID, roomID, threadRootEventID string) (bool, error)

IsFollowingThread checks if a user is following a thread.

func (*ChattoCore) IsHiddenChannelEcho

func (c *ChattoCore) IsHiddenChannelEcho(messageEventID string) bool

IsHiddenChannelEcho reports whether an echo row was directly retracted while its canonical thread reply remains visible. Such rows disappear from the room projection instead of rendering as deleted-message tombstones.

func (*ChattoCore) IsLoginAvailable

func (c *ChattoCore) IsLoginAvailable(login string) bool

IsLoginAvailable reports whether a login currently passes validation and conflicts with neither reserved names nor existing mention handles. The result is advisory; account creation remains the race-safe authority.

func (*ChattoCore) IsPublicServerAsset

func (c *ChattoCore) IsPublicServerAsset(ctx context.Context, key string) bool

IsPublicServerAsset reports whether ResolvePublicServerAsset can bind the request key to an explicitly public object. Prefer the resolver in delivery paths so classification cannot fall through to a different backend object.

func (*ChattoCore) IsServerOwner

func (c *ChattoCore) IsServerOwner(ctx context.Context, userID string) (bool, error)

IsServerOwner checks whether a user has the durable owner role. Configured owners.emails entries are materialized into that role at boot and by the durable notification-effects worker after email verification, so live and event-time authorization cannot diverge.

func (*ChattoCore) JoinRoom

func (c *ChattoCore) JoinRoom(ctx context.Context, actorID string, kind RoomKind, user_id, room_id string) (*readmodel.RoomMembership, error)

JoinRoom delegates to the owning RoomMembershipModel.

func (*ChattoCore) JoinVoiceCall

func (c *ChattoCore) JoinVoiceCall(ctx context.Context, actorID, roomID string) error

JoinVoiceCall records authorized user intent. The authorization callback runs on every OCC attempt, including a retry that changes a join into a start.

func (*ChattoCore) KeyWrapper

func (c *ChattoCore) KeyWrapper() kms.KeyWrapper

KeyWrapper returns the key-only KMS boundary used by encryption operations.

func (*ChattoCore) LeaveRoom

func (c *ChattoCore) LeaveRoom(ctx context.Context, actorID string, kind RoomKind, user_id, room_id string) error

LeaveRoom delegates to the owning RoomMembershipModel.

func (*ChattoCore) LinkExternalIdentity

func (c *ChattoCore) LinkExternalIdentity(ctx context.Context, providerID, providerType, issuer, subject, userID string) error

LinkExternalIdentity links a verified provider subject to a user. The issuer is the durable identity namespace: the verified OIDC issuer URL for OIDC providers and the stable configured provider ID for OAuth-only providers. providerID/providerType are event-time metadata and are not used for lookup, so config changes do not break existing links. Idempotent for the same user.

func (*ChattoCore) LinkExternalIdentityAs

func (c *ChattoCore) LinkExternalIdentityAs(ctx context.Context, actorID, providerID, providerType, issuer, subject, userID string) (ExternalIdentity, error)

LinkExternalIdentityAs links an operator-verified or provider-verified identity with explicit actor attribution. It checks ownership across all users and waits for authentication projection catch-up. Repeating the same link does not append another event. Issuer and subject are exact, opaque identifiers.

func (*ChattoCore) LinkPendingExternalIdentity

func (c *ChattoCore) LinkPendingExternalIdentity(ctx context.Context, userID string, flow *PendingExternalIdentityFlow) (ExternalIdentity, error)

func (*ChattoCore) LinkedChannelEchoEventID

func (c *ChattoCore) LinkedChannelEchoEventID(messageEventID string) (string, bool)

LinkedChannelEchoEventID returns a linked non-hidden echo even after the canonical reply retraction has turned that echo into a tombstone.

func (*ChattoCore) ListAdminMembers

func (c *ChattoCore) ListAdminMembers(ctx context.Context, actorID string, input AdminMemberListInput) (*AdminMemberIDPage, error)

ListAdminMembers returns ordered IDs for an authorized admin directory read. Hydration is owned by BatchGetAdminMembers and checks authorization again.

func (*ChattoCore) ListAdmins

func (c *ChattoCore) ListAdmins(ctx context.Context) ([]string, error)

ListAdmins returns all user IDs with the admin role assigned via RBAC. Does NOT include config-based admins (owners.emails).

func (*ChattoCore) ListBotOutboundWebhooks

func (c *ChattoCore) ListBotOutboundWebhooks(ctx context.Context, actorID, botID string) ([]*BotOutboundWebhook, error)

ListBotOutboundWebhooks returns all endpoints, including paused endpoints, only to a bot manager. The collection is bounded to 20 non-revoked credentials.

func (*ChattoCore) ListBotWebhookFailures

func (c *ChattoCore) ListBotWebhookFailures(ctx context.Context, actorID, botID, webhookID string, pageSize uint32, cursor string) (*BotWebhookFailurePage, error)

ListBotWebhookFailures reads LOG directly, so replicas and expiry share the same source of truth. Pagination fixes a tail and skips records removed by retention. Each page performs at most pageSize+1 subject-filtered reads.

func (*ChattoCore) ListBots

func (c *ChattoCore) ListBots(ctx context.Context, actorID string) ([]*Bot, error)

ListBots returns owned bots, or every bot for callers with bot.manage. It leaves optional credential-use telemetry unhydrated so callers can filter and paginate before they read RUNTIME_STATE.

func (*ChattoCore) ListEffectivePermissions

func (c *ChattoCore) ListEffectivePermissions(ctx context.Context, actorID, userID string) ([]EffectivePermission, error)

ListEffectivePermissions reads one coherent content view. Bot targets are visible to authenticated members; human targets require permission management. It returns no stored overrides or inactive grants and filters room identities only after evaluating child coverage, so hidden restrictions cannot cause a false claim of global authority.

func (*ChattoCore) ListEventLog

func (c *ChattoCore) ListEventLog(ctx context.Context, userID string, query EventLogQuery) (*EventLogConnection, error)

func (*ChattoCore) ListInvitations

func (c *ChattoCore) ListInvitations(ctx context.Context, actorID string) ([]InvitationState, error)

ListInvitations returns all visible codes. Callers must paginate after this ownership filter.

func (*ChattoCore) ListJobs

func (c *ChattoCore) ListJobs(ctx context.Context, actorID string, limit int, token string, status jobqueue.Status) ([]jobqueue.Job, string, error)

ListJobs returns payload-free jobs after the operation's gate. The page token is sealed and bound to the viewer; no broker position is public.

func (*ChattoCore) ListManagedNeighbors

func (c *ChattoCore) ListManagedNeighbors(ctx context.Context, actorID string) ([]Neighbor, error)

ListManagedNeighbors returns the administrative Neighbor collection.

func (*ChattoCore) ListMemberRooms

func (c *ChattoCore) ListMemberRooms(ctx context.Context, kind RoomKind, userID string, opts MemberRoomListOptions) ([]*readmodel.Room, error)

ListMemberRooms delegates to the owning RoomMembershipModel.

func (*ChattoCore) ListOAuthClients

func (c *ChattoCore) ListOAuthClients(ctx context.Context, actorID string) ([]OAuthClientState, error)

func (*ChattoCore) ListRoomAttachments

func (c *ChattoCore) ListRoomAttachments(ctx context.Context, input ListRoomAttachmentsInput) (*RoomAttachmentsResult, error)

ListRoomAttachments returns current message-owned attachments for a room the actor may read.

func (*ChattoCore) ListRoomGroupsOrdered

func (c *ChattoCore) ListRoomGroupsOrdered(ctx context.Context, kind RoomKind) ([]*readmodel.RoomGroup, error)

ListRoomGroupsOrdered delegates to the owning RoomLayoutModel.

func (*ChattoCore) ListRooms

func (c *ChattoCore) ListRooms(ctx context.Context, kind RoomKind) ([]*readmodel.Room, error)

ListRooms retrieves all rooms of the given kind from the RoomModel's room catalog, composed with its group-layout state for the group_id field.

func (*ChattoCore) ListServerRoleMembers

func (c *ChattoCore) ListServerRoleMembers(ctx context.Context, actorID, roleName string, limit, offset int) (*RoleMemberPage, error)

ListServerRoleMembers gates every page with role.assign. The implicit everyone role has no explicit assignments. Limits default to 20 and cap at 100.

func (*ChattoCore) ListServerRoles

func (c *ChattoCore) ListServerRoles(ctx context.Context) ([]RoleWithPermissions, error)

ListServerRoles returns all roles with their permissions. Note: Admin roles are NOT special-cased - permissions are read from the RBAC projection.

func (*ChattoCore) ListServerRolesForUser

func (c *ChattoCore) ListServerRolesForUser(ctx context.Context, actorID string) (*RoleCatalog, error)

func (*ChattoCore) ListUsers

func (c *ChattoCore) ListUsers(ctx context.Context) ([]*readmodel.User, error)

func (*ChattoCore) ListUsersWithVerifiedEmail

func (c *ChattoCore) ListUsersWithVerifiedEmail(ctx context.Context) ([]string, error)

ListUsersWithVerifiedEmail returns all user IDs that have at least one verified email.

func (*ChattoCore) LivePresenceCount

func (c *ChattoCore) LivePresenceCount(ctx context.Context) (int, error)

LivePresenceCount returns how many users currently have live presence, regardless of whether that status is Online, Away, or Do Not Disturb.

func (*ChattoCore) LoadCookieSessionValue

func (c *ChattoCore) LoadCookieSessionValue(ctx context.Context, sessionID string, now time.Time) (CookieSessionStoreEntry, error)

LoadCookieSessionValue returns a well-formed, unexpired cookie-session value together with the exact KV revision observed by the caller. Malformed or expired records fail closed and are removed with a revision fence.

func (*ChattoCore) LoginLengthLimit

func (c *ChattoCore) LoginLengthLimit() int

LoginLengthLimit returns this server's maximum for new and changed usernames.

func (*ChattoCore) MarkBearerTokenFresh

func (c *ChattoCore) MarkBearerTokenFresh(ctx context.Context, token, method, source string) error

MarkBearerTokenFresh records a re-verification on the bearer token's session. It validates the token through the stream leader.

func (*ChattoCore) MarkCookieSessionFresh

func (c *ChattoCore) MarkCookieSessionFresh(ctx context.Context, sessionID, method, source string) error

func (*ChattoCore) MarkRemoteImageFailure

func (c *ChattoCore) MarkRemoteImageFailure(ctx context.Context, rawURL string)

MarkRemoteImageFailure makes every replica skip rawURL for remoteImageFailureTTL. FetchRemoteImage calls it for failed downloads; callers call it when a downloaded source turns out not to be a usable image. Concurrent first requests on several replicas can each fetch before a marker exists, so the marker bounds repeated failures, not the first one.

func (*ChattoCore) MayPublishTyping

func (c *ChattoCore) MayPublishTyping(ctx context.Context, userID string) (bool, error)

MayPublishTyping applies the private visibility choice to automatic activity.

func (*ChattoCore) MessageAttachments

func (c *ChattoCore) MessageAttachments(ctx context.Context, input MessageAttachmentsInput) ([]*evtv1.Attachment, error)

MessageAttachments returns the current attachments for one visible message in a room the actor may read. Retracted, hidden, wrong-room, and non-message event IDs return ErrMessageNotFound so callers do not learn more than the timeline read path would reveal.

func (*ChattoCore) MessageEventSourceMessageID

func (c *ChattoCore) MessageEventSourceMessageID(roomID string, event *evtv1.Event) (string, bool)

MessageEventSourceMessageID returns the message that owns one protected message-derived fact. Asset creation has no message owner until attachment and therefore returns false.

func (*ChattoCore) MessageEventThreadRoot

func (c *ChattoCore) MessageEventThreadRoot(roomID string, event *evtv1.Event) (string, bool)

MessageEventThreadRoot resolves the canonical channel-room thread affected by one message-derived fact. The Threads and Assets projections must be current through the fact before callers use this result for authorization.

func (*ChattoCore) MessageReadProtectedEventRoomID

func (c *ChattoCore) MessageReadProtectedEventRoomID(event *evtv1.Event) (string, bool)

MessageReadProtectedEventRoomID identifies a durable fact whose public delivery can expose message content or message-specific metadata.

func (*ChattoCore) MessageSearchReads

func (c *ChattoCore) MessageSearchReads() *MessageSearchReadModel

MessageSearchReads returns the operation-level model that resolves a viewer's provider query scope and re-authorizes provider hits against current room membership and message state.

func (*ChattoCore) Messages

func (c *ChattoCore) Messages() *MessageModel

Messages returns the operation-level model for message reads/writes that need shared public-API authorization and response semantics.

func (*ChattoCore) MyEventsMetrics

func (c *ChattoCore) MyEventsMetrics() MyEventsMetrics

MyEventsMetrics returns process-local live-event stream counters.

func (*ChattoCore) NATSRecoveryLivenessError

func (c *ChattoCore) NATSRecoveryLivenessError(now time.Time) error

NATSRecoveryLivenessError reports recovery that has exceeded the grace period in which keeping this process alive is more useful than replacing it.

func (*ChattoCore) NeighborhoodDirectory

func (c *ChattoCore) NeighborhoodDirectory(ctx context.Context) (*cachestatev1.NeighborhoodDirectory, error)

NeighborhoodDirectory returns the latest cached Neighborhood. It returns nil before the first completed discovery pass. The call does not contact remote servers.

func (*ChattoCore) NewCookieSessionData

func (c *ChattoCore) NewCookieSessionData(ctx context.Context, userID, source string) (AuthTokenData, error)

NewCookieSessionData validates a browser authentication and returns the typed record that a session-store adapter can commit under its own opaque token.

func (*ChattoCore) NewCookieSessionDataForGeneration

func (c *ChattoCore) NewCookieSessionDataForGeneration(ctx context.Context, userID, source string, authGeneration uint64) (AuthTokenData, error)

NewCookieSessionDataForGeneration returns a typed browser-session record for an authentication that proved credentials against authGeneration.

func (*ChattoCore) NewEmailJobs

func (c *ChattoCore) NewEmailJobs(sender email.Sender) *EmailJobs

NewEmailJobs binds the HTTP runtime's transport to the core-owned queue.

func (*ChattoCore) NotificationAlertEligible

func (c *ChattoCore) NotificationAlertEligible(ctx context.Context, occurrence *notificationv1.NotificationOccurrence) (bool, error)

NotificationAlertEligible fences notification materialization and policy, then checks the exact unread occurrence and current target visibility. Push transports call it again immediately before contacting their provider.

func (*ChattoCore) NotificationOccurrences

func (c *ChattoCore) NotificationOccurrences() *NotificationOccurrenceModel

func (*ChattoCore) NotificationPolicy

func (c *ChattoCore) NotificationPolicy() *NotificationPolicyModel

NotificationPolicy returns the operation-level Notifications 2.0 policy model.

func (*ChattoCore) NotificationSoundEligible

func (c *ChattoCore) NotificationSoundEligible(ctx context.Context, occurrence *notificationv1.NotificationOccurrence) (bool, error)

NotificationSoundEligible fences notification materialization and policy, then checks the exact unread occurrence and current target visibility. Local sound remains a best-effort live effect and is not durable delivery work.

func (*ChattoCore) NotifyNotificationUnreadStateChanged

func (c *ChattoCore) NotifyNotificationUnreadStateChanged(ctx context.Context, userID, actorID, roomID, threadRootEventID string)

NotifyNotificationUnreadStateChanged publishes a content-free, user-scoped invalidation after Badge state may have changed.

func (*ChattoCore) OpenPublicCursor

func (c *ChattoCore) OpenPublicCursor(purpose, scope, token string) ([]byte, error)

OpenPublicCursor authenticates and decrypts a cursor created by SealPublicCursor.

func (*ChattoCore) PermResolver

func (c *ChattoCore) PermResolver() *PermissionResolver

PermResolver returns the hierarchical permission resolver for permission checks. This implements the server < space < room specificity model.

func (*ChattoCore) PlanRealtimeReplay

func (c *ChattoCore) PlanRealtimeReplay(ctx context.Context, userID, resumeCursor string, admitReplay func() error) (RealtimeReplayPlan, error)

PlanRealtimeReplay builds a caller-wide replay of public durable events after resumeCursor. An empty cursor starts at the current EVT boundary and returns no history. Authorization uses the caller's current room visibility; transient live.sync events are intentionally not replayed.

This initial implementation scans a bounded global sequence range directly. It is suitable for reconnect gaps, not bulk event-log export.

admitReplay applies the transport's additional budget to an invalid cursor or a validated gap above 32 EVT sequences. It runs after the exact boundary is captured and before history is scanned or a fallback is returned. Its error aborts the plan. A nil callback applies no additional admission policy.

func (*ChattoCore) PostMessage

func (c *ChattoCore) PostMessage(ctx context.Context, kind RoomKind, room_id, user_id, body string, assetIDs []string, inThread, inReplyTo string, linkPreview *evtv1.LinkPreview, alsoSendToChannel bool, opts ...PostMessageOption) (*evtv1.Event, error)

PostMessage posts a message to a room. Publishes a MessagePostedEvent on evt.room.{R}.message_posted with the encrypted body in a companion MessageBodyEvent.

Threading: inThread is the event ID of the thread root for replies, empty for root posts. If inThread is empty but inReplyTo points at a message that is itself a thread reply, inThread is derived from the target's own inThread so the new message joins that thread. inReplyTo is the event ID of the message being responded to (attribution only). alsoSendToChannel publishes an echo MessagePostedEvent on the same subject with echo_of_event_id set, making the reply visible in the channel timeline. The requested echo commits in the same atomic batch as the reply and its body.

Authorization: Caller must verify room membership and CanPostMessage / CanPostInThread before calling, and CanEchoMessage (if alsoSendToChannel).

func (*ChattoCore) PrimaryVerifiedEmail

func (c *ChattoCore) PrimaryVerifiedEmail(ctx context.Context, userID string) (VerifiedEmail, bool, error)

PrimaryVerifiedEmail returns the address selected for account-directed email.

func (*ChattoCore) ProcessMediaJob

func (c *ChattoCore) ProcessMediaJob(ctx context.Context, assetID, messageID string, process func(context.Context, string, string) error) error

ProcessMediaJob fences processing on current asset state and confirms a terminal outcome. A failed conversion is a terminal asset outcome; job success means the handler completed, not that the media conversion succeeded.

func (*ChattoCore) ProjectionAdminStates

func (c *ChattoCore) ProjectionAdminStates(ctx context.Context) ([]ProjectionAdminState, error)

ProjectionAdminStates returns read-only projection diagnostics for the server-admin UI. It is intentionally on-demand; the byte counts walk in-memory projection state and are meant for operator pages, not hot paths.

func (*ChattoCore) ProjectionHealthError

func (c *ChattoCore) ProjectionHealthError() error

ProjectionHealthError returns the first fatal projection error currently recorded by any registered projector.

func (*ChattoCore) ProjectionSnapshotMetrics

func (c *ChattoCore) ProjectionSnapshotMetrics() prometheus.Collector

ProjectionSnapshotMetrics returns a collector for local snapshot operations. Collection reads memory only and remains independent of readiness and storage. Register once per process registry. No snapshot payload or locator is exposed.

func (*ChattoCore) ProtectedRoles

func (c *ChattoCore) ProtectedRoles(userID string) []string

ProtectedRoles returns the roles the user can select for Shield Mode.

func (*ChattoCore) ProviderUsernameManaged

func (c *ChattoCore) ProviderUsernameManaged(providerID string) bool

ProviderUsernameManaged returns the current creation policy for a provider.

func (*ChattoCore) PublishSessionTerminated

func (c *ChattoCore) PublishSessionTerminated(ctx context.Context, userID, reason string) error

PublishSessionTerminated publishes a SessionTerminatedEvent for the given user. This notifies all of the user's active subscriptions (across tabs/devices) that their session has been terminated. The subscription handler closes the stream after forwarding this event, tearing down the WebSocket connection server-side.

Reasons: "logout", "admin_boot", "account_deleted"

func (*ChattoCore) PublishTypingIndicator

func (c *ChattoCore) PublishTypingIndicator(ctx context.Context, actorID string, kind RoomKind, roomID string, threadRootEventID *string) error

PublishTypingIndicator publishes a typing indicator event to other users in the room. This is a live-only event (bypasses JetStream storage). The threadRootEventID is optional - if set, indicates typing in a thread; if nil, typing in main room.

Authorization: Caller must verify room membership before calling.

func (*ChattoCore) PushSubscriptionCurrentForUser

func (c *ChattoCore) PushSubscriptionCurrentForUser(ctx context.Context, userID string, subscription *runtimestatev1.PushSubscription) (bool, error)

PushSubscriptionCurrentForUser reports whether subscription is still the exact active record for userID. Callers should recheck this immediately before delivery because browsers can transfer or rotate a subscription while a push is being prepared.

func (*ChattoCore) PushSubscriptionOwnedByUser

func (c *ChattoCore) PushSubscriptionOwnedByUser(ctx context.Context, userID, endpoint string) (bool, error)

PushSubscriptionOwnedByUser reports whether the endpoint is currently claimed by userID.

func (*ChattoCore) ReactionModel

func (c *ChattoCore) ReactionModel() *ReactionModel

ReactionModel returns the operation-level model for user-facing reaction mutations. Public transports should authenticate at the edge, pass the actor ID here, and let this model own membership, applicable channel-room message.read, and message.react checks.

func (*ChattoCore) ReadServerContentView

func (c *ChattoCore) ReadServerContentView(
	ctx context.Context,
	read func(context.Context, uint64) error,
) error

ReadServerContentView runs one bounded in-memory operation against an exact ServerContentView generation. Calls to other content-view-backed core reads from the callback reuse the same barrier instead of trying to acquire a nested barrier. The callback must not perform network, storage, or other unbounded work.

func (*ChattoCore) ReadState

func (c *ChattoCore) ReadState() *ReadStateModel

ReadState returns the operation-level model for user-facing read marker updates. Public transports should authenticate at the edge, pass the actor ID here, and let this model own membership checks and anchor validation.

func (*ChattoCore) Ready

func (c *ChattoCore) Ready(ctx context.Context) error

Ready checks if the core is fully initialized and current persistent resources are accessible. Returns nil if ready, or an error describing what's not ready. Used by the /readyz endpoint to verify the server can handle requests.

func (*ChattoCore) RealtimeCursorForSequence

func (c *ChattoCore) RealtimeCursorForSequence(userID string, sequence uint64) (string, error)

RealtimeCursorForSequence returns the opaque public cursor for one durable EVT delivery sequence.

func (*ChattoCore) ReassignBotOwner

func (c *ChattoCore) ReassignBotOwner(ctx context.Context, actorID, botID, ownerUserID string) (*Bot, error)

ReassignBotOwner changes the human account responsible for a bot without changing its configured permission allowlist or active API key. User-family OCC serializes bot changes with deletion of the previous or new owner. Authorization uses a stable request-time read.

func (*ChattoCore) RecordAssetDeleted

func (c *ChattoCore) RecordAssetDeleted(ctx context.Context, actorID, roomID, assetID string) error

func (*ChattoCore) RecordAssetProcessedWithHLS

func (c *ChattoCore) RecordAssetProcessedWithHLS(ctx context.Context, actorID, roomID, messageEventID, attachmentID string, durationMs int64, width, height int32, thumbnail *evtv1.Attachment, variants []*runtimestatev1.VideoVariant, hls *evtv1.AssetProcessedHLS) error

func (*ChattoCore) RecordAssetProcessingFailed

func (c *ChattoCore) RecordAssetProcessingFailed(ctx context.Context, actorID, roomID, messageEventID, attachmentID string, failureCode evtv1.AssetProcessingFailureCode) error

func (*ChattoCore) RecordAssetProcessingStarted

func (c *ChattoCore) RecordAssetProcessingStarted(ctx context.Context, actorID, roomID, messageEventID, assetID string) error

func (*ChattoCore) RecordCallParticipantJoined

func (c *ChattoCore) RecordCallParticipantJoined(ctx context.Context, roomID, userID string, source evtv1.CallParticipantEventSource) error

func (*ChattoCore) RecordCallParticipantLeft

func (c *ChattoCore) RecordCallParticipantLeft(ctx context.Context, roomID, userID string, source evtv1.CallParticipantEventSource) error

func (*ChattoCore) RecordLiveKitWebhook

func (c *ChattoCore) RecordLiveKitWebhook(accepted bool)

RecordLiveKitWebhook records that this process received a LiveKit webhook. accepted is false when the webhook signature was invalid.

func (*ChattoCore) RecordLoginFailed

func (c *ChattoCore) RecordLoginFailed(ctx context.Context, identifier string) error

RecordLoginFailed appends a durable audit fact for an unsuccessful login attempt without recording whether the identifier matched an account.

func (*ChattoCore) RecordLoginSucceeded

func (c *ChattoCore) RecordLoginSucceeded(ctx context.Context, userID, identifier string) error

RecordLoginSucceeded appends a durable audit fact for a completed login.

func (*ChattoCore) RecordLogoutSucceeded

func (c *ChattoCore) RecordLogoutSucceeded(ctx context.Context, userID string) error

RecordLogoutSucceeded appends a durable audit fact for a completed logout.

func (*ChattoCore) RecordOAuthClientAuthorization

func (c *ChattoCore) RecordOAuthClientAuthorization(ctx context.Context, actorID, clientID, clientName, clientOrigin, redirectOrigin string, source evtv1.OAuthClientSource) error

RecordOAuthClientAuthorization records one successful user authorization. Every authorization advances the durable last-authorization timestamp; the projection de-duplicates callback origins and authorizing users.

func (*ChattoCore) RecordOAuthClientConsentDenied

func (c *ChattoCore) RecordOAuthClientConsentDenied(ctx context.Context, userID, clientID, clientName, clientURI, redirectOrigin string) error

func (*ChattoCore) RecordOAuthClientScopedConsentDenied

func (c *ChattoCore) RecordOAuthClientScopedConsentDenied(ctx context.Context, userID, clientID, clientName, clientURI, redirectOrigin, resource string, scopes []string) error

RecordOAuthClientScopedConsentDenied records a denied delegated grant for audit without changing the set of approved grants.

func (*ChattoCore) RecordOAuthConsentDenied

func (c *ChattoCore) RecordOAuthConsentDenied(ctx context.Context, userID, redirectOrigin string) error

func (*ChattoCore) RecordUserAssetDeleted

func (c *ChattoCore) RecordUserAssetDeleted(ctx context.Context, actorID, userID, assetID string) error

func (*ChattoCore) RecoverUnmanifestedVideoAttachments

func (c *ChattoCore) RecoverUnmanifestedVideoAttachments(ctx context.Context)

func (*ChattoCore) RefreshBearerSession

func (c *ChattoCore) RefreshBearerSession(ctx context.Context, refreshToken, requestID, clientID string) (BearerSessionCredentials, error)

RefreshBearerSession rotates a refresh credential using a client-persisted UUID version 4 recovery nonce. The immediately preceding committed rotation can be replayed only with the same nonce and only while its access token remains useful. Runtime state stores only a purpose-separated HMAC verifier.

func (*ChattoCore) RemoteImagePath

func (c *ChattoCore) RemoteImagePath(preset remoteimage.Preset, rawURL string) string

RemoteImagePath returns the signed, server-relative URL through which this server serves rawURL resized to preset. Sign only URLs that the server decided to show.

func (*ChattoCore) RenewCookieSession

func (c *ChattoCore) RenewCookieSession(ctx context.Context, sessionID string, now time.Time) (*runtimestatev1.CookieSession, bool, error)

RenewCookieSession advances one cookie session's expiry in place when its current window is in the final quarter. The expected KV revision serializes renewal with other replicas and makes an unrevisioned logout delete fence a concurrent renewal without changing the browser's opaque handle.

func (*ChattoCore) ReorderServerRoles

func (c *ChattoCore) ReorderServerRoles(ctx context.Context, actorID string, roleNames []string) ([]RoleWithPermissions, error)

ReorderServerRoles reorders custom roles. System roles (owner, admin, moderator, everyone) maintain fixed positions and should not be included. Positions are assigned from PositionCustomFirst upward while skipping system-role positions. Note: everyone=0, moderator=100, admin=900, owner=1000. Returns all roles sorted by position.

func (*ChattoCore) RequireAuthenticationAllowed

func (c *ChattoCore) RequireAuthenticationAllowed(ctx context.Context, userID string, authGeneration uint64) error

RequireAuthenticationAllowed is the single auth-generation policy gate for runtime credentials. It returns ErrAuthenticationRevoked unless authGeneration is the user's current auth generation. Issuance passes the generation that the authentication proved. Validation passes the generation that the stored credential records. Every credential record that validation accepts records the generation it was issued against, so any mismatch means that a later password, account, or identity event revoked the credential.

It always runs the strict check. Only the read-only first pass of request validation can use the fast check; see requireAuthenticationAllowed.

func (*ChattoCore) RequireFreshAuthForBearerToken

func (c *ChattoCore) RequireFreshAuthForBearerToken(ctx context.Context, token string) error

RequireFreshAuthForBearerToken reports ErrFreshAuthRequired unless the bearer token's session re-verified within FreshAuthWindow.

func (*ChattoCore) RequireFreshAuthForCookieSession

func (c *ChattoCore) RequireFreshAuthForCookieSession(ctx context.Context, sessionID string) error

RequireFreshAuthForCookieSession reports ErrFreshAuthRequired unless the cookie session re-verified within FreshAuthWindow.

func (*ChattoCore) RequireOAuthClientAllowed

func (c *ChattoCore) RequireOAuthClientAllowed(ctx context.Context, clientID string) error

func (*ChattoCore) ResetPassword

func (c *ChattoCore) ResetPassword(ctx context.Context, token string, newPasswordHash string) error

ResetPassword validates the token, updates the user's password, and deletes the token. The newPasswordHash should already be bcrypt-hashed by the caller. This is atomic: the token is deleted regardless of password update outcome.

func (*ChattoCore) ResolveDirectRoomMentions

func (c *ChattoCore) ResolveDirectRoomMentions(ctx context.Context, kind RoomKind, roomID string, handles []string) ([]string, error)

ResolveDirectRoomMentions resolves only direct @user handles to room-member user IDs. Role and virtual broadcast handles are intentionally ignored.

func (*ChattoCore) ResolveLinkPreviewToken

func (c *ChattoCore) ResolveLinkPreviewToken(ctx context.Context, token string) (*evtv1.LinkPreview, error)

ResolveLinkPreviewToken resolves a composer token to the canonical cached server-fetched preview. Client-provided metadata is intentionally not trusted.

func (*ChattoCore) ResolveMentions

func (c *ChattoCore) ResolveMentions(ctx context.Context, usernames []string) ([]string, error)

ResolveMentions takes a list of usernames and resolves them to user IDs. Invalid usernames are silently ignored. Returns a slice of valid user IDs.

func (*ChattoCore) ResolveMessageContentID

func (c *ChattoCore) ResolveMessageContentID(roomID, eventID string) (string, error)

ResolveMessageContentID returns the canonical content owner in the given room. It rejects hidden echoes and invalid links. Callers must authorize the requested operation; resolving a link does not grant message access.

func (*ChattoCore) ResolvePublicServerAsset

func (c *ChattoCore) ResolvePublicServerAsset(ctx context.Context, key string) (*PublicServerAssetLocation, bool)

ResolvePublicServerAsset positively classifies an object and binds the decision to one exact backend key before the public route performs cache access, content reads, or transforms. Unknown objects fail closed.

func (*ChattoCore) ResolveRoomMentionKinds

func (c *ChattoCore) ResolveRoomMentionKinds(ctx context.Context, kind RoomKind, roomID string, handles []string) (*RoomMentionResolution, error)

ResolveRoomMentionKinds resolves @handles in a message to concrete room-member user IDs while retaining each typed mention's provenance. Handles share one namespace across users, roles, and virtual room-scoped broadcasts:

  • @all: every current room member
  • @here: current room members whose presence is not OFFLINE
  • @pingable-role: current room members explicitly assigned that role
  • @user: that user, if they are a current room member

Invalid handles are silently ignored, matching existing @user behavior.

func (*ChattoCore) ResolveRoomMentions

func (c *ChattoCore) ResolveRoomMentions(ctx context.Context, kind RoomKind, roomID string, handles []string) ([]string, error)

ResolveRoomMentions is the compatibility view used by message rendering and legacy callers that only need the concrete recipient list.

func (*ChattoCore) ResolveUserPermission

func (c *ChattoCore) ResolveUserPermission(ctx context.Context, userID string, kind RoomKind, roomID string, perm Permission) (DecisionKind, error)

ResolveUserPermission returns the walker's decision (allow / deny / none) for a user-permission pair. Single source of truth for both the bool authorizer and the inspector. Pass roomID="" with KindDM to resolve the singleton direct-message scope before the server scope.

func (*ChattoCore) RetryJob

func (c *ChattoCore) RetryJob(ctx context.Context, actorID, id, expectedVersion string) (jobqueue.Job, error)

RetryJob starts one new attempt budget without changing the deadline or payload of the job. OCC on the facts of the job serializes concurrent operator requests.

func (*ChattoCore) RevokeAdminRole

func (c *ChattoCore) RevokeAdminRole(ctx context.Context, userID string) error

RevokeAdminRole removes the admin role from a user.

func (*ChattoCore) RevokeAllAuthTokensForUserWithReason

func (c *ChattoCore) RevokeAllAuthTokensForUserWithReason(ctx context.Context, userID, reason string) (int, error)

RevokeAllAuthTokensForUserWithReason deletes every renewable bearer session for a user and records one revocation audit fact per session. The scan reads every renewable session on the server, so do not call it on latency-sensitive paths; password changes and resets revoke sessions through the auth generation.

func (*ChattoCore) RevokeAllUserRoles

func (c *ChattoCore) RevokeAllUserRoles(ctx context.Context, actorID, userID string) error

RevokeAllUserRoles removes every role assignment for a user. Post-#330 roles are server-wide, so this clears the user from every role they hold. Used during LeaveSpace cleanup and account deletion. Authorization: Internal use only (no permission check needed).

func (*ChattoCore) RevokeAuthToken

func (c *ChattoCore) RevokeAuthToken(ctx context.Context, token string) error

RevokeAuthToken deletes a bearer token, immediately invalidating it. This is idempotent — revoking a non-existent token is not an error.

func (*ChattoCore) RevokeAuthTokenWithReason

func (c *ChattoCore) RevokeAuthTokenWithReason(ctx context.Context, token, reason string) error

RevokeAuthTokenWithReason deletes a bearer token and records the revocation audit fact when the token existed and could be associated with a user.

func (*ChattoCore) RevokeBotAPIKey

func (c *ChattoCore) RevokeBotAPIKey(ctx context.Context, actorID, botID, keyID string) (*Bot, error)

RevokeBotAPIKey irreversibly invalidates one credential. Repeated calls for the same well-formed ID are idempotent.

func (*ChattoCore) RevokeBotIncomingWebhook

func (c *ChattoCore) RevokeBotIncomingWebhook(ctx context.Context, actorID, botID, webhookID string) (*Bot, error)

RevokeBotIncomingWebhook irreversibly invalidates one credential. Repeated calls for the same well-formed ID are idempotent.

func (*ChattoCore) RevokeBotOutboundWebhook

func (c *ChattoCore) RevokeBotOutboundWebhook(ctx context.Context, actorID, botID, webhookID string) error

RevokeBotOutboundWebhook permanently removes one credential. Already absent endpoints are successful no-ops; an in-flight HTTP request may still finish.

func (*ChattoCore) RevokeCookieSession

func (c *ChattoCore) RevokeCookieSession(ctx context.Context, sessionID string) error

RevokeCookieSession deletes one typed cookie session. It is idempotent.

func (*ChattoCore) RevokeCookieSessionsForUser

func (c *ChattoCore) RevokeCookieSessionsForUser(ctx context.Context, userID string) (int, error)

RevokeCookieSessionsForUser deletes all cookie sessions for a user. The scan reads every `session.*` record on the server, including bearer access records, so do not call it on latency-sensitive paths. Password changes and resets revoke sessions through the auth generation.

func (*ChattoCore) RevokeInvitation

func (c *ChattoCore) RevokeInvitation(ctx context.Context, actorID, id string) (InvitationState, error)

RevokeInvitation invalidates a visible code and preserves its history. Repeated revocation is safe.

func (*ChattoCore) RevokeOAuthClientTokens

func (c *ChattoCore) RevokeOAuthClientTokens(ctx context.Context, clientID string) (int, error)

RevokeOAuthClientTokens removes all bearer credentials issued to a public OAuth client. Policy enforcement remains authoritative even if this defense-in-depth cleanup is interrupted.

func (*ChattoCore) RevokePresentedRuntimeCredentialWithReason

func (c *ChattoCore) RevokePresentedRuntimeCredentialWithReason(ctx context.Context, token string, presentation AuthTokenPresentation, reason string) (string, bool, error)

RevokePresentedRuntimeCredentialWithReason deletes one opaque runtime credential for the requested presentation channel. It returns the owning user ID when the credential existed so HTTP-edge logout can apply one audit and live-session termination flow for bearer and cookie presentations. A credential that a newer auth generation already revoked is deleted and reported as not revoked.

func (*ChattoCore) RevokeProviderGroupRoles

func (c *ChattoCore) RevokeProviderGroupRoles(ctx context.Context, userID string, source ProviderRoleSource) error

RevokeProviderGroupRoles revokes every assignment of the user that the provider with source.Issuer owns, whatever its current mapping. Chatto calls it when the user may no longer sign in through the provider, or no longer has an identity of it, so the user keeps no authority from the provider (FDR-050). Admin and configuration assignments stay.

func (*ChattoCore) RevokeRefreshTokenWithReason

func (c *ChattoCore) RevokeRefreshTokenWithReason(ctx context.Context, refreshToken, reason string) error

RevokeRefreshTokenWithReason revokes the whole renewable session identified by an authentic refresh token, regardless of whether that token is current.

func (*ChattoCore) RevokeRefreshTokenWithReasonResult

func (c *ChattoCore) RevokeRefreshTokenWithReasonResult(ctx context.Context, refreshToken, reason string) (string, bool, error)

RevokeRefreshTokenWithReasonResult revokes a renewable session and returns the owning user when the presented refresh credential was authentic and the session still existed. A session that a newer auth generation already revoked is deleted and reported as not revoked, so logout does not terminate the user's current sessions.

func (*ChattoCore) RevokeServerPermission

func (c *ChattoCore) RevokeServerPermission(ctx context.Context, actorID, roleName string, perm Permission) error

RevokeServerPermission removes a permission grant from a role. This only removes grants, not denials. Use ClearServerPermissionState to remove both. Idempotent — revoking a non-granted permission is a no-op.

(GrantServerPermission, DenyServerPermission, and ClearServerPermissionState live in permission_ops.go, alongside the space-tier and room-tier counterparts.)

func (*ChattoCore) RevokeServerRole

func (c *ChattoCore) RevokeServerRole(ctx context.Context, actorID, userID, roleName string) error

RevokeServerRole removes an role from a user. The role must exist (system or custom). The everyone role cannot be revoked (it's implicit). The model enforces assignment-authority bounds and self-owner lockout; API boundaries additionally require role.assign.

func (*ChattoCore) RevokeServerRoleFromExistingUser

func (c *ChattoCore) RevokeServerRoleFromExistingUser(ctx context.Context, actorID, userID, roleName string) error

RevokeServerRoleFromExistingUser revokes a role from an existing user. Unlike RevokeServerRole, it validates target-user existence inside the append OCC loop so operator APIs cannot report NotFound after persisting a role fact for a user that was already deleted.

func (*ChattoCore) RoomCommands

func (c *ChattoCore) RoomCommands() *RoomCommandModel

RoomCommands returns the operation-level model for public room lifecycle, membership, and moderation writes.

func (*ChattoCore) RoomDirectoryReads

func (c *ChattoCore) RoomDirectoryReads() *RoomDirectoryReadModel

RoomDirectoryReads returns the operation-level model for public room directory and sidebar reads.

func (*ChattoCore) RoomInvitations

func (c *ChattoCore) RoomInvitations() *RoomInvitationModel

RoomInvitations returns the room invitation command and query model.

func (*ChattoCore) RoomLayout

func (c *ChattoCore) RoomLayout() *RoomLayoutModel

RoomLayout returns the owner of group and sidebar layout operations. Transports use its Admin methods for request-time authorization.

func (*ChattoCore) RoomMembershipExists

func (c *ChattoCore) RoomMembershipExists(ctx context.Context, kind RoomKind, user_id, room_id string) (bool, error)

RoomMembershipExists delegates to AuthorizationModel, which owns the effective-membership check.

func (*ChattoCore) RoomMemberships

func (c *ChattoCore) RoomMemberships() *RoomMembershipModel

RoomMemberships returns the owner of membership reads and trusted mutations. Public room mutations use RoomCommands to enforce operation authorization.

func (*ChattoCore) RoomNameExists

func (c *ChattoCore) RoomNameExists(_ context.Context, _ RoomKind, name string) (bool, error)

RoomNameExists reports whether a channel room with the given name exists after trimming, Unicode compatibility normalization, and full case folding. ADR-035 phase 6: served from RoomCatalog.FindByName.

func (*ChattoCore) RoomNameExistsExcluding

func (c *ChattoCore) RoomNameExistsExcluding(_ context.Context, _ RoomKind, name, excludeRoomID string) (bool, error)

RoomNameExistsExcluding is like RoomNameExists but treats excludeRoomID as "free." Used by callers checking whether a rename would collide.

func (*ChattoCore) RoomTimelineReads

func (c *ChattoCore) RoomTimelineReads() *RoomTimelineReadModel

RoomTimelineReads returns the operation-level model for user-facing room and thread timeline reads.

func (*ChattoCore) Run

func (c *ChattoCore) Run(ctx context.Context) error

Run starts every background component owned by the core, including process-wide KV indexes, live models, and every registered projector. It blocks until ctx is cancelled or any component returns an error and returns the first error observed (or ctx.Err on shutdown).

Call this once per process from an errgroup goroutine; tests typically launch it in a bare goroutine with a per-test context that cleanup cancels. Background services are not designed to be restarted.

New projectors should be registered during NewChattoCore; they are then started automatically here without any additional wiring.

func (*ChattoCore) S3Client

func (c *ChattoCore) S3Client() *S3Client

S3Client returns the S3 client, or nil if S3 is not configured.

func (*ChattoCore) SavePushSubscription

func (c *ChattoCore) SavePushSubscription(
	ctx context.Context,
	userID string,
	endpoint, p256dh, auth, userAgent string,
) (*runtimestatev1.PushSubscription, error)

SavePushSubscription stores or updates a push subscription for a user. Authorization: Caller must verify userID matches authenticated user.

func (*ChattoCore) SavePushSubscriptionForClient

func (c *ChattoCore) SavePushSubscriptionForClient(
	ctx context.Context,
	userID string,
	endpoint, p256dh, auth, userAgent, clientHost string,
) (*runtimestatev1.PushSubscription, error)

SavePushSubscriptionForClient stores or updates a browser subscription with the URL host of its serving Chatto client.

func (*ChattoCore) SavePushSubscriptionForClientWithCleanupToken

func (c *ChattoCore) SavePushSubscriptionForClientWithCleanupToken(
	ctx context.Context,
	userID string,
	endpoint, p256dh, auth, userAgent, clientHost, cleanupToken string,
) (*runtimestatev1.PushSubscription, error)

SavePushSubscriptionForClientWithCleanupToken stores a host-aware subscription with a capability that identifies only this save generation.

func (*ChattoCore) SavePushSubscriptionWithCleanupToken

func (c *ChattoCore) SavePushSubscriptionWithCleanupToken(
	ctx context.Context,
	userID string,
	endpoint, p256dh, auth, userAgent, cleanupToken string,
) (*runtimestatev1.PushSubscription, error)

SavePushSubscriptionWithCleanupToken stores a subscription with a capability that identifies only this save generation.

func (*ChattoCore) SealPublicCursor

func (c *ChattoCore) SealPublicCursor(purpose, scope string, payload []byte) (string, error)

SealPublicCursor protects an internal API coordinate with the server-wide secret. Purpose and scope must be stable, domain-specific values.

func (*ChattoCore) SeedDefaultRooms

func (c *ChattoCore) SeedDefaultRooms(ctx context.Context) error

SeedDefaultRooms creates the default channel rooms (`announcements`, `general`) on a fresh server. Idempotent — returns nil without creating anything once any channel room exists, so an operator can delete the defaults without seeing them reappear on the next boot (as long as at least one channel room remains).

Relies on `ensureChannelRoomsAreInAGroup` having run first so the seed "Lobby" group is already in the layout; `CreateRoom` with an empty groupID then auto-routes each new room into it.

func (*ChattoCore) ServerAssetRecordFromAnyBackend

func (c *ChattoCore) ServerAssetRecordFromAnyBackend(ctx context.Context, assetID, filename string) (*evtv1.AssetRecord, error)

ServerAssetRecordFromAnyBackend builds an AssetRecord by probing the server-asset backends. It is primarily for legacy ID-only server-scoped assets that need to be rehydrated into richer metadata.

func (*ChattoCore) ServerStore

func (c *ChattoCore) ServerStore() jetstream.ObjectStore

func (*ChattoCore) SetAttachmentDescription

func (c *ChattoCore) SetAttachmentDescription(ctx context.Context, actorID string, kind RoomKind, roomID, eventID, attachmentID, description string, opts ...EditMessageOption) error

SetAttachmentDescription replaces one attachment description with the same authorization, edit window, OCC, linked-echo, and secure-deletion behavior as a message-body edit. An empty description clears the value.

func (*ChattoCore) SetBearerPrivilegedMode

func (c *ChattoCore) SetBearerPrivilegedMode(ctx context.Context, token string, action PrivilegedModeAction, roles ...string) (PrivilegedModeActivation, error)

SetBearerPrivilegedMode activates or deactivates privileged mode on the renewable session behind one current public bearer token. Activation is idempotent and does not extend an activation that is already current.

func (*ChattoCore) SetCookiePrivilegedMode

func (c *ChattoCore) SetCookiePrivilegedMode(ctx context.Context, sessionID string, action PrivilegedModeAction, roles ...string) (PrivilegedModeActivation, error)

SetCookiePrivilegedMode activates or deactivates privileged mode on one same-origin browser session. Activation is idempotent and does not slide.

func (*ChattoCore) SetInitialPasswordHash

func (c *ChattoCore) SetInitialPasswordHash(ctx context.Context, userID string, password string) error

SetInitialPasswordHash adds the first password credential for a passwordless account. It refuses to overwrite an existing password.

func (*ChattoCore) SetMediaJobHandler

func (c *ChattoCore) SetMediaJobHandler(handler func(context.Context, string, string) error, concurrency int)

SetMediaJobHandler registers media processing before Run starts. The handler owns asset projection barriers and terminal outcomes. concurrency is the size of the media worker pool of this process.

func (*ChattoCore) SetNotificationAlertHandler

func (c *ChattoCore) SetNotificationAlertHandler(handler func(context.Context, *notificationv1.NotificationOccurrence) error)

SetNotificationAlertHandler enables alert work and configures its provider transport. It must be called during process setup, before ChattoCore.Run.

func (*ChattoCore) SetOwnPassword

func (c *ChattoCore) SetOwnPassword(ctx context.Context, userID, currentPassword, newPassword string) error

SetOwnPassword sets or changes a user's own password. Existing password credentials require current password proof; adding the first password keeps existing runtime credentials valid so SSO-only users are not logged out.

func (*ChattoCore) SetPasswordHash

func (c *ChattoCore) SetPasswordHash(ctx context.Context, userID string, password string) error

SetPasswordHash hashes and stores a password for a user. Password hashes are stored separately from user profile data in the user event stream.

func (*ChattoCore) SetPasswordHashAs

func (c *ChattoCore) SetPasswordHashAs(ctx context.Context, actorID, userID string, password string) error

SetPasswordHashAs hashes and stores a password for a user with explicit actor attribution. Operator/admin flows should pass SystemActorID.

func (*ChattoCore) SetPresence

func (c *ChattoCore) SetPresence(ctx context.Context, userID string, status string) error

SetPresence writes/refreshes a user's live presence in MEMORY_CACHE. Authorization: Caller must verify the user is authenticated before calling.

func (*ChattoCore) SetPresencePreference

func (c *ChattoCore) SetPresencePreference(ctx context.Context, userID string, status apiv1.PresenceStatus, revision string) (*apiv1.PresencePreference, error)

SetPresencePreference commits an explicit, revision-checked selection. It does not retry stale user intent. Heartbeats never call this operation.

func (*ChattoCore) SetPresenceWithOptions

func (c *ChattoCore) SetPresenceWithOptions(ctx context.Context, userID string, status string, manuallySet bool) error

func (*ChattoCore) SetPrimaryVerifiedEmail

func (c *ChattoCore) SetPrimaryVerifiedEmail(ctx context.Context, userID, email string) error

SetPrimaryVerifiedEmail selects one verified address for account-directed email. The command is idempotent when the address is already primary.

func (*ChattoCore) SetRolePermissionState

func (c *ChattoCore) SetRolePermissionState(ctx context.Context, actorID, roleName string, scope PermissionTargetScope, perm Permission, state PermissionState) error

func (*ChattoCore) SetServerBanner

func (c *ChattoCore) SetServerBanner(ctx context.Context, actorID string, asset *evtv1.AssetRecord) error

SetServerBanner atomically points the instance at a new banner asset using optimistic locking. The same transaction requests cleanup of the prior asset.

func (c *ChattoCore) SetServerLogo(ctx context.Context, actorID string, asset *evtv1.AssetRecord) error

SetServerLogo atomically points the instance at a new logo asset using optimistic locking. The same transaction requests cleanup of the prior asset.

func (*ChattoCore) SetUserAvatar

func (c *ChattoCore) SetUserAvatar(ctx context.Context, userID string, asset *evtv1.AssetRecord) error

SetUserAvatar stores the user's avatar asset reference through the user aggregate.

func (*ChattoCore) SetUserCustomStatus

func (c *ChattoCore) SetUserCustomStatus(ctx context.Context, userID, emoji, text string, expiresAt *time.Time) (*readmodel.User, error)

SetUserCustomStatus stores or replaces a user's durable custom status. Expiry is modeled on the event itself; readers hide expired statuses without writing auxiliary runtime state.

func (*ChattoCore) SetUserDeactivated

func (c *ChattoCore) SetUserDeactivated(ctx context.Context, actorID, userID string, deactivated bool) error

SetUserDeactivated changes access without erasing account data. The durable auth projection rejects credentials on every replica, including credentials written by a login concurrent with this command. Reactivation never restores an old session. Repeated commands do not append another fact.

func (*ChattoCore) SetUserPermissionState

func (c *ChattoCore) SetUserPermissionState(ctx context.Context, actorID, userID string, scope PermissionTargetScope, perm Permission, state PermissionState) error

func (*ChattoCore) SetupRequired

func (c *ChattoCore) SetupRequired(ctx context.Context) (bool, error)

SetupRequired reads authoritative durable state, independent of snapshots or projection lag. Config only suppresses setup; it never changes durable state. Any user history also closes eligibility for operator/bootstrap-created users, even if all those users were later deleted.

func (*ChattoCore) ShouldUseS3

func (c *ChattoCore) ShouldUseS3() bool

ShouldUseS3 returns true if new uploads should be stored in S3.

func (*ChattoCore) StoreCachedResize

func (c *ChattoCore) StoreCachedResize(ctx context.Context, key string, data []byte) error

func (*ChattoCore) StoreCachedResizeIfAbsent

func (c *ChattoCore) StoreCachedResizeIfAbsent(ctx context.Context, key string, data []byte) error

func (*ChattoCore) StoreCallRoleSelection

func (c *ChattoCore) StoreCallRoleSelection(ctx context.Context, roomName, identity, userID string, now time.Time) (string, error)

StoreCallRoleSelection saves the issuing credential's selection until its deadline. The reference is bound to one LiveKit room, participant and user.

func (*ChattoCore) StreamMyEvents

func (c *ChattoCore) StreamMyEvents(ctx context.Context, userID string) (<-chan EventEnvelope, error)

StreamMyEvents creates a unified stream of every event on this deployment that is relevant to a specific user.

The process-wide MyEventsHub receives two internal NATS Core subject roots: live.sync.> carries PubSubEvent messages and live.evt.> is the raw singleton republish of committed EVT facts. EVT delivery is not UI-safe by itself: the hub waits for the relevant local projection(s) to reach the republished stream sequence, then applies each user's authorization before forwarding the event through the realtime API.

Authorization:

  • Room events (live.sync.room.> and deliverable live.evt.room.>) are delivered only for rooms where the user is a member. Message-bearing durable facts and typing indicators also require applicable message-read authority. The membership set is pre-loaded across both kinds (channel + dm) and updated as join/leave/room-deleted events arrive.
  • User-scoped PubSub subjects are delivered only to their target user. Room-scoped PubSub subjects must match their typing payload and room.
  • Presence updates from the per-process PresenceHub are deployment-wide; the hub dedups status flapping.

The subscription also tracks presence liveness: subscribing implies the user is online, and a ticker refreshes the KV TTL while the connection lives. A synthetic Heartbeat is emitted every 15s so clients can detect a dead subscription on an otherwise-healthy WebSocket.

The returned channel closes when the context is cancelled or when a SessionTerminatedEvent is delivered to the user.

func (*ChattoCore) StreamMyEventsWithOptions

func (c *ChattoCore) StreamMyEventsWithOptions(ctx context.Context, userID string, options StreamMyEventsOptions) (<-chan EventEnvelope, error)

StreamMyEventsWithOptions creates a myEvents stream with explicit compatibility options.

func (*ChattoCore) StreamRoomEventsLive

func (c *ChattoCore) StreamRoomEventsLive(ctx context.Context, kind RoomKind, room_id string) (<-chan *evtv1.Event, error)

StreamRoomEventsLive creates a continuous stream of live events for a specific room. Only delivers new events that occur after subscription starts (no historical fetch). For historical events, use GetRoomEvents query instead. The returned channel will be closed when the context is cancelled or after unrecoverable errors.

Reliability: Transient JetStream errors (heartbeat missed, leadership change) trigger automatic retry with backoff. Terminal errors (connection closed, consumer deleted) close the channel. Clients should handle channel closure by resubscribing if they want to continue receiving events.

func (*ChattoCore) Subscribe

func (c *ChattoCore) Subscribe(ctx context.Context, subject string, handler nats.MsgHandler) (*nats.Subscription, error)

func (*ChattoCore) SuggestProviderUsername

func (c *ChattoCore) SuggestProviderUsername(base string) (string, error)

SuggestProviderUsername is a preview, not a reservation. Creation rechecks uniqueness atomically and can select the next suffix if the preview was taken.

func (*ChattoCore) SyncProviderGroupRoles

func (c *ChattoCore) SyncProviderGroupRoles(ctx context.Context, userID string, source ProviderRoleSource, mappings []config.GroupRole, groups ProviderGroups) error

SyncProviderGroupRoles applies mappings, the group_roles mapping of the provider source, to a user after a verified sign-in, identity link, or account creation through that provider (FDR-050). It assigns each mapped role that the user's groups give and that the user does not have. It revokes a mapped role only when the user is in no matching group and the provider owns the assignment. Admin and configuration assignments are never changed.

The configuration authorizes these changes, so they use the system actor and skip the delegated role-assignment limits. All changes commit in one RBAC batch with OCC. A conflict recomputes the changes from the current RBAC state, so concurrent syncs and admin changes do not lose updates.

Provider assignments must exist only while the user has an identity of the provider. A concurrent unlink can commit before this sync, so the sync checks the links again after a grant and revokes when none remains.

func (*ChattoCore) SyncProviderUsername

func (c *ChattoCore) SyncProviderUsername(ctx context.Context, userID, providerID, base string) error

SyncProviderUsername applies a verified provider username at sign-in when enabled by configuration. Existing collision suffixes stay stable. Callers must authenticate the provider subject before calling this method.

func (*ChattoCore) ThreadFollows

func (c *ChattoCore) ThreadFollows() *ThreadFollowModel

ThreadFollows returns the operation-level model for user-facing thread follow state changes.

func (*ChattoCore) TryPresignedAttachmentURL

func (c *ChattoCore) TryPresignedAttachmentURL(ctx context.Context, attachment *evtv1.Attachment, ttl time.Duration) (string, error)

func (*ChattoCore) UnarchiveRoom

func (c *ChattoCore) UnarchiveRoom(ctx context.Context, actorID string, kind RoomKind, roomID string) (*readmodel.Room, error)

UnarchiveRoom clears a room's archived flag. The room keeps its set position throughout the archive/unarchive cycle. Authorization: Caller must verify CanManageAnyRoom before calling.

ADR-035 phase 6: event-only.

func (*ChattoCore) UnfollowThread

func (c *ChattoCore) UnfollowThread(ctx context.Context, kind RoomKind, userID, roomID, threadRootEventID string) error

UnfollowThread removes a user's follow on a thread so they stop receiving reply notifications. Idempotent - calling when not following is a no-op. Publishes a ThreadViewerStateChangedEvent for multi-tab sync when state changes.

func (*ChattoCore) UpdateBlockedUsernames

func (c *ChattoCore) UpdateBlockedUsernames(ctx context.Context, actorID string, blockedUsernames []string) ([]string, error)

func (*ChattoCore) UpdateBotOutboundWebhook

func (c *ChattoCore) UpdateBotOutboundWebhook(ctx context.Context, actorID, botID, webhookID string, patch BotOutboundWebhookPatch) (*BotOutboundWebhook, error)

UpdateBotOutboundWebhook changes the supplied settings without rotating the secret. Changes cancel queued work; an HTTP request already in flight can still finish.

func (*ChattoCore) UpdateCookieSessionValue

func (c *ChattoCore) UpdateCookieSessionValue(ctx context.Context, sessionID string, value []byte, revision uint64, now time.Time) error

UpdateCookieSessionValue changes one cookie session only when the caller still owns the revision it loaded. The updated message receives a fresh per-message TTL rounded up to cover the authoritative expiry in the value.

func (*ChattoCore) UpdateManagedUserProfile

func (c *ChattoCore) UpdateManagedUserProfile(ctx context.Context, actorID, targetUserID string, login, displayName, bio *string) (*readmodel.User, error)

UpdateManagedUserProfile applies one identity patch to targetUserID as an atomic batch. Omitted fields remain unchanged.

A self-update delegates to UpdateOwnUserProfile and keeps its login cooldown rules. Updating another account uses the same target-aware policy as avatars: user.manage-accounts for humans; ownership, bot.manage, or user.manage-accounts for bots. Such updates record actorID on the facts. A login change by a bot owner or bot manager checks and starts the target's login cooldown, as a self-service change would. An actor with user.manage-accounts neither checks nor advances it. Conflicts are returned to the caller; replacement values are never replayed after a concurrent profile edit.

func (*ChattoCore) UpdateNeighbor

func (c *ChattoCore) UpdateNeighbor(ctx context.Context, actorID, neighborID, rawOrigin, revision string) (Neighbor, error)

UpdateNeighbor changes one Neighbor origin if its revision is current.

func (*ChattoCore) UpdateOAuthClientPolicy

func (c *ChattoCore) UpdateOAuthClientPolicy(ctx context.Context, actorID, clientID string, policy evtv1.OAuthClientPolicy) (OAuthClientState, error)

func (*ChattoCore) UpdateOwnUserProfile

func (c *ChattoCore) UpdateOwnUserProfile(ctx context.Context, userID string, login, displayName, bio *string) (*readmodel.User, error)

UpdateOwnUserProfile applies one self-service identity patch as an atomic batch. Omitted fields remain unchanged. Login changes retain the existing cooldown and permission-based bypass. Conflicts are returned to the caller; replacement values are never replayed after a concurrent profile edit. Authorization: userID must identify the authenticated caller.

func (*ChattoCore) UpdateServerConfig

func (c *ChattoCore) UpdateServerConfig(ctx context.Context, actorID string, input ServerConfigUpdateInput) (*configv1.ServerConfig, error)

func (*ChattoCore) UpdateServerRole

func (c *ChattoCore) UpdateServerRole(ctx context.Context, actorID, name, displayName, description string, pingableValue ...bool) (*RoleWithPermissions, error)

UpdateServerRole updates an existing role's metadata. The role name cannot be changed.

func (*ChattoCore) UpdateUserAvatar

func (c *ChattoCore) UpdateUserAvatar(ctx context.Context, actorID, targetUserID string, reader io.Reader) (*readmodel.User, error)

UpdateUserAvatar uploads and sets an avatar for targetUserID after applying the target-aware user and bot management authorization policy.

func (*ChattoCore) UpdateUserBio

func (c *ChattoCore) UpdateUserBio(ctx context.Context, userID, bio string) (*readmodel.User, error)

UpdateUserBio updates a user's public bio. An empty value clears it. A no-op write (unchanged bio) appends no EVT event. Authorization: Caller should verify the actor is the user being updated.

func (*ChattoCore) UpdateUserDisplayName

func (c *ChattoCore) UpdateUserDisplayName(ctx context.Context, userID, displayName string) (*readmodel.User, error)

UpdateUserDisplayName updates a user's display name. Authorization: Caller should verify the actor is the user being updated.

func (*ChattoCore) UpdateUserLogin

func (c *ChattoCore) UpdateUserLogin(ctx context.Context, userID, newLogin string) (*readmodel.User, error)

UpdateUserLogin changes a user's login/username. The 30-day cooldown applies unless the user has user.manage-accounts. A bypassed change does not advance the user's cooldown timestamp. Authorization: Caller should verify the actor is the user being updated.

func (*ChattoCore) UpdateUserSettings

func (c *ChattoCore) UpdateUserSettings(ctx context.Context, userID string, input UserSettingsInput) (*evtv1.ServerUserPreferences, error)

UpdateUserSettings merges the provided fields into the user's existing settings. Nil fields in the input are ignored (not cleared). To clear the timezone override, pass a pointer to an empty string. Authorization: Caller must verify access before calling this helper.

func (*ChattoCore) UploadAttachment

func (c *ChattoCore) UploadAttachment(
	ctx context.Context,
	actorID string,
	roomID string,
	filename string,
	contentType string,
	reader io.Reader,
) (*evtv1.Attachment, error)

func (*ChattoCore) UploadDerivativeAttachment

func (c *ChattoCore) UploadDerivativeAttachment(
	ctx context.Context,
	parentAssetID string,
	derivativeRole evtv1.AssetDerivativeRole,
	roomID string,
	filename string,
	contentType string,
	reader io.ReadSeeker,
) (*evtv1.Attachment, error)

func (*ChattoCore) UploadDerivativeAttachmentWithDimensions

func (c *ChattoCore) UploadDerivativeAttachmentWithDimensions(
	ctx context.Context,
	parentAssetID string,
	derivativeRole evtv1.AssetDerivativeRole,
	roomID string,
	filename string,
	contentType string,
	reader io.ReadSeeker,
	width int32,
	height int32,
) (*evtv1.Attachment, error)

func (*ChattoCore) UploadManagedServerBanner

func (c *ChattoCore) UploadManagedServerBanner(ctx context.Context, actorID string, reader io.Reader) (*evtv1.AssetRecord, error)
func (c *ChattoCore) UploadManagedServerLogo(ctx context.Context, actorID string, reader io.Reader) (*evtv1.AssetRecord, error)

func (*ChattoCore) UploadServerBanner

func (c *ChattoCore) UploadServerBanner(ctx context.Context, reader io.Reader) (*evtv1.AssetRecord, error)

UploadServerBanner processes a banner image (resize + WebP) and uploads the bytes to the object store. Returns the asset reference. Use SetServerBanner to atomically swap the server's banner pointer (and clean up the prior asset).

Banners double as the OG link-preview image, so they're processed at the canonical 1200x630 OG aspect rather than the older 4:3 sidebar shape.

func (c *ChattoCore) UploadServerLogo(ctx context.Context, reader io.Reader) (*evtv1.AssetRecord, error)

UploadServerLogo processes a logo image (resize + WebP) and uploads the bytes to the object store. Returns the asset reference. Use SetServerLogo to atomically swap the server's logo pointer (and clean up the prior asset).

func (*ChattoCore) UploadUserAvatar

func (c *ChattoCore) UploadUserAvatar(ctx context.Context, userID string, reader io.Reader) (*evtv1.AssetRecord, error)

UploadUserAvatar processes an image (resizes to 256x256 max, converts to WebP), uploads it to the object store (NATS or S3), and returns the asset reference. If the user already has an avatar, the old one is deleted after successful upload.

func (*ChattoCore) UsernameManaged

func (c *ChattoCore) UsernameManaged(ctx context.Context, userID string) (bool, error)

UsernameManaged returns the effective local-edit restriction after catching up account links. Mutations must recheck it under the user OCC guard.

func (*ChattoCore) ValidateAccountDeletionToken

func (c *ChattoCore) ValidateAccountDeletionToken(ctx context.Context, token, userID string) error

ValidateAccountDeletionToken validates a token and ensures it belongs to the user. If valid, the token is consumed (deleted) to prevent reuse. Returns an error if the token is invalid, expired, or doesn't belong to the user.

func (*ChattoCore) ValidateAuthToken

func (c *ChattoCore) ValidateAuthToken(ctx context.Context, token string) (string, error)

ValidateAuthToken checks if a bearer token is valid and returns the associated user ID. Returns ErrAuthTokenNotFound if the token doesn't exist, has reached its fixed expiry, or its renewable session is no longer valid.

func (*ChattoCore) ValidateBotAPIKey

func (c *ChattoCore) ValidateBotAPIKey(ctx context.Context, token string) (*readmodel.User, error)

ValidateBotAPIKey authenticates a bot's non-expiring API key against the latest verifier replayed from EVT. It returns ErrAuthTokenNotFound for every malformed, stale, deleted, or otherwise unusable key.

func (*ChattoCore) ValidateBotAPIKeyCredential

func (c *ChattoCore) ValidateBotAPIKeyCredential(ctx context.Context, token string) (*readmodel.User, []byte, error)

ValidateBotAPIKeyCredential authenticates a bot API key and returns the non-secret verifier generation needed to revoke long-lived transports when a later durable revocation reaches this replica.

func (*ChattoCore) ValidateBotIncomingWebhookCredential

func (c *ChattoCore) ValidateBotIncomingWebhookCredential(ctx context.Context, token string) (*readmodel.User, error)

ValidateBotIncomingWebhookCredential authenticates an action-limited incoming webhook credential against the latest verifier replayed from EVT.

func (*ChattoCore) ValidateCookieCredential

func (c *ChattoCore) ValidateCookieCredential(ctx context.Context, sessionID string) (*runtimestatev1.CookieSession, error)

ValidateCookieCredential validates a typed cookie-presentation runtime credential. The credential carries its user ID in the runtime-state record, so callers do not need to trust or duplicate a user ID in the signed browser cookie.

func (*ChattoCore) ValidateInvitationAdmission

func (c *ChattoCore) ValidateInvitationAdmission(ctx context.Context, id string) error

ValidateInvitationAdmission rechecks remembered admission, including expiry, revocation, and consumption. It does not consume the code.

func (*ChattoCore) ValidateInvitationCode

func (c *ChattoCore) ValidateInvitationCode(ctx context.Context, code string) (string, error)

ValidateInvitationCode checks a code without reserving or consuming it. Final account creation must validate its durable invitation again under OCC.

func (*ChattoCore) ValidatePasswordResetToken

func (c *ChattoCore) ValidatePasswordResetToken(ctx context.Context, token string) (string, error)

ValidatePasswordResetToken validates a token and returns the associated userID. This is useful for checking if a token is valid before showing the reset form.

func (*ChattoCore) ValidatePresentedRuntimeCredential

func (c *ChattoCore) ValidatePresentedRuntimeCredential(ctx context.Context, handle string, presentation AuthTokenPresentation) (ValidatedRuntimeCredential, error)

ValidatePresentedRuntimeCredential validates an opaque runtime credential handle as presented over a specific transport. General bearer, resource-bound bearer, and same-origin cookie auth use session.{hmac} records. The presentation check prevents a handle minted for one channel or grant class from being replayed through another.

Validation runs on every request, so it first reads from any replica. That read can accept a credential but never rejects one: a lagging replica can miss a just-issued record, show an older session generation, or show an expiry that a renewal already moved. A rejection is decided again through the stream leader, and only that pass removes invalid records.

For the same reason, the first pass can use the fast auth generation check inside the auth generation check window (ADR-127). The second pass, and every caller that reads through the stream leader, uses the strict check.

func (*ChattoCore) ValidatePublicBearerCredential

func (c *ChattoCore) ValidatePublicBearerCredential(ctx context.Context, handle string) (ValidatedRuntimeCredential, error)

ValidatePublicBearerCredential validates a bearer credential for Chatto's general public API and realtime transports. A resource-bound credential is valid only at its resource server and must not become general account authority through these transports.

func (*ChattoCore) VerifyEmailCode

func (c *ChattoCore) VerifyEmailCode(ctx context.Context, userID, email, code string) (string, error)

VerifyEmailCode verifies an email using a submitted code.

func (*ChattoCore) VerifyPassword

func (c *ChattoCore) VerifyPassword(ctx context.Context, identifier string, password string) (*readmodel.User, error)

VerifyPassword verifies a user's password by login name or email and returns the user if valid.

func (*ChattoCore) VerifyPasswordWithAuthGeneration

func (c *ChattoCore) VerifyPasswordWithAuthGeneration(ctx context.Context, identifier string, password string) (*readmodel.User, uint64, error)

VerifyPasswordWithAuthGeneration verifies a password and returns the user auth generation that was current when the password hash was checked.

func (*ChattoCore) VerifyRegistrationCode

func (c *ChattoCore) VerifyRegistrationCode(ctx context.Context, email, code string) (string, error)

VerifyRegistrationCode validates an email registration code and returns a short-lived completion token for the account-creation form.

func (*ChattoCore) VerifyRemoteImageSignature

func (c *ChattoCore) VerifyRemoteImageSignature(preset remoteimage.Preset, rawURL, signature string) bool

VerifyRemoteImageSignature reports whether signature authorizes serving rawURL resized to preset.

func (*ChattoCore) VerifyUserPassword

func (c *ChattoCore) VerifyUserPassword(ctx context.Context, userID, password string) error

func (*ChattoCore) VoiceCallRoomForMember

func (c *ChattoCore) VoiceCallRoomForMember(ctx context.Context, actorID, roomID string) (*readmodel.Room, RoomKind, error)

func (*ChattoCore) WaitForBoot

func (c *ChattoCore) WaitForBoot(ctx context.Context) error

WaitForBoot blocks until Run has finished boot-time setup (projection startup hooks and ensureChannelRoomsAreInAGroup done) or ctx is cancelled. Callers that issue projection-backed mutations during startup — e.g. SeedDefaultRooms in cmd/run.go — must wait here first; mutating before boot completes leaves orphan rooms because CreateRoom's default-group lookup reads the (still-empty) projection.

func (*ChattoCore) WaitForProjectionsCurrent

func (c *ChattoCore) WaitForProjectionsCurrent(ctx context.Context) error

WaitForProjectionsCurrent blocks until every registered projection has applied the latest stream message matching its filters as of this call. Each target lookup is a broker round trip, so projections wait concurrently. Realtime replay planning calls this once for each WebSocket connection.

func (*ChattoCore) WaitForRealtimeCursor

func (c *ChattoCore) WaitForRealtimeCursor(ctx context.Context, userID, cursor string) error

WaitForRealtimeCursor validates one viewer-bound public cursor and waits until this replica's server content view includes at least that EVT boundary.

This is a lower bound, not a historical read. The view consumes all evt.> sequences, including facts that do not change its resources. Other projections and asynchronous effects are not part of this barrier. The server caps the wait even if the caller provides no deadline.

An expired cursor satisfies the barrier at once: its boundary is older than the cursor lifetime or the retained EVT history, so this replica is already past it. Only replay must reject expired cursors.

func (*ChattoCore) WaitForRegistrationPolicy

func (c *ChattoCore) WaitForRegistrationPolicy(ctx context.Context) error

WaitForRegistrationPolicy catches this replica up before an admission read.

func (*ChattoCore) WatchAccountAccessInvalidated

func (c *ChattoCore) WatchAccountAccessInvalidated(userID string) (<-chan struct{}, func())

WatchAccountAccessInvalidated closes when a durable deactivation transition invalidates this credential. Registration checks state under the projection lock, so a transition before registration cannot leave a socket unwatched. The caller must cancel the watch when its connection closes.

func (*ChattoCore) WatchBotAPIKeyInvalidated

func (c *ChattoCore) WatchBotAPIKeyInvalidated(botID string, verifier []byte) (<-chan struct{}, func())

WatchBotAPIKeyInvalidated closes when the durable user-auth projection observes that verifier is no longer current for botID.

func (*ChattoCore) WatchOAuthClientAccessDenied

func (c *ChattoCore) WatchOAuthClientAccessDenied(clientID string) (<-chan struct{}, func())

WatchOAuthClientAccessDenied returns a process-local notification backed by the durable OAuth-client projection. The channel closes when this replica observes a blocked or unsupported policy. Callers must invoke the returned cleanup function when they stop watching.

type ConfigModel

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

ConfigModel owns semantic configuration/preference reads and event writes.

func NewConfigModel

func NewConfigModel(publisher *evtstream.Publisher, config events.ProjectionHandle[*ConfigProjection]) *ConfigModel

func (*ConfigModel) GetBlockedUsernamesList

func (cm *ConfigModel) GetBlockedUsernamesList() []string

GetBlockedUsernamesList returns the blocked usernames as a slice of lowercase strings.

func (*ConfigModel) GetEffectiveBlockedUsernames

func (cm *ConfigModel) GetEffectiveBlockedUsernames() string

GetEffectiveBlockedUsernames returns the blocked usernames string from the projection. Returns DefaultBlockedUsernames if no config has ever been written; returns "" if the operator explicitly cleared it.

func (*ConfigModel) GetEffectiveDescription

func (cm *ConfigModel) GetEffectiveDescription() string

GetEffectiveDescription returns the server description from the projection, falling back to DefaultDescription if unset.

func (*ConfigModel) GetEffectiveMOTD

func (cm *ConfigModel) GetEffectiveMOTD() string

GetEffectiveMOTD returns the Message of the Day from the projection. Empty string if not configured.

func (*ConfigModel) GetEffectiveServerName

func (cm *ConfigModel) GetEffectiveServerName() string

GetEffectiveServerName returns the server name from the projection, falling back to "Chatto" if unset.

func (*ConfigModel) GetEffectiveWelcomeMessage

func (cm *ConfigModel) GetEffectiveWelcomeMessage() string

GetEffectiveWelcomeMessage returns the welcome message from the projection. Empty string if not configured.

func (*ConfigModel) GetNeighbor

func (cm *ConfigModel) GetNeighbor(neighborID string) (Neighbor, bool)

GetNeighbor returns one projected Neighbor.

func (*ConfigModel) GetServerConfig

func (cm *ConfigModel) GetServerConfig() *configv1.ServerConfig

GetServerConfig returns the raw server configuration values currently held by the projection, or nil when no server config fields have been set.

func (*ConfigModel) IsUsernameBlocked

func (cm *ConfigModel) IsUsernameBlocked(login string) bool

IsUsernameBlocked checks if a username is in the blocked list (case-insensitive).

func (*ConfigModel) ListNeighbors

func (cm *ConfigModel) ListNeighbors() []Neighbor

ListNeighbors returns the current Neighbor collection without an ordering contract.

func (*ConfigModel) RegistrationAdmission

func (cm *ConfigModel) RegistrationAdmission() evtv1.RegistrationAdmission

RegistrationAdmission reads the effective self-service account policy. No policy event means open. Unknown persisted values remain intact.

func (*ConfigModel) SetServerConfig

func (cm *ConfigModel) SetServerConfig(ctx context.Context, actorID string, cfg *configv1.ServerConfig) error

SetServerConfig stores the server configuration by publishing semantic config events and waiting for the projection to apply.

Deprecated for runtime callers — they should use UpdateServerConfigFunc to compose against the current state. SetServerConfig is kept for tests and controlled repair paths that bypass the compose step.

func (*ConfigModel) UpdateServerConfigFunc

func (cm *ConfigModel) UpdateServerConfigFunc(
	ctx context.Context,
	actorID string,
	updateFn func(current *configv1.ServerConfig) (*configv1.ServerConfig, error),
) (*configv1.ServerConfig, error)

UpdateServerConfigFunc atomically updates the server config using optimistic concurrency control. The updateFn receives the current projection snapshot (or nil if no config has been written yet) and should return the updated config. On conflict, the whole compose step is retried against the newer projection snapshot, so field-level edits do not publish stale full-config replacements.

type ConfigProjection

type ConfigProjection struct {
	events.MemoryProjection
	// contains filtered or unexported fields
}

ConfigProjection consumes first-party configuration/preference events from EVT and keeps the current server/user settings in memory. It also understands legacy UserServerPreferencesChangedEvent events so older EVT streams keep projecting correctly.

func NewConfigProjection

func NewConfigProjection() *ConfigProjection

func (*ConfigProjection) Apply

func (p *ConfigProjection) Apply(event *evtv1.Event, _ uint64) error

func (*ConfigProjection) Restore

func (p *ConfigProjection) Restore(data []byte) error

func (*ConfigProjection) Snapshot

func (p *ConfigProjection) Snapshot() ([]byte, error)

func (*ConfigProjection) SnapshotContractID

func (*ConfigProjection) SnapshotContractID() string

func (*ConfigProjection) Subjects

func (p *ConfigProjection) Subjects() []string

type ConnectionInfo

type ConnectionInfo struct {
	Connected  bool
	ServerID   string
	ServerName string
	Version    string
	MaxPayload int64
	RTT        string
}

GetConnectionInfo returns information about the NATS connection.

type ConsumerStats

type ConsumerStats struct {
	Stream               string
	Name                 string
	Durable              string
	FilterSubject        string
	FilterSubjects       []string
	AckPolicy            string
	PullBased            bool
	PushBound            bool
	Pending              uint64
	AckPending           int
	Redelivered          int
	Waiting              int
	DeliveredConsumerSeq uint64
	DeliveredStreamSeq   uint64
	AckFloorConsumerSeq  uint64
	AckFloorStreamSeq    uint64
}

ConsumerStats contains basic JetStream consumer state.

type ContentKeyProjection

type ContentKeyProjection struct {
	events.MemoryProjection
	// contains filtered or unexported fields
}

ContentKeyProjection indexes per-user encrypted DEK epochs by purpose.

func NewContentKeyProjection

func NewContentKeyProjection() *ContentKeyProjection

func (*ContentKeyProjection) Active

func (*ContentKeyProjection) Apply

func (p *ContentKeyProjection) Apply(event *evtv1.Event, seq uint64) error

func (*ContentKeyProjection) CompleteStartupReplay

func (p *ContentKeyProjection) CompleteStartupReplay()

func (*ContentKeyProjection) Get

func (*ContentKeyProjection) Restore

func (p *ContentKeyProjection) Restore(data []byte) error

func (*ContentKeyProjection) Snapshot

func (p *ContentKeyProjection) Snapshot() ([]byte, error)

func (*ContentKeyProjection) SnapshotContractID

func (*ContentKeyProjection) SnapshotContractID() string

func (*ContentKeyProjection) Subjects

func (p *ContentKeyProjection) Subjects() []string

func (*ContentKeyProjection) UserShredded

func (p *ContentKeyProjection) UserShredded(userID string) bool

UserShredded reports whether the projection removed the keys of userID for a key-shredding request or a completed shredding.

type CookieSessionStoreEntry

type CookieSessionStoreEntry struct {
	Value    []byte
	Revision uint64
}

CookieSessionStoreEntry is the revisioned value loaded by an HTTP session store adapter. The revision must be supplied when a request changes or conditionally deletes the value so replicas cannot overwrite one another.

type CreateNotificationOccurrenceInput

type CreateNotificationOccurrenceInput struct {
	RecipientID          string
	SourceEventID        string
	SourceCreated        time.Time
	ActorID              string
	Signal               *notificationv1.NotificationSignal
	Mode                 evtv1.NotificationDeliveryMode
	AttentionLevel       notificationv1.NotificationAttentionLevel
	SourceStreamSequence uint64
	InitiallyRead        bool
	SkipReadLookup       bool
}

type CreateRoomOption

type CreateRoomOption func(*createRoomOptions)

CreateRoomOption customizes room creation for trusted/internal callers.

func WithAnnouncementsRoomDefaults

func WithAnnouncementsRoomDefaults() CreateRoomOption

WithAnnouncementsRoomDefaults applies the built-in announcements room's creation-time posting permissions. It is for first-boot seeding only; a user-created room does not gain special permissions from its display name.

func WithRoomThreadingMode

func WithRoomThreadingMode(mode evtv1.RoomThreadingMode) CreateRoomOption

WithRoomThreadingMode sets the initial threading policy for a channel room. Omitting this option preserves the ENABLED default.

func WithUniversalRoom

func WithUniversalRoom(universal bool) CreateRoomOption

WithUniversalRoom sets the initial universal membership flag for a channel room. DM rooms reject universal membership at CreateRoom validation time.

type DecisionKind

type DecisionKind string

DecisionKind is the kind of decision a role contributed.

const (
	DecisionAllow DecisionKind = "allow"
	DecisionDeny  DecisionKind = "deny"
	DecisionNone  DecisionKind = "none"
)

type DecryptedMessageBody

type DecryptedMessageBody struct {
	// MessageEventID is the canonical owner used for encryption and assets.
	MessageEventID         string
	AuthorId               string
	Body                   string
	Attachments            []*evtv1.Attachment
	AttachmentDescriptions map[string]string
	LinkPreview            *evtv1.LinkPreview
	CreatedAt              time.Time
	UpdatedAt              *time.Time
}

DecryptedMessageBody is the public view of a message body with plaintext content. The body's encryption envelope is unwrapped by the resolver layer's decryptMessageBody helper.

type DefaultGlobalRoom

type DefaultGlobalRoom struct {
	Name        string
	Description string
	Universal   bool
}

DefaultGlobalRoom describes a channel that ships with a fresh deployment. Universal rooms are available to every join-eligible server member without writing explicit memberships.

type DeleteMessageOption

type DeleteMessageOption func(*deleteMessageOptions)

DeleteMessageOption customizes the message-retraction command.

type DirectoryRoom

type DirectoryRoom struct {
	Room        *readmodel.Room
	ViewerState DirectoryRoomViewerState
	// DM posting activity in threads that the member can read.
	// Zero means no qualifying message or no access to message-derived state.
	LastMessageAt     time.Time
	LastRootMessageAt time.Time
}

type DirectoryRoomGroup

type DirectoryRoomGroup struct {
	Group       *readmodel.RoomGroup
	ViewerState DirectoryRoomGroupViewerState
	Rooms       []*DirectoryRoom
	Items       []DirectoryRoomGroupItem
}

type DirectoryRoomGroupItem

type DirectoryRoomGroupItem struct {
	Room        *DirectoryRoom
	SidebarLink *readmodel.SidebarLink
}

type DirectoryRoomGroupViewerState

type DirectoryRoomGroupViewerState struct {
	CanCreateRoom      bool
	CanManageRoomGroup bool
}

type DirectoryRoomViewerState

type DirectoryRoomViewerState struct {
	Invitation          *RoomInvitationState
	CanAcceptInvitation bool
	CanInvite           bool
	CallPermissions     CallPermissions // Effective call actions, false for non-members.
	IsMember            bool
	HasUnread           bool
	CanListRoom         bool
	CanJoinRoom         bool
	// CanRejoin retains joining authority even while the viewer is a member.
	CanRejoin              bool
	CanReadMessages        bool
	CanReadInteractions    bool
	CanPostMessage         bool
	CanPostInThread        bool
	CanPostInteractions    bool // RBAC gate only; each reply also needs a thread relationship.
	CanAttach              bool
	CanReact               bool
	CanEchoMessage         bool
	CanPinMessages         bool // Pin mutations in an active channel where the viewer is a member.
	CanManageNotice        bool // Notice mutations by members of an active channel.
	CanManageOthersMessage bool
	CanManageRoom          bool
	CanBanRoomMembers      bool
	SlowModeNextPostAt     time.Time
}

type DurableWorkerAdminStatus

type DurableWorkerAdminStatus struct {
	Key                   string
	Health                DurableWorkerHealth
	PendingCount          uint64
	AckPendingCount       uint64
	WaitingCount          int
	RedeliveredCount      int
	LastDeliveredSequence uint64
	AckFloorSequence      uint64
}

DurableWorkerAdminStatus contains owner-only operational queue metadata.

type DurableWorkerHealth

type DurableWorkerHealth int

DurableWorkerHealth is broker-derived health for a known durable queue.

const (
	DurableWorkerHealthInactive DurableWorkerHealth = iota
	DurableWorkerHealthHealthy
	DurableWorkerHealthWorking
	DurableWorkerHealthUnconfirmed
	DurableWorkerHealthStalled
	DurableWorkerHealthUnavailable
)

type EditMessageOption

type EditMessageOption func(*editMessageOptions)

EditMessageOption customizes side effects owned by the message-edit command.

func WithMessageChannelEcho

func WithMessageChannelEcho(enabled bool) EditMessageOption

WithMessageChannelEcho reconciles whether a thread reply should have a visible echo in the channel timeline after the edit is saved.

type EffectivePermission

type EffectivePermission struct {
	Permission        Permission
	Scope             PermissionMatrixScope
	CoversDescendants bool
}

EffectivePermission is allowed authority at one scope. CoversDescendants is evaluated across all applicable child scopes, including invisible rooms. Membership and operation-specific requirements remain separate.

type EmailJobs

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

EmailJobs stores encrypted, expiring messages and runs the email job worker. SendContext confirms durable queue acceptance, not transport delivery. A crash after transport acceptance can cause duplicate delivery.

func (*EmailJobs) IsEnabled

func (m *EmailJobs) IsEnabled() bool

IsEnabled reports whether the configured transport can accept mail.

func (*EmailJobs) Run

func (m *EmailJobs) Run(ctx context.Context) error

Run owns a bounded worker pool. Shutdown cancels transport calls and leaves unfinished deliveries to the durable consumer for another process.

func (*EmailJobs) Send

func (m *EmailJobs) Send(msg email.Message) error

Send accepts a message without a request cancellation context.

func (*EmailJobs) SendContext

func (m *EmailJobs) SendContext(ctx context.Context, msg email.Message) error

SendContext encrypts content before publishing a job with only an opaque ID. A failed or ambiguous handoff leaves at most an expiring encrypted record.

type EmailVerificationCode

type EmailVerificationCode struct {
	UserID    string    `json:"user_id"`
	Email     string    `json:"email"`
	CreatedAt time.Time `json:"created_at"`
}

EmailVerificationCode represents a pending code used to verify an email address. Stored as JSON (short-lived, auto-expires via KV TTL — not worth proto).

type EventEnvelope

type EventEnvelope interface {
	ID() string
	CreatedAt() *timestamppb.Timestamp
	ActorID() string
	Payload() any
	DeliverySeq() uint64
	EVTEvent() *evtv1.Event
	PubSubEvent() *pubsubv1.PubSubEvent
	Heartbeat() bool
	// SharedRealtimeMapping returns the viewer-independent realtime mapping of
	// the envelope. The first successful compute result is stored on the
	// envelope and returned to all later callers, so concurrent connections
	// that get the same envelope from the hub do the work once. An error is
	// returned only to its caller and is not stored; the next caller computes
	// again. The realtime API owns this slot. The value must be safe to share:
	// it must not hold a value for one viewer, and callers must not change it.
	// The value lives as long as the envelope: until no session queue or
	// connection refers to it. It can contain decrypted message content, which
	// stays only in process memory for that time.
	SharedRealtimeMapping(compute func() (any, error)) (any, error)
}

EventEnvelope is the in-process envelope used by StreamMyEvents and the realtime API. Concrete implementations are intentionally private so an envelope can only wrap one backing source: a durable EVT fact, a pubsub event, or a synthetic heartbeat.

func NewEVTEventEnvelopeWithDeliverySeq

func NewEVTEventEnvelopeWithDeliverySeq(event *evtv1.Event, seq uint64) EventEnvelope

func NewHeartbeatEventEnvelope

func NewHeartbeatEventEnvelope(id string, createdAt *timestamppb.Timestamp) EventEnvelope

func NewPubSubEventEnvelope

func NewPubSubEventEnvelope(event *pubsubv1.PubSubEvent) EventEnvelope

NewPubSubEventEnvelope wraps one NATS Core pubsub event.

type EventLogConnection

type EventLogConnection struct {
	Entries      []*EventLogEntry
	HasOlder     bool
	EndCursor    *string
	TotalCount   int64
	ScannedCount int32
	ScanLimit    int32
	ScanLimited  bool
}

type EventLogEntry

type EventLogEntry struct {
	Sequence      string
	Subject       string
	AggregateType string
	AggregateID   string
	EventType     string
	EventID       string
	ActorID       string
	CreatedAt     *timestamppb.Timestamp
	PayloadJSON   string
}

type EventLogFilter

type EventLogFilter struct {
	EventType     string
	ActorID       string
	CreatedAtFrom *time.Time
	CreatedAtTo   *time.Time
}

type EventLogQuery

type EventLogQuery struct {
	Limit  int
	Before string
	Filter EventLogFilter
}

type ExternalIdentity

type ExternalIdentity struct {
	ProviderID   string
	ProviderType string
	Issuer       string
	Subject      string
	SubjectHash  string
}

func LinkedIdentityForProvider

func LinkedIdentityForProvider(provider config.AuthProviderConfig, identities []ExternalIdentity) (ExternalIdentity, bool)

LinkedIdentityForProvider returns the identity in identities that provider signs in. An OIDC identity also matches a provider with the same issuer.

type ExternalIdentitySignInPolicy

type ExternalIdentitySignInPolicy struct {
	// PasswordLoginEnabled counts a stored password as an available method.
	PasswordLoginEnabled bool
	// Issuers contains identity namespaces accepted by configured providers.
	Issuers []string
}

ExternalIdentitySignInPolicy describes the sign-in methods enabled on the serving replica. Issuers contains exact OIDC issuer URLs and configured provider IDs for OAuth-only providers. Stored event-time provider IDs do not determine whether an identity is usable.

func (ExternalIdentitySignInPolicy) AllowsIdentity

func (p ExternalIdentitySignInPolicy) AllowsIdentity(identity ExternalIdentity) bool

AllowsIdentity reports whether a configured provider accepts this namespace.

func (ExternalIdentitySignInPolicy) CanDisconnect

func (p ExternalIdentitySignInPolicy) CanDisconnect(subjectHash string, identities []ExternalIdentity, hasPassword bool) bool

CanDisconnect reports whether removing subjectHash from this snapshot leaves an enabled sign-in method. It does not verify that the target exists or that the caller is authorized. Mutations must check again inside the user OCC loop.

type FollowedThread

type FollowedThread struct {
	SpaceID           string
	RoomID            string
	ThreadRootEventID string
	Exists            bool
	ReplyCount        int
	LastReplyAt       *time.Time
	ActivityAt        *time.Time
	// RootCreatedAt is the root message creation time, independent of replies.
	RootCreatedAt  *time.Time
	ParticipantIDs []string
	// ParticipantCount counts distinct current reply authors,
	// excluding erased users, beyond the preview limit.
	ParticipantCount   int
	LatestReplyEventID string
	HasUnreadReplies   bool
}

FollowedThread represents a thread the user is following, enriched with metadata for display.

type FollowedThreadsPage

type FollowedThreadsPage struct {
	Threads    []*FollowedThread
	TotalCount int
	HasMore    bool
}

FollowedThreadsPage is a paginated set of followed threads with the total count before pagination.

type HistoricalMessageChange

type HistoricalMessageChange struct {
	RoomID, MessageID, OperationKey, ActorID, Kind, Body, UserID, Emoji string
	OccurredAt                                                          *time.Time
	AssetIDs                                                            []string
	Present                                                             bool
}

HistoricalMessageChange is one mutation on an existing mapped message.

type HistoricalMessageInput

type HistoricalMessageInput struct {
	RoomID             string
	AuthorID           string
	CreatedAt          time.Time
	EditedAt           *time.Time
	InReplyTo          string
	AttachmentAssetIDs []string
	Body               string
	LinkPreview        *evtv1.LinkPreview
	// ThreadRootEventID places a reply explicitly; InReplyTo stays attribution only.
	ThreadRootEventID string
	// CreateThread establishes an empty thread on the new root without a follow.
	CreateThread bool
	// IdempotencyKey reserves one import identity for MessageIdempotencyWindow.
	IdempotencyKey string
	// Deleted imports a native tombstone without storing any message body.
	Deleted bool
	// OperationKey provides permanent exact retry protection, independently of archives.
	OperationKey string
	// DeletedAt and SourceActorID preserve optional source metadata for keyed imports.
	DeletedAt     *time.Time
	SourceActorID string
}

HistoricalMessageInput is one operator import. A UUID enables the same bounded retry window as interactive sends, scoped separately to imports.

type HistoricalMessageOperation

type HistoricalMessageOperation struct {
	Message             HistoricalMessageInput
	ThreadRootOperation string
	ReplyToOperation    string
	Reactions           []HistoricalMessageChange
}

HistoricalMessageOperation imports a message and its ordered reaction changes. Local references must name earlier message operation keys in the same call. They cannot accompany the corresponding destination event ID. Reaction inputs omit RoomID, MessageID, and Kind; the parent supplies these fields.

type HistoricalReactionInput

type HistoricalReactionInput struct {
	RoomID         string
	MessageEventID string
	UserID         string
	Emoji          string
}

HistoricalReactionInput identifies one imported reaction. Source timestamps are intentionally absent: Slack exports provide membership, not reaction time.

type HistoricalRoomChange

type HistoricalRoomChange struct {
	RoomID, OperationKey, ActorID, Kind, Value string
	OccurredAt                                 *time.Time
	Hidden                                     bool
}

HistoricalRoomChange is one channel transition with mapped destination IDs. Unknown times are nil; Hidden reconciles state without visible activity.

type HistoricalUserInput

type HistoricalUserInput struct {
	Login, DisplayName, Email, BotOwnerID string
	Deactivated                           bool
}

HistoricalUserInput describes an imported account, not a source-platform identity. BotOwnerID selects bot creation and must name an active human.

type HydratedUserContent

type HydratedUserContent struct {
	User        *readmodel.User
	Avatar      *evtv1.AssetRecord
	Preferences *evtv1.ServerUserPreferences
}

HydratedUserContent contains the public user state that was captured in one UserContentSnapshot. Presence is runtime state and is not included.

type InteractionUserPage

type InteractionUserPage struct {
	UserIDs    []string
	TotalCount int
	HasMore    bool
}

InteractionUserPage is a bounded set of user references. TotalCount counts relationships before pagination; clients can hydrate profiles separately.

type InvalidArgumentError

type InvalidArgumentError struct {
	Message string
}

InvalidArgumentError carries a caller-safe validation message while still matching ErrInvalidArgument through errors.Is.

func (*InvalidArgumentError) Error

func (e *InvalidArgumentError) Error() string

func (*InvalidArgumentError) Is

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

type InvitationModel

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

type InvitationProjection

type InvitationProjection struct {
	events.MemoryProjection
	// contains filtered or unexported fields
}

func NewInvitationProjection

func NewInvitationProjection() *InvitationProjection

func (*InvitationProjection) Apply

func (p *InvitationProjection) Apply(event *evtv1.Event, _ uint64) error

func (*InvitationProjection) Subjects

func (p *InvitationProjection) Subjects() []string

type InvitationState

type InvitationState struct {
	ID        string
	CreatedBy string
	CreatedAt time.Time
	ExpiresAt *time.Time
	Used      bool
	RevokedAt *time.Time
	// Note is creation-time metadata, visible only to invitation managers.
	Note string
}

InvitationState is the durable, administrator-visible state derived for one invitation.

type InvitationStatus

type InvitationStatus string
const (
	InvitationStatusActive  InvitationStatus = "active"
	InvitationStatusExpired InvitationStatus = "expired"
	InvitationStatusUsed    InvitationStatus = "used"
	InvitationStatusRevoked InvitationStatus = "revoked"
)

func InvitationStatusAt

func InvitationStatusAt(state InvitationState, now time.Time) InvitationStatus

type JetStreamStats

type JetStreamStats struct {
	Streams              []StreamStats
	Consumers            []ConsumerStats
	TotalMessages        uint64
	TotalBytes           uint64
	TotalConsumerPending uint64
	TotalAckPending      int
}

JetStreamStats contains operator-facing stream and consumer diagnostics.

type LastReadEventIDAdvance

type LastReadEventIDAdvance struct {
	PreviousEventID string
	PreviousTime    time.Time
	CurrentEventID  string
	CurrentTime     time.Time
	Updated         bool
}

LastReadEventIDAdvance describes the result of an advance-only room read marker update.

type ListRoomAttachmentsInput

type ListRoomAttachmentsInput struct {
	ActorID string
	RoomID  string
	Limit   int
	Offset  int
}

ListRoomAttachmentsInput is the authorized room attachment list request.

type LiveKitAdminStatus

type LiveKitAdminStatus struct {
	Enabled            bool
	Configured         bool
	URL                string
	APIKey             string
	SeparateWebhookKey bool
	// WebhookURL is the endpoint LiveKit must call, derived from the public server URL.
	WebhookURL      string
	ConnectionState LiveKitConnectionState
	// ConnectionError is the check failure detail. It is empty when the check passed or did not run.
	ConnectionError string
	// InsecureURL reports an unencrypted LiveKit URL on a non-local deployment.
	InsecureURL bool
	// LastWebhookAt and LastRejectedWebhookAt are process-local and reset on restart.
	LastWebhookAt         time.Time
	LastRejectedWebhookAt time.Time
}

LiveKitAdminStatus describes the LiveKit setup for owner diagnostics. It never contains the API secret or the webhook signing secret.

type LiveKitConnectionState

type LiveKitConnectionState int

LiveKitConnectionState is the result of the LiveKit server API check.

const (
	// LiveKitConnectionNotConfigured means LiveKit is not configured, so no check ran.
	LiveKitConnectionNotConfigured LiveKitConnectionState = iota + 1
	// LiveKitConnectionOK means LiveKit accepted an API call with the configured credentials.
	LiveKitConnectionOK
	// LiveKitConnectionUnreachable means Chatto could not connect to the LiveKit URL.
	LiveKitConnectionUnreachable
	// LiveKitConnectionUnauthorized means LiveKit rejected the configured API key or secret.
	LiveKitConnectionUnauthorized
	// LiveKitConnectionError means the server at the LiveKit URL replied with another error.
	LiveKitConnectionError
)

type MarkRoomAsReadResult

type MarkRoomAsReadResult struct {
	LastReadAt         time.Time
	PreviousLastReadAt time.Time
}

MarkRoomAsReadResult describes the timestamp response for a room-level read marker update.

type MarkThreadAsReadResult

type MarkThreadAsReadResult struct {
	// LastReadAt is the retained marker after this operation. Zero means no marker.
	LastReadAt time.Time
	// PreviousLastReadAt is the marker observed by the successful advance decision.
	PreviousLastReadAt time.Time
}

MarkThreadAsReadResult describes the timestamp response for a thread-level read marker update.

type MatrixDecision

type MatrixDecision string
const (
	MatrixDecisionAllow MatrixDecision = "ALLOW"
	MatrixDecisionDeny  MatrixDecision = "DENY"
	MatrixDecisionNone  MatrixDecision = "NONE"
)

type MatrixScopeKind

type MatrixScopeKind string
const (
	MatrixScopeServer MatrixScopeKind = "SERVER"
	MatrixScopeGroup  MatrixScopeKind = "GROUP"
	MatrixScopeRoom   MatrixScopeKind = "ROOM"
	MatrixScopeDM     MatrixScopeKind = "DM"
)

type MediaModel

type MediaModel struct {
	*ChattoCore
	// contains filtered or unexported fields
}

MediaModel owns attachment/media storage, media URL generation, and resize cache operations.

It currently embeds ChattoCore so the model boundary can be introduced without copying the full core dependency graph. As more models settle, this can shrink to explicit dependencies in the same direction as RoomModel and PresenceModel.

func NewMediaModel

func NewMediaModel(core *ChattoCore) *MediaModel

func (*MediaModel) DeleteAttachmentFromStorage

func (c *MediaModel) DeleteAttachmentFromStorage(ctx context.Context, attachment *evtv1.Attachment) error

DeleteAttachmentFromStorage deletes an attachment's binary and its cached resizes. When Storage is missing for legacy imported derivatives, it falls back to known backend key layouts by attachment ID.

func (*MediaModel) DeleteCachedResizesForAttachment

func (c *MediaModel) DeleteCachedResizesForAttachment(ctx context.Context, attachmentID string) (int, error)

DeleteCachedResizesForAttachment deletes all cached resizes for an attachment. Returns the number of deleted cache entries and any error encountered. One cache scan removes current and earlier stable attachment cache namespaces; older room-kind prefixes remain unaddressable and expire after seven days.

func (*MediaModel) DeleteCachedResizesForKey

func (c *MediaModel) DeleteCachedResizesForKey(ctx context.Context, prefix, assetKey string) (int, error)

DeleteCachedResizesForKey deletes all cached resizes for a given prefix and asset key. Returns the number of deleted cache entries and any error encountered.

func (*MediaModel) DeleteCachedResizesForServerAsset

func (c *MediaModel) DeleteCachedResizesForServerAsset(ctx context.Context, assetID string) (int, error)

DeleteCachedResizesForServerAsset deletes all cached resizes for a server asset such as a user avatar or server branding image.

func (*MediaModel) GetAttachment

func (c *MediaModel) GetAttachment(ctx context.Context, attachmentID string) (io.Reader, *jetstream.ObjectInfo, error)

GetAttachment retrieves an attachment by ID from NATS ObjectStore. This is the legacy path for attachments stored in NATS. Returns a reader for the attachment content and the object info.

func (*MediaModel) GetAttachmentReader

func (c *MediaModel) GetAttachmentReader(ctx context.Context, attachment *evtv1.Attachment) (io.Reader, *AttachmentInfo, error)

GetAttachmentReader reads an attachment's binary from whichever storage backend its `Storage` field points at. Returns a reader and metadata. The caller is responsible for closing the reader if it implements io.Closer.

When `Storage` is nil, falls back to probing known backend layouts for the binary by attachment ID — this handles pre-locator video variants and thumbnails whose backfilled Attachment protos came from minimal standalone records that lacked a `Storage` field.

func (*MediaModel) GetAttachmentsStore

func (c *MediaModel) GetAttachmentsStore(ctx context.Context) (jetstream.ObjectStore, error)

GetAttachmentsStore returns the ObjectStore for attachments. Uses lazy-loading and caching for efficiency.

func (*MediaModel) GetCachedResize

func (c *MediaModel) GetCachedResize(ctx context.Context, key string) ([]byte, error)

GetCachedResize retrieves a cached resized image. Returns nil, nil if the key is not found.

func (*MediaModel) GetS3Attachment

func (c *MediaModel) GetS3Attachment(ctx context.Context, s3Key string) (io.ReadCloser, *AttachmentInfo, error)

GetS3Attachment retrieves an attachment from S3 by its key. Returns a reader for the attachment content and metadata. The caller is responsible for closing the reader.

AttachmentInfo.RoomID is NOT populated here — S3 has no equivalent of the NATS `Room-Id` header. Callers that need authorization should instead look up the canonical Attachment record via GetAttachmentRecord.

func (*MediaModel) GetStableAttachmentAssetURL

func (c *MediaModel) GetStableAttachmentAssetURL(assetID, userID string) StableAssetURL

GetStableAttachmentAssetURL returns the canonical URL for an asset binary together with the exact expiry embedded in its access ticket. The path identifies the asset; the asset-scoped access ticket authorizes the viewer so browsers and standalone clients can load the URL directly from the owning host without custom headers.

func (*MediaModel) GetStableHLSMasterPlaylistAssetURL

func (c *MediaModel) GetStableHLSMasterPlaylistAssetURL(assetID, userID string) StableAssetURL

GetStableHLSMasterPlaylistAssetURL returns the authorised entry point for one processed video's HLS generation.

func (*MediaModel) GetStableTransformedAttachmentAssetURL

func (c *MediaModel) GetStableTransformedAttachmentAssetURL(assetID, userID string, width, height int, fit string) StableAssetURL

GetStableTransformedAttachmentAssetURL returns the canonical URL for a derived image form factor together with the exact expiry embedded in its access ticket. The dimensions are visible in the URL; authorization is a scoped access ticket.

func (*MediaModel) GetTransformedServerAssetURL

func (c *MediaModel) GetTransformedServerAssetURL(key string, width, height int, fit string) string

GetTransformedServerAssetURL returns the URL for accessing a transformed version of an server asset. Server assets include server logos, server banners, and user avatars stored in SERVER_ASSETS. The URL includes HMAC signature to prevent parameter tampering. Format: /assets/server/{key}/t/{params}.{signature} where {params} is base64url-encoded JSON: {"w":width,"h":height,"f":"fit"}

func (*MediaModel) MessageBodyAttachments

func (c *MediaModel) MessageBodyAttachments(body *evtv1.MessageBody) []*evtv1.Attachment

MessageBodyAttachments returns the materialised attachments for a MessageBody, hydrating from the asset projection when the body uses asset_ids (current format) and falling back to the legacy embedded attachments slice otherwise. The returned slice preserves the body's declared order; missing projection entries are skipped.

func (*MediaModel) StoreCachedResize

func (c *MediaModel) StoreCachedResize(ctx context.Context, key string, data []byte) error

StoreCachedResize stores a resized image in the cache.

func (*MediaModel) StoreCachedResizeIfAbsent

func (c *MediaModel) StoreCachedResizeIfAbsent(ctx context.Context, key string, data []byte) error

StoreCachedResizeIfAbsent stores a resized image unless the key already exists. Reading an object while it is replaced can stall and fail, so a cache whose keys never change content uses this to avoid replacements. Two writers that check at the same moment can still both write.

func (*MediaModel) TryPresignedAttachmentURL

func (c *MediaModel) TryPresignedAttachmentURL(ctx context.Context, attachment *evtv1.Attachment, ttl time.Duration) (string, error)

TryPresignedAttachmentURL generates a presigned S3 URL for an attachment. Returns an error if S3 isn't configured, the attachment isn't stored in S3 (e.g. NATS), or no S3 key can be found (in any of which cases the caller should fall back to GetAttachmentReader).

When `Storage` is nil, falls back to stat-probing known S3 key layouts. See `GetAttachmentReader` for why this exists.

Authorization is the caller's responsibility.

func (*MediaModel) UploadAttachment

func (c *MediaModel) UploadAttachment(
	ctx context.Context,
	actorID string,
	roomID string,
	filename string,
	contentType string,
	reader io.Reader,
) (*evtv1.Attachment, error)

UploadAttachment uploads a file as an attachment and returns the attachment metadata. For images, it extracts dimensions. Thumbnails are generated on-the-fly via transforms. The storage backend (NATS or S3) is determined by configuration.

UploadAttachment stores a binary in the configured backend, emits a durable AssetCreatedEvent into the asset aggregate (so the asset becomes a first-class entity from the moment its bytes hit storage), and returns the rendered Attachment view for the caller.

`actorID` is the uploader; it's stamped on the AssetCreatedEvent as the asset's user_id, distinct from any future message_event_id that attaches the asset. The returned Attachment has `MessageBodyId` empty — the asset is not yet bound to a message; PostMessage references it by ID.

func (*MediaModel) UploadDerivativeAttachment

func (c *MediaModel) UploadDerivativeAttachment(
	ctx context.Context,
	parentAssetID string,
	derivativeRole evtv1.AssetDerivativeRole,
	roomID string,
	filename string,
	contentType string,
	reader io.ReadSeeker,
) (*evtv1.Attachment, error)

UploadDerivativeAttachment is the worker-side variant of UploadAttachment. It streams generated bytes without a user upload limit; for an image, it reads only the headers to get the dimensions. It emits AssetCreatedEvent with parent_asset_id + derivative_role already set, so the projection knows this asset is a child of `parentAssetID` (thumbnails, transcoded video variants, etc.). Always attributed to SystemActorID — derivatives are produced by workers, not user actions.

func (*MediaModel) UploadDerivativeAttachmentWithDimensions

func (c *MediaModel) UploadDerivativeAttachmentWithDimensions(
	ctx context.Context,
	parentAssetID string,
	derivativeRole evtv1.AssetDerivativeRole,
	roomID string,
	filename string,
	contentType string,
	reader io.ReadSeeker,
	width int32,
	height int32,
) (*evtv1.Attachment, error)

UploadDerivativeAttachmentWithDimensions is UploadDerivativeAttachment with explicit media dimensions supplied by the worker for generated non-image derivatives such as transcoded video variants. The reader must be seekable so storage can receive the binary size without buffering its content.

type MemberRoomListOptions

type MemberRoomListOptions struct {
	// RequireLastMessage excludes rooms that have never received a message.
	RequireLastMessage bool
	// SortByLastMessageDesc sorts rooms by latest message time, newest first.
	// Rooms without messages sort last when RequireLastMessage is false.
	SortByLastMessageDesc bool
}

MemberRoomListOptions controls optional filtering/sorting for ListMemberRooms.

type MentionableAvailability

type MentionableAvailability struct {
	Available bool
	OwnerKind mentionableOwnerKind
	OwnerID   string
}

func (MentionableAvailability) String

func (a MentionableAvailability) String() string

type MentionablesModel

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

func (*MentionablesModel) Availability

func (s *MentionablesModel) Availability(handle string, allowedOwner *mentionableOwner) MentionableAvailability

type MentionablesProjection

type MentionablesProjection struct {
	events.MemoryProjection
	// contains filtered or unexported fields
}

MentionablesProjection derives the global @handle namespace from durable user and RBAC facts. It consumes the whole EVT stream so callers can use the stream-wide OCC boundary for user-vs-role uniqueness without adding a separate claim record.

func NewMentionablesProjection

func NewMentionablesProjection(keyWrapper kms.KeyWrapper, dekStore dekstore.Reader) *MentionablesProjection

NewMentionablesProjection creates the global mentionable-handle read model. It keeps encrypted DEK event references for replay, while raw key bytes are resolved through the shared unwrapped-DEK resolver.

func (*MentionablesProjection) Apply

func (p *MentionablesProjection) Apply(event *evtv1.Event, _ uint64) error

func (*MentionablesProjection) Availability

func (p *MentionablesProjection) Availability(handle string, allowedOwner *mentionableOwner) MentionableAvailability

func (*MentionablesProjection) Prepare

Prepare resolves encrypted user handles before the content view commits any component mutation.

func (*MentionablesProjection) Restore

func (p *MentionablesProjection) Restore(data []byte) error

func (*MentionablesProjection) Snapshot

func (p *MentionablesProjection) Snapshot() ([]byte, error)

func (*MentionablesProjection) SnapshotContractID

func (*MentionablesProjection) SnapshotContractID() string

func (*MentionablesProjection) Subjects

func (p *MentionablesProjection) Subjects() []string

type MessageAssetRef

type MessageAssetRef struct {
	RoomID         string
	MessageEventID string
	AssetID        string
}

MessageAssetRef identifies the message, room, and asset in one projected message-to-asset ownership relationship.

type MessageAttachmentDeleteInput

type MessageAttachmentDeleteInput struct {
	ActorID      string
	RoomID       string
	EventID      string
	AttachmentID string
}

MessageAttachmentDeleteInput describes removal of one attachment from a message body.

type MessageAttachmentDescriptionInput

type MessageAttachmentDescriptionInput struct {
	AssetID     string
	Description string
}

MessageAttachmentDescriptionInput associates one attachment asset with user-provided descriptive text.

type MessageAttachmentDescriptionSetInput

type MessageAttachmentDescriptionSetInput struct {
	ActorID      string
	RoomID       string
	EventID      string
	AttachmentID string
	Description  string
}

MessageAttachmentDescriptionSetInput describes one attachment-description replacement. An empty normalized description clears the current value.

type MessageAttachmentSet

type MessageAttachmentSet struct {
	EventID     string
	Attachments []*evtv1.Attachment
}

MessageAttachmentSet contains current attachments for one visible message.

type MessageAttachmentsInput

type MessageAttachmentsInput struct {
	ActorID string
	RoomID  string
	EventID string
}

MessageAttachmentsInput is the authorized current-message attachment request.

type MessageBodyVersion

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

HydrateMessagePost resolves echo attribution and mentions for a read response. The returned echo payload is detached from EVT. Missing originals never use old copied echo metadata. Envelope identity and timeline routing remain unchanged. MessageBodyVersion identifies the body that GetFullMessageBody reads for one message. Two equal values mean that the body did not change between them. An edit, a retraction, or a key-shredding request of the author changes the value. The room timeline and the content-key projections apply a key-shredding request independently, so the value checks both. The value is comparable with ==.

type MessageDeleteInput

type MessageDeleteInput struct {
	ActorID string
	RoomID  string
	EventID string
}

MessageDeleteInput describes one user-facing message retraction operation.

type MessageLinkPreviewDeleteInput

type MessageLinkPreviewDeleteInput struct {
	ActorID string
	RoomID  string
	EventID string
	URL     string
}

MessageLinkPreviewDeleteInput describes removal of one link preview from a message body.

type MessageModel

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

MessageModel owns user-facing message operations. Lower-level ChattoCore helpers still perform the event-sourced write, while this model centralizes authZ and post-write sync behavior for public transports.

func (*MessageModel) AuthorizePost

AuthorizePost checks the room, visibility, and permission gates for a user-facing message post.

func (*MessageModel) DeleteAttachment

func (s *MessageModel) DeleteAttachment(ctx context.Context, input MessageAttachmentDeleteInput) error

DeleteAttachment removes one attachment from a message. Authorization: actor must be a room member; the core partial-edit helper keeps the operation author-only.

func (*MessageModel) DeleteLinkPreview

func (s *MessageModel) DeleteLinkPreview(ctx context.Context, input MessageLinkPreviewDeleteInput) error

DeleteLinkPreview removes the selected link preview from a message. Authorization: actor must be a room member; the core partial-edit helper keeps the operation author-only.

func (*MessageModel) DeleteMessage

func (s *MessageModel) DeleteMessage(ctx context.Context, input MessageDeleteInput) error

DeleteMessage retracts an existing message. Authorization: actor must be a room member. Authors may delete their own messages; non-authors need message.manage.

func (*MessageModel) PostMessage

func (s *MessageModel) PostMessage(ctx context.Context, input MessagePostInput) (*MessagePostResult, error)

PostMessage posts a message as actorID and returns the committed event. Authorization: actor must be a room member and must have message.post or message.post-in-thread, or message.post-in-interactions with a relationship to the target thread. Replies also require read access. Explicit thread creation requires message.post. Echoing a thread reply additionally requires message.echo and message.post.

func (*MessageModel) PreflightPost

func (s *MessageModel) PreflightPost(ctx context.Context, input MessagePostInput) (*MessagePostPreflight, error)

PreflightPost checks authorization and request validity before a transport uploads binary attachments.

func (*MessageModel) SendTypingIndicator

func (s *MessageModel) SendTypingIndicator(ctx context.Context, input TypingIndicatorInput) error

SendTypingIndicator publishes a live-only typing indicator. Authorization: actor must be a room member and must be authorized to read the destination timeline. There is intentionally no message-posting permission check.

func (*MessageModel) SetAttachmentDescription

func (s *MessageModel) SetAttachmentDescription(ctx context.Context, input MessageAttachmentDescriptionSetInput) (*evtv1.Event, RoomKind, error)

SetAttachmentDescription sets or clears one description. Authorization: actor must be able to read the message. Authors may edit within the message edit window; effective message.manage bypasses the window and permits edits to other authors' messages.

func (*MessageModel) ThreadSlowModeNextPostAt

func (s *MessageModel) ThreadSlowModeNextPostAt(ctx context.Context, roomID, threadID, actorID string) (time.Time, error)

ThreadSlowModeNextPostAt resolves the caller's deadline after the read path has authorized access to the room and canonical thread.

func (*MessageModel) ThreadSlowModeReader

func (s *MessageModel) ThreadSlowModeReader(ctx context.Context, roomID, actorID string) (func(string) time.Time, error)

ThreadSlowModeReader resolves configuration and exemptions once for one response. The caller must authorize room and thread access separately. Do not cache this reader across requests: settings and permissions can change.

func (*MessageModel) UpdateMessage

func (s *MessageModel) UpdateMessage(ctx context.Context, input MessageUpdateInput) (*evtv1.Event, RoomKind, error)

UpdateMessage edits an existing message. Authorization: actor must be a room member and authorized to read the message. Authors may edit their own messages within the core edit window. Effective message.manage bypasses the window and permits edits to other authors' messages. A thread reply's room-timeline echo can be removed by the author or with effective message.manage. Enabling the echo is author-only and additionally requires message.echo and message.post.

type MessagePostAppliedError

type MessagePostAppliedError struct{ Cause error }

MessagePostAppliedError reports that EVT contains the requested message but its result cannot be returned. Unwrap retains the current read-policy error. Transports must not describe this as an unapplied write.

func (*MessagePostAppliedError) Error

func (e *MessagePostAppliedError) Error() string

func (*MessagePostAppliedError) Unwrap

func (e *MessagePostAppliedError) Unwrap() error

type MessagePostAuthorization

type MessagePostAuthorization struct {
	Room *readmodel.Room
	Kind RoomKind
}

MessagePostAuthorization is the resolved room context for an authorized post.

type MessagePostAuthorizationInput

type MessagePostAuthorizationInput struct {
	ActorID           string
	RoomID            string
	Body              string
	HasAttachments    bool
	ThreadRootEventID string
	InReplyTo         string
	AlsoSendToChannel bool
	CreateThread      bool
	// contains filtered or unexported fields
}

MessagePostAuthorizationInput describes the authorization preflight for a user-facing message post. HasAttachments covers attachments that have not yet been uploaded and therefore do not have asset IDs.

type MessagePostInput

type MessagePostInput struct {
	ActorID                 string
	RoomID                  string
	Body                    string
	AttachmentAssetIDs      []string
	AttachmentDescriptions  []MessageAttachmentDescriptionInput
	HasPendingAttachments   bool
	VideoProcessingAssetIDs []string
	ThreadRootEventID       string
	InReplyTo               string
	AlsoSendToChannel       bool
	CreateThread            bool
	LinkPreview             *evtv1.LinkPreview
	// LinkPreviewToken is resolved only when a new write is needed. Exact
	// retries remain valid after the original preview token expires.
	LinkPreviewToken string
	// IdempotencyKey is an optional account-scoped caller UUID. It reserves a
	// server-generated message identity for 30 minutes without entering EVT.
	IdempotencyKey string
	// contains filtered or unexported fields
}

MessagePostInput describes one user-facing message post operation.

type MessagePostPreflight

type MessagePostPreflight struct {
	Authorization *MessagePostAuthorization
}

MessagePostPreflight is the result of checking whether a post can proceed before any transport-specific attachment uploads are performed.

type MessagePostResult

type MessagePostResult struct {
	Event *evtv1.Event
}

MessagePostResult is returned by MessageModel.PostMessage.

type MessageReadResult

type MessageReadResult struct {
	Kind  RoomKind
	Event *evtv1.Event
}

type MessageSearchHit

type MessageSearchHit struct {
	MessageID   string
	RoomID      string
	BodyEventID string
	Score       float64
}

MessageSearchHit is one untrusted provider candidate.

type MessageSearchReadModel

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

MessageSearchReadModel keeps the full-text provider outside Chatto's authorization boundary. Provider hits are candidates, never readable facts.

func (*MessageSearchReadModel) FilterFollowedSearchResults

func (s *MessageSearchReadModel) FilterFollowedSearchResults(ctx context.Context, actorID string, results []MessageSearchResult) ([]MessageSearchResult, error)

FilterFollowedSearchResults rechecks follow state after provider work.

func (*MessageSearchReadModel) FollowedSearchRoots

func (s *MessageSearchReadModel) FollowedSearchRoots(ctx context.Context, scope *MessageSearchScope, actorID string, rootAuthor ThreadRootAuthorFilter) ([]string, error)

FollowedSearchRoots returns the followed-root scope in authorized rooms, restricted by root author when requested. Empty must be handled by the caller as no matches, never unrestricted search.

func (*MessageSearchReadModel) HydrateHits

HydrateHits preserves provider order while omitting duplicate, inaccessible, stale, retracted, crypto-shredded, wrong-room, and non-message candidates.

func (*MessageSearchReadModel) ResolveScope

ResolveScope returns only rooms where the actor is currently a member with applicable message-read authority. Archived rooms remain eligible.

func (*MessageSearchReadModel) SearchThreadGroups

func (s *MessageSearchReadModel) SearchThreadGroups(ctx context.Context, actorID string, limit, offset int, scope *MessageSearchScope, normalized *searchv1.QueryRequest, followedOnly bool, threadOrder ThreadOrder, query ThreadSearchQuery) (*ThreadSearchPage, error)

SearchThreadGroups resolves groups before pagination. The first current hit in provider order represents its thread; resolved roots are excluded on the next request so a large thread does not require reading all matching replies. Totals and thread-date order require visiting all matching groups. Work has one deadline, including stale-hit walks. Cursors do not pin an index snapshot.

type MessageSearchResult

type MessageSearchResult struct {
	Kind  RoomKind
	Event *evtv1.Event
	Score float64
}

MessageSearchResult is one current message that survived authorization and current-state hydration.

type MessageSearchScope

type MessageSearchScope struct {
	RoomIDs   []string
	AuthorIDs []string
	NoMatches bool
	// contains filtered or unexported fields
}

MessageSearchScope contains stable provider filters and the current room objects used to reject provider hits outside the authorized candidate set.

type MessageSearchScopeInput

type MessageSearchScopeInput struct {
	ActorID         string
	RoomID          string
	RoomSelectors   []string
	AuthorID        string
	AuthorSelectors []string
}

MessageSearchScopeInput combines explicit public request filters with selectors parsed from the canonical query language.

type MessageUpdateInput

type MessageUpdateInput struct {
	ActorID           string
	RoomID            string
	EventID           string
	Body              *string
	AlsoSendToChannel *bool
}

MessageUpdateInput describes one user-facing message edit operation.

type MyEventsHub

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

MyEventsHub owns the process-wide NATS ingress for realtime events. It classifies and decodes each message once, waits for local projections once, and then fans immutable event envelopes out through per-session queues. Room visibility is shared by all sessions of one principal: the same user with the same privileged-mode state.

func NewMyEventsHub

func NewMyEventsHub(model *MyEventsModel) *MyEventsHub

func (*MyEventsHub) Run

func (h *MyEventsHub) Run(ctx context.Context) error

Run subscribes to the internal live-delivery roots and processes their messages in arrival order. It is started once by ChattoCore.Run.

The subscription uses the NATS client's pending queue, not a Go channel that NATS writes to without waiting: a full channel makes NATS drop the message at once. The subscription callback waits for the hub instead, so a burst waits in the pending queue. NATS drops a message only when the queue exceeds myEventsIngressPendingBytes. A dropped message can be a durable fact or a security control, such as session termination, so the hub then closes every subscriber. Clients reconnect and catch up.

func (*MyEventsHub) Subscribe

func (h *MyEventsHub) Subscribe(ctx context.Context, userID string) (*myEventsSubscription, error)

func (*MyEventsHub) Unsubscribe

func (h *MyEventsHub) Unsubscribe(sub *myEventsSubscription)

type MyEventsMetrics

type MyEventsMetrics struct {
	ActiveStreams     int64
	DeliveredEvents   uint64
	SlowDisconnects   uint64
	PresenceRefreshes uint64
	PresenceFailures  uint64
}

MyEventsMetrics is a process-local snapshot of the realtime event stream.

type MyEventsModel

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

MyEventsModel owns the server-side myEvents live stream machinery.

ChattoCore remains the public facade, while this model keeps live root filtering, projection readiness, shared per-user room visibility, and per-session delivery together.

func NewMyEventsModel

func NewMyEventsModel(core *ChattoCore) *MyEventsModel

func (*MyEventsModel) Metrics

func (s *MyEventsModel) Metrics() MyEventsMetrics

Metrics returns process-local live-event stream counters.

func (*MyEventsModel) Run

func (s *MyEventsModel) Run(ctx context.Context) error

Run starts the process-wide live-event ingress and blocks until ctx ends.

func (*MyEventsModel) StreamMyEvents

func (s *MyEventsModel) StreamMyEvents(ctx context.Context, userID string, options StreamMyEventsOptions) (<-chan EventEnvelope, error)

type Neighbor

type Neighbor struct {
	ID       string
	Origin   string
	Revision string
}

Neighbor is one server advertised through the public Neighbor directory. Revision is the envelope ID of the latest durable fact for this resource.

type NotificationDecisionProjection

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

NotificationDecisionProjection keeps the compact current state needed to derive notification recipients and policy while enforcing persistent privacy boundaries.

func NewNotificationDecisionProjection

func NewNotificationDecisionProjection() *NotificationDecisionProjection

NewNotificationDecisionProjection returns an empty projection with a private event ID table.

func (*NotificationDecisionProjection) Apply

func (p *NotificationDecisionProjection) Apply(event *evtv1.Event, seq uint64) error

func (*NotificationDecisionProjection) CompleteStartupReplay

func (p *NotificationDecisionProjection) CompleteStartupReplay()

func (*NotificationDecisionProjection) ReplaySubjects

func (*NotificationDecisionProjection) ReplaySubjects() []string

ReplaySubjects uses one physical EVT filter. This projection's logical contract spans several sparse aggregate families; one broad scan avoids the JetStream multi-filter cost while Projector still rejects unrelated subjects before decoding or applying them.

func (*NotificationDecisionProjection) Restore

func (p *NotificationDecisionProjection) Restore(data []byte) error

func (*NotificationDecisionProjection) Snapshot

func (p *NotificationDecisionProjection) Snapshot() ([]byte, error)

func (*NotificationDecisionProjection) SnapshotContractID

func (*NotificationDecisionProjection) SnapshotContractID() string

func (*NotificationDecisionProjection) Subjects

func (*NotificationDecisionProjection) Subjects() []string

type NotificationMaterializer

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

NotificationMaterializer consumes existing domain facts and applies their notification effects. It makes each decision from current projected state, then stores self-contained durable output before it acknowledges EVT. EVT contains no notification-only planning events and RUNTIME_STATE contains no notification work queue.

func (*NotificationMaterializer) Initialize

func (m *NotificationMaterializer) Initialize(ctx context.Context) error

Initialize creates the DeliverNew consumer before projectors start. This closes the gap in which a source fact could commit before durable work discovery exists.

func (*NotificationMaterializer) Run

func (*NotificationMaterializer) WaitCurrent

func (m *NotificationMaterializer) WaitCurrent(ctx context.Context) error

WaitCurrent captures the latest EVT sequence relevant to the notification worker and waits until the durable consumer has acknowledged it. A fresh DeliverNew consumer reports its creation-time stream floor as delivered with consumer sequence zero; that boundary is intentionally considered current because Notifications 2.0 does not replay older facts.

func (*NotificationMaterializer) WaitReady

func (m *NotificationMaterializer) WaitReady(ctx context.Context) error

WaitReady waits until the durable consumer exists. Serving must not begin before this boundary: DeliverNew can recover only source facts committed after the consumer was created.

func (*NotificationMaterializer) WaitThrough

func (m *NotificationMaterializer) WaitThrough(ctx context.Context, streamSequence uint64) error

WaitThrough waits until the shared durable consumer has acknowledged the triggering EVT sequence. Request paths use this only for read-your-writes; the worker remains the sole owner of occurrence creation and cleanup.

type NotificationOccurrenceModel

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

NotificationOccurrenceModel owns commands and reads over the bounded NOTIFICATIONS event log and its process-wide framework projection.

func (*NotificationOccurrenceModel) CreateMany

CreateMany materializes one source fact's complete recipient fanout with bounded atomic writes, one projection wait, and one live invalidation per recipient. It is intentionally internal to the ordered materializer.

func (*NotificationOccurrenceModel) Delete

func (m *NotificationOccurrenceModel) Delete(ctx context.Context, userID, notificationID string) (bool, error)

func (*NotificationOccurrenceModel) DeleteMany

func (m *NotificationOccurrenceModel) DeleteMany(ctx context.Context, userID string, notificationIDs []string) (int, error)

func (*NotificationOccurrenceModel) Get

func (*NotificationOccurrenceModel) HasNotificationUnread

func (m *NotificationOccurrenceModel) HasNotificationUnread(ctx context.Context, userID, roomID, threadRootEventID string) (bool, error)

HasNotificationUnread reports whether a room or exact thread has Badge attention. It is computed from current projected state and the user's read boundaries; no per-user Badge state is stored. An empty thread root includes every thread of the room.

func (*NotificationOccurrenceModel) List

func (*NotificationOccurrenceModel) MarkCoveredRead

func (m *NotificationOccurrenceModel) MarkCoveredRead(ctx context.Context, userID, roomID, threadRootEventID, targetEventID string) (int, error)

func (*NotificationOccurrenceModel) MarkRead

func (m *NotificationOccurrenceModel) MarkRead(ctx context.Context, userID, notificationID string) (*notificationv1.NotificationOccurrence, error)

func (*NotificationOccurrenceModel) PurgeUser

func (m *NotificationOccurrenceModel) PurgeUser(ctx context.Context, userID string) (int, error)

func (*NotificationOccurrenceModel) RemoveReaction

func (m *NotificationOccurrenceModel) RemoveReaction(ctx context.Context, recipientID, roomID, messageEventID, actorID, emoji string, removedAtSequence uint64) (int, error)

func (*NotificationOccurrenceModel) RemoveRoom

func (m *NotificationOccurrenceModel) RemoveRoom(ctx context.Context, roomID string) (int, error)

func (*NotificationOccurrenceModel) RemoveRoomForUser

func (m *NotificationOccurrenceModel) RemoveRoomForUser(ctx context.Context, userID, roomID string, removedThroughSequence uint64) (int, error)

func (*NotificationOccurrenceModel) RemoveTarget

func (m *NotificationOccurrenceModel) RemoveTarget(ctx context.Context, roomID, eventID string) (int, error)

func (*NotificationOccurrenceModel) Resync

func (*NotificationOccurrenceModel) Run

func (*NotificationOccurrenceModel) UnreadCount

func (m *NotificationOccurrenceModel) UnreadCount(ctx context.Context, userID string) (int, error)

func (*NotificationOccurrenceModel) VisibleOccurrences

VisibleOccurrences returns occurrences whose message or pending invitation targets recipientID can currently access, in input order. It waits once for the current authorization inputs and then checks the occurrences in chunks, each under one content-view barrier. The notification API deletes occurrences that it omits; alert delivery skips them.

func (*NotificationOccurrenceModel) WaitCurrent

func (m *NotificationOccurrenceModel) WaitCurrent(ctx context.Context) error

func (*NotificationOccurrenceModel) WaitReady

type NotificationPolicy

type NotificationPolicy struct {
	Scope NotificationPolicyScope
	// RoomID remains populated for the legacy server/room API adapter.
	RoomID    string
	Overrides *evtv1.NotificationDeliveryModes
	Effective *evtv1.NotificationDeliveryModes
}

NotificationPolicy is the complete explicit and effective policy at one server, room-group, or room scope.

type NotificationPolicyModel

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

NotificationPolicyModel owns authenticated Notifications 2.0 policy reads and writes. Legacy notification-level events are replay-decodable only and are deliberately not consulted here.

func (*NotificationPolicyModel) BatchGetNotificationPolicies

func (s *NotificationPolicyModel) BatchGetNotificationPolicies(ctx context.Context, actorID string, scopes []NotificationPolicyScope) ([]*NotificationPolicy, error)

BatchGetNotificationPolicies returns visible policies in de-duplicated, first-seen scope order. Missing and inaccessible resource scopes are omitted.

func (*NotificationPolicyModel) GetNotificationPolicy

func (s *NotificationPolicyModel) GetNotificationPolicy(ctx context.Context, actorID, roomID string) (*NotificationPolicy, error)

GetNotificationPolicy preserves the legacy server/room operation model.

func (*NotificationPolicyModel) GetScopedNotificationPolicy

func (s *NotificationPolicyModel) GetScopedNotificationPolicy(ctx context.Context, actorID string, scope NotificationPolicyScope) (*NotificationPolicy, error)

GetScopedNotificationPolicy returns explicit and effective modes for one server, room-group, or room scope.

func (*NotificationPolicyModel) UpdateNotificationPolicy

func (s *NotificationPolicyModel) UpdateNotificationPolicy(ctx context.Context, actorID, roomID string, patch *evtv1.NotificationDeliveryModes, mask *fieldmaskpb.FieldMask) (*NotificationPolicy, error)

UpdateNotificationPolicy preserves the legacy server/room operation model.

func (*NotificationPolicyModel) UpdateScopedNotificationPolicy

func (s *NotificationPolicyModel) UpdateScopedNotificationPolicy(ctx context.Context, actorID string, scope NotificationPolicyScope, patch *evtv1.NotificationDeliveryModes, mask *fieldmaskpb.FieldMask) (*NotificationPolicy, error)

UpdateScopedNotificationPolicy sparsely sets or clears overrides. The complete resulting scope is committed as one OCC-protected domain fact. Badge attention follows the current policy, so the actor's rooms whose Badge state changed receive an invalidation.

type NotificationPolicyScope

type NotificationPolicyScope struct {
	Kind NotificationPolicyScopeKind
	ID   string
}

NotificationPolicyScope identifies one server, room-group, or room policy.

type NotificationPolicyScopeKind

type NotificationPolicyScopeKind int

NotificationPolicyScopeKind identifies one supported notification-policy inheritance tier.

const (
	NotificationPolicyScopeServer NotificationPolicyScopeKind = iota
	NotificationPolicyScopeRoomGroup
	NotificationPolicyScopeRoom
)

type NotificationProjection

type NotificationProjection struct {
	events.MemoryProjection
	// contains filtered or unexported fields
}

NotificationProjection materializes the current, bounded notification list from the NOTIFICATIONS lifecycle log. Its expiry scheduler is an acceleration only: every read also applies the immutable expires_at boundary.

func NewNotificationProjection

func NewNotificationProjection(eventIDs *eventIDTable) *NotificationProjection

NewNotificationProjection returns an empty projection. eventIDs is the process-wide event ID table. With nil, the projection owns a private table.

func (*NotificationProjection) Apply

func (*NotificationProjection) Restore

func (p *NotificationProjection) Restore(data []byte) error

func (*NotificationProjection) Snapshot

func (p *NotificationProjection) Snapshot() ([]byte, error)

func (*NotificationProjection) SnapshotContractID

func (*NotificationProjection) SnapshotContractID() string

func (*NotificationProjection) Subjects

func (*NotificationProjection) Subjects() []string

type OAuthClientAuthorization

type OAuthClientAuthorization struct {
	UserID         string
	ClientID       string
	ClientName     string
	ClientOrigin   string
	RedirectOrigin string
	Source         evtv1.OAuthClientSource
}

OAuthClientAuthorization describes the validated client identity attached to one user-approved authorization request.

type OAuthClientModel

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

type OAuthClientProjection

type OAuthClientProjection struct {
	events.MemoryProjection
	// contains filtered or unexported fields
}

func NewOAuthClientProjection

func NewOAuthClientProjection() *OAuthClientProjection

func (*OAuthClientProjection) Apply

func (p *OAuthClientProjection) Apply(event *evtv1.Event, sequence uint64) error

func (*OAuthClientProjection) Subjects

func (p *OAuthClientProjection) Subjects() []string

type OAuthClientState

type OAuthClientState struct {
	ClientID             string
	ClientName           string
	ClientOrigin         string
	Source               evtv1.OAuthClientSource
	Policy               evtv1.OAuthClientPolicy
	FirstAuthorizationAt time.Time
	LastAuthorizationAt  time.Time
	RedirectOrigins      []string
	AuthorizedUserCount  uint32
	// contains filtered or unexported fields
}

OAuthClientState is the durable administrator-visible state of one public client that completed a successful user authorization.

type PasswordResetToken

type PasswordResetToken struct {
	UserID    string    `json:"user_id"`
	Email     string    `json:"email"`
	CreatedAt time.Time `json:"created_at"`
}

PasswordResetToken represents a token used to reset a user's password.

type PendingExternalIdentityFlow

type PendingExternalIdentityFlow struct {
	Kind          string `json:"kind"`
	ProviderID    string `json:"provider_id"`
	ProviderType  string `json:"provider_type"`
	ProviderLabel string `json:"provider_label"`
	Issuer        string `json:"issuer"`
	Subject       string `json:"subject"`
	SubjectHash   string `json:"subject_hash"`
	VerifiedEmail string `json:"verified_email,omitempty"`
	AvatarURL     string `json:"avatar_url,omitempty"`
	LoginHint     string `json:"login_hint,omitempty"`
	// ProviderUsername is the verified username without email/display-name fallback.
	ProviderUsername string    `json:"provider_username,omitempty"`
	DisplayNameHint  string    `json:"display_name_hint,omitempty"`
	RedirectPath     string    `json:"redirect_path,omitempty"`
	BoundUserID      string    `json:"bound_user_id,omitempty"`
	CreatedAt        time.Time `json:"created_at"`
	InvitationID     string    `json:"invitation_id,omitempty"`
	// Groups and GroupsKnown carry the provider groups claim to account
	// creation for group role sync. Flows from older versions have neither.
	Groups      []string `json:"groups,omitempty"`
	GroupsKnown bool     `json:"groups_known,omitempty"`
}

type PendingExternalIdentityLinkStart

type PendingExternalIdentityLinkStart struct {
	ProviderID   string    `json:"provider_id"`
	RedirectPath string    `json:"redirect_path,omitempty"`
	BoundUserID  string    `json:"bound_user_id"`
	CreatedAt    time.Time `json:"created_at"`
}

type PendingOAuthAuthorize

type PendingOAuthAuthorize struct {
	RedirectURI         string    `json:"redirect_uri"`
	CodeChallenge       string    `json:"code_challenge"`
	CodeChallengeMethod string    `json:"code_challenge_method"`
	State               string    `json:"state,omitempty"`
	ClientID            string    `json:"client_id,omitempty"`
	ClientName          string    `json:"client_name,omitempty"`
	ClientURI           string    `json:"client_uri,omitempty"`
	Resource            string    `json:"resource,omitempty"`
	Scopes              []string  `json:"scopes,omitempty"`
	CreatedAt           time.Time `json:"created_at"`
}

PendingOAuthAuthorize is validated authorization-request state stored in RUNTIME_STATE. The browser cookie carries only its opaque lookup token.

type Permission

type Permission string

Permission is an opaque, stable identifier in the permission model. Its punctuation does not define authorization relationships.

const (

	// PermServerManage allows updating server settings (name, description, logo).
	PermServerManage Permission = "server.manage"

	// PermServerManageNeighbors allows maintaining the public Neighbor directory.
	PermServerManageNeighbors Permission = "server.manage-neighbors"

	// PermRoomCreate allows creating new rooms.
	PermRoomCreate Permission = "room.create"

	// PermRoomJoin allows joining existing rooms. Distinct from
	// `room.list`: a user can be allowed to *see* a room in the
	// directory (request-access flow) without being allowed to join
	// it directly.
	PermRoomJoin Permission = "room.join"

	// PermRoomInvite allows members to invite human accounts to a channel room.
	PermRoomInvite Permission = "room.invite"

	// PermRoomList allows seeing a room in the directory and elsewhere
	// the server enumerates rooms (e.g. group "Join all" affordances).
	// Default-granted at server scope so the directory works out of the
	// box; deny it on a restricted room to keep it hidden from
	// non-members.
	PermRoomList Permission = "room.list"

	// PermRoomManage allows updating or deleting channel rooms.
	PermRoomManage Permission = "room.manage"

	// PermRoomManageNotice allows members to publish, correct, republish, and
	// clear channel notices. It is independent of general room management.
	PermRoomManageNotice Permission = "room.manage-notice"

	// PermRoomMemberRemove allows moderated removal from channel rooms,
	// with an optional suspension that prevents rejoining.
	PermRoomMemberRemove Permission = "room.remove-member"

	// PermCallStart allows starting a call. Joining also requires PermCallJoin.
	PermCallStart Permission = "call.start"
	// PermCallJoin allows joining an active call, including as a listener.
	PermCallJoin Permission = "call.join"
	// PermCallVoice allows publishing microphone audio.
	PermCallVoice Permission = "call.voice"
	// PermCallCamera allows publishing camera video.
	PermCallCamera Permission = "call.camera"
	// PermCallScreenShare allows screen/window/tab video and captured audio,
	// including native application sharing. It does not grant microphone use.
	PermCallScreenShare Permission = "call.screenshare"

	// PermMessageRead allows reading message content. Room or direct-message
	// membership remains a separate requirement.
	PermMessageRead Permission = "message.read"

	// PermMessageReadInteractions allows reading threads that the
	// account authored or where another account directly mentioned it. Room
	// membership remains a separate requirement. PermMessageRead explicitly
	// includes this permission.
	PermMessageReadInteractions Permission = "message.read-interactions"

	// PermMessagePost allows posting root messages and thread replies. It includes
	// PermMessagePostInThread and PermMessagePostInInteractions. Server-scope
	// decisions act as global defaults/overrides; room or group denies can narrow
	// that default where a room should be more restrictive.
	PermMessagePost Permission = "message.post"

	// PermMessagePostInThread allows posting messages in a thread (first or subsequent reply).
	PermMessagePostInThread Permission = "message.post-in-thread"

	// PermMessagePostInInteractions allows replies only in threads with an existing
	// interaction relationship. It does not grant read access or root posting.
	PermMessagePostInInteractions Permission = "message.post-in-interactions"

	// PermMessageAttach allows attaching files to new messages.
	PermMessageAttach Permission = "message.attach"

	// PermMessageManage allows moderating other users' messages in a room
	// (editing or deleting). Authors editing or deleting their own messages do
	// NOT need this permission; it is always allowed.
	PermMessageManage Permission = "message.manage"

	// PermMessagePin allows pinning and unpinning messages in channel rooms.
	// It does not grant room management or message read access.
	PermMessagePin Permission = "message.pin"

	// PermMessageReact allows adding/removing reactions to messages.
	PermMessageReact Permission = "message.react"

	// PermMessageEcho allows echoing thread replies to the room timeline.
	PermMessageEcho Permission = "message.echo"

	// PermRoleManage allows creating, editing, deleting, and reordering roles
	// and their permission grants. Single canonical permission for "manage the
	// server's role definitions" (formerly split between role.manage and
	// admin.manage-roles).
	PermRoleManage Permission = "role.manage"

	// PermRoleAssign allows assigning and revoking roles to/from users.
	// Single canonical permission for "manage user role assignments"
	// (formerly split between role.assign and admin.manage-users).
	PermRoleAssign Permission = "role.assign"

	// PermAdminUsersView allows viewing the users page in admin.
	PermAdminUsersView Permission = "admin.view-users"

	// PermAdminAuditView allows viewing the audit log in admin.
	PermAdminAuditView Permission = "admin.view-audit"

	// PermUserDeleteAny allows admins to delete any user's account.
	PermUserDeleteAny Permission = "user.delete-any"

	// PermUserDeleteSelf allows users to delete their own account.
	PermUserDeleteSelf Permission = "user.delete-self"

	// PermUserInvite allows creating, reading, and revoking one's own invitation codes.
	PermUserInvite Permission = "user.invite"

	// PermUserManageInvites allows listing, creating, copying, and revoking all codes.
	PermUserManageInvites Permission = "user.manage-invites"

	// PermUserManageAccounts allows account lifecycle and recovery operations
	// for other users, such as creating accounts, admin profile edits, password
	// resets, verified-email attachment, and login-cooldown resets.
	PermUserManageAccounts Permission = "user.manage-accounts"

	// PermUserManagePermissions allows editing direct per-user permission
	// overrides.
	PermUserManagePermissions Permission = "user.manage-permissions"

	// PermBotCreate allows bot creation for the caller's human owner (or the
	// caller itself when human). Newly created bots have no permission grants.
	PermBotCreate Permission = "bot.create"

	// PermBotManage allows management of every bot, including issuing keys
	// that act with the target bot's authority rather than the manager's.
	PermBotManage Permission = "bot.manage"
)

func DefaultAdminPermissions

func DefaultAdminPermissions() []Permission

DefaultAdminPermissions returns the server-scope permissions granted to admins by default. Admins inherit the implicit everyone role at runtime, so this list contains only admin-specific capabilities plus global room administration defaults.

func DefaultAnnouncementsAdminPermissions

func DefaultAnnouncementsAdminPermissions() []Permission

DefaultAnnouncementsAdminPermissions returns the room-scope grants that let admins publish announcements. Other ordinary content capabilities continue to come from the everyone baseline, and moderators receive no announcement- specific grant.

func DefaultAnnouncementsEveryoneDenials

func DefaultAnnouncementsEveryoneDenials() []Permission

DefaultAnnouncementsEveryoneDenials returns the room-scope denials for the built-in announcements room. This blocks root posts unless a named role or direct user has a room-local allow. Effective owners bypass the decision while privileged mode is active.

func DefaultEveryonePermissions

func DefaultEveryonePermissions() []Permission

DefaultEveryonePermissions returns server-scope permissions granted to every authenticated user (the implicit everyone role). These defaults make normal rooms usable out of the box; operators can deny the room/group permissions at room or group scope where they need local restrictions.

func DefaultModeratorPermissions

func DefaultModeratorPermissions() []Permission

DefaultModeratorPermissions returns the permissions granted to moderators by default. Moderators inherit the implicit everyone role at runtime; this list contains only moderator-specific server-scope capabilities.

type PermissionCategory

type PermissionCategory string

PermissionCategory groups related permissions for UI organization.

const (
	CategoryServer  PermissionCategory = "server"
	CategoryRoom    PermissionCategory = "room"
	CategoryCall    PermissionCategory = "call"
	CategoryMessage PermissionCategory = "message"
	CategoryRole    PermissionCategory = "role"
	CategoryAdmin   PermissionCategory = "admin"
	CategoryUser    PermissionCategory = "user"
	CategoryBot     PermissionCategory = "bot"
)

type PermissionExplanation

type PermissionExplanation struct {
	Permission Permission
	// IncludedBy identifies the broader permission whose allow produced State.
	// It is empty when Permission was resolved directly.
	IncludedBy    Permission
	State         DecisionKind
	DecidedAt     PermissionLevel
	DecidedByRole string
	Trace         []TraceEntry
}

PermissionExplanation captures the full resolution trace for a single permission check, including which level/role produced the winning decision.

State is the overall outcome (allow/deny/none). DecidedAt and DecidedByRole identify the trace entry that determined State; both are zero-valued if no role had an explicit grant or deny.

type PermissionLevel

type PermissionLevel string

PermissionLevel identifies the level at which a permission decision was reached.

const (
	LevelServer PermissionLevel = "server"
	LevelGroup  PermissionLevel = "group"
	LevelRoom   PermissionLevel = "room"
	LevelDM     PermissionLevel = "dm"
)

type PermissionMatrixCell

type PermissionMatrixCell struct {
	Permission string
	ScopeID    string
	Override   MatrixDecision
	Effective  MatrixDecision
	// AllowPermitted reports the bot owner's RBAC entitlement at this scope.
	// It does not include the acting human's session activation or edit authority.
	// Nil means that the cell does not use a bot owner ceiling.
	AllowPermitted *bool
}

type PermissionMatrixScope

type PermissionMatrixScope struct {
	ID            string
	Label         string
	Kind          MatrixScopeKind
	ParentGroupID string
}

type PermissionMetadata

type PermissionMetadata struct {
	Permission Permission
	Category   PermissionCategory
	Scopes     []PermissionScope // Scopes where this permission can be configured
	Includes   []Permission      // Permissions granted by an allow for this permission
}

PermissionMetadata defines one known permission. Includes lists other permissions that an allow for this permission also grants. Each relationship is direct and explicit. Denials do not follow inclusion relationships.

func AllPermissions

func AllPermissions() []PermissionMetadata

AllPermissions returns all defined permissions with their metadata.

func GetPermissionMetadata

func GetPermissionMetadata(perm Permission) (PermissionMetadata, bool)

GetPermissionMetadata returns metadata for a specific permission. Returns zero value if permission not found.

func PermissionsForCategory

func PermissionsForCategory(category PermissionCategory) []PermissionMetadata

PermissionsForCategory returns all permissions in a given category.

func PermissionsForScope

func PermissionsForScope(scope PermissionScope) []PermissionMetadata

PermissionsForScope returns all permissions that can be configured at a given scope.

type PermissionResolver

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

PermissionResolver handles permission resolution using a deliberately small model:

  1. Effective owners are entitled to every known RBAC permission. The override is effective only where privileged mode allows it; otherwise owners resolve through the same rules as everyone else.
  2. For everyone else, permissions outside the DM scope are denied in DMs.
  3. Each direct-user or explicitly assigned role contributes its nearest decision (room, then group, then server). Across those decisions, any deny wins; otherwise any allow grants the permission.
  4. The implicit everyone role supplies the nearest scope baseline. A named allow overrides an everyone deny only at the same or a nearer scope; named denies always win.
  5. An allow from an explicitly including permission satisfies the requested permission. Denies do not propagate through an inclusion.
  6. No decision is denied at the API boundary.

This makes everyone a scoped baseline rather than an absolute restriction: a room allow can grant access that everyone lacks in that room, while an unrelated server-wide role grant cannot bypass a nearer room baseline. A deny from another named role (for example suspended) still blocks the action. Scope specificity is evaluated independently for each subject, so a room decision replaces that subject's group/server decision for the room.

func NewPermissionResolver

func NewPermissionResolver(rooms *RoomModel, users *UserModel, rbac *RBACModel, view *ServerContentView) *PermissionResolver

NewPermissionResolver creates a new permission resolver.

func (*PermissionResolver) ExplainAllPermissions

func (r *PermissionResolver) ExplainAllPermissions(ctx context.Context, userID string, kind RoomKind, roomID string) ([]PermissionExplanation, error)

ExplainAllPermissions returns explanations for every permission applicable at the given scope:

  • userID only → server-scoped permissions
  • userID + KindDM → direct-message permissions with Server inheritance
  • userID + kind + roomID → room-scoped permissions

roomID without kind is invalid and returns an error.

func (*PermissionResolver) ExplainRoomPermission

func (r *PermissionResolver) ExplainRoomPermission(ctx context.Context, userID string, kind RoomKind, roomID string, perm Permission) (PermissionExplanation, error)

ExplainRoomPermission resolves a permission with a room context and returns the full decision trace.

func (*PermissionResolver) ExplainServerPermission

func (r *PermissionResolver) ExplainServerPermission(ctx context.Context, userID string, perm Permission) (PermissionExplanation, error)

ExplainServerPermission resolves a server-only permission (no room context) and returns the full decision trace.

func (*PermissionResolver) HasRoomPermission

func (r *PermissionResolver) HasRoomPermission(ctx context.Context, userID string, kind RoomKind, roomID string, perm Permission) (bool, error)

HasRoomPermission checks a permission with a room context. The room kind selects either the direct-message chain or the channel room and group chain.

func (*PermissionResolver) HasServerPermission

func (r *PermissionResolver) HasServerPermission(ctx context.Context, userID string, perm Permission) (bool, error)

HasServerPermission checks a server-only permission (no room context).

func (*PermissionResolver) HasSpacePermission

func (r *PermissionResolver) HasSpacePermission(ctx context.Context, userID string, kind RoomKind, perm Permission) (bool, error)

HasSpacePermission is a kind-aware singleton-scope check. KindDM resolves the direct-message scope before the inherited server scope.

func (*PermissionResolver) Resolve

func (r *PermissionResolver) Resolve(ctx context.Context, userID string, kind RoomKind, roomID string, perm Permission) (DecisionKind, error)

Resolve is the single resolver entry point. Returns the effective decision (allow / deny / none) for the user-permission pair. Both the bool authorizer (Has*Permission) and the inspector go through this — there is no parallel implementation.

Order of operations:

  1. Effective-owner override, when privileged mode allows it.
  2. Permissions that do not apply at the direct-message scope are denied for direct-message checks.
  3. Resolve the nearest decision for the user and each named role. Any deny beats any allow across those subjects.
  4. Apply the implicit everyone baseline. A named allow beats an everyone deny only when it is at least as specific; named denies always win.
  5. Apply explicit permission inclusion to effective allows.

func (*PermissionResolver) ResolveGroup

func (r *PermissionResolver) ResolveGroup(ctx context.Context, userID string, kind RoomKind, groupID string, perm Permission) (DecisionKind, error)

ResolveGroup is like Resolve but for group-scope checks (no room context). Used by CanCreateRoom and other group-scoped capability gates.

type PermissionScope

type PermissionScope string

PermissionScope marks where a permission can be configured. Most permissions apply at the server level (default). Channel-room permissions (e.g. message.post) additionally include ScopeGroup (to be configured per room group) and ScopeRoom (to be overridden per individual room).

const (
	ScopeServer PermissionScope = "server"
	ScopeGroup  PermissionScope = "group"
	ScopeRoom   PermissionScope = "room"
	ScopeDM     PermissionScope = "dm"
)

type PermissionScopePage

type PermissionScopePage struct {
	TotalCount int
	HasMore    bool
}

PermissionScopePage describes the matching visible scope collection.

type PermissionScopeQuery

type PermissionScopeQuery struct {
	Scope  *PermissionTargetScope
	Limit  int
	Offset int
	// All returns every matching scope for a complete matrix. Decision lists use pages.
	All bool
}

PermissionScopeQuery selects matching scopes before permission evaluation. All selects a complete matrix; otherwise Limit and Offset count scopes, not cells. Scope is an optional exact filter in both modes.

type PermissionState

type PermissionState string
const (
	PermissionStateAllow PermissionState = "allow"
	PermissionStateDeny  PermissionState = "deny"
	PermissionStateNone  PermissionState = "none"
)

type PermissionTargetScope

type PermissionTargetScope struct {
	Kind MatrixScopeKind
	ID   string
}

type PinnedMessageItem

type PinnedMessageItem struct {
	Pin   PinnedMessageState
	Event *evtv1.Event
}

PinnedMessageItem pairs current pin metadata with the canonical message fact.

type PinnedMessageListInput

type PinnedMessageListInput struct {
	ActorID string
	RoomID  string
	Limit   int
	Offset  int
}

PinnedMessageListInput describes one member-visible pin page.

type PinnedMessageListResult

type PinnedMessageListResult struct {
	Items            []PinnedMessageItem
	TotalCount       int
	HasMore          bool
	LatestPinEventID string
}

PinnedMessageListResult is a stable newest-first page of active room pins.

type PinnedMessageMutationInput

type PinnedMessageMutationInput struct {
	ActorID        string
	RoomID         string
	MessageEventID string
}

PinnedMessageMutationInput identifies one channel message pin association.

type PinnedMessageState

type PinnedMessageState struct {
	PinEventID     string
	PinSequence    uint64
	RoomID         string
	MessageEventID string
}

PinnedMessageState is the current derived pin association for one canonical message. Message content remains owned by the timeline projection's normal message indexes and is never copied into this state.

type PostMessageOption

type PostMessageOption func(*postMessageOptions)

PostMessageOption customizes side effects owned by the message-post command.

func WithThreadCreation

func WithThreadCreation() PostMessageOption

WithThreadCreation establishes a durable thread for the new root message and follows it for the author in the same atomic append as the message.

func WithVideoProcessingAssets

func WithVideoProcessingAssets(assetIDs ...string) PostMessageOption

WithVideoProcessingAssets schedules video processing for the listed message attachments after their AssetCreatedEvent records have been appended.

type PresenceHub

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

PresenceHub combines one liveness watcher in MEMORY_CACHE and one private choice watcher in RUNTIME_STATE. Each process has one hub, independent of the number of connected users and rooms.

func NewPresenceHub

func NewPresenceHub(memoryCacheKV, runtimeStateKV jetstream.KeyValue, logger *log.Logger) *PresenceHub

NewPresenceHub creates a PresenceHub. Call Run() to start it.

func (*PresenceHub) GetUserPresences

func (h *PresenceHub) GetUserPresences(ctx context.Context, userIDs []string) (map[string]string, error)

GetUserPresences returns the current status for each requested user from the process-wide watcher snapshot. Missing and invalid users are reported as offline. The returned map is detached from the hub's internal state.

This is intended for bulk read hydration. Mutation responses that require read-your-writes should continue to read the backing KV directly.

func (*PresenceHub) LivePresenceCount

func (h *PresenceHub) LivePresenceCount(ctx context.Context) (int, error)

LivePresenceCount returns the number of users with a current live presence record in MEMORY_CACHE. Offline users are represented by absence and are not included. The call waits for the initial watcher snapshot so callers see a process-local count derived from the same state used for live presence fanout.

func (*PresenceHub) Resync

func (h *PresenceHub) Resync(ctx context.Context) error

Resync replaces the watcher and waits for its latest-value snapshot.

func (*PresenceHub) Run

func (h *PresenceHub) Run(ctx context.Context) error

Run starts the KV watcher and fans out updates to subscribers. Blocks until ctx is cancelled. Should be started in an errgroup.

func (*PresenceHub) Subscribe

func (h *PresenceHub) Subscribe(ctx context.Context) (*PresenceSubscription, error)

Subscribe registers a new subscriber for future presence transitions. The hub owns the process-wide current-state snapshot and already suppresses unchanged status refreshes, so subscribers do not need private snapshot copies for deduplication.

The caller must call Unsubscribe() when done.

func (*PresenceHub) Unsubscribe

func (h *PresenceHub) Unsubscribe(sub *PresenceSubscription)

Unsubscribe removes a subscriber and closes its channel.

type PresenceModel

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

PresenceModel owns live presence state and the per-process presence hub.

func NewPresenceModel

func NewPresenceModel(memoryCacheKV, runtimeStateKV *jetstreamutil.KeyValue, logger *log.Logger) *PresenceModel

NewPresenceModel uses the existing shared buckets: liveness in MEMORY_CACHE and one current private choice per user in RUNTIME_STATE. Run starts their watchers; no presence projection or event-log writer is installed.

func (*PresenceModel) GetUserPresence

func (s *PresenceModel) GetUserPresence(ctx context.Context, userID string) (string, error)

GetUserPresence retrieves a user's current presence status. Returns "OFFLINE" if the user has no presence entry (never connected or TTL expired).

func (*PresenceModel) GetUserPresences

func (s *PresenceModel) GetUserPresences(ctx context.Context, userIDs []string) (map[string]string, error)

GetUserPresences returns watcher-backed presence for bulk read hydration.

func (*PresenceModel) LivePresenceCount

func (s *PresenceModel) LivePresenceCount(ctx context.Context) (int, error)

LivePresenceCount returns the number of users with any current live presence record, including Online, Away, and Do Not Disturb.

func (*PresenceModel) Resync

func (s *PresenceModel) Resync(ctx context.Context) error

Resync replaces the presence watcher and waits for a current snapshot.

func (*PresenceModel) Run

func (s *PresenceModel) Run(ctx context.Context) error

func (*PresenceModel) SetPresence

func (s *PresenceModel) SetPresence(ctx context.Context, userID string, status string) error

SetPresence writes/refreshes a user's live presence in MEMORY_CACHE. Authorization: Caller must verify the user is authenticated before calling.

func (*PresenceModel) SetPresenceWithOptions

func (s *PresenceModel) SetPresenceWithOptions(ctx context.Context, userID string, status string, manuallySet bool) error

SetPresenceWithOptions writes/refreshes a user's live presence in MEMORY_CACHE. manuallySet marks explicit user-selected Away/DND so automatic reports from other clients do not overwrite the user's chosen availability.

func (*PresenceModel) Subscribe

func (s *PresenceModel) Subscribe(ctx context.Context) (*PresenceSubscription, error)

func (*PresenceModel) Unsubscribe

func (s *PresenceModel) Unsubscribe(sub *PresenceSubscription)

type PresenceSubscription

type PresenceSubscription struct {
	// C receives presence updates. Closed when Unsubscribe is called.
	C <-chan PresenceUpdate

	// Done closes as soon as the subscription ends, even if C still contains
	// buffered updates. Callers should stop immediately and reconnect when
	// Lagged reports true.
	Done <-chan struct{}
	// contains filtered or unexported fields
}

PresenceSubscription represents a subscriber to the PresenceHub.

func (*PresenceSubscription) Lagged

func (s *PresenceSubscription) Lagged() bool

Lagged reports whether the hub closed this subscription after its queue overflowed. Callers must reconnect and refetch latest-value presence state.

type PresenceUpdate

type PresenceUpdate struct {
	UserID string
	Status string // PresenceStatusOnline, PresenceStatusAway, etc., or PresenceStatusOffline for delete
}

PresenceUpdate represents a deduplicated presence change from the KV watcher.

type PrivilegedModeAction

type PrivilegedModeAction int

PrivilegedModeAction distinguishes an explicit role selection from the legacy command to activate all eligible roles.

const (
	DeactivatePrivilegedMode PrivilegedModeAction = iota
	ActivateAllPrivilegedRoles
	ActivateSelectedPrivilegedRoles
)

type PrivilegedModeActivation

type PrivilegedModeActivation struct {
	Roles     []string
	ExpiresAt time.Time
}

PrivilegedModeActivation is the selection and deadline from one session revision.

type ProjectionAdminMetric

type ProjectionAdminMetric struct {
	Name  string
	Value int64
	Bytes int64
}

type ProjectionAdminState

type ProjectionAdminState struct {
	Key               string
	Name              string
	Subjects          []string
	Started           bool
	StartupComplete   bool
	StartupDuration   float64
	StartupMessages   uint64
	LastAppliedSeq    uint64
	MatchingStreamSeq uint64
	StreamLastSeq     uint64
	Lag               uint64
	Failed            bool
	FailedSeq         uint64
	Failure           string
	// Stalled, PendingFor, CurrentOperation, CurrentOperationDuration, and
	// LastCommitAt copy the projector's freshness status.
	Stalled                  bool
	PendingFor               time.Duration
	CurrentOperation         string
	CurrentOperationDuration time.Duration
	LastCommitAt             time.Time
	LastCommitDuration       time.Duration
	// EstimateAvailable is false when the memory estimate did not finish in
	// time, for example because a blocked apply holds the projection lock.
	// EntryCount, EstimatedBytes, AverageEntryBytes, and Metrics are then zero.
	EstimateAvailable bool
	EntryCount        int64
	EstimatedBytes    int64
	AverageEntryBytes int64
	Metrics           []ProjectionAdminMetric
}

ProjectionAdminState is the operator-facing runtime state for one event-sourced projection.

type ProviderGroups

type ProviderGroups struct {
	Groups []string
	Known  bool
}

ProviderGroups is the groups claim of one verified provider sign-in. Known is false when the provider sent no readable groups claim; group role sync then changes nothing. A known claim can be empty.

type ProviderRoleSource

type ProviderRoleSource struct {
	ProviderID string
	Issuer     string
	Subject    string
}

ProviderRoleSource identifies the auth provider of a group role change. Issuer is the identity namespace of the provider's links (the verified OIDC issuer URL) and owns the assignments. ProviderID is the configured provider ID, recorded for the audit log only, because it can change. Subject is the provider subject of the verified identity; group role sync uses it to complete legacy links that have no issuer.

type PublicServerAssetLocation

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

PublicServerAssetLocation binds a successful public classification to one exact backend object. Its fields stay private so callers cannot manufacture a location that bypasses ResolvePublicServerAsset.

type RBACModel

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

RBACModel owns RBAC projection reads and readiness.

func (*RBACModel) GetUserRoles

func (m *RBACModel) GetUserRoles(ctx context.Context, userID string) ([]string, error)

GetUserRoles returns the explicit role assignments for a user. The implicit `everyone` role is omitted — callers that need it can prepend it themselves based on the relevant scope (e.g. space membership).

type RBACProjection

type RBACProjection struct {
	events.MemoryProjection
	// contains filtered or unexported fields
}

RBACProjection derives deployment-wide roles, role assignments, and explicit permission decisions from durable evt.rbac.> events.

func NewRBACProjection

func NewRBACProjection() *RBACProjection

func (*RBACProjection) Apply

func (p *RBACProjection) Apply(event *evtv1.Event, seq uint64) error

func (*RBACProjection) AssignmentOwner

func (p *RBACProjection) AssignmentOwner(userID, roleName string) (ownerIssuer string, assigned bool)

AssignmentOwner returns the identity issuer of the auth provider that owns the user's assignment of roleName. It is empty for an admin or configuration assignment. assigned is false when the user does not have the role.

func (*RBACProjection) Assignments

func (p *RBACProjection) Assignments() []rbacSeedAssignment

func (*RBACProjection) CompleteStartupReplay

func (p *RBACProjection) CompleteStartupReplay()

func (*RBACProjection) Decisions

func (p *RBACProjection) Decisions() []rbacSeedDecision

func (*RBACProjection) DecisionsFor

func (p *RBACProjection) DecisionsFor(scope PermissionScope, scopeID, subject string) (grants []Permission, denials []Permission)

func (*RBACProjection) DecisionsForRoleServer

func (p *RBACProjection) DecisionsForRoleServer(roleName string) (grants []Permission, denials []Permission)

func (*RBACProjection) GetDecision

func (p *RBACProjection) GetDecision(scope PermissionScope, scopeID, subject string, perm Permission) DecisionKind

func (*RBACProjection) GetRole

func (p *RBACProjection) GetRole(name string) (*readmodel.Role, bool)

func (*RBACProjection) GetRoleUsers

func (p *RBACProjection) GetRoleUsers(roleName string) []string

func (*RBACProjection) GetUserRoles

func (p *RBACProjection) GetUserRoles(userID string) []string

func (*RBACProjection) HasRole

func (p *RBACProjection) HasRole(userID, roleName string) bool

func (*RBACProjection) ListRoles

func (p *RBACProjection) ListRoles() []*readmodel.Role

func (*RBACProjection) NextAvailablePosition

func (p *RBACProjection) NextAvailablePosition() int32

func (*RBACProjection) ProtectedRoles

func (p *RBACProjection) ProtectedRoles(userID string) []string

ProtectedRoles returns the user's assigned protected roles in name order.

func (*RBACProjection) ProviderAssignments

func (p *RBACProjection) ProviderAssignments(userID, issuer string) []string

ProviderAssignments returns the sorted role names of the user's assignments that the auth provider with identity issuer owns. An empty issuer matches nothing, because admin assignments have no owner.

func (*RBACProjection) Restore

func (p *RBACProjection) Restore(data []byte) error

func (*RBACProjection) RoleCounts

func (p *RBACProjection) RoleCounts(activeHumanIDs []string) map[string]RoleCounts

RoleCounts returns detached totals in one pass over active humans and permission decisions. The caller supplies active human IDs without profiles.

func (*RBACProjection) RoleExists

func (p *RBACProjection) RoleExists(name string) bool

func (*RBACProjection) RolePermissionDecisions

func (p *RBACProjection) RolePermissionDecisions(roleName string) []ScopedRolePermissionDecision

func (*RBACProjection) RoleRequiresShieldMode

func (p *RBACProjection) RoleRequiresShieldMode(name string) bool

RoleRequiresShieldMode reports whether the role's grants require selection.

func (*RBACProjection) Snapshot

func (p *RBACProjection) Snapshot() ([]byte, error)

func (*RBACProjection) SnapshotContractID

func (*RBACProjection) SnapshotContractID() string

func (*RBACProjection) Subjects

func (p *RBACProjection) Subjects() []string

type ReactionModel

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

ReactionModel owns user-facing reaction authorization, event-sourced writes, OCC retries, and projection readiness.

func (*ReactionModel) AddReaction

func (s *ReactionModel) AddReaction(ctx context.Context, input ReactionMutationInput) (bool, error)

AddReaction adds actorID's reaction to a message. Authorization: actor must be a room member and have message.react. Reactions also require permission to read the target message. The emoji must be a case-sensitive name from the bundled catalogue, including a supported skin-tone suffix if present.

func (*ReactionModel) RemoveReaction

func (s *ReactionModel) RemoveReaction(ctx context.Context, input ReactionMutationInput) (bool, error)

RemoveReaction removes actorID's reaction from a message. Authorization: actor must be a room member and have message.react. Reactions also require permission to read the target message.

type ReactionMutationInput

type ReactionMutationInput struct {
	ActorID        string
	RoomID         string
	MessageEventID string
	Emoji          string
}

ReactionMutationInput describes one user-facing reaction add/remove operation.

type ReactionMutationSnapshot

type ReactionMutationSnapshot struct {
	Exists            bool
	UserReactionCount int
	Seq               uint64
	SourceEventID     string
}

type ReactionProjection

type ReactionProjection struct {
	events.MemoryProjection
	// contains filtered or unexported fields
}

ReactionProjection derives current reaction state from durable room aggregate events. It consumes the full room namespace so mutation snapshots can carry the per-room OCC position even when the latest room fact is not a reaction. v1 intentionally keeps the whole current reaction set in RAM; bounded/windowed variants can build on this once real access patterns are known.

func NewReactionProjection

func NewReactionProjection() *ReactionProjection

NewReactionProjection returns an empty projection with a private message ID table.

func (*ReactionProjection) Apply

func (p *ReactionProjection) Apply(event *evtv1.Event, seq uint64) error

func (*ReactionProjection) CompleteStartupReplay

func (p *ReactionProjection) CompleteStartupReplay()

func (*ReactionProjection) HasReaction

func (p *ReactionProjection) HasReaction(messageEventID, emoji, userID string) bool

func (*ReactionProjection) ReactionMutationSnapshot

func (p *ReactionProjection) ReactionMutationSnapshot(roomID, messageEventID, emoji, userID string) ReactionMutationSnapshot

func (*ReactionProjection) Reactions

func (p *ReactionProjection) Reactions(messageEventID string) []ReactionSummary

func (*ReactionProjection) ReactionsBatch

func (p *ReactionProjection) ReactionsBatch(messageEventIDs []string) map[string][]ReactionSummary

func (*ReactionProjection) Restore

func (p *ReactionProjection) Restore(data []byte) error

func (*ReactionProjection) RoomSequence

func (p *ReactionProjection) RoomSequence(roomID string) uint64

RoomSequence returns the highest applied EVT sequence among the events that this projection attributes to the room. Every reaction in the room that this projection has applied has a sequence at or below it.

func (*ReactionProjection) Snapshot

func (p *ReactionProjection) Snapshot() ([]byte, error)

func (*ReactionProjection) SnapshotContractID

func (*ReactionProjection) SnapshotContractID() string

func (*ReactionProjection) Stats

func (p *ReactionProjection) Stats() (messages int, activeReactions int)

Stats returns aggregate counts useful for import/rollout diagnostics.

func (*ReactionProjection) Subjects

func (p *ReactionProjection) Subjects() []string

type ReactionSummary

type ReactionSummary struct {
	Emoji   string
	UserIDs []string
}

ReactionSummary represents aggregated reactions for a message.

type ReadMarker

type ReadMarker struct {
	EventID    string
	LastReadAt time.Time
}

ReadMarker is a stored position, independent of notification attention. A nil result means that no non-empty marker has been stored.

type ReadStateIndex

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

ReadStateIndex maintains the process-local mirror of persisted room and thread read markers. RUNTIME_STATE remains authoritative; one filtered KV watcher per Chatto process supplies both the initial latest-value snapshot and every later update from local or remote replicas.

func NewReadStateIndex

func NewReadStateIndex(kv jetstream.KeyValue, logger *log.Logger) *ReadStateIndex

NewReadStateIndex creates an empty index. Run must be started before reads.

func (*ReadStateIndex) Resync

func (i *ReadStateIndex) Resync(ctx context.Context) error

Resync replaces the watcher and waits for its latest-value snapshot.

func (*ReadStateIndex) Run

func (i *ReadStateIndex) Run(ctx context.Context) error

Run watches every read marker, applies the initial latest-value snapshot, and then keeps the index current until ctx is cancelled.

func (*ReadStateIndex) WaitReady

func (i *ReadStateIndex) WaitReady(ctx context.Context) error

WaitReady blocks until the watcher's initial latest-value snapshot has been applied or ctx is cancelled.

type ReadStateModel

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

ReadStateModel owns user-facing read marker reads and mutations. Lower-level marker helpers stay available for trusted/internal callers, while this model keeps public API authorization and anchor semantics in one place.

func (*ReadStateModel) AdvanceLastReadEventID

func (s *ReadStateModel) AdvanceLastReadEventID(ctx context.Context, kind RoomKind, userID, roomID, eventID string) (*LastReadEventIDAdvance, error)

AdvanceLastReadEventID stores eventID as the user's room read marker only if it is newer than the marker already in RUNTIME_STATE. The compare-and-write loop uses KV revisions so concurrent replicas cannot move the marker backwards after seeing stale state.

func (*ReadStateModel) GetEventTimestamp

func (s *ReadStateModel) GetEventTimestamp(ctx context.Context, kind RoomKind, roomID, eventID string) (time.Time, error)

GetEventTimestamp returns the proto-level `created_at` timestamp for a root message event ID in a room. Returns zero time if the event ID is empty or the message doesn't exist (e.g. deleted or never published).

Reads from the proto payload rather than JetStream's stored time so the value stays correct after #354 phase 4d (which re-publishes with fresh JetStream timestamps but preserves the proto payload).

func (*ReadStateModel) GetLastReadEventID

func (s *ReadStateModel) GetLastReadEventID(ctx context.Context, kind RoomKind, userID, roomID string) (string, error)

GetLastReadEventID returns the user's last-read root-message event ID for a room. If no marker exists yet, it lazy-initializes the marker to the room's current last root event ("caught up at deploy time"); if the room has no messages, it returns "".

func (*ReadStateModel) GetRoomLastEvent

func (s *ReadStateModel) GetRoomLastEvent(ctx context.Context, kind RoomKind, roomID string) (eventID string, ts time.Time, exists bool, err error)

GetRoomLastEvent returns the last root message's event ID and proto-level `created_at` timestamp for a room. Excludes thread replies — only root messages affect room-level unread tracking. exists is false if the room has no ordinary root messages. Historical imports do not advance this marker.

Uses the proto's `created_at` rather than JetStream's stored time so the value stays correct after #354 phase 4d (which re-publishes messages with fresh JetStream timestamps but leaves the proto payloads intact).

func (*ReadStateModel) GetRoomLastReadableEvent

func (s *ReadStateModel) GetRoomLastReadableEvent(ctx context.Context, kind RoomKind, userID, roomID string) (eventID string, ts time.Time, exists bool, err error)

GetRoomLastReadableEvent returns the most recent room-visible message that userID can currently read. Channel echoes use the interaction relationship of their canonical thread root.

func (*ReadStateModel) GetRoomReadMarker

func (s *ReadStateModel) GetRoomReadMarker(ctx context.Context, actorID, roomID string) (*ReadMarker, error)

GetRoomReadMarker reads only; it never performs lazy marker initialization.

func (*ReadStateModel) GetThreadLastOpened

func (s *ReadStateModel) GetThreadLastOpened(ctx context.Context, kind RoomKind, userID, roomID, threadRootEventID string) (time.Time, error)

GetThreadLastOpened retrieves the timestamp of the latest thread message the user has seen. Returns zero time if the thread has never been opened.

New RUNTIME_STATE markers store the seen message event ID. Values migrated from SERVER_RUNTIME may still be the legacy 8-byte UnixNano timestamp; those are decoded here so existing read state survives the rollout.

func (*ReadStateModel) GetThreadReadMarker

func (s *ReadStateModel) GetThreadReadMarker(ctx context.Context, actorID, roomID, rootID string) (*ReadMarker, error)

GetThreadReadMarker reads only after checking access to the thread root.

func (*ReadStateModel) HasUnread

func (s *ReadStateModel) HasUnread(ctx context.Context, kind RoomKind, userID, roomID string) (bool, error)

HasUnread reports whether a room has active Badge attention for a user. Thread Badge attention rolls up into the parent room. The result is independent of the user's last-read cursor and false when the user cannot see the room.

func (*ReadStateModel) MarkRoomAsRead

func (s *ReadStateModel) MarkRoomAsRead(ctx context.Context, actorID, roomID, upToEventID string) (*MarkRoomAsReadResult, error)

func (*ReadStateModel) MarkThreadAsRead

func (s *ReadStateModel) MarkThreadAsRead(ctx context.Context, actorID, roomID, threadRootEventID, upToEventID string) (*MarkThreadAsReadResult, error)

func (*ReadStateModel) NotifyRoomMarkedAsRead

func (s *ReadStateModel) NotifyRoomMarkedAsRead(ctx context.Context, userID string, kind RoomKind, roomID string)

NotifyRoomMarkedAsRead publishes a live event to notify the user that they marked a room as read. This enables real-time updates to space unread indicators. This is best-effort - failures are logged but don't affect the mark-as-read operation.

func (*ReadStateModel) PeekLastReadEventID

func (s *ReadStateModel) PeekLastReadEventID(ctx context.Context, userID, roomID string) (eventID string, exists bool, err error)

PeekLastReadEventID returns the stored read marker for a room without lazy initialization. exists is false when no marker has been written yet.

func (*ReadStateModel) Resync

func (s *ReadStateModel) Resync(ctx context.Context) error

Resync replaces the read-state watcher and waits for a current snapshot.

func (*ReadStateModel) Run

func (s *ReadStateModel) Run(ctx context.Context) error

Run maintains the process-wide read marker index until ctx is cancelled.

func (*ReadStateModel) SetLastReadEventID

func (s *ReadStateModel) SetLastReadEventID(ctx context.Context, kind RoomKind, userID, roomID, eventID string) error

SetLastReadEventID stores the user's last-read root-message event ID.

Callers MUST pass either a root message event ID or the empty string. Thread reply event IDs are tracked separately by the thread read marker; using one here would make room-level unread comparisons point at the wrong timeline.

func (*ReadStateModel) SetThreadLastOpened

func (s *ReadStateModel) SetThreadLastOpened(ctx context.Context, kind RoomKind, userID, roomID, threadRootEventID string) (time.Time, error)

SetThreadLastOpened records the latest current reply in the thread as read. Returns the previous marker time (zero if never opened before).

func (*ReadStateModel) SetThreadLastOpenedAt

func (s *ReadStateModel) SetThreadLastOpenedAt(ctx context.Context, kind RoomKind, userID, roomID, threadRootEventID string, ts time.Time) (time.Time, error)

SetThreadLastOpenedAt is retained for timestamp-based callers/tests. It stores a legacy timestamp marker in RUNTIME_STATE and should not be used for new code when a concrete event ID is available.

func (*ReadStateModel) SetThreadLastReadEventID

func (s *ReadStateModel) SetThreadLastReadEventID(ctx context.Context, kind RoomKind, userID, roomID, threadRootEventID, eventID string) (time.Time, error)

SetThreadLastReadEventID stores eventID as the latest thread message the user has seen, but only if it is newer than the existing marker (advance-only). Returns the previous marker time (zero if never opened before).

func (*ReadStateModel) WaitReady

func (s *ReadStateModel) WaitReady(ctx context.Context) error

WaitReady blocks until the read marker index has applied its initial RUNTIME_STATE snapshot.

type RealtimeReplayPlan

type RealtimeReplayPlan struct {
	// Reset requires the transport to use the requested current-state fallback.
	Reset bool
	// BoundaryCursor is safe to persist after all Events have been applied.
	BoundaryCursor string
	// BoundarySequence is the EVT cutoff used to suppress buffered duplicates.
	BoundarySequence uint64
	// Events contains authorized deliverable durable events in global EVT order.
	Events []EventEnvelope
}

RealtimeReplayPlan is a bounded, authorized durable replay ending at one stable EVT boundary. The caller starts live delivery before requesting the plan, buffers that stream while replay is sent, and discards buffered EVT events through BoundarySequence before continuing live.

type RegistrationCode

type RegistrationCode struct {
	Email        string    `json:"email"`
	CreatedAt    time.Time `json:"created_at"`
	InvitationID string    `json:"invitation_id,omitempty"`
}

RegistrationCode represents a pending email-first registration OTP.

type RegistrationToken

type RegistrationToken struct {
	Email        string    `json:"email"`
	CreatedAt    time.Time `json:"created_at"`
	InvitationID string    `json:"invitation_id,omitempty"`
}

RegistrationToken represents a token used to complete email-first registration after the email code has already been verified. Unlike password reset tokens, this has no UserID — the user doesn't exist yet.

type RenewableSession

type RenewableSession struct {
	UserID            string                      `json:"user_id"`
	ClientID          string                      `json:"client_id,omitempty"`
	Resource          string                      `json:"resource,omitempty"`
	Scopes            []string                    `json:"scopes,omitempty"`
	Kind              AuthTokenKind               `json:"kind"`
	Source            string                      `json:"source,omitempty"`
	Request           *evtv1.AuditRequestMetadata `json:"request,omitempty"`
	CreatedAt         time.Time                   `json:"created_at"`
	ExpiresAt         time.Time                   `json:"expires_at"`
	AuthGeneration    uint64                      `json:"auth_generation"`
	CurrentGeneration uint64                      `json:"current_generation"`
	// LastRefreshRequestVerifier is a purpose-separated HMAC of the show-once
	// recovery nonce. The raw nonce must not enter runtime state or backups.
	LastRefreshRequestVerifier string    `json:"last_refresh_request_verifier,omitempty"`
	LastRotatedAt              time.Time `json:"last_rotated_at,omitzero"`
	// UsedGeneration is the highest generation that a client has shown it
	// holds: its access token passed validation, or its refresh token rotated
	// successfully. No client used a generation newer than a stale refresh
	// generation at or above this value, so that client lost the rotation
	// responses, and refresh rotates again instead of revoking. Nil means that the record predates
	// this tracking, or that a replica without it rewrote the record; refresh
	// then treats every stale generation outside exact recovery as reuse.
	UsedGeneration  *uint64   `json:"used_generation,omitempty"`
	FreshAuthAt     time.Time `json:"fresh_auth_at,omitzero"`
	FreshAuthMethod string    `json:"fresh_auth_method,omitempty"`
	FreshAuthSource string    `json:"fresh_auth_source,omitempty"`
	// A separate storage field keeps older replicas from treating a partial
	// selection as permission to activate every role.
	PrivilegedModeExpiresAt time.Time `json:"selected_roles_expire_at,omitzero"`
	PrivilegedRoles         []string  `json:"privileged_roles,omitempty"`
}

RenewableSession is the latest-value authority stored in RUNTIME_STATE for one human bearer login. CurrentGeneration and the KV revision jointly fence refresh-token rotation across replicas.

type RoleCatalog

type RoleCatalog struct {
	Roles                []RoleWithPermissions
	ViewerCanManageRoles bool
	ViewerCanAssignRoles bool
}

type RoleCounts

type RoleCounts struct {
	MemberCount           uint64
	PermissionGrantCount  uint64
	PermissionDenialCount uint64
}

RoleCounts describes current human membership and explicit permission rows. Grants and denials count each scope separately; inherited and virtual permission outcomes do not add rows.

type RoleDetails

type RoleDetails struct {
	Role                 *RoleWithPermissions
	ViewerCanManageRoles bool
	ViewerCanAssignRoles bool
}

type RoleMemberPage

type RoleMemberPage struct {
	UserIDs    []string
	TotalCount int
	HasMore    bool
}

RoleMemberPage selects assignments before any user or profile hydration. IDs are sorted, but separate requests do not share a fixed snapshot.

type RolePermissionMatrix

type RolePermissionMatrix struct {
	Page                  PermissionScopePage
	RoleName              string
	ApplicablePermissions []string
	Scopes                []PermissionMatrixScope
	Cells                 []PermissionMatrixCell
}

type RoleWithPermissions

type RoleWithPermissions struct {
	Name               string
	DisplayName        string
	Description        string
	Permissions        []Permission // Permissions granted (allowed) by this role
	PermissionDenials  []Permission // Permissions denied by this role
	IsSystem           bool
	Position           int32 // Display/order position. Everyone=0, Owner=1000.
	Pingable           bool
	RequiresShieldMode bool
	// Counts is present on authorized administrative catalog reads.
	Counts *RoleCounts
}

RoleWithPermissions represents a role with its grants and denials, used by the public API and admin tooling.

type RoomArchiveFilter

type RoomArchiveFilter int

RoomArchiveFilter selects room archive state without changing visibility.

const (
	// RoomArchiveActive preserves the default active-room navigation snapshot.
	RoomArchiveActive RoomArchiveFilter = iota
	// RoomArchiveArchived selects only archived rooms.
	RoomArchiveArchived
	// RoomArchiveAll selects both active and archived rooms.
	RoomArchiveAll
)

type RoomAssetInput

type RoomAssetInput struct {
	ActorID string
	RoomID  string
	AssetID string
}

RoomAssetInput is the authorized room-scoped asset read request.

type RoomAttachmentItem

type RoomAttachmentItem struct {
	Attachment        *evtv1.Attachment
	Description       string
	MessageEventID    string
	ThreadRootEventID string
	CreatedAt         *timestamppb.Timestamp
}

RoomAttachmentItem is one current attachment as it appears in a room, including the message anchor needed by UI surfaces that jump back to where the file was posted.

type RoomAttachmentsResult

type RoomAttachmentsResult struct {
	Items      []*RoomAttachmentItem
	TotalCount int
	HasMore    bool
}

RoomAttachmentsResult is the return type for room-scoped attachment lists.

type RoomBan

type RoomBan struct {
	EventID     string
	RoomID      string
	UserID      string
	ModeratorID string
	Reason      string
	CreatedAt   time.Time
	ExpiresAt   *time.Time
}

func (RoomBan) Active

func (b RoomBan) Active(now time.Time) bool

type RoomBanListInput

type RoomBanListInput struct {
	ActorID string
	RoomID  *string
}

type RoomBanProjection

type RoomBanProjection struct {
	events.MemoryProjection
	// contains filtered or unexported fields
}

func NewRoomBanProjection

func NewRoomBanProjection() *RoomBanProjection

func (*RoomBanProjection) ActiveBan

func (p *RoomBanProjection) ActiveBan(roomID, userID string, now time.Time) (RoomBan, bool)

func (*RoomBanProjection) ActiveBans

func (p *RoomBanProjection) ActiveBans(now time.Time) []RoomBan

ActiveBans returns active bans by creation time descending, then event ID ascending so equal timestamps do not change offset page boundaries.

func (*RoomBanProjection) ActiveRoomBans

func (p *RoomBanProjection) ActiveRoomBans(roomID string, now time.Time) []RoomBan

ActiveRoomBans uses the same stable order as ActiveBans within one room.

func (*RoomBanProjection) Apply

func (p *RoomBanProjection) Apply(event *evtv1.Event, _ uint64) error

func (*RoomBanProjection) IsActive

func (p *RoomBanProjection) IsActive(roomID, userID string, now time.Time) bool

func (*RoomBanProjection) Subjects

func (p *RoomBanProjection) Subjects() []string

type RoomCatalogProjection

type RoomCatalogProjection struct {
	events.MemoryProjection
	// contains filtered or unexported fields
}

RoomCatalogProjection holds per-room metadata derived from evt.room.{R} events: id, name, description, kind, archived state, and creation timestamp. It does NOT track group assignment — that's the group aggregate's concern.

The projection coexists with RoomMembershipProjection on the same subject family (evt.room.>); each ignores the other's event variants per the Projection.Apply forward-compat rule. This is the first concrete pair of projections on a shared filter — see the "single consumer per filter" out-of-scope note in ADR-033.

func NewRoomCatalogProjection

func NewRoomCatalogProjection() *RoomCatalogProjection

NewRoomCatalogProjection returns an empty projection.

func (*RoomCatalogProjection) AllByKind

func (p *RoomCatalogProjection) AllByKind(kind evtv1.RoomKind) []*readmodel.Room

AllByKind returns every room of the given kind. Order is unspecified; the caller sorts / joins with grouping info as needed. The returned models are fresh values.

func (*RoomCatalogProjection) Apply

func (p *RoomCatalogProjection) Apply(event *evtv1.Event, seq uint64) error

Apply implements evtstream.Projection.

Recognised events: RoomCreated, RoomUpdated (rename + description), RoomArchived, RoomUnarchived, RoomDeleted. Membership events (UserJoinedRoom, UserLeftRoom) and any other variants under evt.room.> are silently ignored.

func (*RoomCatalogProjection) Count

func (p *RoomCatalogProjection) Count() int

Count returns the number of rooms in the catalog. Useful for admin/diagnostic surfaces.

func (*RoomCatalogProjection) Exists

func (p *RoomCatalogProjection) Exists(roomID string) bool

Exists reports whether the room is present in the catalog.

func (*RoomCatalogProjection) FindByName

func (p *RoomCatalogProjection) FindByName(name string) string

FindByName returns the ID of a channel room with an equivalent normalized, case-folded name, or "" if no such room exists.

Channel-room only: DM rooms have empty names by convention. Includes archived rooms — operators must rename them before reclaiming the slot, matching the previous KV-index semantics.

func (*RoomCatalogProjection) Get

func (p *RoomCatalogProjection) Get(roomID string) (*readmodel.Room, bool)

Get returns the room's metadata, or (nil, false) if no such room has been projected. The returned model is a fresh value; callers may mutate it freely.

func (*RoomCatalogProjection) Kind

func (p *RoomCatalogProjection) Kind(roomID string) (evtv1.RoomKind, bool)

Kind returns the room's kind, or (ROOM_KIND_UNSPECIFIED, false) if no such room has been projected.

func (*RoomCatalogProjection) NameClaimSnapshot

func (p *RoomCatalogProjection) NameClaimSnapshot(name, excludeRoomID string) RoomNameClaimSnapshot

NameClaimSnapshot returns the room-directory sequence and any room other than excludeRoomID whose derived comparison key matches name. Inspecting all entries is important when stronger Unicode comparison reveals collisions in data written by an older release.

func (*RoomCatalogProjection) Subjects

func (p *RoomCatalogProjection) Subjects() []string

Subjects implements evtstream.Projection. The catalog is a room-derived read model, so it subscribes to the room aggregate namespace and ignores room events it does not handle.

type RoomCommandModel

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

RoomCommandModel owns user-facing room commands. Lower-level room helpers are still available to trusted internal callers, while this model centralizes public API authorization and DM/channel preconditions. The publisher and projection owners keep lifecycle, update and pin consistency inside this model. Explicit capabilities supply the remaining policy and low-level mutations.

func (*RoomCommandModel) AddMember

AddMember permits account and room managers to add members without room.join. Bot managers without either override need their own effective room.join. The bot's join grant applies only to self-service joins. Bans and room lifecycle restrictions still apply.

func (*RoomCommandModel) ArchiveRoom

func (s *RoomCommandModel) ArchiveRoom(ctx context.Context, input RoomIDInput) (*readmodel.Room, error)

func (*RoomCommandModel) ClearNotice

func (s *RoomCommandModel) ClearNotice(ctx context.Context, input RoomNoticeInput) (*readmodel.RoomNotice, error)

ClearNotice removes current content while retaining the concurrency version.

func (*RoomCommandModel) CreatePinnedMessage

CreatePinnedMessage adds a canonical message to a channel's current pin set. The operation is idempotent and rechecks message.pin in each OCC attempt.

func (*RoomCommandModel) CreateRoom

func (s *RoomCommandModel) CreateRoom(ctx context.Context, input RoomCreateInput) (*readmodel.Room, error)

func (*RoomCommandModel) DeletePinnedMessage

func (s *RoomCommandModel) DeletePinnedMessage(ctx context.Context, input PinnedMessageMutationInput) (bool, error)

DeletePinnedMessage removes a canonical message from a channel's current pin set. Removing an absent pin is a successful no-op.

func (*RoomCommandModel) DeleteRoom

func (m *RoomCommandModel) DeleteRoom(ctx context.Context, actorID string, kind RoomKind, room_id string) error

DeleteRoom deletes a room. Authorization: Caller must verify CanManageAnyRoom before calling.

ADR-035 phase 6: event-only. Atomically publishes RoomDeletedEvent (which the room directory applies to both catalog and membership indexes) and, for a channel room in a group, RoomRemovedFromGroupEvent per ADR-086. Historical room events are retained in EVT; the legacy KV room record is no longer touched here.

func (*RoomCommandModel) GetNotice

func (s *RoomCommandModel) GetNotice(ctx context.Context, input RoomIDInput) (*readmodel.RoomNotice, error)

GetNotice returns member-only channel content, including cleared state. Notice visibility does not depend on message-read or management permissions.

func (*RoomCommandModel) JoinGroup

func (s *RoomCommandModel) JoinGroup(ctx context.Context, actorID, groupID string) ([]string, error)

JoinGroup joins each eligible active room in a group. Existing memberships are skipped. Each join keeps its own OCC and projection barrier.

func (*RoomCommandModel) JoinRoom

func (s *RoomCommandModel) JoinRoom(ctx context.Context, input RoomIDInput) (*readmodel.Room, error)

func (*RoomCommandModel) LeaveRoom

func (s *RoomCommandModel) LeaveRoom(ctx context.Context, input RoomIDInput) error

func (*RoomCommandModel) LiftSuspension

func (s *RoomCommandModel) LiftSuspension(ctx context.Context, input RoomUnbanInput) error

func (*RoomCommandModel) ListActiveRoomSuspensions

func (s *RoomCommandModel) ListActiveRoomSuspensions(ctx context.Context, input RoomBanListInput) ([]RoomBan, error)

func (*RoomCommandModel) PublishNotice

func (s *RoomCommandModel) PublishNotice(ctx context.Context, input RoomNoticeInput) (*readmodel.RoomNotice, error)

PublishNotice replaces content and optionally resurfaces it. Corrections keep the publication ID; first publication and republish receive a fresh one.

func (*RoomCommandModel) RemoveMember

func (s *RoomCommandModel) RemoveMember(ctx context.Context, input RoomUserInput) (bool, error)

RemoveMember permits account, room, and target-bot managers to remove members, even after join authority is lost. Membership changes preserve grants.

func (*RoomCommandModel) RemoveUser

func (s *RoomCommandModel) RemoveUser(ctx context.Context, input RoomRemoveUserInput) error

RemoveUser removes a current member and optionally prevents rejoining. It uses the room.remove-member permission at the target room.

func (*RoomCommandModel) StartDM

func (*RoomCommandModel) UnarchiveRoom

func (s *RoomCommandModel) UnarchiveRoom(ctx context.Context, input RoomIDInput) (*readmodel.Room, error)

func (*RoomCommandModel) UpdateRoom

func (s *RoomCommandModel) UpdateRoom(ctx context.Context, input RoomUpdateInput) (*readmodel.Room, error)

UpdateRoom commits all supplied fields atomically. Omitted fields retain their latest values, including after a concurrent update forces a retry.

type RoomCreateInput

type RoomCreateInput struct {
	ActorID       string
	GroupID       string
	Name          string
	Description   string
	Universal     bool
	ThreadingMode evtv1.RoomThreadingMode
}

type RoomDirectoryGroupOptions

type RoomDirectoryGroupOptions struct {
	IncludeArchivedRooms bool
}

type RoomDirectoryListOptions

type RoomDirectoryListOptions struct {
	IncludeChannels bool
	IncludeDMs      bool
	// ArchiveFilter defaults to active rooms and intersects the room-kind flags.
	ArchiveFilter RoomArchiveFilter
	// IncludeEmptyDMs includes accessible DMs before their first message.
	// Public directory and snapshot reads set this; clients choose whether
	// to hide empty conversations from navigation.
	IncludeEmptyDMs bool
}

type RoomDirectoryPage

type RoomDirectoryPage struct {
	Rooms      []*DirectoryRoom
	TotalCount int
	HasMore    bool
}

RoomDirectoryPage contains a visible room page and its filtered count.

type RoomDirectoryProjection

type RoomDirectoryProjection struct {
	events.MemoryProjection
	Catalog    *RoomCatalogProjection
	Membership *RoomMembershipProjection
	Bans       *RoomBanProjection
}

RoomDirectoryProjection combines the room aggregate's structural read models: catalog metadata and membership indexes. Keeping them under one projector avoids duplicate evt.room.> consumers while preserving the smaller read-model APIs used by callers.

func NewRoomDirectoryProjection

func NewRoomDirectoryProjection() *RoomDirectoryProjection

func (*RoomDirectoryProjection) Apply

func (p *RoomDirectoryProjection) Apply(event *evtv1.Event, seq uint64) error

func (*RoomDirectoryProjection) Prepare

Prepare validates the fallible room-directory event shapes before the content view commits any component for the event.

func (*RoomDirectoryProjection) Restore

func (p *RoomDirectoryProjection) Restore(data []byte) error

func (*RoomDirectoryProjection) Snapshot

func (p *RoomDirectoryProjection) Snapshot() ([]byte, error)

func (*RoomDirectoryProjection) SnapshotContractID

func (*RoomDirectoryProjection) SnapshotContractID() string

func (*RoomDirectoryProjection) Subjects

func (p *RoomDirectoryProjection) Subjects() []string

type RoomDirectoryReadModel

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

RoomDirectoryReadModel composes authorized room views from explicit domain dependencies. Construction does not start projectors or background work.

func (*RoomDirectoryReadModel) BatchGetRoomGroups

func (s *RoomDirectoryReadModel) BatchGetRoomGroups(ctx context.Context, actorID string, groupIDs []string, opts RoomDirectoryGroupOptions) ([]*DirectoryRoomGroup, error)

func (*RoomDirectoryReadModel) BatchGetRooms

func (s *RoomDirectoryReadModel) BatchGetRooms(ctx context.Context, actorID string, roomIDs []string) ([]*DirectoryRoom, error)

func (*RoomDirectoryReadModel) GetRoom

func (s *RoomDirectoryReadModel) GetRoom(ctx context.Context, actorID, roomID string) (*DirectoryRoom, error)

func (*RoomDirectoryReadModel) GetRoomGroup

func (s *RoomDirectoryReadModel) GetRoomGroup(ctx context.Context, actorID, groupID string, opts RoomDirectoryGroupOptions) (*DirectoryRoomGroup, error)

func (*RoomDirectoryReadModel) ListRoomGroups

func (*RoomDirectoryReadModel) ListRooms

func (*RoomDirectoryReadModel) ListRoomsPage

func (s *RoomDirectoryReadModel) ListRoomsPage(ctx context.Context, actorID string, opts RoomDirectoryListOptions, limit, offset int) (*RoomDirectoryPage, error)

ListRoomsPage filters and orders room identities before hydrating the page. Complete internal snapshots continue to use ListRooms.

type RoomEvent

type RoomEvent struct {
	*evtv1.Event
	Sequence uint64
	// EchoMetadataHydrated marks detached echo attribution and mentions that
	// the transport can reuse without loading the original post again.
	EchoMetadataHydrated bool
}

RoomEvent pairs a *evtv1.Event with its stream sequence so the pagination layer can build opaque cursors without re-deriving the sequence per event. Event is embedded so callers can access event fields directly (`event.Id`, `event.GetMessagePosted()`, etc.).

type RoomEventsAroundResult

type RoomEventsAroundResult struct {
	Events      []*RoomEvent
	TargetIndex int
	HasOlder    bool
	HasNewer    bool
}

RoomEventsAroundResult contains the result of fetching events around a target event.

type RoomEventsResult

type RoomEventsResult struct {
	Events         []*RoomEvent
	HasOlder       bool
	HasNewer       bool
	StartCursorSeq uint64
	EndCursorSeq   uint64
}

RoomEventsResult is the return type for paginated room event queries. HasOlder/HasNewer indicate whether more events exist beyond the returned page. StartCursorSeq/EndCursorSeq are stream sequences for the first and last event in the page; API layers render them as opaque cursor strings. Both are zero when Events is empty.

type RoomGroupLayoutProjection

type RoomGroupLayoutProjection struct {
	events.MemoryProjection
	Groups *RoomGroupProjection
	Layout *RoomLayoutProjection
}

RoomGroupLayoutProjection combines room-group state and explicit sidebar ordering. RoomModel owns both read surfaces and their shared projector.

func NewRoomGroupLayoutProjection

func NewRoomGroupLayoutProjection() *RoomGroupLayoutProjection

func (*RoomGroupLayoutProjection) Apply

func (p *RoomGroupLayoutProjection) Apply(event *evtv1.Event, seq uint64) error

func (*RoomGroupLayoutProjection) Restore

func (p *RoomGroupLayoutProjection) Restore(data []byte) error

func (*RoomGroupLayoutProjection) Snapshot

func (p *RoomGroupLayoutProjection) Snapshot() ([]byte, error)

func (*RoomGroupLayoutProjection) SnapshotContractID

func (*RoomGroupLayoutProjection) SnapshotContractID() string

func (*RoomGroupLayoutProjection) Subjects

func (p *RoomGroupLayoutProjection) Subjects() []string

type RoomGroupMoveSnapshot

type RoomGroupMoveSnapshot struct {
	TargetExists  bool
	SourceGroupID string
	Seq           uint64
}

type RoomGroupProjection

type RoomGroupProjection struct {
	events.MemoryProjection
	// contains filtered or unexported fields
}

RoomGroupProjection holds the current set of room groups derived from evt.group.{G} events: id, name, description, and the ordered list of room IDs in the group. The group aggregate owns both "what rooms are in me" and "in what order" — see ADR-034 / the design discussion accompanying the room-metadata + room-group migration PR.

Move-room operations land as two events (one per affected group), matching the per-aggregate cascade rule from ADR-034 Approach A.

func NewRoomGroupProjection

func NewRoomGroupProjection() *RoomGroupProjection

NewRoomGroupProjection returns an empty projection.

func (*RoomGroupProjection) All

All returns every group in the projection. Order is unspecified; RoomLayoutProjection provides the configured order. Returned models and their nested values are detached.

func (*RoomGroupProjection) Apply

func (p *RoomGroupProjection) Apply(event *evtv1.Event, seq uint64) error

Apply implements evtstream.Projection. Recognised events: RoomGroupCreated, RoomGroupUpdated, RoomGroupDeleted, RoomAddedToGroup, RoomRemovedFromGroup, RoomsInGroupReordered, SidebarLinkAddedToGroup, SidebarLinkUpdated, SidebarLinkRemovedFromGroup, SidebarGroupEntriesReordered. Unrecognised variants are silently ignored.

func (*RoomGroupProjection) Count

func (p *RoomGroupProjection) Count() int

Count returns the number of groups projected. Useful for admin/diagnostic surfaces.

func (*RoomGroupProjection) Exists

func (p *RoomGroupProjection) Exists(groupID string) bool

Exists reports whether the group is in the projection.

func (*RoomGroupProjection) Get

func (p *RoomGroupProjection) Get(groupID string) (*readmodel.RoomGroup, bool)

Get returns the group's data, or (nil, false) if no such group has been projected. The returned model and its nested values are detached, so callers can change them without changing the projection.

func (*RoomGroupProjection) GroupForRoom

func (p *RoomGroupProjection) GroupForRoom(roomID string) string

GroupForRoom returns the group ID that currently contains the given room, or "" if the room isn't in any group. Linear scan; fine for the small group counts we expect on a server.

func (p *RoomGroupProjection) GroupForSidebarLink(linkID string) string

func (*RoomGroupProjection) MoveSnapshot

func (p *RoomGroupProjection) MoveSnapshot(roomID, targetGroupID string) RoomGroupMoveSnapshot

func (*RoomGroupProjection) PlacementSnapshot

func (p *RoomGroupProjection) PlacementSnapshot(item *evtv1.SidebarGroupEntry, targetGroupID string) SidebarItemPlacementSnapshot

PlacementSnapshot returns a consistent source/destination view for a room or sidebar-link placement command. The returned read models are detached from projection state.

func (*RoomGroupProjection) SidebarLinkMoveSnapshot

func (p *RoomGroupProjection) SidebarLinkMoveSnapshot(linkID, targetGroupID string) SidebarLinkMoveSnapshot

func (*RoomGroupProjection) Snapshot

func (p *RoomGroupProjection) Snapshot(groupID string) RoomGroupSnapshot

func (*RoomGroupProjection) Subjects

func (p *RoomGroupProjection) Subjects() []string

Subjects implements evtstream.Projection. Room groups are a group-derived read model, so the projection subscribes to the group aggregate namespace and ignores group events it does not handle.

type RoomGroupSnapshot

type RoomGroupSnapshot struct {
	Group  *readmodel.RoomGroup
	Exists bool
	Seq    uint64
}

type RoomIDInput

type RoomIDInput struct {
	ActorID string
	RoomID  string
}

type RoomInvitationModel

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

RoomInvitationModel owns invitation commands and participant-only reads. All invitation transitions share the room aggregate guard with membership and lifecycle.

func (*RoomInvitationModel) CanAccept

func (m *RoomInvitationModel) CanAccept(ctx context.Context, actorID string, v RoomInvitationState) (bool, error)

CanAccept reports whether the recipient can accept with present authority.

func (*RoomInvitationModel) Create

func (m *RoomInvitationModel) Create(ctx context.Context, actorID, roomID, recipientID string) (RoomInvitationState, error)

Create keeps duplicate sends idempotent without extending the existing deadline.

func (*RoomInvitationModel) Get

func (m *RoomInvitationModel) Get(ctx context.Context, actorID, id string) (RoomInvitationState, error)

Get returns an invitation only to its sender or recipient.

func (*RoomInvitationModel) List

func (m *RoomInvitationModel) List(ctx context.Context, actorID string, sent, pendingOnly bool) ([]RoomInvitationState, error)

List returns the actor's sent or received invitations.

func (*RoomInvitationModel) Respond

func (m *RoomInvitationModel) Respond(ctx context.Context, actorID, id string, accept bool) (RoomInvitationState, error)

Respond commits the terminal fact and any membership change in a single atomic batch. Retrying an accepted invitation never recreates membership after a later leave.

type RoomInvitationProjection

type RoomInvitationProjection struct {
	events.MemoryProjection
	// contains filtered or unexported fields
}

RoomInvitationProjection cold-replays invitation facts independently of room snapshots.

func NewRoomInvitationProjection

func NewRoomInvitationProjection() *RoomInvitationProjection

NewRoomInvitationProjection creates an empty projection for cold replay.

func (*RoomInvitationProjection) Apply

func (p *RoomInvitationProjection) Apply(event *evtv1.Event, _ uint64) error

func (*RoomInvitationProjection) Subjects

func (p *RoomInvitationProjection) Subjects() []string

type RoomInvitationState

type RoomInvitationState struct {
	ID, RoomID, SenderID, RecipientID string
	CreatedAt, ExpiresAt              time.Time
	// Status is pending, accepted, or declined; expiry is derived from ExpiresAt.
	Status string
}

RoomInvitationState is derived only from EVT. Notification retention cannot change it.

type RoomKind

type RoomKind string

RoomKind is the closed enum of room kinds carried in subjects and KV keys (`server.room.{kind}.>`, `room_membership.{kind}.{roomId}.{userId}`, etc.). The string form goes on the wire — don't rename the variants.

const (
	// KindChannel is a regular (non-DM) chat room.
	KindChannel RoomKind = "channel"
	// KindDM is a direct-message room.
	KindDM RoomKind = "dm"
)

func KindOfRoom

func KindOfRoom(room *readmodel.Room) RoomKind

KindOfRoom returns the canonical RoomKind for a Room. Reads Room.kind directly; legacy `space_id`-based fallback was removed when the field was retired from the proto.

func RoomKindFromLegacySpaceID

func RoomKindFromLegacySpaceID(spaceID string) RoomKind

RoomKindFromLegacySpaceID maps a wire-format-frozen `space_id` value to the room kind it now represents. Use this only at compatibility boundaries where persisted payloads or public APIs still carry `space_id`; code working with Room records should read Room.kind via KindOfRoom.

type RoomLayoutModel

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

RoomLayoutModel owns room-group and sidebar mutations. It keeps authorization, layout conflict checks, atomic event batches and projection waits together.

func (*RoomLayoutModel) AdminCreateRoomGroup

func (m *RoomLayoutModel) AdminCreateRoomGroup(ctx context.Context, actorID, name, description string) (*readmodel.RoomGroup, error)
func (m *RoomLayoutModel) AdminCreateSidebarLink(ctx context.Context, actorID, groupID, label, rawURL string) (*readmodel.SidebarLink, error)

func (*RoomLayoutModel) AdminDeleteRoomGroup

func (m *RoomLayoutModel) AdminDeleteRoomGroup(ctx context.Context, actorID, groupID string) error
func (m *RoomLayoutModel) AdminDeleteSidebarLink(ctx context.Context, actorID, linkID string) error

func (*RoomLayoutModel) AdminMoveRoomGroup

func (m *RoomLayoutModel) AdminMoveRoomGroup(ctx context.Context, actorID, groupID, beforeGroupID string) error

AdminMoveRoomGroup places one group before another group, or last when beforeGroupID is empty. The server recomputes the complete order on an OCC conflict so callers can submit relative intent from a filtered UI.

func (*RoomLayoutModel) AdminMoveRoomToGroup

func (m *RoomLayoutModel) AdminMoveRoomToGroup(ctx context.Context, actorID, roomID, targetGroupID string) (*readmodel.Room, error)

func (*RoomLayoutModel) AdminMoveSidebarItem

func (m *RoomLayoutModel) AdminMoveSidebarItem(ctx context.Context, actorID string, item *evtv1.SidebarGroupEntry, targetGroupID string, before *evtv1.SidebarGroupEntry) (*readmodel.RoomGroup, error)

AdminMoveSidebarItem places one room or sidebar link in a destination group. Each OCC attempt validates the source and destination authorization inputs with a stable request-time read.

func (*RoomLayoutModel) AdminMoveSidebarLinkToGroup

func (m *RoomLayoutModel) AdminMoveSidebarLinkToGroup(ctx context.Context, actorID, linkID, targetGroupID string) (*readmodel.SidebarLink, error)

func (*RoomLayoutModel) AdminReorderRoomGroups

func (m *RoomLayoutModel) AdminReorderRoomGroups(ctx context.Context, actorID string, orderedGroupIDs []string) error

func (*RoomLayoutModel) AdminReorderSidebarItemsInGroup

func (m *RoomLayoutModel) AdminReorderSidebarItemsInGroup(ctx context.Context, actorID, groupID string, orderedEntries []*evtv1.SidebarGroupEntry) (*readmodel.RoomGroup, error)

func (*RoomLayoutModel) AdminUpdateRoomGroup

func (m *RoomLayoutModel) AdminUpdateRoomGroup(ctx context.Context, actorID, groupID string, name, description *string) (*readmodel.RoomGroup, error)
func (m *RoomLayoutModel) AdminUpdateSidebarLink(ctx context.Context, actorID, linkID string, label, rawURL *string) (*readmodel.SidebarLink, error)

func (*RoomLayoutModel) CreateRoomGroup

func (m *RoomLayoutModel) CreateRoomGroup(ctx context.Context, actorID, name, description string) (*readmodel.RoomGroup, error)

CreateRoomGroup publishes a RoomGroupCreatedEvent and appends the new group ID to the layout ordering via a RoomGroupsReorderedEvent. Name is trimmed; description may be empty.

func (m *RoomLayoutModel) CreateSidebarLink(ctx context.Context, actorID, groupID, label, rawURL string) (*readmodel.SidebarLink, error)

func (*RoomLayoutModel) DeleteRoomGroup

func (m *RoomLayoutModel) DeleteRoomGroup(ctx context.Context, actorID, groupID string) error

DeleteRoomGroup removes a group via RoomGroupDeletedEvent. Fails with ErrRoomGroupHasRooms if the group still contains any rooms or sidebar links. The group tombstone and resulting RoomGroupsReorderedEvent commit atomically.

func (m *RoomLayoutModel) DeleteSidebarLink(ctx context.Context, actorID, linkID string) error

func (*RoomLayoutModel) DeleteSidebarLinkInGroup

func (m *RoomLayoutModel) DeleteSidebarLinkInGroup(ctx context.Context, actorID, groupID, linkID string) error

func (*RoomLayoutModel) GetAdminRoom

func (m *RoomLayoutModel) GetAdminRoom(ctx context.Context, actorID, roomID string) (*AdminRoomManagementDetails, error)

func (*RoomLayoutModel) GetAdminRoomGroup

func (m *RoomLayoutModel) GetAdminRoomGroup(ctx context.Context, actorID, groupID string) (*AdminRoomGroupManagementDetails, error)

func (*RoomLayoutModel) GetRoomGroup

func (m *RoomLayoutModel) GetRoomGroup(ctx context.Context, groupID string) (*readmodel.RoomGroup, error)

GetRoomGroup reads a single group through RoomModel. Returns ErrRoomGroupNotFound if no RoomGroupCreatedEvent for the ID has been observed.

func (*RoomLayoutModel) ListRoomGroupsOrdered

func (m *RoomLayoutModel) ListRoomGroupsOrdered(ctx context.Context, kind RoomKind) ([]*readmodel.RoomGroup, error)

ListRoomGroupsOrdered returns the layout-ordered list of channel groups, dropping stale references and appending orphans (groups present in the catalog but missing from the layout) at the end by NanoID order so the sidebar self-heals on read.

`kind` is preserved on the signature for symmetry with other room APIs; only KindChannel participates in the layout today.

func (*RoomLayoutModel) MoveRoomToGroup

func (m *RoomLayoutModel) MoveRoomToGroup(ctx context.Context, actorID, roomID, targetGroupID string) error

MoveRoomToGroup moves a room into the target group, removing it from any other group it was previously in (ADR-031's "every room belongs to exactly one group" invariant). Two events per ADR-034 Approach A: RoomRemovedFromGroup on source, RoomAddedToGroup on target — projection sees them in stream order and the invariant holds at every intermediate sequence.

Authorization for the source and target groups must be checked by the caller — see ADR-031's two-group rule.

func (*RoomLayoutModel) MoveRoomToGroupFromSource

func (m *RoomLayoutModel) MoveRoomToGroupFromSource(ctx context.Context, actorID, roomID, sourceGroupID, targetGroupID string) error

MoveRoomToGroupFromSource moves a room only if the room's current source group still matches sourceGroupID. API callers that authorize the source group before calling core should use this variant so a concurrent move cannot swap the source group between authorization and append.

func (*RoomLayoutModel) MoveSidebarLinkBetweenGroups

func (m *RoomLayoutModel) MoveSidebarLinkBetweenGroups(ctx context.Context, actorID, linkID, sourceGroupID, targetGroupID string) error

func (*RoomLayoutModel) MoveSidebarLinkToGroup

func (m *RoomLayoutModel) MoveSidebarLinkToGroup(ctx context.Context, actorID, linkID, targetGroupID string) error

func (*RoomLayoutModel) ReorderRoomGroups

func (m *RoomLayoutModel) ReorderRoomGroups(ctx context.Context, actorID string, orderedGroupIDs []string) error

ReorderRoomGroups publishes a RoomGroupsReorderedEvent with the new inter-group ordering. orderedGroupIDs must be a permutation of the current group set in RoomModel — extras, duplicates, or missing IDs return ErrRoomGroupOrderMismatch.

func (*RoomLayoutModel) ReorderRoomsInGroup

func (m *RoomLayoutModel) ReorderRoomsInGroup(ctx context.Context, actorID, groupID string, orderedRoomIDs []string) error

ReorderRoomsInGroup publishes a RoomsInGroupReorderedEvent with a new intra-group room ordering. orderedRoomIDs must be a permutation of the group's current room_ids — extras, duplicates, or missing IDs return ErrRoomGroupOrderMismatch.

Cross-group moves go through MoveRoomToGroup; this method is for intra-group drag-reorder where the membership set doesn't change.

func (*RoomLayoutModel) ReorderSidebarItemsInGroup

func (m *RoomLayoutModel) ReorderSidebarItemsInGroup(ctx context.Context, actorID, groupID string, orderedEntries []*evtv1.SidebarGroupEntry) error

func (*RoomLayoutModel) UpdateRoomGroup

func (m *RoomLayoutModel) UpdateRoomGroup(ctx context.Context, actorID, groupID, name, description string) (*readmodel.RoomGroup, error)

UpdateRoomGroup publishes a RoomGroupUpdatedEvent. Layout ordering is untouched; only metadata changes.

func (*RoomLayoutModel) UpdateRoomGroupFields

func (m *RoomLayoutModel) UpdateRoomGroupFields(ctx context.Context, actorID, groupID string, name, description *string) (*readmodel.RoomGroup, error)

UpdateRoomGroupFields applies a sparse metadata patch. Each OCC retry recomposes omitted fields from the latest group projection so a stale client cannot overwrite a concurrent update to a field it did not submit.

func (m *RoomLayoutModel) UpdateSidebarLink(ctx context.Context, actorID, linkID, label, rawURL string) (*readmodel.SidebarLink, error)

func (*RoomLayoutModel) UpdateSidebarLinkInGroup

func (m *RoomLayoutModel) UpdateSidebarLinkInGroup(ctx context.Context, actorID, groupID, linkID, label, rawURL string) (*readmodel.SidebarLink, error)

type RoomLayoutProjection

type RoomLayoutProjection struct {
	events.MemoryProjection
	// contains filtered or unexported fields
}

RoomLayoutProjection holds the operator-defined inter-group ordering for the sidebar — the `group_ids` slice that used to live in the `room_layout` KV doc. The set of groups themselves is owned by the group aggregate (and projected by RoomGroupProjection); this projection only tracks the order operators have explicitly set.

New groups appear at the end of the sidebar implicitly: the reconciliation in ListRoomGroupsOrdered walks this ordering first, then appends any groups present in RoomGroupProjection that aren't already listed (by NanoID order — roughly creation order). That's why this projection doesn't need to observe group create/delete events; it only cares about explicit reorders.

func NewRoomLayoutProjection

func NewRoomLayoutProjection() *RoomLayoutProjection

NewRoomLayoutProjection returns an empty projection. Order is empty on a fresh server and is rebuilt from RoomGroupsReordered events when present.

func (*RoomLayoutProjection) Apply

func (p *RoomLayoutProjection) Apply(event *evtv1.Event, _ uint64) error

Apply implements evtstream.Projection. Recognised events: RoomGroupsReordered (full ordering replacement). Other variants are silently ignored per the framework's forward-compat rule.

func (*RoomLayoutProjection) Order

func (p *RoomLayoutProjection) Order() []string

Order returns the current explicit ordering of group IDs. May reference IDs of groups that have since been deleted; the reconciler in ListRoomGroupsOrdered drops those before returning to callers.

func (*RoomLayoutProjection) Subjects

func (p *RoomLayoutProjection) Subjects() []string

Subjects implements evtstream.Projection. Singleton aggregate with one event type — the per-(agg, event-type) subject is exact.

type RoomMembershipModel

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

RoomMembershipModel owns explicit and effective membership reads, membership writes and moderation. Its batches preserve call and notification boundaries; the collaborating domains retain ownership of their external effects.

func (*RoomMembershipModel) AddMember

func (m *RoomMembershipModel) AddMember(ctx context.Context, actorID string, kind RoomKind, roomID, targetUserID string) (*readmodel.RoomMembership, error)

AddMember creates an explicit channel-room membership for another user. Authorization: caller must verify room.manage before calling.

The membership transition is still represented by UserJoinedRoomEvent with the target user as actor, so existing membership projections and public room history remain compatible. A separate moderation event records the manager action for audit.

func (*RoomMembershipModel) BanMember

func (m *RoomMembershipModel) BanMember(ctx context.Context, actorID string, kind RoomKind, roomID, targetUserID, reason string, expiresAt *time.Time) (*RoomBan, error)

BanMember records a durable room ban and emits an ordinary leave event for public room history. The caller is responsible for permission checks. The target must currently be a room member.

func (*RoomMembershipModel) GetRoomMemberReferencesForLookup

func (m *RoomMembershipModel) GetRoomMemberReferencesForLookup(ctx context.Context, actorID, roomID string, userIDs []string) ([]*readmodel.User, error)

GetRoomMemberReferencesForLookup reads only the requested accounts. Channel membership may be read by room members, room managers, account managers, and managers of the requested bot. Bot ownership never exposes other members. DMs retain their membership-only privacy boundary.

func (*RoomMembershipModel) GetRoomMembersList

func (m *RoomMembershipModel) GetRoomMembersList(ctx context.Context, kind RoomKind, room_id string) ([]*readmodel.RoomMembership, error)

GetRoomMembersList returns every user currently a member of the room. ADR-035 phase 6: served from the projection.

kind is preserved on the signature for symmetry with the rest of the room API; the (roomID, userID) pair is globally unique so kind is irrelevant to the lookup.

func (*RoomMembershipModel) GetRoomMembership

func (m *RoomMembershipModel) GetRoomMembership(ctx context.Context, kind RoomKind, user_id, room_id string) (*readmodel.RoomMembership, error)

GetRoomMembership retrieves a room membership for a user in a specific room. Reads explicit membership through RoomModel (ADR-035 phase 5 cutover). kind is ignored — roomID is globally unique, so the (roomID, userID) pair fully identifies a membership.

func (*RoomMembershipModel) GetUserRoomMemberships

func (m *RoomMembershipModel) GetUserRoomMemberships(ctx context.Context, kind RoomKind, user_id string) ([]*readmodel.RoomMembership, error)

GetUserRoomMemberships retrieves all room memberships for a given user of a given kind. The membership projection doesn't track kind, so ListMemberRooms filters the user's projected room IDs through RoomModel's projected room catalog. This is O(N) in the user's room count and uses local projection reads; each user has a bounded number of rooms.

func (*RoomMembershipModel) JoinRoom

func (m *RoomMembershipModel) JoinRoom(ctx context.Context, actorID string, kind RoomKind, user_id, room_id string) (*readmodel.RoomMembership, error)

JoinRoom creates a room membership for a user. Idempotent: calling it multiple times with the same parameters is a no-op (the projection's Apply is idempotent on already-present (room, user) pairs, and we early-out via IsMember). Authorization: Caller must verify CanJoinRoomAt before calling.

Event-only. Publishes UserJoinedRoomEvent to EVT, then WaitForSeq on the projections that serve membership and room history reads.

func (*RoomMembershipModel) LeaveRoom

func (m *RoomMembershipModel) LeaveRoom(ctx context.Context, actorID string, kind RoomKind, user_id, room_id string) error

LeaveRoom removes a room membership for a user. Idempotent: no-op if the user is not a member.

Business rules:

  • DM conversations are permanent and cannot be left.
  • Universal rooms grant effective membership to join-eligible server members and cannot be left (users can mute them via notification preferences).

ADR-035 phase 6: event-only. Publishes UserLeftRoomEvent, then WaitFor on the projections that serve membership and room history reads.

func (*RoomMembershipModel) ListActiveRoomBans

func (m *RoomMembershipModel) ListActiveRoomBans(_ context.Context, roomID *string) ([]RoomBan, error)

func (*RoomMembershipModel) ListActiveRoomMemberIDs

func (m *RoomMembershipModel) ListActiveRoomMemberIDs(ctx context.Context, actorID, roomID string) ([]string, error)

ListActiveRoomMemberIDs authorizes a membership listing and removes deleted, shredded, and unknown users without reading or decrypting user profiles.

func (*RoomMembershipModel) ListMemberRooms

func (m *RoomMembershipModel) ListMemberRooms(ctx context.Context, kind RoomKind, userID string, opts MemberRoomListOptions) ([]*readmodel.Room, error)

ListMemberRooms retrieves rooms of the given kind that the user participates in. It is the shared room-list primitive for member-scoped room surfaces; callers layer product policy on top with MemberRoomListOptions.

func (*RoomMembershipModel) ListRoomMemberIDsForList

func (m *RoomMembershipModel) ListRoomMemberIDsForList(ctx context.Context, actorID, roomID string) ([]string, error)

ListRoomMemberIDsForList authorizes the public room-member listing and returns projected membership IDs without hydrating user PII. Deleted or unavailable user records can still have a membership ID; callers that return user resources must remove IDs that they cannot hydrate.

func (*RoomMembershipModel) ListRoomMemberReferences

func (m *RoomMembershipModel) ListRoomMemberReferences(ctx context.Context, actorID, roomID string) ([]*readmodel.User, error)

func (*RoomMembershipModel) ListRoomMemberReferencesForList

func (m *RoomMembershipModel) ListRoomMemberReferencesForList(ctx context.Context, actorID, roomID string) ([]*readmodel.User, error)

ListRoomMemberReferencesForList authorizes the public room-member listing. Existing members and channel-room managers may list their room. Other channel-room nonmembers need both room.list and room.join; DMs retain their membership-only privacy boundary.

func (*RoomMembershipModel) ListRoomMemberReferencesForLookup

func (m *RoomMembershipModel) ListRoomMemberReferencesForLookup(ctx context.Context, actorID, roomID string) ([]*readmodel.User, error)

ListRoomMemberReferencesForLookup authorizes member hydration for room members and channel-room managers. DMs require membership.

func (*RoomMembershipModel) RemoveMember

func (m *RoomMembershipModel) RemoveMember(ctx context.Context, actorID string, kind RoomKind, roomID, targetUserID string) (bool, error)

RemoveMember removes another user's explicit channel-room membership. Authorization: caller must verify room.manage before calling.

The public membership transition remains a UserLeftRoomEvent with the target user as actor. A separate moderation event records who performed the removal.

func (*RoomMembershipModel) RoomMembershipExists

func (m *RoomMembershipModel) RoomMembershipExists(ctx context.Context, kind RoomKind, user_id, room_id string) (bool, error)

RoomMembershipExists checks if a user is an effective member of a room. AuthorizationModel owns this read because universal channels derive membership from join authority. This method is a convenience for consumers that already depend on the membership model; it adds no logic.

func (*RoomMembershipModel) UnbanMember

func (m *RoomMembershipModel) UnbanMember(ctx context.Context, actorID string, kind RoomKind, roomID, targetUserID, reason string) error

UnbanMember clears an active room ban. It is idempotent when no active ban exists; otherwise a durable moderation event records the moderator action.

type RoomMembershipProjection

type RoomMembershipProjection struct {
	events.MemoryProjection
	// contains filtered or unexported fields
}

RoomMembershipProjection is the first event-sourced projection (ADR-033). It consumes UserJoinedRoomEvent / UserLeftRoomEvent / RoomDeletedEvent from the EVT stream and maintains the current set of room memberships in memory.

Two indices are kept so both "who's in this room?" and "what rooms is this user in?" are O(1) hash lookups. They stay in sync — neither drifts independently.

Room kind ("channel" or "dm") is intentionally NOT tracked here. The subject scheme is `evt.room.{roomID}.{eventType}` — kind is a property of the room itself, not of any individual event. Kind-filtered membership queries compose this index with RoomModel's projected room catalog.

DM membership is fixed at creation, so UserLeftRoom does not remove a DM member. LeaveRoom rejects DMs; account deletion still records DM leave facts to end the account's call participation, and ignoring them keeps deleted participants in their conversations. The DM check needs the room kind, which RoomDirectoryProjection supplies through roomKind.

func NewRoomMembershipProjection

func NewRoomMembershipProjection() *RoomMembershipProjection

NewRoomMembershipProjection returns an empty projection. Call Run on a Projector wrapping it to populate from the stream.

func (*RoomMembershipProjection) Apply

func (p *RoomMembershipProjection) Apply(event *evtv1.Event, _ uint64) error

Apply implements evtstream.Projection. Apply runs from a single goroutine in stream order, so the write path locks only to publish state to concurrent readers.

func (*RoomMembershipProjection) IsMember

func (p *RoomMembershipProjection) IsMember(roomID, userID string) bool

IsMember reports whether the user is a member of the room.

func (*RoomMembershipProjection) Members

func (p *RoomMembershipProjection) Members(roomID string) []string

Members returns the user IDs of the room's current members. The returned slice is a copy; the caller may mutate it freely. Order is unspecified.

func (*RoomMembershipProjection) Rooms

func (p *RoomMembershipProjection) Rooms(userID string) []string

Rooms returns the room IDs the user is currently a member of, across every kind. The returned slice is a copy; order is unspecified.

func (*RoomMembershipProjection) Stats

func (p *RoomMembershipProjection) Stats() (rooms int, memberships int)

Stats returns counts useful for diagnostics. Intended for admin/dev endpoints rather than hot paths.

func (*RoomMembershipProjection) Subjects

func (p *RoomMembershipProjection) Subjects() []string

Subjects implements evtstream.Projection. Room membership is a room-derived read model, so it follows the projection policy of subscribing to the owning aggregate namespace and ignoring room events it does not handle.

type RoomMentionResolution

type RoomMentionResolution struct {
	RecipientIDs []string
	Mentions     []*evtv1.MessageMention
}

RoomMentionResolution retains both the concrete recipients and each mention kind that selected them. This provenance is embedded in the durable message source fact so @here presence and overlapping handles are not re-evaluated later by notification materialization.

type RoomModel

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

RoomModel owns the room-derived projections and their projectors.

ChattoCore is still the compatibility facade for most room APIs, but room write paths should use this type for projection readiness instead of naming individual projector fields. That keeps the "which projections must catch up?" knowledge with the room read models.

func (*RoomModel) FindRoomByID

func (m *RoomModel) FindRoomByID(ctx context.Context, roomID string) (*readmodel.Room, error)

FindRoomByID returns a detached room with its current group, without a kind filter.

func (*RoomModel) FindRoomKind

func (m *RoomModel) FindRoomKind(ctx context.Context, roomID string) (RoomKind, error)

FindRoomKind resolves the kind of an existing room.

func (*RoomModel) GetRoom

func (m *RoomModel) GetRoom(ctx context.Context, kind RoomKind, roomID string) (*readmodel.Room, error)

GetRoom returns a detached room with its current group. A missing room or kind mismatch returns ErrNotFound.

func (*RoomModel) GetRoomGroup

func (m *RoomModel) GetRoomGroup(_ context.Context, groupID string) (*readmodel.RoomGroup, error)

GetRoomGroup returns a detached group, or ErrRoomGroupNotFound.

func (*RoomModel) GetRoomLastMessageAt

func (m *RoomModel) GetRoomLastMessageAt(ctx context.Context, kind RoomKind, roomID string) (time.Time, error)

GetRoomLastMessageAt returns the latest ordinary message time, or zero for an empty room.

func (*RoomModel) ListRoomGroupsOrdered

func (m *RoomModel) ListRoomGroupsOrdered(_ context.Context, kind RoomKind) ([]*readmodel.RoomGroup, error)

ListRoomGroupsOrdered returns channel groups in layout order, followed by orphan groups in ID order.

func (*RoomModel) ListRooms

func (m *RoomModel) ListRooms(ctx context.Context, kind RoomKind) ([]*readmodel.Room, error)

ListRooms returns detached rooms of the requested kind with their current groups.

type RoomNameClaimSnapshot

type RoomNameClaimSnapshot struct {
	ConflictingRoomID string
	Seq               uint64
}

type RoomNoticeInput

type RoomNoticeInput struct {
	ActorID, RoomID, ExpectedVersion, Body string
	Republish                              bool
}

RoomNoticeInput carries an editor's version. Empty ExpectedVersion means no notice has ever been published. Clear retains a version to prevent ABA edits.

type RoomRemoveUserInput

type RoomRemoveUserInput struct {
	ActorID    string
	RoomID     string
	UserID     string
	Reason     string
	Suspension bool
	ExpiresAt  *time.Time
}

RoomRemoveUserInput describes a reasoned moderation removal. Suspension is true for both a timed suspension and an indefinite one.

type RoomStartDMInput

type RoomStartDMInput struct {
	ActorID        string
	ParticipantIDs []string
}

type RoomTimelineAroundResult

type RoomTimelineAroundResult struct {
	Kind   RoomKind
	Result *RoomEventsAroundResult
}

type RoomTimelineEventsInput

type RoomTimelineEventsInput struct {
	ActorID   string
	RoomID    string
	Limit     int
	BeforeSeq *uint64
	AfterSeq  *uint64
}

type RoomTimelineEventsResult

type RoomTimelineEventsResult struct {
	Kind RoomKind
	Page *RoomEventsResult
}

type RoomTimelineHydrator

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

RoomTimelineHydrator loads complete room events and message bodies from EVT for compact Room Timeline projection references.

type RoomTimelineMessageHydrationState

type RoomTimelineMessageHydrationState struct {
	DeletedAt          time.Time
	HasDeletedAt       bool
	ChannelEchoEventID string
	Pinned             bool
}

RoomTimelineMessageHydrationState is the detached projection state needed to render one message in a public timeline response.

type RoomTimelineProjection

type RoomTimelineProjection struct {
	events.MemoryProjection
	// contains filtered or unexported fields
}

RoomTimelineProjection holds the visible append-only event log per room.

It consumes the full evt.room.> firehose, but only room-visible events land in the owning room's timeline slice. Folded state such as edits, retractions, thread replies, reactions, and asset-processing events is maintained through focused derived indexes or sibling projections rather than bloating the room timeline readers walk on every page load.

func NewRoomTimelineProjection

func NewRoomTimelineProjection() *RoomTimelineProjection

NewRoomTimelineProjection returns an empty projection with a private event ID table.

func (*RoomTimelineProjection) AllObsoleteBodyEventSeqs

func (p *RoomTimelineProjection) AllObsoleteBodyEventSeqs() []uint64

AllObsoleteBodyEventSeqs returns every projected MessageBodyEvent seq whose payload is no longer needed for the current message state.

func (*RoomTimelineProjection) Apply

func (p *RoomTimelineProjection) Apply(event *evtv1.Event, seq uint64) error

Apply implements evtstream.Projection. Extracts the room_id from whichever room-scoped event variant we recognise and appends visible entries to that room's slice. Events that don't carry a room_id (shouldn't appear on evt.room.>, but defensive) are silently skipped — projections forward-compat by ignoring what they don't understand.

func (*RoomTimelineProjection) BodyEventSeqs

func (p *RoomTimelineProjection) BodyEventSeqs(eventID string) (seqs []uint64, current uint64, ok bool)

BodyEventSeqs returns all projected MessageBodyEvent stream sequences for a message and identifies the most recently observed body sequence. A retracted or hidden message retains this history for secure deletion.

func (*RoomTimelineProjection) BodyReferenceCurrent

func (p *RoomTimelineProjection) BodyReferenceCurrent(reference TimelineBodyReference) bool

BodyReferenceCurrent reports whether a detached active body reference still represents the current visible message body.

func (*RoomTimelineProjection) ChannelEchoEventID

func (p *RoomTimelineProjection) ChannelEchoEventID(originalEventID string) (string, bool)

ChannelEchoEventID returns the first visible echo event for an original thread reply, if one exists. Hidden/retracted echoes are ignored.

func (*RoomTimelineProjection) CompleteStartupReplay

func (p *RoomTimelineProjection) CompleteStartupReplay()

func (*RoomTimelineProjection) ContentEventID

func (p *RoomTimelineProjection) ContentEventID(eventID string) (string, bool)

ContentEventID resolves a visible message to the owner of its content. Echo links must point directly to a thread reply in the same room.

func (*RoomTimelineProjection) CurrentRoomAttachmentMessages

func (p *RoomTimelineProjection) CurrentRoomAttachmentMessages(roomID string) []projectedRoomAttachmentMessage

CurrentRoomAttachmentMessages returns current, visible messages whose latest body references attachments. Results are newest message first.

func (*RoomTimelineProjection) EventRoomID

func (p *RoomTimelineProjection) EventRoomID(eventID string) (string, bool)

EventRoomID returns the room of a timeline event of any kind. It copies no entry, so callers that need only the room can check many events cheaply.

func (*RoomTimelineProjection) Get

func (p *RoomTimelineProjection) Get(eventID string) (*TimelineEntry, bool)

Get returns a single timeline entry by its envelope id, or (nil, false) if no such event has been projected.

func (*RoomTimelineProjection) IsEcho

func (p *RoomTimelineProjection) IsEcho(eventID string) bool

IsEcho reports whether eventID is a MessagePostedEvent echo.

func (*RoomTimelineProjection) IsHiddenEcho

func (p *RoomTimelineProjection) IsHiddenEcho(eventID string) bool

IsHiddenEcho reports whether an echo has been directly retracted from the room timeline.

func (*RoomTimelineProjection) LastPostedMessageTimes

func (p *RoomTimelineProjection) LastPostedMessageTimes(roomID string, visible func(*TimelineEntry) bool) (lastMessage, lastRoot time.Time)

LastPostedMessageTimes returns the creation times of the latest ordinary message and root message in commit order. It reads retained posting facts: edits, retractions, and hidden echoes do not change activity. Historical imports are excluded. A non-nil visible predicate limits both times to readable threads. It runs under the timeline read lock and must not acquire another projection lock or call back into this projection. Zero means no qualifying post.

func (*RoomTimelineProjection) LastRoomMessageEntry

func (p *RoomTimelineProjection) LastRoomMessageEntry(roomID string) (*TimelineEntry, bool)

LastRoomMessageEntry returns the newest non-hidden ordinary post in a room, including thread replies that are intentionally absent from byRoom. Historical imports do not count as new room activity.

func (*RoomTimelineProjection) LastVisibleRoomEntry

func (p *RoomTimelineProjection) LastVisibleRoomEntry(
	roomID string,
	visible func(*TimelineEntry) bool,
) (*TimelineEntry, bool)

LastVisibleRoomEntry walks the room's timeline newest-first and returns the first entry that passes `visible`. Useful for "last root message", "last activity", and similar single-entry lookups that don't need to materialise a full slice. Returns (nil, false) if no entry matches.

func (*RoomTimelineProjection) LatestBodyReference

func (p *RoomTimelineProjection) LatestBodyReference(eventID string) (reference TimelineBodyReference, retracted bool, ok bool)

LatestBodyReference returns the current MessageBodyEvent reference for a message, or a zero reference plus retracted=true after retraction.

Echo references identify the original content owner, not the echo's physical body history. Unknown messages return a zero reference and ok=false. Invalid links return a zero reference without reporting a deletion.

O(1): it consults indexes that Apply keeps in lockstep with byRoom.

func (*RoomTimelineProjection) LatestPinEventID

func (p *RoomTimelineProjection) LatestPinEventID(roomID string) string

LatestPinEventID returns the opaque identity of the latest durable pin fact for a room. Unpinning does not move this marker backwards.

func (*RoomTimelineProjection) LatestRootPostAt

func (p *RoomTimelineProjection) LatestRootPostAt(roomID, actorID string) (time.Time, bool)

LatestRootPostAt returns the latest committed non-echo root message time for one actor in one room. The timestamp remains authoritative after edits or retractions so those actions cannot evade slow mode.

func (*RoomTimelineProjection) LinkedChannelEchoEventID

func (p *RoomTimelineProjection) LinkedChannelEchoEventID(originalEventID string) (string, bool)

LinkedChannelEchoEventID returns the first non-hidden echo linked to an original reply, including a retracted echo that must render as a tombstone.

func (*RoomTimelineProjection) LinkedEventIDs

func (p *RoomTimelineProjection) LinkedEventIDs(eventID string) []string

LinkedEventIDs returns related timeline IDs for physical legacy-body cleanup. Content edits must resolve the original instead of writing to these IDs.

func (*RoomTimelineProjection) MessageDeletedAt

func (p *RoomTimelineProjection) MessageDeletedAt(eventID string) (time.Time, bool)

MessageDeletedAt returns when the message first became unavailable through retraction or account key shredding. Echoes inherit the original message's timestamp.

func (*RoomTimelineProjection) MessageHydrationState

func (p *RoomTimelineProjection) MessageHydrationState(eventID string) RoomTimelineMessageHydrationState

MessageHydrationState returns the timeline metadata needed to render one message. The detached result is captured under one projection read lock so deletion, channel-echo, and pin metadata come from the same projection moment. Echoes inherit the pin state of their canonical thread reply.

func (*RoomTimelineProjection) MessageTombstoned

func (p *RoomTimelineProjection) MessageTombstoned(eventID string) bool

func (*RoomTimelineProjection) ObsoleteBodyEventSeqs

func (p *RoomTimelineProjection) ObsoleteBodyEventSeqs(eventID string) []uint64

ObsoleteBodyEventSeqs returns body event sequences that can be securely deleted without losing the current body. For retracted messages, every body event is obsolete. For active messages, every non-current body event is obsolete.

func (*RoomTimelineProjection) PinnedMessage

func (p *RoomTimelineProjection) PinnedMessage(roomID, messageEventID string) (PinnedMessageState, bool)

PinnedMessage returns one active pin association.

func (*RoomTimelineProjection) PinnedMessages

func (p *RoomTimelineProjection) PinnedMessages(roomID string) []PinnedMessageState

PinnedMessages returns one room's active pins in newest-pin-first order.

func (*RoomTimelineProjection) PinnedMessagesWithLatest

func (p *RoomTimelineProjection) PinnedMessagesWithLatest(roomID string) ([]PinnedMessageState, string)

PinnedMessagesWithLatest returns active pins and the opaque latest-pin marker from one projection read boundary.

func (*RoomTimelineProjection) ReplaySubjects

func (p *RoomTimelineProjection) ReplaySubjects() []string

ReplaySubjects uses one stream-wide physical filter because JetStream's multi-filter scan is expensive when it combines the broad room wildcard with the sparse user-key-shredded family. The Projector rejects unrelated subjects before decoding or applying them.

func (*RoomTimelineProjection) Restore

func (p *RoomTimelineProjection) Restore(data []byte) error

func (*RoomTimelineProjection) RoomEventCount

func (p *RoomTimelineProjection) RoomEventCount(roomID string) int

RoomEventCount returns the total number of non-hidden visible timeline entries in the room.

func (*RoomTimelineProjection) RoomEvents

func (p *RoomTimelineProjection) RoomEvents(roomID string, limit int, beforeStreamSeq uint64) []*TimelineEntry

RoomEvents returns up to `limit` entries from a room's timeline in newest-first order, optionally bounded by an exclusive stream-sequence cursor (beforeStreamSeq == 0 means "from the newest"). It returns detached compact references that callers can inspect without holding the projection lock.

Entries are the room-visible timeline; folded state such as edits, reactions, thread replies, asset processing, and directly hidden echoes is excluded.

func (*RoomTimelineProjection) Snapshot

func (p *RoomTimelineProjection) Snapshot() ([]byte, error)

func (*RoomTimelineProjection) SnapshotContractID

func (*RoomTimelineProjection) SnapshotContractID() string

func (*RoomTimelineProjection) Stats

func (p *RoomTimelineProjection) Stats() (rooms int, entries int, messagePosts int)

Stats returns aggregate counts useful for import/rollout diagnostics.

func (*RoomTimelineProjection) Subjects

func (p *RoomTimelineProjection) Subjects() []string

Subjects implements evtstream.Projection. The projection owns the "everything that happened in this room" surface, so it subscribes to the room aggregate namespace plus the extra user key-shred events it needs.

func (*RoomTimelineProjection) VisibleRoomEventCount

func (p *RoomTimelineProjection) VisibleRoomEventCount(roomID string) int

VisibleRoomEventCount returns the total number of room-visible timeline entries in the room. Hidden echoes may still be present in the room slice and are excluded by the visible timeline readers.

func (*RoomTimelineProjection) VisibleRoomTimeline

func (p *RoomTimelineProjection) VisibleRoomTimeline(
	roomID string,
	limit int,
	beforeStreamSeq uint64,
	visible func(*TimelineEntry) bool,
) []*TimelineEntry

VisibleRoomTimeline walks the room's visible timeline newest-first, applying `visible` as an optional per-entry filter, and returns up to `limit` matching entries. `beforeStreamSeq > 0` excludes entries with stream seq >= that value (exclusive upper bound for pagination).

Stops as soon as `limit` visible entries are accumulated — no full-slice materialisation. Caller may inspect more than `limit` entries when a custom visibility filter rejects some of them.

Returns entries in newest-first order. Caller reverses to oldest-first if needed.

func (*RoomTimelineProjection) VisibleRoomTimelineAfter

func (p *RoomTimelineProjection) VisibleRoomTimelineAfter(
	roomID string,
	limit int,
	afterStreamSeq uint64,
	visible func(*TimelineEntry) bool,
) []*TimelineEntry

VisibleRoomTimelineAfter walks the room's timeline oldest-first, applying `visible` as a per-entry filter, and returns up to `limit` matching entries with stream seq > afterStreamSeq. This is the forward-pagination counterpart to VisibleRoomTimeline.

func (*RoomTimelineProjection) VisibleRoomTimelineAround

func (p *RoomTimelineProjection) VisibleRoomTimelineAround(
	roomID string,
	eventID string,
	limit int,
	visibility ...func(*TimelineEntry) bool,
) (entries []*TimelineEntry, targetIndex int, hasOlder bool, hasNewer bool, ok bool)

VisibleRoomTimelineAround returns a room-visible window centered on eventID in oldest-first order. It walks the visible room slice, so edits/reactions/ assets/thread replies are not revisited when serving "jump to message" style reads.

type RoomTimelineReadModel

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

RoomTimelineReadModel owns public timeline read authorization and target validation. It returns core event pages; transports remain responsible for cursor encoding and public DTO hydration.

func (*RoomTimelineReadModel) BatchGetMessages

func (s *RoomTimelineReadModel) BatchGetMessages(ctx context.Context, actorID, roomID string, eventIDs []string) (*BatchMessagesReadResult, error)

func (*RoomTimelineReadModel) GetMessage

func (s *RoomTimelineReadModel) GetMessage(ctx context.Context, actorID, roomID, eventID string) (*MessageReadResult, error)

func (*RoomTimelineReadModel) GetRoomEvents

func (*RoomTimelineReadModel) GetRoomEventsAround

func (s *RoomTimelineReadModel) GetRoomEventsAround(ctx context.Context, actorID, roomID, eventID string, limit int) (*RoomTimelineAroundResult, error)

func (*RoomTimelineReadModel) GetThreadEvents

func (*RoomTimelineReadModel) GetThreadEventsAround

func (s *RoomTimelineReadModel) GetThreadEventsAround(ctx context.Context, actorID, roomID, threadRootEventID, eventID string, limit int) (*ThreadTimelineAroundResult, error)

func (*RoomTimelineReadModel) ListPinnedMessages

ListPinnedMessages returns active pins for a channel room. A member with message-read authority may read them; direct-message rooms do not support pins.

func (*RoomTimelineReadModel) ListReactionUsers

func (s *RoomTimelineReadModel) ListReactionUsers(ctx context.Context, actorID, roomID, eventID, emoji string, limit, offset int) (*InteractionUserPage, error)

ListReactionUsers returns complete reaction membership under the same read authorization as the message. A channel echo is an alias for its reply. Existing names are exact lookup keys, even if current write validation rejects them. Catalogue changes must not make persisted reaction membership unreadable.

func (*RoomTimelineReadModel) ListThreadParticipants

func (s *RoomTimelineReadModel) ListThreadParticipants(ctx context.Context, actorID, roomID, rootID string, limit, offset int) (*InteractionUserPage, error)

ListThreadParticipants returns distinct authors of current visible replies, excluding erased users and matching thread summaries.

func (*RoomTimelineReadModel) MessageHydrationState

func (s *RoomTimelineReadModel) MessageHydrationState(eventID string) (RoomTimelineMessageHydrationState, error)

MessageHydrationState returns detached projection metadata for rendering one message. Timeline authorization belongs to the operation that supplied the message event; this method only interprets already-authorized projected state.

type RoomUnbanInput

type RoomUnbanInput struct {
	ActorID string
	RoomID  string
	UserID  string
	Reason  string
}

type RoomUpdateInput

type RoomUpdateInput struct {
	ActorID         string
	RoomID          string
	Name            *string
	Description     *string
	Universal       *bool
	SlowModeSeconds *uint32
	// ThreadSlowModeSeconds changes the independent per-thread interval.
	ThreadSlowModeSeconds *uint32
	ThreadingMode         *evtv1.RoomThreadingMode
	// ShowMembershipEvents changes timeline display without changing membership facts.
	ShowMembershipEvents *bool
}

type RoomUserInput

type RoomUserInput struct {
	ActorID string
	RoomID  string
	UserID  string
}

type S3Client

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

S3Client wraps the AWS S3 client for S3-compatible storage operations.

func NewS3Client

func NewS3Client(cfg config.S3Config) (*S3Client, error)

NewS3Client creates a new S3 client from configuration. Returns nil if S3 storage is not configured.

func (*S3Client) Bucket

func (s *S3Client) Bucket() string

Bucket returns the configured bucket name.

func (*S3Client) DeleteObject

func (s *S3Client) DeleteObject(ctx context.Context, key string) error

DeleteObject deletes an object from S3.

func (*S3Client) DeleteObjectFromBucket

func (s *S3Client) DeleteObjectFromBucket(ctx context.Context, bucket, key string) error

DeleteObjectFromBucket deletes an object from a specific bucket (for multi-bucket support).

func (*S3Client) EnsureBucket

func (s *S3Client) EnsureBucket(ctx context.Context) error

EnsureBucket creates the bucket if it doesn't exist.

func (*S3Client) GetObject

func (s *S3Client) GetObject(ctx context.Context, key string) (io.ReadCloser, *S3ObjectInfo, error)

GetObject retrieves an object from S3. The returned reader must be closed by the caller.

func (*S3Client) PathPrefix

func (s *S3Client) PathPrefix() string

PathPrefix returns the configured S3 object-key prefix after normalization.

func (*S3Client) PresignedGetURL

func (s *S3Client) PresignedGetURL(ctx context.Context, key string, expiry time.Duration) (*url.URL, error)

PresignedGetURL generates a presigned GET URL for an S3 object. The URL is valid for the specified duration (max 7 days).

func (*S3Client) PutObject

func (s *S3Client) PutObject(ctx context.Context, key string, reader io.Reader, size int64, contentType string) (*S3ObjectInfo, error)

PutObject uploads an object to S3.

func (*S3Client) PutObjectFromBytes

func (s *S3Client) PutObjectFromBytes(ctx context.Context, key string, data []byte, contentType string) (*S3ObjectInfo, error)

PutObjectFromBytes uploads bytes to S3.

func (*S3Client) PutObjectWithMetadata

func (s *S3Client) PutObjectWithMetadata(ctx context.Context, key string, reader io.Reader, size int64, contentType string, metadata map[string]string) (*S3ObjectInfo, error)

PutObjectWithMetadata uploads an object with private provider metadata.

func (*S3Client) StatObject

func (s *S3Client) StatObject(ctx context.Context, key string) (*S3ObjectInfo, error)

StatObject returns metadata about an object without downloading it.

func (*S3Client) WalkObjects

func (s *S3Client) WalkObjects(ctx context.Context, prefix string, visit func(S3ObjectInfo) error) error

WalkObjects visits every object under a logical key prefix using bounded S3 ListObjectsV2 pages. Returning an error from visit stops pagination.

type S3ObjectInfo

type S3ObjectInfo struct {
	Key         string
	Size        int64
	ContentType string
	ModifiedAt  time.Time
	Metadata    map[string]string
}

S3ObjectInfo contains metadata about an S3 object.

type ScopedRolePermissionDecision

type ScopedRolePermissionDecision struct {
	Scope      PermissionScope
	ScopeID    string
	Permission Permission
	Decision   DecisionKind
}

ScopedRolePermissionDecision is one explicit permission decision carried by a role. It is used to keep delegated role assignment within the caller's own authority without treating display order as an authorization rank.

type ServerAssetInfo

type ServerAssetInfo struct {
	Size        int64
	ContentType string
}

ServerAssetInfo contains metadata about a server asset.

type ServerConfigUpdateInput

type ServerConfigUpdateInput struct {
	// RegistrationAdmission changes only account admission; nil leaves it unchanged.
	RegistrationAdmission *evtv1.RegistrationAdmission
	ServerName            *string
	Description           *string
	MOTD                  *string
	WelcomeMessage        *string
}

type ServerContentView

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

ServerContentView is the sequence-consistent process-local view of client-readable EVT state. Focused models keep their own read APIs. The bound projector owns their ordered apply, readiness, failure, and snapshot lifecycle.

func (*ServerContentView) CompleteStartupReplay

func (v *ServerContentView) CompleteStartupReplay()

CompleteStartupReplay releases component compatibility state after replay.

func (*ServerContentView) OwnsProjection

func (v *ServerContentView) OwnsProjection(model events.SubjectProjection) bool

OwnsProjection reports whether model is part of this content view.

func (*ServerContentView) Prepare

func (v *ServerContentView) Prepare(event *evtv1.Event, sequence uint64) (events.PreparedMutation, error)

Prepare prepares every component mutation before any component changes.

func (*ServerContentView) PrepareSubject

func (v *ServerContentView) PrepareSubject(event *evtv1.Event, subject string, sequence uint64) (events.PreparedMutation, error)

PrepareSubject prepares only components that consume the delivered subject.

func (*ServerContentView) Read

func (v *ServerContentView) Read(read func(sequence uint64) error) error

Read runs one bounded in-memory operation against a stable content-view generation and supplies its exact EVT sequence.

func (*ServerContentView) ReadContext

func (v *ServerContentView) ReadContext(
	ctx context.Context,
	read func(context.Context, uint64) error,
) error

ReadContext runs a bounded read in this view and reuses nested read transactions.

func (*ServerContentView) ResetComponents

func (v *ServerContentView) ResetComponents() error

ResetComponents restores the canonical empty state of every focused model.

func (*ServerContentView) RestoreComponents

func (v *ServerContentView) RestoreComponents(components []events.ProjectionSnapshotComponent) error

RestoreComponents restores a complete focused model cohort.

func (*ServerContentView) SnapshotComponentContracts

func (v *ServerContentView) SnapshotComponentContracts() []events.ProjectionSnapshotComponentContract

SnapshotComponentContracts returns the exact required snapshot component set and part limits for repository validation.

func (*ServerContentView) SnapshotComponents

func (v *ServerContentView) SnapshotComponents() ([]events.ProjectionSnapshotComponent, error)

SnapshotComponents captures the focused model payloads.

func (*ServerContentView) SnapshotContractID

func (v *ServerContentView) SnapshotContractID() string

SnapshotContractID returns the contract for this exact component set.

func (*ServerContentView) Subjects

func (v *ServerContentView) Subjects() []string

Subjects declares the complete EVT stream as the view's logical sequence contract. Events that do not change a component still advance the exact global sequence represented by the view.

type ServerMemberWithRoles

type ServerMemberWithRoles struct {
	UserID string
	User   *readmodel.User
	Roles  []string
}

ServerMemberWithRoles represents a server member with their assigned roles.

type ServerSetupInput

type ServerSetupInput struct {
	ServerName  string
	Description string
	Login       string
	DisplayName string
	Password    string
}

ServerSetupInput contains the initial public settings and local owner credentials. Password is transient and must never be logged or stored as plaintext.

type ServerStats

type ServerStats struct {
	UserCount        int
	ChannelRoomCount int
	DMRoomCount      int
}

ServerStats contains aggregate counts surfaced in the admin dashboard.

type SidebarItemPlacementSnapshot

type SidebarItemPlacementSnapshot struct {
	SourceGroupID string
	SourceGroup   *readmodel.RoomGroup
	TargetGroup   *readmodel.RoomGroup
	Link          *readmodel.SidebarLink
	Seq           uint64
}

SidebarItemPlacementSnapshot captures the source and destination groups for one relative sidebar-item move from a single projection generation.

type SidebarLinkMoveSnapshot

type SidebarLinkMoveSnapshot struct {
	TargetExists  bool
	SourceGroupID string
	Link          *readmodel.SidebarLink
	Seq           uint64
}

type SlowModeActiveError

type SlowModeActiveError struct {
	NextPostAt time.Time
}

SlowModeActiveError reports the authoritative time at which a rejected message post may be retried.

func (*SlowModeActiveError) Error

func (e *SlowModeActiveError) Error() string

func (*SlowModeActiveError) Unwrap

func (e *SlowModeActiveError) Unwrap() error

type StableAssetURL

type StableAssetURL struct {
	URL       string
	ExpiresAt time.Time
}

StableAssetURL is an asset URL together with the expiry of its access ticket. Core asset URL methods return server-relative paths. With webserver.url, the API layer makes them absolute on the public origin of each request, so a client on a configured hostname alias gets URLs on that alias.

type StreamMyEventsOptions

type StreamMyEventsOptions struct {
	// TouchPresence preserves the legacy behavior where opening myEvents marks
	// the user online and refreshes the current presence value. New clients that
	// refresh presence through ConnectRPC set this to false.
	TouchPresence bool
}

StreamMyEventsOptions controls process-local behavior for a myEvents stream.

type StreamStats

type StreamStats struct {
	Name          string
	Description   string
	Subjects      []string
	Storage       string
	Messages      uint64
	Bytes         uint64
	FirstSeq      uint64
	LastSeq       uint64
	ConsumerCount int
	Replicas      int
	ClusterLeader string
}

StreamStats contains basic JetStream stream state.

type StringLengthError

type StringLengthError struct {
	Field string
	Max   int
}

StringLengthError is returned when a persisted user-controlled string exceeds the field's durable storage limit.

func (*StringLengthError) Error

func (e *StringLengthError) Error() string

func (*StringLengthError) Is

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

type ThreadFollowModel

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

ThreadFollowModel owns public thread follow/unfollow mutations. It keeps membership and thread-root validation alongside durable EVT writes and projection waits. Trusted internal callers can also request automatic follows.

func (*ThreadFollowModel) FollowThread

func (s *ThreadFollowModel) FollowThread(ctx context.Context, actorID, roomID, threadRootEventID string) error

func (*ThreadFollowModel) FollowThreadIfNeverSet

func (s *ThreadFollowModel) FollowThreadIfNeverSet(ctx context.Context, kind RoomKind, userID, roomID, threadRootEventID string, source evtv1.ThreadFollowSource) (bool, error)

FollowThreadIfNeverSet follows a thread only when the user has no prior follow state. Explicit unfollows and existing follows are left untouched.

func (*ThreadFollowModel) FollowThreadWithSource

func (s *ThreadFollowModel) FollowThreadWithSource(ctx context.Context, kind RoomKind, userID, roomID, threadRootEventID string, source evtv1.ThreadFollowSource) error

FollowThreadWithSource records a follow with an explicit source for trusted internal callers, such as the automatic follow when a user posts a reply. It replaces any earlier follow state, including an explicit unfollow, and is a no-op when the user already follows the thread. Unlike a manual follow, it does not send a Badge hint to the user's clients. It does not check membership or read access. Use FollowThreadIfNeverSet to keep an earlier user choice.

func (*ThreadFollowModel) GetThreadFollowers

func (s *ThreadFollowModel) GetThreadFollowers(ctx context.Context, kind RoomKind, roomID, threadRootEventID string) ([]string, error)

GetThreadFollowers returns all user IDs following a specific thread.

func (*ThreadFollowModel) HasUnreadFollowedThreads

func (s *ThreadFollowModel) HasUnreadFollowedThreads(ctx context.Context, actorID string) (bool, error)

func (*ThreadFollowModel) IsFollowingThread

func (s *ThreadFollowModel) IsFollowingThread(ctx context.Context, kind RoomKind, userID, roomID, threadRootEventID string) (bool, error)

IsFollowingThread checks if a user is following a thread.

func (*ThreadFollowModel) ListFollowedThreads

func (s *ThreadFollowModel) ListFollowedThreads(ctx context.Context, actorID string, includeDM, unreadOnly bool, limit, offset int, rootAuthor ThreadRootAuthorFilter, order ThreadOrder) (*FollowedThreadsPage, error)

ListFollowedThreads returns one page of the actor's followed threads. When unreadOnly is set, the page and its total include only threads with unread replies. rootAuthor selects root authors before pagination and total counts. order selects the sort date before pagination; the default is latest activity.

func (*ThreadFollowModel) ListFollowedThreadsPage

func (s *ThreadFollowModel) ListFollowedThreadsPage(ctx context.Context, userID string, spaceIDs []string, unreadOnly bool, limit, offset int, rootAuthor ThreadRootAuthorFilter, order ThreadOrder) (*FollowedThreadsPage, error)

ListFollowedThreadsPage returns followed threads for the user in the given spaces, sorted by last activity (newest first), with pagination applied before per-thread read-marker lookups.

When unreadOnly is set, the function reads the markers of all followed threads, keeps only threads with unread replies, and then applies pagination. TotalCount then counts only unread threads.

The result includes only rooms where the user is still a member and has applicable message-read authority.

func (*ThreadFollowModel) UnfollowThread

func (s *ThreadFollowModel) UnfollowThread(ctx context.Context, actorID, roomID, threadRootEventID string) error

type ThreadFollowState

type ThreadFollowState string
const (
	ThreadFollowStateNone       ThreadFollowState = ""
	ThreadFollowStateFollowing  ThreadFollowState = "following"
	ThreadFollowStateUnfollowed ThreadFollowState = "unfollowed"
)

type ThreadMetadata

type ThreadMetadata struct {
	Exists             bool
	ReplyCount         int
	LastReplyAt        *time.Time
	LatestReplyEventID string
	ParticipantIDs     []string
	// ParticipantCount counts distinct current reply authors,
	// excluding erased users, beyond the preview limit.
	ParticipantCount int
}

ThreadMetadata contains existence and display metadata for a thread.

type ThreadOrder

type ThreadOrder int32

ThreadOrder selects the date used to order followed threads before pagination.

const (
	// ThreadOrderDefault preserves the caller's default ordering.
	ThreadOrderDefault ThreadOrder = iota
	// ThreadOrderActivity puts the latest reply or unreplied root first.
	ThreadOrderActivity
	// ThreadOrderCreated puts the newest root message first.
	ThreadOrderCreated
)

func (ThreadOrder) Validate

func (o ThreadOrder) Validate() error

Validate rejects unsupported order values at the domain boundary.

type ThreadProjection

type ThreadProjection struct {
	events.MemoryProjection
	// contains filtered or unexported fields
}

ThreadProjection holds an append-only event log per thread, derived from the same evt.room.> firehose RoomTimelineProjection consumes.

"Per thread" means: reply posts (MessagePostedEvent with in_thread != ""). The thread root message itself is NOT stored here; the thread-view resolver fetches the root from RoomTimelineProjection.Get(rootEventID) and concatenates. Reply rows retain only event IDs and stream sequences, and resolvers hydrate the full event from RoomTimelineProjection.

To route edits and retracts to the right thread, we maintain a secondary index mapping reply event_id → thread root event_id, populated as MessagePostedEvent replies arrive. Edits and retracts of root messages (which aren't in any thread bucket) are silently skipped here; they'll be handled at the room- timeline level.

Edits and retractions targeting replies are folded into cached summaries and latest-body state instead of being retained as separate thread rows.

func NewThreadProjection

func NewThreadProjection() *ThreadProjection

NewThreadProjection returns an empty projection with a private event ID table.

func (*ThreadProjection) Apply

func (p *ThreadProjection) Apply(event *evtv1.Event, seq uint64) error

Apply implements evtstream.Projection.

Recognised events:

  • MessagePostedEvent with in_thread != "" → append to the thread's slice, remember its event_id → thread mapping.
  • ThreadCreatedEvent → initialise the thread's bucket even before replies land.
  • MessageEditedEvent whose target event_id is a known thread reply → mark the fact applied; latest body state lives in RoomTimelineProjection.
  • MessageRetractedEvent whose target event_id is a known thread reply → fold the retraction into the thread summary.

Room lifecycle and DM membership establish the recipient set for message interactions. Edits/retracts of non-reply messages are silently ignored.

func (*ThreadProjection) CompleteStartupReplay

func (p *ThreadProjection) CompleteStartupReplay()

func (*ThreadProjection) FollowState

func (p *ThreadProjection) FollowState(userID, roomID, threadRootEventID string) ThreadFollowState

func (*ThreadProjection) FollowedThreadsForUser

func (p *ThreadProjection) FollowedThreadsForUser(userID string) []threadFollowRef

FollowedThreadsForUser returns the threads that a user currently follows, sorted by room ID and then thread root ID.

func (*ThreadProjection) HasInteraction

func (p *ThreadProjection) HasInteraction(userID, roomID, threadRootEventID string) bool

HasInteraction reports whether userID has a derived relationship with one channel-room or DM thread.

func (*ThreadProjection) ParticipantIDs

func (p *ThreadProjection) ParticipantIDs(rootEventID, rootAuthorID string) []string

ParticipantIDs returns current reply authors once each, independent of the bounded display preview. Erased authors are excluded. Pass an empty rootAuthorID when Room Timeline cannot resolve the root author.

func (*ThreadProjection) ReplaySubjects

func (p *ThreadProjection) ReplaySubjects() []string

ReplaySubjects uses one stream-wide physical filter because JetStream's multi-filter scan is expensive when it combines the broad room wildcard with the sparse user-key-shredded family. The Projector rejects unrelated subjects before decoding or applying them.

func (*ThreadProjection) ReplyCount

func (p *ThreadProjection) ReplyCount(rootEventID string) int

ReplyCount returns how many visible MessagePostedEvent replies the thread has accumulated. Edits don't bump the count; retractions and key-shredded authors remove replies from the visible summary.

func (*ThreadProjection) Restore

func (p *ThreadProjection) Restore(data []byte) error

Restore replaces the projection state with a snapshot. Empty data restores an empty projection. A failed restore leaves the current state unchanged; it can only add IDs to the append-only event ID table.

func (*ThreadProjection) Snapshot

func (p *ThreadProjection) Snapshot() ([]byte, error)

func (*ThreadProjection) SnapshotContractID

func (*ThreadProjection) SnapshotContractID() string

func (*ThreadProjection) Stats

func (p *ThreadProjection) Stats() (threads int, entries int, replies int)

Stats returns aggregate counts useful for import/rollout diagnostics.

func (*ThreadProjection) Subjects

func (p *ThreadProjection) Subjects() []string

Subjects implements evtstream.Projection. Room lifecycle, DM membership, and every message post supply the room and relationship indexes. Thread lifecycle, message mutation, and user key-shred facts supply the thread views.

func (*ThreadProjection) ThreadCount

func (p *ThreadProjection) ThreadCount() int

ThreadCount returns how many threads are currently in the projection. Diagnostics only.

func (*ThreadProjection) ThreadEvents

func (p *ThreadProjection) ThreadEvents(rootEventID string) []ThreadTimelineEntry

ThreadEvents returns reply event references for a thread in stream order. Edit and retract facts are folded into the projection's summaries and latest body state instead of being retained as separate rows.

The root message is NOT included — resolvers fetch it from RoomTimelineProjection.Get(rootEventID) and prepend.

func (*ThreadProjection) ThreadExists

func (p *ThreadProjection) ThreadExists(rootEventID string) bool

ThreadExists reports whether an explicit ThreadCreatedEvent or at least one reply has established this thread in the projection.

func (*ThreadProjection) ThreadFollowers

func (p *ThreadProjection) ThreadFollowers(roomID, threadRootEventID string) []string

ThreadFollowers returns the users who currently follow a thread, sorted by user ID. A restore does not keep the follow order, so reads do not expose it.

func (*ThreadProjection) ThreadMetadata

func (p *ThreadProjection) ThreadMetadata(rootEventID, rootAuthorID string) *ThreadMetadata

ThreadMetadata reads the cached reply summary. If the root author has replied, put that author first so bounded previews can identify their contribution. Pass an empty rootAuthorID when the root author is unavailable.

func (*ThreadProjection) ThreadRootForMessage

func (p *ThreadProjection) ThreadRootForMessage(roomID, eventID string) (string, bool)

ThreadRootForMessage returns the canonical thread root for one projected channel-room message, including roots, replies, and channel echoes.

type ThreadRootAuthorFilter

type ThreadRootAuthorFilter int

ThreadRootAuthorFilter selects followed threads by their root author.

const (
	// ThreadRootAuthorAll preserves the complete followed-thread feed.
	ThreadRootAuthorAll ThreadRootAuthorFilter = iota
	// ThreadRootAuthorViewer selects roots created by the viewer.
	ThreadRootAuthorViewer
	// ThreadRootAuthorOthers selects roots created by other users.
	ThreadRootAuthorOthers
)

func (ThreadRootAuthorFilter) Validate

func (f ThreadRootAuthorFilter) Validate() error

Validate rejects unknown filters rather than silently returning another feed.

type ThreadSearchPage

type ThreadSearchPage struct {
	Threads    []ThreadSearchResult
	TotalCount int
	HasMore    bool
}

ThreadSearchPage counts distinct authorized groups before pagination.

type ThreadSearchQuery

type ThreadSearchQuery func(context.Context, *searchv1.QueryRequest) (*searchv1.QueryResponse, error)

ThreadSearchQuery queries the optional provider. Hits are untrusted until hydration.

type ThreadSearchResult

type ThreadSearchResult struct {
	Metadata  *FollowedThread
	Match     MessageSearchResult
	Following bool
}

ThreadSearchResult joins current display state with one authorized matching message.

type ThreadTimelineAroundResult

type ThreadTimelineAroundResult struct {
	Kind        RoomKind
	Root        *RoomEvent
	Replies     *RoomEventsResult
	TargetIndex int
}

type ThreadTimelineEntry

type ThreadTimelineEntry struct {
	EventID   string
	StreamSeq uint64
}

ThreadTimelineEntry is one detached reply reference returned by ThreadEvents.

type ThreadTimelineEventsInput

type ThreadTimelineEventsInput struct {
	ActorID           string
	RoomID            string
	ThreadRootEventID string
	Limit             int
	BeforeSeq         *uint64
	AfterSeq          *uint64
}

type ThreadTimelineEventsResult

type ThreadTimelineEventsResult struct {
	Kind        RoomKind
	Root        *RoomEvent
	Replies     *RoomEventsResult
	IncludeRoot bool
}

type TierPermissions

type TierPermissions struct {
	Permissions       []string
	PermissionDenials []string
}

type TierRole

type TierRole struct {
	RoleName           string
	DisplayName        string
	Description        string
	IsSystem           bool
	Position           int32
	Pingable           bool
	RequiresShieldMode bool
	Override           TierPermissions
	InheritedAllows    []string
	InheritedDenials   []string
}

type TierRoles

type TierRoles struct {
	ApplicablePermissions []string
	Roles                 []TierRole
}

type TimelineBodyReference

type TimelineBodyReference struct {
	MessageEventID  string
	BodyEventID     string
	RoomID          string
	AuthorID        string
	StreamSeq       uint64
	AttachmentCount int
}

TimelineBodyReference identifies one active MessageBodyEvent in EVT. The reference is detached from projection state and contains no message payload.

type TimelineEntry

type TimelineEntry struct {
	StreamSeq         uint64
	EventID           string
	RoomID            string
	ActorID           string
	MessageAuthorID   string
	CreatedAt         time.Time
	EventType         string
	ThreadRootEventID string
	InThreadEventID   string
	EchoOfEventID     string
	HistoricalImport  bool
}

TimelineEntry is a detached read reference for one projected room event. It carries values needed to select, authorize, order, and validate EVT hydration. The projection retains timelineRow values; complete event payloads remain in EVT.

func (TimelineEntry) IsMessagePost

func (e TimelineEntry) IsMessagePost() bool

IsMessagePost reports whether this reference points to a durable message post event.

type TraceEntry

type TraceEntry struct {
	Level    PermissionLevel
	RoleName string
	Decision DecisionKind // Allow or Deny only
	ObjectID string       // "any" for server scope; groupID for group scope; roomID for room overrides
}

TraceEntry is one step in the permission resolution trace. Only explicit projection-backed decisions are emitted (allow or deny); roles with no decision at the level being checked are silent.

type TypingIndicatorInput

type TypingIndicatorInput struct {
	ActorID           string
	RoomID            string
	ThreadRootEventID *string
}

TypingIndicatorInput describes one live-only typing indicator publish.

type UserAuthProjection

type UserAuthProjection struct {
	events.MemoryProjection
	// contains filtered or unexported fields
}

UserAuthProjection retains credential and external-identity state. It is a separate cold-replay projection so profile snapshots can never serialize authentication material by construction.

func (*UserAuthProjection) Apply

func (p *UserAuthProjection) Apply(event *evtv1.Event, seq uint64) error

func (*UserAuthProjection) AuthGeneration

func (p *UserAuthProjection) AuthGeneration(userID string) (uint64, bool)

func (*UserAuthProjection) BotAPIKeyAccess

func (p *UserAuthProjection) BotAPIKeyAccess(botID string) (ownerID string, active bool)

BotAPIKeyAccess returns the owner of a bot and reports whether the bot and its owner can use the bot's API keys in this projection state: the bot is a projected, active bot, and its owner is projected and active. watchBotAPIKeyInvalidated uses the same rule.

func (*UserAuthProjection) BotAPIKeyCredentials

func (p *UserAuthProjection) BotAPIKeyCredentials(userID string) []BotAPIKeyCredential

func (*UserAuthProjection) BotAPIKeyLegacyCreatedAt

func (p *UserAuthProjection) BotAPIKeyLegacyCreatedAt(userID string) time.Time

func (*UserAuthProjection) BotIncomingWebhookCredential

func (p *UserAuthProjection) BotIncomingWebhookCredential(userID, webhookID string) (BotIncomingWebhookCredential, bool)

func (*UserAuthProjection) BotIncomingWebhookCredentials

func (p *UserAuthProjection) BotIncomingWebhookCredentials(userID string) []BotIncomingWebhookCredential

func (*UserAuthProjection) CompleteStartupReplay

func (p *UserAuthProjection) CompleteStartupReplay()

func (*UserAuthProjection) ExternalIdentities

func (p *UserAuthProjection) ExternalIdentities(userID string) []ExternalIdentity

func (*UserAuthProjection) ExternalIdentityAuthentication

func (p *UserAuthProjection) ExternalIdentityAuthentication(issuer, subject string) (string, uint64, bool)

ExternalIdentityAuthentication returns the identity owner and the exact authentication generation from one projection snapshot. Authentication callers must carry this generation through credential issuance so an unlink that races the login invalidates the pending proof.

func (*UserAuthProjection) ExternalIdentityOwnerID

func (p *UserAuthProjection) ExternalIdentityOwnerID(issuer, subject string) (string, bool)

func (*UserAuthProjection) HasExternalIdentity

func (p *UserAuthProjection) HasExternalIdentity(userID string) bool

func (*UserAuthProjection) HasOAuthConsent

func (p *UserAuthProjection) HasOAuthConsent(userID, redirectOrigin string) bool

func (*UserAuthProjection) IdentityCount

func (p *UserAuthProjection) IdentityCount() int

func (*UserAuthProjection) MatchBotAPIKeyCredential

func (p *UserAuthProjection) MatchBotAPIKeyCredential(userID string, verifier []byte) (BotAPIKeyCredential, bool)

func (*UserAuthProjection) PasswordHash

func (p *UserAuthProjection) PasswordHash(userID string) ([]byte, bool)

func (*UserAuthProjection) Subjects

func (p *UserAuthProjection) Subjects() []string

func (*UserAuthProjection) VerifiedAccountIDs

func (p *UserAuthProjection) VerifiedAccountIDs() []string

type UserContentSnapshot

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

UserContentSnapshot is an immutable capture of one user's content-view state. It contains encrypted PII and can be hydrated after the content-view read barrier is released.

func (*UserContentSnapshot) Deleted

func (s *UserContentSnapshot) Deleted() bool

Deleted reports whether the captured account was deleted or crypto-shredded. Hydration returns no content for such an account; callers that must keep its ID show it as a deleted user instead.

type UserDirectoryMetadata

type UserDirectoryMetadata struct {
	ID        string
	CreatedAt *timestamppb.Timestamp
}

UserDirectoryMetadata contains only the lifecycle fields needed to order an admin member page. It does not retain decrypted profile data.

type UserKeyShreddingModel

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

UserKeyShreddingModel owns the request-before-destruction protocol. The command path attempts work synchronously; the shared durable consumer recovers requests after crashes and safely redelivers partial attempts.

func (*UserKeyShreddingModel) Request

func (m *UserKeyShreddingModel) Request(ctx context.Context, actorID, userID string) error

func (*UserKeyShreddingModel) Run

type UserModel

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

UserModel owns user-derived projection reads and readiness barriers.

func (*UserModel) GetUser

func (m *UserModel) GetUser(ctx context.Context, userID string) (*readmodel.User, error)

GetUser retrieves a user from the user projection.

func (*UserModel) GetUserByLogin

func (m *UserModel) GetUserByLogin(ctx context.Context, login string) (*readmodel.User, error)

GetUserByLogin retrieves a user by their login name using the login index.

type UserPermissionMatrix

type UserPermissionMatrix struct {
	Page                  PermissionScopePage
	UserID                string
	ApplicablePermissions []string
	Scopes                []PermissionMatrixScope
	Cells                 []PermissionMatrixCell
}

type UserProjection

type UserProjection struct {
	events.MemoryProjection
	// contains filtered or unexported fields
}

UserProjection derives current account/profile/auth lookup state from durable evt.user.{userID} events.

func NewUserProjection

func NewUserProjection(keyWrapper kms.KeyWrapper, dekStore dekstore.Reader) *UserProjection

NewUserProjection creates the user/account read model. It owns user-facing projected state, while unwrapped DEK bytes are delegated to a resolver so user PII and message-body reads share one cache and shred path.

func (*UserProjection) ActiveDirectoryMetadata

func (p *UserProjection) ActiveDirectoryMetadata() []UserDirectoryMetadata

ActiveDirectoryMetadata returns detached creation metadata without resolving encryption keys. Deleted and shredded accounts are excluded.

func (*UserProjection) ActiveIDs

func (p *UserProjection) ActiveIDs(userIDs []string) []string

ActiveIDs filters membership references using lifecycle metadata only. It does not decrypt profiles or resolve encryption keys.

func (*UserProjection) AllActiveIDs

func (p *UserProjection) AllActiveIDs() []string

AllActiveIDs returns active account IDs without reading encrypted profiles.

func (*UserProjection) Apply

func (p *UserProjection) Apply(event *evtv1.Event, seq uint64) error

func (*UserProjection) AuthGeneration

func (p *UserProjection) AuthGeneration(userID string) (uint64, bool)

func (*UserProjection) AuthProjection

func (p *UserProjection) AuthProjection() *UserAuthProjection

AuthProjection returns the credential-bearing companion projection. It is deliberately excluded from profile snapshots and rebuilt from focused EVT subjects on every startup.

func (*UserProjection) Avatar

func (p *UserProjection) Avatar(userID string) (*evtv1.AssetRecord, bool)

func (*UserProjection) BotIDs

func (p *UserProjection) BotIDs() []string

BotIDs returns every active bot ID in stable order.

func (*UserProjection) BotIDsOwnedBy

func (p *UserProjection) BotIDsOwnedBy(ownerUserID string) []string

BotIDsOwnedBy returns active bot IDs owned by one human user.

func (*UserProjection) CompleteStartupReplay

func (p *UserProjection) CompleteStartupReplay()

func (*UserProjection) Count

func (p *UserProjection) Count() int

func (*UserProjection) Deactivated

func (p *UserProjection) Deactivated(userID string) bool

Deactivated reads the account access flag without decrypting profile data.

func (*UserProjection) EmailClaimed

func (p *UserProjection) EmailClaimed(email string) bool

func (*UserProjection) EmailOwnerID

func (p *UserProjection) EmailOwnerID(email string) (string, bool)

EmailOwnerID returns the projected owner of an email digest without decrypting profile data. Mutation invariants use this lookup so KMS availability cannot make an existing claim appear free.

func (*UserProjection) ExternalIdentities

func (p *UserProjection) ExternalIdentities(userID string) []ExternalIdentity

func (*UserProjection) ExternalIdentityOwnerID

func (p *UserProjection) ExternalIdentityOwnerID(issuer, subject string) (string, bool)

ExternalIdentityOwnerID returns the projected owner of an identity digest without hydrating the user's encrypted profile.

func (*UserProjection) Get

func (p *UserProjection) Get(userID string) (*readmodel.User, bool)

func (*UserProjection) GetByEmail

func (p *UserProjection) GetByEmail(email string) (*readmodel.User, bool)

func (*UserProjection) GetByEmailContext

func (p *UserProjection) GetByEmailContext(ctx context.Context, email string) (*readmodel.User, bool, error)

func (*UserProjection) GetByExternalIdentity

func (p *UserProjection) GetByExternalIdentity(issuer, subject string) (*readmodel.User, bool)

func (*UserProjection) GetByExternalIdentityContext

func (p *UserProjection) GetByExternalIdentityContext(ctx context.Context, issuer, subject string) (*readmodel.User, bool, error)

func (*UserProjection) GetByLogin

func (p *UserProjection) GetByLogin(login string) (*readmodel.User, bool)

func (*UserProjection) GetByLoginContext

func (p *UserProjection) GetByLoginContext(ctx context.Context, login string) (*readmodel.User, bool, error)

func (*UserProjection) GetByOIDCSubject

func (p *UserProjection) GetByOIDCSubject(issuer, subject string) (*readmodel.User, bool)

func (*UserProjection) GetContext

func (p *UserProjection) GetContext(ctx context.Context, userID string) (*readmodel.User, bool, error)

func (*UserProjection) GetReferenceContext

func (p *UserProjection) GetReferenceContext(ctx context.Context, userID string) (*readmodel.User, bool, error)

func (*UserProjection) GetReferences

func (p *UserProjection) GetReferences(userIDs []string) []*readmodel.User

func (*UserProjection) GetReferencesContext

func (p *UserProjection) GetReferencesContext(ctx context.Context, userIDs []string) ([]*readmodel.User, error)

GetReferencesContext returns public user references aligned with userIDs. Unknown users are nil.

func (*UserProjection) HasOAuthConsent

func (p *UserProjection) HasOAuthConsent(userID, redirectOrigin string) bool

func (*UserProjection) HasVerifiedEmail

func (p *UserProjection) HasVerifiedEmail(userID string) bool

func (*UserProjection) IsBotAndOwner

func (p *UserProjection) IsBotAndOwner(userID string) (bool, string, bool)

IsBotAndOwner returns bot status and ownership without hydrating the encrypted user profile.

func (*UserProjection) IsPublicAvatarAsset

func (p *UserProjection) IsPublicAvatarAsset(assetID string) bool

IsPublicAvatarAsset reports whether assetID or key is the current avatar of a non-deleted user. User avatars are intentionally public server assets. The replay-built index keeps this unauthenticated request-path check O(1).

func (*UserProjection) KeyShreddingRequested

func (p *UserProjection) KeyShreddingRequested(userID string) bool

func (*UserProjection) LoginChangedAt

func (p *UserProjection) LoginChangedAt(userID string) time.Time

func (*UserProjection) LoginExists

func (p *UserProjection) LoginExists(login string) bool

func (*UserProjection) PasswordHash

func (p *UserProjection) PasswordHash(userID string) ([]byte, bool)

func (*UserProjection) Preferences

func (p *UserProjection) Preferences(userID string) (*evtv1.ServerUserPreferences, bool)

func (*UserProjection) Prepare

func (p *UserProjection) Prepare(event *evtv1.Event, seq uint64) (events.PreparedMutation, error)

Prepare performs the only fallible content-view work before any component commits. It resolves login and verified-email lookup values without keeping plaintext in projected state.

func (*UserProjection) Restore

func (p *UserProjection) Restore(data []byte) error

func (*UserProjection) Snapshot

func (p *UserProjection) Snapshot() ([]byte, error)

func (*UserProjection) SnapshotContractID

func (*UserProjection) SnapshotContractID() string

func (*UserProjection) Stats

func (p *UserProjection) Stats() (users int, verifiedEmails int, oidcSubjects int)

func (*UserProjection) Subjects

func (p *UserProjection) Subjects() []string

func (*UserProjection) Users

func (p *UserProjection) Users() []*readmodel.User

func (*UserProjection) UsersContext

func (p *UserProjection) UsersContext(ctx context.Context) ([]*readmodel.User, error)

UsersContext decrypts every active user profile. The result order is not defined. The cost grows with the number of users, so use it only for reads that must inspect decrypted profile fields, such as substring search.

func (*UserProjection) VerifiedAccountIDs

func (p *UserProjection) VerifiedAccountIDs() []string

func (*UserProjection) VerifiedEmails

func (p *UserProjection) VerifiedEmails(userID string) []VerifiedEmail

func (*UserProjection) VerifiedEmailsContext

func (p *UserProjection) VerifiedEmailsContext(ctx context.Context, userID string) ([]VerifiedEmail, error)

func (*UserProjection) VerifiedUserIDs

func (p *UserProjection) VerifiedUserIDs() []string

type UserRoleAssignments

type UserRoleAssignments struct {
	UserID              string
	RoleNames           []string
	AssignableRoleNames []string
	RevocableRoleNames  []string
}

UserRoleAssignments contains explicit human-account roles and advisory action limits. It excludes private account fields and the implicit everyone role.

type UserSettingsInput

type UserSettingsInput struct {
	// Timezone is an IANA timezone name. nil = no change, pointer to "" = clear override.
	Timezone *string
	// TimeFormat preference. nil = no change.
	TimeFormat *evtv1.TimeFormat
	// ShareTimezone controls whether the stored time zone is public. nil = no change.
	ShareTimezone *bool
}

UserSettingsInput represents a partial update to user settings. Pointer fields: nil = don't change, non-nil = set to this value.

type ValidatedRuntimeCredential

type ValidatedRuntimeCredential struct {
	Handle             string
	UserID             string
	ClientID           string
	Resource           string
	Scopes             []string
	Kind               AuthTokenKind
	Presentation       AuthTokenPresentation
	Source             string
	Request            *evtv1.AuditRequestMetadata
	CreatedAt          time.Time
	ExpiresAt          time.Time
	AuthGeneration     uint64
	RenewableSessionID string
	AccessGeneration   uint64
	FreshAuthAt        time.Time
	FreshAuthMethod    string
	FreshAuthSource    string
	// A separate storage field keeps older replicas from treating a partial
	// selection as permission to activate every role.
	PrivilegedModeExpiresAt time.Time
	PrivilegedRoles         []string
}

ValidatedRuntimeCredential is the normalized result of validating an opaque runtime credential handle from a specific presentation channel.

type VerifiedEmail

type VerifiedEmail struct {
	Email      string    `json:"email"`
	VerifiedAt time.Time `json:"verified_at"`
	Primary    bool      `json:"primary"`
}

VerifiedEmail is the read-time plaintext shape returned by GetVerifiedEmails. UserProjection retains only its encrypted value and materialises this shape while hydrating a request.

type VideoAttachmentManifest

type VideoAttachmentManifest struct {
	Started   *evtv1.AssetProcessingStartedEvent
	Succeeded *evtv1.AssetProcessingSucceededEvent
	Failed    *evtv1.AssetProcessingFailedEvent
}

VideoAttachmentManifest is the projection's current processing state for one original video attachment. Started fires when processing is enqueued; Succeeded or Failed fires on terminal outcome.

type VideoProcessingRequest

type VideoProcessingRequest struct {
	RoomID         string
	MessageEventID string
	Attachment     *evtv1.Attachment
}

VideoProcessingRequest describes an original video/GIF attachment embedded in a durable MessageBodyEvent that does not yet have a projected manifest.

type VoiceCallToken

type VoiceCallToken struct {
	Token   string
	E2EEKey string
	CallID  string
}

VoiceCallToken contains the LiveKit JWT for a client to join a call.

func GenerateCallMediaPublisherToken

func GenerateCallMediaPublisherToken(apiKey, apiSecret, roomName, publisherIdentity, ownerIdentity, displayName, e2eeKey, callID, publisherKind, selectionRef string) (*VoiceCallToken, error)

GenerateCallMediaPublisherToken creates a publish-only LiveKit credential for a native companion process. The companion has its own opaque identity so it cannot evict the owner's primary LiveKit connection. selectionRef refers to private call authorization state. Authorization: Caller must verify room membership and active participation.

func GenerateVoiceCallToken

func GenerateVoiceCallToken(apiKey, apiSecret, roomName, userID, displayName, login, avatarURL string, isBot bool, e2eeKey string, permissions CallPermissions, selectionRef, callID string) (*VoiceCallToken, error)

GenerateVoiceCallToken creates a LiveKit join token for a user. The login, avatar URL, and bot status are embedded as JSON metadata so the frontend can render identity without additional queries. selectionRef refers to private call authorization state. Authorization: Caller must verify current membership and call.join, then pass the resolved publishing permissions.

Source Files

Directories

Path Synopsis
Package neighborhood discovers public Chatto servers through Neighbor recommendations.
Package neighborhood discovers public Chatto servers through Neighbor recommendations.
Package remoteimage fetches images from remote hosts for Chatto and signs the URLs through which the server serves them.
Package remoteimage fetches images from remote hosts for Chatto and signs the URLs through which the server serves them.

Jump to

Keyboard shortcuts

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