Jakub Zych 6539dd2fb3 test: MessageSaving parity, refusals on every write path and other errors
- TestMessageSavingNoListener: send, reply, ReplyTo and edit answer as
  before the seam, post-save events fire; event fields pinned
- TestMessageSavingRejects: 422 under the Rejection field (content when
  empty), nothing stored or changed, no post-save event, no publication
- TestMessageSavingOtherError: a plain listener error stays a 500
2026-11-01 18:56:29 +01:00
2026-10-26 20:30:56 +01:00

Chat

A compiled chat plugin for SummerCMS: conversations, messages and realtime delivery through lighthouse.

import _ "git.golem15.com/golem15/sm-chat-plugin"

Name: Talk on the shore; messages stay after the tide.

Module git.golem15.com/golem15/sm-chat-plugin, package chat, plugin ID golem15.chat, requires golem15.user. Display name Chat / Czat.

Overview

The plugin ports the WinterCMS Golem15.Chat plugin. Hosts register a chat context (a team, an organisation) at build time through *contracts.Registry. classes.Service is the ChatService successor: it persists messages, fires golem15.chat.message.created / .updated / .deleted inside the write transaction, and lighthouse Bind publishes created.chat.message to the context channel plus chat:conversation:{id} with an ids-only payload. Explicit Emit helpers cover typing, per-user chat:message / chat:read / chat:unread, deleted.chat.message, and the additive updated.chat.message and reacted.chat.message.

Tables (PHP v1.3.0 names, one idempotent baseline migration 202610160001_create_golem15_chat_baseline, every statement IF NOT EXISTS):

  • golem15_chat_conversations: the conversations (models.Conversation), keyed to a context by context_type (a morph alias) and context_id;
  • golem15_chat_participants: membership and read/mute flags (models.Participant);
  • golem15_chat_messages: messages (models.Message) with root_id threading, edited_at and soft deletes; metadata is JSONB;
  • golem15_chat_thread_summaries: the reply sidecar (models.ThreadSummary);
  • golem15_chat_thread_mutes: per-member mute of one thread root (models.ThreadMute);
  • golem15_chat_reactions: one row per message, user and reaction key (models.Reaction), added by the additive migration 202610260001_create_golem15_chat_reactions (also IF NOT EXISTS).

Message.MorphName stays the PHP class string Golem15\Chat\Models\Message so adopted system_files rows keep resolving.

