Skip to content

armgit / posta

Public Imported from GitHub
0

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.

feat(forms): add a per-workspace switch for hosted pages and a team detail page

Jonas Kaninda8db7065cfeeb
diff --git a/internal/handlers/admin_workspace_handler.go b/internal/handlers/admin_workspace_handler.go
index 714b390..58d5fec 100644
--- a/internal/handlers/admin_workspace_handler.go
+++ b/internal/handlers/admin_workspace_handler.go
@@ -23,33 +23,38 @@ import (
"time"
"github.com/goposta/posta/internal/models"
+ "github.com/goposta/posta/internal/services/audit"
"github.com/goposta/posta/internal/storage/repositories"
"github.com/jkaninda/okapi"
"gorm.io/gorm"
)
type AdminWorkspaceHandler struct {
- db *gorm.DB
- repo *repositories.WorkspaceRepository
+ db *gorm.DB
+ repo *repositories.WorkspaceRepository
+ audit *audit.Logger
}
-func NewAdminWorkspaceHandler(db *gorm.DB, repo *repositories.WorkspaceRepository) *AdminWorkspaceHandler {
- return &AdminWorkspaceHandler{db: db, repo: repo}
+func NewAdminWorkspaceHandler(db *gorm.DB, repo *repositories.WorkspaceRepository, auditLogger *audit.Logger) *AdminWorkspaceHandler {
+ return &AdminWorkspaceHandler{db: db, repo: repo, audit: auditLogger}
}
// AdminWorkspaceRow is one line of the platform-wide workspace table.
type AdminWorkspaceRow struct {
- ID uint `json:"id"`
- Name string `json:"name"`
- Slug string `json:"slug"`
- System bool `json:"system"`
- OwnerID uint `json:"owner_id"`
- OwnerName string `json:"owner_name"`
- OwnerEmail string `json:"owner_email"`
- PlanID *uint `json:"plan_id"`
- PlanName string `json:"plan_name"`
- MemberCount int64 `json:"member_count"`
- CreatedAt time.Time `json:"created_at"`
+ ID uint `json:"id"`
+ Name string `json:"name"`
+ Slug string `json:"slug"`
+ System bool `json:"system"`
+ OwnerID uint `json:"owner_id"`
+ OwnerName string `json:"owner_name"`
+ OwnerEmail string `json:"owner_email"`
+ PlanID *uint `json:"plan_id"`
+ PlanName string `json:"plan_name"`
+ MemberCount int64 `json:"member_count"`
+ // HostedFormsDisabled is set when a platform admin took the workspace's
+ // hosted form pages offline.
+ HostedFormsDisabled bool `json:"hosted_forms_disabled"`
+ CreatedAt time.Time `json:"created_at"`
}
// AdminWorkspaceMember is a workspace member with the account details an
@@ -99,6 +104,41 @@ type AdminWorkspaceIDRequest struct {
ID int `param:"id"`
}
+type AdminSetHostedFormsRequest struct {
+ ID int `param:"id"`
+ Body struct {
+ Enabled bool `json:"enabled" doc:"false takes the workspace's hosted form pages offline"`
+ } `json:"body"`
+}
+
+// SetHostedForms turns a workspace's hosted form pages (/f/{key}) on or off.
+// Off, the pages answer 404 and the widget refuses to load or submit from
+// Posta's own domain, so a phishing form stops at once. Forms embedded on the
+// workspace's own sites, its submissions and its data are untouched.
+func (h *AdminWorkspaceHandler) SetHostedForms(c *okapi.Context, req *AdminSetHostedFormsRequest) error {
+ ws, err := h.repo.FindByID(uint(req.ID))
+ if err != nil {
+ return c.AbortNotFound("workspace not found")
+ }
+ disabled := !req.Body.Enabled
+ if ws.HostedFormsDisabled != disabled {
+ if err := h.db.Model(&models.Workspace{}).Where("id = ?", ws.ID).
+ Update("hosted_forms_disabled", disabled).Error; err != nil {
+ return c.AbortInternalServerError("failed to update workspace")
+ }
+ ws.HostedFormsDisabled = disabled
+ if h.audit != nil {
+ action, message := "workspace.hosted_forms_enabled", "Hosted form pages turned back on: "+ws.Name
+ if disabled {
+ action, message = "workspace.hosted_forms_disabled", "Hosted form pages taken offline: "+ws.Name
+ }
+ h.audit.LogCtxScoped(c, ws.ID, action, message, map[string]any{"workspace_id": ws.ID})
+ }
+ }
+ one := []models.Workspace{*ws}
+ return ok(c, h.row(ws, h.owners(one), h.planNames(one), h.memberCounts(one)))
+}
+
func (h *AdminWorkspaceHandler) List(c *okapi.Context, req *AdminListWorkspacesRequest) error {
page, size, offset := normalizePageParams(req.Page, req.Size)
@@ -179,6 +219,8 @@ func (h *AdminWorkspaceHandler) row(ws *models.Workspace, owners map[uint]models
PlanID: ws.PlanID,
MemberCount: members[ws.ID],
CreatedAt: ws.CreatedAt,
+
+ HostedFormsDisabled: ws.HostedFormsDisabled,
}
if ws.PlanID != nil {
row.PlanName = plans[*ws.PlanID]
diff --git a/internal/handlers/form_handler.go b/internal/handlers/form_handler.go
index 100f56b..4db41ef 100644
--- a/internal/handlers/form_handler.go
+++ b/internal/handlers/form_handler.go
@@ -36,6 +36,7 @@ import (
"github.com/goposta/posta/internal/models"
"github.com/goposta/posta/internal/services/audit"
"github.com/goposta/posta/internal/services/messages"
+ "github.com/goposta/posta/internal/services/settings"
"github.com/goposta/posta/internal/storage/repositories"
"github.com/jkaninda/okapi"
)
@@ -48,13 +49,16 @@ const publicKeyLength = 22
var formSlugPattern = regexp.MustCompile(`[^a-z0-9]+`)
type FormHandler struct {
- repo *repositories.FormRepository
- messageRepo *repositories.MessageRepository
- domainRepo *repositories.DomainRepository
- audit *audit.Logger
- apiBaseURL string
- keyCache FormKeyInvalidator
- edition enterprise.EE
+ repo *repositories.FormRepository
+ // hostedSettings and workspaces tell the snippet whether the share link works.
+ hostedSettings *settings.Provider
+ workspaces *repositories.WorkspaceRepository
+ messageRepo *repositories.MessageRepository
+ domainRepo *repositories.DomainRepository
+ audit *audit.Logger
+ apiBaseURL string
+ keyCache FormKeyInvalidator
+ edition enterprise.EE
}
// FormKeyInvalidator drops cached public-key lookups; *messages.Service
@@ -176,6 +180,15 @@ type FormSnippetResponse struct {
Fetch string `json:"fetch"`
Widget string `json:"widget" doc:"Website widget embed: a placeholder element and the script tag"`
ShareURL string `json:"share_url" doc:"The form's hosted page, a link that works without a website"`
+ // ShareUnavailable is set when the hosted page is offline: "platform" when
+ // the instance serves no hosted pages, "workspace" when a platform admin
+ // took this workspace's pages offline.
+ ShareUnavailable string `json:"share_unavailable,omitempty" enum:"platform,workspace"`
+}
+
+// SetHostedPageChecks lets the snippet say when the share link is offline.
+func (h *FormHandler) SetHostedPageChecks(p *settings.Provider, workspaces *repositories.WorkspaceRepository) {
+ h.hostedSettings, h.workspaces = p, workspaces
}
func (h *FormHandler) Create(c *okapi.Context, req *CreateFormRequest) error {
@@ -524,6 +537,8 @@ func (h *FormHandler) Snippet(c *okapi.Context, req *FormIDRequest) error {
Fetch: buildFetchSnippet(endpoint),
Widget: buildWidgetSnippet(h.apiBaseURL, form),
ShareURL: h.apiBaseURL + "/f/" + url.PathEscape(form.PublicKey),
+
+ ShareUnavailable: hostedOffline(h.hostedSettings, h.workspaces, form),
})
}
diff --git a/internal/handlers/form_ingest_handler.go b/internal/handlers/form_ingest_handler.go
index b620c64..2e51764 100644
--- a/internal/handlers/form_ingest_handler.go
+++ b/internal/handlers/form_ingest_handler.go
@@ -38,6 +38,7 @@ import (
"github.com/goposta/posta/internal/services/messages"
"github.com/goposta/posta/internal/services/settings"
"github.com/goposta/posta/internal/storage/blob"
+ "github.com/goposta/posta/internal/storage/repositories"
"github.com/goposta/posta/internal/web/widget"
"github.com/jkaninda/logger"
"github.com/jkaninda/okapi"
@@ -48,6 +49,7 @@ const genericAcceptMessage = "Thanks — your message has been received."
type FormIngestHandler struct {
settings *settings.Provider
abuseFallback string
+ workspaces *repositories.WorkspaceRepository
svc *messages.Service
blobStore blob.Store
@@ -236,6 +238,9 @@ func (h *FormIngestHandler) WidgetConfig(c *okapi.Context) error {
if err != nil {
form = nil
}
+ if form != nil && isSelfOrigin(c.Request()) && !h.hostedAllowed(form) {
+ form = nil
+ }
cfg := widgetConfig(form, form != nil && originAllowed(c.Request(), form), time.Now())
if !cfg.Enabled {
// A disabled answer carries no form data, so any origin may read it.
@@ -285,6 +290,9 @@ func (h *FormIngestHandler) Submit(c *okapi.Context) error {
}
origin := req.Header.Get("Origin")
+ if isSelfOrigin(req) && !h.hostedAllowed(form) {
+ return h.respond(c, form, nil, http.StatusForbidden, "unavailable", "This form is not available.")
+ }
if !originAllowed(req, form) {
return h.respond(c, form, nil, http.StatusForbidden, "origin_not_allowed", "This origin is not allowed to submit to this form.")
}
diff --git a/internal/handlers/form_page_handler.go b/internal/handlers/form_page_handler.go
index 3f3390c..7c795de 100644
--- a/internal/handlers/form_page_handler.go
+++ b/internal/handlers/form_page_handler.go
@@ -30,6 +30,7 @@ import (
"github.com/goposta/posta/internal/models"
"github.com/goposta/posta/internal/services/settings"
+ "github.com/goposta/posta/internal/storage/repositories"
"github.com/jkaninda/okapi"
)
@@ -51,10 +52,40 @@ const hostedPageCSP = "default-src 'none'; script-src 'self'; connect-src 'self'
"frame-ancestors 'none'; base-uri 'none'"
// SetHostedPages enables the hosted form pages. adminEmail is the abuse
-// contact when the platform setting abuse_report_email is empty.
-func (h *FormIngestHandler) SetHostedPages(p *settings.Provider, adminEmail string) {
+// contact when the platform setting abuse_report_email is empty; workspaces
+// says which workspaces a platform admin has taken offline.
+func (h *FormIngestHandler) SetHostedPages(p *settings.Provider, adminEmail string, workspaces *repositories.WorkspaceRepository) {
h.settings = p
h.abuseFallback = adminEmail
+ h.workspaces = workspaces
+}
+
+// Why a form's hosted page is offline (FormSnippetResponse.ShareUnavailable).
+const (
+ hostedOffPlatform = "platform" // the platform setting hosted_forms_enabled is off
+ hostedOffWorkspace = "workspace" // a platform admin took the workspace's pages offline
+)
+
+// hostedOffline says why form may not be used from Posta's own domain, or ""
+// when it may. The workspace flag is read on every request, so turning it off
+// takes effect at once, past any cached form.
+func hostedOffline(p *settings.Provider, workspaces *repositories.WorkspaceRepository, form *models.Form) string {
+ if p != nil && !p.HostedFormsEnabled() {
+ return hostedOffPlatform
+ }
+ if workspaces == nil || form.WorkspaceID == nil {
+ return ""
+ }
+ ws, err := workspaces.FindByID(*form.WorkspaceID)
+ // Fail closed: a page that cannot be checked is not served.
+ if err != nil || ws.HostedFormsDisabled {
+ return hostedOffWorkspace
+ }
+ return ""
+}
+
+func (h *FormIngestHandler) hostedAllowed(form *models.Form) bool {
+ return hostedOffline(h.settings, h.workspaces, form) == ""
}
type hostedPageData struct {
@@ -75,7 +106,7 @@ func (h *FormIngestHandler) HostedPage(c *okapi.Context) error {
}
key := c.Param("key")
form, err := h.svc.FindFormByKey(key)
- if err != nil || form.Status == models.FormStatusArchived {
+ if err != nil || form.Status == models.FormStatusArchived || !h.hostedAllowed(form) {
return trackingNotice(c, http.StatusNotFound, "Form not found", "This form does not exist.", "error")
}
diff --git a/internal/handlers/team_handler.go b/internal/handlers/team_handler.go
index 40e1e59..c32d911 100644
--- a/internal/handlers/team_handler.go
+++ b/internal/handlers/team_handler.go
@@ -63,6 +63,28 @@ type TeamIDRequest struct {
ID int `param:"id"`
}
+// TeamMemberView is a team member with their workspace account.
+type TeamMemberView struct {
+ UserID uint `json:"user_id"`
+ Name string `json:"name"`
+ Email string `json:"email"`
+ Role models.WorkspaceRole `json:"role"`
+}
+
+// TeamDetail is a team with its members, the rules that route to it, and how
+// many submissions it holds.
+type TeamDetail struct {
+ ID uint `json:"id"`
+ UUID string `json:"uuid"`
+ Name string `json:"name"`
+ Email string `json:"email"`
+ CreatedAt time.Time `json:"created_at"`
+ Members []TeamMemberView `json:"members"`
+ Rules []repositories.RuleUsingTeam `json:"rules"`
+ OpenMessages int64 `json:"open_messages" doc:"Submissions routed to the team that are new or open"`
+ Messages int64 `json:"messages" doc:"All submissions routed to the team"`
+}
+
// requireManage allows workspace owners and admins: teams decide who is
// sent submissions.
func requireManage(c *okapi.Context) error {
@@ -134,6 +156,46 @@ func (h *TeamHandler) List(c *okapi.Context) error {
return ok(c, teams)
}
+// Get returns one team with its members, the rules that use it and its
+// submission counts. Any workspace member may read it.
+func (h *TeamHandler) Get(c *okapi.Context, req *TeamIDRequest) error {
+ ws, err := h.workspace(c)
+ if ws == 0 {
+ return err
+ }
+ team, err := h.repo.FindForWorkspace(ws, uint(req.ID))
+ if err != nil {
+ return c.AbortNotFound("team not found")
+ }
+ members, err := h.workspaceRepo.ListMembers(ws)
+ if err != nil {
+ return c.AbortInternalServerError("failed to load members")
+ }
+ byUser := map[uint]models.WorkspaceMember{}
+ for _, m := range members {
+ byUser[m.UserID] = m
+ }
+ detail := TeamDetail{
+ ID: team.ID, UUID: team.UUID, Name: team.Name, Email: team.Email, CreatedAt: team.CreatedAt,
+ Members: []TeamMemberView{}, Rules: []repositories.RuleUsingTeam{},
+ }
+ for _, tm := range team.Members {
+ m, ok := byUser[tm.UserID]
+ if !ok {
+ // A member who left the workspace no longer receives anything.
+ continue
+ }
+ detail.Members = append(detail.Members, TeamMemberView{UserID: m.UserID, Name: m.User.Name, Email: m.User.Email, Role: m.Role})
+ }
+ if rules, err := h.ruleRepo.RulesUsingTeam(ws, team.ID); err == nil && rules != nil {
+ detail.Rules = rules
+ }
+ if detail.OpenMessages, detail.Messages, err = h.repo.MessageCounts(team.ID); err != nil {
+ return c.AbortInternalServerError("failed to count messages")
+ }
+ return ok(c, detail)
+}
+
func (h *TeamHandler) Create(c *okapi.Context, req *CreateTeamRequest) error {
if err := requireManage(c); err != nil {
return c.AbortForbidden("only workspace owners and admins can manage teams", err)
diff --git a/internal/models/workspace.go b/internal/models/workspace.go
index a738ed9..8209634 100644
--- a/internal/models/workspace.go
+++ b/internal/models/workspace.go
@@ -49,9 +49,13 @@ type Workspace struct {
// System marks the single built-in platform workspace. It owns
// platform-managed resources, is created on first boot, cannot be renamed or
// deleted, and admits only platform admins.
- System bool `json:"system" gorm:"not null;default:false"`
- CreatedAt time.Time `json:"created_at"`
- UpdatedAt time.Time `json:"updated_at"`
+ System bool `json:"system" gorm:"not null;default:false"`
+ // HostedFormsDisabled lets a platform admin take the workspace's hosted
+ // form pages (/f/{key}) offline, for example when they are used for
+ // phishing. Forms embedded on the workspace's own sites keep working.
+ HostedFormsDisabled bool `json:"hosted_forms_disabled" gorm:"not null;default:false"`
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt time.Time `json:"updated_at"`
Owner User `json:"-" gorm:"foreignKey:OwnerID"`
Plan Plan `json:"-" gorm:"foreignKey:PlanID"`
diff --git a/internal/routes/admin_routes.go b/internal/routes/admin_routes.go
index 5e76e30..a488e45 100644
--- a/internal/routes/admin_routes.go
+++ b/internal/routes/admin_routes.go
@@ -417,6 +417,20 @@ func (r *Router) adminRoutes() []okapi.RouteDefinition {
okapi.DocResponse(404, &dto.ErrorResponseBody{}),
},
},
+ {
+ Method: http.MethodPut,
+ Path: pathWorkspaceByID + "/hosted-forms",
+ Handler: okapi.H(r.h.adminWorkspace.SetHostedForms),
+ Group: adminGroup,
+ Summary: "Turn a workspace's hosted form pages on or off",
+ Description: "Off, the workspace's /f/{key} pages answer 404 and forms cannot be loaded or submitted from Posta's own domain. Forms embedded on the workspace's own sites keep working.",
+ Request: &handlers.AdminSetHostedFormsRequest{},
+ Response: &dto.Response[handlers.AdminWorkspaceRow]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Workspace ID"),
+ okapi.DocResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
// ==================== Plans ====================
{
diff --git a/internal/routes/message_routes.go b/internal/routes/message_routes.go
index ad8d8a1..6bd5f68 100644
--- a/internal/routes/message_routes.go
+++ b/internal/routes/message_routes.go
@@ -546,6 +546,18 @@ func (r *Router) messageWorkspaceRoutes() []okapi.RouteDefinition {
okapi.DocResponse(409, &dto.ErrorResponseBody{}),
},
},
+ {
+ Method: http.MethodGet,
+ Path: "/teams/{id:int}",
+ Handler: okapi.H(r.h.team.Get),
+ Group: opsGroup,
+ Middlewares: r.licensed(),
+ Summary: "Get a team",
+ Description: "The team with its members, the routing rules that notify or assign it, and how many submissions it holds.",
+ Request: &handlers.TeamIDRequest{},
+ Response: &dto.Response[handlers.TeamDetail]{},
+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Team ID")},
+ },
{
Method: http.MethodPut,
Path: "/teams/{id:int}",
diff --git a/internal/routes/routes.go b/internal/routes/routes.go
index f142264..80ad5fa 100644
--- a/internal/routes/routes.go
+++ b/internal/routes/routes.go
@@ -294,7 +294,7 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c
dashboard: handlers.NewDashboardHandler(db, statsCache, webhookDeliveryRepo),
domain: handlers.NewDomainHandler(domainRepo),
adminDomain: handlers.NewAdminDomainHandler(db, domainRepo, auditLogger),
- adminWorkspace: handlers.NewAdminWorkspaceHandler(db, workspaceRepo),
+ adminWorkspace: handlers.NewAdminWorkspaceHandler(db, workspaceRepo, auditLogger),
notification: handlers.NewNotificationHandler(notificationRepo, inboxService),
announcement: handlers.NewAdminAnnouncementHandler(db, inboxService, auditLogger),
bounce: handlers.NewBounceHandler(bounceRepo, suppressionRepo, emailRepo, dispatcher),
@@ -500,7 +500,8 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c
inbound.NewIPRateLimiter(cfg.MessagesIPRateLimit, time.Duration(cfg.MessagesIPRateWindow)*time.Second),
cfg.MessagesMaxAttachSize,
)
- r.h.formIngest.SetHostedPages(settingsProvider, cfg.AdminEmail)
+ r.h.formIngest.SetHostedPages(settingsProvider, cfg.AdminEmail, workspaceRepo)
+ r.h.form.SetHostedPageChecks(settingsProvider, workspaceRepo)
if blobStore != nil {
r.h.message.SetBlobStore(blobStore)
r.h.formIngest.SetBlobStore(blobStore)
diff --git a/internal/storage/repositories/form_rule_repo.go b/internal/storage/repositories/form_rule_repo.go
index 92e7cdd..41083b4 100644
--- a/internal/storage/repositories/form_rule_repo.go
+++ b/internal/storage/repositories/form_rule_repo.go
@@ -121,11 +121,36 @@ func (r *FormRuleRepository) NamesByUUID(uuids []string) (map[string]string, err
return out, nil
}
+// RuleUsingTeam is a rule that notifies or assigns a team, with its form.
+type RuleUsingTeam struct {
+ ID uint `json:"id"`
+ Name string `json:"name"`
+ Enabled bool `json:"enabled"`
+ FormID uint `json:"form_id"`
+ FormName string `json:"form_name"`
+}
+
+// RulesUsingTeam lists a workspace's rules that notify or assign team teamID,
+// by form then rule order.
+func (r *FormRuleRepository) RulesUsingTeam(workspaceID, teamID uint) ([]RuleUsingTeam, error) {
+ var out []RuleUsingTeam
+ err := r.db.Table("form_rules").
+ Select("form_rules.id, form_rules.name, form_rules.enabled, form_rules.form_id, forms.name AS form_name").
+ Joins("JOIN forms ON forms.id = form_rules.form_id AND forms.deleted_at IS NULL").
+ Where("form_rules.workspace_id = ? AND form_rules.actions @> ?::jsonb", workspaceID, fmt.Sprintf(`[{"team_id":%d}]`, teamID)).
+ Order("LOWER(forms.name), form_rules.position").
+ Scan(&out).Error
+ return out, err
+}
+
// UsingTeam names a workspace's rules that notify or assign team teamID.
+// Rules of a deleted form never run and can no longer be edited, so they do
+// not count.
func (r *FormRuleRepository) UsingTeam(workspaceID, teamID uint) ([]string, error) {
- var names []string
- err := r.db.Model(&models.FormRule{}).
- Where("workspace_id = ? AND actions @> ?::jsonb", workspaceID, fmt.Sprintf(`[{"team_id":%d}]`, teamID)).
- Pluck("name", &names).Error
+ rules, err := r.RulesUsingTeam(workspaceID, teamID)
+ names := make([]string, 0, len(rules))
+ for _, rule := range rules {
+ names = append(names, rule.Name)
+ }
return names, err
}
diff --git a/internal/storage/repositories/team_repo.go b/internal/storage/repositories/team_repo.go
index cb9ed14..a217baa 100644
--- a/internal/storage/repositories/team_repo.go
+++ b/internal/storage/repositories/team_repo.go
@@ -57,6 +57,17 @@ func (r *TeamRepository) FindByID(id uint) (*models.Team, error) {
return &team, nil
}
+// MessageCounts counts the submissions routed to a team: those still to handle
+// (new or open) and all of them.
+func (r *TeamRepository) MessageCounts(teamID uint) (open, total int64, err error) {
+ q := func() *gorm.DB { return r.db.Model(&models.Message{}).Where("team_id = ?", teamID) }
+ if err = q().Count(&total).Error; err != nil {
+ return 0, 0, err
+ }
+ err = q().Where("state IN ?", []models.MessageState{models.MessageStateNew, models.MessageStateOpen}).Count(&open).Error
+ return open, total, err
+}
+
func (r *TeamRepository) NameTaken(workspaceID uint, name string, exceptID uint) bool {
var count int64
r.db.Model(&models.Team{}).Where("workspace_id = ? AND LOWER(name) = LOWER(?) AND id <> ?", workspaceID, name, exceptID).Count(&count)
diff --git a/web/src/api/admin.ts b/web/src/api/admin.ts
index 354ae66..0d7adf7 100644
--- a/web/src/api/admin.ts
+++ b/web/src/api/admin.ts
@@ -61,6 +61,9 @@ export const adminApi = {
getWorkspace(id: number) {
return api.get<ApiResponse<AdminWorkspaceDetail>>(`/admin/workspaces/${id}`)
},
+ setWorkspaceHostedForms(id: number, enabled: boolean) {
+ return api.put<ApiResponse<AdminWorkspaceRow>>(`/admin/workspaces/${id}/hosted-forms`, { enabled })
+ },
createUser(name: string, email: string, password: string, role: string) {
return api.post<ApiResponse<User>>('/admin/users', { name, email, password, role })
diff --git a/web/src/api/messages.ts b/web/src/api/messages.ts
index a0b69f2..9d02944 100644
--- a/web/src/api/messages.ts
+++ b/web/src/api/messages.ts
@@ -20,6 +20,7 @@ import type {
RuleTestResult,
Team,
TeamInput,
+ TeamDetail,
} from './types'
const WORKSPACE_KEY = 'posta_workspace_id'
@@ -280,6 +281,9 @@ export const teamsApi = {
list() {
return api.get<ApiResponse<Team[]>>('/workspaces/current/teams')
},
+ get(id: number) {
+ return api.get<ApiResponse<TeamDetail>>(`/workspaces/current/teams/${id}`)
+ },
create(team: TeamInput) {
return api.post<ApiResponse<Team>>('/workspaces/current/teams', team)
},
diff --git a/web/src/api/types.ts b/web/src/api/types.ts
index 3dbc130..61f21bb 100644
--- a/web/src/api/types.ts
+++ b/web/src/api/types.ts
@@ -453,6 +453,8 @@ export interface AdminWorkspaceRow {
plan_id: number | null
plan_name: string
member_count: number
+ /** A platform admin took the workspace's hosted form pages offline. */
+ hosted_forms_disabled: boolean
created_at: string
}
@@ -1432,6 +1434,8 @@ export interface FormSnippet {
fetch: string
widget: string
share_url: string
+ /** Why the share link is offline: the instance serves no hosted pages, or an admin took this workspace's offline. */
+ share_unavailable?: 'platform' | 'workspace'
}
export interface SubmissionOptionCount {
@@ -1562,6 +1566,35 @@ export interface Team {
created_at: string
}
+export interface TeamMemberView {
+ user_id: number
+ name: string
+ email: string
+ role: string
+}
+
+export interface TeamRuleRef {
+ id: number
+ name: string
+ enabled: boolean
+ form_id: number
+ form_name: string
+}
+
+export interface TeamDetail {
+ id: number
+ uuid: string
+ name: string
+ email: string
+ created_at: string
+ members: TeamMemberView[]
+ /** Routing rules that notify or assign this team. */
+ rules: TeamRuleRef[]
+ /** Submissions routed to the team that are new or open. */
+ open_messages: number
+ messages: number
+}
+
export interface TeamInput {
name: string
email?: string
diff --git a/web/src/router/index.ts b/web/src/router/index.ts
index ca7e9bd..3c66805 100644
--- a/web/src/router/index.ts
+++ b/web/src/router/index.ts
@@ -64,6 +64,7 @@ const routes = [
{ path: 'messages', name: 'messages', component: () => import('../views/messages/Messages.vue'), meta: { title: 'Messages' } },
{ path: 'messages/:id', name: 'message-detail', component: () => import('../views/messages/MessageDetail.vue'), meta: { title: 'Message' } },
{ path: 'teams', name: 'teams', component: () => import('../views/teams/Teams.vue'), meta: { title: 'Teams' } },
+ { path: 'teams/:id', name: 'team-detail', component: () => import('../views/teams/TeamDetail.vue'), meta: { title: 'Team' } },
{ path: 'message-filters', name: 'message-filters', component: () => import('../views/messages/MessageFilters.vue'), meta: { title: 'Spam Filters' } },
{ path: 'forms', name: 'forms', component: () => import('../views/forms/Forms.vue'), meta: { title: 'Forms' } },
{ path: 'forms/:id', name: 'form-detail', component: () => import('../views/forms/FormDetail.vue'), meta: { title: 'Form' } },
diff --git a/web/src/views/admin/WorkspaceDetail.vue b/web/src/views/admin/WorkspaceDetail.vue
index 13e6f98..25034c9 100644
--- a/web/src/views/admin/WorkspaceDetail.vue
+++ b/web/src/views/admin/WorkspaceDetail.vue
@@ -5,6 +5,7 @@ import { adminApi } from "../../api/admin";
import { plansApi } from "../../api/plans";
import { useNotificationStore } from "../../stores/notification";
import { apiMessage } from "../../composables/apiError";
+import { useConfirm } from "../../composables/useConfirm";
import type { AdminWorkspaceDetail, Plan } from "../../api/types";
const route = useRoute();
@@ -17,6 +18,35 @@ const plans = ref<Plan[]>([]);
const loading = ref(true);
const loadFailed = ref(false);
const changingPlan = ref(false);
+const { confirm } = useConfirm();
+const changingHosted = ref(false);
+
+// Taking hosted pages offline is the abuse switch for one workspace: its share
+// links stop at once, while forms embedded on its own sites keep working.
+async function toggleHostedForms() {
+ const ws = workspace.value;
+ if (!ws) return;
+ const enable = ws.hosted_forms_disabled;
+ const ok = await confirm({
+ title: enable ? "Turn hosted form pages back on?" : "Take hosted form pages offline?",
+ message: enable
+ ? `The share links of "${ws.name}" forms work again.`
+ : `Every share link of "${ws.name}" forms answers "not found" at once, and forms can no longer be loaded or submitted from this Posta's domain. Forms embedded on the workspace's own websites, its submissions and its data are not affected. Use this when hosted forms are abused, for example for phishing.`,
+ confirmText: enable ? "Turn back on" : "Take offline",
+ variant: enable ? "info" : "danger",
+ });
+ if (!ok) return;
+ changingHosted.value = true;
+ try {
+ const res = await adminApi.setWorkspaceHostedForms(ws.id, enable);
+ ws.hosted_forms_disabled = res.data.data.hosted_forms_disabled;
+ notify.success(enable ? "Hosted form pages are back on." : "Hosted form pages are offline.");
+ } catch (e: any) {
+ notify.error(apiMessage(e, "Failed to update hosted form pages"));
+ } finally {
+ changingHosted.value = false;
+ }
+}
async function load() {
loading.value = true;
@@ -163,6 +193,21 @@ onMounted(load);
</select>
</td>
</tr>
+ <tr>
+ <td class="label-cell">Hosted form pages</td>
+ <td>
+ <span v-if="workspace.hosted_forms_disabled" class="badge badge-danger">Offline</span>
+ <span v-else class="badge badge-success">Online</span>
+ <button
+ class="btn btn-sm hosted-toggle"
+ :class="workspace.hosted_forms_disabled ? 'btn-secondary' : 'btn-danger'"
+ :disabled="changingHosted"
+ @click="toggleHostedForms"
+ >
+ {{ workspace.hosted_forms_disabled ? "Turn back on" : "Take offline" }}
+ </button>
+ </td>
+ </tr>
<tr>
<td class="label-cell">Pending invitations</td>
<td>{{ workspace.pending_invitations }}</td>
@@ -264,4 +309,8 @@ onMounted(load);
.plan-select {
max-width: 300px;
}
+
+.hosted-toggle {
+ margin-left: 10px;
+}
</style>
diff --git a/web/src/views/forms/FormDetail.vue b/web/src/views/forms/FormDetail.vue
index 705bd9c..befd56e 100644
--- a/web/src/views/forms/FormDetail.vue
+++ b/web/src/views/forms/FormDetail.vue
@@ -543,6 +543,20 @@ onMounted(load);
<p class="muted" style="margin: 0 0 12px">
A page Posta hosts for this form. Send it to people, or post it anywhere; no website needed.
</p>
+ <div v-if="snippet?.share_unavailable" class="app-banner app-banner--warning" role="status" style="margin-bottom: 12px">
+ <div class="app-banner-content">
+ <p class="app-banner-text">
+ <template v-if="snippet.share_unavailable === 'workspace'">
+ A platform administrator has taken this workspace's hosted form pages offline, so this link
+ shows "not found". The website widget keeps working. Contact your Posta administrator to restore it.
+ </template>
+ <template v-else>
+ Hosted form pages are turned off on this Posta instance, so this link shows "not found". The
+ website widget keeps working.
+ </template>
+ </p>
+ </div>
+ </div>
<div class="form-group">
<div style="display: flex; gap: 8px">
<input class="form-input" :value="snippet?.share_url || ''" readonly />
diff --git a/web/src/views/teams/TeamDetail.vue b/web/src/views/teams/TeamDetail.vue
new file mode 100644
index 0000000..89773e3
--- /dev/null
+++ b/web/src/views/teams/TeamDetail.vue
@@ -0,0 +1,334 @@
+<script setup lang="ts">
+import { computed, onMounted, ref } from "vue";
+import { useRoute, useRouter } from "vue-router";
+import { teamsApi } from "../../api/messages";
+import { workspaceApi } from "../../api/workspaces";
+import { useNotificationStore } from "../../stores/notification";
+import { useLicenseStore } from "../../stores/license";
+import { useConfirm } from "../../composables/useConfirm";
+import { apiMessage } from "../../composables/apiError";
+import EnterpriseLock from "../../components/EnterpriseLock.vue";
+import type { TeamDetail, WorkspaceMember } from "../../api/types";
+
+// One team: who is on it, which routing rules send work to it, and how much
+// work it holds. Owners and admins change it; every member can read it.
+
+const route = useRoute();
+const router = useRouter();
+const notify = useNotificationStore();
+const license = useLicenseStore();
+const { confirm } = useConfirm();
+
+const id = Number(route.params.id);
+const team = ref<TeamDetail | null>(null);
+const workspaceMembers = ref<WorkspaceMember[]>([]);
+const loading = ref(true);
+const notFound = ref(false);
+const saving = ref(false);
+
+const addUserId = ref<number | "">("");
+const showEditor = ref(false);
+const draft = ref({ name: "", email: "" });
+
+const memberIds = computed(() => (team.value?.members ?? []).map((m) => m.user_id));
+const addable = computed(() => workspaceMembers.value.filter((m) => !memberIds.value.includes(m.user_id)));
+
+async function load() {
+ loading.value = true;
+ try {
+ const [teamRes, membersRes] = await Promise.all([teamsApi.get(id), workspaceApi.listMembers()]);
+ team.value = teamRes.data.data;
+ workspaceMembers.value = membersRes.data.data || [];
+ } catch (e: any) {
+ if (e?.response?.status === 404) notFound.value = true;
+ else notify.error(apiMessage(e, "Failed to load the team"));
+ } finally {
+ loading.value = false;
+ }
+}
+
+// The API replaces the whole team, so every change sends name, address and members.
+async function save(changes: { name?: string; email?: string; user_ids?: number[] }, success: string) {
+ const t = team.value;
+ if (!t) return false;
+ saving.value = true;
+ try {
+ await teamsApi.update(t.id, {
+ name: changes.name ?? t.name,
+ email: changes.email ?? t.email,
+ user_ids: changes.user_ids ?? memberIds.value,
+ });
+ notify.success(success);
+ await load();
+ return true;
+ } catch (e: any) {
+ notify.error(apiMessage(e, "Failed to save the team"));
+ return false;
+ } finally {
+ saving.value = false;
+ }
+}
+
+async function addMember() {
+ const userId = addUserId.value;
+ if (userId === "") return;
+ const who = workspaceMembers.value.find((m) => m.user_id === userId);
+ if (await save({ user_ids: [...memberIds.value, userId] }, `${who?.name || who?.email || "Member"} added.`)) {
+ addUserId.value = "";
+ }
+}
+
+async function removeMember(userId: number, name: string) {
+ const ok = await confirm({
+ title: `Remove ${name} from ${team.value?.name}?`,
+ message: "They stop being notified when a rule notifies this team, and the team's work leaves their “My work” view. Submissions already assigned to them stay assigned.",
+ confirmText: "Remove",
+ variant: "danger",
+ });
+ if (!ok) return;
+ await save({ user_ids: memberIds.value.filter((x) => x !== userId) }, `${name} removed.`);
+}
+
+function openEditor() {
+ if (!team.value) return;
+ draft.value = { name: team.value.name, email: team.value.email };
+ showEditor.value = true;
+}
+
+async function saveDetails() {
+ if (await save({ name: draft.value.name.trim(), email: draft.value.email.trim() }, "Team saved.")) {
+ showEditor.value = false;
+ }
+}
+
+async function remove() {
+ const t = team.value;
+ if (!t) return;
+ const ok = await confirm({
+ title: `Delete the team "${t.name}"?`,
+ message: "Submissions routed to it keep no team. A team that routing rules still use can't be deleted.",
+ confirmText: "Delete team",
+ variant: "danger",
+ });
+ if (!ok) return;
+ try {
+ await teamsApi.delete(t.id);
+ notify.success("Team deleted.");
+ router.push("/teams");
+ } catch (e: any) {
+ notify.error(apiMessage(e, "Failed to delete the team"));
+ }
+}
+
+function roleLabel(role: string) {
+ return role ? role.charAt(0).toUpperCase() + role.slice(1) : "—";
+}
+
+onMounted(async () => {
+ await license.load();
+ if (license.licensed) await load();
+ else loading.value = false;
+});
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <div>
+ <h1>{{ team?.name || "Team" }}</h1>
+ <p v-if="team" class="team-subtitle">
+ {{ team.email ? `Shared address ${team.email}` : "No shared address" }}
+ </p>
+ </div>
+ <div class="header-actions">
+ <router-link class="btn btn-secondary" to="/teams">Back</router-link>
+ <template v-if="team && license.mutable">
+ <button class="btn btn-secondary" @click="openEditor">Edit</button>
+ <button class="btn btn-danger" @click="remove">Delete</button>
+ </template>
+ </div>
+ </div>
+
+ <EnterpriseLock
+ feature="Teams"
+ description="Group members into teams like Sales or Billing. Routing rules notify a team or assign submissions to it, and its members see them under “My work” in Messages."
+ >
+ <div v-if="loading" class="loading-page"><div class="spinner"></div></div>
+
+ <div v-else-if="notFound || !team" class="card">
+ <div class="empty-state">
+ <h3>Team not found</h3>
+ <router-link class="btn btn-secondary" to="/teams">Back to teams</router-link>
+ </div>
+ </div>
+
+ <template v-else>
+ <div class="stats-grid team-stats">
+ <router-link class="stat-card" :to="`/messages?team_id=${team.id}`">
+ <div class="stat-label">Open submissions</div>
+ <div class="stat-value">{{ team.open_messages }}</div>
+ </router-link>
+ <router-link class="stat-card" :to="`/messages?team_id=${team.id}`">
+ <div class="stat-label">All submissions</div>
+ <div class="stat-value">{{ team.messages }}</div>
+ </router-link>
+ <div class="stat-card">
+ <div class="stat-label">Members</div>
+ <div class="stat-value">{{ team.members.length }}</div>
+ </div>
+ </div>
+
+ <div class="card section-card">
+ <div class="card-header">
+ <h2>Members ({{ team.members.length }})</h2>
+ </div>
+ <div class="card-body">
+ <div v-if="license.mutable" class="add-member">
+ <select v-model="addUserId" class="form-select" aria-label="Workspace member to add" :disabled="!addable.length">
+ <option value="" disabled>{{ addable.length ? "Add a workspace member…" : "Every workspace member is on this team" }}</option>
+ <option v-for="m in addable" :key="m.user_id" :value="m.user_id">
+ {{ m.name || m.email }}{{ m.name ? ` — ${m.email}` : "" }}
+ </option>
+ </select>
+ <button class="btn btn-primary" :disabled="saving || addUserId === ''" @click="addMember">Add</button>
+ </div>
+
+ <p v-if="!team.members.length" class="muted empty-members">
+ No members yet. Rules that notify this team reach only its shared address{{ team.email ? "" : ", which isn't set" }}.
+ </p>
+ <div v-else class="table-wrapper">
+ <table>
+ <thead>
+ <tr>
+ <th>Name</th>
+ <th>Email</th>
+ <th>Workspace role</th>
+ <th v-if="license.mutable"></th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="m in team.members" :key="m.user_id">
+ <td><strong>{{ m.name || "—" }}</strong></td>
+ <td class="muted">{{ m.email }}</td>
+ <td><span class="badge badge-secondary">{{ roleLabel(m.role) }}</span></td>
+ <td v-if="license.mutable" class="row-actions">
+ <button class="btn btn-ghost btn-sm" :disabled="saving" @click="removeMember(m.user_id, m.name || m.email)">
+ Remove
+ </button>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+ </div>
+
+ <div class="card section-card">
+ <div class="card-header">
+ <h2>Routing rules ({{ team.rules.length }})</h2>
+ </div>
+ <div class="card-body">
+ <p v-if="!team.rules.length" class="muted">
+ No routing rule notifies or assigns this team yet. Add one on a form's Routing tab.
+ </p>
+ <div v-else class="table-wrapper">
+ <table>
+ <thead>
+ <tr>
+ <th>Rule</th>
+ <th>Form</th>
+ <th>Status</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="r in team.rules" :key="r.id">
+ <td><strong>{{ r.name }}</strong></td>
+ <td>
+ <router-link :to="`/forms/${r.form_id}?tab=routing`">{{ r.form_name }}</router-link>
+ </td>
+ <td>
+ <span v-if="r.enabled" class="badge badge-success">On</span>
+ <span v-else class="badge badge-neutral">Off</span>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+ </div>
+ </template>
+ </EnterpriseLock>
+
+ <div v-if="showEditor" class="modal-overlay" @click.self="showEditor = false">
+ <div class="modal">
+ <div class="modal-header">
+ <h3>Edit {{ team?.name }}</h3>
+ </div>
+ <div class="modal-body">
+ <div class="form-group">
+ <label class="form-label" for="team-name">Name</label>
+ <input id="team-name" v-model="draft.name" class="form-input" maxlength="80" />
+ </div>
+ <div class="form-group">
+ <label class="form-label" for="team-email">Shared address <span class="muted">(optional)</span></label>
+ <input id="team-email" v-model="draft.email" type="email" class="form-input" placeholder="[email protected]" />
+ <small class="muted">Notified along with the members when a rule notifies this team.</small>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-secondary" @click="showEditor = false">Cancel</button>
+ <button class="btn btn-primary" :disabled="saving || !draft.name.trim()" @click="saveDetails">
+ {{ saving ? "Saving…" : "Save team" }}
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+</template>
+
+<style scoped>
+.team-subtitle {
+ margin: 4px 0 0;
+ color: var(--text-muted);
+ font-size: 13px;
+}
+
+.header-actions {
+ display: flex;
+ gap: 8px;
+ flex-wrap: wrap;
+}
+
+.team-stats {
+ margin-bottom: 20px;
+}
+
+.team-stats a.stat-card {
+ color: inherit;
+ text-decoration: none;
+}
+
+.section-card {
+ margin-bottom: 20px;
+}
+
+.add-member {
+ display: flex;
+ gap: 8px;
+ margin-bottom: 16px;
+ max-width: 560px;
+}
+
+.add-member select {
+ flex: 1;
+ min-width: 0;
+}
+
+.empty-members {
+ margin: 0;
+}
+
+.row-actions {
+ text-align: right;
+}
+</style>
diff --git a/web/src/views/teams/Teams.vue b/web/src/views/teams/Teams.vue
index 22a3383..e73ea26 100644
--- a/web/src/views/teams/Teams.vue
+++ b/web/src/views/teams/Teams.vue
@@ -129,7 +129,9 @@ onMounted(async () => {
</thead>
<tbody>
<tr v-for="team in teams" :key="team.id">
- <td><strong>{{ team.name }}</strong></td>
+ <td>
+ <router-link :to="`/teams/${team.id}`"><strong>{{ team.name }}</strong></router-link>
+ </td>
<td class="team-members">{{ memberList(team) }}</td>
<td>{{ team.email || "—" }}</td>
<td class="team-actions">