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(admin): add platform-wide domain list and detail pages feat: allow admin to mark a domain as verified
Jonas Kaninda76948bd24c8d
diff --git a/internal/handlers/admin_domain_handler.go b/internal/handlers/admin_domain_handler.gonew file mode 100644index 0000000..5f2dc93--- /dev/null+++ b/internal/handlers/admin_domain_handler.go@@ -0,0 +1,308 @@+// SPDX-FileCopyrightText: 2026 Jonas Kaninda+// SPDX-License-Identifier: AGPL-3.0-or-later++package handlers++import (+ "strings"+ "time"++ "github.com/goposta/posta/internal/models"+ "github.com/goposta/posta/internal/services/audit"+ "github.com/goposta/posta/internal/services/domain"+ "github.com/goposta/posta/internal/storage/repositories"+ "github.com/jkaninda/okapi"+ "gorm.io/gorm"+)++type AdminDomainHandler struct {+ db *gorm.DB+ repo *repositories.DomainRepository+ audit *audit.Logger+}++func NewAdminDomainHandler(db *gorm.DB, repo *repositories.DomainRepository, auditLogger *audit.Logger) *AdminDomainHandler {+ return &AdminDomainHandler{db: db, repo: repo, audit: auditLogger}+}++// AdminDomainRow is one line of the platform-wide domain table.+type AdminDomainRow struct {+ ID uint `json:"id"`+ Domain string `json:"domain"`+ WorkspaceID *uint `json:"workspace_id,omitempty"`+ WorkspaceName string `json:"workspace_name"`+ OwnerID uint `json:"owner_id"`+ OwnerEmail string `json:"owner_email"`+ OwnershipVerified bool `json:"ownership_verified"`+ SPFVerified bool `json:"spf_verified"`+ DKIMVerified bool `json:"dkim_verified"`+ DMARCVerified bool `json:"dmarc_verified"`+ FullyVerified bool `json:"fully_verified"`+ CreatedAt time.Time `json:"created_at"`+}++// AdminDomainDetail adds what an administrator needs to act on a domain: who+// owns it, the records its owner still has to publish, and whether the same name+// is already verified somewhere else.+type AdminDomainDetail struct {+ AdminDomainRow+ VerificationToken string `json:"verification_token"`+ Records *domain.DNSRecords `json:"records"`+ ConflictWorkspaceID *uint `json:"conflict_workspace_id,omitempty"`+ ConflictWorkspaceName string `json:"conflict_workspace_name,omitempty"`+}++type AdminListDomainsRequest struct {+ Page int `query:"page" default:"0"`+ Size int `query:"size" default:"20"`+ Search string `query:"search" doc:"Match part of the domain name"`+ Status string `query:"status" enum:"verified,unverified" doc:"Filter on ownership verification"`+ Workspace int `query:"workspace" doc:"Restrict to one workspace id"`+}++type AdminDomainIDRequest struct {+ ID int `param:"id"`+}++type AdminSetDomainVerificationRequest struct {+ ID int `param:"id"`+ Body struct {+ OwnershipVerified bool `json:"ownership_verified" required:"true"`+ Reason string `json:"reason" doc:"Why the DNS check is being bypassed. Required when granting."`+ } `json:"body"`+}++func (h *AdminDomainHandler) List(c *okapi.Context, req *AdminListDomainsRequest) error {+ page, size, offset := normalizePageParams(req.Page, req.Size)++ filter := repositories.AdminDomainFilter{Search: req.Search}+ switch req.Status {+ case "verified":+ v := true+ filter.Verified = &v+ case "unverified":+ v := false+ filter.Verified = &v+ }+ if req.Workspace > 0 {+ ws := uint(req.Workspace)+ filter.WorkspaceID = &ws+ }++ domains, total, err := h.repo.FindAllFiltered(filter, size, offset)+ if err != nil {+ return c.AbortInternalServerError("failed to list domains")+ }++ workspaces := h.workspaceNames(domains)+ owners := h.ownerEmails(domains)++ rows := make([]AdminDomainRow, 0, len(domains))+ for i := range domains {+ rows = append(rows, h.row(&domains[i], workspaces, owners))+ }+ return paginated(c, rows, total, page, size)+}++func (h *AdminDomainHandler) Get(c *okapi.Context, req *AdminDomainIDRequest) error {+ d, err := h.repo.FindByID(uint(req.ID))+ if err != nil {+ return c.AbortNotFound("domain not found")+ }++ detail := AdminDomainDetail{+ AdminDomainRow: h.row(d, h.workspaceNames([]models.Domain{*d}), h.ownerEmails([]models.Domain{*d})),+ VerificationToken: d.VerificationToken,+ Records: domain.RequiredRecords(d),+ }+ if other := h.conflictingOwner(d); other != nil {+ detail.ConflictWorkspaceID = other.WorkspaceID+ detail.ConflictWorkspaceName = h.workspaceName(other.WorkspaceID)+ }+ return ok(c, detail)+}++// Verify runs the real DNS check against a tenant's domain, so an administrator+// can answer "is their DNS actually right?" without asking them to click it.+func (h *AdminDomainHandler) Verify(c *okapi.Context, req *AdminDomainIDRequest) error {+ d, err := h.repo.FindByID(uint(req.ID))+ if err != nil {+ return c.AbortNotFound("domain not found")+ }++ result, err := domain.Verify(d)+ if err != nil {+ return c.AbortInternalServerError("DNS verification failed")+ }++ var conflict *models.Domain+ if result.OwnershipVerified && !d.OwnershipVerified {+ if conflict = h.conflictingOwner(d); conflict != nil {+ result.OwnershipVerified = false+ }+ }++ d.OwnershipVerified = result.OwnershipVerified+ d.SPFVerified = result.SPFVerified+ d.DKIMVerified = result.DKIMVerified+ d.DMARCVerified = result.DMARCVerified++ if err := h.repo.Update(d); err != nil {+ return c.AbortInternalServerError("failed to record the verification result")+ }++ h.log(c, d, "admin.domain.verified", "Ran DNS verification for "+d.Domain, map[string]any{+ "ownership_verified": d.OwnershipVerified,+ "fully_verified": d.IsFullyVerified(),+ })++ payload := okapi.M{+ "domain": d,+ "verification": result,+ "fully_verified": d.IsFullyVerified(),+ }+ if conflict != nil {+ payload["conflict_workspace_id"] = conflict.WorkspaceID+ payload["conflict_workspace_name"] = h.workspaceName(conflict.WorkspaceID)+ }+ return ok(c, payload)+}++func (h *AdminDomainHandler) SetVerification(c *okapi.Context, req *AdminSetDomainVerificationRequest) error {+ d, err := h.repo.FindByID(uint(req.ID))+ if err != nil {+ return c.AbortNotFound("domain not found")+ }++ reason := strings.TrimSpace(req.Body.Reason)+ if req.Body.OwnershipVerified && reason == "" {+ return c.AbortBadRequest("a reason is required when verifying a domain without a DNS check")+ }++ if req.Body.OwnershipVerified {+ // At most one workspace may hold a given name verified; the database+ // enforces it with a partial unique index. Catching it here turns what+ // would be an opaque 500 into an answer naming the workspace at fault.+ if other := h.conflictingOwner(d); other != nil {+ return c.AbortConflict(+ "another workspace has already verified " + d.Domain ++ "; unverify it there before granting it here")+ }+ }++ if d.OwnershipVerified == req.Body.OwnershipVerified {+ return ok(c, d)+ }++ d.OwnershipVerified = req.Body.OwnershipVerified+ if err := h.repo.Update(d); err != nil {+ return c.AbortInternalServerError("failed to update the domain")+ }++ action, message := "admin.domain.unverified", "Ownership revoked for "+d.Domain+ if req.Body.OwnershipVerified {+ action, message = "admin.domain.force_verified", "Ownership granted for "+d.Domain+" without a DNS check"+ }+ h.log(c, d, action, message, map[string]any{"reason": reason})++ return ok(c, d)+}++// conflictingOwner returns the domain row that already holds this name verified,+// when it is a different row. Nil means the name is free to verify.+func (h *AdminDomainHandler) conflictingOwner(d *models.Domain) *models.Domain {+ other, err := h.repo.FindVerifiedByName(d.Domain)+ if err != nil || other == nil || other.ID == d.ID {+ return nil+ }+ return other+}++func (h *AdminDomainHandler) row(d *models.Domain, workspaces map[uint]string, owners map[uint]string) AdminDomainRow {+ row := AdminDomainRow{+ ID: d.ID,+ Domain: d.Domain,+ WorkspaceID: d.WorkspaceID,+ OwnerID: d.UserID,+ OwnerEmail: owners[d.UserID],+ OwnershipVerified: d.OwnershipVerified,+ SPFVerified: d.SPFVerified,+ DKIMVerified: d.DKIMVerified,+ DMARCVerified: d.DMARCVerified,+ FullyVerified: d.IsFullyVerified(),+ CreatedAt: d.CreatedAt,+ }+ if d.WorkspaceID != nil {+ row.WorkspaceName = workspaces[*d.WorkspaceID]+ }+ return row+}++// workspaceNames resolves the names for a page of domains in one query rather+// than one per row.+func (h *AdminDomainHandler) workspaceNames(domains []models.Domain) map[uint]string {+ ids := make([]uint, 0, len(domains))+ for i := range domains {+ if domains[i].WorkspaceID != nil {+ ids = append(ids, *domains[i].WorkspaceID)+ }+ }+ out := map[uint]string{}+ if len(ids) == 0 {+ return out+ }+ var rows []models.Workspace+ if err := h.db.Select("id", "name").Where("id IN ?", ids).Find(&rows).Error; err != nil {+ return out+ }+ for i := range rows {+ out[rows[i].ID] = rows[i].Name+ }+ return out+}++func (h *AdminDomainHandler) workspaceName(id *uint) string {+ if id == nil {+ return ""+ }+ var ws models.Workspace+ if err := h.db.Select("id", "name").First(&ws, *id).Error; err != nil {+ return ""+ }+ return ws.Name+}++func (h *AdminDomainHandler) ownerEmails(domains []models.Domain) map[uint]string {+ ids := make([]uint, 0, len(domains))+ for i := range domains {+ ids = append(ids, domains[i].UserID)+ }+ out := map[uint]string{}+ if len(ids) == 0 {+ return out+ }+ var rows []models.User+ if err := h.db.Select("id", "email").Where("id IN ?", ids).Find(&rows).Error; err != nil {+ return out+ }+ for i := range rows {+ out[rows[i].ID] = rows[i].Email+ }+ return out+}++func (h *AdminDomainHandler) log(c *okapi.Context, d *models.Domain, action, message string, meta map[string]any) {+ if h.audit == nil {+ return+ }+ if meta == nil {+ meta = map[string]any{}+ }+ meta["domain_id"] = d.ID+ meta["domain"] = d.Domain+ if d.WorkspaceID != nil {+ h.audit.LogCtxScoped(c, *d.WorkspaceID, action, message, meta)+ return+ }+ h.audit.LogCtx(c, action, message, meta)+}diff --git a/internal/routes/admin_routes.go b/internal/routes/admin_routes.goindex 82bcd39..349041d 100644--- a/internal/routes/admin_routes.go+++ b/internal/routes/admin_routes.go@@ -286,6 +286,59 @@ func (r *Router) adminRoutes() []okapi.RouteDefinition {Response: &dto.Response[dto.MessageData]{},},+ // ==================== Domains ====================+ {+ Method: http.MethodGet,+ Path: pathDomains,+ Handler: okapi.H(r.h.adminDomain.List),+ Group: adminGroup,+ Summary: "List domains across every workspace",+ Description: "Platform-wide domain list, filterable by name, ownership verification, and workspace.",+ Request: &handlers.AdminListDomainsRequest{},+ Response: &dto.PageableResponse[handlers.AdminDomainRow]{},+ },+ {+ Method: http.MethodGet,+ Path: pathDomainByID,+ Handler: okapi.H(r.h.adminDomain.Get),+ Group: adminGroup,+ Summary: "Get a domain",+ Description: "Returns the domain with its owner, the DNS records still required, and any workspace already holding the name verified.",+ Response: &dto.Response[handlers.AdminDomainDetail]{},+ Options: []okapi.RouteOption{+ okapi.DocPathParam("id", "integer", "Domain ID"),+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),+ },+ },+ {+ Method: http.MethodPost,+ Path: pathDomainByID + "/verify",+ Handler: okapi.H(r.h.adminDomain.Verify),+ Group: adminGroup,+ Summary: "Run DNS verification for a domain",+ Description: "Performs the same DNS checks the owning workspace would, on their behalf.",+ Options: []okapi.RouteOption{+ okapi.DocPathParam("id", "integer", "Domain ID"),+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),+ },+ },+ {+ Method: http.MethodPut,+ Path: pathDomainByID + "/verification",+ Handler: okapi.H(r.h.adminDomain.SetVerification),+ Group: adminGroup,+ Summary: "Set domain ownership manually",+ Description: "Marks ownership verified, or revokes it, without a DNS check. Requires a reason when granting, " ++ "and is refused when another workspace already holds the name verified.",+ Request: &handlers.AdminSetDomainVerificationRequest{},+ Response: &dto.Response[models.Domain]{},+ Options: []okapi.RouteOption{+ okapi.DocPathParam("id", "integer", "Domain ID"),+ okapi.DocErrorResponse(400, &dto.ErrorResponseBody{}),+ okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),+ },+ },+// ==================== Plans ===================={Method: http.MethodPost,diff --git a/internal/routes/paths.go b/internal/routes/paths.goindex e665938..3baf750 100644--- a/internal/routes/paths.go+++ b/internal/routes/paths.go@@ -12,11 +12,13 @@ package routes// file, and several are shared across route files.const (pathBounces = "/bounces"+ pathDomains = "/domains"pathSettings = "/settings"pathSuppressions = "/suppressions"pathWebhooks = "/webhooks"pathCampaignByID = "/campaigns/{id:int}"+ pathDomainByID = "/domains/{id:int}"pathFormByID = "/forms/{id:int}"pathPlanByID = "/plans/{id:int}"pathServerByID = "/servers/{id:int}"diff --git a/internal/routes/routes.go b/internal/routes/routes.goindex bdc1a67..6bd7332 100644--- a/internal/routes/routes.go+++ b/internal/routes/routes.go@@ -97,6 +97,7 @@ type routerHandlers struct {server *handlers.ServerHandlerevent *handlers.EventHandleranalytics *handlers.AnalyticsHandler+ adminDomain *handlers.AdminDomainHandlersetting *handlers.SettingHandleruserSetting *handlers.UserSettingHandlerworkspaceSetting *handlers.WorkspaceSettingHandler@@ -252,6 +253,7 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *cwebhookDelivery: handlers.NewWebhookDeliveryHandler(webhookDeliveryRepo),dashboard: handlers.NewDashboardHandler(db, statsCache, webhookDeliveryRepo),domain: handlers.NewDomainHandler(domainRepo),+ adminDomain: handlers.NewAdminDomainHandler(db, domainRepo, auditLogger),bounce: handlers.NewBounceHandler(bounceRepo, suppressionRepo, emailRepo, dispatcher),suppression: handlers.NewSuppressionHandler(suppressionRepo, unsubListRepo),unsubscribeList: handlers.NewUnsubscribeListHandler(unsubListRepo),diff --git a/internal/routes/workspace_resource_routes.go b/internal/routes/workspace_resource_routes.goindex 8948c02..56f4e13 100644--- a/internal/routes/workspace_resource_routes.go+++ b/internal/routes/workspace_resource_routes.go@@ -732,7 +732,7 @@ func (r *Router) workspaceResourceRoutes() []okapi.RouteDefinition {},{Method: http.MethodPost,- Path: "/domains",+ Path: pathDomains,Handler: okapi.H(r.h.domain.Create),Group: opsGroup,Summary: "Add domain",@@ -745,7 +745,7 @@ func (r *Router) workspaceResourceRoutes() []okapi.RouteDefinition {},{Method: http.MethodGet,- Path: "/domains",+ Path: pathDomains,Handler: okapi.H(r.h.domain.List),Group: opsGroup,Summary: "List domains",@@ -754,7 +754,7 @@ func (r *Router) workspaceResourceRoutes() []okapi.RouteDefinition {},{Method: http.MethodGet,- Path: "/domains/{id:int}",+ Path: pathDomainByID,Handler: okapi.H(r.h.domain.Get),Group: opsGroup,Summary: "Get domain details",@@ -766,7 +766,7 @@ func (r *Router) workspaceResourceRoutes() []okapi.RouteDefinition {},{Method: http.MethodDelete,- Path: "/domains/{id:int}",+ Path: pathDomainByID,Handler: okapi.H(r.h.domain.Delete),Group: opsGroup,Tags: []string{tagUser},@@ -779,7 +779,7 @@ func (r *Router) workspaceResourceRoutes() []okapi.RouteDefinition {},{Method: http.MethodPost,- Path: "/domains/{id:int}/verify",+ Path: pathDomainByID + "/verify",Handler: okapi.H(r.h.domain.Verify),Group: opsGroup,Summary: "Verify domain DNS records",diff --git a/internal/storage/repositories/domain_repo.go b/internal/storage/repositories/domain_repo.goindex 9eed3f3..c89abf0 100644--- a/internal/storage/repositories/domain_repo.go+++ b/internal/storage/repositories/domain_repo.go@@ -4,6 +4,8 @@package repositoriesimport (+ "strings"+"github.com/goposta/posta/internal/models""gorm.io/gorm")@@ -89,9 +91,46 @@ func (r *DomainRepository) FindByScope(scope ResourceScope, limit, offset int) (return items, total, nil}-// FindVerifiedByName returns an ownership-verified Domain row matching the given name,-// regardless of the owning user. Used for routing inbound email to the right tenant.-// Returns gorm.ErrRecordNotFound if no verified domain matches.+type AdminDomainFilter struct {+ Search string+ Verified *bool+ WorkspaceID *uint+}++func (r *DomainRepository) FindAllFiltered(f AdminDomainFilter, limit, offset int) ([]models.Domain, int64, error) {+ var items []models.Domain+ var total int64++ apply := func(q *gorm.DB) *gorm.DB {+ if s := strings.TrimSpace(f.Search); s != "" {+ q = q.Where("LOWER(domain) LIKE ?", "%"+strings.ToLower(s)+"%")+ }+ if f.Verified != nil {+ q = q.Where("ownership_verified = ?", *f.Verified)+ }+ if f.WorkspaceID != nil {+ q = q.Where("workspace_id = ?", *f.WorkspaceID)+ }+ return q+ }++ apply(r.db.Model(&models.Domain{})).Count(&total)++ if err := apply(r.db).+ Order("created_at DESC").+ Limit(limit).Offset(offset).+ Find(&items).Error; err != nil {+ return nil, 0, err+ }+ return items, total, nil+}++func (r *DomainRepository) CountAll() (total, verified int64) {+ r.db.Model(&models.Domain{}).Count(&total)+ r.db.Model(&models.Domain{}).Where("ownership_verified = ?", true).Count(&verified)+ return+}+func (r *DomainRepository) FindVerifiedByName(domainName string) (*models.Domain, error) {var d models.Domainif err := r.db.Where("LOWER(domain) = LOWER(?) AND ownership_verified = ?", domainName, true).diff --git a/web/src/api/admin.ts b/web/src/api/admin.tsindex 6ec085e..00b05dd 100644--- a/web/src/api/admin.ts+++ b/web/src/api/admin.ts@@ -1,10 +1,39 @@import api from './client'-import type { ApiResponse, PaginatedResponse, User, ApiKey, Email, Event, AdminMetrics, UserDetailMetrics, CronJob, AdminWorkspace, UpdateInfo } from './types'+import type {+ ApiResponse, PaginatedResponse, User, ApiKey, Email, Event, AdminMetrics,+ UserDetailMetrics, CronJob, AdminWorkspace, UpdateInfo,+ Domain, AdminDomainRow, AdminDomainDetail, AdminDomainVerifyResult,+} from './types'export const adminApi = {listUsers(page = 0, size = 20, search = '') {return api.get<PaginatedResponse<User>>('/admin/users', { params: { page, size, search: search || undefined } })},+ // ---- Domains (platform-wide) ----+ listDomains(page = 0, size = 20, search = '', status = '', workspace = 0) {+ return api.get<PaginatedResponse<AdminDomainRow>>('/admin/domains', {+ params: {+ page,+ size,+ search: search || undefined,+ status: status || undefined,+ workspace: workspace || undefined,+ },+ })+ },+ getDomain(id: number) {+ return api.get<ApiResponse<AdminDomainDetail>>(`/admin/domains/${id}`)+ },+ verifyDomain(id: number) {+ return api.post<ApiResponse<AdminDomainVerifyResult>>(`/admin/domains/${id}/verify`)+ },+ setDomainVerification(id: number, ownershipVerified: boolean, reason: string) {+ return api.put<ApiResponse<Domain>>(`/admin/domains/${id}/verification`, {+ ownership_verified: ownershipVerified,+ reason,+ })+ },+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/types.ts b/web/src/api/types.tsindex b13b148..12c77f9 100644--- a/web/src/api/types.ts+++ b/web/src/api/types.ts@@ -411,6 +411,48 @@ export interface DnsRecord {value: string}+// ---- Admin domains (platform-wide) ----++export interface AdminDomainRow {+ id: number+ domain: string+ workspace_id?: number | null+ workspace_name: string+ owner_id: number+ owner_email: string+ ownership_verified: boolean+ spf_verified: boolean+ dkim_verified: boolean+ dmarc_verified: boolean+ fully_verified: boolean+ created_at: string+}++export interface AdminDomainDetail extends AdminDomainRow {+ verification_token: string+ records: DnsRecords | null+ /** Set when a different workspace already holds this name verified. */+ conflict_workspace_id?: number | null+ conflict_workspace_name?: string+}++export interface AdminDomainVerifyResult {+ domain: Domain+ verification: {+ ownership_verified: boolean+ spf_verified: boolean+ dkim_verified: boolean+ dmarc_verified: boolean+ spf_record?: string+ dkim_record?: string+ dmarc_record?: string+ }+ fully_verified: boolean+ /** Set when DNS passed but another workspace already holds the name verified. */+ conflict_workspace_id?: number | null+ conflict_workspace_name?: string+}+export interface Webhook {id: numberuser_id: numberdiff --git a/web/src/layouts/DashboardLayout.vue b/web/src/layouts/DashboardLayout.vueindex 3249954..89adcef 100644--- a/web/src/layouts/DashboardLayout.vue+++ b/web/src/layouts/DashboardLayout.vue@@ -227,6 +227,7 @@ const navSections: NavSection[] = [{ name: 'Users', path: '/admin/users', icon: 'users' },{ name: 'Plans', path: '/admin/plans', icon: 'layers' },{ name: 'Shared Servers', path: '/admin/servers', icon: 'server' },+ { name: 'Domains', path: '/admin/domains', icon: 'globe' },{ name: 'OAuth', path: '/admin/oauth', icon: 'shield' },{ name: 'Jobs', path: '/admin/jobs', icon: 'clock' },{ name: 'Events', path: '/admin/events', icon: 'zap' },diff --git a/web/src/router/index.ts b/web/src/router/index.tsindex 2d03beb..723a1d9 100644--- a/web/src/router/index.ts+++ b/web/src/router/index.ts@@ -107,6 +107,8 @@ const routes = [// The page was called Metrics until it grew a health summary and quick// links; keep the old path working for bookmarks and muscle memory.{ path: 'admin/metrics', redirect: '/admin/dashboard' },+ { path: 'admin/domains', name: 'admin-domains', component: () => import('../views/admin/Domains.vue'), meta: { admin: true, title: 'Admin · Domains' } },+ { path: 'admin/domains/:id', name: 'admin-domain-detail', component: () => import('../views/admin/DomainDetail.vue'), meta: { admin: true, title: 'Admin · Domain' } },{ 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' } },diff --git a/web/src/views/admin/DomainDetail.vue b/web/src/views/admin/DomainDetail.vuenew file mode 100644index 0000000..10eb43f--- /dev/null+++ b/web/src/views/admin/DomainDetail.vue@@ -0,0 +1,439 @@+<script setup lang="ts">+import { computed, onMounted, ref } from "vue";+import { useRoute, useRouter } from "vue-router";+import { adminApi } from "../../api/admin";+import { useNotificationStore } from "../../stores/notification";+import { useConfirm } from "../../composables/useConfirm";+import { apiMessage } from "../../composables/apiError";+import type { AdminDomainDetail, DnsRecord } from "../../api/types";++const route = useRoute();+const router = useRouter();+const notify = useNotificationStore();+const { confirm } = useConfirm();++const id = Number(route.params.id);+const domain = ref<AdminDomainDetail | null>(null);+const loading = ref(true);+const loadFailed = ref(false);+const verifying = ref(false);+const overriding = ref(false);++const showOverride = ref(false);+const overrideReason = ref("");++async function load() {+ loading.value = true;+ try {+ domain.value = (await adminApi.getDomain(id)).data.data;+ } catch (e: any) {+ loadFailed.value = true;+ notify.error(apiMessage(e, "Failed to load the domain"));+ } finally {+ loading.value = false;+ }+}++async function runVerification() {+ verifying.value = true;+ try {+ const res = await adminApi.verifyDomain(id);+ const result = res.data.data;+ await load();+ if (result.verification.ownership_verified) {+ notify.success("DNS verification passed");+ } else if (result.conflict_workspace_id) {+ notify.error(+ `DNS is correct, but ${result.conflict_workspace_name || "another workspace"} already holds this domain verified`+ );+ } else {+ notify.info("DNS verification ran; ownership is still unproven");+ }+ } catch (e: any) {+ notify.error(apiMessage(e, "Verification failed"));+ } finally {+ verifying.value = false;+ }+}++async function grantOwnership() {+ if (!overrideReason.value.trim()) return;+ overriding.value = true;+ try {+ await adminApi.setDomainVerification(id, true, overrideReason.value.trim());+ showOverride.value = false;+ overrideReason.value = "";+ await load();+ notify.success("Ownership granted");+ } catch (e: any) {+ notify.error(apiMessage(e, "Could not grant ownership"));+ } finally {+ overriding.value = false;+ }+}++async function revokeOwnership() {+ const confirmed = await confirm({+ title: "Revoke ownership",+ message:+ `Mail from ${domain.value?.domain} will be treated as unverified. ` ++ "Workspaces that require a verified domain will stop sending from it.",+ confirmText: "Revoke",+ variant: "danger",+ });+ if (!confirmed) return;+ overriding.value = true;+ try {+ await adminApi.setDomainVerification(id, false, "");+ await load();+ notify.success("Ownership revoked");+ } catch (e: any) {+ notify.error(apiMessage(e, "Could not revoke ownership"));+ } finally {+ overriding.value = false;+ }+}++const checks = computed(() => {+ const d = domain.value;+ if (!d) return [];+ return [+ { key: "ownership", label: "Ownership", passed: d.ownership_verified, record: d.records?.verification },+ { key: "spf", label: "SPF", passed: d.spf_verified, record: d.records?.spf },+ { key: "dkim", label: "DKIM", passed: d.dkim_verified, record: d.records?.dkim },+ { key: "dmarc", label: "DMARC", passed: d.dmarc_verified, record: d.records?.dmarc },+ ];+});++const hasConflict = computed(() => !!domain.value?.conflict_workspace_id);++function copy(record?: DnsRecord) {+ if (!record) return;+ navigator.clipboard?.writeText(record.value);+ notify.success("Record value copied");+}++function formatDate(value?: string) {+ return value ? new Date(value).toLocaleString() : "—";+}++onMounted(load);+</script>++<template>+ <div>+ <div class="page-header">+ <div>+ <h1>{{ domain?.domain || "Domain" }}</h1>+ <p v-if="domain" class="page-subtitle">+ {{ domain.workspace_name || (domain.workspace_id ? `Workspace #${domain.workspace_id}` : "No workspace") }}+ · added {{ formatDate(domain.created_at) }}+ </p>+ </div>+ <div class="header-actions">+ <button class="btn btn-secondary" :disabled="verifying" @click="runVerification">+ {{ verifying ? "Checking DNS…" : "Run DNS check" }}+ </button>+ <button+ v-if="domain && !domain.ownership_verified"+ class="btn btn-primary"+ :disabled="hasConflict"+ :title="hasConflict ? 'Another workspace holds this domain verified' : ''"+ @click="showOverride = true"+ >+ Mark verified+ </button>+ <button+ v-else-if="domain"+ class="btn btn-danger"+ :disabled="overriding"+ @click="revokeOwnership"+ >+ Revoke ownership+ </button>+ <button class="btn btn-secondary" @click="router.push('/admin/domains')">Back</button>+ </div>+ </div>++ <div v-if="loading" class="loading-page"><div class="spinner"></div></div>++ <div v-else-if="loadFailed || !domain" class="card">+ <div class="empty-state">+ <h3>Domain not found</h3>+ <button class="btn btn-secondary" @click="router.push('/admin/domains')">Back to domains</button>+ </div>+ </div>++ <template v-else>+ <div v-if="hasConflict" class="alert-banner">+ <strong>Already verified elsewhere.</strong>+ <span>+ {{ domain.conflict_workspace_name || `Workspace #${domain.conflict_workspace_id}` }}+ holds <code>{{ domain.domain }}</code> verified. Only one workspace may own a domain, so+ ownership cannot be granted here until it is revoked there.+ </span>+ </div>++ <div class="card" style="margin-bottom: 20px">+ <div class="card-header"><h2>Status</h2></div>+ <div class="card-body">+ <div class="checks">+ <div v-for="check in checks" :key="check.key" class="check" :class="{ passed: check.passed }">+ <span class="check-mark" aria-hidden="true">+ <svg v-if="check.passed" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">+ <path d="M3.5 8.5l3 3 6-7" />+ </svg>+ </span>+ <span class="check-label">{{ check.label }}</span>+ <span class="check-state">{{ check.passed ? "passing" : "not detected" }}</span>+ </div>+ </div>+ <p class="note">+ Ownership decides whether the workspace may send from this domain at all. SPF, DKIM and+ DMARC do not gate sending; they decide how the mail is received.+ </p>+ </div>+ </div>++ <div class="card" style="margin-bottom: 20px">+ <div class="card-header">+ <h2>Owner</h2>+ </div>+ <div class="card-body">+ <table>+ <tbody>+ <tr>+ <td class="label-cell">Workspace</td>+ <td>{{ domain.workspace_name || (domain.workspace_id ? `#${domain.workspace_id}` : "—") }}</td>+ </tr>+ <tr>+ <td class="label-cell">Account</td>+ <td>{{ domain.owner_email || `#${domain.owner_id}` }}</td>+ </tr>+ <tr>+ <td class="label-cell">Verification token</td>+ <td><code>{{ domain.verification_token }}</code></td>+ </tr>+ </tbody>+ </table>+ </div>+ </div>++ <div class="card">+ <div class="card-header"><h2>Required DNS records</h2></div>+ <div class="card-body">+ <p class="note" style="margin-top: 0">+ What the owner has to publish. Values are shown so you can compare them against what+ their zone actually returns.+ </p>+ <div v-for="check in checks" :key="check.key" class="record">+ <div class="record-head">+ <span class="record-label">{{ check.label }}</span>+ <span :class="check.passed ? 'badge badge-success' : 'badge badge-neutral'">+ {{ check.passed ? "found" : "missing" }}+ </span>+ <button v-if="check.record" class="record-copy" type="button" @click="copy(check.record)">+ Copy value+ </button>+ </div>+ <dl v-if="check.record" class="record-body">+ <dt>Type</dt>+ <dd>{{ check.record.type }}</dd>+ <dt>Name</dt>+ <dd>{{ check.record.name }}</dd>+ <dt>Value</dt>+ <dd class="wrap">{{ check.record.value }}</dd>+ </dl>+ <p v-else class="note">No record is published for this check.</p>+ </div>+ </div>+ </div>+ </template>++ <div v-if="showOverride" class="modal-overlay" @click.self="showOverride = false">+ <div class="modal">+ <div class="modal-header"><h3>Mark {{ domain?.domain }} verified</h3></div>+ <div class="modal-body">+ <p class="note" style="margin-top: 0">+ This grants ownership without a DNS check, and the workspace will be able to send from+ the domain immediately. Use it when DNS cannot settle the question — a registrar that+ strips TXT records, an internal domain with no public zone — not as a shortcut past a+ failing check.+ </p>+ <div class="form-group">+ <label class="form-label" for="override-reason">Reason</label>+ <input+ id="override-reason"+ v-model="overrideReason"+ class="form-input"+ placeholder="Why is the DNS proof being bypassed?"+ />+ <span class="form-hint">Recorded on the audit entry, alongside who granted it.</span>+ </div>+ </div>+ <div class="modal-footer">+ <button class="btn btn-secondary" @click="showOverride = false">Cancel</button>+ <button+ class="btn btn-primary"+ :disabled="overriding || !overrideReason.trim()"+ @click="grantOwnership"+ >+ {{ overriding ? "Granting…" : "Grant ownership" }}+ </button>+ </div>+ </div>+ </div>+ </div>+</template>++<style scoped>+.page-subtitle {+ font-size: 13px;+ color: var(--text-tertiary);+ margin-top: 4px;+}++.header-actions {+ display: flex;+ gap: 8px;+ flex-wrap: wrap;+}++.alert-banner {+ display: flex;+ flex-direction: column;+ gap: 3px;+ padding: 12px 16px;+ margin-bottom: 20px;+ border-radius: 10px;+ border: 1px solid var(--warning-500);+ background: var(--warning-50);+ font-size: 13px;+ color: var(--text-secondary);+}++.alert-banner strong {+ color: var(--text-primary);+}++.checks {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));+ gap: 14px;+}++.check {+ display: flex;+ flex-direction: column;+ gap: 3px;+ padding: 12px 14px;+ border: 1px solid var(--border-primary);+ border-radius: 8px;+}++.check-mark {+ width: 20px;+ height: 20px;+ border-radius: 50%;+ border: 1.5px solid var(--border-input);+ display: inline-flex;+ align-items: center;+ justify-content: center;+ color: var(--text-inverse);+}++.check-mark svg {+ width: 12px;+ height: 12px;+}++.passed .check-mark {+ background: var(--success-600);+ border-color: var(--success-600);+}++.check-label {+ font-size: 14px;+ font-weight: 600;+ color: var(--text-primary);+}++.check-state {+ font-size: 12px;+ color: var(--text-tertiary);+}++.note {+ font-size: 12px;+ color: var(--text-tertiary);+ margin-top: 14px;+ line-height: 1.6;+}++.label-cell {+ font-weight: 600;+ width: 190px;+ color: var(--text-secondary);+}++.record {+ padding: 14px 0;+ border-bottom: 1px solid var(--border-secondary);+}++.record:last-child {+ border-bottom: 0;+}++.record-head {+ display: flex;+ align-items: center;+ gap: 10px;+}++.record-label {+ font-size: 13px;+ font-weight: 600;+ color: var(--text-primary);+}++.record-copy {+ margin-left: auto;+ border: 0;+ background: none;+ padding: 0;+ font: inherit;+ font-size: 12px;+ color: var(--text-tertiary);+ cursor: pointer;+}++.record-copy:hover {+ color: var(--primary-600);+ text-decoration: underline;+}++.record-body {+ display: grid;+ grid-template-columns: 70px 1fr;+ gap: 4px 12px;+ margin: 10px 0 0;+ font-size: 13px;+}++.record-body dt {+ color: var(--text-tertiary);+ font-size: 12px;+}++.record-body dd {+ margin: 0;+ color: var(--text-primary);+ font-family: "SFMono-Regular", Consolas, monospace;+ font-size: 12px;+}++.wrap {+ overflow-wrap: anywhere;+}+</style>diff --git a/web/src/views/admin/Domains.vue b/web/src/views/admin/Domains.vuenew file mode 100644index 0000000..e341dbf--- /dev/null+++ b/web/src/views/admin/Domains.vue@@ -0,0 +1,213 @@+<script setup lang="ts">+import { ref } from "vue";+import { useRouter } from "vue-router";+import { adminApi } from "../../api/admin";+import { useNotificationStore } from "../../stores/notification";+import { apiMessage } from "../../composables/apiError";+import { usePagination } from "../../composables/usePagination";+import Pagination from "../../components/Pagination.vue";+import type { AdminDomainRow } from "../../api/types";++const router = useRouter();+const notify = useNotificationStore();++const domains = ref<AdminDomainRow[]>([]);+const loading = ref(true);+const search = ref("");+const status = ref<"" | "verified" | "unverified">("");++let searchTimer: ReturnType<typeof setTimeout> | undefined;++const { pageable, goToPage } = usePagination(async (page) => {+ loading.value = true;+ try {+ const res = await adminApi.listDomains(page, pageable.value.size, search.value.trim(), status.value);+ domains.value = res.data.data;+ pageable.value = res.data.pageable;+ } catch (e: any) {+ notify.error(apiMessage(e, "Failed to load domains"));+ } finally {+ loading.value = false;+ }+});++function onSearchInput() {+ if (searchTimer) clearTimeout(searchTimer);+ searchTimer = setTimeout(() => goToPage(0), 300);+}++function setStatus(next: typeof status.value) {+ status.value = next;+ goToPage(0);+}++// A domain is only usable for sending once ownership is proven; SPF, DKIM and+// DMARC then decide how well that mail is received. The two are worth showing+// separately rather than collapsing into one "verified" badge.+function ownershipBadge(d: AdminDomainRow) {+ return d.ownership_verified ? "badge badge-success" : "badge badge-warning";+}++function dnsSummary(d: AdminDomainRow) {+ const passed = [d.spf_verified, d.dkim_verified, d.dmarc_verified].filter(Boolean).length;+ return `${passed}/3`;+}++function dnsBadge(d: AdminDomainRow) {+ const passed = [d.spf_verified, d.dkim_verified, d.dmarc_verified].filter(Boolean).length;+ if (passed === 3) return "badge badge-success";+ if (passed === 0) return "badge badge-neutral";+ return "badge badge-warning";+}++function formatDate(value: string) {+ return new Date(value).toLocaleDateString(undefined, {+ year: "numeric",+ month: "short",+ day: "numeric",+ });+}+</script>++<template>+ <div>+ <div class="page-header">+ <div>+ <h1>Domains</h1>+ <p class="page-subtitle">Every workspace's sending domains and their DNS state</p>+ </div>+ </div>++ <div class="card">+ <div class="card-body toolbar">+ <input+ v-model="search"+ class="form-input search"+ placeholder="Search by domain name…"+ @input="onSearchInput"+ />+ <div class="chips">+ <button class="chip" :class="{ active: status === '' }" @click="setStatus('')">All</button>+ <button class="chip" :class="{ active: status === 'verified' }" @click="setStatus('verified')">+ Verified+ </button>+ <button class="chip" :class="{ active: status === 'unverified' }" @click="setStatus('unverified')">+ Unverified+ </button>+ </div>+ <span class="count">+ {{ pageable.total_elements }} domain{{ pageable.total_elements === 1 ? "" : "s" }}+ </span>+ </div>++ <div v-if="loading && !domains.length" class="card-body">+ <div class="spinner"></div>+ </div>++ <div v-else-if="!domains.length" class="empty-state">+ <h3>{{ search.trim() || status ? "No domains match these filters" : "No domains yet" }}</h3>+ <p v-if="!search.trim() && !status">Domains appear here once a workspace adds one.</p>+ </div>++ <template v-else>+ <div class="table-wrapper">+ <table>+ <thead>+ <tr>+ <th>Domain</th>+ <th>Workspace</th>+ <th>Owner</th>+ <th>Ownership</th>+ <th>SPF / DKIM / DMARC</th>+ <th>Added</th>+ </tr>+ </thead>+ <tbody>+ <tr+ v-for="d in domains"+ :key="d.id"+ style="cursor: pointer"+ @click="router.push(`/admin/domains/${d.id}`)"+ >+ <td class="mono">{{ d.domain }}</td>+ <td>{{ d.workspace_name || (d.workspace_id ? `#${d.workspace_id}` : "—") }}</td>+ <td class="muted-cell">{{ d.owner_email || `#${d.owner_id}` }}</td>+ <td>+ <span :class="ownershipBadge(d)">+ {{ d.ownership_verified ? "verified" : "unverified" }}+ </span>+ </td>+ <td><span :class="dnsBadge(d)">{{ dnsSummary(d) }}</span></td>+ <td class="muted-cell">{{ formatDate(d.created_at) }}</td>+ </tr>+ </tbody>+ </table>+ </div>+ <Pagination :pageable="pageable" @page="goToPage" />+ </template>+ </div>+ </div>+</template>++<style scoped>+.page-subtitle {+ font-size: 13px;+ color: var(--text-tertiary);+ margin-top: 4px;+}++.toolbar {+ display: flex;+ align-items: center;+ gap: 16px;+ flex-wrap: wrap;+}++.search {+ flex: 1 1 260px;+ max-width: 360px;+}++.chips {+ display: flex;+ gap: 6px;+}++.chip {+ padding: 6px 12px;+ border-radius: 999px;+ border: 1px solid var(--border-primary);+ background: var(--bg-primary);+ color: var(--text-secondary);+ font: inherit;+ font-size: 12px;+ font-weight: 500;+ cursor: pointer;+}++.chip:hover {+ background: var(--bg-hover);+}++.chip.active {+ border-color: var(--primary-500);+ background: var(--primary-50);+ color: var(--primary-600);+}++.count {+ margin-left: auto;+ font-size: 12px;+ color: var(--text-tertiary);+}++.mono {+ font-family: "SFMono-Regular", Consolas, monospace;+ font-size: 13px;+}++.muted-cell {+ color: var(--text-tertiary);+ font-size: 13px;+}+</style>