Features

  • Build-time context registry. A host plugin calls Registry.Add(pluginID, Registration{Alias, Loader, LegacyPHPClass}). Resolver(alias) returns ErrUnknownContextType and is never skipped. Chat itself registers no host aliases.
  • CanActFor. contracts.Context.CanActFor(ctx, actorID, memberID) is on the interface. contracts.DefaultCanActFor returns true only when actorID == memberID.
  • SendMessage / EditMessage / DeleteMessage. Persist inside lagoon.Transaction and Fire the matching festival event. SendMessage requires the sender to be a conversation participant (PHP hasParticipant); a context member who is not a participant is ErrNotParticipant. A reply also enqueues golem15.chat.maintain_thread_summary on the broadcasts queue.
  • GetOrCreateDm. Same registered context only (not a friendship DM). Creates the two-person DM of the actor and the other user. Refusal is ErrCannotCreateDM when the host is missing or ChatEnabled is false.
  • GetGroupChat. Finds or creates the one group conversation of a context. On an existing group it still lazy-joins a context member via addParticipant.
  • user.Deleting. Boot Listens user.Deleting and ReassignCreatedBy moves created_by to another remaining participant (DMs and group rows) so the PHP ON DELETE CASCADE constraint on golem15_chat_conversations.created_by can stay.
  • MuteThread. Upserts golem15_chat_thread_mutes for (actor_id, root_id). Missing or unauthorized is ErrNotFound.
  • Ids-only socket payload. Bind payload keys are id, conversation_id, sender_id, root_id, type, action, created_at. Content, names, avatars and attachments never travel on the conversation channel. Full MessageAPI (PHP toApiArray plus root_id / thread_summary) travels only on chat:message and REST. Attachment URLs use /_chat/api/v1/attachments/{messageId}/{fileId}.
  • Reactions (additive). A participant who can see a message adds or removes a reaction key from the configured list (golem15.chat.reactions). Adding is idempotent. Adding any other key is classes.ErrUnknownReaction (HTTP 422 errors.key); removing checks only the key's shape (1 to 32 bytes), so a reaction whose key left the config can still be taken off. MessageAPI.reactions is [{key, count, user_ids}] in configured key order, omitted when empty, and a message page loads its reactions in one query. A change emits reacted.chat.message on chat:conversation:{id} with {id, conversation_id, user_id, key, action} (added or removed), inside the write.
  • Message metadata (additive). SendMessageWith(ctx, SendInput{…, Metadata}) stores an optional JSON object of at most classes.MaxMetadataBytes (4096) bytes serialized in golem15_chat_messages.metadata; anything else is classes.ErrMetadataInvalid (HTTP 422 errors.metadata). The plugin does not interpret it (hosts keep, for example, embed references there). MessageAPI.metadata returns it, omitted when empty, and an edit keeps it. SendMessage keeps its signature as a wrapper without metadata.
  • Live edits (additive). EditMessage emits updated.chat.message on chat:conversation:{id} with {id, conversation_id, action: "updated", edited_at} inside the edit transaction, so other clients refetch the message.
  • Delete-only moderation (additive). A host Context may also implement contracts.MessageModerator. CanDeleteMessage is the sender while they still take part (Service.IsParticipant), else CanModerateMessage(ctx, userID, conversationType), else CanOverseeChats. CanEditMessage is the sender while they still take part, or CanOverseeChats, and never consults the moderator hook; CanView is unchanged. Moderators and overseers need not be participants: the host decides, so a host that wants moderation to end when someone leaves checks membership in CanModerateMessage. Hosts that do not implement it behave as before.
  • Live membership (additive). A host Context may also implement contracts.LiveMembership. When RequireLiveMembership() is true, a participant row of that context's conversations counts only while HasMember is true: reading, sending, editing and deleting their own messages, marking read, typing, uploading, subscribing to chat:conversation:{id} and receiving chat:message on user:{id} stop as soon as someone leaves the context, before the host prunes their rows. Service.IsParticipant exposes the same check. Hosts that do not implement it keep the participant-row behaviour.
  • Pre-save seam (additive). SendMessageWith (and so SendMessage, replies and ReplyTo) and EditMessage fire events.MessageSaving after their access and empty-content checks and before the write transaction opens. A listener error aborts the write: no row is stored or changed, MessageCreated / MessageUpdated do not fire and nothing is published. A listener that returns contracts.Rejection{Field, Message} gets the 422 validation envelope {"error":"Validation failed","errors":{Field:[Message]}} (content when Field is empty); any other listener error stays a 500. Without a listener nothing changes.
  • Channel authorizer. AuthorizeChat allows only participants on chat:conversation:{id} (the plugin registers it with Service.IsParticipant, so live membership applies) with capabilities ["prs"]. It splits the channel itself after stripping a presence: prefix and does not call lighthouse.ChannelID.

Usage

Register a context from an application plugin after looking the registry up (chat publishes it at Boot):

func (p *Plugin) Boot(app *backpack.App) error {
	reg, _ := app.Lookup[*contracts.Registry]()
	return reg.Add(p.ID(), contracts.Registration{
		Alias:          "teams",
		LegacyPHPClass: `Acme\Teams\Models\Team`,
		Loader:         loadTeam, // returns contracts.Context
	})
}

The service is published once the database is. Look it up at request time:

svc, _ := app.Lookup[*classes.Service]()
msg, err := svc.SendMessage(ctx, conversationID, senderID, "hello", nil, nil)

