Self-hosted email delivery platform that enables applications to send emails via HTTP APIs while handling SMTP delivery, templates, storage, security, and analytics. Fully self-hostable alternative to services like SendGrid or Mailgun.
Go email-relayemail-routinghttp-to-smtpmail-deliverymailchimp-alternativemailgun-alternativemailsendermailservermailtemplatemailtestpostmark-alternativesend-emailsendgrid-alternativesendmailtransactional-emailtransactional-outbox
feat(events): workspace-scoped audit trail with detail views
Jonas Kanindacde0cbec2044
diff --git a/internal/handlers/api_key_handler.go b/internal/handlers/api_key_handler.goindex b8966db..57191c7 100644--- a/internal/handlers/api_key_handler.go+++ b/internal/handlers/api_key_handler.go@@ -108,9 +108,9 @@ func (h *APIKeyHandler) Create(c *okapi.Context, req *CreateAPIKeyRequest) errorreturn c.AbortInternalServerError("failed to create API key", err)}- h.audit.Log(scope.UserID, c.GetString("email"), c.RealIP(), "apikey.created", "API key created: "+req.Body.Name, nil)+ h.audit.LogCtx(c, "apikey.created", "API key created: "+req.Body.Name, nil)- // Send API key created notification (best-effort)+ // Send API key created notificationif h.notifier != nil {expiresStr := "Never"if key.ExpiresAt != nil {@@ -161,7 +161,7 @@ func (h *APIKeyHandler) Revoke(c *okapi.Context, req *RevokeAPIKeyRequest) errorreturn c.AbortInternalServerError("failed to revoke API key")}- h.audit.Log(key.UserID, c.GetString("email"), c.RealIP(), "apikey.revoked", "API key revoked: "+key.Name, nil)+ h.audit.LogCtx(c, "apikey.revoked", "API key revoked: "+key.Name, nil)return ok(c, okapi.M{"message": "API key revoked"})}@@ -184,7 +184,7 @@ func (h *APIKeyHandler) Delete(c *okapi.Context, req *DeleteAPIKeyRequest) errorreturn c.AbortInternalServerError("failed to delete API key")}- h.audit.Log(key.UserID, c.GetString("email"), c.RealIP(), "apikey.deleted", "API key deleted: "+key.Name, nil)+ h.audit.LogCtx(c, "apikey.deleted", "API key deleted: "+key.Name, nil)return ok(c, okapi.M{"message": "API key deleted"})}diff --git a/internal/handlers/event_handler.go b/internal/handlers/event_handler.goindex 887c9a2..fc6c58c 100644--- a/internal/handlers/event_handler.go+++ b/internal/handlers/event_handler.go@@ -41,6 +41,19 @@ func NewEventHandler(repo *repositories.EventRepository, bus *eventbus.EventBus)return &EventHandler{repo: repo, bus: bus}}+type EventRequest struct {+ ID int `param:"id"`+}++// Get returns a single event by ID (admin scope, any category or workspace).+func (h *EventHandler) Get(c *okapi.Context, req *EventRequest) error {+ event, err := h.repo.FindByID(uint(req.ID))+ if err != nil {+ return c.AbortNotFound("event not found")+ }+ return ok(c, event)+}+// List returns paginated historical events.func (h *EventHandler) List(c *okapi.Context, req *ListEventsRequest) error {page, size, offset := normalizePageParams(req.Page, req.Size)@@ -66,7 +79,7 @@ func (h *EventHandler) UserAuditLog(c *okapi.Context, req *ListEventsRequest) eruserID := c.GetInt("user_id")page, size, offset := normalizePageParams(req.Page, req.Size)- events, total, err := h.repo.FindByActorAndCategory(uint(userID), models.EventCategoryAudit, size, offset)+ events, total, err := h.repo.FindPersonalByActorAndCategory(uint(userID), models.EventCategoryAudit, size, offset)if err != nil {return c.AbortInternalServerError("failed to list audit events")}@@ -86,6 +99,27 @@ func (h *EventHandler) WorkspaceAuditLog(c *okapi.Context, req *ListEventsRequesreturn paginated(c, events, total, page, size)}+type AuditEventRequest struct {+ ID int `param:"id"`+}++// WorkspaceAuditLogDetail returns a single audit event scoped to the current workspace.+func (h *EventHandler) WorkspaceAuditLogDetail(c *okapi.Context, req *AuditEventRequest) error {+ wsID := uint(c.GetInt("workspace_id"))++ event, err := h.repo.FindByID(uint(req.ID))+ if err != nil {+ return c.AbortNotFound("audit event not found")+ }++ // Only expose audit events that belong to the current workspace.+ if event.Category != models.EventCategoryAudit || event.WorkspaceID == nil || *event.WorkspaceID != wsID {+ return c.AbortNotFound("audit event not found")+ }++ return ok(c, event)+}+// Stream sends real-time events to the admin via SSE.func (h *EventHandler) Stream(c *okapi.Context) error {ctx := c.Request().Context()diff --git a/internal/handlers/smtp_handler.go b/internal/handlers/smtp_handler.goindex 9b35338..b4ecce2 100644--- a/internal/handlers/smtp_handler.go+++ b/internal/handlers/smtp_handler.go@@ -165,7 +165,7 @@ func (h *SMTPHandler) Create(c *okapi.Context, req *CreateSMTPRequest) error {return c.AbortInternalServerError("failed to create SMTP server", err)}- h.audit.Log(scope.UserID, c.GetString("email"), c.RealIP(), "smtp.created", "SMTP server created: "+req.Body.Host, nil)+ h.audit.LogCtx(c, "smtp.created", "SMTP server created: "+req.Body.Host, nil)return created(c, server)}@@ -256,7 +256,7 @@ func (h *SMTPHandler) Update(c *okapi.Context, req *UpdateSMTPRequest) error {return c.AbortInternalServerError("failed to update SMTP server")}- h.audit.Log(server.UserID, c.GetString("email"), c.RealIP(), "smtp.updated", "SMTP server updated: "+server.Host, nil)+ h.audit.LogCtx(c, "smtp.updated", "SMTP server updated: "+server.Host, nil)return ok(c, server)}@@ -285,7 +285,7 @@ func (h *SMTPHandler) Delete(c *okapi.Context, req *DeleteSMTPRequest) error {return c.AbortInternalServerError("failed to delete SMTP server")}- h.audit.Log(server.UserID, c.GetString("email"), c.RealIP(), "smtp.deleted", "SMTP server deleted: "+server.Host, nil)+ h.audit.LogCtx(c, "smtp.deleted", "SMTP server deleted: "+server.Host, nil)return noContent(c)}diff --git a/internal/handlers/webhook_handler.go b/internal/handlers/webhook_handler.goindex dae876a..e5b88ec 100644--- a/internal/handlers/webhook_handler.go+++ b/internal/handlers/webhook_handler.go@@ -72,7 +72,7 @@ func (h *WebhookHandler) Create(c *okapi.Context, req *CreateWebhookRequest) errreturn c.AbortInternalServerError("failed to create webhook", err)}- h.audit.Log(scope.UserID, c.GetString("email"), c.RealIP(), "webhook.created", "Webhook created: "+req.Body.URL, nil)+ h.audit.LogCtx(c, "webhook.created", "Webhook created: "+req.Body.URL, nil)return created(c, wh)}@@ -101,7 +101,7 @@ func (h *WebhookHandler) Delete(c *okapi.Context, req *DeleteWebhookRequest) errreturn c.AbortInternalServerError("failed to delete webhook")}- h.audit.Log(wh.UserID, c.GetString("email"), c.RealIP(), "webhook.deleted", "Webhook deleted: "+wh.URL, nil)+ h.audit.LogCtx(c, "webhook.deleted", "Webhook deleted: "+wh.URL, nil)return noContent(c)}diff --git a/internal/handlers/workspace_handler.go b/internal/handlers/workspace_handler.goindex bde0c6f..6733226 100644--- a/internal/handlers/workspace_handler.go+++ b/internal/handlers/workspace_handler.go@@ -26,6 +26,7 @@ import ("time""github.com/goposta/posta/internal/models"+ "github.com/goposta/posta/internal/services/audit""github.com/goposta/posta/internal/services/notification""github.com/goposta/posta/internal/storage/repositories""github.com/jkaninda/okapi"@@ -39,6 +40,7 @@ type WorkspaceHandler struct {planService planServicenotifier *notification.ServiceappURL string+ audit *audit.Logger}// planService is an optional interface for resolving workspace plans and quotas.@@ -184,6 +186,8 @@ func (h *WorkspaceHandler) Create(c *okapi.Context, req *CreateWorkspaceRequest)return c.AbortInternalServerError("failed to add workspace member")}+ h.logAudit(c, ws.ID, "workspace.created", "Workspace created: "+ws.Name, map[string]any{"slug": ws.Slug})+return created(c, WorkspaceResponse{ID: ws.ID,Name: ws.Name,@@ -271,6 +275,8 @@ func (h *WorkspaceHandler) Update(c *okapi.Context, req *UpdateWorkspaceRequest)return c.AbortInternalServerError("failed to update workspace")}+ h.logAudit(c, ws.ID, "workspace.updated", "Workspace updated: "+ws.Name, nil)+role := c.GetString("workspace_role")return ok(c, WorkspaceResponse{@@ -300,6 +306,8 @@ func (h *WorkspaceHandler) Delete(c *okapi.Context) error {return c.AbortInternalServerError("failed to delete workspace")}+ h.logAudit(c, ws.ID, "workspace.deleted", "Workspace deleted: "+ws.Name, map[string]any{"slug": ws.Slug})+return noContent(c)}@@ -349,6 +357,10 @@ func (h *WorkspaceHandler) UpdateMemberRole(c *okapi.Context, req *UpdateMemberRreturn c.AbortInternalServerError("failed to update member role")}+ h.logAudit(c, uint(wsID), "member.role_updated",+ fmt.Sprintf("Member role changed from %s to %s", oldRole, req.Body.Role),+ map[string]any{"member_user_id": req.MemberID, "old_role": string(oldRole), "new_role": string(req.Body.Role)})+// Send role change notification (best-effort)if h.notifier != nil && req.Body.Role != oldRole {ws, _ := h.workspaceRepo.FindByID(uint(wsID))@@ -394,6 +406,9 @@ func (h *WorkspaceHandler) RemoveMember(c *okapi.Context, req *RemoveWorkspaceMereturn c.AbortInternalServerError("failed to remove member")}+ h.logAudit(c, uint(wsID), "member.removed", "Member removed from workspace",+ map[string]any{"member_user_id": req.MemberID, "role": string(member.Role)})+return noContent(c)}@@ -436,6 +451,9 @@ func (h *WorkspaceHandler) InviteMember(c *okapi.Context, req *InviteMemberRequereturn c.AbortInternalServerError("failed to create invitation")}+ h.logAudit(c, uint(wsID), "member.invited", "Invitation sent to "+email,+ map[string]any{"email": email, "role": string(req.Body.Role)})+// Send invitation email (best-effort, don't fail the request)if h.notifier != nil {ws, _ := h.workspaceRepo.FindByID(uint(wsID))@@ -507,10 +525,18 @@ type DeleteInvitationRequest struct {}func (h *WorkspaceHandler) DeleteInvitation(c *okapi.Context, req *DeleteInvitationRequest) error {+ inv, err := h.workspaceRepo.FindInvitationByID(uint(req.InvitationID))+ if err != nil {+ return c.AbortNotFound("invitation not found")+ }+if err := h.workspaceRepo.DeleteInvitation(uint(req.InvitationID)); err != nil {return c.AbortNotFound("invitation not found")}+ h.logAudit(c, inv.WorkspaceID, "invitation.revoked", "Invitation revoked for "+inv.Email,+ map[string]any{"email": inv.Email})+return noContent(c)}@@ -585,6 +611,9 @@ func (h *WorkspaceHandler) AcceptInvitation(c *okapi.Context, req *AcceptInvitatinv.Status = models.InvitationStatusAccepted_ = h.workspaceRepo.UpdateInvitation(inv)+ h.logAudit(c, inv.WorkspaceID, "member.joined", "Joined workspace "+inv.Workspace.Name,+ map[string]any{"role": string(inv.Role)})+return ok(c, okapi.M{"message": fmt.Sprintf("joined workspace %q", inv.Workspace.Name),"workspace_id": inv.WorkspaceID,@@ -645,6 +674,9 @@ func (h *WorkspaceHandler) AcceptInvitationByID(c *okapi.Context, req *AcceptInvinv.Status = models.InvitationStatusAccepted_ = h.workspaceRepo.UpdateInvitation(inv)+ h.logAudit(c, inv.WorkspaceID, "member.joined", "Joined workspace "+inv.Workspace.Name,+ map[string]any{"role": string(inv.Role)})+return ok(c, okapi.M{"message": fmt.Sprintf("joined workspace %q", inv.Workspace.Name),"workspace_id": inv.WorkspaceID,@@ -731,6 +763,17 @@ func (h *WorkspaceHandler) SetNotifier(n *notification.Service, appURL string) {h.appURL = appURL}+func (h *WorkspaceHandler) SetAuditLogger(l *audit.Logger) {+ h.audit = l+}++func (h *WorkspaceHandler) logAudit(c *okapi.Context, workspaceID uint, action, message string, metadata map[string]any) {+ if h.audit == nil {+ return+ }+ h.audit.LogCtxScoped(c, workspaceID, action, message, metadata)+}+// GetPlan returns the effective plan for the current workspace.func (h *WorkspaceHandler) GetPlan(c *okapi.Context) error {wsID := uint(c.GetInt("workspace_id"))diff --git a/internal/models/email.go b/internal/models/email.goindex 4ff454d..1699374 100644--- a/internal/models/email.go+++ b/internal/models/email.go@@ -52,16 +52,14 @@ type Email struct {ListUnsubscribeURL string `json:"list_unsubscribe_url,omitempty" gorm:"type:text"`ListUnsubscribeMailto string `json:"list_unsubscribe_mailto,omitempty" gorm:"type:text"`ListUnsubscribePost bool `json:"list_unsubscribe_post,omitempty"`- // UnsubscribeListID scopes a one-click unsubscribe to a single UnsubscribeList.- // nil ⇒ a click suppresses globally (legacy links only).- UnsubscribeListID *uint `json:"unsubscribe_list_id,omitempty" gorm:"index"`- Status EmailStatus `json:"status" gorm:"default:pending;not null"`- ErrorMessage string `json:"error_message"`- RetryCount int `json:"retry_count" gorm:"default:0;not null"`- CreatedAt time.Time `json:"created_at"`- SentAt *time.Time `json:"sent_at"`- ScheduledAt *time.Time `json:"scheduled_at"`- Provider string `json:"provider,omitempty" gorm:"index;size:32"`+ UnsubscribeListID *uint `json:"unsubscribe_list_id,omitempty" gorm:"index"`+ Status EmailStatus `json:"status" gorm:"default:pending;not null"`+ ErrorMessage string `json:"error_message"`+ RetryCount int `json:"retry_count" gorm:"default:0;not null"`+ CreatedAt time.Time `json:"created_at"`+ SentAt *time.Time `json:"sent_at"`+ ScheduledAt *time.Time `json:"scheduled_at"`+ Provider string `json:"provider,omitempty" gorm:"index;size:32"`SMTPHostname string `json:"smtp_hostname,omitempty"`diff --git a/internal/routes/admin_routes.go b/internal/routes/admin_routes.goindex f516085..11ee5d2 100644--- a/internal/routes/admin_routes.go+++ b/internal/routes/admin_routes.go@@ -208,6 +208,16 @@ func (r *Router) adminRoutes() []okapi.RouteDefinition {Request: &handlers.ListEventsRequest{},Response: &dto.PageableResponse[models.Event]{},},+ {+ Method: http.MethodGet,+ Path: "/events/{id:int}",+ Handler: okapi.H(r.h.event.Get),+ Group: adminGroup,+ Summary: "Get event",+ Description: "Returns a single platform event by ID",+ Request: &handlers.EventRequest{},+ Response: &dto.Response[models.Event]{},+ },// ==================== Metrics & Analytics ===================={diff --git a/internal/routes/admin_sse_route_order_test.go b/internal/routes/admin_sse_route_order_test.gonew file mode 100644index 0000000..3bd544a--- /dev/null+++ b/internal/routes/admin_sse_route_order_test.go@@ -0,0 +1,54 @@+/*+ * Copyright 2026 Jonas Kaninda+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ */++package routes++import (+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/jkaninda/okapi"+)++func TestAdminEventsStreamNotShadowedByParamRoute(t *testing.T) {+ o := okapi.NewTestServer(t)++ o.Get("/admin/events/stream", func(c *okapi.Context) error {+ return c.String(http.StatusOK, "stream")+ })+ o.Get("/admin/events/{id:int}", func(c *okapi.Context) error {+ return c.String(http.StatusOK, "detail")+ })++ cases := map[string]string{+ "/admin/events/stream": "stream",+ "/admin/events/42": "detail",+ }+ for path, want := range cases {+ req := httptest.NewRequest(http.MethodGet, path, nil)+ rec := httptest.NewRecorder()+ o.ServeHTTP(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("%s: status = %d, want 200", path, rec.Code)+ }+ if got := rec.Body.String(); got != want {+ t.Errorf("%s: handler = %q, want %q (route shadowing regression)", path, got, want)+ }+ }+}diff --git a/internal/routes/routes.go b/internal/routes/routes.goindex 63e794d..d6331c8 100644--- a/internal/routes/routes.go+++ b/internal/routes/routes.go@@ -274,6 +274,7 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *cr.h.plan = handlers.NewPlanHandler(planRepo, workspaceRepo, userRepo, planService, auditLogger)r.h.admin.SetWorkspaceRepo(workspaceRepo, planRepo)r.h.workspace.SetPlanService(planService)+ r.h.workspace.SetAuditLogger(auditLogger)r.h.apiKey.SetQuota(planService, db)r.h.domain.SetQuota(planService, db)r.h.smtp.SetQuota(planService, db)@@ -464,8 +465,9 @@ func (r *Router) registerRoutes() {r.app.Register(r.inboundWebhookRoutes()...)r.app.Register(r.inboundWorkspaceRoutes()...)}- r.app.Register(r.adminRoutes()...)+r.app.Register(r.adminSSERoutes()...)+ r.app.Register(r.adminRoutes()...)// Documentation-only OpenAPI webhooks (events Posta POSTs to subscribers).r.registerWebhookDocs()diff --git a/internal/routes/workspace_routes.go b/internal/routes/workspace_routes.goindex cbd0cf9..720c24c 100644--- a/internal/routes/workspace_routes.go+++ b/internal/routes/workspace_routes.go@@ -229,6 +229,18 @@ func (r *Router) workspaceRoutes() []okapi.RouteDefinition {Response: &dto.PageableResponse[models.Event]{},Options: []okapi.RouteOption{workspaceHeaderRequired},},+ {+ Method: http.MethodGet,+ Path: "/audit-log/{id:int}",+ Handler: okapi.H(r.h.event.WorkspaceAuditLogDetail),+ Group: wsGroup,+ Middlewares: []okapi.Middleware{middlewares.RequireWorkspaceRole(models.WorkspaceRoleAdmin)},+ Summary: "Get workspace audit event",+ Description: "Returns a single audit event for the current workspace (admin/owner only)",+ Request: &handlers.AuditEventRequest{},+ Response: &dto.Response[models.Event]{},+ Options: []okapi.RouteOption{workspaceHeaderRequired},+ },// Data Export/Import{diff --git a/internal/services/audit/audit.go b/internal/services/audit/audit.goindex 768ca85..9f00d03 100644--- a/internal/services/audit/audit.go+++ b/internal/services/audit/audit.go@@ -20,6 +20,7 @@ package auditimport ("github.com/goposta/posta/internal/models""github.com/goposta/posta/internal/services/eventbus"+ "github.com/jkaninda/okapi")// Logger records audit trail events via the existing event bus.@@ -32,7 +33,30 @@ func NewLogger(bus *eventbus.EventBus) *Logger {return &Logger{bus: bus}}-// Log records an audit event with the given actor, action type, message, and optional metadata.func (l *Logger) Log(actorID uint, actorEmail, clientIP, action, message string, metadata map[string]any) {- l.bus.PublishSimple(models.EventCategoryAudit, action, &actorID, actorEmail, clientIP, message, metadata)+ l.LogScoped(nil, actorID, actorEmail, clientIP, action, message, metadata)+}++func (l *Logger) LogScoped(workspaceID *uint, actorID uint, actorEmail, clientIP, action, message string, metadata map[string]any) {+ l.bus.PublishScoped(workspaceID, models.EventCategoryAudit, action, &actorID, actorEmail, clientIP, message, metadata)+}++func (l *Logger) LogCtx(c *okapi.Context, action, message string, metadata map[string]any) {+ l.LogScoped(ctxWorkspaceID(c), actorID(c), c.GetString("email"), c.RealIP(), action, message, metadata)+}++func (l *Logger) LogCtxScoped(c *okapi.Context, workspaceID uint, action, message string, metadata map[string]any) {+ l.LogScoped(&workspaceID, actorID(c), c.GetString("email"), c.RealIP(), action, message, metadata)+}++func actorID(c *okapi.Context) uint {+ return uint(c.GetInt("user_id"))+}++func ctxWorkspaceID(c *okapi.Context) *uint {+ if w := c.GetInt("workspace_id"); w > 0 {+ id := uint(w)+ return &id+ }+ return nil}diff --git a/internal/services/eventbus/eventbus.go b/internal/services/eventbus/eventbus.goindex 4c7fc46..7c32efd 100644--- a/internal/services/eventbus/eventbus.go+++ b/internal/services/eventbus/eventbus.go@@ -59,8 +59,11 @@ func (b *EventBus) Publish(event *models.Event) {}}-// PublishSimple is a convenience method for emitting events with JSON metadata.func (b *EventBus) PublishSimple(category models.EventCategory, eventType string, actorID *uint, actorName, clientIP, message string, meta map[string]any) {+ b.PublishScoped(nil, category, eventType, actorID, actorName, clientIP, message, meta)+}++func (b *EventBus) PublishScoped(workspaceID *uint, category models.EventCategory, eventType string, actorID *uint, actorName, clientIP, message string, meta map[string]any) {var metaStr stringif meta != nil {if data, err := json.Marshal(meta); err == nil {@@ -69,13 +72,14 @@ func (b *EventBus) PublishSimple(category models.EventCategory, eventType string}b.Publish(&models.Event{- Category: category,- Type: eventType,- ActorID: actorID,- ActorName: actorName,- ClientIP: clientIP,- Message: message,- Metadata: metaStr,+ Category: category,+ Type: eventType,+ WorkspaceID: workspaceID,+ ActorID: actorID,+ ActorName: actorName,+ ClientIP: clientIP,+ Message: message,+ Metadata: metaStr,})}diff --git a/internal/storage/repositories/event_repo.go b/internal/storage/repositories/event_repo.goindex f9e9ca7..ff61caf 100644--- a/internal/storage/repositories/event_repo.go+++ b/internal/storage/repositories/event_repo.go@@ -36,6 +36,15 @@ func (r *EventRepository) Create(event *models.Event) error {return r.db.Create(event).Error}+// FindByID returns a single event by its primary key.+func (r *EventRepository) FindByID(id uint) (*models.Event, error) {+ var event models.Event+ if err := r.db.First(&event, id).Error; err != nil {+ return nil, err+ }+ return &event, nil+}+func (r *EventRepository) FindAll(limit, offset int) ([]models.Event, int64, error) {var events []models.Eventvar total int64@@ -50,13 +59,13 @@ func (r *EventRepository) FindAll(limit, offset int) ([]models.Event, int64, errreturn events, total, nil}-func (r *EventRepository) FindByActorAndCategory(actorID uint, category models.EventCategory, limit, offset int) ([]models.Event, int64, error) {+func (r *EventRepository) FindPersonalByActorAndCategory(actorID uint, category models.EventCategory, limit, offset int) ([]models.Event, int64, error) {var events []models.Eventvar total int64- r.db.Model(&models.Event{}).Where("actor_id = ? AND category = ?", actorID, category).Count(&total)+ r.db.Model(&models.Event{}).Where("actor_id = ? AND category = ? AND workspace_id IS NULL", actorID, category).Count(&total)- if err := r.db.Where("actor_id = ? AND category = ?", actorID, category).+ if err := r.db.Where("actor_id = ? AND category = ? AND workspace_id IS NULL", actorID, category).Order("created_at DESC").Limit(limit).Offset(offset).Find(&events).Error; err != nil {@@ -112,8 +121,6 @@ func (r *EventRepository) FindByWorkspaceAndCategory(workspaceID uint, categoryreturn events, total, nil}-// DeleteOlderThan deletes event records older than the given time.-// Returns the number of rows deleted.func (r *EventRepository) DeleteOlderThan(before time.Time) (int64, error) {result := r.db.Where("created_at < ?", before).Delete(&models.Event{})return result.RowsAffected, result.Errordiff --git a/web/src/api/admin.ts b/web/src/api/admin.tsindex 04b99d2..3ca8197 100644--- a/web/src/api/admin.ts+++ b/web/src/api/admin.ts@@ -49,6 +49,9 @@ export const adminApi = {if (category) params.category = categoryreturn api.get<PaginatedResponse<Event>>('/admin/events', { params })},+ getEvent(id: number) {+ return api.get<ApiResponse<Event>>(`/admin/events/${id}`)+ },listJobs() {return api.get<ApiResponse<CronJob[]>>('/admin/jobs')},diff --git a/web/src/api/audit.ts b/web/src/api/audit.tsindex 12ba0b1..abbe084 100644--- a/web/src/api/audit.ts+++ b/web/src/api/audit.ts@@ -3,10 +3,16 @@ import type { PaginatedResponse, Event } from './types'export const auditApi = {// Workspace audit log. The X-Posta-Workspace-Id header (injected by the- // workspace store) scopes this to the active workspace.- list(page = 0, size = 20, category?: string) {- const params: Record<string, any> = { page, size }- if (category) params.category = category- return api.get<PaginatedResponse<Event>>('/workspaces/current/audit-log', { params })+ // workspace store) scopes this to the active workspace. The endpoint always+ // returns audit-category events for the workspace.+ list(page = 0, size = 20) {+ return api.get<PaginatedResponse<Event>>('/workspaces/current/audit-log', {+ params: { page, size },+ })+ },++ // A single audit event for the active workspace.+ get(id: number) {+ return api.get<{ success: boolean; data: Event }>(`/workspaces/current/audit-log/${id}`)},}diff --git a/web/src/api/types.ts b/web/src/api/types.tsindex 003b10f..4ffa4d7 100644--- a/web/src/api/types.ts+++ b/web/src/api/types.ts@@ -513,8 +513,9 @@ export interface WorkerDetail {export interface Event {id: number- category: 'user' | 'email' | 'system'+ category: 'user' | 'email' | 'system' | 'audit'type: string+ workspace_id?: number | nullactor_id: number | nullactor_name: stringclient_ip?: stringdiff --git a/web/src/layouts/DashboardLayout.vue b/web/src/layouts/DashboardLayout.vueindex b98b5df..ca42d78 100644--- a/web/src/layouts/DashboardLayout.vue+++ b/web/src/layouts/DashboardLayout.vue@@ -184,6 +184,7 @@ const navSections: NavSection[] = [{ name: 'All Workspaces', path: '/workspaces', icon: 'layers' },{ name: 'Members', path: '', icon: 'users', workspaceSubpath: 'members', hideInPersonal: true },{ name: 'Plan & Billing', path: '', icon: 'credit-card', workspaceTab: 'plan', hideInPersonal: true },+ { name: 'Audit Log', path: '/audit-log', icon: 'history' },{ name: 'Settings', path: '', icon: 'settings', workspaceTab: 'settings', requiresWorkspaceAdmin: true },],},@@ -478,17 +479,6 @@ function getIcon(name: string): string {</svg>Settings</a>- <a class="user-dropdown-item" @click.stop="navigate('/audit-log'); userMenuOpen = false">- <svg width="15" height="15" viewBox="0 0 16 16" fill="none">- <path d="M2 8a6 6 0 102.7-5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"- stroke-linejoin="round" />- <path d="M2 12V8.7h3.3" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"- stroke-linejoin="round" />- <path d="M8 4.7V8l2 1.3" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"- stroke-linejoin="round" />- </svg>- Audit Log- </a><div class="user-dropdown-divider"></div><div class="user-dropdown-theme"><div class="user-dropdown-theme-label">diff --git a/web/src/router/index.ts b/web/src/router/index.tsindex d6cf152..2290893 100644--- a/web/src/router/index.ts+++ b/web/src/router/index.ts@@ -73,6 +73,7 @@ const routes = [{ path: 'campaigns/:id', name: 'campaign-detail', component: () => import('../views/campaigns/CampaignDetail.vue'), meta: { title: 'Campaign' } },{ path: 'analytics', name: 'analytics', component: () => import('../views/analytics/Analytics.vue'), meta: { title: 'Analytics' } },{ path: 'audit-log', name: 'audit-log', component: () => import('../views/audit/AuditLog.vue'), meta: { title: 'Audit Log' } },+ { path: 'audit-log/:id', name: 'audit-log-detail', component: () => import('../views/audit/AuditLogDetail.vue'), meta: { title: 'Audit Event' } },{ path: 'settings', name: 'settings', component: () => import('../views/settings/Settings.vue'), meta: { title: 'Settings' } },{ path: 'workspaces', name: 'workspaces', component: () => import('../views/workspaces/Workspaces.vue'), meta: { title: 'Workspaces' } },{ path: 'workspaces/:id', name: 'workspace-detail', component: () => import('../views/workspaces/WorkspaceSettings.vue'), meta: { title: 'Workspace Settings' } },@@ -85,6 +86,7 @@ const routes = [{ path: 'admin/users/:id', name: 'admin-user-detail', component: () => import('../views/admin/UserDetail.vue'), meta: { admin: true, title: 'Admin · User' } },{ path: 'admin/metrics', name: 'admin-metrics', component: () => import('../views/admin/Metrics.vue'), meta: { admin: true, title: 'Admin · Metrics' } },{ path: 'admin/events', name: 'admin-events', component: () => import('../views/admin/Events.vue'), meta: { admin: true, title: 'Admin · Events' } },+ { path: 'admin/events/:id', name: 'admin-event-detail', component: () => import('../views/admin/EventDetail.vue'), meta: { admin: true, title: 'Admin · Event' } },{ path: 'admin/plans', name: 'admin-plans', component: () => import('../views/admin/Plans.vue'), meta: { admin: true, title: 'Admin · Plans' } },{ path: 'admin/plans/:id', name: 'admin-plan-detail', component: () => import('../views/admin/PlanDetail.vue'), meta: { admin: true, title: 'Admin · Plan' } },{ path: 'admin/servers', name: 'admin-servers', component: () => import('../views/admin/Servers.vue'), meta: { admin: true, title: 'Admin · Servers' } },diff --git a/web/src/views/admin/EventDetail.vue b/web/src/views/admin/EventDetail.vuenew file mode 100644index 0000000..8d67cee--- /dev/null+++ b/web/src/views/admin/EventDetail.vue@@ -0,0 +1,159 @@+<script setup lang="ts">+import { ref, computed, onMounted } from 'vue'+import { useRoute, useRouter } from 'vue-router'+import { adminApi } from '../../api/admin'+import type { Event } from '../../api/types'+import { useNotificationStore } from '../../stores/notification'++const route = useRoute()+const router = useRouter()+const notify = useNotificationStore()++const loading = ref(true)+const event = ref<Event | null>(null)++onMounted(async () => {+ try {+ const id = Number(route.params.id)+ const res = await adminApi.getEvent(id)+ event.value = res.data.data+ } catch {+ notify.error('Failed to load event')+ } finally {+ loading.value = false+ }+})++function formatDate(dateStr: string): string {+ return new Date(dateStr).toLocaleString()+}++function categoryBadgeClass(cat: string) {+ switch (cat) {+ case 'user': return 'badge badge-info'+ case 'email': return 'badge badge-success'+ case 'system': return 'badge badge-warning'+ default: return 'badge badge-neutral'+ }+}++// Pretty-print the JSON metadata blob; fall back to the raw string if it+// isn't valid JSON (or empty).+const prettyMetadata = computed(() => {+ const raw = event.value?.metadata+ if (!raw) return ''+ try {+ return JSON.stringify(JSON.parse(raw), null, 2)+ } catch {+ return raw+ }+})+</script>++<template>+ <div>+ <div class="page-header">+ <h1>Event</h1>+ <div style="display: flex; gap: 8px">+ <button class="btn btn-secondary" @click="router.push('/admin/events')">Back to Events</button>+ </div>+ </div>++ <div v-if="loading" class="loading-page">+ <div class="spinner"></div>+ </div>++ <div v-else-if="!event" class="card">+ <div class="empty-state">+ <h3>Event not found</h3>+ <p>This event may have been removed by the retention policy.</p>+ </div>+ </div>++ <template v-else>+ <div class="card" style="margin-bottom: 24px">+ <div class="card-header">+ <h2><code>{{ event.type }}</code></h2>+ <span :class="categoryBadgeClass(event.category)">{{ event.category }}</span>+ </div>+ <div class="card-body">+ <dl class="detail-grid">+ <dt>Event ID</dt>+ <dd><code>{{ event.id }}</code></dd>++ <dt>Date</dt>+ <dd>{{ formatDate(event.created_at) }}</dd>++ <dt>Category</dt>+ <dd>{{ event.category }}</dd>++ <dt>Type</dt>+ <dd><code>{{ event.type }}</code></dd>++ <dt>Workspace</dt>+ <dd><code v-if="event.workspace_id">#{{ event.workspace_id }}</code><span v-else>— (platform)</span></dd>++ <dt>Actor</dt>+ <dd>{{ event.actor_name || '—' }}<span v-if="event.actor_id"> (#{{ event.actor_id }})</span></dd>++ <dt>IP Address</dt>+ <dd><code v-if="event.client_ip">{{ event.client_ip }}</code><span v-else>—</span></dd>++ <dt>Message</dt>+ <dd class="detail-message">{{ event.message }}</dd>+ </dl>+ </div>+ </div>++ <div class="card">+ <div class="card-header">+ <h2>Metadata</h2>+ </div>+ <div class="card-body">+ <div v-if="!prettyMetadata" class="empty-state">+ <p>No additional metadata for this event.</p>+ </div>+ <pre v-else class="metadata-block">{{ prettyMetadata }}</pre>+ </div>+ </div>+ </template>+ </div>+</template>++<style scoped>+.detail-grid {+ display: grid;+ grid-template-columns: 160px 1fr;+ gap: 12px 16px;+ margin: 0;+}++.detail-grid dt {+ font-size: 13px;+ font-weight: 600;+ color: var(--text-muted);+}++.detail-grid dd {+ margin: 0;+ font-size: 14px;+ color: var(--text-primary);+ word-break: break-word;+}++.detail-message {+ white-space: pre-wrap;+}++.metadata-block {+ margin: 0;+ padding: 12px 14px;+ background: var(--bg-secondary);+ border: 1px solid var(--border-primary);+ border-radius: var(--radius-sm);+ font-size: 13px;+ overflow-x: auto;+ white-space: pre-wrap;+ word-break: break-word;+}+</style>diff --git a/web/src/views/admin/Events.vue b/web/src/views/admin/Events.vueindex 032ebcf..4801d8c 100644--- a/web/src/views/admin/Events.vue+++ b/web/src/views/admin/Events.vue@@ -1,11 +1,13 @@<script setup lang="ts">import { ref, onMounted, onBeforeUnmount } from 'vue'+import { useRouter } from 'vue-router'import { adminApi } from '../../api/admin'import { useAuthStore } from '../../stores/auth'-import type { Event, Pageable } from '../../api/types'+import type { Event } from '../../api/types'import { usePagination } from '@/composables/usePagination'import Pagination from '@/components/Pagination.vue'const auth = useAuthStore()+const router = useRouter()const loading = ref(true)const events = ref<Event[]>([])const page = ref(0)@@ -115,6 +117,16 @@ function formatDate(date: string) {return new Date(date).toLocaleString()}+function truncate(text: string, max = 80): string {+ if (!text) return ''+ return text.length > max ? text.slice(0, max).replace(/\s+$/, '') + '…' : text+}++function openDetail(evt: Event) {+ if (!evt.id) return+ router.push({ name: 'admin-event-detail', params: { id: evt.id } })+}+function timeAgo(date: string) {const seconds = Math.floor((Date.now() - new Date(date).getTime()) / 1000)if (seconds < 60) return 'just now'@@ -142,11 +154,12 @@ function timeAgo(date: string) {</div><div class="card-body"><div class="live-events">- <div v-for="(evt, i) in liveEvents" :key="'live-' + i" class="live-event-item">+ <div v-for="(evt, i) in liveEvents" :key="'live-' + i" class="live-event-item"+ :class="{ clickable: !!evt.id }" @click="openDetail(evt)"><span :class="categoryBadgeClass(evt.category)">{{ evt.category }}</span><span class="event-type">{{ evt.type }}</span><span v-if="evt.client_ip" class="event-ip">{{ evt.client_ip }}</span>- <span class="event-message">{{ evt.message }}</span>+ <span class="event-message">{{ truncate(evt.message) }}</span><span class="event-time">{{ timeAgo(evt.created_at) }}</span></div></div>@@ -188,13 +201,13 @@ function timeAgo(date: string) {</tr></thead><tbody>- <tr v-for="evt in events" :key="evt.id">+ <tr v-for="evt in events" :key="evt.id" class="clickable-row" @click="openDetail(evt)"><td><span :class="categoryBadgeClass(evt.category)">{{ evt.category }}</span></td><td><code>{{ evt.type }}</code></td><td>{{ evt.actor_name || '-' }}</td><td><code v-if="evt.client_ip">{{ evt.client_ip }}</code><span v-else>-</span></td>- <td>{{ evt.message }}</td>- <td>{{ formatDate(evt.created_at) }}</td>+ <td class="message-cell" :title="evt.message">{{ truncate(evt.message) }}</td>+ <td style="white-space: nowrap">{{ formatDate(evt.created_at) }}</td></tr></tbody></table>@@ -262,6 +275,29 @@ function timeAgo(date: string) {animation: fadeIn 0.3s ease;}+.live-event-item.clickable {+ cursor: pointer;+}++.live-event-item.clickable:hover {+ background: var(--bg-hover);+}++.clickable-row {+ cursor: pointer;+}++.clickable-row:hover {+ background: var(--bg-hover);+}++.message-cell {+ max-width: 360px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.event-type {font-family: 'JetBrains Mono', 'Fira Code', monospace;font-size: 12px;diff --git a/web/src/views/audit/AuditLog.vue b/web/src/views/audit/AuditLog.vueindex 2a526e4..325542a 100644--- a/web/src/views/audit/AuditLog.vue+++ b/web/src/views/audit/AuditLog.vue@@ -1,21 +1,19 @@<script setup lang="ts">-import { ref, onMounted } from 'vue'+import { ref } from 'vue'+import { useRouter } from 'vue-router'import { auditApi } from '../../api/audit'-import type { Event, Pageable } from '../../api/types'+import type { Event } from '../../api/types'import Pagination from '../../components/Pagination.vue'import { usePagination } from '@/composables/usePagination'-+const router = useRouter()const events = ref<Event[]>([])const loading = ref(true)-const categoryFilter = ref('')--const { pageable, goToPage } = usePagination(async (page) => {loading.value = truetry {- const res = await auditApi.list(page, pageable.value.size, categoryFilter.value || undefined)+ const res = await auditApi.list(page, pageable.value.size)events.value = res.data.datapageable.value = res.data.pageable} catch (e) {@@ -29,29 +27,20 @@ function formatDate(dateStr: string): string {return new Date(dateStr).toLocaleString()}-function categoryBadgeClass(category: string): string {- switch (category) {- case 'user': return 'badge badge-info'- case 'email': return 'badge badge-success'- case 'system': return 'badge badge-warning'- default: return 'badge'- }+function truncate(text: string, max = 80): string {+ if (!text) return ''+ return text.length > max ? text.slice(0, max).replace(/\s+$/, '') + '…' : text}+function openDetail(event: Event) {+ router.push({ name: 'audit-log-detail', params: { id: event.id } })+}</script><template><div><div class="page-header"><h1>Audit Log</h1>- <div class="page-header-actions">- <select v-model="categoryFilter" class="form-select" style="min-width: 140px" @change="goToPage(0)">- <option value="">All categories</option>- <option value="user">User</option>- <option value="email">Email</option>- <option value="system">System</option>- </select>- </div></div><div v-if="loading" class="loading-page">@@ -61,7 +50,7 @@ function categoryBadgeClass(category: string): string {<div v-else class="card"><div v-if="events.length === 0" class="empty-state"><h3>No audit events</h3>- <p>Your activity log will appear here as you use the platform.</p>+ <p>Workspace activity — member changes, server, webhook and API key updates — will appear here.</p></div><template v-else>@@ -70,36 +59,43 @@ function categoryBadgeClass(category: string): string {<thead><tr><th>Date</th>- <th>Category</th>- <th>Type</th>+ <th>Action</th>+ <th>Actor</th><th>IP Address</th><th>Message</th></tr></thead><tbody>- <tr v-for="event in events" :key="event.id">+ <tr v-for="event in events" :key="event.id" class="clickable-row" @click="openDetail(event)"><td style="white-space: nowrap">{{ formatDate(event.created_at) }}</td>- <td><span :class="categoryBadgeClass(event.category)">{{ event.category }}</span></td><td><code>{{ event.type }}</code></td>- <td><code v-if="event.client_ip">{{ event.client_ip }}</code><span v-else>-</span></td>- <td>{{ event.message }}</td>+ <td>{{ event.actor_name || '—' }}</td>+ <td><code v-if="event.client_ip">{{ event.client_ip }}</code><span v-else>—</span></td>+ <td class="message-cell" :title="event.message">{{ truncate(event.message) }}</td></tr></tbody></table></div><Pagination :pageable="pageable" @page="goToPage" />--</template></div></div></template><style scoped>-.page-header-actions {- display: flex;- gap: 8px;- align-items: center;+.clickable-row {+ cursor: pointer;+}++.clickable-row:hover {+ background: var(--bg-hover);+}++.message-cell {+ max-width: 360px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;}</style>diff --git a/web/src/views/audit/AuditLogDetail.vue b/web/src/views/audit/AuditLogDetail.vuenew file mode 100644index 0000000..2b09655--- /dev/null+++ b/web/src/views/audit/AuditLogDetail.vue@@ -0,0 +1,143 @@+<script setup lang="ts">+import { ref, computed, onMounted } from 'vue'+import { useRoute, useRouter } from 'vue-router'+import { auditApi } from '../../api/audit'+import type { Event } from '../../api/types'+import { useNotificationStore } from '../../stores/notification'++const route = useRoute()+const router = useRouter()+const notify = useNotificationStore()++const loading = ref(true)+const event = ref<Event | null>(null)++onMounted(async () => {+ try {+ const id = Number(route.params.id)+ const res = await auditApi.get(id)+ event.value = res.data.data+ } catch {+ notify.error('Failed to load audit event')+ } finally {+ loading.value = false+ }+})++function formatDate(dateStr: string): string {+ return new Date(dateStr).toLocaleString()+}++// Pretty-print the JSON metadata blob; fall back to the raw string if it+// isn't valid JSON (or empty).+const prettyMetadata = computed(() => {+ const raw = event.value?.metadata+ if (!raw) return ''+ try {+ return JSON.stringify(JSON.parse(raw), null, 2)+ } catch {+ return raw+ }+})+</script>++<template>+ <div>+ <div class="page-header">+ <h1>Audit Event</h1>+ <div style="display: flex; gap: 8px">+ <button class="btn btn-secondary" @click="router.push('/audit-log')">Back to Audit Log</button>+ </div>+ </div>++ <div v-if="loading" class="loading-page">+ <div class="spinner"></div>+ </div>++ <div v-else-if="!event" class="card">+ <div class="empty-state">+ <h3>Audit event not found</h3>+ <p>This event may have been removed by the workspace retention policy.</p>+ </div>+ </div>++ <template v-else>+ <div class="card" style="margin-bottom: 24px">+ <div class="card-header">+ <h2><code>{{ event.type }}</code></h2>+ </div>+ <div class="card-body">+ <dl class="detail-grid">+ <dt>Event ID</dt>+ <dd><code>{{ event.id }}</code></dd>++ <dt>Date</dt>+ <dd>{{ formatDate(event.created_at) }}</dd>++ <dt>Action</dt>+ <dd><code>{{ event.type }}</code></dd>++ <dt>Actor</dt>+ <dd>{{ event.actor_name || '—' }}<span v-if="event.actor_id"> (#{{ event.actor_id }})</span></dd>++ <dt>IP Address</dt>+ <dd><code v-if="event.client_ip">{{ event.client_ip }}</code><span v-else>—</span></dd>++ <dt>Message</dt>+ <dd class="detail-message">{{ event.message }}</dd>+ </dl>+ </div>+ </div>++ <div class="card">+ <div class="card-header">+ <h2>Metadata</h2>+ </div>+ <div class="card-body">+ <div v-if="!prettyMetadata" class="empty-state">+ <p>No additional metadata for this event.</p>+ </div>+ <pre v-else class="metadata-block">{{ prettyMetadata }}</pre>+ </div>+ </div>+ </template>+ </div>+</template>++<style scoped>+.detail-grid {+ display: grid;+ grid-template-columns: 160px 1fr;+ gap: 12px 16px;+ margin: 0;+}++.detail-grid dt {+ font-size: 13px;+ font-weight: 600;+ color: var(--text-muted);+}++.detail-grid dd {+ margin: 0;+ font-size: 14px;+ color: var(--text-primary);+ word-break: break-word;+}++.detail-message {+ white-space: pre-wrap;+}++.metadata-block {+ margin: 0;+ padding: 12px 14px;+ background: var(--bg-secondary);+ border: 1px solid var(--border-primary);+ border-radius: var(--radius-sm);+ font-size: 13px;+ overflow-x: auto;+ white-space: pre-wrap;+ word-break: break-word;+}+</style>