Documentation
¶
Overview ¶
Package audit provides an audit log plugin that records user actions within campaigns. Every significant mutation (entity CRUD, membership changes, campaign updates) is captured as an AuditEntry and persisted to the audit_log table. The activity feed gives campaign owners visibility into who changed what and when.
This is an optional plugin -- it does not modify campaign data, only records observations about changes made by other plugins.
Index ¶
Constants ¶
const ( // ActionEntityCreated is logged when a new entity is added to a campaign. ActionEntityCreated = "entity.created" // ActionEntityUpdated is logged when an entity's content or fields change. ActionEntityUpdated = "entity.updated" // ActionEntityDeleted is logged when an entity is removed from a campaign. ActionEntityDeleted = "entity.deleted" // ActionEntityClaimed is logged when a player claims ownership of a // (character) entity. Distinct from entity.updated so claims are filterable // and read legibly in the activity feed ("Alice claimed Tyne"). ActionEntityClaimed = "entity.claimed" // ActionEntityOwnerChanged is logged when an Owner/Scribe reassigns or // clears an entity's owner (the GM-side counterpart to a player claim). ActionEntityOwnerChanged = "entity.owner_changed" // ActionMemberJoined is logged when a user is added to a campaign. ActionMemberJoined = "member.joined" // ActionMemberLeft is logged when a user leaves or is removed from a campaign. ActionMemberLeft = "member.left" // ActionMemberRoleChanged is logged when a member's role is updated. ActionMemberRoleChanged = "member.role_changed" // ActionCampaignUpdated is logged when campaign settings are modified. ActionCampaignUpdated = "campaign.updated" // ActionEntityTypeCreated is logged when a new entity type is added to a campaign. ActionEntityTypeCreated = "entity_type.created" // ActionEntityTypeUpdated is logged when an entity type is modified. ActionEntityTypeUpdated = "entity_type.updated" // ActionEntityTypeDeleted is logged when an entity type is removed from a campaign. ActionEntityTypeDeleted = "entity_type.deleted" // hidden item their character holds. The armory plugin writes the string. ActionItemShared = "item.shared" // ActionTagCreated is logged when a new tag is added to a campaign. ActionTagCreated = "tag.created" // ActionTagDeleted is logged when a tag is removed from a campaign. ActionTagDeleted = "tag.deleted" // ActionTrashRestored is logged when the owner brings something back // from the campaign Trash. EntityType names the kind ("entity" for a // page, or the Trash kind such as "map"). ActionTrashRestored = "trash.restored" ActionCalendarCreated = "calendar.created" ActionCalendarUpdated = "calendar.updated" ActionCalendarDeleted = "calendar.deleted" ActionCalendarDefaultChanged = "calendar.default_changed" ActionCalendarMonthsSet = "calendar.months_set" ActionCalendarWeekdaysSet = "calendar.weekdays_set" ActionCalendarMoonsSet = "calendar.moons_set" ActionCalendarSeasonsSet = "calendar.seasons_set" ActionCalendarErasSet = "calendar.eras_set" // ActionCalendarAnchorSet records a change to the real-date anchor. It // is audited rather than treated as a preference because it silently // re-dates every schedulable thing on the calendar at once, with // nothing on screen to say why; who moved it and when is the only way // that is diagnosable. ActionCalendarAnchorSet = "calendar.anchor_set" ActionCalendarCategoriesSet = "calendar.categories_set" ActionCalendarVisibilityChanged = "calendar.visibility_changed" ActionCalendarEraCreated = "calendar.era_created" ActionCalendarEraUpdated = "calendar.era_updated" ActionCalendarEraDeleted = "calendar.era_deleted" ActionCalendarWeatherSet = "calendar.weather_set" ActionCalendarCyclesSet = "calendar.cycles_set" ActionCalendarFestivalsSet = "calendar.festivals_set" ActionCalendarWeatherZonesSet = "calendar.weather_zones_set" // ActionCalendarWeatherActiveZoneChanged covers SetActiveWeatherZone, // logged separately from SetWeatherZones. ActionCalendarWeatherActiveZoneChanged = "calendar.weather_active_zone_changed" ActionCalendarEventCreated = "calendar.event_created" ActionCalendarEventUpdated = "calendar.event_updated" ActionCalendarEventDeleted = "calendar.event_deleted" ActionCalendarEventVisibilityChanged = "calendar.event_visibility_changed" ActionCalendarDateAdvanced = "calendar.date_advanced" ActionCalendarTimeAdvanced = "calendar.time_advanced" ActionCalendarDateSet = "calendar.date_set" ActionCalendarImported = "calendar.imported" ActionTimelineCreated = "timeline.created" ActionTimelineUpdated = "timeline.updated" ActionTimelineDeleted = "timeline.deleted" ActionTimelineEventLinked = "timeline.event_linked" ActionTimelineEventUnlinked = "timeline.event_unlinked" ActionTimelineStandaloneEventCreated = "timeline.standalone_event_created" ActionTimelineStandaloneEventUpdated = "timeline.standalone_event_updated" ActionTimelineStandaloneEventDeleted = "timeline.standalone_event_deleted" ActionTimelineEntityGroupCreated = "timeline.entity_group_created" ActionTimelineEntityGroupUpdated = "timeline.entity_group_updated" ActionTimelineEntityGroupDeleted = "timeline.entity_group_deleted" ActionTimelineEntityGroupMemberAdded = "timeline.entity_group_member_added" ActionTimelineEntityGroupMemberRemoved = "timeline.entity_group_member_removed" ActionTimelineEventConnectionCreated = "timeline.event_connection_created" ActionTimelineEventConnectionDeleted = "timeline.event_connection_deleted" ActionTimelineVisibilityChanged = "timeline.visibility_changed" ActionTimelineEventLinkVisibilityChanged = "timeline.event_link_visibility_changed" )
Variables ¶
This section is empty.
Functions ¶
func RegisterRoutes ¶
func RegisterRoutes(e *echo.Echo, h *Handler, campaignSvc campaigns.CampaignService, authSvc auth.AuthService)
RegisterRoutes sets up all audit-related routes on the given Echo instance. All routes are campaign-scoped and require authentication plus campaign membership. The activity page is restricted to campaign owners (RoleOwner).
Types ¶
type AuditEntry ¶
type AuditEntry struct {
ID int64 `json:"id"`
CampaignID string `json:"campaignId"`
UserID string `json:"userId"`
Action string `json:"action"`
EntityType string `json:"entityType,omitempty"`
EntityID string `json:"entityId,omitempty"`
EntityName string `json:"entityName,omitempty"`
Details map[string]any `json:"details,omitempty"`
CreatedAt time.Time `json:"createdAt"`
// UserName is joined from the users table for display in the activity
// feed. Not stored in audit_log -- populated at query time.
UserName string `json:"userName,omitempty"`
}
AuditEntry represents a single recorded action in the audit log. Each entry ties a user action to a campaign and optionally to a specific entity. The Details map holds action-specific metadata (e.g., old/new values for updates).
type AuditRepository ¶
type AuditRepository interface {
// Log inserts a new audit entry into the database.
Log(ctx context.Context, entry *AuditEntry) error
// ListByCampaign returns paginated audit entries for a campaign, most
// recent first. Joins the users table to include display_name. Returns
// the entries, total count (for pagination), and any error.
ListByCampaign(ctx context.Context, campaignID string, limit, offset int) ([]AuditEntry, int, error)
// ListByEntity returns the most recent audit entries for a specific entity,
// scoped to campaignID so a foreign entity id can't read another campaign's
// change history (SEC-IDOR-2).
ListByEntity(ctx context.Context, entityID, campaignID string, limit int) ([]AuditEntry, error)
// CountByCampaign returns the total number of audit entries for a campaign.
CountByCampaign(ctx context.Context, campaignID string) (int, error)
// GetCampaignStats returns aggregate statistics for a campaign including
// entity count, approximate word count, last edit time, and active editors.
GetCampaignStats(ctx context.Context, campaignID string) (*CampaignStats, error)
}
AuditRepository defines the data access contract for audit log operations. All SQL lives in the concrete implementation -- no SQL leaks out.
func NewAuditRepository ¶
func NewAuditRepository(db *sql.DB) AuditRepository
NewAuditRepository creates a new repository backed by the given DB pool.
type AuditService ¶
type AuditService interface {
// Log records an audit entry. Designed to be fire-and-forget friendly:
// errors are logged but callers may choose to ignore them since audit
// failures should not block the primary operation.
Log(ctx context.Context, entry *AuditEntry) error
// GetCampaignActivity returns a paginated activity feed for a campaign.
// Returns entries, total count, and any error.
GetCampaignActivity(ctx context.Context, campaignID string, page int) ([]AuditEntry, int, error)
// GetEntityHistory returns the recent change history for a single entity,
// scoped to campaignID so it never returns another campaign's log (SEC-IDOR-2).
GetEntityHistory(ctx context.Context, entityID, campaignID string) ([]AuditEntry, error)
// GetCampaignStats returns aggregate statistics for a campaign including
// entity counts, word counts, and editor activity.
GetCampaignStats(ctx context.Context, campaignID string) (*CampaignStats, error)
}
AuditService handles business logic for the audit log. It validates inputs, enforces limits, and delegates persistence to the repository.
func NewAuditService ¶
func NewAuditService(repo AuditRepository) AuditService
NewAuditService creates a new audit service with the given repository.
type CampaignStats ¶
type CampaignStats struct {
// TotalEntities is the number of entities in the campaign.
TotalEntities int `json:"totalEntities"`
// TotalWords is an approximate word count across all entity HTML content.
// Computed by counting spaces in entry_html -- rough but fast.
TotalWords int64 `json:"totalWords"`
// LastEditedAt is the timestamp of the most recent audit log entry.
// Nil if the campaign has no activity yet.
LastEditedAt *time.Time `json:"lastEditedAt,omitempty"`
// ActiveEditors is the count of distinct users who performed actions
// in the campaign within the last 30 days.
ActiveEditors int `json:"activeEditors"`
}
CampaignStats holds aggregate statistics for a campaign's content and activity. Used on the activity page header to give owners a quick overview.
type EntityViewGuard ¶
type EntityViewGuard interface {
// ResolveEntityView returns the entity's campaign id and whether a viewer
// with the given role/user may see it. Returns an apperror (NotFound) when
// the entity does not exist.
ResolveEntityView(ctx context.Context, entityID string, role int, userID string) (campaignID string, canView bool, err error)
}
EntityViewGuard resolves an entity's campaign and whether the requesting member may view it. Injected from the entities plugin (adapter in app/routes.go) so the audit plugin never imports entities directly — mirrors the npcs.VisibilityToggler seam. When unset, EntityHistory still applies the unconditional campaign scope on the history query (the cross-campaign IDOR stays closed); only the per-entity visibility gate is skipped.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler handles HTTP requests for audit log operations. Handlers are thin: bind request, call service, render response. No business logic lives here.
func NewHandler ¶
func NewHandler(service AuditService) *Handler
NewHandler creates a new audit handler.
func (*Handler) Activity ¶
Activity redirects to the activity log on Campaign settings' Data tab. GET /campaigns/:id/activity
func (*Handler) ActivityFragment ¶
ActivityFragment returns an HTMX fragment with stats and timeline for the settings Activity tab. GET /campaigns/:id/activity/fragment
func (*Handler) EmbedActivity ¶
EmbedActivity returns an HTMX fragment for the dashboard activity feed block. Shows recent campaign activity entries in a compact feed format. GET /campaigns/:id/activity/embed
func (*Handler) EntityHistory ¶
EntityHistory returns JSON history for a specific entity (GET /campaigns/:id/entities/:eid/history). Used by HTMX or API clients to display per-entity change logs.
func (*Handler) SetEntityViewGuard ¶
func (h *Handler) SetEntityViewGuard(g EntityViewGuard)
SetEntityViewGuard injects the guard EntityHistory uses to enforce campaign ownership + per-entity visibility on the requested entity (SEC-IDOR-2).