The generic JSON API is chat.APIPrefix (/_chat/api/v1). Routes sit behind jwt.auth and named buckets (chat-api 120/min, chat-dm 10/min). The app mounts that guard (and lighthouse.Mount); this plugin only names it (D-09). Published paths:

  • GET|POST /contexts/{type}/{id}/conversation
  • GET|POST /conversations/{id}/messages (POST body {content, attachment_ids?, root_id?, metadata?}; attachments above golem15.chat.max_message_bytes together, when set, are 422 errors.attachment_ids)
  • POST /conversations/{id}/read, /typing, /mute
  • GET|PUT|DELETE /messages/{id}
  • GET|POST /messages/{id}/replies
  • PUT /threads/{rootId}/mute (chat-owned golem15_chat_thread_mutes; body muted; response root_id, is_muted)
  • POST /contexts/{type}/{id}/dm (chat-dm)
  • GET /reactions ({"data": [key, …]}, the configured list in order; additive)
  • POST /messages/{id}/reactions (body {"key"}; idempotent) and DELETE /messages/{id}/reactions/{key} (URL-encoded key); both answer {"data": {"message_id", "reactions"}}, 404 for a message the caller cannot see or a deleted one, 422 errors.key for an added key outside the list or a removed key over 32 bytes (additive)
  • POST /attachments (pending, is_public=false, field chat-pending-{actorID}; request body limit golem15.chat.upload_body_limit; own chat-upload bucket, 20/min; only for a user who takes part in at least one conversation, else 404; at most golem15.chat.pending_max_files (10) unsent uploads per user, and pending_max_bytes when set, else 422 errors.file)
  • GET /attachments/{messageId}/{fileId} (private stream after participation; missing and unauthorized 404)

A host plugin can refuse content before it is stored by listening to the pre-save event (here a neutral acme plugin with its own allowed check):

app.Events.Listen[*events.MessageSaving]("acme.filter", func(ctx context.Context, ev *events.MessageSaving) error {
	if !allowed(ev.Content) {
		return contracts.Rejection{Field: "content", Message: "This message is not allowed."}
	}
	return nil
})

Downloads are never served from a public blob URL. Legacy /api/chat/* is not registered (D-10).

Uploads that are never sent with a message are deleted by chat:prune-pending (row and blob), which the plugin schedules every hour through pact.HasSchedule; the age is golem15.chat.pending_ttl_hours (24). The schedule runs where the app runs a queue worker (queue.work_in_serve or queue:work).

API reference

Identifier Description
chat.PluginID golem15.chat
chat.APIPrefix /_chat/api/v1 (D-06)
chat.APIBucket Throttle bucket chat-api (120/min)
chat.DMBucket Throttle bucket chat-dm (10/min)
chat.ConfigUseUIAvatars Config key golem15.chat.use_ui_avatars
chat.ConfigUploadBodyLimit Config key golem15.chat.upload_body_limit
chat.DefaultUploadBodyLimit 1048576 (1 MiB, the framework body limit; hosts opt in to more)
chat.UploadBucket Throttle bucket chat-upload (20/min) on POST /attachments
chat.ConfigPendingMaxFiles / chat.ConfigPendingMaxBytes / chat.ConfigMaxMessageBytes Config keys of the pending-upload quota and the per-message attachment total
chat.UploadBodyLimit The upload route's body limit from the config
contracts.MessageModerator Optional host hook CanModerateMessage(ctx, userID, conversationType), consulted only by CanDeleteMessage
contracts.Context Host grouping: members, HasMember, CanOverseeChats, ChatEnabled, GroupName, CanActFor, BroadcastChannel
contracts.DefaultCanActFor Self-action only
contracts.Registry Add, Resolver, Registrations, optional SetProvider / ContextForUser
contracts.ErrUnknownContextType Unknown morph alias; never skipped
classes.Service ChatService successor (SendMessage, GetOrCreateDm, GetGroupChat, MuteThread, EditMessage, DeleteMessage, WithDB, ReassignCreatedBy, …)
classes.New Builds the service; refuses a nil DB
classes.Service.WithDB Shallow copy bound to a festival event transaction
classes.Service.ReassignCreatedBy Moves created_by to another remaining participant on user.Deleting
classes.APIPrefix /_chat/api/v1
classes.AttachmentLimits MaxBytes 102400*1024, PHP KNOWN_EXTS, banned SVG/HTML/XML
classes.MaxAttachments 5 files per message
classes.PendingField chat-pending-{actorID}
classes.Service.PrunePendingAttachments Deletes unsent uploads stored before a cutoff (row and blob); run by chat:prune-pending
classes.Service.SetMaxMessageBytes / MaxMessageBytes Total size of one message's attachments (classes.ErrAttachmentsTooLarge)
classes.Service.IsParticipant Participant check with the context's live membership
classes.ErrPendingQuota Too many unsent uploads (HTTP 422 errors.file)
contracts.LiveMembership Optional host hook RequireLiveMembership(): participant checks also require HasMember
classes.MessageAPI PHP toApiArray plus root_id, thread_summary, and the additive reactions and metadata (both omitempty)
classes.Service.MessagesAPI Serializes a page of messages with one reaction query
classes.SendInput / classes.Service.SendMessageWith Send with optional metadata
classes.MaxMetadataBytes / classes.ErrMetadataInvalid 4096-byte metadata object limit
classes.DefaultReactions / classes.AllowedReactions / classes.ConfigReactions Reaction key list (default 👍 ❤️ 😂 😮 😢 🙏)
classes.Service.AddReaction / RemoveReaction / AllowedReactionKeys Reaction writes and the allowed list
classes.ReactionAPI / classes.ErrUnknownReaction {key, count, user_ids}; key outside the list
classes.Service.EmitReacted / EmitUpdated reacted.chat.message / updated.chat.message (ids-only)
classes.AuthorizeChat lighthouse authorizer for namespace chat
events.MessageCreated Festival event golem15.chat.message.created
events.MessageUpdated Festival event golem15.chat.message.updated
events.MessageDeleted Festival event golem15.chat.message.deleted
events.MessageSaving Pre-save event: ConversationID, ActorID, MessageID (0 on create), RootID, Content (trimmed), Op; fired before the transaction, no Tx; a listener error aborts the write
events.MessageSavingEventName golem15.chat.message.saving (Go-only, no PHP counterpart)
events.OpCreate / events.OpUpdate MessageSaving.Op: create (send or reply) or update (edit)
contracts.Rejection {Field, Message} error a MessageSaving listener returns to refuse content; the API answers 422 errors.{Field} (match with errors.As)
jobs.MaintainThreadSummaryArgs River kind golem15.chat.maintain_thread_summary
models.Message Row of golem15_chat_messages; MorphName is the PHP class string
models.Conversation Row of golem15_chat_conversations
models.Reaction Row of golem15_chat_reactions

Configuration

Key Env Default Meaning
golem15.chat.use_ui_avatars SUMMER_GOLEM15__CHAT__USE_UI_AVATARS (PHP: CHAT_USE_UI_AVATARS) true Fall back to ui-avatars.com when a member has no avatar
golem15.chat.reactions SUMMER_GOLEM15__CHAT__REACTIONS (comma-separated, e.g. 👍,❤️) ["👍", "❤️", "😂", "😮", "😢", "🙏"] Allowed reaction keys in display order; trimmed, deduplicated, at most 32 bytes each; an empty result means the default
golem15.chat.upload_body_limit SUMMER_GOLEM15__CHAT__UPLOAD_BODY_LIMIT 1048576 Request body limit of POST /attachments in bytes; 0 or negative means the default (1 MiB). Hosts that want larger files opt in; keep it at or below the proxy limit. The per-file, 5-file and banned-type rules still apply
golem15.chat.pending_max_files SUMMER_GOLEM15__CHAT__PENDING_MAX_FILES 10 Unsent uploads one user may have waiting; above it the upload is 422 errors.file
golem15.chat.pending_max_bytes SUMMER_GOLEM15__CHAT__PENDING_MAX_BYTES 0 Total size of one user's unsent uploads; 0 means no byte quota
golem15.chat.pending_ttl_hours SUMMER_GOLEM15__CHAT__PENDING_TTL_HOURS 24 Age after which chat:prune-pending deletes an unsent upload
golem15.chat.max_message_bytes SUMMER_GOLEM15__CHAT__MAX_MESSAGE_BYTES 0 Total size of one message's attachments; 0 means no total limit

CLI commands

Command Meaning Example
chat:prune-pending Deletes chat uploads never sent with a message (field chat-pending-*, unattached) older than --hours (default golem15.chat.pending_ttl_hours), row and blob. Scheduled every hour by the plugin. Ends with Deleted N pending chat upload(s) older than H hour(s). bin/<app> chat:prune-pending --hours 2
chat:rewrite-context-types Idempotent UPDATE of golem15_chat_conversations.context_type from each registration's LegacyPHPClass to its alias. Hosts must Registry.Add before running it. Does not rewrite system_files.attachment_type. No flags; ends with Rewrote N conversation context_type row(s). bin/<app> chat:rewrite-context-types

bin/<app> help chat:rewrite-context-types shows the long help and examples. The plugin logs through the component chat (log.components.chat in config/log.yaml).

chat:migrate-attachments is not ported.

Dependencies

  • golem15.user (required), git.golem15.com/golem15/sm-user-plugin v0.1.2 or later (classes.DeletingEvent)
  • SummerCMS v0.4.0 modules: backpack, party, pact, lagoon, festival, lighthouse, conga, bonfire, diary

Testing

go vet ./...
go test -short ./...                   # includes TestChatHTTPAuth (401 without jwt)
go test -run '^TestChatTracer$' -v .   # needs Docker
go test -run '^TestChatHTTPTracer$' -v .  # needs Docker; one authenticated send

TestCommandsDocumented (in -short) logs, without failing, each command whose help lacks a description, long help, examples or an option description (bonfire.CheckDocs).

The proof host is golem15.user + golem15.chat + a test-only teams fixture. TestFixtureAbsentFromProduction keeps the fixture id and the four retired tokens out of production sources.

Changelog

v0.1.5

  • v0.1.5: pre-save MessageSaving event and contracts.Rejection (additive; no listener means no change). SendMessageWith, replies and EditMessage fire it before the write transaction; writeChatError maps a Rejection to the 422 validation envelope. No route, payload, table, migration or config key changes.

v0.1.4

  • plugin.yaml manifest for the SummerCMS marketplace. No code change.

v0.1.3

  • Editing or deleting one's own message now requires the sender to still take part in the conversation (Service.IsParticipant: a participant row and, for a context implementing contracts.LiveMembership, current membership).
  • A removed user gets ErrCannotEdit / ErrCannotDelete, which is HTTP 404 on PUT / DELETE /messages/{id} (the answer every other refusal gives); CanEditMessage / CanDeleteMessage answer the same way.
  • The moderator (contracts.MessageModerator) and overseer (CanOverseeChats) rules are unchanged and used as the host answers them. Moderators need not be participants (a host's CanModerateMessage may require membership).
  • Restrictive only: no route, payload or exported signature changes. Hosts without LiveMembership see a change only for a sender whose participant row is gone.
  • On a Service without a database, CanEditMessage and CanDeleteMessage now return an error instead of answering for the sender.

v0.1.2

  • The service resolves the private uploads bucket lazily through classes.Options.BucketLookup; bootService passes a lookup over app.Lookup[*blob.Bucket]().
  • Why: surf serve publishes *blob.Bucket after it runs the database hooks, and the service is built inside lagoon.OnDatabase. The eager lookup alone stayed nil there, so every POST /_chat/api/v1/attachments and every chat:prune-pending run failed with golem15.chat: uploads bucket is not published. The first non-nil lookup result is cached and shared by WithDB copies.
  • Options.Bucket still wins when set, and the lookup is then never called. With neither, Bucket() is nil and the error is unchanged. Hosts that build their own Service can pass a BucketLookup.

v0.1.1

Several v0.1.1 changes apply to every host by default and can make existing upload flows fail after an upgrade.

  • Deleted messages are tombstones (security fix): the API and realtime payloads carry no content, metadata, attachments or reactions for them, and an overseer can no longer read deleted content through GET /messages/{id}.
  • Upload gate: POST /attachments is 404 for a user with no participant row in any conversation.
  • Pending-upload quota: golem15.chat.pending_max_files (default 10; 0 or negative also means 10) and optional golem15.chat.pending_max_bytes (0 = off). Above it the upload is 422 errors.file (classes.ErrPendingQuota).
  • New chat:prune-pending, scheduled hourly through pact.HasSchedule, deletes unsent uploads older than golem15.chat.pending_ttl_hours (24), row and blob. It runs where the app runs a queue worker.
  • New chat-upload throttle bucket (20/min) on POST /attachments, on top of chat-api.
  • The default golem15.chat.upload_body_limit is 1048576 (1 MiB, the framework body limit), down from v0.1.0's 105906176. Hosts that accept larger files must set it.
  • Opt-in golem15.chat.max_message_bytes / Service.SetMaxMessageBytes (default 0 = off): attachments above the total are 422 errors.attachment_ids.
  • Opt-in contracts.LiveMembership and Service.IsParticipant.
  • Removing a reaction checks only the key shape (1-32 bytes); adding one still checks the configured list.
Description
SummerCMS Chat plugin (golem15.chat)
Readme 504 KiB
Languages
Go 100%